text:
%rebase('layout.tpl')

        <form class="form-horizontal" role="form"  enctype="multipart/form-data"  method="post">
            <legend>
            To get started, you'll need to upload the following three account history files from Virtex
            </legend>
            % for name, uploaded in uploadSet.files().items():

                        {{name}}

                        % if uploaded:

                        % else:
                        <input type="file" class="form-control" name="{{name}}">
                        %end

            %end
            % if not all(uploadSet.files().values()):

                    <button class="btn btn-lg btn-primary btn-block " type="submit" value="upload"> Upload Files</button>

            %end
        </form>
        % if any (uploadSet.files().values()):
        <form class="form-inline" method="post" action="delete_uploads">
            <button class="btn btn-lg btn-danger btn-block " type="submit" value="remove"> Delete Uploaded Files</button>
        </form>
        % end

Bookmark this link to return to this session:
                /upload/{{Helpers.upload_uuid()}}

% if all(uploadSet.files().values()):

                Now you've uploaded all your files, we can present you with your report.

CAD Deposits

CAD Withdrawals

BTC Deposits

BTC Withdrawals

Fees

BTC holdings

CAD holdings

Calculated

                    {{!uploadSet.depositsCAD().to_html(index=False)}}

                    {{!uploadSet.withdrawalsCAD().to_html(index=False)}}

                    {{!uploadSet.depositsBTC().to_html(index=False)}}

                    {{!uploadSet.withdrawalsBTC().to_html(index=False)}}

                    {{!uploadSet.fees().to_html(index=False)}}

                    {{!uploadSet.chart('Total(BTC)')}}

                    {{!uploadSet.chart('Total(CAD)')}}

This report will be available shortly

%end

A Bitcoins.ca project

 Twitter

 Surveymedia


text:
@implementation GPUImageDirectionalNonMaximumSuppressionFilter

NSString *const kGPUImageDirectionalNonmaximumSuppressionFragmentShaderString = SHADER_STRING
(
 precision mediump float;

 varying highp vec2 textureCoordinate;

 uniform sampler2D inputImageTexture;
 uniform highp float texelWidth;
 uniform highp float texelHeight;
 uniform mediump float upperThreshold;
 uniform mediump float lowerThreshold;

 void main()
 {
     vec3 currentGradientAndDirection = texture2D(inputImageTexture, textureCoordinate).rgb;
     vec2 gradientDirection = ((currentGradientAndDirection.gb * 2.0) - 1.0) * vec2(texelWidth, texelHeight);

     float firstSampledGradientMagnitude = texture2D(inputImageTexture, textureCoordinate + gradientDirection).r;
     float secondSampledGradientMagnitude = texture2D(inputImageTexture, textureCoordinate - gradientDirection).r;

     float multiplier = step(firstSampledGradientMagnitude, currentGradientAndDirection.r);
     multiplier = multiplier * step(secondSampledGradientMagnitude, currentGradientAndDirection.r);

     float thresholdCompliance = smoothstep(lowerThreshold, upperThreshold, currentGradientAndDirection.r);
     multiplier = multiplier * thresholdCompliance;

     gl_FragColor = vec4(multiplier, multiplier, multiplier, 1.0);
 }
);

@synthesize texelWidth = _texelWidth;
@synthesize texelHeight = _texelHeight;
@synthesize upperThreshold = _upperThreshold;
@synthesize lowerThreshold = _lowerThreshold;

#pragma mark -
#pragma mark Initialization and teardown

- (id)init;
{
    if (!(self = [super initWithFragmentShaderFromString:kGPUImageDirectionalNonmaximumSuppressionFragmentShaderString]))
    {
        return nil;
    }

    texelWidthUniform = [filterProgram uniformIndex:@"texelWidth"];
    texelHeightUniform = [filterProgram uniformIndex:@"texelHeight"];
    upperThresholdUniform = [filterProgram uniformIndex:@"upperThreshold"];
    lowerThresholdUniform = [filterProgram uniformIndex:@"lowerThreshold"];

    self.upperThreshold = 0.5;
    self.lowerThreshold = 0.1;

    return self;
}

- (void)setupFilterForSize:(CGSize)filterFrameSize;
{
    if (!hasOverriddenImageSizeFactor)
    {
        _texelWidth = 1.0 / filterFrameSize.width;
        _texelHeight = 1.0 / filterFrameSize.height;

        [GPUImageOpenGLESContext useImageProcessingContext];
        [filterProgram use];
        glUniform1f(texelWidthUniform, _texelWidth);
        glUniform1f(texelHeightUniform, _texelHeight);
    }
}

#pragma mark -
#pragma mark Accessors

- (void)setTexelWidth:(CGFloat)newValue;
{
    hasOverriddenImageSizeFactor = YES;
    _texelWidth = newValue;

    [GPUImageOpenGLESContext useImageProcessingContext];
    [filterProgram use];
    glUniform1f(texelWidthUniform, _texelWidth);
}

- (void)setTexelHeight:(CGFloat)newValue;
{
    hasOverriddenImageSizeFactor = YES;
    _texelHeight = newValue;

    [GPUImageOpenGLESContext useImageProcessingContext];
    [filterProgram use];
    glUniform1f(texelHeightUniform, _texelHeight);
}

- (void)setLowerThreshold:(CGFloat)newValue;
{
    _lowerThreshold = newValue;

    [GPUImageOpenGLESContext useImageProcessingContext];
    [filterProgram use];
    glUniform1f(lowerThresholdUniform, _lowerThreshold);
}

- (void)setUpperThreshold:(CGFloat)newValue;
{
    _upperThreshold = newValue;

    [GPUImageOpenGLESContext useImageProcessingContext];
    [filterProgram use];
    glUniform1f(upperThresholdUniform, _upperThreshold);
}

@end

redpajama_set_name: RedPajamaGithub


text:
package cmwell.tlog

import scala.collection.mutable
import java.lang.String
import java.util.concurrent.atomic.AtomicLong
import scala._
import cmwell.perf.PerfCounter
import com.typesafe.scalalogging.LazyLogging
import scala.Predef._

//import java.util.concurrent._
import scala.concurrent._
import concurrent.duration._

import scala.Some
import java.util.concurrent.{Executors, LinkedBlockingQueue, TimeUnit}
import java.io._
import scala.Some
import scala.collection.mutable.ArrayBuffer
import scala.Some
import java.nio.channels.FileChannel
import java.nio.ByteBuffer
import java.util.zip.{Adler32, CRC32, Checksum}
import net.jpountz.lz4.{LZ4FastDecompressor, LZ4Compressor, LZ4Factory}
import scala.Some
import ExecutionContext.Implicits.global
import scala.util._
import cmwell.common.metrics.WithMetrics
import com.google.common.cache.{CacheBuilder, Cache}
import scala.language.postfixOps

/**
 * Created with IntelliJ IDEA.
 * User: markz
 * Date: 10/30/12
 * Time: 11:11 AM
 * TLog implementation
 */

object TLog {
  def apply(tlogName : String , partitionName : String , cmwell_home_path : String = System.getProperty("cmwell.home"),readOnly : Boolean = false,bucketSize : Long = 1L * 1024L * 1024L * 1024L ) = new TLogFileImpl(tlogName, partitionName.replace('-', '_'), cmwell_home_path, readOnly, bucketSize)
}

trait TLog {
  def name() : String
  def partition() : String
  def init()
  def write(payload : Array[Byte]) : scala.concurrent.Future[Long]
  def write_sync(payload : Array[Byte])
  def read(ts: Long , count : Int ) : (Long , Vector[(Long,Array[Byte])] )
  def read(ts: Long , size : Long ) : (Long , Vector[(Long,Array[Byte])] )
  def readOne(ts:Long):Option[(Long, Array[Byte])]
  def getPartitions : Vector[String]
  def size : Long
  def shutdown()
}

object Header {
  def get = 6074352486920120832L
//  val headerString = "TLogObj\u0000"
//  val arr = java.nio.ByteBuffer.allocate( 8 )
//  arr.put(headerString.getBytes())
//  arr.flip()
//  val headerVal = arr.getLong()
//  def get : Long = headerVal
//  val headerString = "TLogObj".getBytes("utf8")
}

object DataChunk {
  def create(payload : Array[Byte],original_size : Int) = new DataChunk(Header.get , payload, original_size)
}

object Compression {
  val factory : LZ4Factory = LZ4Factory.fastestInstance();

  def compress(payload : Array[Byte]) : Array[Byte] = {
    val compressor : LZ4Compressor = factory.fastCompressor()
    val payload_compress = compressor.compress(payload)
    payload_compress
  }

  def uncompress(payload : Array[Byte] , original_size : Int ) : Array[Byte] = {
    val decompressor : LZ4FastDecompressor = factory.fastDecompressor()
    val payload_uncompress = decompressor.decompress(payload , original_size)
    payload_uncompress
  }
}

/**
 * Header
 *     8       4               4     size         8
 * |header | original size | size | payload | checksum |
 */

/**
 *
 * @param payload
 */
class DataChunk(header : Long , payload : Array[Byte], original_size : Int) {
  val checksum = new Adler32()
  val size = payload.size
  checksum.update(payload, 0 , size)

  def writeData(os:FileOutputStream) = {
    val arr = java.nio.ByteBuffer.allocate( 8 + 8 + 4 + 4 + payload.size + 8)
    // write header
    arr.putLong(header)
    arr.putLong(System.currentTimeMillis())
    arr.putInt(original_size)
    arr.putInt(size)
    arr.put(payload)
    arr.putLong(checksum.getValue)
    arr.flip()
    os.getChannel.write(arr)
  }

  /**
   *
   * @return
   */
  def getHeader : Array[Byte] = {
    val arr = java.nio.ByteBuffer.allocate( 8 + 8 + 4 + 4 )
    arr.putLong(header)
    arr.putLong(System.currentTimeMillis())
    arr.putInt(original_size)
    arr.putInt(size)
    arr.flip()
    arr.array()
  }

  /**
   *
   * @return
   */
  def getPayload : Array[Byte] = payload

  /**
   *
   * @return
   */
  def getCheckSum : Array[Byte] = {
    val arr = java.nio.ByteBuffer.allocate( 8 )
    arr.putLong(checksum.getValue)
    arr.flip()
    arr.array()
  }
}

class DataWriter(dataPath : String , fileName : String , bucketSize : Long) extends LazyLogging {

