text:
/*!
 *  @file
 *
 *  @brief  Driver for Nokia 6610 LCD Display (PCF8833 Controller)
 *
 *     Controller used for LCD Display is a Philips PCF8833 STN RGB-132x132x3 driver
 *     Note: Leadis LDS176 controller (GE-12) is 100% compatible with Philips PCF8833
 *
 *     Nokia 6610 has a 132 x 132 pixel matrix - each pixel has 12 bits of colour information.
 *
 * @verbatim
 *                                 +--+
 *                                 |  |
 *              ___________________|__|_____
 *              |  ======================  |
 *     ^ (131,0)|--------------------------|(131,131)
 *     |        |                          |
 *     |        |                          |
 *     |        |                          |
 *     |        |                          |
 *     |        |                          |
 *     |    Rows|   Nokia 6610 Display     | Note: In general, you can't view Row 0 or Row 131
 *     |        |                          |        and Column 0 and Column 131.
 *     Y        |                          |
 *     |        |
 *     |        |                          |
 *     |        |                          |
 *     |        |                          |
 *     |        |                          |
 *     +        |--------------------------|
 *             (0,0)     Columns          (0,131)
 *              +---------- X ------------->
 *
 * @endverbatim
 *
 *     132 x 132 pixel matrix has three methods to specify the colour info
 *
 *     1. 12 bits per pixel
 *        requires command and 1.5 data bytes to specify a single pixel
 *        (3 data bytes can specify 2 pixels)
 *
 *     2. 8 bits per pixel
 *        requires one command and one data byte to specify the single pixel
 *        note: pixel data byte converted by RGB table to 12-bit format above
 *
 *     3. 16 bits per pixel
 *        requires one command and two data bytes to specify the single pixel
 *        note: pixel data bytes converted by dithering circuitry to 12-bit format above
 *
 *     THIS IMPLEMENTATION USES THE 12 BITS PER PIXEL METHOD!
 *     -------------------------
 *
 *     Notes: To orient the LCD display so that the origin (0, 0) is at the opposite
 *            corner from the connector (to match the orientation of the Olimex SAM7-EX256
 *            boards silk screen printing), I selected "mirror x" and "mirror y" setting
 *            in the MADCTL command (MY=1, MX=1).
 *
 *            Also, while I can't yet explain it, I had to reverse the RGB orientation in the
 *            MADCTL command and invert the entire display using the INVON command to make
 *            0x0=black, 0xF= full red.
 *
 * @author James P Lynch July 7, 2007,
 *         modified for Kinetis PO'Donoghue May, 2013
 *
 */
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include <stddef.h>
#include "nokia_LCD.h"
#define   LCD_SPI_PRIVATE
#include "nokia_LCD_private.h"
#include "lcd_spi.h"
#include "lcd_fonts.h"
#include "derivative.h"

#define DEFAULT_LCD_CONTRAST (65) // Philips controller

void lcd_spiTxCommand(uint8_t data);
void lcd_spiTxData(uint8_t data);

#ifdef ELEC_FREAKS
#define   PHILIPS
#undef    EPSON
#endif

#ifdef ELEC_FREAKS
#include "utilities.h"
#define LCD_PWM_REG            C  // = D10 on arduino
#define LCD_PWM_NUM            2

#define LCD_PWM_MASK         (1<<LCD_PWM_NUM)
#define LCD_PWM_PCR          PCR(LCD_PWM_REG,LCD_PWM_NUM)
#define LCD_PWM_PDOR         PDOR(LCD_PWM_REG)
#define LCD_PWM_PSOR         PSOR(LCD_PWM_REG)  // Data set
#define LCD_PWM_PCOR         PCOR(LCD_PWM_REG)  // Data clear
#define LCD_PWM_PTOR         PTOR(LCD_PWM_REG)  // Data toggle
#define LCD_PWM_PDIR         PDIR(LCD_PWM_REG)  // Data input
#define LCD_PWM_PDDR         PDDR(LCD_PWM_REG)  // Data direction

void lcdPwmOn(void) {
   LCD_PWM_PSOR = LCD_PWM_MASK;
}
void lcdPwmOff(void) {
   LCD_PWM_PCOR = LCD_PWM_MASK;
}

void lcdPwmInitialise(void) {
   SIM_SCGC5 |= SIM_SCGC5_PORTC_MASK;
   lcdPwmOn();

   LCD_PWM_PDDR  |= LCD_PWM_MASK;
   LCD_PWM_PCR    = PORT_PCR_MUX(1)|PORT_PCR_DSE_MASK|PORT_PCR_PE_MASK|PORT_PCR_PS_MASK;
}
#endif

//! Initialise the LCD before first use
//!
void lcd_initialise(void) {
   lcd_spiInitialise();
   lcd_spiSetSpeed(12000 /* kHz */);

#ifdef ELEC_FREAKS
   lcdPwmInitialise();
#endif

#ifdef PHILIPS
   lcd_spiTxCommand(P_INVOFF);                  // Inversion off
   lcd_spiTxCommand(P_SLEEPOUT);                // Sleep out

   lcd_spiTxCommand(P_COLMOD);                  // Set Colour Mode
   lcd_spiTxData(0x03);                         // 3 = 12-bits/pixel

   lcd_spiTxCommand(P_MADCTL);                  // Memory Access Control
   lcd_spiTxData(0x80);                         // Mirror x,y

   lcd_setContrast(DEFAULT_LCD_CONTRAST);       // Set default contrast
//   spi_txCommand(P_BSTRON);                   // Boost On

   lcd_spiTxCommand(P_DISPON);                  // Display on
#endif
#ifdef EPSON
   lcd_spiTxCommand(DISCTL);        // Display control(EPSON)
   lcd_spiTxData(0x00);             // P1: 0x00 = 2 divisions, switching period=8 (default)
   lcd_spiTxData(0x20);             // P2: 0x20 = nlines/4 - 1 = 132/4 - 1 = 32)
   lcd_spiTxData(0x00);             // P3: 0x00 = no inversely highlighted lines
   lcd_spiTxData(0x01);             // P4 ??

   lcd_spiTxCommand(COMSCN);        // COM scan
   lcd_spiTxData(0x01);             // P1: 0x01 = Scan 1->80, 160<-81

   lcd_spiTxCommand(OSCON);         // Internal oscillator ON

   lcd_spiTxCommand(SLPOUT);        // Sleep out

   lcd_spiTxCommand(PWRCTR);        // Power control
   lcd_spiTxData(0x0F);             // Reference voltage regulator on, circuit voltage follower on, BOOST ON

   lcd_spiTxCommand(DISINV);        // Inverse display

   lcd_spiTxCommand(DATCTL);        // Data control
   lcd_spiTxData(0x03);             // P1: //0x01 = page address inverted, col address normal, address scan in col direction
   lcd_spiTxData(0x00);             // P2: 0x00 = RGB sequence (default value)
   lcd_spiTxData(0x02);             // P3: 0x02 = Grayscale -> 16 (selects 12-bit color, type A)

   lcd_spiTxCommand(VOLCTR);        // Voltage control (contrast setting)
   lcd_spiTxData(35);               // P1: 32 volume value (adjust this setting for your display 0 .. 63)
   lcd_spiTxData(0x03);             // P2: 3 resistance ratio (determined by experiment)

   WAIT_MS(200);                    // Allow power supply to stabilise

   lcd_spiTxCommand(DISON);         // Turn on the display

//   int i;
//   for (i=0; i<64; i++) {
//      lcd_spiTxCommand(VOLCTR);        // Voltage control (contrast setting)
//      lcd_spiTxData(i);                // P1: 32 volume value (adjust this setting for your display 0 .. 63)
//      lcd_spiTxData(0x03);             // P2: 3 resistance ratio (determined by experiment)
//      WAIT_MS(200);
//   }

//   lcd_spiTxCommand(DATCTL);        // data control(EPSON)
//   lcd_spiTxData(0x03);             // correct for normal sin7
//   lcd_spiTxData(0x00);             // normal RGB arrangement
//   lcd_spiTxData(0x01);             // 8-bit Grayscale
//   lcd_spiTxData(0x02);             // 16-bit Grayscale Type A

#endif
}

//! Writes the entire LCD screen from a bmp file
//! Uses Olimex BmpToArray.exe utility
//!
//! @param bmp - bitmap to display
//!
//! @author Olimex, James P Lynch July 7, 2007
//!
void lcd_write130x130bmp(uint8_t bmp[131*131]) {
   unsigned j; // loop counter

#ifdef PHILIPS
   // Memory access controller (command 0x36)
   lcd_spiTxCommand(P_MADCTL);
   lcd_spiTxData(0x48); // no mirror Y (temporary to satisfy Olimex bmptoarray utility)
   // Display OFF
   lcd_spiTxCommand(P_DISPOFF);
   // Column address set (command 0x2A)
   lcd_spiTxCommand(P_CASET);
   lcd_spiTxData(0);
   lcd_spiTxData(131);
   // Page address set (command 0x2B)
   lcd_spiTxCommand(P_PASET);
   lcd_spiTxData(0);
   lcd_spiTxData(131);
   // WRITE MEMORY
   lcd_spiTxCommand(P_RAMWR);
   for (j = 0; j < sizeof(bmp); j++) {
      lcd_spiTxData(bmp[j]);
   }
   // Memory access controller (command 0x36)
   lcd_spiTxCommand(P_MADCTL);
   lcd_spiTxData(0xC8); // restore to (mirror x and y, reverse rgb)
   // Display On
   lcd_spiTxCommand(P_DISPON);
#endif
#ifdef EPSON
   // Memory access controller (command 0x36)
   lcd_spiTxCommand(DATCTL);
   lcd_spiTxData(0x48); // no mirror Y (temporary to satisfy Olimex bmptoarray utility)
   // Display OFF
   lcd_spiTxCommand(DISOFF);
   // Column address set (command 0x2A)
   lcd_spiTxCommand(CASET);
   lcd_spiTxData(0);
   lcd_spiTxData(131);
   // Page address set (command 0x2B)
   lcd_spiTxCommand(PASET);
   lcd_spiTxData(0);
   lcd_spiTxData(131);
   // WRITE MEMORY
   lcd_spiTxCommand(RAMWR);
   for (j = 0; j < sizeof(bmp); j++) {
      lcd_spiTxData(bmp[j]);
   }
   // Memory access controller (command 0x36)
   lcd_spiTxCommand(DATCTL);
   lcd_spiTxData(0xC8); // restore to (mirror x and y, reverse rgb)
   // Display On
   lcd_spiTxCommand(DISON);
#endif
}

//! This function will clear the screen to the given color.
//!
//! @param color - 12-bit color value rrrrggggbbbb
//!
//! @author James P Lynch July 7, 2007
//!
void lcd_clear(int color) {
   int i;

#ifdef PHILIPS
   lcd_spiTxCommand(P_PASET);
   lcd_spiTxData(0);
   lcd_spiTxData(131);

   lcd_spiTxCommand(P_CASET);
   lcd_spiTxData(0);
   lcd_spiTxData(131);

   // Construct RRRRGGGG|GGGGRRRR|GGGGBBBB in 3 bytes = 2 pixels
   uint8_t data1 = (color >> 4);
   uint8_t data2 = ((color & 0xF) << 4) | ((color >> 8) & 0xF);
   uint8_t data3 = color & 0xFF;;
   lcd_spiTxCommand(P_RAMWR);
   for (i = 0; i < ((131 * 131) / 2); i++) {
      lcd_spiTxData(data1);
      lcd_spiTxData(data2);
      lcd_spiTxData(data3);
   }
#endif
#ifdef EPSON
   lcd_spiTxCommand(PASET);
   lcd_spiTxData(0);
   lcd_spiTxData(131);

   lcd_spiTxCommand(CASET);
   lcd_spiTxData(0);
   lcd_spiTxData(131);

   // Construct RRRRGGGGBBBB=>RRRRGGGG|BBBBRRRR|GGGGBBBB in 3 bytes = 2 pixels
   uint8_t data1 = (color >> 4);
   uint8_t data2 = ((color & 0xF) << 4) | ((color >> 8) & 0xF);
   uint8_t data3 = color & 0xFF;;

   lcd_spiTxCommand(RAMWR);

   for (i=0; i < (131*131)/2; i++) {
      lcd_spiTxData(data1);
      lcd_spiTxData(data2);
      lcd_spiTxData(data3);
   }
#endif
}

//! Sets the Row and Column addresses
//!
//! @param x = row address (0 .. 131)
//! @param y = column address (0 .. 131)
//!
//! @author James P Lynch July 7, 2007
//!
static void lcd_setXY(int x, int y) {
   // Row address set (command 0x2B)
#ifdef PHILIPS
   lcd_spiTxCommand(P_PASET);
   lcd_spiTxData(y);
   lcd_spiTxData(y);
   // Column address set (command 0x2A)
   lcd_spiTxCommand(P_CASET);
   lcd_spiTxData(x);
   lcd_spiTxData(x);
#endif

#ifdef EPSON
   lcd_spiTxCommand(PASET);
   lcd_spiTxData(y);
   lcd_spiTxData(y);
   // Column address set (command 0x2A)
   lcd_spiTxCommand(CASET);
   lcd_spiTxData(x);
   lcd_spiTxData(x);
#endif
}

//! Lights a single pixel in the specified color at the specified x and y addresses
//!
//! @param  x     - row address (0 .. 131)
//! @param  y     - column address (0 .. 131)
//! @param  color - 12-bit color value rrrrggggbbbb
//!
//! @note See lcd.h for some sample color settings
//!
//! @author James P Lynch July 7, 2007
//!
void lcd_drawPixel(int x, int y, int color) {
#ifdef PHILIPS
   lcd_setXY(x, y);
   lcd_spiTxCommand(P_RAMWR);
   // Construct RRRRGGGGBBBB=>RRRRGGGG|BBBBxxxx in 3 bytes = 2 pixels
   lcd_spiTxData((unsigned char)(color >> 4));
   lcd_spiTxData((unsigned char)(((color & 0x0F) << 4) | 0x00));
   lcd_spiTxCommand(P_NOP);
#endif

#ifdef EPSON
   lcd_setXY(x, y);
   lcd_spiTxCommand(RAMWR);
   // Construct RRRRGGGGBBBB=>RRRRGGGG|BBBBxxxx in 3 bytes = 2 pixels
   lcd_spiTxData((unsigned char)(color >> 4));
   lcd_spiTxData((unsigned char)(((color & 0x0F) << 4) | 0x0F));
   lcd_spiTxCommand(0xFF);
#endif

}

//! Draws a line in the specified color from (x0,y0) to (x1,y1)
//!
//! @param  x0     - row address (0 .. 131)
//! @param  y0     - column address (0 .. 131)
//! @param  x1     - row address (0 .. 131)
//! @param  y1     - column address (0 .. 131)
//! @param  color  - 12-bit color value rrrrggggbbbb
//!
//! @note See lcd.h for some sample color settings
//!
//! @author James P Lynch July 7, 2007
//!
//! @note Good write-up on this algorithm in Wikipedia (search for Bresenham's line algorithm)
//! @note See lcd.h for some sample color settings
//!
//! @author Authors: Dr. Leonard McMillan, Associate Professor UNC \n
//!                  Jack Bresenham IBM, Winthrop University (Father of this algorithm, 1962)
//!
//! @note Taken verbatim from Professor McMillan's presentation: \n
//!       http://www.cs.unc.edu/~mcmillan/comp136/Lecture6/Lines.html
//!
void lcd_drawLine(int x0, int y0, int x1, int y1, int color) {
   int dy = y1 - y0;
   int dx = x1 - x0;
   int stepx, stepy;
   if (dy < 0) {
      dy = -dy;
      stepy = -1;
   } else {
      stepy = 1;
   }
   if (dx < 0) {
      dx = -dx;
      stepx = -1;
   } else {
      stepx = 1;
   }
   dy <<= 1; // dy is now 2*dy
   dx <<= 1; // dx is now 2*dx
   lcd_drawPixel(x0, y0, color);
   if (dx > dy) {
      int fraction = dy - (dx >> 1); // same as 2*dy - dx
      while (x0 != x1) {
         if (fraction >= 0) {
            y0 += stepy;
            fraction -= dx; // same as fraction -= 2*dx
         }
         x0 += stepx;
         fraction += dy; // same as fraction -= 2*dy
         lcd_drawPixel(x0, y0, color);
      }
   } else {
      int fraction = dx - (dy >> 1);
      while (y0 != y1) {
         if (fraction >= 0) {
            x0 += stepx;
            fraction -= dy;
         }
         y0 += stepy;
         fraction += dx;
         lcd_drawPixel(x0, y0, color);
      }
   }
}

//! Draws a rectangle in the specified color from (x1,y1) to (x2,y2)
//! Rectangle can be filled with a color if desired
//!
//! @param  x0     - row address (0 .. 131)
//! @param  y0     - column address (0 .. 131)
//! @param  x1     - row address (0 .. 131)
//! @param  y1     - column address (0 .. 131)
//! @param  color  - 12-bit color value rrrrggggbbbb
//!
//! @note See lcd.h for some sample color settings
//!
//! @author James P Lynch July 7, 2007
//!
//! @note
//!     The best way to fill a rectangle is to take advantage of the "wrap-around" feature
//!     built into the Philips PCF8833 controller. By defining a drawing box, the memory can
//!     be simply filled by successive memory writes until all pixels have been illuminated.
//!
//!     1. Given the coordinates of two opposing corners (x0, y0) (x1, y1)
//!        calculate the minimums and maximums of the coordinates
//!
//!        xmin = (x0 <= x1) ? x0 : x1;
//!        xmax = (x0 > x1) ? x0 : x1;
//!        ymin = (y0 <= y1) ? y0 : y1;
//!        ymax = (y0 > y1) ? y0 : y1;
//!
//!     2. Now set up the drawing box to be the desired rectangle
//!
//!        LCDCommand(PASET); // set the row boundaries
//!        LCDData(xmin);
//!        LCDData(xmax);
//!        LCDCommand(CASET); // set the column boundaries
//!        LCDData(ymin);
//!        LCDData(ymax);
//!
//!     3. Calculate the number of pixels to be written divided by 2
//!
//!        NumPixels = ((((xmax - xmin + 1) * (ymax - ymin + 1)) / 2) + 1)
//!
//!        You may notice that I added one pixel to the formula.
//!        This covers the case where the number of pixels is odd and we
//!        would lose one pixel due to rounding error. In the case of
//!        odd pixels, the number of pixels is exact.
//!        in the case of even pixels, we have one more pixel than
//!        needed, but it cannot be displayed because it is outside
//!        the drawing box.
//!
//!        We divide by 2 because two pixels are represented by three bytes.
//!        So we work through the rectangle two pixels at a time.
//!
//!     4. Now a simple memory write loop will fill the rectangle
//!
//!        for (i = 0; i < ((((xmax - xmin + 1) * (ymax - ymin + 1)) / 2) + 1); i++) {
//!           LCDData((color >> 4) & 0xFF);
//!           LCDData(((color & 0xF) << 4) | ((color >> 8) & 0xF));
//!           LCDData(color & 0xFF);
//!        }
//!
//!        In the case of an unfilled rectangle, drawing four lines with the Bresenham line
//!        drawing algorithm is reasonably efficient.
//!
void lcd_drawRect(int x0, int y0, int x1, int y1, int fill, int color) {
   int xmin, xmax, ymin, ymax;
   int i;
   // check if the rectangle is to be filled
   if (fill) {
      // best way to create a filled rectangle is to define a drawing box
      // and loop two pixels at a time
      // calculate the min and max for x and y directions
      xmin = (x0 <= x1) ? x0 : x1;
      xmax = (x0 > x1) ? x0 : x1;
      ymin = (y0 <= y1) ? y0 : y1;
      ymax = (y0 > y1) ? y0 : y1;
      // specify the controller drawing box according to those limits
      // Row address set (command 0x2B)
#ifdef PHILIPS
      lcd_spiTxCommand(P_CASET);
#endif
#ifdef EPSON
      lcd_spiTxCommand(CASET);
#endif
      lcd_spiTxData(xmin);
      lcd_spiTxData(xmax);
      // Column address set (command 0x2A)
#ifdef PHILIPS
      lcd_spiTxCommand(P_PASET);
#endif
#ifdef EPSON
      lcd_spiTxCommand(PASET);
#endif
      lcd_spiTxData(ymin);
      lcd_spiTxData(ymax);
      // WRITE MEMORY
#ifdef PHILIPS
      lcd_spiTxCommand(P_RAMWR);
#endif
#ifdef EPSON
      lcd_spiTxCommand(RAMWR);
#endif
      // loop on total number of pixels / 2
      for (i = 0; i < ((((xmax - xmin + 1) * (ymax - ymin + 1)) / 2) + 1);
            i++) {
         // use the color value to output three data bytes covering two pixels
         lcd_spiTxData((color >> 4) & 0xFF);
         lcd_spiTxData(((color & 0xF) << 4) | ((color >> 8) & 0xF));
         lcd_spiTxData(color & 0xFF);
      }
   } else {
      // best way to draw unfilled rectangle is to draw four lines
      lcd_drawLine(x0, y0, x1, y0, color);
      lcd_drawLine(x0, y1, x1, y1, color);
      lcd_drawLine(x0, y0, x0, y1, color);
      lcd_drawLine(x1, y0, x1, y1, color);
   }
}

//!  Draws an ASCII character at the specified (x,y) address and color
//!
//!  @param c      = character to be displayed
//!  @param x      = row address (0 .. 131)
//!  @param y      = column address (0 .. 131)
//!  @param size   = font pitch (SMALL, MEDIUM, LARGE)
//!  @param fcolor = 12-bit foreground color value
//!  @param bcolor = 12-bit background color value
//!
//!  @verbatim
//!  Notes: Here's an example to display "E" at address (20,20)
//!
//!            LCDPutChar('E', 20, 20, MEDIUM, WHITE, BLACK);
//!
//!                 (27,20)       (27,27)
//!                    |             |
//!                    |             |
//!                  ^ V             V
//!                  : _ # # # # # # #   0x7F
//!                  : _ _ # # _ _ _ #   0x31
//!                  : _ _ # # _ # _ _   0x34
//!                  x _ _ # # # # _ _   0x3C
//!                  : _ _ # # _ # _ _   0x34
//!                  : _ _ # # _ _ _ #   0x31
//!                  : _ # # # # # # #   0x7F
//!                  : _ _ _ _ _ _ _ _   0x00
//!
//!                    ------y------->
//!                    ^             ^
//!                    |             |
//!                    |             |
//!                 (20,20)       (20,27)
//!
//!
//!     The most efficient way to display a character is to make use of the "wrap-around" feature
//!     of the Philips PCF8833 LCD controller chip.
//!
//!     Assume that we position the character at (20, 20) that's a (row, col) specification.
//!     With the row and column address set commands, you can specify an 8x8 box for the SMALL and MEDIUM
//!     characters or a 16x8 box for the LARGE characters.
//!
//!             spi_txCommand(PASET);   // set the row drawing limits
//!             spi_txData(20);         //
//!             spi_txData(27);         // limit rows to (20, 27)
//!
//!             spi_txCommand(CASET);   // set the column drawing limits
//!             spi_txData(20);         //
//!             spi_txData(27);         // limit columns to (20,27)
//!
//!     When the algorithm completes col 27, the column address wraps back to 20
//!     At the same time, the row address increases by one (this is done by the controller)
//!
//!     We walk through each row, two pixels at a time. The purpose is to create three
//!     data bytes representing these two pixels in the following format (as specified by Philips
//!     for RGB 4 : 4 : 4 format (see page 62 of PCF8833 controller manual).
//!
//!             Data for pixel 0: RRRRGGGGBBBB
//!             Data for Pixel 1: RRRRGGGGBBBB
//!
//!             spi_txCommand(RAMWR);                 // start a memory write (96 data bytes to follow)
//!
//!             spi_txData(RRRRGGGG);                 // first pixel, red and green data
//!             spi_txData(BBBBRRRR);                 // first pixel, blue data; second pixel, red data
//!             spi_txData(GGGGBBBB);                 // second pixel, green and blue data
//!             :
//!             and so on until all pixels displayed!
//!             :
//!             spi_txCommand(NOP);                   // this will terminate the RAMWR command
//!
//!   @endverbatim
//!
//!   @author James P Lynch July 7, 2007
//!
void lcd_putChar(char c, int x, int y, FontSize fontSize, int fColor, int bColor) {
   unsigned int nCols;
   unsigned int nRows;
   unsigned int nBytes;
   unsigned char pixelRow;
   unsigned char mask;
   unsigned int word0;
   unsigned int word1;
   unsigned char *pFont;
   unsigned char *pChar;
   static const unsigned char *FontTable[] = {
         (unsigned char *)FONT6x8,
         (unsigned char *)FONT8x8,
         (unsigned char *)FONT8x16
   };
   // Get pointer to the beginning of the selected font table
   pFont = (unsigned char *)FontTable[fontSize];

   // Get the nColumns, nRows and nBytes
   nCols  = *pFont;
   nRows  = *(pFont + 1);
   nBytes = *(pFont + 2);

   // Get pointer to the last byte of the desired character
   pChar = pFont + (nBytes * (c - 0x1F)) + nBytes - 1;

   // Row address set (command 0x2B)
#ifdef PHILIPS
      lcd_spiTxCommand(P_CASET);
#endif
#ifdef EPSON
      lcd_spiTxCommand(CASET);
#endif
   lcd_spiTxData(x);
   lcd_spiTxData(x + nCols - 1);

   // Column address set (command 0x2A)
#ifdef PHILIPS
      lcd_spiTxCommand(P_PASET);
#endif
#ifdef EPSON
      lcd_spiTxCommand(PASET);
#endif
   lcd_spiTxData(y);
   lcd_spiTxData(y + nRows - 1);

   // Write memory
#ifdef PHILIPS
      lcd_spiTxCommand(P_RAMWR);
#endif
#ifdef EPSON
      lcd_spiTxCommand(RAMWR);
#endif

   // Loop on each row, working backwards from the bottom to the top
   int i;
   for (i = nRows - 1; i >= 0; i--) {
      unsigned j;
      // Copy pixel row from font table and then decrement row
      pixelRow = *pChar--;
      // Loop on each pixel in the row (left to right)
      // Note: we do two pixels each loop
      mask = 0x80;
      for (j = 0; j < nCols; j += 2) {
         // If pixel bit set, use foreground colour; else use the background colour
         // Now get the pixel colour for two successive pixels
         if ((pixelRow & mask) == 0) {
            word0 = bColor;
         }
         else {
            word0 = fColor;
         }
         mask = mask >> 1;
         if ((pixelRow & mask) == 0) {
            word1 = bColor;
         }
         else {
            word1 = fColor;
         }
         mask = mask >> 1;

         // Use this information to output three data bytes
         lcd_spiTxData((word0 >> 4) & 0xFF);
         lcd_spiTxData(((word0 & 0xF) << 4) | ((word1 >> 8) & 0xF));
         lcd_spiTxData(word1 & 0xFF);
      }
   }
   // Terminate the Write Memory command
#ifdef PHILIPS
      lcd_spiTxCommand(P_NOP);
#endif
#ifdef EPSON
      lcd_spiTxCommand(NOP);
#endif
}