  def calcFileNumber : Long = {
    val listOfFiles = new File(dataPath).listFiles()
    //println(s"calcFileNumber ${fileName} ${dataPath} ${listOfFiles.mkString("[",",","]")}")

    val l = listOfFiles.filter(_.getName.startsWith(fileName) ).sorted.toList
    if ( l.isEmpty )
      0L
    else {
      val n = l.last.getName.split('_').last
      val nn = n.split('.')
      nn.head.toLong
    }
  }

  // scan directory
  var fileNumber : Long = calcFileNumber

  def buildFileName(dataPath : String , fileName : String , fileNumber : Long) : String = {
    val n= "%09d".format(fileNumber)
    s"${dataPath}${File.separator}${fileName}_${n}.dat"
  }

  var fileNameWithPath = buildFileName( dataPath, fileName , fileNumber )

  var fos : FileOutputStream = new FileOutputStream(fileNameWithPath , true);

  def position : Long = {
    val numOfFiles = calcFileNumber
    val fileNameWithPath = buildFileName( dataPath, fileName , numOfFiles )
    val tmpFos : FileOutputStream = new FileOutputStream(fileNameWithPath , true);
    val size = tmpFos.getChannel.position()
    tmpFos.close()
    ( numOfFiles * bucketSize ) + size
  }

  // this is running on executor actor like
  // THIS IS NOT THREAD SAFE!!!
  def write(payload : Array[Byte] , original_size : Int) : Option[Long] = {
    var offset = fos.getChannel.position()
    //println(s"current offset ${offset} bucketSize ${bucketSize}")
    // check do we need to switch a file
    if ( offset >= bucketSize ) {
      logger info(s"switch file in tlog from ${fileNameWithPath} in offset ${offset}. ")
      try {
        fos.flush()
        fos.close()
      }
      catch {
        case ioe:IOException =>
          logger.error("IOException : ", ioe);
      }
      // first switch a file and make some padding to the new file
      val paddingSize : Long = offset - bucketSize
      fileNumber += 1
      fileNameWithPath = buildFileName( dataPath, fileName , fileNumber )
//      println(s"we need to switch to file ${fileNameWithPath} and make some padding ${paddingSize}.")
      logger info (s"to file ${fileNameWithPath} padding ${paddingSize}. ")
      // switch file
      fos = new FileOutputStream(fileNameWithPath , true);
      // do some padding to the file
      if ( paddingSize != 0 ) {
//        println("try to allocate")
        val arr = java.nio.ByteBuffer.allocate(paddingSize.toInt)
        val v: Byte = 77
//        println("build array allocate")
        (0 to (paddingSize - 1).toInt)
        arr.put(v)
        arr.flip()

        try {
//          println("before write")
          fos.write(arr.array())
//          println("after write")
        }
        catch {
          case ex: FileNotFoundException =>
            logger.error("FileNotFoundException : ", ex);
          case ioe: IOException =>
            logger.error("IOException : ", ioe);
        }
      }
      offset = paddingSize
    }
    // get size
    /*
    val size = payload.size
    checksum.update(payload, 0 , size)
    val checksumValue = checksum.getValue
    checksum.reset()
    val header : Long = 1;
    // pack to byte array
    val arr = java.nio.ByteBuffer.allocate( 8 + 4 + size + 8)
    arr.putLong(header)
    arr.putInt(size)
    arr.put(payload)
    arr.putLong(checksumValue)
    arr.flip()
    */
    try {
      //fos.write(arr.array())
      //arr.clear()
      val d = DataChunk.create(payload,original_size)
      d.writeData(fos)
//      fos.write(d.getHeader)
//      fos.write(d.getPayload)
//      fos.write(d.getCheckSum)
    }
    catch {
      case ex: FileNotFoundException =>
        logger.error("FileNotFoundException : ", ex);
      case ioe: IOException =>
        logger.error("IOException : ", ioe);
    }
    Some(offset)
  }
}

class DataReader(dataPath : String , fileName : String ,bucketSize : Long) extends LazyLogging {

  val fileCacheMap : Cache[String, RandomAccessFile] = CacheBuilder.newBuilder().maximumSize(5).build[String , RandomAccessFile]()

  def buildFileName(dataPath : String , fileName : String , fileNumber : Long) : String = {
    val n = "%09d".format(fileNumber)
    s"${dataPath}${File.separator}${fileName}_${n}.dat"
  }

  def getFileHandel(dataPath : String , fileName : String , fileNumber : Long ) : Option[RandomAccessFile] = {
    val fileNameWithPath = buildFileName( dataPath, fileName , fileNumber )
    val fh = fileCacheMap.getIfPresent(fileNameWithPath)
    if ( fh == null ) {
      // first check if file
      val f = new File(fileNameWithPath)
      if ( f.exists() ) {
        val aFile = new RandomAccessFile(fileNameWithPath, "r");
        fileCacheMap.put(fileNameWithPath, aFile)
        Some(aFile)
      }
      else {
        None
      }
    } else {
      Some(fh)
    }
  }

  val factory : LZ4Factory = LZ4Factory.fastestInstance();

  private def readHeader(offset : Long , inChannel : FileChannel) : Option[Long] = {
    val buf : ByteBuffer = ByteBuffer.allocate(8);
    inChannel.read(buf,offset)
    if ( buf.position != 8 ) {
      //logger.error("header size(%s) is not complete. ".format(buf.position))
      None
    } else {
      buf.flip()
      val header = buf.getLong
      Some(header)
    }
  }

  private def readTimeStamp(offset : Long , inChannel : FileChannel) : Option[Long] = {
    val buf : ByteBuffer = ByteBuffer.allocate(8);
    inChannel.read(buf,offset)
    if ( buf.position != 8 ) {
      //logger.error("timestamp size(%s) is not complete. ".format(buf.position))
      None
    } else {
      buf.flip()
      val timestamp = buf.getLong
      Some(timestamp)
    }
  }

  private def readSize(offset : Long , inChannel : FileChannel) : Option[Int] = {
    val buf = ByteBuffer.allocate(4);
    inChannel.read(buf,offset)
    if ( buf.position != 4 ) {
      //logger.error("size size(%s) is not complete. ".format(buf.position))
      None
    } else {
      buf.flip()
      val size = buf.getInt
      Some(size)
    }
  }

  private def readPayload(offset : Long , size : Int, original_size : Int ,inChannel : FileChannel)  : Option[Array[Byte]] = {
    val buf = ByteBuffer.allocate(size);
    inChannel.read(buf, offset)
    if ( buf.position != size ) {
      //logger.error("payload size(%s) is not complete. ".format(buf.position))
      None
    } else {
      buf.flip()
      //val arr = decompressor.decompress(buf.array() , original_size)
      //println(new String(arr))
      val arr = buf.array()
      Some(arr)
    }
  }

  private def readCheckSum(offset : Long , inChannel : FileChannel) : Option[Long] = {
    val buf = ByteBuffer.allocate(8);
    inChannel.read(buf,offset )
    if ( buf.position != 8 ) {
      //logger.error("checksum size(%s) is not complete. ".format(buf.position))
      None
    } else {
      buf.flip()
      val checksumValue = buf.getLong
      Some(checksumValue)
    }
  }

  //var aFile : RandomAccessFile = new RandomAccessFile(fileNameWithPath, "r")

  // not thread safe

  def read(offset: Long , weight : Long ) : (Long , Vector[(Long,Array[Byte])] ) = {
    var totalWeight = 0L
    // calc the correct buckt to read from

    // create new buffer in size of requested chunk
    val buf : mutable.Buffer[(Long , Array[Byte])] = new mutable.ArrayBuffer[(Long, Array[Byte])](10)
    var stop : Boolean = false
    var newOffset = offset

    while (!stop) {
      val fileNumber = newOffset / bucketSize
      val aFile = getFileHandel(dataPath,fileName,fileNumber)
      aFile match {
        case Some(tlogFileHandel) =>
          val internalFileOffset = newOffset - (fileNumber * bucketSize)
          val item = read_one(internalFileOffset , tlogFileHandel,fileNumber)
          item match {
            case None =>
              // if there is no data stop the while
              stop = true
            case Some(i) =>
              // append data to the item
              val el = ( i._1 + (fileNumber * bucketSize) , i._2 )
              buf.append(i)
              newOffset = el._1
              totalWeight += el._2.size
              if ( totalWeight >= weight)
                stop = true
          }
        case None =>
          stop = true
      }

      //if ( buf.size == size ) stop = true
    }
    if ( buf.isEmpty ) {
      (offset , Vector.empty)
    }
    else {
      val v = Vector.empty[(Long, Array[Byte])] ++ buf
      val l = v.last._1
      ( l , v)
    }

  }

  // not thread safe
  def read(offset: Long,count: Int): (Long, Vector[(Long, Array[Byte])]) = {
//    println(s"read ${ts} ${count} ${fileName} ")
    // create new buffer in size of requested chunk
    val buf : mutable.Buffer[(Long , Array[Byte])] = new mutable.ArrayBuffer[(Long, Array[Byte])](count.toInt)
    var stop : Boolean = false
    var newOffset = offset
    while (!stop) {
      // first try to read one
      val fileNumber = newOffset / bucketSize
      //println(s"${dataPath},${fileName},${fileNumber}")
      val aFile = getFileHandel(dataPath,fileName,fileNumber)
      aFile match {
        case Some(tlogFileHandel) =>
          val internalFileOffset = newOffset - (fileNumber * bucketSize)
          //println(s"${internalFileOffset} ${newTs} ${fileNumber}")
//          if (internalFileOffset == 0 )
//            println(s"aFile ${fileName} newTs ${newTs} fileNumber ${fileNumber} internalFileOffset ${internalFileOffset} count ${count} buf size ${buf.size}" )
          val item = read_one(internalFileOffset, tlogFileHandel,fileNumber)
          item match {
            case None =>
              // if there is no data stop the while
              stop = true
            case Some(i) =>
              // append data to the item
              val el = ( i._1 + (fileNumber * bucketSize) , i._2 )
              buf.append(el)
              //println(s" ${el._1} + ${fileNumber} * ${bucketSize}")
              newOffset = el._1
          }
        case None =>
          stop = true
      }
      if ( buf.size == count.toInt ) stop = true
    }
    if ( buf.isEmpty ) {
      (offset , Vector.empty)
    }
    else {
      val v = Vector.empty[(Long, Array[Byte])] ++ buf
      val l = v.last._1
      ( l , v)
    }

  }

  def readOne(ts:Long):Option[(Long, Array[Byte])] = {
    val d = read(ts,1)
    if ( d._2.isEmpty )
      None
    else
      Some(d._2(0))
  }