//!  Draws a null-terminates character string at the specified (x,y) address and color
//!
//!  @param pString = pointer to character string to be displayed
//!  @param x = row address (0 .. 131)
//!  @param y = column address (0 .. 131)
//!  @param Size = font pitch (SMALL, MEDIUM, LARGE)
//!  @param fColor = 12-bit foreground colour value rrrrggggbbbb
//!  @param bColor = 12-bit background colour value rrrrggggbbbb
//!
//!  @note Here's an example to display "Hello World!" at address (20,20) \n
//!        LCDPutChar("Hello World!", 20, 20, WHITE, BLACK);
//!
//!  @author James P Lynch, August 30, 2007 \n
//!          Edited by Peter Davenport on August 23, 2010
//!
//!  @note For more information on how this code does it's thing look at this \n
//!        "http://www.sparkfun.com/tutorial/Nokia%206100%20LCD%20Display%20Driver.pdf"
//!
void lcd_putStr(const char *pString, int x, int y, FontSize fontSize, int fColor, int bColor) {
   // loop until null-terminator is seen
   while (*pString != 0x00) {
      // draw the character
      lcd_putChar(*pString++, x, y, fontSize, fColor, bColor);
      // advance the y position
      if (fontSize == FontSmall)
         x = x + 6;
      else if (fontSize == FontMedium)
         x = x + 8;
      else
         x = x + 8;
      // bail out if y exceeds 131
      if (y > 131) break;
   }
}

//! Set LCD contrast - varies with device
//!
//! @param setting - contrast level (0..127) ?
//!
void lcd_setContrast(uint8_t setting) {
#ifdef EPSON
   lcd_spiTxCommand(VOLCTR);       // electronic volume, this is the contrast/brightness(EPSON)
   lcd_spiTxData(setting);         // volume (contrast) setting - course adjustment,  -- original was 24
   //     LCDData(0x03);     // internal resistor ratio - coarse adjustment
   //     LCDData(0x30);
   lcd_spiTxCommand(NOP);          // nop(EPSON)
#endif
#ifdef PHILIPS
   lcd_spiTxCommand(P_SETCON);     // Contrast/brightness
   lcd_spiTxData(setting);
#endif
}

//! Draws a line in the specified colour at center (x0,y0) with radius
//!
//! @param x0 = row address (0 .. 131)
//! @param y0 = column address (0 .. 131)
//! @param radius = radius in pixels
//! @param color = 12-bit colour value rrrrggggbbbb
//!
//! @author Jack Bresenham IBM, Winthrop University (Father of this algorithm, 1962)
//!
//! @note Taken verbatim Wikipedia article on Bresenham's line algorithm \n
//!        http://www.wikipedia.org
//!
void lcd_drawCircle(int x0, int y0, int radius, int color, int circleType) {
   int f = 1 - radius;
   int ddF_x = 0;
   int ddF_y = -2 * radius;
   int x = 0;
   int y = radius;

   if (circleType&(SECTOR_315_360|SECTOR_0_45)) {
      lcd_drawPixel(x0 + radius, y0, color);  // 0,360
   }
   if (circleType&(SECTOR_45_90|SECTOR_90_135)) {
      lcd_drawPixel(x0, y0 + radius, color);  // 90
   }
   if (circleType&(SECTOR_135_180|SECTOR_180_225)) {
      lcd_drawPixel(x0 - radius, y0, color);  // 180
   }
   if (circleType&(SECTOR_225_270|SECTOR_270_315)) {
      lcd_drawPixel(x0, y0 - radius, color);  // 270
   }
   while (x < y) {
      if (f >= 0) {
         y--;
         ddF_y += 2;
         f += ddF_y;
      }
      x++;
      ddF_x += 2;
      f += ddF_x + 1;
      if (circleType&SECTOR_0_45) {
         lcd_drawPixel(x0 + y, y0 + x, color);   // 0-45
      }
      if (circleType&SECTOR_45_90) {
         lcd_drawPixel(x0 + x, y0 + y, color);   // 45-90
      }
      if (circleType&SECTOR_90_135) {
         lcd_drawPixel(x0 - x, y0 + y, color);   // 90-135
      }
      if (circleType&SECTOR_135_180) {
         lcd_drawPixel(x0 - y, y0 + x, color);   // 135-180
      }
      if (circleType&SECTOR_180_225) {
         lcd_drawPixel(x0 - y, y0 - x, color);   // 180-225
      }
      if (circleType&SECTOR_225_270) {
         lcd_drawPixel(x0 - x, y0 - y, color);   // 225-270
      }
      if (circleType&SECTOR_270_315) {
         lcd_drawPixel(x0 + x, y0 - y, color);   // 270-315
      }
      if (circleType&SECTOR_315_360) {
         lcd_drawPixel(x0 + y, y0 - x, color);   // 315-360
      }
   }
}


text:
package shadowsocks

import (
	"errors"
	"strings"
	"fmt"
	"net"
	"time"
)

type Dialer struct {
	cipher *Cipher
	server string
	support_udp bool
}

type ProxyConn struct {
	*Conn
	raddr *ProxyAddr
}

type ProxyAddr struct {
	network string
	address string
}

var ErrNilCipher = errors.New("cipher can't be nil")

func NewDialer(server string, cipher *Cipher) (dialer *Dialer, err error) {
	// Currently shadowsocks-go do not support UDP
	if cipher == nil {
		return nil, ErrNilCipher
	}
	return &Dialer {
		cipher: cipher,
		server: server,
		support_udp: false,
	}, nil
}

func (d *Dialer) Dial(network, addr string) (c net.Conn, err error) {
	if strings.HasPrefix(network, "tcp") {
		conn, err := Dial(addr, d.server, d.cipher.Copy())
		if err != nil {
			return nil, err
		}
		return &ProxyConn {
			Conn: conn,
			raddr: &ProxyAddr {
				network: network,
				address: addr,
			},
		}, nil
	}
	return nil, fmt.Errorf("unsupported connection type: %s", network)
}

func (c *ProxyConn) LocalAddr() net.Addr {
	return c.Conn.LocalAddr()
}

func (c *ProxyConn) RemoteAddr() net.Addr {
	return c.raddr
}

func (c *ProxyConn) SetDeadline(t time.Time) error {
	return c.Conn.SetDeadline(t)
}

func (c *ProxyConn) SetReadDeadline(t time.Time) error {
	return c.Conn.SetReadDeadline(t)
}

func (c *ProxyConn) SetWriteDeadline(t time.Time) error {
	return c.Conn.SetWriteDeadline(t)
}

func (a *ProxyAddr) Network() string {
	return a.network
}

func (a *ProxyAddr) String() string {
	return a.address
}

redpajama_set_name: RedPajamaGithub


text:
package com.vocalabs.egtest.writer.junit;

import com.squareup.javapoet.AnnotationSpec;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.TypeSpec;
import com.vocalabs.egtest.annotation.EgLanguage;
import com.vocalabs.egtest.writer.AllClassesWriter;
import com.vocalabs.egtest.processor.JavaModelUtil;
import com.vocalabs.egtest.processor.MessageHandler;
import com.vocalabs.egtest.processor.data.EgItem;
import com.vocalabs.egtest.writer.Constants;

import javax.annotation.Generated;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * Build JUnit test classes; used by {@link AllClassesWriter}.
 */
public class JUnitClassWriter {

    public static void write(Map<String,EgLanguage> languageForClassName,
                             EgLanguage defaultLanguage,
                             String classUnderTestName,
                             MessageHandler messageHandler,
                             List<EgItem<?>> items,
                             File targetDirectory)
    throws IOException {
        if (items.isEmpty())
            throw new IllegalArgumentException("Must have at least one Example to write a test file for "+classUnderTestName);
        TypeElement classElement = JavaModelUtil.topLevelClass(items.get(0).getElement());
        CodeInjector codeInjector = new CodeInjector(classElement, languageForClassName, defaultLanguage);
        new JUnitClassWriter(codeInjector, classElement, messageHandler, items)
                .createFileSpec()
                .writeTo(targetDirectory);
    }

    private final MessageHandler messageHandler;
    private final List<EgItem<?>> items;
    private final TypeElement classElement;
    private final String className;
    private final CodeInjector codeInjector;

    private JUnitClassWriter(CodeInjector codeInjector, TypeElement classElement, MessageHandler messageHandler, List<EgItem<?>> items) {
        this.codeInjector = codeInjector;
        this.messageHandler = messageHandler;
        this.items = items;
        this.classElement = JavaModelUtil.topLevelClass(items.get(0).getElement());
        this.className = classElement.getSimpleName() +"$EgTest";
    }

    private JavaFile createFileSpec() {
        AnnotationSpec generated = AnnotationSpec.builder(Generated.class)
                .addMember("value", "$S", Constants.GENERATED_BY)
                .build();
        TypeSpec.Builder typeSpecBuilder = TypeSpec.classBuilder(className)
                .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
                .addAnnotation(generated);
        TestWriter.write(this, typeSpecBuilder);
        codeInjector.decorateClass(typeSpecBuilder);
        TypeSpec javaFileSpec = typeSpecBuilder.build();
        JavaFile.Builder fileBuilder = JavaFile.builder(codeInjector.getPackageName(), javaFileSpec);
        return fileBuilder.build();
    }

    MessageHandler getMessageHandler() { return messageHandler; }

    List<EgItem<?>> getItems() { return items; }

    TypeElement getClassElement() { return classElement; }

    public CodeInjector getCodeInjector() { return codeInjector; }
}


text:
import QUnit from 'steal-qunit';
import plugin from './done-masonry';

QUnit.module('done-masonry');

QUnit.test('Initialized the plugin', function(){
  QUnit.equal(typeof plugin, 'function');
  QUnit.equal(plugin(), 'This is the done-masonry plugin');
});


text:
module ReplaceTempWithChain

  class Select

    def self.with_option option
      select = self.new
      select.options << option
      select
    end

    def options
      @options ||= []
    end

    def add_option arg
      options << arg
      self
    end

    alias_method :and, :add_option

  end

end


text:
import Component from '@ember/component';
import { computed } from '@ember/object';

export default Component.extend({
  tagName: 'tr',
  classNameBindings: ['isOdd:tr-odd:tr-even'],
  isOdd: computed('rowIndex', function() {
    return (this.get('rowIndex') % 2 === 0);
  })
});


text:
import Ember from 'ember';
import { expectTypeOf } from 'expect-type';

Ember.Component.extend({
  layout: 'my-layout',
});

const MyComponent = Ember.Component.extend();
expectTypeOf(Ember.get(MyComponent, 'positionalParams')).toEqualTypeOf<string | string[]>();

const component1 = Ember.Component.extend({
  actions: {
    hello(name: string) {
      console.log('Hello', name);
    },
  },
});

class AnotherComponent extends Ember.Component {
  name = '';

  hello(name: string) {
    this.set('name', name);
    this.name = name;
  }
}

Ember.Component.extend({
  tagName: 'em',
});

Ember.Component.extend({
  classNames: ['my-class', 'my-other-class'],
});

class Bindings extends Ember.Component {
  classNameBindings = ['propertyA', 'propertyB'];
  propertyA = 'from-a';

  @Ember.computed()
  get propertyB() {
    if (!this.get('propertyA')) {
      return 'from-b';
    }
  }
}

Ember.Component.extend({
  classNameBindings: ['hovered'],
  hovered: true,
});

class Message extends Ember.Object {
  empty = false;
}

Ember.Component.extend({
  classNameBindings: ['messages.empty'],
  messages: Message.create({
    empty: true,
  }),
});

Ember.Component.extend({
  classNameBindings: ['isEnabled:enabled:disabled'],
  isEnabled: true,
});

Ember.Component.extend({
  classNameBindings: ['isEnabled::disabled'],
  isEnabled: true,
});

Ember.Component.extend({
  tagName: 'a',
  attributeBindings: ['href'],
  href: 'http://google.com',
});

Ember.Component.extend({
  tagName: 'a',
  attributeBindings: ['url:href'],
  url: 'http://google.com',
});

Ember.Component.extend({
  tagName: 'use',
  attributeBindings: ['xlinkHref:xlink:href'],
  xlinkHref: '#triangle',
});

Ember.Component.extend({
  tagName: 'input',
  attributeBindings: ['disabled'],
  disabled: false,
});

Ember.Component.extend({
  tagName: 'input',
  attributeBindings: ['disabled'],
  disabled: Ember.computed(() => {
    return someLogic();
  }),
});

declare function someLogic(): boolean;

Ember.Component.extend({
  tagName: 'form',
  attributeBindings: ['novalidate'],
  novalidate: null,
});

Ember.Component.extend({
  click(event: object) {
    // will be called when an instance's
    // rendered element is clicked
  },
});


text:
import urllib
import json
import os
from bs4 import BeautifulSoup

def fetch(url):
    _, filename = os.path.split(url)
    path = os.path.join("cache", filename)
    if not os.path.exists(path):
        urllib.urlretrieve(url, path)
    return filename, path

LICENSES = []

for line in open("licenses/all.txt"):
    url, name = line.strip().split(" ", 1)
    title, filename = fetch("http://www.opensource.org" + url.replace("\"", ""))

    try:
        soup = BeautifulSoup(open(filename))
    except:
        continue

    pre = soup.find("pre")

    if pre:
        LICENSES.append({
            'name': title,
            'description': name,
            'txt': pre.text,
            })

print json.dumps(LICENSES, indent=4)


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('leagues', '0009_auto_20180625_2035'),
    ]

    operations = [
        migrations.AlterModelOptions(
            name='registrations',
            options={'ordering': ['-registered', '-updated', '-created'], 'verbose_name_plural': 'registrations'},
        ),
    ]


text:
#ifndef N_PARTICLESERVER_H
#define N_PARTICLESERVER_H
//------------------------------------------------------------------------------
/**
    @class nParticleServer
    @ingroup NebulaParticleSystem
    @brief
    Particle subsystem server. Holds an array of all particles and all particle
    emitters in the world. Take care when updating them, the rendering is a
    function of the emitters.

    (C) 2003 RadonLabs GmbH
*/
#include "kernel/nroot.h"
#include "particle/nparticle.h"
#include "particle/nparticleemitter.h"
#include "util/narray.h"
#include "util/nringbuffer.h"

//------------------------------------------------------------------------------
class nParticle;
class nParticleEmitter;

class nParticleServer: public nReferenced
{
private:
    typedef nArray<nParticle> ParticlePool;
    typedef nArray<nParticle*> FreeParticlePool;
    typedef nArray<nParticleEmitter*> EmitterPool;
    typedef nArray<float> FloatRandomPool;
    typedef nArray<int> IntRandomPool;

    enum
    {
        MaxParticles = 10000,       // maximum number of particles in the world
        FloatRandomCount = 65536,   // number of floats in the float random pool
        IntRandomCount = 512,       // number of ints in the int random pool
    };
public:
    /// constructor
    nParticleServer();
    /// destructor
    virtual ~nParticleServer();
    /// get server instance
    static nParticleServer* Instance();
    /// enable/disable particle subsystem
    void SetEnabled(bool b);
    /// is currently enabled?
    bool IsEnabled() const;
    /// Update particles and emitters, delete unused emitters
    void Trigger();
    /// get particle emitter by its key
    nParticleEmitter* GetParticleEmitter(int key);
    /// create a new particle emitter
    nParticleEmitter* NewParticleEmitter();
    /// get a free particle from the pool, or 0 if none exists
    nParticle* GiveFreeParticle();
    /// a particle can go back to the free pool
    void TakeBackParticle(nParticle* particle);
    /// set global force attribute
    void SetGlobalAccel(const vector3& accel);
    /// get global force attribute
    const vector3& GetGlobalAccel() const;
    /// get a random int from the int random pool
    int PseudoRandomInt(int key);
    /// get a random float from the float random pool
    float PseudoRandomFloat(int key);
    /// pseudo random vector
    vector3 PseudoRandomVector3(int key);

private:
    static nParticleServer* Singleton;

    bool enabled;
    EmitterPool        emitterPool;         // stores all used emitters
    ParticlePool       particlePool;        // stores all particles in the world
    FreeParticlePool   freeParticlePool;    // points to all free particles in particlePool
    FloatRandomPool    floatRandomPool;
    IntRandomPool      intRandomPool;
    vector3            globalAccel;
};

//------------------------------------------------------------------------------
/**
*/
inline
nParticleServer*
nParticleServer::Instance()
{
    n_assert(Singleton);
    return Singleton;
}

//------------------------------------------------------------------------------
/**
*/
inline
void
nParticleServer::SetEnabled(bool b)
{
    this->enabled = b;
}

//------------------------------------------------------------------------------
/**
*/
inline
bool
nParticleServer::IsEnabled() const
{
    return this->enabled;
}

//------------------------------------------------------------------------------
/**
*/
inline
void
nParticleServer::SetGlobalAccel(const vector3& accel)
{
    this->globalAccel = accel;
}

//------------------------------------------------------------------------------
/**
*/
inline
const vector3&
nParticleServer::GetGlobalAccel() const
{
    return this->globalAccel;
}

//------------------------------------------------------------------------------
/**
*/
inline
int
nParticleServer::PseudoRandomInt(int key)
{
    // force key into valid range
    key %= (IntRandomCount-1);
    n_assert(key >= 0);
    return this->intRandomPool[key];
};

//------------------------------------------------------------------------------
/**
*/
inline
float
nParticleServer::PseudoRandomFloat(int key)
{
    // force key into valid range
    key %= (FloatRandomCount-1);
    n_assert(key >= 0);
    return this->floatRandomPool[key];
};

//------------------------------------------------------------------------------
/**
*/
inline
vector3
nParticleServer::PseudoRandomVector3(int key)
{
    // align to start of random normalized 3d vector
    key *= 4;
    int k0 = key % (FloatRandomCount - 1);
    n_assert((k0 >= 0) && ((k0 + 2) < FloatRandomCount));
    return vector3(this->floatRandomPool[k0], this->floatRandomPool[k0+1], this->floatRandomPool[k0+2]);
};

//------------------------------------------------------------------------------
/**
*/
inline
nParticle*
nParticleServer::GiveFreeParticle()
{
    if (this->freeParticlePool.Empty())
    {
        return 0;
    }
    else
    {
        nParticle* particle = *(this->freeParticlePool.EraseQuick(this->freeParticlePool.End()-1));
        return particle;
    }
}

//------------------------------------------------------------------------------
/**
*/
inline
void
nParticleServer::TakeBackParticle(nParticle* particle)
{
    particle->SetState(nParticle::Unborn);
    this->freeParticlePool.PushBack(particle);
}

//------------------------------------------------------------------------------
#endif


text:
package com.guillaume.event.db;

import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.ToString;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import java.io.Serializable;
import java.time.LocalDateTime;

@Getter
@Setter
@NoArgsConstructor
@EqualsAndHashCode(of = {"id", "name", "dateTime"})
@ToString
@Entity
public class Event implements Serializable {

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private Long id;

	private String name;

	@JsonDeserialize(using = LocalDateTimeDeserializer.class)
	@JsonSerialize(using = LocalDateTimeSerializer.class)
	private LocalDateTime dateTime;
}


text:
<app-spinner [resource]="league"></app-spinner>

  League doesn't exist!
  Create new league

  League
  {{league.name}}

<app-league-assign [league]="league"></app-league-assign>

    <app-player-ranking [league]="league"></app-player-ranking>


text:
package com.gjiazhe.ggprogressbar;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;

/**
 * Created by gjz on 12/11/15.
 */
public class GGArcProgressBar extends GGProgressBar {

    private float mReachedBarWidth;
    private float mUnreachedBarWidth;
    private float mStartAngle;

    public GGArcProgressBar(Context context) {
        this(context, null);
    }

    public GGArcProgressBar(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public GGArcProgressBar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        final float default_reached_bar_width = dp2px(1.5f);
        final float default_unreached_bar_width = dp2px(1.0f);

        final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.GGProgressBar, defStyleAttr, 0);

        mReachedBarWidth = a.getDimension(R.styleable.GGProgressBar_gpb_reached_bar_width, default_reached_bar_width);
        mUnreachedBarWidth = a.getDimension(R.styleable.GGProgressBar_gpb_unreached_bar_width, default_unreached_bar_width);
        mStartAngle = a.getFloat(R.styleable.GGProgressBar_gpb_start_angle, 0);