  private def read_one(ts : Long , aFile : RandomAccessFile, fileNumber : Long ): Option[(Long, Array[Byte])] = {
    def calcRealOffset(offset : Long) = offset + 1024L * 1024L * 1024L * fileNumber
    try {
      val inChannel : FileChannel = aFile.getChannel();
      if ( ts > inChannel.size() ) {
        None
      } else {
        val checksum : Checksum = new Adler32();

        // *********** patch to fix landing in improper frame. ************

        var hadProblem = false
        var finalTs = ts

        val fileSize = aFile.length()
        while(finalTs <= fileSize && readHeader(finalTs , inChannel).getOrElse(Header.get) != Header.get ) {
          hadProblem = true
          finalTs += 1
        }

        if(hadProblem) {
          logger.error(s"Encountered bad header jumped ${finalTs - ts} bytes. (from ${calcRealOffset(ts)} to ${calcRealOffset(finalTs)})")
        }
        // *****************************************************************
        readHeader(finalTs , inChannel) match {
          case Some(header) =>
            if ( header != Header.get ) {
              logger.error("Header value is not as expected [%s]".format(header))
              //println(s"Header value is not as expected ${ts} ${inChannel.size()} ${fileNumber} ")
              throw new RuntimeException
            } else {
              readTimeStamp( finalTs + 8 , inChannel )  match {
                case None => None
                case Some(timestamp) =>
                  // read the original size
                  //println(timestamp)
                  readSize(finalTs + 8 + 8 , inChannel ) match {
                    case None => None
                    case Some(original_size) =>
                      // read size
                      readSize(finalTs + 8 + 8 + 4 , inChannel ) match {
                        case None => None
                        case Some(size) =>
                          readPayload(finalTs + 8 + 8 + 4 + 4 , size , original_size ,inChannel ) match {
                            case Some(compressed_payload) =>
                              val decompressor : LZ4FastDecompressor = factory.fastDecompressor()
                              val uncompressed_payload = decompressor.decompress(compressed_payload , original_size)

                              //val uncompressed_payload = compressed_payload
                              readCheckSum( finalTs + 8 + 8 + 4 + 4 + size , inChannel ) match {
                                case Some(checkSum) =>
                                  val cs = new Adler32()
                                  cs.update(compressed_payload, 0 , size)
                                  if ( checkSum != cs.getValue ) {
                                    logger.error("checksum is not correct")
                                    val off = finalTs + 8 + 8 + 4 + 4 + size
                                    val d = (off , uncompressed_payload)
                                    Some(d)
                                  } else {
                                    val off = finalTs + 8 + 8 + 4 + 4 + size + 8
                                    val d = (off , uncompressed_payload)
                                    Some(d)
                                  }
                                case None => None
                              }
                            case None => None
                      }
                    }
                  }
              }
            }
          case None => None
        }
      }
    }
    catch {
      case lz4x : net.jpountz.lz4.LZ4Exception => {
        logger.error(s"Couldn't decompress data at offset: ${calcRealOffset(ts)}, skipping to next offset.")
        read_one(ts + 1 , aFile, fileNumber)
      }
      case t : Throwable => throw t
    }
  }

  private def read(ts: Long, aFile : RandomAccessFile): (Long, Vector[(Long, Array[Byte])]) = {
    val inChannel : FileChannel = aFile.getChannel();
    if ( ts >= inChannel.size() ) {
      (ts , Vector.empty)
    } else {
      //
      val checksum : Checksum = new Adler32();
      readHeader(ts , inChannel) match {
        case Some(header) =>
          if ( header != Header.get ) {
            logger.error("Header value is not as expected [%s]".format(header))
            throw new RuntimeException
          } else {
            // read the original size
            readSize(ts + 8 , inChannel ) match {
              case None => (ts , Vector.empty)
              case Some(original_size) =>
                // read size
                readSize(ts + 8 + 4 , inChannel ) match {
                  case None => (ts , Vector.empty)
                  case Some(size) =>
                    readPayload(ts + 8 + 4 + 4 , size , original_size ,inChannel ) match {
                      case Some(compressed_payload) =>
                        val decompressor : LZ4FastDecompressor = factory.fastDecompressor()
                        val uncompressed_payload = decompressor.decompress(compressed_payload , original_size)
                        readCheckSum( ts + 8 + 4 + 4 + size , inChannel ) match {
                          case Some(checkSum) =>
                            val cs = new Adler32()
                            cs.update(compressed_payload, 0 , size)
                            if ( checkSum != cs.getValue ) {
                                logger.error("checksum is not correct")
                                (ts , Vector.empty)
                            } else {
                                val off = ts + 8 + 4 + 4 + size + 8
                                (off , Vector( (off , uncompressed_payload)) )
                            }
                          case None => (ts , Vector.empty)
                        }
                      case None => (ts , Vector.empty)
                    }
                }
              }
            }
        case None => (ts , Vector.empty)
      }
    }
  }

}
/*
class TLogInMemoryBuf(tlogName : String , partitionName : String , homePath : String) extends TLog with LazyLogging {

  val tlog_file = new TLogFileImpl(tlog_file , partitionName , homePath )
  def name() = tlog_file.name()
  def partition() = tlog_file.partition()
  def init() {
    tlog_file.init()
  }
  def write(payload : Array[Byte]) = tlog_file.write(payload)
  def write_sync(payload : Array[Byte]) = tlog_file.write_sync(payload)
  def read(ts: Long , count : Int ) = {

    (Long , Vector[(Long,Array[Byte])] )
  }
  def getPartitions = tlog_file.getPartitions
  def shutdown() {
    tlog_file.shutdown()
  }

}*/

class TLogFileImpl(tlogName : String , partitionName : String , homePath : String , readOnly : Boolean ,bucketSize : Long) extends TLog with LazyLogging /*with WithMetrics*/ {

//  println(s"bucketSize ${bucketSize}")
//  val readTLogTimer  = metrics.meter(s"TLog [$tlogName $partitionName] Read Actions Produced")
//  val writeTLogTimer  = metrics.meter(s"TLog [$tlogName $partitionName] Write Actions Produced")
//  println(s" ${tlogName} ${partitionName} tlog version 1.0")
  val factory : LZ4Factory = LZ4Factory.fastestInstance();
  // dataPath full path to data directory
  val dataPath = homePath + File.separator + "data" + File.separator + "tlog"
  logger.info("data directory for tlog %s".format(dataPath))

  // create directory if not exists
  new File(dataPath).mkdirs()
  // tlog file name
  val fileName = "%s_%s".format(tlogName , partitionName )
  logger.info("tlog filename [%s]".format(fileName))
  // perf
  val perf : PerfCounter = new PerfCounter(tlogName + "." + partitionName,"write:success,write:failure,internal_write:success,internal_write:failure,read:success,read:failure")
  // internal queue to aggregate write operations
  val writeQueue = new LinkedBlockingQueue[ ( Promise[Long], Array[Byte] , Int) ]()
  // define the asyncWriteExcutor internal queue size
  val MAX_QUEUE_SIZE = 10000
  // init executor for internal write operation execution
  val internalProcessingExecutor = Executors.newSingleThreadExecutor()
  // stop boolean in order to stop internal processing thread
  var stop : Boolean = false

  // the writer
  var dataWriter : DataWriter = null
  var dataReader : DataReader = null

  // get operations and execute it via the executor
  def runOnExecutorWriteProcessor(body: => Unit) {
    val r = new Runnable {
      def run = body
    }
    internalProcessingExecutor.submit(r)
  }

  // if readOnly do not start the thread
  if (!readOnly) {
    runOnExecutorWriteProcessor {
      //TODO: optimize: pull more than 1, and write in a bulk
      while (!stop || !writeQueue.isEmpty) {
        val d = writeQueue.poll(1, TimeUnit.SECONDS)
        if (d != null) {
          val p: Promise[Long] = d._1
          val payload: Array[Byte] = d._2
          val original_size = d._3
          internal_write(p, payload, original_size)
        }
      }
    }
  }

  // get current tlog name
  def name() = tlogName
  // get current partition name
  def partition() = partitionName

  def write_sync(payload : Array[Byte]) {
    val f = write(payload)
    val id = Await.result(f,400 seconds )
    //sw.stop("write:success")
  }

  def write(payload : Array[Byte]) : scala.concurrent.Future[Long] = {

    // if readOnly
    if (readOnly)
      ???
    val p = Promise[Long]()

    val compression_f = Future {
      val compressor : LZ4Compressor = factory.fastCompressor()
      val payload_compress = compressor.compress(payload)
      payload_compress
    }

    compression_f onComplete  {
      case Success(payload_compress) =>
        //println("Compression is done.")
        val data = ( p , payload_compress , payload.length )
        //println("Write into q.")
        writeQueue.put(data)
//        writeTLogTimer.mark()
      case Failure(t) =>
        p.failure(t)
    }

    p.future
    //sw.stop("write:success")
  }

  //TODO: bulk writes optimization
  private def internal_write(p : Promise[Long] , payload : Array[Byte] , original_size : Int) {
    val sw = perf.getStopWatch
    dataWriter.write(payload, original_size) match {
      case Some(offset) =>
        sw.stop("internal_write:success")
        p.success(offset)
      case None =>
        sw.stop("internal_write:failure")
        p.success(-1)
    }
  }

  def read(ts: Long , size : Long ) : (Long , Vector[(Long,Array[Byte])] ) = {
    val sw = perf.getStopWatch
    val data = dataReader.read(ts , size)
    sw.stop("read:success")
    data
  }

  def readOne(ts:Long):Option[(Long, Array[Byte])] = {
    val sw = perf.getStopWatch
    val data = dataReader.readOne(ts)
    sw.stop("read:success")
    data
  }

  def read(ts: Long,count: Int): (Long, Vector[(Long, Array[Byte])]) = {
    // here we will make based on calc where we need to route the req for data (what datareader to use)
    val sw = perf.getStopWatch
    val data = dataReader.read(ts , count)
    sw.stop("read:success")
//    readTLogTimer.mark(count)
    data
  }

  def init() {
    dataWriter = new DataWriter(dataPath , fileName , bucketSize)
    dataReader = new DataReader(dataPath , fileName , bucketSize)
  }

  def size : Long = {
    dataWriter.position
  }

  def getPartitions = {
    Vector.empty
  }

  def shutdown() {
    logger.debug("Shutting down TLog [%s-%s]".format(this.name() , this.partition()))
    // only if started to write flush bucket size
    stop = true
    internalProcessingExecutor.shutdown()
    perf.shutdown()
  }

}


text:
package com.peterphi.std.guice.web.rest.service.caches;

import com.google.inject.ImplementedBy;
import com.peterphi.std.annotation.Doc;
import com.peterphi.std.annotation.ServiceName;

import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;

@Path("/guice/caches")
@ServiceName("Caches")
@Doc("Displays cache information and allows them to be invalidated")
@ImplementedBy(GuiceCacheManagerRestServiceImpl.class)
public interface GuiceCacheManagerRestService
{
	@GET
	@Path("/")
	@Produces("text/html")
	String getIndex(@QueryParam("message") @Doc("for internal use") String message);

	@POST
	@Path("/invalidate")
	@Produces("text/html")
	@Doc("Invalidate cached values")
	Response invalidate(@FormParam("csrf_token") String providedCsrfToken,
	                    @FormParam("name") @Doc("If omitted will invalidate all caches") String cacheName);
}


text:
package com.eixox.web.controls;

import java.util.LinkedList;

public class Accordion extends LinkedList<AccordionItem> implements Component {

	/**
	 *
	 */
	private static final long serialVersionUID = 3829287765467082135L;
	private String id;

	public final String getId() {
		return this.id;
	}

	public final void setId(String id) {
		this.id = id;

	}

}


text:
package k8s

import (
	"log"

	"k8s.io/client-go/1.4/kubernetes"
	"k8s.io/client-go/1.4/pkg/api"
	"k8s.io/client-go/1.4/pkg/api/v1"
	"k8s.io/client-go/1.4/pkg/watch"
)

func createPodsWatcher(clientset *kubernetes.Clientset) (watch.Interface, error) {
	watcher, err := clientset.Core().Pods("").Watch(api.ListOptions{})
	if err != nil {
		return nil, err
	}
	return watcher, nil
}

func managePodEvent(eventType watch.EventType, pod *v1.Pod) {
	switch eventType {
	case watch.Added:
		log.Printf("[INFO] Add pod: %s\n", pod.Name)
	case watch.Deleted:
		log.Printf("[INFO] Deleted pod: %s\n", pod.Name)
	case watch.Modified:
		log.Printf("[INFO] Modified pod: %s\n", pod.Name)
	}
}


text:
module.exports = {
	before: function (browser) {
		browser.app = browser.page.app();
		browser.signinPage = browser.page.signin();
		browser.listPage = browser.page.list();
		browser.itemPage = browser.page.item();
		browser.initialFormPage = browser.page.initialForm();
		browser.deleteConfirmation = browser.page.deleteConfirmation();

		browser.app.navigate();
		browser.app.waitForSigninScreen();

		browser.signinPage.signin();
		browser.app.waitForElementVisible('@homeScreen');
	},
	after: function (browser) {
		browser.app.signout();
		browser.end();
	},
	'Demonstrate issue 3126': function(browser) {

		// Add new text item

		browser.app.openMiscList('DateFieldMap');
		browser.listPage.createFirstItem();
		browser.app.waitForInitialFormScreen();

		browser.initialFormPage.fillInputs({
			listName: 'DateFieldMap',
			fields: {
				'datefield': {value: '2016-01-01'},
			}
		});
		browser.initialFormPage.save();
		browser.app.waitForItemScreen();

		browser.itemPage.back();

		// The following command fails, because there is no link to follow. This is a bug.
		// If you remove the map from test/e2e/models/misc/DateFieldMap.js then the command works.
		browser.listPage.navigateToFirstItem();

	}
};


text:
package org.omg.dds.core;

import java.util.UUID;

public interface SampleIdentity {

	@Override
	public boolean equals(Object identity);

	@Override
	public int hashCode();

	public UUID guid();

	public long sequenceNumber();
}


text:
"""High level ssh library.

Usage examples:

Execute command and get output:

    ssh = sshclient.SSH("root", "example.com", port=33)
    status, stdout, stderr = ssh.execute("ps ax")
    if status:
        raise Exception("Command failed with non-zero status.")
    print stdout.splitlines()

Execute command with huge output:

    class PseudoFile(object):
        def write(chunk):
            if "error" in chunk:
                email_admin(chunk)

    ssh = sshclient.SSH("root", "example.com")
    ssh.run("tail -f /var/log/syslog", stdout=PseudoFile(), timeout=False)

Execute local script on remote side:

    ssh = sshclient.SSH("user", "example.com")
    status, out, err = ssh.execute("/bin/sh -s arg1 arg2",
                                   stdin=open("~/myscript.sh", "r"))

Upload file:

    ssh = sshclient.SSH("user", "example.com")
    ssh.run("cat > ~/upload/file.gz", stdin=open("/store/file.gz", "rb"))

Eventlet:

    eventlet.monkey_patch(select=True, time=True)
    or
    eventlet.monkey_patch()
    or
    sshclient = eventlet.import_patched("opentstack.common.sshclient")

"""

import os
import select
import socket
import time

import paramiko
import six

from rally.common.i18n import _
from rally.common import log as logging

LOG = logging.getLogger(__name__)

class SSHError(Exception):
    pass

class SSHTimeout(SSHError):
    pass

class SSH(object):
    """Represent ssh connection."""

    def __init__(self, user, host, port=22, pkey=None,
                 key_filename=None, password=None):
        """Initialize SSH client.

        :param user: ssh username
        :param host: hostname or ip address of remote ssh server
        :param port: remote ssh port
        :param pkey: RSA or DSS private key string or file object
        :param key_filename: private key filename
        :param password: password
        """

        self.user = user
        self.host = host
        self.port = port
        self.pkey = self._get_pkey(pkey) if pkey else None
        self.password = password
        self.key_filename = key_filename
        self._client = False

    def _get_pkey(self, key):
        if isinstance(key, six.string_types):
            key = six.moves.StringIO(key)
        errors = []
        for key_class in (paramiko.rsakey.RSAKey, paramiko.dsskey.DSSKey):
            try:
                return key_class.from_private_key(key)
            except paramiko.SSHException as e:
                errors.append(e)
        raise SSHError("Invalid pkey: %s" % (errors))

    def _get_client(self):
        if self._client:
            return self._client
        try:
            self._client = paramiko.SSHClient()
            self._client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            self._client.connect(self.host, username=self.user,
                                 port=self.port, pkey=self.pkey,
                                 key_filename=self.key_filename,
                                 password=self.password, timeout=1)
            return self._client
        except Exception as e:
            message = _("Exception %(exception_type)s was raised "
                        "during connect to %(user)s@%(host)s:%(port)s. "
                        "Exception value is: %(exception)r")
            self._client = False
            raise SSHError(message % {"exception": e,
                                      "user": self.user,
                                      "host": self.host,
                                      "port": self.port,
                                      "exception_type": type(e)})

    def close(self):
        self._client.close()
        self._client = False

    def run(self, cmd, stdin=None, stdout=None, stderr=None,
            raise_on_error=True, timeout=3600):
        """Execute specified command on the server.

        :param cmd:             Command to be executed.
        :param stdin:           Open file or string to pass to stdin.
        :param stdout:          Open file to connect to stdout.
        :param stderr:          Open file to connect to stderr.
        :param raise_on_error:  If False then exit code will be return. If True
                                then exception will be raized if non-zero code.
        :param timeout:         Timeout in seconds for command execution.
                                Default 1 hour. No timeout if set to 0.
        """

        client = self._get_client()

        if isinstance(stdin, six.string_types):
            stdin = six.moves.StringIO(stdin)

        return self._run(client, cmd, stdin=stdin, stdout=stdout,
                         stderr=stderr, raise_on_error=raise_on_error,
                         timeout=timeout)

    def _run(self, client, cmd, stdin=None, stdout=None, stderr=None,
             raise_on_error=True, timeout=3600):

        if isinstance(cmd, (list, tuple)):
            cmd = " ".join(six.moves.shlex_quote(str(p)) for p in cmd)

        transport = client.get_transport()
        session = transport.open_session()
        session.exec_command(cmd)
        start_time = time.time()

        data_to_send = ""
        stderr_data = None

        # If we have data to be sent to stdin then `select' should also
        # check for stdin availability.
        if stdin and not stdin.closed:
            writes = [session]
        else:
            writes = []

        while True:
            # Block until data can be read/write.
            r, w, e = select.select([session], writes, [session], 1)

            if session.recv_ready():
                data = session.recv(4096)
                LOG.debug("stdout: %r" % data)
                if stdout is not None:
                    stdout.write(data)
                continue

            if session.recv_stderr_ready():
                stderr_data = session.recv_stderr(4096)
                LOG.debug("stderr: %r" % stderr_data)
                if stderr is not None:
                    stderr.write(stderr_data)
                continue

            if session.send_ready():
                if stdin is not None and not stdin.closed:
                    if not data_to_send:
                        data_to_send = stdin.read(4096)
                        if not data_to_send:
                            stdin.close()
                            session.shutdown_write()
                            writes = []
                            continue
                    sent_bytes = session.send(data_to_send)
                    LOG.debug("sent: %s" % data_to_send[:sent_bytes])
                    data_to_send = data_to_send[sent_bytes:]

            if session.exit_status_ready():
                break

            if timeout and (time.time() - timeout) > start_time:
                args = {"cmd": cmd, "host": self.host}
                raise SSHTimeout(_("Timeout executing command "
                                   "'%(cmd)s' on host %(host)s") % args)
            if e:
                raise SSHError("Socket error.")

        exit_status = session.recv_exit_status()
        if 0 != exit_status and raise_on_error:
            fmt = _("Command '%(cmd)s' failed with exit_status %(status)d.")
            details = fmt % {"cmd": cmd, "status": exit_status}
            if stderr_data:
                details += _(" Last stderr data: '%s'.") % stderr_data
            raise SSHError(details)
        return exit_status

    def execute(self, cmd, stdin=None, timeout=3600):
        """Execute the specified command on the server.

        :param cmd:     Command to be executed, can be a list.
        :param stdin:   Open file to be sent on process stdin.
        :param timeout: Timeout for execution of the command.

        :returns: tuple (exit_status, stdout, stderr)
        """
        stdout = six.moves.StringIO()
        stderr = six.moves.StringIO()

        exit_status = self.run(cmd, stderr=stderr,
                               stdout=stdout, stdin=stdin,
                               timeout=timeout, raise_on_error=False)
        stdout.seek(0)
        stderr.seek(0)
        return (exit_status, stdout.read(), stderr.read())

    def wait(self, timeout=120, interval=1):
        """Wait for the host will be available via ssh."""
        start_time = time.time()
        while True:
            try:
                return self.execute("uname")
            except (socket.error, SSHError) as e:
                LOG.debug("Ssh is still unavailable: %r" % e)
                time.sleep(interval)
            if time.time() > (start_time + timeout):
                raise SSHTimeout(_("Timeout waiting for '%s'") % self.host)

    def _put_file_sftp(self, localpath, remotepath, mode=None):
        client = self._get_client()

        with client.open_sftp() as sftp:
            sftp.put(localpath, remotepath)
            if mode is None:
                mode = 0o777 & os.stat(localpath).st_mode
            sftp.chmod(remotepath, mode)

    def _put_file_shell(self, localpath, remotepath, mode=None):
        cmd = ["cat > %s" % remotepath]
        if mode is not None:
            cmd.append("chmod 0%o %s" % (mode, remotepath))

        with open(localpath, "rb") as localfile:
            cmd = "; ".join(cmd)
            self.run(cmd, stdin=localfile)

    def put_file(self, localpath, remotepath, mode=None):
        """Copy specified local file to the server.

        :param localpath:   Local filename.
        :param remotepath:  Remote filename.
        :param mode:        Permissions to set after upload
        """

        try:
            self._put_file_sftp(localpath, remotepath, mode=mode)
        except paramiko.SSHException:
            self._put_file_shell(localpath, remotepath, mode=mode)