        a.recycle();
        setupPaints();
    }

    @Override
    protected void setupPaints() {
        super.setupPaints();
        mReachedBarPaint.setStyle(Paint.Style.STROKE);
        mReachedBarPaint.setStrokeWidth(mReachedBarWidth);
        if (mIfDrawUnreachedBar) {
            mUnreachedBarPaint.setStyle(Paint.Style.STROKE);
            mUnreachedBarPaint.setStrokeWidth(mUnreachedBarWidth);
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.getSize(heightMeasureSpec));
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if (mIfDrawText){
            setupRectFWithText();
            canvas.drawText(mDrawText, mDrawTextX, mDrawTextY, mTextPaint);
        }else {
            setupRectFWithoutText();
        }

        if (mIfDrawUnreachedBar) {
            canvas.drawArc(mUnreachedRectF, 0, 360, false, mUnreachedBarPaint);
        }
        canvas.drawArc(mReachedRectF, mStartAngle, mShownProgress * 360 / mMaxProgress, false, mReachedBarPaint);
    }

    @Override
    protected void setupRectFWithoutText() {
        int paddingLeft = getPaddingLeft();
        int paddingTop = getPaddingTop();
        int paddingRight = getPaddingRight();
        int paddingBottom = getPaddingBottom();
        int widthWithoutPadding = getWidth() - paddingLeft - paddingRight;
        int heightWithoutPadding = getHeight() - paddingTop - paddingBottom;
        int diameter = Math.min(widthWithoutPadding, heightWithoutPadding);
        mReachedRectF.left = paddingLeft + mReachedBarWidth/2.0f;
        mReachedRectF.top = paddingTop + mReachedBarWidth/2.0f;
        mReachedRectF.right = paddingLeft + diameter - mReachedBarWidth/2.0f;
        mReachedRectF.bottom = paddingTop + diameter - mReachedBarWidth/2.0f;

        if (mIfDrawUnreachedBar) {
            mUnreachedRectF.left = paddingLeft + mUnreachedBarWidth/2.0f;
            mUnreachedRectF.top = paddingTop + mUnreachedBarWidth/2.0f;
            mUnreachedRectF.right = paddingLeft + diameter - mUnreachedBarWidth/2.0f;
            mUnreachedRectF.bottom = paddingTop + diameter - mUnreachedBarWidth/2.0f;
        }
    }

    @Override
    protected void setupRectFWithText() {
        setupRectFWithoutText();

        mDrawText = String.format("%d", mShownProgress * 100 / mMaxProgress);
        mDrawText = mPrefix + mDrawText + mSuffix;

        float DrawTextWidth = mTextPaint.measureText(mDrawText);
        mDrawTextX = (mReachedRectF.right + mReachedRectF.left)/2.0f - DrawTextWidth/2.0f;
        mDrawTextY = (mReachedRectF.bottom + mReachedRectF.top)/2.0f- (mTextPaint.descent() + mTextPaint.ascent())/2.0f;
    }

    public void setReachedBarWidth(float width) {
        mReachedBarWidth = width;
        mReachedBarPaint.setStrokeWidth(width);
    }

    public void setUnreachedBarWidth(float width) {
        if (mIfDrawUnreachedBar) {
            mUnreachedBarWidth = width;
            mUnreachedBarPaint.setStrokeWidth(width);
        }
    }

    public float getReachedBarWidth() {
        return mReachedBarWidth;
    }

    public float getUnreachedBarWidth() {
        return mUnreachedBarWidth;
    }

    public float getReachedBarRadius() {
        return (mReachedRectF.right - mReachedRectF.left + mReachedBarWidth)/2.0f;
    }

    public float getUnreachedBarRadius() {
        return (mUnreachedRectF.right - mUnreachedRectF.left + mUnreachedBarWidth)/2.0f;
    }

}


text:
opensips_opts="fifo get_statistics all"
opensips_cmd=
opensips_update_every=5
opensips_timeout=2
opensips_priority=80000

opensips_get_stats() {
	timeout $opensips_timeout "$opensips_cmd" $opensips_opts |\
		grep "^\(core\|dialog\|net\|registrar\|shmem\|siptrace\|sl\|tm\|uri\|usrloc\):[a-zA-Z0-9_ -]\+[[:space:]]*=[[:space:]]*[0-9]\+[[:space:]]*$" |\
		sed \
			-e "s|-|_|g" \
			-e "s|:|_|g" \
			-e "s|[[:space:]]\+=[[:space:]]\+|=|g" \
			-e "s|[[:space:]]\+$||" \
			-e "s|^[[:space:]]\+||" \
			-e "s|[[:space:]]\+|_|" \
			-e "s|^|opensips_|g"

	local ret=$?
	[ $ret -ne 0 ] && echo "opensips_command_failed=1"
	return $ret
}

opensips_check() {
	# if the user did not provide an opensips_cmd
	# try to find it in the system
	if [ -z "$opensips_cmd" ]
		then
		require_cmd opensipsctl || return 1
	fi

	# check once if the command works
	local x="$(opensips_get_stats | grep "^opensips_core_")"
	if [ ! $? -eq 0 -o -z "$x" ]
	then
		echo >&2 "$PROGRAM_NAME: opensips: cannot get global status. Please set opensips_opts='options' whatever needed to get connected to opensips server, in $confd/opensips.conf"
		return 1
	fi

	return 0
}

opensips_create() {
	# create the charts
	cat <<EOF
CHART opensips.dialogs_active '' "OpenSIPS Active Dialogs" "dialogs" dialogs '' area $[opensips_priority + 1] $opensips_update_every
DIMENSION dialog_active_dialogs active absolute 1 1
DIMENSION dialog_early_dialogs early absolute -1 1

CHART opensips.users '' "OpenSIPS Users" "users" users '' line $[opensips_priority + 2] $opensips_update_every
DIMENSION usrloc_registered_users registered absolute 1 1
DIMENSION usrloc_location_users location absolute 1 1
DIMENSION usrloc_location_contacts contacts absolute 1 1
DIMENSION usrloc_location_expires expires incremental -1 1

CHART opensips.registrar '' "OpenSIPS Registrar" "registrations/s" registrar '' line $[opensips_priority + 3] $opensips_update_every
DIMENSION registrar_accepted_regs accepted incremental 1 1
DIMENSION registrar_rejected_regs rejected incremental -1 1

CHART opensips.transactions '' "OpenSIPS Transactions" "transactions/s" transactions '' line $[opensips_priority + 4] $opensips_update_every
DIMENSION tm_UAS_transactions UAS incremental 1 1
DIMENSION tm_UAC_transactions UAC incremental -1 1

CHART opensips.core_rcv '' "OpenSIPS Core Receives" "queries/s" core '' line $[opensips_priority + 5] $opensips_update_every
DIMENSION core_rcv_requests requests incremental 1 1
DIMENSION core_rcv_replies replies incremental -1 1

CHART opensips.core_fwd '' "OpenSIPS Core Forwards" "queries/s" core '' line $[opensips_priority + 6] $opensips_update_every
DIMENSION core_fwd_requests requests incremental 1 1
DIMENSION core_fwd_replies replies incremental -1 1

CHART opensips.core_drop '' "OpenSIPS Core Drops" "queries/s" core '' line $[opensips_priority + 7] $opensips_update_every
DIMENSION core_drop_requests requests incremental 1 1
DIMENSION core_drop_replies replies incremental -1 1

CHART opensips.core_err '' "OpenSIPS Core Errors" "queries/s" core '' line $[opensips_priority + 8] $opensips_update_every
DIMENSION core_err_requests requests incremental 1 1
DIMENSION core_err_replies replies incremental -1 1

CHART opensips.core_bad '' "OpenSIPS Core Bad" "queries/s" core '' line $[opensips_priority + 9] $opensips_update_every
DIMENSION core_bad_URIs_rcvd bad_URIs_rcvd incremental 1 1
DIMENSION core_unsupported_methods unsupported_methods incremental 1 1
DIMENSION core_bad_msg_hdr bad_msg_hdr incremental 1 1

CHART opensips.tm_replies '' "OpenSIPS TM Replies" "replies/s" transactions '' line $[opensips_priority + 10] $opensips_update_every
DIMENSION tm_received_replies received incremental 1 1
DIMENSION tm_relayed_replies relayed incremental 1 1
DIMENSION tm_local_replies local incremental 1 1

CHART opensips.transactions_status '' "OpenSIPS Transactions Status" "transactions/s" transactions '' line $[opensips_priority + 11] $opensips_update_every
DIMENSION tm_2xx_transactions 2xx incremental 1 1
DIMENSION tm_3xx_transactions 3xx incremental 1 1
DIMENSION tm_4xx_transactions 4xx incremental 1 1
DIMENSION tm_5xx_transactions 5xx incremental 1 1
DIMENSION tm_6xx_transactions 6xx incremental 1 1

CHART opensips.transactions_inuse '' "OpenSIPS InUse Transactions" "transactions" transactions '' line $[opensips_priority + 12] $opensips_update_every
DIMENSION tm_inuse_transactions inuse absolute 1 1

CHART opensips.sl_replies '' "OpenSIPS SL Replies" "replies/s" core '' line $[opensips_priority + 13] $opensips_update_every
DIMENSION sl_1xx_replies 1xx incremental 1 1
DIMENSION sl_2xx_replies 2xx incremental 1 1
DIMENSION sl_3xx_replies 3xx incremental 1 1
DIMENSION sl_4xx_replies 4xx incremental 1 1
DIMENSION sl_5xx_replies 5xx incremental 1 1
DIMENSION sl_6xx_replies 6xx incremental 1 1
DIMENSION sl_sent_replies sent incremental 1 1
DIMENSION sl_sent_err_replies error incremental 1 1
DIMENSION sl_received_ACKs ACKed incremental 1 1

CHART opensips.dialogs '' "OpenSIPS Dialogs" "dialogs/s" dialogs '' line $[opensips_priority + 14] $opensips_update_every
DIMENSION dialog_processed_dialogs processed incremental 1 1
DIMENSION dialog_expired_dialogs expired incremental 1 1
DIMENSION dialog_failed_dialogs failed incremental -1 1

CHART opensips.net_waiting '' "OpenSIPS Network Waiting" "kilobytes" net '' line $[opensips_priority + 15] $opensips_update_every
DIMENSION net_waiting_udp UDP absolute 1 1024
DIMENSION net_waiting_tcp TCP absolute 1 1024

CHART opensips.uri_checks '' "OpenSIPS URI Checks" "checks / sec" uri '' line $[opensips_priority + 16] $opensips_update_every
DIMENSION uri_positive_checks positive incremental 1 1
DIMENSION uri_negative_checks negative incremental -1 1

CHART opensips.traces '' "OpenSIPS Traces" "traces / sec" traces '' line $[opensips_priority + 17] $opensips_update_every
DIMENSION siptrace_traced_requests requests incremental 1 1
DIMENSION siptrace_traced_replies replies incremental -1 1

CHART opensips.shmem '' "OpenSIPS Shared Memory" "kilobytes" mem '' line $[opensips_priority + 18] $opensips_update_every
DIMENSION shmem_total_size total absolute 1 1024
DIMENSION shmem_used_size used absolute 1 1024
DIMENSION shmem_real_used_size real_used absolute 1 1024
DIMENSION shmem_max_used_size max_used absolute 1 1024
DIMENSION shmem_free_size free absolute 1 1024

CHART opensips.shmem_fragments '' "OpenSIPS Shared Memory Fragmentation" "fragments" mem '' line $[opensips_priority + 19] $opensips_update_every
DIMENSION shmem_fragments fragments absolute 1 1
EOF

	return 0
}