text:
Vous pouvez inclure un champ `meta` quand vous définissez une route :

``` js
const router = new VueRouter({
  routes: [
    {
      path: '/foo',
      component: Foo,
      children: [
        {
          path: 'bar',
          component: Bar,
          // un champ `meta`
          meta: { requiresAuth: true }
        }
      ]
    }
  ]
})
```

Comment maintenant accéder à ce champ `meta` ?

Tout d'abord, chaque objet route dans la configuration de `routes` est appelé un **registre de route**. Les registres de route peuvent être imbriqués. Par conséquent, quand une route concorde, elle peut potentiellement concorder avec plus d'un registre de route.

Par exemple, avec la configuration de route ci-dessous, l'URL `/foo/bar` va concorder avec le registre parent et le registre enfant.

Tous les registres concordants avec une route sont exposés dans l'objet `$route` (ainsi que les objets de route dans les sécurisations de navigation) dans le tableau `$route.matched`. Donc, nous devons itérer à travers `$route.matched` pour vérifier les champs meta dans les registres de route.

Un exemple concret est la vérification d'un champ meta dans une interception de navigation globale :

``` js
router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresAuth)) {
    // cette route demande une autorisation, vérifions si l'utilisateur est logué.
    // sinon, redirigeons le sur la page de login.
    if (!auth.loggedIn()) {
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
    } else {
      next()
    }
  } else {
    next() // assurez vous de toujours appeler `next()` !
  }
})
```


text:
BASE_DIR=$(cd $(dirname ${BASH_SOURCE[0]})/../ && pwd)
cd ${BASE_DIR}/../

./bin/setup-example-material.bash

ARCHIVE_DIR_NAME=advanced-python-topics
TIMESTAMP=$(date "+%Y%m%d-%H%M%S")
ZIP_NAME="${ARCHIVE_DIR_NAME}-${TIMESTAMP}.zip"

zip -vr "${ZIP_NAME}" "${ARCHIVE_DIR_NAME}"


text:
require.config({
    //'baseUrl': "js/",
    'paths': {
        jquery: 'libs/jquery-1.10.0.min',
        underscore: 'libs/underscore-min',
        backbone: 'libs/backbone',
        backboneMaster: 'libs/backbone.cleanup-amd',
        backboneCustom: 'libs/backbone.custom',
        backboneParams:'libs/backbone.queryparams',
        backboneValidate:'libs/backbone-validation',
        foundation: 'libs/foundation.min',
        bridget:'libs/isotope/jquery.bridget',
        isotope:'libs/isotope/isotope.pkgd',
        bridget:'libs/isotope/jquery.bridget',
        isotope_item: 'libs/isotope/item',
        layout_mode: 'libs/isotope/layout-mode',
        fit_rows: 'libs/isotope/layout-modes/fit-rows',
        masonry: 'libs/isotope/layout-modes/masonry',
        vertical:'libs/isotope/layout-modes/vertical',
        templates: '../templates'
    },
    'shim': {
        'backbone': {
            deps: ['underscore', 'jquery'],
            exports: 'Backbone'
        },
        backboneCustom: {
            deps: ['backbone'],
            exports: 'backboneCustom'
        },
        'underscore': {
            exports: '_'
        },
        'isotope' :{
            deps: ['bridget','jquery']
        },
        'validate' :{
            deps: ['jquery']
        },
        'foundation' :{
            deps: ['jquery']
        },
        'backboneValidate' : {
            deps:['jquery', 'backbone']
        },
        'backboneParams' : {
            deps:['backbone']
        }
    }

});

require(['app'], function(App){
    //App.initialize();
});


text:
from git.test.lib import *
from git import *
from gitdb import IStream
from gitdb.util import hex_to_bin

from cStringIO import StringIO
import time
import sys

def assert_commit_serialization(rwrepo, commit_id, print_performance_info=False):
    """traverse all commits in the history of commit identified by commit_id and check
    if the serialization works.
    :param print_performance_info: if True, we will show how fast we are"""
    ns = 0      # num serializations
    nds = 0     # num deserializations

    st = time.time()
    for cm in rwrepo.commit(commit_id).traverse():
        nds += 1

        # assert that we deserialize commits correctly, hence we get the same
        # sha on serialization
        stream = StringIO()
        cm._serialize(stream)
        ns += 1
        streamlen = stream.tell()
        stream.seek(0)

        istream = rwrepo.odb.store(IStream(Commit.type, streamlen, stream))
        assert istream.hexsha == cm.hexsha

        nc = Commit(rwrepo, Commit.NULL_BIN_SHA, cm.tree,
                        cm.author, cm.authored_date, cm.author_tz_offset,
                        cm.committer, cm.committed_date, cm.committer_tz_offset,
                        cm.message, cm.parents, cm.encoding)

        assert nc.parents == cm.parents
        stream = StringIO()
        nc._serialize(stream)
        ns += 1
        streamlen = stream.tell()
        stream.seek(0)

        # reuse istream
        istream.size = streamlen
        istream.stream = stream
        istream.binsha = None
        nc.binsha = rwrepo.odb.store(istream).binsha

        # if it worked, we have exactly the same contents !
        assert nc.hexsha == cm.hexsha
    # END check commits
    elapsed = time.time() - st

    if print_performance_info:
        print >> sys.stderr, "Serialized %i and deserialized %i commits in %f s ( (%f, %f) commits / s" % (ns, nds, elapsed, ns/elapsed, nds/elapsed)
    # END handle performance info