opensips_update() {
	# the first argument to this function is the microseconds since last update
	# pass this parameter to the BEGIN statement (see bellow).

	# do all the work to collect / calculate the values
	# for each dimension

	# 1. get the counters page from opensips
	# 2. sed to remove spaces; replace . with _; remove spaces around =; prepend each line with: local opensips_
	# 3. egrep lines starting with:
	#    local opensips_client_http_ then one or more of these a-z 0-9 _ then = and one of more of 0-9
	#    local opensips_server_all_ then one or more of these a-z 0-9 _ then = and one of more of 0-9
	# 4. then execute this as a script with the eval
	#    be very carefull with eval:
	#    prepare the script and always grep at the end the lines that are usefull, so that
	#    even if something goes wrong, no other code can be executed

	unset \
		opensips_dialog_active_dialogs \
		opensips_dialog_early_dialogs \
		opensips_usrloc_registered_users \
		opensips_usrloc_location_users \
		opensips_usrloc_location_contacts \
		opensips_usrloc_location_expires \
		opensips_registrar_accepted_regs \
		opensips_registrar_rejected_regs \
		opensips_tm_UAS_transactions \
		opensips_tm_UAC_transactions \
		opensips_core_rcv_requests \
		opensips_core_rcv_replies \
		opensips_core_fwd_requests \
		opensips_core_fwd_replies \
		opensips_core_drop_requests \
		opensips_core_drop_replies \
		opensips_core_err_requests \
		opensips_core_err_replies \
		opensips_core_bad_URIs_rcvd \
		opensips_core_unsupported_methods \
		opensips_core_bad_msg_hdr \
		opensips_tm_received_replies \
		opensips_tm_relayed_replies \
		opensips_tm_local_replies \
		opensips_tm_2xx_transactions \
		opensips_tm_3xx_transactions \
		opensips_tm_4xx_transactions \
		opensips_tm_5xx_transactions \
		opensips_tm_6xx_transactions \
		opensips_tm_inuse_transactions \
		opensips_sl_1xx_replies \
		opensips_sl_2xx_replies \
		opensips_sl_3xx_replies \
		opensips_sl_4xx_replies \
		opensips_sl_5xx_replies \
		opensips_sl_6xx_replies \
		opensips_sl_sent_replies \
		opensips_sl_sent_err_replies \
		opensips_sl_received_ACKs \
		opensips_dialog_processed_dialogs \
		opensips_dialog_expired_dialogs \
		opensips_dialog_failed_dialogs \
		opensips_net_waiting_udp \
		opensips_net_waiting_tcp \
		opensips_uri_positive_checks \
		opensips_uri_negative_checks \
		opensips_siptrace_traced_requests \
		opensips_siptrace_traced_replies \
		opensips_shmem_total_size \
		opensips_shmem_used_size \
		opensips_shmem_real_used_size \
		opensips_shmem_max_used_size \
		opensips_shmem_free_size \
		opensips_shmem_fragments

	opensips_command_failed=0
	eval "local $(opensips_get_stats)"
	[ $? -ne 0 ] && return 1

	[ $opensips_command_failed -eq 1 ] && echo >&2 "$PROGRAM_NAME: opensips: failed to get values, disabling." && return 1

	# write the result of the work.
	cat <<VALUESEOF
BEGIN opensips.dialogs_active $1
SET dialog_active_dialogs = $opensips_dialog_active_dialogs
SET dialog_early_dialogs = $opensips_dialog_early_dialogs
END
BEGIN opensips.users $1
SET usrloc_registered_users = $opensips_usrloc_registered_users
SET usrloc_location_users = $opensips_usrloc_location_users
SET usrloc_location_contacts = $opensips_usrloc_location_contacts
SET usrloc_location_expires = $opensips_usrloc_location_expires
END
BEGIN opensips.registrar $1
SET registrar_accepted_regs = $opensips_registrar_accepted_regs
SET registrar_rejected_regs = $opensips_registrar_rejected_regs
END
BEGIN opensips.transactions $1
SET tm_UAS_transactions = $opensips_tm_UAS_transactions
SET tm_UAC_transactions = $opensips_tm_UAC_transactions
END
BEGIN opensips.core_rcv $1
SET core_rcv_requests = $opensips_core_rcv_requests
SET core_rcv_replies = $opensips_core_rcv_replies
END
BEGIN opensips.core_fwd $1
SET core_fwd_requests = $opensips_core_fwd_requests
SET core_fwd_replies = $opensips_core_fwd_replies
END
BEGIN opensips.core_drop $1
SET core_drop_requests = $opensips_core_drop_requests
SET core_drop_replies = $opensips_core_drop_replies
END
BEGIN opensips.core_err $1
SET core_err_requests = $opensips_core_err_requests
SET core_err_replies = $opensips_core_err_replies
END
BEGIN opensips.core_bad $1
SET core_bad_URIs_rcvd = $opensips_core_bad_URIs_rcvd
SET core_unsupported_methods = $opensips_core_unsupported_methods
SET core_bad_msg_hdr = $opensips_core_bad_msg_hdr
END
BEGIN opensips.tm_replies $1
SET tm_received_replies = $opensips_tm_received_replies
SET tm_relayed_replies = $opensips_tm_relayed_replies
SET tm_local_replies = $opensips_tm_local_replies
END
BEGIN opensips.transactions_status $1
SET tm_2xx_transactions = $opensips_tm_2xx_transactions
SET tm_3xx_transactions = $opensips_tm_3xx_transactions
SET tm_4xx_transactions = $opensips_tm_4xx_transactions
SET tm_5xx_transactions = $opensips_tm_5xx_transactions
SET tm_6xx_transactions = $opensips_tm_6xx_transactions
END
BEGIN opensips.transactions_inuse $1
SET tm_inuse_transactions = $opensips_tm_inuse_transactions
END
BEGIN opensips.sl_replies $1
SET sl_1xx_replies = $opensips_sl_1xx_replies
SET sl_2xx_replies = $opensips_sl_2xx_replies
SET sl_3xx_replies = $opensips_sl_3xx_replies
SET sl_4xx_replies = $opensips_sl_4xx_replies
SET sl_5xx_replies = $opensips_sl_5xx_replies
SET sl_6xx_replies = $opensips_sl_6xx_replies
SET sl_sent_replies = $opensips_sl_sent_replies
SET sl_sent_err_replies = $opensips_sl_sent_err_replies
SET sl_received_ACKs = $opensips_sl_received_ACKs
END
BEGIN opensips.dialogs $1
SET dialog_processed_dialogs = $opensips_dialog_processed_dialogs
SET dialog_expired_dialogs = $opensips_dialog_expired_dialogs
SET dialog_failed_dialogs = $opensips_dialog_failed_dialogs
END
BEGIN opensips.net_waiting $1
SET net_waiting_udp = $opensips_net_waiting_udp
SET net_waiting_tcp = $opensips_net_waiting_tcp
END
BEGIN opensips.uri_checks $1
SET uri_positive_checks = $opensips_uri_positive_checks
SET uri_negative_checks = $opensips_uri_negative_checks
END
BEGIN opensips.traces $1
SET siptrace_traced_requests = $opensips_siptrace_traced_requests
SET siptrace_traced_replies = $opensips_siptrace_traced_replies
END
BEGIN opensips.shmem $1
SET shmem_total_size = $opensips_shmem_total_size
SET shmem_used_size = $opensips_shmem_used_size
SET shmem_real_used_size = $opensips_shmem_real_used_size
SET shmem_max_used_size = $opensips_shmem_max_used_size
SET shmem_free_size = $opensips_shmem_free_size
END
BEGIN opensips.shmem_fragments $1
SET shmem_fragments = $opensips_shmem_fragments
END
VALUESEOF

	return 0
}


text:
/*
 * gn.c
 */

/*-
 * Copyright (c) 2008 Maksim Yevmenkin <m_evmenkin@yahoo.com>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 * $Id: gn.c,v 1.1 2008/03/11 00:02:42 max Exp $
 * $FreeBSD$
 */

#include <sys/queue.h>
#include <bluetooth.h>
#include <sdp.h>
#include <string.h>
#include "profile.h"
#include "provider.h"

static int32_t
gn_profile_create_service_class_id_list(
		uint8_t *buf, uint8_t const * const eob,
		uint8_t const *data, uint32_t datalen)
{
	static uint16_t	service_classes[] = {
		SDP_SERVICE_CLASS_GN
	};

	return (common_profile_create_service_class_id_list(
			buf, eob,
			(uint8_t const *) service_classes,
			sizeof(service_classes)));
}

static int32_t
gn_profile_create_bluetooth_profile_descriptor_list(
		uint8_t *buf, uint8_t const * const eob,
		uint8_t const *data, uint32_t datalen)
{
	static uint16_t	profile_descriptor_list[] = {
		SDP_SERVICE_CLASS_GN,
		0x0100
	};

	return (common_profile_create_bluetooth_profile_descriptor_list(
			buf, eob,
			(uint8_t const *) profile_descriptor_list,
			sizeof(profile_descriptor_list)));
}

static int32_t
gn_profile_create_service_name(
		uint8_t *buf, uint8_t const * const eob,
		uint8_t const *data, uint32_t datalen)
{
	static char	service_name[] = "Group Ad-hoc Network";

	return (common_profile_create_string8(
			buf, eob,
			(uint8_t const *) service_name, strlen(service_name)));
}

static int32_t
gn_profile_create_service_description(
		uint8_t *buf, uint8_t const * const eob,
		uint8_t const *data, uint32_t datalen)
{
	static char	service_descr[] =
				"Personal Group Ad-hoc Network Service";

	return (common_profile_create_string8(
			buf, eob,
			(uint8_t const *) service_descr,
			strlen(service_descr)));
}

static int32_t
gn_profile_create_protocol_descriptor_list(
		uint8_t *buf, uint8_t const * const eob,
		uint8_t const *data, uint32_t datalen)
{
	provider_p		provider = (provider_p) data;
	sdp_gn_profile_p	gn = (sdp_gn_profile_p) provider->data;

	return (bnep_profile_create_protocol_descriptor_list(
			buf, eob, (uint8_t const *) &gn->psm,
			sizeof(gn->psm)));
}

static int32_t
gn_profile_create_security_description(
		uint8_t *buf, uint8_t const * const eob,
		uint8_t const *data, uint32_t datalen)
{
	provider_p		provider = (provider_p) data;
	sdp_gn_profile_p	gn = (sdp_gn_profile_p) provider->data;

	return (bnep_profile_create_security_description(buf, eob,
			(uint8_t const *) &gn->security_description,
			sizeof(gn->security_description)));
}

static int32_t
gn_profile_create_service_availability(
		uint8_t *buf, uint8_t const * const eob,
		uint8_t const *data, uint32_t datalen)
{
	provider_p		provider = (provider_p) data;
	sdp_gn_profile_p	gn = (sdp_gn_profile_p) provider->data;

	return (common_profile_create_service_availability(buf, eob,
			&gn->load_factor, 1));
}

static int32_t
gn_profile_data_valid(uint8_t const *data, uint32_t datalen)
{
	sdp_gn_profile_p	gn = (sdp_gn_profile_p) data;

	return ((gn->psm == 0)? 0 : 1);
}

static attr_t	gn_profile_attrs[] = {
	{ SDP_ATTR_SERVICE_RECORD_HANDLE,
	  common_profile_create_service_record_handle },
	{ SDP_ATTR_SERVICE_CLASS_ID_LIST,
	  gn_profile_create_service_class_id_list },
	{ SDP_ATTR_PROTOCOL_DESCRIPTOR_LIST,
	  gn_profile_create_protocol_descriptor_list },
	{ SDP_ATTR_LANGUAGE_BASE_ATTRIBUTE_ID_LIST,
	  common_profile_create_language_base_attribute_id_list },
	{ SDP_ATTR_SERVICE_AVAILABILITY,
	  gn_profile_create_service_availability },
	{ SDP_ATTR_BLUETOOTH_PROFILE_DESCRIPTOR_LIST,
	  gn_profile_create_bluetooth_profile_descriptor_list },
	{ SDP_ATTR_PRIMARY_LANGUAGE_BASE_ID + SDP_ATTR_SERVICE_NAME_OFFSET,
	  gn_profile_create_service_name },
	{ SDP_ATTR_PRIMARY_LANGUAGE_BASE_ID + SDP_ATTR_SERVICE_DESCRIPTION_OFFSET,
	  gn_profile_create_service_description },
	{ SDP_ATTR_SECURITY_DESCRIPTION,
	  gn_profile_create_security_description },
	{ 0, NULL } /* end entry */
};

profile_t	gn_profile_descriptor = {
	SDP_SERVICE_CLASS_GN,
	sizeof(sdp_gn_profile_t),
	gn_profile_data_valid,
	(attr_t const * const) &gn_profile_attrs
};


text:
<?php namespace ZoneEU\Nimbusec\OAuth;

abstract class SignatureMethod {
  /**
   * Needs to return the name of the Signature Method (ie HMAC-SHA1)
   * @return string
   */
  abstract public function get_name();

  /**
   * Build up the signature
   * NOTE: The output of this function MUST NOT be urlencoded.
   * the encoding is handled in OAuthRequest when the final
   * request is serialized
   * @param OAuthRequest $request
   * @param OAuthConsumer $consumer
   * @param OAuthToken $token
   * @return string
   */
  abstract public function build_signature($request, $consumer, $token);

  /**
   * Verifies that a given signature is correct
   * @param OAuthRequest $request
   * @param OAuthConsumer $consumer
   * @param OAuthToken $token
   * @param string $signature
   * @return bool
   */
  public function check_signature($request, $consumer, $token, $signature) {
    $built = $this->build_signature($request, $consumer, $token);

    // Check for zero length, although unlikely here
    if (strlen($built) == 0 || strlen($signature) == 0) {
      return false;
    }

    if (strlen($built) != strlen($signature)) {
      return false;
    }

    // Avoid a timing leak with a (hopefully) time insensitive compare
    $result = 0;
    for ($i = 0; $i < strlen($signature); $i++) {
      $result |= ord($built{$i}) ^ ord($signature{$i});
    }

    return $result == 0;
  }
}


text:
package org.apache.spark.sql.json

import java.io.IOException

import org.apache.hadoop.fs.Path

import org.apache.spark.sql.{SaveMode, DataFrame, SQLContext}
import org.apache.spark.sql.sources._
import org.apache.spark.sql.types.{DataType, StructType}