class TestCommit(TestBase):

    def test_bake(self):

        commit = self.rorepo.commit('2454ae89983a4496a445ce347d7a41c0bb0ea7ae')
        # commits have no dict
        self.failUnlessRaises(AttributeError, setattr, commit, 'someattr', 1)
        commit.author # bake

        assert_equal("Sebastian Thiel", commit.author.name)
        assert_equal("byronimo@gmail.com", commit.author.email)
        assert commit.author == commit.committer
        assert isinstance(commit.authored_date, int) and isinstance(commit.committed_date, int)
        assert isinstance(commit.author_tz_offset, int) and isinstance(commit.committer_tz_offset, int)
        assert commit.message == "Added missing information to docstrings of commit and stats module\n"

    def test_stats(self):
        commit = self.rorepo.commit('33ebe7acec14b25c5f84f35a664803fcab2f7781')
        stats = commit.stats

        def check_entries(d):
            assert isinstance(d, dict)
            for key in ("insertions", "deletions", "lines"):
                assert key in d
        # END assertion helper
        assert stats.files
        assert stats.total

        check_entries(stats.total)
        assert "files" in stats.total

        for filepath, d in stats.files.items():
            check_entries(d)
        # END for each stated file

        # assure data is parsed properly
        michael = Actor._from_string("Michael Trier <mtrier@gmail.com>")
        assert commit.author == michael
        assert commit.committer == michael
        assert commit.authored_date == 1210193388
        assert commit.committed_date == 1210193388
        assert commit.author_tz_offset == 14400, commit.author_tz_offset
        assert commit.committer_tz_offset == 14400, commit.committer_tz_offset
        assert commit.message == "initial project\n"

    def test_unicode_actor(self):
        # assure we can parse unicode actors correctly
        name = "Üäöß ÄußÉ".decode("utf-8")
        assert len(name) == 9
        special = Actor._from_string(u"%s <something@this.com>" % name)
        assert special.name == name
        assert isinstance(special.name, unicode)

    def test_traversal(self):
        start = self.rorepo.commit("a4d06724202afccd2b5c54f81bcf2bf26dea7fff")
        first = self.rorepo.commit("33ebe7acec14b25c5f84f35a664803fcab2f7781")
        p0 = start.parents[0]
        p1 = start.parents[1]
        p00 = p0.parents[0]
        p10 = p1.parents[0]

        # basic branch first, depth first
        dfirst = start.traverse(branch_first=False)
        bfirst = start.traverse(branch_first=True)
        assert dfirst.next() == p0
        assert dfirst.next() == p00

        assert bfirst.next() == p0
        assert bfirst.next() == p1
        assert bfirst.next() == p00
        assert bfirst.next() == p10

        # at some point, both iterations should stop
        assert list(bfirst)[-1] == first
        stoptraverse = self.rorepo.commit("254d04aa3180eb8b8daf7b7ff25f010cd69b4e7d").traverse(as_edge=True)
        l = list(stoptraverse)
        assert len(l[0]) == 2

        # ignore self
        assert start.traverse(ignore_self=False).next() == start

        # depth
        assert len(list(start.traverse(ignore_self=False, depth=0))) == 1

        # prune
        assert start.traverse(branch_first=1, prune=lambda i,d: i==p0).next() == p1

        # predicate
        assert start.traverse(branch_first=1, predicate=lambda i,d: i==p1).next() == p1

        # traversal should stop when the beginning is reached
        self.failUnlessRaises(StopIteration, first.traverse().next)

        # parents of the first commit should be empty ( as the only parent has a null
        # sha )
        assert len(first.parents) == 0

    def test_iteration(self):
        # we can iterate commits
        all_commits = Commit.list_items(self.rorepo, self.rorepo.head)
        assert all_commits
        assert all_commits == list(self.rorepo.iter_commits())

        # this includes merge commits
        mcomit = self.rorepo.commit('d884adc80c80300b4cc05321494713904ef1df2d')
        assert mcomit in all_commits

        # we can limit the result to paths
        ltd_commits = list(self.rorepo.iter_commits(paths='CHANGES'))
        assert ltd_commits and len(ltd_commits) < len(all_commits)

        # show commits of multiple paths, resulting in a union of commits
        less_ltd_commits = list(Commit.iter_items(self.rorepo, 'master', paths=('CHANGES', 'AUTHORS')))
        assert len(ltd_commits) < len(less_ltd_commits)

    def test_iter_items(self):
        # pretty not allowed
        self.failUnlessRaises(ValueError, Commit.iter_items, self.rorepo, 'master', pretty="raw")

    def test_rev_list_bisect_all(self):
        """
        'git rev-list --bisect-all' returns additional information
        in the commit header.  This test ensures that we properly parse it.
        """
        revs = self.rorepo.git.rev_list('933d23bf95a5bd1624fbcdf328d904e1fa173474',
                                      first_parent=True,
                                      bisect_all=True)

        commits = Commit._iter_from_process_or_stream(self.rorepo, StringProcessAdapter(revs))
        expected_ids = (
            '7156cece3c49544abb6bf7a0c218eb36646fad6d',
            '1f66cfbbce58b4b552b041707a12d437cc5f400a',
            '33ebe7acec14b25c5f84f35a664803fcab2f7781',
            '933d23bf95a5bd1624fbcdf328d904e1fa173474'
        )
        for sha1, commit in zip(expected_ids, commits):
            assert_equal(sha1, commit.hexsha)

    def test_count(self):
        assert self.rorepo.tag('refs/tags/0.1.5').commit.count( ) == 143

    def test_list(self):
        assert isinstance(Commit.list_items(self.rorepo, '0.1.5', max_count=5)[hex_to_bin('5117c9c8a4d3af19a9958677e45cda9269de1541')], Commit)

    def test_str(self):
        commit = Commit(self.rorepo, Commit.NULL_BIN_SHA)
        assert_equal(Commit.NULL_HEX_SHA, str(commit))

    def test_repr(self):
        commit = Commit(self.rorepo, Commit.NULL_BIN_SHA)
        assert_equal('<git.Commit "%s">' % Commit.NULL_HEX_SHA, repr(commit))

    def test_equality(self):
        commit1 = Commit(self.rorepo, Commit.NULL_BIN_SHA)
        commit2 = Commit(self.rorepo, Commit.NULL_BIN_SHA)
        commit3 = Commit(self.rorepo, "\1"*20)
        assert_equal(commit1, commit2)
        assert_not_equal(commit2, commit3)

    def test_iter_parents(self):
        # should return all but ourselves, even if skip is defined
        c = self.rorepo.commit('0.1.5')
        for skip in (0, 1):
            piter = c.iter_parents(skip=skip)
            first_parent = piter.next()
            assert first_parent != c
            assert first_parent == c.parents[0]
        # END for each

    def test_base(self):
        name_rev = self.rorepo.head.commit.name_rev
        assert isinstance(name_rev, basestring)

    @with_rw_repo('HEAD', bare=True)
    def test_serialization(self, rwrepo):
        # create all commits of our repo
        assert_commit_serialization(rwrepo, '0.1.6')

    def test_serialization_unicode_support(self):
        assert Commit.default_encoding.lower() == 'utf-8'

        # create a commit with unicode in the message, and the author's name
        # Verify its serialization and deserialization
        cmt = self.rorepo.commit('0.1.6')
        assert isinstance(cmt.message, unicode)     # it automatically decodes it as such
        assert isinstance(cmt.author.name, unicode) # same here

        cmt.message = "üäêèß".decode("utf-8")
        assert len(cmt.message) == 5

        cmt.author.name = "äüß".decode("utf-8")
        assert len(cmt.author.name) == 3

        cstream = StringIO()
        cmt._serialize(cstream)
        cstream.seek(0)
        assert len(cstream.getvalue())

        ncmt = Commit(self.rorepo, cmt.binsha)
        ncmt._deserialize(cstream)

        assert cmt.author.name == ncmt.author.name
        assert cmt.message == ncmt.message
        # actually, it can't be printed in a shell as repr wants to have ascii only
        # it appears
        cmt.author.__repr__()


text:
Set-ExecutionPolicy Bypass -scope Process
$ProgressPreference = 'SilentlyContinue';

Write-Host "Downloading LCOW LinuxKit ..."
Invoke-WebRequest -OutFile "$env:TEMP\linuxkit-lcow.zip" "https://23-111085629-gh.circle-artifacts.com/0/release.zip"
Expand-Archive -Path "$env:TEMP\linuxkit-lcow.zip" -DestinationPath "$env:ProgramFiles\Linux Containers" -Force
Remove-Item "$env:TEMP\linuxkit-lcow.zip"

Write-Host "Downloading docker nightly ..."
Invoke-WebRequest -OutFile "$env:TEMP\docker-master.zip" "https://master.dockerproject.com/windows/x86_64/docker.zip"
Expand-Archive -Path "$env:TEMP\docker-master.zip" -DestinationPath $env:ProgramFiles -Force
Remove-Item "$env:TEMP\docker-master.zip"

$env:Path = $env:Path + ";$($env:ProgramFiles)\docker"
Write-Host "Registering docker service ..."
. dockerd --register-service -H npipe:// -H 0.0.0.0:2375 -G docker --experimental
Start-Service Docker