private[sql] class DefaultSource
  extends RelationProvider with SchemaRelationProvider with CreatableRelationProvider {

  private def checkPath(parameters: Map[String, String]): String = {
    parameters.getOrElse("path", sys.error("'path' must be specified for json data."))
  }

  /** Returns a new base relation with the parameters. */
  override def createRelation(
      sqlContext: SQLContext,
      parameters: Map[String, String]): BaseRelation = {
    val path = checkPath(parameters)
    val samplingRatio = parameters.get("samplingRatio").map(_.toDouble).getOrElse(1.0)

    JSONRelation(path, samplingRatio, None)(sqlContext)
  }

  /** Returns a new base relation with the given schema and parameters. */
  override def createRelation(
      sqlContext: SQLContext,
      parameters: Map[String, String],
      schema: StructType): BaseRelation = {
    val path = checkPath(parameters)
    val samplingRatio = parameters.get("samplingRatio").map(_.toDouble).getOrElse(1.0)

    JSONRelation(path, samplingRatio, Some(schema))(sqlContext)
  }

  override def createRelation(
      sqlContext: SQLContext,
      mode: SaveMode,
      parameters: Map[String, String],
      data: DataFrame): BaseRelation = {
    val path = checkPath(parameters)
    val filesystemPath = new Path(path)
    val fs = filesystemPath.getFileSystem(sqlContext.sparkContext.hadoopConfiguration)
    val doSave = if (fs.exists(filesystemPath)) {
      mode match {
        case SaveMode.Append =>
          sys.error(s"Append mode is not supported by ${this.getClass.getCanonicalName}")
        case SaveMode.Overwrite =>
          fs.delete(filesystemPath, true)
          true
        case SaveMode.ErrorIfExists =>
          sys.error(s"path $path already exists.")
        case SaveMode.Ignore => false
      }
    } else {
      true
    }
    if (doSave) {
      // Only save data when the save mode is not ignore.
      data.toJSON.saveAsTextFile(path)
    }

    createRelation(sqlContext, parameters, data.schema)
  }
}

private[sql] case class JSONRelation(
    path: String,
    samplingRatio: Double,
    userSpecifiedSchema: Option[StructType])(
    @transient val sqlContext: SQLContext)
  extends BaseRelation
  with TableScan
  with InsertableRelation {

  // TODO: Support partitioned JSON relation.
  private def baseRDD = sqlContext.sparkContext.textFile(path)

  override val schema = userSpecifiedSchema.getOrElse(
    JsonRDD.nullTypeToStringType(
      JsonRDD.inferSchema(
        baseRDD,
        samplingRatio,
        sqlContext.conf.columnNameOfCorruptRecord)))

  override def buildScan() =
    JsonRDD.jsonStringToRow(baseRDD, schema, sqlContext.conf.columnNameOfCorruptRecord)

  override def insert(data: DataFrame, overwrite: Boolean) = {
    val filesystemPath = new Path(path)
    val fs = filesystemPath.getFileSystem(sqlContext.sparkContext.hadoopConfiguration)

    if (overwrite) {
      try {
        fs.delete(filesystemPath, true)
      } catch {
        case e: IOException =>
          throw new IOException(
            s"Unable to clear output directory ${filesystemPath.toString} prior"
              + s" to INSERT OVERWRITE a JSON table:\n${e.toString}")
      }
      // Write the data.
      data.toJSON.saveAsTextFile(path)
      // Right now, we assume that the schema is not changed. We will not update the schema.
      // schema = data.schema
    } else {
      // TODO: Support INSERT INTO
      sys.error("JSON table only support INSERT OVERWRITE for now.")
    }
  }

  override def hashCode(): Int = 41 * (41 + path.hashCode) + schema.hashCode()

  override def equals(other: Any): Boolean = other match {
    case that: JSONRelation =>
      (this.path == that.path) && this.schema.sameType(that.schema)
    case _ => false
  }
}


text:
<!DOCTYPE html>

<input id="input"></input>

        <template>
            <input id="target" value="test">

        </template>


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>com.alain898</groupId>
    <artifactId>distributed-search-cache</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <!--base config-->
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <charset>UTF-8</charset>
        <maven-compiler-plugin.version>3.1</maven-compiler-plugin.version>
        <maven-assembly-plugin.version>2.3</maven-assembly-plugin.version>

        <!--dependencies version-->
        <commons-io.version>2.4</commons-io.version>
        <gson.version>2.3.1</gson.version>
        <junit.version>4.11</junit.version>
        <slf4j.version>1.7.6</slf4j.version>
        <!--the latest jetty version which supports jersey container is 9.2.10.v20150310 -->
        <jetty.version>9.2.10.v20150310</jetty.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.1.7</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.21</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>com.typesafe</groupId>
            <artifactId>config</artifactId>
            <version>1.3.0</version>
        </dependency>

        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-server</artifactId>
            <version>${jetty.version}</version>
        </dependency>
        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-http</artifactId>
            <version>${jetty.version}</version>
        </dependency>
        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-io</artifactId>
            <version>${jetty.version}</version>
        </dependency>

        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-servlet</artifactId>
            <version>2.23.1</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-jetty-servlet</artifactId>
            <version>2.23.1</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-json-jackson</artifactId>
            <version>2.23.1</version>
        </dependency>

        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>19.0</version>
        </dependency>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.3.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.4</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-collections4</artifactId>
            <version>4.1</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>commons-daemon</groupId>
            <artifactId>commons-daemon</artifactId>
            <version>1.0.15</version>
        </dependency>

        <dependency>
            <groupId>org.apache.zookeeper</groupId>
            <artifactId>zookeeper</artifactId>
            <version>3.4.8</version>
        </dependency>
        <dependency>
            <groupId>org.apache.curator</groupId>
            <artifactId>curator-framework</artifactId>
            <version>2.10.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.curator</groupId>
            <artifactId>curator-recipes</artifactId>
            <version>2.10.0</version>
        </dependency>

    </dependencies>

    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>2.3.2</version>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-assembly-plugin</artifactId>
                <version>2.3</version>
                <configuration>
                    <descriptors>
                        <descriptor>src/main/assembly.xml</descriptor>
                    </descriptors>
                </configuration>
                <executions>
                    <execution>
                        <id>assembly</id>
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>


text:
sidebarDepth: 3
sidebar: auto
prev:
  text: Back To 目录
  link: /mybatis/
typora-root-url: ..\.vuepress\public
---

## 环境搭建

IDEA创建 spring项目

1. 引入spring Data JDBC的原因是为了方便去执行sql文件

<img src="/images/mybatis/image-20210823214003003.png" alt="image-20210823214003003" style="zoom:67%;" />

2. 引入Druid依赖

   ```xml
           <dependency>
               <groupId>com.alibaba</groupId>
               <artifactId>druid</artifactId>
               <version>1.2.3</version>
           </dependency>
   ```

### 不太推荐:第一种配置DruidDataSource的Bean

```java
@Configuration
public class DruidConfig {

    @Bean
    @ConfigurationProperties("spring.datasource")  // 会根据DruidDataSource的setXXX方法将配置文件的属性注入到bean中
    public DataSource druidDataSource(){
        return new DruidDataSource();
    }
}
```

```java
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
    username: root
    password: root
    url: jdbc:mysql://localhost:3306/springboot_mybatis?characterEncoding=utf8&useSSL=false&serverTimezone=UTC
    schema: classpath:sql/schema.sql   # 项目启动运行的sql脚本
    initialization-mode: always  # 每次项目启动都会运行

    #druid数据源其他配置

    initialSize: 5  # 数据源初始化时建立的连接数
    minIdle: 5
    maxActive: 21
    maxWait: 5
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: SELECT 1 FROM DUAL
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true
    filters: stat,wall
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

```

### 推荐2:使用JDBC中的数据源

```java
    @Bean
    @ConfigurationProperties("spring.datasource.druid") // 单独指定了druid
    public DataSource druidDataSource(DataSourceProperties dataSourceProperties){
        return dataSourceProperties.initializeDataSourceBuilder().build();
    }
```

```java
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
    username: root
    password: root
    url: jdbc:mysql://localhost:3306/springboot_mybatis?characterEncoding=utf8&useSSL=false&serverTimezone=UTC
    schema: classpath:sql/schema.sql   # 项目启动运行的sql脚本
    initialization-mode: always  # 每次项目启动都会运行

    #druid数据源其他配置
    druid:
      initialSize: 5  # 数据源初始化时建立的连接数
      minIdle: 5
      maxActive: 21
      maxWait: 5
      timeBetweenEvictionRunsMillis: 60000
      minEvictableIdleTimeMillis: 300000
      validationQuery: SELECT 1 FROM DUAL
      testWhileIdle: true
      testOnBorrow: false
      testOnReturn: false
      poolPreparedStatements: true
      filters: stat,wall
      maxPoolPreparedStatementPerConnectionSize: 20
      useGlobalDataSourceStat: true
      connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

```

## 推荐:3种方法场景启动器配置方法❤

::: tip