text:
namespace juce
{

IIRCoefficients::IIRCoefficients() noexcept
{
    zeromem (coefficients, sizeof (coefficients));
}

IIRCoefficients::~IIRCoefficients() noexcept {}

IIRCoefficients::IIRCoefficients (const IIRCoefficients& other) noexcept
{
    memcpy (coefficients, other.coefficients, sizeof (coefficients));
}

IIRCoefficients& IIRCoefficients::operator= (const IIRCoefficients& other) noexcept
{
    memcpy (coefficients, other.coefficients, sizeof (coefficients));
    return *this;
}

IIRCoefficients::IIRCoefficients (double c1, double c2, double c3,
                                  double c4, double c5, double c6) noexcept
{
    auto a = 1.0 / c4;

    coefficients[0] = (float) (c1 * a);
    coefficients[1] = (float) (c2 * a);
    coefficients[2] = (float) (c3 * a);
    coefficients[3] = (float) (c5 * a);
    coefficients[4] = (float) (c6 * a);
}

IIRCoefficients IIRCoefficients::makeLowPass (double sampleRate,
                                              double frequency) noexcept
{
    return makeLowPass (sampleRate, frequency, 1.0 / MathConstants<double>::sqrt2);
}

IIRCoefficients IIRCoefficients::makeLowPass (double sampleRate,
                                              double frequency,
                                              double Q) noexcept
{
    jassert (sampleRate > 0.0);
    jassert (frequency > 0.0 && frequency <= sampleRate * 0.5);
    jassert (Q > 0.0);

    auto n = 1.0 / std::tan (MathConstants<double>::pi * frequency / sampleRate);
    auto nSquared = n * n;
    auto c1 = 1.0 / (1.0 + 1.0 / Q * n + nSquared);

    return IIRCoefficients (c1,
                            c1 * 2.0,
                            c1,
                            1.0,
                            c1 * 2.0 * (1.0 - nSquared),
                            c1 * (1.0 - 1.0 / Q * n + nSquared));
}

IIRCoefficients IIRCoefficients::makeHighPass (double sampleRate,
                                               double frequency) noexcept
{
    return makeHighPass (sampleRate, frequency, 1.0 / std::sqrt(2.0));
}

IIRCoefficients IIRCoefficients::makeHighPass (double sampleRate,
                                               double frequency,
                                               double Q) noexcept
{
    jassert (sampleRate > 0.0);
    jassert (frequency > 0.0 && frequency <= sampleRate * 0.5);
    jassert (Q > 0.0);

    auto n = std::tan (MathConstants<double>::pi * frequency / sampleRate);
    auto nSquared = n * n;
    auto c1 = 1.0 / (1.0 + 1.0 / Q * n + nSquared);

    return IIRCoefficients (c1,
                            c1 * -2.0,
                            c1,
                            1.0,
                            c1 * 2.0 * (nSquared - 1.0),
                            c1 * (1.0 - 1.0 / Q * n + nSquared));
}

IIRCoefficients IIRCoefficients::makeBandPass (double sampleRate,
                                               double frequency) noexcept
{
    return makeBandPass (sampleRate, frequency, 1.0 / MathConstants<double>::sqrt2);
}

IIRCoefficients IIRCoefficients::makeBandPass (double sampleRate,
                                               double frequency,
                                               double Q) noexcept
{
    jassert (sampleRate > 0.0);
    jassert (frequency > 0.0 && frequency <= sampleRate * 0.5);
    jassert (Q > 0.0);

    auto n = 1.0 / std::tan (MathConstants<double>::pi * frequency / sampleRate);
    auto nSquared = n * n;
    auto c1 = 1.0 / (1.0 + 1.0 / Q * n + nSquared);

    return IIRCoefficients (c1 * n / Q,
                            0.0,
                            -c1 * n / Q,
                            1.0,
                            c1 * 2.0 * (1.0 - nSquared),
                            c1 * (1.0 - 1.0 / Q * n + nSquared));
}

IIRCoefficients IIRCoefficients::makeNotchFilter (double sampleRate,
                                                  double frequency) noexcept
{
    return makeNotchFilter (sampleRate, frequency, 1.0 / MathConstants<double>::sqrt2);
}

IIRCoefficients IIRCoefficients::makeNotchFilter (double sampleRate,
                                                  double frequency,
                                                  double Q) noexcept
{
    jassert (sampleRate > 0.0);
    jassert (frequency > 0.0 && frequency <= sampleRate * 0.5);
    jassert (Q > 0.0);

    auto n = 1.0 / std::tan (MathConstants<double>::pi * frequency / sampleRate);
    auto nSquared = n * n;
    auto c1 = 1.0 / (1.0 + n / Q + nSquared);

    return IIRCoefficients (c1 * (1.0 + nSquared),
                            2.0 * c1 * (1.0 - nSquared),
                            c1 * (1.0 + nSquared),
                            1.0,
                            c1 * 2.0 * (1.0 - nSquared),
                            c1 * (1.0 - n / Q + nSquared));
}

IIRCoefficients IIRCoefficients::makeAllPass (double sampleRate,
                                              double frequency) noexcept
{
    return makeAllPass (sampleRate, frequency, 1.0 / MathConstants<double>::sqrt2);
}

IIRCoefficients IIRCoefficients::makeAllPass (double sampleRate,
                                              double frequency,
                                              double Q) noexcept
{
    jassert (sampleRate > 0.0);
    jassert (frequency > 0.0 && frequency <= sampleRate * 0.5);
    jassert (Q > 0.0);

    auto n = 1.0 / std::tan (MathConstants<double>::pi * frequency / sampleRate);
    auto nSquared = n * n;
    auto c1 = 1.0 / (1.0 + 1.0 / Q * n + nSquared);

    return IIRCoefficients (c1 * (1.0 - n / Q + nSquared),
                            c1 * 2.0 * (1.0 - nSquared),
                            1.0,
                            1.0,
                            c1 * 2.0 * (1.0 - nSquared),
                            c1 * (1.0 - n / Q + nSquared));
}

IIRCoefficients IIRCoefficients::makeLowShelf (double sampleRate,
                                               double cutOffFrequency,
                                               double Q,
                                               float gainFactor) noexcept
{
    jassert (sampleRate > 0.0);
    jassert (cutOffFrequency > 0.0 && cutOffFrequency <= sampleRate * 0.5);
    jassert (Q > 0.0);

    auto A = jmax (0.0f, std::sqrt (gainFactor));
    auto aminus1 = A - 1.0;
    auto aplus1 = A + 1.0;
    auto omega = (MathConstants<double>::twoPi * jmax (cutOffFrequency, 2.0)) / sampleRate;
    auto coso = std::cos (omega);
    auto beta = std::sin (omega) * std::sqrt (A) / Q;
    auto aminus1TimesCoso = aminus1 * coso;

    return IIRCoefficients (A * (aplus1 - aminus1TimesCoso + beta),
                            A * 2.0 * (aminus1 - aplus1 * coso),
                            A * (aplus1 - aminus1TimesCoso - beta),
                            aplus1 + aminus1TimesCoso + beta,
                            -2.0 * (aminus1 + aplus1 * coso),
                            aplus1 + aminus1TimesCoso - beta);
}

IIRCoefficients IIRCoefficients::makeHighShelf (double sampleRate,
                                                double cutOffFrequency,
                                                double Q,
                                                float gainFactor) noexcept
{
    jassert (sampleRate > 0.0);
    jassert (cutOffFrequency > 0.0 && cutOffFrequency <= sampleRate * 0.5);
    jassert (Q > 0.0);

    auto A = jmax (0.0f, std::sqrt (gainFactor));
    auto aminus1 = A - 1.0;
    auto aplus1 = A + 1.0;
    auto omega = (MathConstants<double>::twoPi * jmax (cutOffFrequency, 2.0)) / sampleRate;
    auto coso = std::cos (omega);
    auto beta = std::sin (omega) * std::sqrt (A) / Q;
    auto aminus1TimesCoso = aminus1 * coso;

    return IIRCoefficients (A * (aplus1 + aminus1TimesCoso + beta),
                            A * -2.0 * (aminus1 + aplus1 * coso),
                            A * (aplus1 + aminus1TimesCoso - beta),
                            aplus1 - aminus1TimesCoso + beta,
                            2.0 * (aminus1 - aplus1 * coso),
                            aplus1 - aminus1TimesCoso - beta);
}

IIRCoefficients IIRCoefficients::makePeakFilter (double sampleRate,
                                                 double frequency,
                                                 double Q,
                                                 float gainFactor) noexcept
{
    jassert (sampleRate > 0.0);
    jassert (frequency > 0.0 && frequency <= sampleRate * 0.5);
    jassert (Q > 0.0);

    auto A = jmax (0.0f, std::sqrt (gainFactor));
    auto omega = (MathConstants<double>::twoPi * jmax (frequency, 2.0)) / sampleRate;
    auto alpha = 0.5 * std::sin (omega) / Q;
    auto c2 = -2.0 * std::cos (omega);
    auto alphaTimesA = alpha * A;
    auto alphaOverA = alpha / A;

    return IIRCoefficients (1.0 + alphaTimesA,
                            c2,
                            1.0 - alphaTimesA,
                            1.0 + alphaOverA,
                            c2,
                            1.0 - alphaOverA);
}

//==============================================================================
IIRFilter::IIRFilter() noexcept
{
}

IIRFilter::IIRFilter (const IIRFilter& other) noexcept  : active (other.active)
{
    const SpinLock::ScopedLockType sl (other.processLock);
    coefficients = other.coefficients;
}

IIRFilter::~IIRFilter() noexcept
{
}

//==============================================================================
void IIRFilter::makeInactive() noexcept
{
    const SpinLock::ScopedLockType sl (processLock);
    active = false;
}

void IIRFilter::setCoefficients (const IIRCoefficients& newCoefficients) noexcept
{
    const SpinLock::ScopedLockType sl (processLock);
    coefficients = newCoefficients;
    active = true;
}

//==============================================================================
void IIRFilter::reset() noexcept
{
    const SpinLock::ScopedLockType sl (processLock);
    v1 = v2 = 0.0;
}

float IIRFilter::processSingleSampleRaw (float in) noexcept
{
    auto out = coefficients.coefficients[0] * in + v1;

    JUCE_SNAP_TO_ZERO (out);

    v1 = coefficients.coefficients[1] * in - coefficients.coefficients[3] * out + v2;
    v2 = coefficients.coefficients[2] * in - coefficients.coefficients[4] * out;

    return out;
}

void IIRFilter::processSamples (float* const samples, const int numSamples) noexcept
{
    const SpinLock::ScopedLockType sl (processLock);

    if (active)
    {
        auto c0 = coefficients.coefficients[0];
        auto c1 = coefficients.coefficients[1];
        auto c2 = coefficients.coefficients[2];
        auto c3 = coefficients.coefficients[3];
        auto c4 = coefficients.coefficients[4];
        auto lv1 = v1, lv2 = v2;

        for (int i = 0; i < numSamples; ++i)
        {
            auto in = samples[i];
            auto out = c0 * in + lv1;
            samples[i] = out;

            lv1 = c1 * in - c3 * out + lv2;
            lv2 = c2 * in - c4 * out;
        }

        JUCE_SNAP_TO_ZERO (lv1);  v1 = lv1;
        JUCE_SNAP_TO_ZERO (lv2);  v2 = lv2;
    }
}

} // namespace juce


text:
package com.moac.android.interceptordemo.injection.module;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.TypeAdapterFactory;

import com.moac.android.interceptordemo.api.SoundCloudApi;
import com.moac.android.interceptordemo.api.model.AutoValueGsonTypeAdapterFactory;
import com.moac.android.interceptordemo.rx.ISchedulerProvider;

import javax.inject.Named;
import javax.inject.Singleton;

import dagger.Module;
import dagger.Provides;
import okhttp3.OkHttpClient;
import retrofit2.CallAdapter;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

@Module(complete = false, library = true)
public class ApiModule {

    // Required configuration settings definitions //

    static final String API_ENDPOINT_URL = "ApiEndpointUrl";

    // Injection providers //

    @Provides
    @Singleton
    OkHttpClient provideClient(@NetworkModule.Api OkHttpClient client) {
        return client;
    }

    @Provides
    @Singleton
    TypeAdapterFactory provideAutoValueGsonTypeAdapterFactory() {
        return new AutoValueGsonTypeAdapterFactory();
    }

    @Provides
    @Singleton
    Gson provideGson(TypeAdapterFactory typeAdapterFactory) {
        return new GsonBuilder().registerTypeAdapterFactory(typeAdapterFactory).create();
    }

    @Provides
    @Singleton
    GsonConverterFactory provideGsonConverterFactory(Gson gson) {
        return GsonConverterFactory.create(gson);
    }

    @Provides
    @Singleton
    CallAdapter.Factory provideRxJavaFactory(ISchedulerProvider schedulerProvider) {
        return RxJavaCallAdapterFactory.createWithScheduler(schedulerProvider.io());
    }

    @Provides
    @Singleton
    Retrofit provideSoundCloudApiRestAdapter(OkHttpClient client,
                                             @Named(API_ENDPOINT_URL) String baseUrl,
                                             CallAdapter.Factory callAdapterFactory,
                                             GsonConverterFactory converterFactory) {

        return new Retrofit.Builder()
                .client(client)
                .baseUrl(baseUrl)
                .addCallAdapterFactory(callAdapterFactory)
                .addConverterFactory(converterFactory)
                .build();

    }

    @Provides
    @Singleton
    SoundCloudApi provideSoundCloudApi(Retrofit retrofit) {
        return retrofit.create(SoundCloudApi.class);
    }

}


text:
// RobotBuilder Version: 2.0
//
// This file was generated by RobotBuilder. It contains sections of
// code that are automatically generated and assigned by robotbuilder.
// These sections will be updated in the future when you export to
// Java from RobotBuilder. Do not put any code or make any change in
// the blocks indicating autogenerated code or it will be lost on an
// update. Deleting the comments indicating the section will prevent
// it from being updated in the future.

package org.usfirst.frc5509.Baeta;

// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=IMPORTS
import edu.wpi.first.wpilibj.ADXRS450_Gyro;
import edu.wpi.first.wpilibj.Compressor;
import edu.wpi.first.wpilibj.DoubleSolenoid;
import edu.wpi.first.wpilibj.RobotDrive;
import edu.wpi.first.wpilibj.SpeedController;
import edu.wpi.first.wpilibj.Talon;

import edu.wpi.first.wpilibj.interfaces.Gyro;
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=IMPORTS
import edu.wpi.first.wpilibj.livewindow.LiveWindow;
import edu.wpi.first.wpilibj.livewindow.LiveWindowSendable;

/**
 * The RobotMap is a mapping from the ports sensors and actuators are wired into
 * to a variable name. This provides flexibility changing wiring, makes checking
 * the wiring easier and significantly reduces the number of magic numbers
 * floating around.
 */
public class RobotMap {
    // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS
    public static SpeedController driveRightDrive;
    public static SpeedController driveLeftDrive;
    public static RobotDrive driveRobotDrive21;
    public static SpeedController weainchWench;
    public static SpeedController ball_MechControl_Mech;
    public static SpeedController ballBox;
    public static Gyro subsystem1Gyro1;
    //public static Compressor pneumaticsCompressor;
    //public static DoubleSolenoid pneumaticsDoubleSolenoid;
    // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS

    public static void init() {
        // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTORS
        driveRightDrive = new Talon(0);
        LiveWindow.addActuator("Drive", "Right Drive", (Talon) driveRightDrive);

        driveLeftDrive = new Talon(1);
        LiveWindow.addActuator("Drive", "Left Drive", (Talon) driveLeftDrive);

        driveRobotDrive21 = new RobotDrive(driveLeftDrive, driveRightDrive);

        driveRobotDrive21.setSafetyEnabled(false);
        //driveRobotDrive21.setExpiration(0.1);
        driveRobotDrive21.setSensitivity(0.5);
        driveRobotDrive21.setMaxOutput(1.0);

        driveRobotDrive21.setInvertedMotor(RobotDrive.MotorType.kRearRight, true);
        weainchWench = new Talon(3);
        LiveWindow.addActuator("Weainch", "Wench", (Talon) weainchWench);

        ball_MechControl_Mech = new Talon(2);
        LiveWindow.addActuator("Ball_Mech", "Control_Mech", (Talon) ball_MechControl_Mech);

        ballBox = new Talon(4);
        LiveWindow.addActuator("BallBox", "BoxWench", (Talon) ballBox);
//pneumaticsCompressor = new Compressor(0);

       // pneumaticsDoubleSolenoid = new DoubleSolenoid(0, 0, 1);
        //LiveWindow.addActuator("Pneumatics", "Double Solenoid", pneumaticsDoubleSolenoid);

        // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTORS
    }
}


text:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class User extends MX_Controller {

	function __construct() {
	    parent::__construct();

		$this->load->module('header/header');
		$this->load->module('footer/footer');
		$this->load->model('user/User_model');
		$this->load->model('helper/helper_model');
		$this->active = "user";
	}

	public function index()
	{

		$this->header->index($this->active);
		$this->load->view('UserAdd');
		$this->footer->index();
	}
	public function adduser()
	{
		 $user_type = isset($_POST['user_type']) ? $_POST['user_type'] : "";
		 $user_fname = isset($_POST['first_name']) ? $_POST['first_name'] : "";
		 $user_lname = isset($_POST['last_name']) ? $_POST['last_name'] : "";
		 $user_email_id = isset($_POST['email_id']) ? $_POST['email_id'] : "";
		 $user_dob = isset($_POST['user_dob']) ? $_POST['user_dob'] : "";
		 $user_name = isset($_POST['user_name']) ? $_POST['user_name'] : "";
		 $password = isset($_POST['password']) ? $_POST['password'] : "";
		 $mob_no = isset($_POST['mob_no']) ? $_POST['mob_no'] : "";
		 $profilephoto = isset($_FILES['profilephoto']) ? $_FILES['profilephoto'] : "";
		 $user_status = isset($_POST['status']) ? $_POST['status'] : "0";
		 $user_id = 0;
		 if(isset($_SESSION['userId']) && !empty($_SESSION['userId'])) {
			$user_id = $_SESSION['userId'];
		}

		 //bdate conversion
		 if(isset($user_dob) && !empty($user_dob)){
		 	$user_dob = $this->helper_model->dbDate($user_dob);

		 }
		    $_FILES['profilephoto']['name']."<br>";
			$_FILES['profilephoto']['tmp_name'];
			$isfile=basename($_FILES['profilephoto']['name']);
			$newname=$isfile;
			$sizeinmb=25;
			$user_profile_photo=FILE_UPLOAD.$user_fname."_".$newname;

		 $user = array(
			'user_type' => isset($_POST['user_type']) ? $_POST['user_type'] : "",
			'user_first_name' => $user_fname,
			'user_last_name' => $user_lname,
			'user_email_id' => $user_email_id,
			'user_dob' => isset($_POST['user_dob']) ? $_POST['user_dob'] : "",
			'user_name' => isset($_POST['user_name']) ? $_POST['user_name'] : "",
			'password' => isset($_POST['password']) ? md5($_POST['password']) : "",
			'user_mobile_number' => isset($_POST['mob_no']) ? $_POST['mob_no'] : "",
			'user_profile_photo' => isset($_FILES['profilephoto']) ? $user_profile_photo : "",
			'status' => $user_status,
			'added_by' => $user_id,
			'added_on' => date('Y-m-d')
			);

			if($isfile!=''){

			$imgerr=$this->helper_model->do_upload($_FILES['profilephoto']['name'],$_FILES['profilephoto']['tmp_name'],$sizeinmb,$newname,$user_fname);
			}

		$select = 'user_id';
		$tableName = 'users_master';
		$column = 'user_id';
		#$value = $_POST['user_id'];

		 //$check = $this->helper_model->select($select, $tableName, $column, $value);

			  $result = $this->helper_model->insert($tableName,$user);

			if($result == true){

			    $response['success'] = true;
				$response['error'] = false;
				$response['successMsg'] = "Successfully Submit";
				$response['redirect'] = base_url()."user/viewuser";
			} else{
				$response['success'] = false;
				$response['error'] = true;
				$response['errorMsg'] = "Please contact IT Dept";
			}

		echo json_encode($response);

	}
	public function viewuser($pageno="")
	{
		 //Pagination
		$count= $this->User_model->getcount();
		$total_page=ceil($count[0]['cnt'] / NUMBER_PER_PAGE);

		if($pageno<=$total_page)
		{
			$newpage= ++$pageno;
			$y = NUMBER_PER_PAGE;
			$x = NUMBER_PER_PAGE * $newpage - NUMBER_PER_PAGE;
			$limit = "$x,$y";
			$data['list']=$this->User_model->listing($limit);
		}

		$data['total_page'] = $total_page;
		$data['pageno'] = $pageno;

        $this->header->index($this->active);
		$this->load->view('userlist', $data);
		$this->footer->index();
	}

	public function edituser()
	{
		$siteid=$_GET['id'];
		$result = $this->User_model->viewuserdet($siteid);
		$result['sitedata']=$result;
		$this->header->index($this->active);
		$this->load->view('editsite',$result);
		$this->footer->index();
	}

	public function update($id)
	{
         $select = '*';
		$tableName = 'users_master';
		$column = 'user_id';
		$value = $id;
		$data['user'] = $this->helper_model->select($select, $tableName, $column, $value);
		$data['update'] = true;
		$this->header->index($this->active);
		$this->load->view('UserAdd', $data);
		$this->footer->index();
 	}

	public function userUpdate()
	{
		 $user_type = isset($_POST['user_type']) ? $_POST['user_type'] : "";
		 $user_fname = isset($_POST['first_name']) ? $_POST['first_name'] : "";
		 $user_lname = isset($_POST['last_name']) ? $_POST['last_name'] : "";
		 $user_email_id = isset($_POST['email_id']) ? $_POST['email_id'] : "";
		 $user_dob = isset($_POST['user_dob']) ? $_POST['user_dob'] : "";
		 $user_name = isset($_POST['user_name']) ? $_POST['user_name'] : "";
		 $password = isset($_POST['password']) ? $_POST['password'] : "";
		 $mob_no = isset($_POST['mob_no']) ? $_POST['mob_no'] : "";
		 $profilephoto = isset($_FILES['profilephoto']) ? $_FILES['profilephoto'] : "";
		 $user_status = isset($_POST['user_status']) ? $_POST['user_status'] : "0";
		 $user_photo_old = isset($_POST['user_image']) ? $_POST['user_image'] : "0";
		 $curr_user_id = isset($_POST['user_id']) ? $_POST['user_id'] : "0";
		 $user_id = 0;
		 if(isset($_SESSION['userId']) && !empty($_SESSION['userId'])) {
			$user_id = $_SESSION['userId'];
		}

			$select = '*';
			$tableName = 'users_master';
			$column = 'user_id';
			$value = $curr_user_id;
			$user_data = $this->helper_model->select($select, $tableName, $column, $value);

			if($user_data[0]->password == $password) {
				$password = $password;
			} else {
				$password = md5($password);
			}

			$isfile=basename($_FILES['profilephoto']['name']);
			$newname=$isfile;
			$sizeinmb=25;
			$user_profile_photo=FILE_UPLOAD.$user_fname."_".$newname;

			if(!isset($newname) || empty($newname)) {
			$user_profile_photo = $user_photo_old;
			}

			  $user = array(
			'user_id' => $_POST['user_id'],
			'user_first_name' => $_POST['first_name'],
			'user_last_name' => $_POST['last_name'],
			'user_email_id' => $_POST['email_id'],
			'user_dob' => $_POST['user_dob'],
			'user_name' => $_POST['user_name'],
			'password' => $password,
			'user_mobile_number' => $_POST['mob_no'],
			'user_profile_photo' => $user_profile_photo,
			'status' => $user_status,
			'updated_by' => $user_id,
			'updated_on' => date('Y-m-d h:i:s')
			);

			if($isfile!=''){

			echo $imgerr=$this->helper_model->do_upload($_FILES['profilephoto']['name'],$_FILES['profilephoto']['tmp_name'],$sizeinmb,$newname,$user_fname);
			}

		$tableName = 'users_master';
		$column = 'user_id';
		$value = $_POST['user_id'];

		$result = $this->helper_model->update($tableName, $user, $column, $value);

		$selectcust='cust_email_id';
		$tablecust='customer_master';
		$columncust='cust_email_id';
		$valuecust=	$_POST['email_id'];
		$check_user_cust=$this->helper_model->select($selectcust, $tablecust, $columncust, $valuecust);

		if(!empty($check_user_cust))
		{
			$cust=array(
				'cust_first_name' => $_POST['first_name'],
				'cust_last_name' => $_POST['last_name'],
				'cust_email_id' => $_POST['email_id'],
				'cust_password' => $password,
				'cust_mobno' => $_POST['mob_no'],
				'status' => $user_status,
				'updated_by'=> 1,
				'updated_on' => date("Y-m-d h:i:s")
				);
			$this->helper_model->update($tablecust, $cust, $columncust, $valuecust);
		}

		if($result == true){
			$response['success'] = true;
			$response['successMsg'] = "Record Updated";
			$response['redirect'] = base_url()."user/viewuser";
        }else{
        	$response['success'] = false;
			$response['successMsg'] = "Something wrong please try again";
        }

        echo json_encode($response);
 	}

	public function userDelete()
	{
        $user_id = $_POST['id'];
        $resultMaster = $this->helper_model->delete('users_master','user_id',$user_id);
        if($resultMaster != false){

        	$response['success'] = true;
			$response['successMsg'] = "Record Deleted";
        }else{
        	$response['success'] = false;
			$response['successMsg'] = "Something wrong please try again";
        }
        echo json_encode($response);
 	}
}