[Source Code](https://github.com/Q10Viking/learncode/tree/main/mybatis/_09_springboot_druid)

:::

以上两种方法都是基于直接依赖druid的方式,现在改为直接引入Druid的场景启动器

```xml
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.1.21</version>
</dependency>
```

> springboot 2.7.2的配置

```yml
spring:
  sql:
    init:
      schema-locations: classpath:sql/schema.sql
      mode: always
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
    username: root
    password: Root.123456
    url: jdbc:mysql://192.168.187.135:3306/springboot_mybatis?characterEncoding=utf8&useSSL=false&serverTimezone=UTC
    #druid数据源其他配置
    druid:   # 需要添加
      initialSize: 5  # 数据源初始化时建立的连接数
      minIdle: 5
      maxActive: 21
      maxWait: 5
      timeBetweenEvictionRunsMillis: 60000
      minEvictableIdleTimeMillis: 300000
      validationQuery: SELECT 1 FROM DUAL
      testWhileIdle: true
      testOnBorrow: false
      testOnReturn: false
      poolPreparedStatements: true
      filters: stat,wall
      maxPoolPreparedStatementPerConnectionSize: 20
      useGlobalDataSourceStat: true
      connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
      stat-view-servlet:
        enabled: true
        login-password: 123456
        login-username: admin
      web-stat-filter:
        enabled: true
```

### 自动配置的原理的分析

https://www.processon.com/view/link/6123f06f7d9c0856876e123c

![img](/images/mybatis/6123d56e0e3e743b327d3700.png)

分析了源码之后我们就知道怎么配置了,需要添加druid的配置

```yml
spring:
  sql:
    init:
      schema-locations: classpath:sql/schema.sql
      mode: always
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
    username: root
    password: Root.123456
    url: jdbc:mysql://192.168.187.135:3306/springboot_mybatis?characterEncoding=utf8&useSSL=false&serverTimezone=UTC
    #druid数据源其他配置
    druid:   # 需要添加
      initialSize: 5  # 数据源初始化时建立的连接数
      minIdle: 5
      maxActive: 21
      maxWait: 5
      timeBetweenEvictionRunsMillis: 60000
      minEvictableIdleTimeMillis: 300000
      validationQuery: SELECT 1 FROM DUAL
      testWhileIdle: true
      testOnBorrow: false
      testOnReturn: false
      poolPreparedStatements: true
      filters: stat,wall
      maxPoolPreparedStatementPerConnectionSize: 20
      useGlobalDataSourceStat: true
      connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
      stat-view-servlet:
        enabled: true
        login-password: 123456
        login-username: admin
      web-stat-filter:
        enabled: true
```

### 访问druid控制台

```
http://localhost:8080/druid/
用户名密码就是配置的信息
```

## 配置详解

![img](/images/mybatis/image-4.png)


text:
using Glav.CognitiveServices.FluentApi.Core;
using System;
using System.Collections.Generic;
using System.Text;
using Glav.CognitiveServices.FluentApi.Core.Communication;
using Glav.CognitiveServices.FluentApi.Core.Configuration;
using Glav.CognitiveServices.FluentApi.Core.Contracts;

namespace Glav.CognitiveServices.FluentApi.Luis.Configuration
{
    public class LuisAnalysisSettings : CoreAnalysisSettings
    {
        public LuisAnalysisSettings(ConfigurationSettings settings, ICommunicationEngine communicationEngine) : base(settings, communicationEngine)
        {
        }

        public LuisAnalysisSettings(IAnalysisSettings analysisSettings) : base(analysisSettings)
        {

        }
    }
}


text:
namespace base {
class FilePath;
}

namespace gfx {
class Image;
}

class SkBitmap;

namespace profiles {

// Avatar access.
extern const char kGAIAPictureFileName[];
extern const char kHighResAvatarFolderName[];

// Avatar formatting.
extern const int kAvatarIconWidth;
extern const int kAvatarIconHeight;
extern const SkColor kAvatarTutorialBackgroundColor;
extern const SkColor kAvatarTutorialContentTextColor;
extern const SkColor kAvatarBubbleAccountsBackgroundColor;
extern const SkColor kAvatarBubbleGaiaBackgroundColor;
extern const SkColor kUserManagerBackgroundColor;

// Returns a version of |image| of a specific size. Note that no checks are
// done on the width/height so make sure they're reasonable values; in the
// range of 16-256 is probably best.
gfx::Image GetSizedAvatarIcon(const gfx::Image& image,
                              bool is_rectangle,
                              int width, int height);

// Returns a version of |image| suitable for use in menus.
gfx::Image GetAvatarIconForMenu(const gfx::Image& image,
                                bool is_rectangle);

// Returns a version of |image| suitable for use in WebUI.
gfx::Image GetAvatarIconForWebUI(const gfx::Image& image,
                                 bool is_rectangle);

// Returns a version of |image| suitable for use in title bars. The returned
// image is scaled to fit |dst_width| and |dst_height|.
gfx::Image GetAvatarIconForTitleBar(const gfx::Image& image,
                                    bool is_rectangle,
                                    int dst_width,
                                    int dst_height);

// Returns a bitmap with a couple of columns shaved off so it is more square,
// so that when resized to a square aspect ratio it looks pretty.
SkBitmap GetAvatarIconAsSquare(const SkBitmap& source_bitmap, int scale_factor);

// Gets the number of default avatar icons that exist.
size_t GetDefaultAvatarIconCount();

// Gets the number of generic avatar icons that exist.
size_t GetGenericAvatarIconCount();

// Gets the index for the (grey silhouette) avatar used as a placeholder.
size_t GetPlaceholderAvatarIndex();

// Gets the resource ID of the placeholder avatar icon.
int GetPlaceholderAvatarIconResourceID();

// Gets the resource ID of the default avatar icon at |index|.
int GetDefaultAvatarIconResourceIDAtIndex(size_t index);

// Gets the resource filename of the default avatar icon at |index|.
const char* GetDefaultAvatarIconFileNameAtIndex(size_t index);

// Gets the full path of the high res avatar icon at |index|.
base::FilePath GetPathOfHighResAvatarAtIndex(size_t index);

// Returns a URL for the default avatar icon with specified index.
std::string GetDefaultAvatarIconUrl(size_t index);

// Checks if |index| is a valid avatar icon index
bool IsDefaultAvatarIconIndex(size_t index);

// Checks if the given URL points to one of the default avatar icons. If it
// is, returns true and its index through |icon_index|. If not, returns false.
bool IsDefaultAvatarIconUrl(const std::string& icon_url, size_t *icon_index);

}  // namespace profiles

#endif  // CHROME_BROWSER_PROFILES_PROFILE_AVATAR_ICON_UTIL_H_


text: export { TranslationDiff } from './components/TranslationDiff';


text:
<?php

namespace App\Infrastructure\Domain\User;

use App\Domain\EmailAddress;
use App\Domain\User\UserId;
use App\Domain\User\User;
use App\Domain\User\UserPassword;
use App\Domain\User\UserRepository;
use App\Infrastructure\Database\DatabaseDriver;

class DbUserRepository implements UserRepository
{
    /**
    * @var DatabaseDriver
    */
    private $db;

    /**
    * Creates a new User repository Constructor
    *
    * @param DatabaseDriver $db
    */
    function __construct(DatabaseDriver $db)
    {
        $this->db = $db->getDatabase();
    }

    /**
    * Returns the array representation of a User
    * object suitable for use with the database.
    *
    * @param  User $book
    * @return array
    */
    private static function serialize(User $user)
    {
        return array(
            'id' => $user->id()->get(),
            'user_email' => $user->emailAddress()->get(),
            'user_password' => $user->password()->get(),
            'user_firstname' => $user->firstName(),
            'user_lastname' => $user->lastName(),
            'last_login' => $user->lastLogIn()
        );
    }

    /**
    * Returns a User object populated with data from
    * a serialized array.
    *
    * @param  array $arr
    * @return User
    */
    private function deserialize(array $arr)
    {
        return User::restore(
            UserId::restore($arr['id']),
            EmailAddress::create($arr['user_email']),
            UserPassword::restore($arr['user_password']),
            $arr['user_firstname'],
            $arr['user_lastname'],
            $arr['last_login']
        );
    }

    public function findById(UserId $id)
    {
        $data = $this->db->queryFirst('
            SELECT  *
            FROM    users
            WHERE   id = :id AND
            deleted IS NULL
            ', array(':id' => $id->get())
        );

        if (!$data) {
            return null;
        }

        return self::deserialize($data);
    }

    public function findByEmail(EmailAddress $email)
    {
        $data = $this->db->queryFirst('
            SELECT  *
            FROM    users
            WHERE   user_email = :email AND
            deleted IS NULL
            ', array(':email' => $email->get())
        );

        if (!$data) {
            return null;
        }

        return self::deserialize($data);
    }

    public function findAll()
    {
        $data = $this->db->queryAll('
        SELECT  *
        FROM    users
        WHERE   deleted IS NULL
        ');
        $users = array();
        foreach ($data as $arr) {
            $users[] = self::deserialize($arr);
        }

        return $users;
    }

    public function add(User $user)
    {
        $original = $this->findById($user->id());
        $arr = self::serialize($user);

        if ($original) {
            $arr['modified_user_id'] = '0000';
            $arr['date_modified'] = gmdate('Y-m-d H:i:s');
            $this->db->update(
                'users',
                array(
                    'id' => $user->id()->get()
                ),
                $arr
            );
        } else {

            $arr['created_by'] = '0000';
            $arr['date_entered'] = gmdate('Y-m-d H:i:s');
            $this->db->insert('users', $arr);
        }
    }

    public function remove(User $user)
    {
        $this->db->update(
            'users',
            array(
                'id' => $user->id()->get()
            ),
            array(
            'modified_user_id' => '0000',
            'deleted' => date('Y-m-d H:i:s')
            )
        );
    }

}


text:
package example.consumer

object ConsumerStreamExample {
  def main(args: Array[String]): Unit = {
    val topicNames = if(args.length == 0) {
      "testTopic"
    } else {
      args.head
    }
    println("topicNames is " + topicNames)
    val consumer = SingleTopicConsumer(topicNames)

    consumer.read().foreach(println)
  }
}


text:
namespace base {
class SingleThreadTaskRunner;
class Value;
}  // namespace base

namespace cc {

class LayerTree;
class Layer;
class PictureLayer;
class MicroBenchmarkImpl;
class CC_EXPORT MicroBenchmark {
 public:
  typedef base::Callback<void(std::unique_ptr<base::Value>)> DoneCallback;

  explicit MicroBenchmark(const DoneCallback& callback);
  virtual ~MicroBenchmark();

  bool IsDone() const;
  virtual void DidUpdateLayers(LayerTree* layer_tree);
  int id() const { return id_; }
  void set_id(int id) { id_ = id; }

  virtual void RunOnLayer(Layer* layer);
  virtual void RunOnLayer(PictureLayer* layer);

  virtual bool ProcessMessage(std::unique_ptr<base::Value> value);

  bool ProcessedForBenchmarkImpl() const;
  std::unique_ptr<MicroBenchmarkImpl> GetBenchmarkImpl(
      scoped_refptr<base::SingleThreadTaskRunner> origin_task_runner);

 protected:
  void NotifyDone(std::unique_ptr<base::Value> result);

  virtual std::unique_ptr<MicroBenchmarkImpl> CreateBenchmarkImpl(
      scoped_refptr<base::SingleThreadTaskRunner> origin_task_runner);

 private:
  DoneCallback callback_;
  bool is_done_;
  bool processed_for_benchmark_impl_;
  int id_;
};

}  // namespace cc

#endif  // CC_DEBUG_MICRO_BENCHMARK_H_


text:
angular.module('MRT')
        .factory('geoModelService', ['$http', 'env', 'localStorageService', function($http, env, localStorageService) {

        var urlBase = env.apiUrl;
        var dataFactory = {};
        var cacheKey = 'model_creation';
        var modelTypes = [
          {
            id: 'ge-mckinsey',
            name: 'GE MCKinsey Matrix',
            image: 'img/matrix.png',
            description: "The GE matrix / McKinsey matrix (MKM) is a model to perform a business portfolio analysis on the Strategic Business Units of a corporation. A business portfolio is the collection of Strategic Business Units that make up a corporation.",
            dimensions: [
              {id: 'c-specifics', name: 'Country Specifics', selection: 'single', weighted: true},
              {id: 'm-attractiveness', name: 'Market Attractiveness', selection: 'single', weighted: true}
            ]
          },
          {
            id: '3-dimentional-bubble',
            name: '3 Dimentional Bubble',
            image: 'img/bubble.png',
            description: "A motion chart is a dynamic bubble chart which allows efficient and interactive exploration and visualization of longitudinal multivariate Data.",
            dimensions: [
              {id: 'x-axis', name: 'X-Axis', selection: 'range'},
              {id: 'y-axis', name: 'Y-Axis', selection: 'range'},
              {id: 'bubble-size', name: 'Bubble Size', selection: 'range'}
            ]
          },
          {
            id: 'map',
            name: 'map',
            image: 'img/map.png',
            description: "Map",
            dimensions: [
              {id: 'indicator', name: 'Indicator(s)', selection: 'range'}
            ]
          },
          {
            id: 'weighted-table',
            name: 'Weighted Table',
            image: 'img/charts/graph-5.png',
            description: "Weighted table description",
            dimensions: [
              {id: 'headers', name: 'Headers', selection: 'range', weighted: true},
            ]
          },
          {
            id: 'stack-chart',
            name: 'Stack Chart',
            image: 'img/charts/graph-24.png',
            description: "Stack chart description",
            dimensions: [
              {id: 'x-axis', name: 'X-Axis', selection: 'range'},
            ]
          },
          {
            id: 'line-chart',
            name: 'Line Chart',
            image: 'img/charts/graph-33.png',
            description: "Line chart description",
            dimensions: [
              {id: 'x-axis', name: 'X-Axis', selection: 'range'},
            ]
          },
          {
            id: 'bar-chart',
            name: 'Bar Chart',
            image: 'img/charts/graph-1.png',
            description: "Bar chart description",
            dimensions: [
              {id: 'x-axis', name: 'X-Axis', selection: 'range'},
            ]
          },
          {
            id: 'donut-chart',
            name: 'Donut Chart',
            image: 'img/charts/graph-2.png',
            description: "Donut chart description",
            dimensions: [
              {id: 'donut', name: 'Donut', selection: 'range', weighted: true},
            ]
          }
        ];

        var model = {
          model: '',
          name: '',
          description: '',
          from: '',
          to: '',
          geographies: [],
          indicators: [],
          data: []
        };

        // localStorageService.remove(cacheKey);

        dataFactory.list = function(params) {
            return $http.get(urlBase + '/geomodel/', {
                params: params
            });
        };

        dataFactory.get = function(params) {
            return $http.get(urlBase + '/geomodel/' + params.id);
        };

        function getPostModel(model) {
          var m = {};
          m.name = model.name;
          if(typeof model.id !== 'undefined' && model.id) {
            m.id = model.id;
          }
          m.algorithm_code = model.modelType.name;
          m.description = model.description;
          m.content = JSON.stringify(model);
          return m;
        }

        dataFactory.localSave = function(model) {
          localStorageService.set(cacheKey, model);
        }

        dataFactory.getLocalModel = function() {
          return localStorageService.get(cacheKey);
        }

        dataFactory.getValues = function(params) {
            return $http.get(urlBase + '/geomodel/values', {
                params: params
            });
        };

        dataFactory.new = function(params) {
            return $http.get(urlBase + '/geomodel/new', {
                params: params
            });
        };

        dataFactory.replace = function(data) {
            var m = getPostModel(data);
            return $http.put(urlBase + '/geomodel/replace', m);
        };

        dataFactory.getIndicators = function(params) {
            return $http.get(urlBase + '/geomodel/indicators', {
                params: params
            });
        };

        dataFactory.addCountry = function(country) {

        }

        dataFactory.addIndicatior = function(indicator) {

        }

        dataFactory.getModelTypes = function() {
          return modelTypes;
        }

        dataFactory.start = function() {
          dataFactory.localSave(model);
        }

        if(!localStorageService.get(cacheKey)) {
          dataFactory.localSave(model);
        }

        return dataFactory;
    }]);


text:
ALTER TABLE casesvc."case"
    ALTER COLUMN caseref SET DEFAULT nextval('casesvc.caserefseq'::regclass);