text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.IO.Compression;
using System.Threading;
using System.Runtime.Serialization.Json;

using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Forms;

using DAQ;
using DAQ.HAL;
using DAQ.Environment;
using DAQ.Analog;

namespace MOTMaster
{
    public class MMDataIOHelper
    {
        MMDataZipper zipper = new MMDataZipper();
        private string motMasterDataPath;
        private string element;
        string[] files;

        public MMDataIOHelper(string motMasterDataPath, string element)
        {
            this.motMasterDataPath = motMasterDataPath;
            this.element = element;
        }

        public void StoreRun(string saveFolder, int batchNumber, string pathToPattern, string pathToHardwareClass,
            MOTMasterSequence sequence, Dictionary<String, Object> dict, Dictionary<String, Object> report,
            string cameraAttributesPath, byte[][,] imageData, string externalFilesPath, string externalFilePattern)
        {
            string fileTag = getDataID(saveFolder, element, batchNumber);
            string ToFFilesPath = (string)DAQ.Environment.Environs.FileSystem.Paths["ToFFilesPath"];

            saveCameraData(fileTag, saveFolder, cameraAttributesPath, imageData);
            saveToFiles(fileTag, saveFolder, batchNumber, pathToPattern, pathToHardwareClass, dict, report, sequence);

            string[] datafiles = Directory.GetFiles(saveFolder, fileTag + "*");

            files = datafiles;
            AddFilesToZip(externalFilesPath, externalFilePattern);
            AddFilesToZip(ToFFilesPath, "*.txt");

            string[] filesCopied = putCopiesOfFilesToZip(saveFolder, fileTag, externalFilesPath, externalFilePattern);

            deleteFiles(files);

        }
        public void StoreRun(string saveFolder, int batchNumber, string pathToPattern, string pathToHardwareClass,
            MOTMasterSequence sequence, Dictionary<String, Object> dict, Dictionary<String, Object> report, string externalFilesPath, string externalFilePattern)
        {
            string fileTag = getDataID(saveFolder, element, batchNumber);
            string ToFFilesPath = (string)DAQ.Environment.Environs.FileSystem.Paths["ToFFilesPath"];

            saveToFiles(fileTag, saveFolder, batchNumber, pathToPattern, pathToHardwareClass, dict, report, sequence);

            string[] datafiles = Directory.GetFiles(saveFolder, fileTag + "*");
            files = datafiles;
            AddFilesToZip(externalFilesPath, externalFilePattern);
            AddFilesToZip(ToFFilesPath, "*.txt");

            string[] filesCopied = putCopiesOfFilesToZip(saveFolder, fileTag, externalFilesPath, externalFilePattern);

            deleteFiles(files);

        }
        private void deleteFiles(string[] files)
        {
            foreach (string s in files)
            {
                File.Delete(s);
            }
        }

        private void AddFilesToZip(string externalFilesPath, string externalFilePattern)
        {
            if (externalFilesPath != null && externalFilePattern != null)
            {
                string[] externalFiles = Directory.GetFiles(externalFilesPath, externalFilePattern);
                files = files.Concat(externalFiles).ToArray();
            }
        }

        // fileTag is the name tag of the files generated by MOTMaster.
        // externalFilePattern is a filename pattern for files generated by external programs to be zipped up with all the other files (e.g. "*.tif" for image files generated by an external camera control program)
        private string[] putCopiesOfFilesToZip(string saveFolder, string fileTag, string externalFilesPath, string externalFilePattern)
        {

            System.IO.FileStream fs = new FileStream(saveFolder + fileTag + ".zip", FileMode.Create);
            zipper.PrepareZip(fs);
            foreach (string s in files)
            {
                zipper.AppendToZip(s);
            }
            zipper.CloseZip();
            fs.Close();
            return files;
        }

        private void saveCameraData(string fileTag, string saveFolder, string cameraAttributesPath, byte[][,] imageData)
        {
            storeCameraAttributes(saveFolder + fileTag + "_cameraParameters.txt", cameraAttributesPath);
            storeImage(saveFolder + fileTag, imageData);
        }

        private void saveToFiles(string fileTag, string saveFolder, int batchNumber, string pathToPattern, string pathToHardwareClass,
            Dictionary<String, Object> dict, Dictionary<String, Object> report, MOTMasterSequence sequence)
        {
            storeDigitalPattern(saveFolder + fileTag + "_digitalPattern.json", sequence);
            storeAnalogPattern(saveFolder + fileTag, sequence);
            storeDictionary(saveFolder + fileTag + "_parameters.txt", dict);
            File.Copy(pathToPattern, saveFolder + fileTag + "_script.cs");
            File.Copy(pathToHardwareClass, saveFolder + fileTag + "_hardwareClass.cs");
            storeDictionary(saveFolder + fileTag + "_hardwareReport.txt", report);
        }

        public string SelectSavedScriptPathDialog()
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Filter = "DataSets|*.zip";
            dialog.Title = "Load previously saved pattern";
            dialog.Multiselect = false;
            dialog.InitialDirectory = motMasterDataPath;
            dialog.ShowDialog();
            return dialog.FileName;
        }

        public void UnzipFolder(string path)
        {
            zipper.Unzip(path);
        }

        public Dictionary<string, object> LoadDictionary(string dictionaryPath)
        {
            string[] parameterStrings = File.ReadAllLines(dictionaryPath);
            Dictionary<string, object> dict = new Dictionary<string, object>();
            char separator = '\t';
            foreach (string str in parameterStrings)
            {
                string[] keyValuePairs = str.Split(separator);
                Type t = System.Type.GetType(keyValuePairs[2]);
                dict.Add(keyValuePairs[0], Convert.ChangeType(keyValuePairs[1], t));
            }
            return dict;
        }

        public void DisposeReplicaScript(string folderPath)
        {
            Directory.Delete(folderPath, true);
        }

        private void storeCameraAttributes(string savePath, string attributesPath)
        {
            File.Copy(attributesPath, savePath);
        }

        private void storeImage(string savePath, byte[][,] imageData)
        {
            for (int i = 0; i < imageData.Length; i++)
            {
                storeImage(savePath + "_" + i.ToString(), imageData[i]);
            }
        }

        private void storeImage(string savePath, byte[,] imageData)
        {
            int width = imageData.GetLength(1);
            int height = imageData.GetLength(0);
            byte[] pixels = new byte[width * height];
            for (int j = 0; j < height; j++)
            {
                for (int i = 0; i < width; i++)
                {
                    pixels[(width * j) + i] = imageData[j, i];
                }
            }
            // Define the image palette
            BitmapPalette myPalette = BitmapPalettes.Gray256Transparent;

            // Creates a new empty image with the pre-defined palette

            BitmapSource image = BitmapSource.Create(
                width,
                height,
                96,
                96,
                PixelFormats.Indexed8,
                myPalette,
                pixels,
                width);

            FileStream stream = new FileStream(savePath + ".png", FileMode.Create);
            PngBitmapEncoder encoder = new PngBitmapEncoder();
            encoder.Interlace = PngInterlaceOption.On;
            encoder.Frames.Add(BitmapFrame.Create(image));
            encoder.Save(stream);
            stream.Dispose();

        }

        private void storeDictionary(String dataStoreFilePath, Dictionary<string, object> dict)
        {
            if (dict != null)
            {
                TextWriter output = File.CreateText(dataStoreFilePath);
                foreach (KeyValuePair<string, object> pair in dict)
                {
                    output.Write(pair.Key);
                    output.Write('\t');
                    output.Write(pair.Value.ToString());
                    output.Write('\t');
                    output.WriteLine(pair.Value.GetType());
                }
                output.Close();
            }

        }

        private void storeDigitalPattern(string dataStoreFilePath, MOTMasterSequence sequence)
        {
            Hashtable digitalChannelsHash = DAQ.Environment.Environs.Hardware.DigitalOutputChannels;

            string patternGeneratorBoard = (string)DAQ.Environment.Environs.Hardware.GetInfo("PatternGeneratorBoard");
            Dictionary<string, string> additionalPGs = (Dictionary<string, string>)DAQ.Environment.Environs.Hardware.GetInfo("AdditionalPatternGeneratorBoards");
            Dictionary<string, int> digitalChannels = new Dictionary<string,int>();
            string digitalPatternString;
            Dictionary<string, int>[] additionaldigitalChannels = new Dictionary<string,int>[additionalPGs.Count];
            string[] additionaldigitalPatternString = new string[additionalPGs.Count];
            int pgIndex;

            for (int i = 0; i < additionalPGs.Count; i++)
                additionaldigitalChannels[i] = new Dictionary<string, int>();

            foreach (DictionaryEntry pair in digitalChannelsHash)
            {

                if (((DigitalOutputChannel)pair.Value).Device == patternGeneratorBoard)
                    digitalChannels.Add((string)pair.Key, ((DigitalOutputChannel)pair.Value).BitNumber);
                else
                {
                    pgIndex = 0;
                    foreach (string pg in additionalPGs.Values)
                    {
                        if (((DigitalOutputChannel)pair.Value).Device == pg && sequence.DigitalPattern.Boards.Keys.Contains<string>(pg))
                            additionaldigitalChannels[pgIndex].Add((string)pair.Key, ((DigitalOutputChannel)pair.Value).BitNumber);
                        pgIndex++;
                    }
                }
            }

            var settings = new DataContractJsonSerializerSettings();
            settings.UseSimpleDictionaryFormat = true; // Make format of json file {key : value} instead of {"Key": key, "Value": value}
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Dictionary<string, int>), settings);

            digitalPatternString = sequence.DigitalPattern.Boards[patternGeneratorBoard].Layout.ToString();

            TextWriter output = File.CreateText(dataStoreFilePath);
            output.Write("{\"" + patternGeneratorBoard + "\":");
            output.Write("{");
            output.Write("\"channels\":");
            using (MemoryStream ms = new MemoryStream())
            {
                serializer.WriteObject(ms, digitalChannels);
                output.Write(Encoding.Default.GetString(ms.ToArray()));
            }

            output.Write(",");
            output.Write("\"pattern\":");
            output.Write("\"");
            output.Write(System.Web.HttpUtility.JavaScriptStringEncode(digitalPatternString));
            output.Write("\"");

            output.Write("}");
            output.Write("}");

            output.Write("\n");

            pgIndex = 0;
            foreach (string pg in additionalPGs.Values)
            {
                if (sequence.DigitalPattern.Boards.Keys.Contains<string>(pg))
                {
                    additionaldigitalPatternString[pgIndex] = sequence.DigitalPattern.Boards[pg].Layout.ToString();
                    output.Write("{\"" + pg + "\":");
                    output.Write("{");
                    output.Write("\"channels\":");
                    using (MemoryStream ms = new MemoryStream())
                    {
                        serializer.WriteObject(ms, additionaldigitalChannels[pgIndex]);
                        output.Write(Encoding.Default.GetString(ms.ToArray()));
                    }

                    output.Write(",");
                    output.Write("\"pattern\":");
                    output.Write("\"");
                    output.Write(System.Web.HttpUtility.JavaScriptStringEncode(additionaldigitalPatternString[pgIndex]));
                    output.Write("\"");

                    output.Write("}");
                    output.Write("}");
                }
            }

            output.Close();
        }

        private void storeAnalogPattern(string dataStoreFilePath, MOTMasterSequence sequence)
        {
            foreach (KeyValuePair<string, AnalogPatternBuilderSingleBoard> kvp in sequence.AnalogPattern.Boards)
            {
                Dictionary<String, Dictionary<Int32, Double>> analogPatterns = kvp.Value.AnalogPatterns;
                var settings = new DataContractJsonSerializerSettings();
                settings.UseSimpleDictionaryFormat = true; // Make format of json file {key : value} instead of {"Key": key, "Value": value}

                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Dictionary<String, Dictionary<Int32, Double>>), settings);
                string singleDataStoreFilePath = dataStoreFilePath + "_" + kvp.Key.Split('/')[1] + "_analogPattern.json";

                TextWriter output = File.CreateText(singleDataStoreFilePath);
                using (MemoryStream ms = new MemoryStream())
                {
                    serializer.WriteObject(ms, analogPatterns);
                    output.Write(Encoding.Default.GetString(ms.ToArray()));
                    output.Close();
                }
            }
        }

        private string getDataID(string directory, string element, int batchNumber)
        {
            DateTime dt = DateTime.Now;
            string dateTag;
            string batchTag;
            int subTag = 0;

            dateTag = String.Format("{0:ddMMMyy}", dt);
            batchTag = batchNumber.ToString().PadLeft(2, '0');
            subTag = (Directory.GetFiles(directory, element +
                dateTag + batchTag + "*.zip")).Length;
            string id = element + dateTag + batchTag
                + "_" + subTag.ToString().PadLeft(3, '0');
            return id;
        }

    }
}


text:
Overview
========

PETSc_ is a suite of data structures and routines for the
scalable (parallel) solution of scientific applications modeled by
partial differential equations. It employs the MPI_ standard for all
message-passing communication.

PETSc is intended for use in large-scale application projects
[petsc-efficient]_, and several ongoing computational science projects
are built around the PETSc libraries. With strict attention to
component interoperability, PETSc facilitates the integration of
independently developed application modules, which often most
naturally employ different coding styles and data structures.

PETSc is easy to use for beginners [petsc-user-ref]_. Moreover, its
careful design allows advanced users to have detailed control over the
solution process. PETSc includes an expanding suite of parallel linear
and nonlinear equation solvers that are easily used in application
codes written in C, C++, and Fortran. PETSc provides many of the
mechanisms needed within parallel application codes, such as simple
parallel matrix and vector assembly routines that allow the overlap of
communication and computation.

.. [petsc-user-ref] Satish Balay, Kris Buschelman, Victor Eijkhout,
   William D. Gropp, Dinesh Kaushik, Matthew G. Knepley, Lois Curfman
   McInnes, Barry F. Smith and Hong Zhang. PETSc Users
   Manual. ANL-95/11 - Revision 2.1.5. Argonne National
   Laboratory. 2004

.. [petsc-efficient] Satish Balay, Victor Eijkhout, William D. Gropp,
   Lois Curfman McInnes and Barry F. Smith. Efficient Management of
   Parallelism in Object Oriented Numerical Software Libraries. Modern
   Software Tools in Scientific Computing. E. Arge, A. M. Bruaset and
   H. P. Langtangen, editors. 163--202. Birkhauser Press. 1997.

.. include:: links.txt

Components
----------

PETSc is designed with an object-oriented style. Almost all
user-visible types are abstract interfaces with implementations that
may be chosen at runtime. Those objects are managed through handles to
opaque data structures which are created, accessed and destroyed by
calling appropriate library routines.

PETSc consists of a variety of components. Each component manipulates
a particular family of objects and the operations one would like to
perform on these objects. These components provide the functionality
required for many parallel solutions of PDEs.

:Vec:  Provides the vector operations required for setting up and
       solving large-scale linear and nonlinear problems. Includes
       easy-to-use parallel scatter and gather operations, as well as
       special-purpose code for handling ghost points for regular data
       structures.

:Mat:  A large suite of data structures and code for the manipulation
       of parallel sparse matrices. Includes four different parallel
       matrix data structures, each appropriate for a different class
       of problems.

:PC:   A collection of sequential and parallel preconditioners,
       including (sequential) ILU(k), LU, and (both sequential and
       parallel) block Jacobi, overlapping additive Schwarz methods
       and (through BlockSolve95) ILU(0) and ICC(0).

:KSP:  Parallel implementations of many popular Krylov subspace
       iterative methods, including GMRES, CG, CGS, Bi-CG-Stab, two
       variants of TFQMR, CR, and LSQR. All are coded so that they are
       immediately usable with any preconditioners and any matrix data
       structures, including matrix-free methods.

:SNES: Data-structure-neutral implementations of Newton-like methods
       for nonlinear systems. Includes both line search and trust
       region techniques with a single interface. Employs by default
       the above data structures and linear solvers. Users can set
       custom monitoring routines, convergence criteria, etc.

:TS:   Code for the time evolution of solutions of PDEs. In addition,
       provides pseudo-transient continuation techniques for computing
       steady-state solutions.

redpajama_set_name: RedPajamaGithub


text:
void hls_func(uint16 volatile const *pSrcBuffer,
			  uint16 volatile *pDestBuffer
			  );

void expected(uint16 const *pSrcBuffer,
			  uint16 *pDestBuffer
			  );
#endif	// !DESIGN_COMMON_H


text:
@interface WBEmotion : NSObject

@property (nonatomic, copy) NSString *chs;

@property (nonatomic, copy) NSString *png;

@property (nonatomic, copy) NSString *code;
@end


text:
package com.xeiam.xchange.vircurex;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.xeiam.xchange.currency.CurrencyPair;
import com.xeiam.xchange.dto.Order.OrderType;
import com.xeiam.xchange.dto.account.AccountInfo;
import com.xeiam.xchange.dto.trade.LimitOrder;
import com.xeiam.xchange.dto.trade.Wallet;
import com.xeiam.xchange.vircurex.dto.account.VircurexAccountInfoReturn;
import com.xeiam.xchange.vircurex.dto.trade.VircurexOpenOrder;

/**
 * Various adapters for converting from Vircurex DTOs to XChange DTOs
 */
public final class VircurexAdapters {

  private static SimpleDateFormat vircurexDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");

  /**
   * private Constructor
   */
  private VircurexAdapters() {

  }

  public static LimitOrder adaptOrder(BigDecimal amount, BigDecimal price, CurrencyPair currencyPair, OrderType orderType, String id) {

    // place a limit order
    return new LimitOrder(orderType, amount, currencyPair, "", null, price);
  }

  public static List<LimitOrder> adaptOrders(List<BigDecimal[]> someOrders, CurrencyPair currencyPair, String orderTypeString, String id) {

    List<LimitOrder> limitOrders = new ArrayList<LimitOrder>();
    OrderType orderType = orderTypeString.equalsIgnoreCase("bid") ? OrderType.BID : OrderType.ASK;

    for (BigDecimal[] order : someOrders) {
      limitOrders.add(adaptOrder(order[1], order[0], currencyPair, orderType, id));
    }

    return limitOrders;
  }

  public static AccountInfo adaptAccountInfo(VircurexAccountInfoReturn vircurexAccountInfo) {

    List<Wallet> wallets = new ArrayList<Wallet>();
    Map<String, Map<String, BigDecimal>> funds = vircurexAccountInfo.getAvailableFunds();

    for (String lcCurrency : funds.keySet()) {
      String currency = lcCurrency.toUpperCase();
      wallets.add(new Wallet(currency, funds.get(lcCurrency).get("availablebalance")));
    }
    return new AccountInfo(vircurexAccountInfo.getAccount(), wallets);
  }

  public static List<LimitOrder> adaptOpenOrders(List<VircurexOpenOrder> openOrders) {

    ArrayList<LimitOrder> adaptedOrders = new ArrayList<LimitOrder>();

    for (VircurexOpenOrder vircurexOpenOrder : openOrders) {

      OrderType orderType = vircurexOpenOrder.getOrderType().equalsIgnoreCase(VircurexUtils.BID) ? OrderType.BID : OrderType.ASK;

      Date timeStamp;

      try {
        timeStamp = vircurexDateFormat.parse(vircurexOpenOrder.getReleaseDate());
      } catch (ParseException e) {
        timeStamp = null;
      }

      adaptedOrders.add(new LimitOrder(orderType, BigDecimal.ONE, new CurrencyPair(vircurexOpenOrder.getBaseCurrency(), vircurexOpenOrder
          .getCounterCurrency()), vircurexOpenOrder.getOrderId(), timeStamp, vircurexOpenOrder.getUnitPrice()));
    }

    return adaptedOrders;
  }
}


text:
'use strict';
var me = module.exports
var {access, namespace, assign, escapeKey} = require('@evoja/ns-plain')

/**
 * A quick way to throw message if condition is incorrect
 */
me.evAssert = function evAssert(isTrue, message, Constuctor = Error) {
  if (!isTrue) {
    throw new Constuctor(message);
  }
};

/**
 * Composition of functions
 */
me.comp = function(...funs) {
  return function (...args) {
    return Array.prototype.reduce.call(
      funs,
      (prev, fun) => [fun.apply(this, prev)],
      args)[0]
  }
}

me.ActionToNamespaceException = function ActionToNamespaceException(message, action, template) {
  Error.apply(this, arguments)
}

/**
 * Gets the template like "a.b.{y}.d.{x}" and action like {x: 10, y: 'hello'}.
 * Returns the namespace by substitution `{...}` fields with values from the action.
 * Example return: "a.b.hello.d.10"
 *
 * Actually this is an action extractor.
 */
me.actionToNamespace = (template) => (action) => {
  return (template.match(/\{\w+(?:\.\w+)*\}/g) || []) // => ['{a}, {b.c}']
    .map(me.comp(
        (str) => str.substring(1, str.length -1), // => ['a', 'b.c']
        (name) => ['{' + name + '}', access(name, action)] // => [['{a}', action.a], ['{b.c}', action.b.c]]
      ))
    .reduce(function(tpl, [ptr, val]) {
        if (typeof val != 'string' && typeof val != 'number') {
         throw new me.ActionToNamespaceException('action does not match to template ' + action + ', ' + template)
        }
        if (typeof val == 'string') {
          val = escapeKey(val)
        }
        return tpl.replace(new RegExp(ptr, 'g'), val)
      },
      template)

}

/**
 * Creates action extractor.
 * Gets the template like "a.b.{x}".
 * Returns the method: (action) => namespace
 */
me.createExtractor = (template) => {
  if (template == '') {
    return (state, action) => state
  }
  var namespacer = me.actionToNamespace(template);
  return (state, action) => access(namespacer(action), state)
}

/**
 * Creates state replacer.
 * Gets the template like "a.b.{x}".
 * Returns the method (state, data, action) => new_state
 *
 * Example:
 *   var replacer = createReplacer('{x}');
 *   var state = {a: 10, b: 20}
 *   var data = 1
 *   var action1 = {x: 'a'}
 *   var action2 = {x: 'b'}
 *   var state1 = replacer(state, data, action1) // {a: 1, b: 20}
 *   var state2 = replacer(state, data, action2) // {a: 10, b: 1}
 *
 */
me.createReplacer = (template) => {
  if (template == '') {
    return (state, data, action) => data
  }
  var namespacer = me.actionToNamespace(template)
  return (state, data, action) => assign(namespacer(action), state, data)
}


text:
					            List of Reported Bed

                    Bed ID
                    Room Type
                    Room Location
                    Status
                    Action

                <?php
                  foreach($roomlist as $room){
                    echo "
";
                      echo "".$room['bed_id']."	";
                      echo "".$room['room_name']."	";
                      echo "".$room['room_location']."	";
                      echo "";
                        if($room['bed_maintenance'] == 1){
                          echo "FOR CLEANING";
                        }else if($room['bed_maintenance'] == 2){
                          echo "FOR MAINTENANCE";
                        }
                      echo "	";
                      echo "";
                        echo "Mark as Done";
                      echo "	";
                    echo "
";
                  }
                ?>


text:
<!DOCTYPE html>
<html>
  <body>
    <script runat="server">
      // This is by no means a comprehensive test suite, just some examples that
      // cover common cases.

      // Do not load the Jaxer client framework
      Jaxer.response.setClientFramework(null);

      Jaxer.console.echo = true;
      Jaxer.console.time("t");

      Jaxer.console.log("Hello world!");
      Jaxer.console.log("Hello %s!", "world", 4, 4, 4);
      Jaxer.console.log("Hello %d!", 4, "How", "gosit?");
      Jaxer.console.log("Hello %i%d!", 4, 2);
      Jaxer.console.info("Multiple", "strings", "separated", 6);
      Jaxer.console.debug("Debug");
      Jaxer.console.warn("Warn");
      Jaxer.console.error("Error");

      Jaxer.console.time("u");
      Jaxer.console.group("Unimplemented");
      Jaxer.console.assert();
      Jaxer.console.dir();
      Jaxer.console.dirxml();
      Jaxer.console.profile();
      Jaxer.console.profileEnd();
      Jaxer.console.count();
      Jaxer.console.table();
      Jaxer.console.dump();
      Jaxer.console.groupEnd();
      Jaxer.console.timeEnd("u");

      Jaxer.console.log({ a : 1, b : 2 });

      try {
        throw new Error("Oh no!");
      } catch (e) { Jaxer.console.error(e); }

      Jaxer.console.timeEnd("t");
      Jaxer.console.time("t");

      Jaxer.console.disable();
      Jaxer.console.log("This", "should", "not", "show", "up");
      Jaxer.console.enable();
      Jaxer.console.log("This", "should", "be", "here");
      Jaxer.console.echo = true;
      Jaxer.console.log(Jaxer.console.echo);
      // Try a really long message
      // var s = ["a"]
      // s[50000] = "z";
      //Jaxer.console.log(s.join("~"));
      Jaxer.console.timeEnd("t");
      Jaxer.console.echo = false;
      Jaxer.console.log("Hi!");
    </script>
  </body>
</html>


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.qualcomm.ftcrobotcontroller"
    android:versionCode="7"
    android:versionName="1.6 DANK MEME EDITION" >

    <uses-sdk
        android:minSdkVersion="16"
        android:targetSdkVersion="19" />

    <uses-permission
        android:name="android.permission.ACCESS_WIFI_STATE"
        android:required="true" />
    <uses-permission
        android:name="android.permission.CHANGE_WIFI_STATE"
        android:required="true" />
    <uses-permission
        android:name="android.permission.WAKE_LOCK"
        android:required="true" />
    <uses-permission
        android:name="android.permission.ACCESS_NETWORK_STATE"
        android:required="true" />
    <uses-permission
        android:name="android.permission.CHANGE_NETWORK_STATE"
        android:required="true" />
    <uses-permission
        android:name="android.permission.INTERNET"
        android:required="true" />
    <uses-permission
        android:name="android.permission.WRITE_EXTERNAL_STORAGE"
        android:required="true" />
    <uses-permission
        android:name="android.permission.READ_EXTERNAL_STORAGE"
        android:required="true" />
    <uses-permission
        android:name="android.permission.WRITE_SETTINGS"
        android:required="true" />

    <uses-feature android:name="android.hardware.usb.accessory" />

    <application
        android:allowBackup="true"
        android:exported="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.qualcomm.ftcrobotcontroller.FtcRobotControllerActivity"
            android:configChanges="orientation|screenSize"
            android:label="@string/app_name"
            android:launchMode="singleTask" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
            </intent-filter>

            <meta-data
                android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"
                android:resource="@xml/device_filter" />
        </activity>
        <activity
            android:name="com.qualcomm.ftccommon.FtcRobotControllerSettingsActivity"
            android:exported="true"
            android:label="@string/settings_activity" >
            <intent-filter>
                <action android:name="com.qualcomm.ftccommon.FtcRobotControllerSettingsActivity.intent.action.Launch" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>

        <service
            android:name="com.qualcomm.ftccommon.FtcRobotControllerService"
            android:enabled="true" />

        <activity
            android:name="com.qualcomm.ftccommon.configuration.FtcLoadFileActivity"
            android:configChanges="orientation|screenSize"
            android:exported="true"
            android:label="@string/configure_activity" >
            <intent-filter>
                <action android:name="com.qualcomm.ftccommon.configuration.FtcLoadFileActivity.intent.action.Launch" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.qualcomm.ftccommon.FtcWifiChannelSelectorActivity"
            android:exported="true"
            android:label="@string/title_activity_wifi_channel_selector" >
            <intent-filter>
                <action android:name="com.qualcomm.ftccommon.FtcWifiChannelSelectorActivity.intent.action.Launch" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.qualcomm.ftccommon.ConfigWifiDirectActivity"
            android:exported="true"
            android:label="@string/title_activity_config_wifi_direct" />
        <activity
            android:name="com.qualcomm.ftccommon.ViewLogsActivity"
            android:configChanges="orientation|screenSize"
            android:label="@string/title_activity_view_logs" >
            <intent-filter>
                <action android:name="com.qualcomm.ftcrobotcontroller.VIEW_LOGS" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
            <intent-filter>
                <action android:name="com.qualcomm.ftccommon.ViewLogsActivity.intent.action.Launch" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.qualcomm.ftccommon.configuration.AutoConfigureActivity"
            android:configChanges="orientation|screenSize"
            android:exported="true"
            android:label="@string/title_activity_autoconfigure" >
            <intent-filter>
                <action android:name="com.qualcomm.ftccommon.configuration.FtcAutoconfigureActivity.intent.action.Launch" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.qualcomm.ftccommon.configuration.FtcConfigurationActivity"
            android:configChanges="orientation|screenSize"
            android:label="@string/app_name" >
        </activity>
        <activity
            android:name="com.qualcomm.ftccommon.AboutActivity"
            android:label="@string/about_activity" >
            <intent-filter>
                <action android:name="com.qualcomm.ftccommon.configuration.AboutActivity.intent.action.Launch" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.qualcomm.ftccommon.configuration.EditMotorControllerActivity"
            android:configChanges="orientation|screenSize"
            android:label="@string/edit_motor_controller_activity"
            android:windowSoftInputMode="stateHidden" >
        </activity>
        <activity
            android:name="com.qualcomm.ftccommon.configuration.EditServoControllerActivity"
            android:configChanges="orientation|screenSize"
            android:label="@string/edit_servo_controller_activity"
            android:windowSoftInputMode="stateHidden|adjustResize" >
        </activity>
        <activity
            android:name="com.qualcomm.ftccommon.configuration.EditLegacyModuleControllerActivity"
            android:configChanges="orientation|screenSize"
            android:label="@string/edit_legacy_module_controller_activity"
            android:windowSoftInputMode="stateHidden|adjustResize" >
        </activity>
        <activity
            android:name="com.qualcomm.ftccommon.configuration.EditMatrixControllerActivity"
            android:configChanges="orientation|screenSize"
            android:label="@string/edit_matrix_controller_activity"
            android:windowSoftInputMode="stateHidden|adjustResize" >
        </activity>
        <activity
            android:name="com.qualcomm.ftccommon.configuration.EditDeviceInterfaceModuleActivity"
            android:configChanges="orientation|screenSize"
            android:label="@string/edit_core_device_interface_module_controller_activity"
            android:windowSoftInputMode="stateHidden|adjustResize" >
        </activity>
        <activity
            android:name="com.qualcomm.ftccommon.configuration.EditPWMDevicesActivity"
            android:configChanges="orientation|screenSize"
            android:label="@string/edit_pwm_devices_activity"
            android:windowSoftInputMode="stateHidden|adjustResize" >
        </activity>
        <activity
            android:name="com.qualcomm.ftccommon.configuration.EditAnalogInputDevicesActivity"
            android:configChanges="orientation|screenSize"
            android:label="@string/edit_analog_input_devices_activity"
            android:windowSoftInputMode="stateHidden|adjustResize" >
        </activity>
        <activity
            android:name="com.qualcomm.ftccommon.configuration.EditDigitalDevicesActivity"
            android:configChanges="orientation|screenSize"
            android:label="@string/edit_digital_devices_activity"
            android:windowSoftInputMode="stateHidden|adjustResize" >
        </activity>
        <activity
            android:name="com.qualcomm.ftccommon.configuration.EditI2cDevicesActivity"
            android:configChanges="orientation|screenSize"
            android:label="@string/edit_i2c_devices_activity"
            android:windowSoftInputMode="stateHidden|adjustResize" >
        </activity>
        <activity
            android:name="com.qualcomm.ftccommon.configuration.EditAnalogOutputDevicesActivity"
            android:configChanges="orientation|screenSize"
            android:label="@string/edit_analog_output_devices_activity"
            android:windowSoftInputMode="stateHidden|adjustResize" >
        </activity>

        <uses-library android:name="android.test.runner" />
    </application>

</manifest>


text:
//
//  Starfield.h
//  Ribbons
//
//  Created by Bryce Matsumori on 11/12/14.
//
//

#ifndef __Ribbons__Starfield__
#define __Ribbons__Starfield__

#include "cinder/Color.h"
#include "cinder/gl/gl.h"
#include <vector>
#include "AudioProcessor.h"

struct Star {
#if VR
    ci::Vec3f pos;
#else
    ci::Vec2f pos;
#endif

    float radius;
    size_t binId;
};

class Starfield {
public:
    explicit Starfield();
    void setProcessor(AudioProcessor *processor);

    void update(float delta);
    void draw();

    void setOpacity(float opacity);

private:
    AudioProcessor *mProcessor;
    float mOpacity = 0;

    std::vector<Star> mStars;
};

#endif /* defined(__Ribbons__Starfield__) */


text:
package com.markjmind.markjbox.test;

public class Log {
	private static final String LOG_TAG = "javassist";

	public static void d(String format, Object...args) {
		android.util.Log.d(LOG_TAG, String.format(format, args));
	}

	public static void i(String format, Object...args) {
		android.util.Log.i(LOG_TAG, String.format(format, args));
	}

	public static void v(String format, Object...args) {
		android.util.Log.v(LOG_TAG, String.format(format, args));
	}

	public static void e(String format, Object...args) {
		android.util.Log.e(LOG_TAG, String.format(format, args));
	}

	public static void w(String format, Object...args) {
		android.util.Log.w(LOG_TAG, String.format(format, args));
	}

	public static void d(Throwable t, String format, Object...args) {
		android.util.Log.d(LOG_TAG, String.format(format, args), t);
	}

	public static void i(Throwable t, String format, Object...args) {
		android.util.Log.i(LOG_TAG, String.format(format, args), t);
	}

	public static void v(Throwable t, String format, Object...args) {
		android.util.Log.v(LOG_TAG, String.format(format, args), t);
	}

	public static void e(Throwable t, String format, Object...args) {
		android.util.Log.e(LOG_TAG, String.format(format, args), t);
	}

	public static void w(Throwable t, String format, Object...args) {
		android.util.Log.w(LOG_TAG, String.format(format, args), t);
	}
}


text:
import os, sys
import subprocess
import pprint as pp
import argparse
import json
from datetime import datetime, timedelta
from dateutil import tz

def get_branch_number(revision_number):
    try:
        revision = revision_number.split('.')
        revision[-1] = revision[-2]
        revision[-2] = '0'
        branch_number = '.'.join(revision)
    except IndexError as e:
        print e
        branch_number = None

    return branch_number

def get_branch_name(info):
    if info['head'] == info['revision']:
        return None

    branch_number = get_branch_number(info['revision'])
    for branch, number in info['symbolic names'].iteritems():
        if branch_number == number:
            return branch

    return None

def get_commit_date(line):
    """
    date: 2015-03-01 19:45:52 -0800;  author: alvin;  state: Exp;  lines: +1 -0;  commitid: 10054F3DCE94030CAE8;
    date: 2015-03-01 19:45:52 -0800;  author: alvin;  state: Exp;  commitid: 10054F3DCE94030CAE8;
    """

    commit = {}
    try:
        for line in line.split(';'):
            line = line.strip()
            if line == '':
                continue

            commit.update(get_dict(line))
    except IndexError as e:
        print e
        return None

    return commit

def get_dict(line, delimiter=':'):
    info = {}

    try:
        line = line.strip()
        line = line.split(delimiter, 1)
        key = line[0].strip()
        value = line[1:]
        value = ''.join(value)
        value = value.strip()
        info[key] = value
    except IndexError as e:
        print e
        return None

    return info

def get_rlog(filepath, revision):
    """
    Get cvs rlog information
    Input: filepath, revision_number
    Returns: Dictionary of cvs log information
    """

    cmd = "cvs rlog -r%s %s" % (revision, filepath)
    cmd = cmd.split()
    info = {}

    p = subprocess.Popen(cmd,stdout=subprocess.PIPE)
    begin_symbolic_names = False
    symbolic_names = {}
    end_of_file= False
    while not end_of_file:
        line = p.stdout.readline()
        if not line:
            break

        line = line.rstrip()

        if line.startswith('head:'):
            info.update(get_dict(line))
            continue

        if line.startswith('branch:'):
            info.update(get_dict(line))
            continue

        if line.startswith('locks:'):
            info.update(get_dict(line))
            continue

        if line.startswith('access list:'):
            info.update(get_dict(line))
            continue

        if line.startswith('symbolic names:'):
            info.update(get_dict(line))
            info['symbolic names'] = {}
            while True:
                line = p.stdout.readline()
                if not line:
                    end_of_file = True
                    break

                line = line.rstrip()

                if line.startswith('keyword substitution:'):
                    info.update(get_dict(line))
                    break

                info['symbolic names'].update(get_dict(line))

            continue

        if line.startswith('total revisions:'):
            info.update(get_dict(line))
            continue

        if line.startswith('revision'):
            info.update(get_dict(line, delimiter=' '))
            continue

        if line.startswith('date:'):
            cd = get_commit_date(line)
            info.update(cd)
            info['comment'] = []
            while True:
                line = p.stdout.readline()
                if not line:
                    end_of_file = True
                    break

                if line.startswith('Files Changed:'):
                    break

                line = line.strip()
                if line != '':
                    info['comment'].append(line)

            # remove last line in the comments if it contains ===
            if len(info['comment']) > 0 and info['comment'][-1].startswith('========'):
                info['comment'].pop()

            continue

    info['branch_name'] = get_branch_name(info)

    # kill process if it has not yet terminated
    if p.returncode is None:
        p.kill()

    return info

def get_history(start=None, files=None, branch=None, summary=False):
    cmd = 'cvs history -a -c'
    cmd = cmd.split()

    if start:
        cmd.append('-D')
        cmd.append(start)

        from_zone = tz.tzutc()
        to_zone = tz.tzlocal()
        d = datetime.strptime(start, '%Y-%m-%d %H:%M:%S')
        local_time = d.replace(tzinfo=from_zone).astimezone(to_zone)

    modules = []
    for f in files:
        if '/' not in f:
            f += '/'
        cmd.append(f)
        modules.append(f.split('/')[0])

    #print cmd
    if start:
        print "Retrieving commit history since %s. Please wait..." % (local_time)
    else:
        print "Retrieving all commit history. Please wait..."

    history = []
    p = subprocess.Popen(cmd,stdout=subprocess.PIPE)
    while True:
        line = p.stdout.readline()
        if not line:
            break

        c = {}
        line = line.strip()
        line = line.split()

        try:
            c['f_change'] = line[0]
            c['date'] = " ".join(line[1:4])
            c['author'] = line[4]
            c['version'] = line[5]
            c['filepath'] = os.path.join(line[7], line[6])
            history.append(c)
        except IndexError as e:
            continue

    # kill process if it has not yet terminated
    if p.returncode is None:
        p.kill()

    history = sorted(history, key=lambda k: k['date'], reverse=True)

    commit = {}
    for h in history:
        f_change = h['f_change']
        author = h['author']
        version = h['version']
        filepath = h['filepath']

        # discard files not belonging to module
        filepath_module = filepath.split('/')[0]
        if not filepath_module in modules:
            continue

        # skip if not trunk; this will speed up query
        if branch is None and len(version.split('.')) > 2:
            continue

        # get information about the file
        info = get_rlog(filepath, version)

        # skip if not the branch queried
        if branch != info['branch_name'] and f_change != 'R':
            continue

        commit_file = { 'filepath': filepath,
                        'version': version,
                        'date': info['date'],
                        'author': info['author'],
                        'commitid': info['commitid'],
                        'change': f_change, }

        commitid = info['commitid']
        # if a new commit date, create hash
        if commitid not in commit:
            commit[commitid] = {}
            commit[commitid]['commits'] = []
            # get Comment
            commit[commitid]['comment'] = info['comment']
            # get User
            commit[commitid]['author'] = author

            commit[commitid]['author'] = info['author']
            commit[commitid]['date'] = info['date']
            commit[commitid]['commitid'] = info['commitid']

        # Get the latest date
        if info['date'] > commit[commitid]['date']:
            commit[commitid]['date'] = info['date']

        # if commit is a removal of a file, don't use branch of commit
        if f_change == 'R':
            commit[commitid]['branch'] = branch
        else:
            commit[commitid]['branch'] = info['branch_name']

        # Set branch of commit
        if 'branch' not in commit[commitid]:
            commit[commitid]['branch'] = info['branch_name']

        if not summary:
            commit[commitid]['commits'].append(commit_file)

    # kill process if it has not yet terminated
    if p.returncode is None:
        p.kill()

    return commit

def display(history):
    history = sorted(history.items(), key=lambda (k,v): v['date'], reverse=True)
    for id,ac in history:
        if ac['branch']:
            branch = ac['branch']
        else:
            branch = 'trunk'

        print 'commit', ac['commitid'], ac['date'], ac['author'], branch
        print "%-7s %s" % ('Author:', ac['author'])
        print "%-7s %s" % ('Date:', ac['date'])
        print
        try:
            for m in ac['comment']:
                print "    %s" % m
            print

            if len(ac['commits']) > 0:
                for c in ac['commits']:
                    print "%-3s %-s %-18s %s %s" % (c['change'],
                                                    c['version'],
                                                    c['date'],
                                                    c['commitid'],
                                                    c['filepath'])
                print
        except Exception as e:
            print e

def main(args):
    files = args.files
    branch = args.branch

    if args.start_date:
        start_date = args.start_date
    elif args.days:
        d = datetime.utcnow() - timedelta(days=args.days)
        start_date = d.strftime('%Y-%m-%d %H:%M:%S')
    else:
        start_date = None

    history = get_history(start=start_date, files=files, branch=branch, summary=args.summary)

    if args.json:
        print json.dumps(history, sort_keys=True, indent=4)
    else:
        display(history)

def parse_cmdline():
    parser = argparse.ArgumentParser(description="Show history of cvs commits similar to git or svn")

    parser.add_argument('-n', '--days',
                        required=False,
                        action='store',
                        type=int,
                        help='Display commit history for the past n days. Warning: If not specified, it gets everything.')

    parser.add_argument('-d', '--start_date',
                        required=False,
                        action='store',
                        help='Display commit history from date in UTC. Format: yyyy-mm-dd hh:mm:ss')

    parser.add_argument('-b', '--branch',
                        required=False,
                        action='store',
                        help='CVS branch name. Omit to use main or trunk.')

    parser.add_argument('-s', '--summary',
                        action='store_true',
                        help='Summary only')

    parser.add_argument('--json',
                        action='store_true',
                        help='Display in JSON format')

    parser.add_argument('files',
                        metavar='file',
                        nargs='+',
                        help='CVS files to query.')

    args = parser.parse_args()
    return args

#-------------------------------------------------------------------------------
# START MAIN
#-------------------------------------------------------------------------------
if __name__ == '__main__':
    args = parse_cmdline()
    main(args)


text:
#region Copyright © 2008 Paul Welter. All rights reserved.

#endregion

using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using Microsoft.Win32;

namespace MSBuild.Community.Tasks.HtmlHelp
{
    /// <summary>
    /// A Html Help 2.0 compiler task.
    /// </summary>
    public class HxCompiler : ToolTask
    {
        #region Properties
        private ITaskItem _projectFile;

        /// <summary>
        /// Gets or sets the project file path.
        /// </summary>
        /// <value>The project file path.</value>
        [Required]
        public ITaskItem ProjectFile
        {
            get { return _projectFile; }
            set { _projectFile = value; }
        }

        private string _logFile;

        /// <summary>
        /// Gets or sets the log file.
        /// </summary>
        /// <value>The log file.</value>
        public string LogFile
        {
            get { return _logFile; }
            set { _logFile = value; }
        }

        private string _projectRoot;

        /// <summary>
        /// Gets or sets the project root.
        /// </summary>
        /// <value>The project root.</value>
        public string ProjectRoot
        {
            get { return _projectRoot; }
            set { _projectRoot = value; }
        }

        private ITaskItem _outputFile;

        /// <summary>
        /// Gets or sets the output file.
        /// </summary>
        /// <value>The output file.</value>
        public ITaskItem OutputFile
        {
            get { return _outputFile; }
            set { _outputFile = value; }
        }

        private bool _noInfoMessages;

        /// <summary>
        /// Gets or sets a value indicating whether no info messages will be output.
        /// </summary>
        /// <value><c>true</c> if no info messages; otherwise, <c>false</c>.</value>
        public bool NoInfoMessages
        {
            get { return _noInfoMessages; }
            set { _noInfoMessages = value; }
        }

        private bool _noWarningMessages;

        /// <summary>
        /// Gets or sets a value indicating whether no warning messages will be output.
        /// </summary>
        /// <value><c>true</c> if no warning messages; otherwise, <c>false</c>.</value>
        public bool NoWarningMessages
        {
            get { return _noWarningMessages; }
            set { _noWarningMessages = value; }
        }

        private bool _noErrorMessages;

        /// <summary>
        /// Gets or sets a value indicating whether no error messages will be output.
        /// </summary>
        /// <value><c>true</c> if no error messages; otherwise, <c>false</c>.</value>
        public bool NoErrorMessages
        {
            get { return _noErrorMessages; }
            set { _noErrorMessages = value; }
        }

        private bool _quiteMode;

        /// <summary>
        /// Gets or sets a value indicating quite mode.
        /// </summary>
        /// <value><c>true</c> if quite mode; otherwise, <c>false</c>.</value>
        public bool QuiteMode
        {
            get { return _quiteMode; }
            set { _quiteMode = value; }
        }

        private ITaskItem _uncompileFile;

        /// <summary>
        /// Gets or sets the uncompile file.
        /// </summary>
        /// <value>The uncompile file.</value>
        public ITaskItem UncompileFile
        {
            get { return _uncompileFile; }
            set { _uncompileFile = value; }
        }

        private string _uncompileDirectory;

        /// <summary>
        /// Gets or sets the uncompile directory.
        /// </summary>
        /// <value>The uncompile directory.</value>
        public string UncompileDirectory
        {
            get { return _uncompileDirectory; }
            set { _uncompileDirectory = value; }
        }
        #endregion

        /// <summary>
        /// Returns the fully qualified path to the executable file.
        /// </summary>
        /// <returns>
        /// The fully qualified path to the executable file.
        /// </returns>
        protected override string GenerateFullPathToTool()
        {
            string folder = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
            folder = Path.Combine(folder, @"Common Files\microsoft shared\Help 2.0 Compiler");

            if (Directory.Exists(folder))
                return Path.Combine(folder, ToolName);
            else
                return ToolName;
        }

        /// <summary>
        /// Gets the name of the executable file to run.
        /// </summary>
        /// <value></value>
        /// <returns>The name of the executable file to run.</returns>
        protected override string ToolName
        {
            get { return "hxcomp.exe"; }
        }

        /// <summary>
        /// Logs the starting point of the run to all registered loggers.
        /// </summary>
        /// <param name="message">A descriptive message to provide loggers, usually the command line and switches.</param>
        protected override void LogToolCommand(string message)
        {
            Log.LogCommandLine(MessageImportance.Low, message);
        }

        /// <summary>
        /// Gets the <see cref="T:Microsoft.Build.Framework.MessageImportance"></see> with which to log errors.
        /// </summary>
        /// <value></value>
        /// <returns>The <see cref="T:Microsoft.Build.Framework.MessageImportance"></see> with which to log errors.</returns>
        protected override MessageImportance StandardOutputLoggingImportance
        {
            get { return MessageImportance.Normal; }
        }

        /// <summary>
        /// Returns a string value containing the command line arguments to pass directly to the executable file.
        /// </summary>
        /// <returns>
        /// A string value containing the command line arguments to pass directly to the executable file.
        /// </returns>
        protected override string GenerateCommandLineCommands()
        {
            CommandLineBuilder builder = new CommandLineBuilder();
            builder.AppendSwitchIfNotNull("-p ", ProjectFile);
            builder.AppendSwitchIfNotNull("-l ", LogFile);
            builder.AppendSwitchIfNotNull("-r ", ProjectRoot);
            builder.AppendSwitchIfNotNull("-o ", OutputFile);
            if (NoInfoMessages)
                builder.AppendSwitch("-i");
            if (NoWarningMessages)
                builder.AppendSwitch("-w");
            if (NoErrorMessages)
                builder.AppendSwitch("-e");
            if (QuiteMode)
                builder.AppendSwitch("-q");
            builder.AppendSwitchIfNotNull("-u ", UncompileFile);
            builder.AppendSwitchIfNotNull("-d ", UncompileDirectory);

            return builder.ToString();
        }

        /// <summary>
        /// Handles execution errors raised by the executable file.
        /// </summary>
        /// <returns>
        /// true if the method runs successfully; otherwise, false.
        /// </returns>
        protected override bool HandleTaskExecutionErrors()
        {
            if (ExitCode != 0)
                Log.LogWarning("'{0}' exited with code {1}.", ToolName, ExitCode);

            //ignore exitcode
            return !Log.HasLoggedErrors;
        }

    }
}


text:
package ru.extas.web.commons.component;

import com.vaadin.ui.Component;
import com.vaadin.ui.CssLayout;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import ru.extas.web.commons.ExtaTheme;

/**
 * @author Valery Orlov
 *         Date: 11.09.2014
 *         Time: 15:13
 */
public class CardPanel extends CssLayout {

    private final Label label;
    private final HorizontalLayout panelCaption;

    public CardPanel(final String caption, final Component action, final Component panelContent) {
        addStyleName(ExtaTheme.LAYOUT_CARD);
        panelCaption = new HorizontalLayout();
        panelCaption.addStyleName("v-panel-caption");
        panelCaption.setWidth(100, Unit.PERCENTAGE);
        label = new Label(caption);
        panelCaption.addComponent(label);
        panelCaption.setExpandRatio(label, 1);
        panelCaption.addComponent(action);

        addComponent(panelCaption);
        addComponent(panelContent);
    }
}


text:
/** @fileOverview CBC mode implementation
 *
 * @author Emily Stark
 * @author Mike Hamburg
 * @author Dan Boneh
 */

if (sjcl.beware === undefined) {
  sjcl.beware = {};
}
sjcl.beware["CBC mode is dangerous because it doesn't protect message integrity."
] = function() {
  /** @namespace
   * Dangerous: CBC mode with PKCS#5 padding.
   *
   * @author Emily Stark
   * @author Mike Hamburg
   * @author Dan Boneh
   */
  sjcl.mode.cbc = {
    /** The name of the mode.
     * @constant
     */
    name: "cbc",

    /** Encrypt in CBC mode with PKCS#5 padding.
     * @param {Object} prp The block cipher.  It must have a block size of 16 bytes.
     * @param {bitArray} plaintext The plaintext data.
     * @param {bitArray} iv The initialization value.
     * @param {bitArray} [adata=[]] The authenticated data.  Must be empty.
     * @return The encrypted data, an array of bytes.
     * @throws {sjcl.exception.invalid} if the IV isn't exactly 128 bits, or if any adata is specified.
     */
    encrypt: function(prp, plaintext, iv, adata) {
      if (adata && adata.length) {
        throw new sjcl.exception.invalid("cbc can't authenticate data");
      }
      if (sjcl.bitArray.bitLength(iv) !== 128) {
        throw new sjcl.exception.invalid("cbc iv must be 128 bits");
      }
      var i,
          w = sjcl.bitArray,
          xor = w._xor4,
          bl = w.bitLength(plaintext),
          bp = 0,
          output = [];

      if (bl&7) {
        throw new sjcl.exception.invalid("pkcs#5 padding only works for multiples of a byte");
      }

      for (i=0; bp+128 <= bl; i+=4, bp+=128) {
        /* Encrypt a non-final block */
        iv = prp.encrypt(xor(iv, plaintext.slice(i,i+4)));
        output.splice(i,0,iv[0],iv[1],iv[2],iv[3]);
      }

      /* Construct the pad. */
      bl = (16 - ((bl >> 3) & 15)) * 0x1010101;

      /* Pad and encrypt. */
      iv = prp.encrypt(xor(iv,w.concat(plaintext,[bl,bl,bl,bl]).slice(i,i+4)));
      output.splice(i,0,iv[0],iv[1],iv[2],iv[3]);
      return output;
    },

    /** Decrypt in CBC mode.
     * @param {Object} prp The block cipher.  It must have a block size of 16 bytes.
     * @param {bitArray} ciphertext The ciphertext data.
     * @param {bitArray} iv The initialization value.
     * @param {bitArray} [adata=[]] The authenticated data.  It must be empty.
     * @return The decrypted data, an array of bytes.
     * @throws {sjcl.exception.invalid} if the IV isn't exactly 128 bits, or if any adata is specified.
     * @throws {sjcl.exception.corrupt} if if the message is corrupt.
     */
    decrypt: function(prp, ciphertext, iv, adata) {
      if (adata && adata.length) {
        throw new sjcl.exception.invalid("cbc can't authenticate data");
      }
      if (sjcl.bitArray.bitLength(iv) !== 128) {
        throw new sjcl.exception.invalid("cbc iv must be 128 bits");
      }
      if ((sjcl.bitArray.bitLength(ciphertext) & 127) || !ciphertext.length) {
        throw new sjcl.exception.corrupt("cbc ciphertext must be a positive multiple of the block size");
      }
      var i,
          w = sjcl.bitArray,
          xor = w._xor4,
          bi, bo,
          output = [];

      adata = adata || [];

      for (i=0; i<ciphertext.length; i+=4) {
        bi = ciphertext.slice(i,i+4);
        bo = xor(iv,prp.decrypt(bi));
        output.splice(i,0,bo[0],bo[1],bo[2],bo[3]);
        iv = bi;
      }

      /* check and remove the pad */
      bi = output[i-1] & 255;
      if (bi === 0 || bi > 16) {
        throw new sjcl.exception.corrupt("pkcs#5 padding corrupt");
      }
      bo = bi * 0x1010101;
      if (!w.equal(w.bitSlice([bo,bo,bo,bo], 0, bi*8),
                   w.bitSlice(output, output.length*32 - bi*8, output.length*32))) {
        throw new sjcl.exception.corrupt("pkcs#5 padding corrupt");
      }

      return w.bitSlice(output, 0, output.length*32 - bi*8);
    }
  };
};


text:
  do {                                                                \
    if (device_->Ioctl(type, arg) != 0) {                             \
      PLOG(ERROR) << __func__ << "(): ioctl() failed: " << type_name; \
      PostNotifyError(kInvalidBitstreamBufferId, PLATFORM_FAILURE);   \
      return value;                                                   \
    }                                                                 \
  } while (0)

#define IOCTL_OR_ERROR_RETURN(type, arg) \
  IOCTL_OR_ERROR_RETURN_VALUE(type, arg, ((void)0), #type)

#define IOCTL_OR_ERROR_RETURN_FALSE(type, arg) \
  IOCTL_OR_ERROR_RETURN_VALUE(type, arg, false, #type)

#define IOCTL_OR_LOG_ERROR(type, arg)                               \
  do {                                                              \
    if (device_->Ioctl(type, arg) != 0) {                           \
      PLOG(ERROR) << __func__ << "(): ioctl() failed: " << #type;   \
      PostNotifyError(kInvalidBitstreamBufferId, PLATFORM_FAILURE); \
    }                                                               \
  } while (0)

#define READ_U8_OR_RETURN_FALSE(reader, out)                               \
  do {                                                                     \
    uint8_t _out;                                                          \
    if (!reader.ReadU8(&_out)) {                                           \
      DVLOG(1)                                                             \
          << "Error in stream: unexpected EOS while trying to read " #out; \
      return false;                                                        \
    }                                                                      \
    *(out) = _out;                                                         \
  } while (0)

#define READ_U16_OR_RETURN_FALSE(reader, out)                              \
  do {                                                                     \
    uint16_t _out;                                                         \
    if (!reader.ReadU16(&_out)) {                                          \
      DVLOG(1)                                                             \
          << "Error in stream: unexpected EOS while trying to read " #out; \
      return false;                                                        \
    }                                                                      \
    *(out) = _out;                                                         \
  } while (0)

namespace content {

// This is default huffman segment for 8-bit precision luminance and
// chrominance. The default huffman segment is constructed with the tables from
// JPEG standard section K.3. Actually there are no default tables. They are
// typical tables. These tables are useful for many applications. Lots of
// softwares use them as standard tables such as ffmpeg.
const uint8_t kDefaultDhtSeg[] = {
  0xFF, 0xC4, 0x01, 0xA2, 0x00, 0x00, 0x01, 0x05, 0x01, 0x01, 0x01, 0x01,
  0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02,
  0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x01, 0x00, 0x03,
  0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09,
  0x0A, 0x0B, 0x10, 0x00, 0x02, 0x01, 0x03, 0x03, 0x02, 0x04, 0x03, 0x05,
  0x05, 0x04, 0x04, 0x00, 0x00, 0x01, 0x7D, 0x01, 0x02, 0x03, 0x00, 0x04,
  0x11, 0x05, 0x12, 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07, 0x22,
  0x71, 0x14, 0x32, 0x81, 0x91, 0xA1, 0x08, 0x23, 0x42, 0xB1, 0xC1, 0x15,
  0x52, 0xD1, 0xF0, 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0A, 0x16, 0x17,
  0x18, 0x19, 0x1A, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x34, 0x35, 0x36,
  0x37, 0x38, 0x39, 0x3A, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A,
  0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x63, 0x64, 0x65, 0x66,
  0x67, 0x68, 0x69, 0x6A, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A,
  0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8A, 0x92, 0x93, 0x94, 0x95,
  0x96, 0x97, 0x98, 0x99, 0x9A, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7, 0xA8,
  0xA9, 0xAA, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7, 0xB8, 0xB9, 0xBA, 0xC2,
  0xC3, 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xD2, 0xD3, 0xD4, 0xD5,
  0xD6, 0xD7, 0xD8, 0xD9, 0xDA, 0xE1, 0xE2, 0xE3, 0xE4, 0xE5, 0xE6, 0xE7,
  0xE8, 0xE9, 0xEA, 0xF1, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7, 0xF8, 0xF9,
  0xFA, 0x11, 0x00, 0x02, 0x01, 0x02, 0x04, 0x04, 0x03, 0x04, 0x07, 0x05,
  0x04, 0x04, 0x00, 0x01, 0x02, 0x77, 0x00, 0x01, 0x02, 0x03, 0x11, 0x04,
  0x05, 0x21, 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71, 0x13, 0x22,
  0x32, 0x81, 0x08, 0x14, 0x42, 0x91, 0xA1, 0xB1, 0xC1, 0x09, 0x23, 0x33,
  0x52, 0xF0, 0x15, 0x62, 0x72, 0xD1, 0x0A, 0x16, 0x24, 0x34, 0xE1, 0x25,
  0xF1, 0x17, 0x18, 0x19, 0x1A, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x35, 0x36,
  0x37, 0x38, 0x39, 0x3A, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A,
  0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x63, 0x64, 0x65, 0x66,
  0x67, 0x68, 0x69, 0x6A, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A,
  0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8A, 0x92, 0x93, 0x94,
  0x95, 0x96, 0x97, 0x98, 0x99, 0x9A, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7,
  0xA8, 0xA9, 0xAA, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7, 0xB8, 0xB9, 0xBA,
  0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xD2, 0xD3, 0xD4,
  0xD5, 0xD6, 0xD7, 0xD8, 0xD9, 0xDA, 0xE2, 0xE3, 0xE4, 0xE5, 0xE6, 0xE7,
  0xE8, 0xE9, 0xEA, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7, 0xF8, 0xF9, 0xFA
};

V4L2JpegDecodeAccelerator::BufferRecord::BufferRecord()
    : address(nullptr), length(0), at_device(false) {
}

V4L2JpegDecodeAccelerator::BufferRecord::~BufferRecord() {
}

V4L2JpegDecodeAccelerator::JobRecord::JobRecord(
    media::BitstreamBuffer bitstream_buffer,
    scoped_refptr<media::VideoFrame> video_frame)
    : bitstream_buffer(bitstream_buffer), out_frame(video_frame) {
}

V4L2JpegDecodeAccelerator::JobRecord::~JobRecord() {
}

V4L2JpegDecodeAccelerator::V4L2JpegDecodeAccelerator(
    const scoped_refptr<V4L2Device>& device,
    const scoped_refptr<base::SingleThreadTaskRunner>& io_task_runner)
    : output_buffer_pixelformat_(0),
      child_task_runner_(base::ThreadTaskRunnerHandle::Get()),
      io_task_runner_(io_task_runner),
      client_(nullptr),
      device_(device),
      decoder_thread_("V4L2JpegDecodeThread"),
      device_poll_thread_("V4L2JpegDecodeDevicePollThread"),
      input_streamon_(false),
      output_streamon_(false),
      weak_factory_(this) {
  weak_ptr_ = weak_factory_.GetWeakPtr();
}

V4L2JpegDecodeAccelerator::~V4L2JpegDecodeAccelerator() {
  DCHECK(child_task_runner_->BelongsToCurrentThread());

  if (decoder_thread_.IsRunning()) {
    decoder_task_runner_->PostTask(
        FROM_HERE, base::Bind(&V4L2JpegDecodeAccelerator::DestroyTask,
                              base::Unretained(this)));
    decoder_thread_.Stop();
  }
  weak_factory_.InvalidateWeakPtrs();
  DCHECK(!device_poll_thread_.IsRunning());
}

void V4L2JpegDecodeAccelerator::DestroyTask() {
  DCHECK(decoder_task_runner_->BelongsToCurrentThread());
  while (!input_jobs_.empty())
    input_jobs_.pop();
  while (!running_jobs_.empty())
    running_jobs_.pop();

  // Stop streaming and the device_poll_thread_.
  StopDevicePoll();

  DestroyInputBuffers();
  DestroyOutputBuffers();
}

void V4L2JpegDecodeAccelerator::VideoFrameReady(int32_t bitstream_buffer_id) {
  DCHECK(child_task_runner_->BelongsToCurrentThread());
  client_->VideoFrameReady(bitstream_buffer_id);
}

void V4L2JpegDecodeAccelerator::NotifyError(int32_t bitstream_buffer_id,
                                            Error error) {
  DCHECK(child_task_runner_->BelongsToCurrentThread());
  LOG(ERROR) << "Notifying of error " << error << " for buffer id "
             << bitstream_buffer_id;
  client_->NotifyError(bitstream_buffer_id, error);
}

void V4L2JpegDecodeAccelerator::PostNotifyError(
    int32_t bitstream_buffer_id,
    Error error) {
  child_task_runner_->PostTask(
      FROM_HERE,
      base::Bind(&V4L2JpegDecodeAccelerator::NotifyError, weak_ptr_,
                 bitstream_buffer_id, error));
}

bool V4L2JpegDecodeAccelerator::Initialize(Client* client) {
  DCHECK(child_task_runner_->BelongsToCurrentThread());

  // Capabilities check.
  struct v4l2_capability caps;
  const __u32 kCapsRequired = V4L2_CAP_STREAMING | V4L2_CAP_VIDEO_M2M;
  memset(&caps, 0, sizeof(caps));
  if (device_->Ioctl(VIDIOC_QUERYCAP, &caps) != 0) {
    PLOG(ERROR) << __func__ << ": ioctl() failed: VIDIOC_QUERYCAP";
    return false;
  }
  if ((caps.capabilities & kCapsRequired) != kCapsRequired) {
    LOG(ERROR) << __func__ << ": VIDIOC_QUERYCAP, caps check failed: 0x"
               << std::hex << caps.capabilities;
    return false;
  }

  // Subscribe to the source change event.
  struct v4l2_event_subscription sub;
  memset(&sub, 0, sizeof(sub));
  sub.type = V4L2_EVENT_SOURCE_CHANGE;
  if (device_->Ioctl(VIDIOC_SUBSCRIBE_EVENT, &sub) != 0) {
    PLOG(ERROR) << __func__ << ": ioctl() failed: VIDIOC_SUBSCRIBE_EVENT";
    return false;
  }

  if (!decoder_thread_.Start()) {
    LOG(ERROR) << __func__ << ": decoder thread failed to start";
    return false;
  }
  client_ = client;
  decoder_task_runner_ = decoder_thread_.task_runner();

  decoder_task_runner_->PostTask(
      FROM_HERE, base::Bind(&V4L2JpegDecodeAccelerator::StartDevicePoll,
                            base::Unretained(this)));

  DVLOG(1) << "V4L2JpegDecodeAccelerator initialized.";
  return true;
}

void V4L2JpegDecodeAccelerator::Decode(
    const media::BitstreamBuffer& bitstream_buffer,
    const scoped_refptr<media::VideoFrame>& video_frame) {
  DVLOG(1) << "Decode(): input_id=" << bitstream_buffer.id()
           << ", size=" << bitstream_buffer.size();
  DCHECK(io_task_runner_->BelongsToCurrentThread());

  if (video_frame->format() != media::PIXEL_FORMAT_I420) {
    PostNotifyError(bitstream_buffer.id(), UNSUPPORTED_JPEG);
    return;
  }

  scoped_ptr<JobRecord> job_record(
      new JobRecord(bitstream_buffer, video_frame));

  decoder_task_runner_->PostTask(
      FROM_HERE, base::Bind(&V4L2JpegDecodeAccelerator::DecodeTask,
                            base::Unretained(this), base::Passed(&job_record)));
}

bool V4L2JpegDecodeAccelerator::IsSupported() {
  v4l2_fmtdesc fmtdesc;
  memset(&fmtdesc, 0, sizeof(fmtdesc));
  fmtdesc.type = V4L2_BUF_TYPE_VIDEO_OUTPUT;

  for (; device_->Ioctl(VIDIOC_ENUM_FMT, &fmtdesc) == 0; ++fmtdesc.index) {
    if (fmtdesc.pixelformat == V4L2_PIX_FMT_JPEG)
      return true;
  }
  return false;
}

void V4L2JpegDecodeAccelerator::DecodeTask(scoped_ptr<JobRecord> job_record) {
  DCHECK(decoder_task_runner_->BelongsToCurrentThread());
  job_record->shm.reset(
      new base::SharedMemory(job_record->bitstream_buffer.handle(), true));
  if (!job_record->shm->Map(job_record->bitstream_buffer.size())) {
    PLOG(ERROR) << __func__ << ": could not map bitstream_buffer";
    PostNotifyError(job_record->bitstream_buffer.id(), UNREADABLE_INPUT);
    return;
  }
  input_jobs_.push(make_linked_ptr(job_record.release()));

  ServiceDeviceTask(false);
}

size_t V4L2JpegDecodeAccelerator::InputBufferQueuedCount() {
  return input_buffer_map_.size() - free_input_buffers_.size();
}

size_t V4L2JpegDecodeAccelerator::OutputBufferQueuedCount() {
  return output_buffer_map_.size() - free_output_buffers_.size();
}

bool V4L2JpegDecodeAccelerator::ShouldRecreateInputBuffers() {
  DCHECK(decoder_task_runner_->BelongsToCurrentThread());
  if (input_jobs_.empty())
    return false;

  linked_ptr<JobRecord> job_record = input_jobs_.front();
  // Check input buffer size is enough
  return (input_buffer_map_.empty() ||
          (job_record->bitstream_buffer.size() + sizeof(kDefaultDhtSeg)) >
              input_buffer_map_.front().length);
}

bool V4L2JpegDecodeAccelerator::RecreateInputBuffers() {
  DVLOG(3) << __func__;
  DCHECK(decoder_task_runner_->BelongsToCurrentThread());

  // If running queue is not empty, we should wait until pending frames finish.
  if (!running_jobs_.empty())
    return true;

  DestroyInputBuffers();

  if (!CreateInputBuffers()) {
    LOG(ERROR) << "Create input buffers failed.";
    return false;
  }

  return true;
}

bool V4L2JpegDecodeAccelerator::RecreateOutputBuffers() {
  DVLOG(3) << __func__;
  DCHECK(decoder_task_runner_->BelongsToCurrentThread());

  DestroyOutputBuffers();

  if (!CreateOutputBuffers()) {
    LOG(ERROR) << "Create output buffers failed.";
    return false;
  }

  return true;
}

bool V4L2JpegDecodeAccelerator::CreateInputBuffers() {
  DVLOG(3) << __func__;
  DCHECK(decoder_task_runner_->BelongsToCurrentThread());
  DCHECK(!input_streamon_);
  DCHECK(!input_jobs_.empty());
  linked_ptr<JobRecord> job_record = input_jobs_.front();
  // The input image may miss huffman table. We didn't parse the image before,
  // so we create more to avoid the situation of not enough memory.
  // Reserve twice size to avoid recreating input buffer frequently.
  size_t reserve_size =
      (job_record->bitstream_buffer.size() + sizeof(kDefaultDhtSeg)) * 2;
  struct v4l2_format format;
  memset(&format, 0, sizeof(format));
  format.type = V4L2_BUF_TYPE_VIDEO_OUTPUT;
  format.fmt.pix.pixelformat = V4L2_PIX_FMT_JPEG;
  format.fmt.pix.sizeimage = reserve_size;
  format.fmt.pix.field = V4L2_FIELD_ANY;
  IOCTL_OR_ERROR_RETURN_FALSE(VIDIOC_S_FMT, &format);

  struct v4l2_requestbuffers reqbufs;
  memset(&reqbufs, 0, sizeof(reqbufs));
  reqbufs.count = kBufferCount;
  reqbufs.type = V4L2_BUF_TYPE_VIDEO_OUTPUT;
  reqbufs.memory = V4L2_MEMORY_MMAP;
  IOCTL_OR_ERROR_RETURN_FALSE(VIDIOC_REQBUFS, &reqbufs);

  DCHECK(input_buffer_map_.empty());
  input_buffer_map_.resize(reqbufs.count);

  for (size_t i = 0; i < input_buffer_map_.size(); ++i) {
    free_input_buffers_.push_back(i);

    struct v4l2_buffer buffer;
    memset(&buffer, 0, sizeof(buffer));
    buffer.index = i;
    buffer.type = V4L2_BUF_TYPE_VIDEO_OUTPUT;
    buffer.memory = V4L2_MEMORY_MMAP;
    IOCTL_OR_ERROR_RETURN_FALSE(VIDIOC_QUERYBUF, &buffer);
    void* address = device_->Mmap(NULL, buffer.length, PROT_READ | PROT_WRITE,
                                  MAP_SHARED, buffer.m.offset);
    if (address == MAP_FAILED) {
      PLOG(ERROR) << __func__ << ": mmap() failed";
      PostNotifyError(kInvalidBitstreamBufferId, PLATFORM_FAILURE);
      return false;
    }
    input_buffer_map_[i].address = address;
    input_buffer_map_[i].length = buffer.length;
  }

  return true;
}

bool V4L2JpegDecodeAccelerator::CreateOutputBuffers() {
  DVLOG(3) << __func__;
  DCHECK(decoder_task_runner_->BelongsToCurrentThread());
  DCHECK(!output_streamon_);
  DCHECK(!running_jobs_.empty());
  linked_ptr<JobRecord> job_record = running_jobs_.front();

  size_t frame_size = media::VideoFrame::AllocationSize(
      media::PIXEL_FORMAT_I420, job_record->out_frame->coded_size());
  struct v4l2_format format;
  memset(&format, 0, sizeof(format));
  format.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  format.fmt.pix.width = job_record->out_frame->coded_size().width();
  format.fmt.pix.height = job_record->out_frame->coded_size().height();
  format.fmt.pix.sizeimage = frame_size;
  format.fmt.pix.pixelformat = V4L2_PIX_FMT_YUV420;
  format.fmt.pix.field = V4L2_FIELD_ANY;
  IOCTL_OR_ERROR_RETURN_FALSE(VIDIOC_S_FMT, &format);
  output_buffer_pixelformat_ = format.fmt.pix.pixelformat;
  output_buffer_coded_size_.SetSize(format.fmt.pix.width,
                                    format.fmt.pix.height);

  struct v4l2_requestbuffers reqbufs;
  memset(&reqbufs, 0, sizeof(reqbufs));
  reqbufs.count = kBufferCount;
  reqbufs.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  reqbufs.memory = V4L2_MEMORY_MMAP;
  IOCTL_OR_ERROR_RETURN_FALSE(VIDIOC_REQBUFS, &reqbufs);

  DCHECK(output_buffer_map_.empty());
  output_buffer_map_.resize(reqbufs.count);

  media::VideoPixelFormat output_format =
      V4L2Device::V4L2PixFmtToVideoPixelFormat(output_buffer_pixelformat_);

  for (size_t i = 0; i < output_buffer_map_.size(); ++i) {
    free_output_buffers_.push_back(i);

    struct v4l2_buffer buffer;
    memset(&buffer, 0, sizeof(buffer));
    buffer.index = i;
    buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    buffer.memory = V4L2_MEMORY_MMAP;
    IOCTL_OR_ERROR_RETURN_FALSE(VIDIOC_QUERYBUF, &buffer);

    DCHECK_GE(buffer.length,
              media::VideoFrame::AllocationSize(
                  output_format,
                  gfx::Size(format.fmt.pix.width, format.fmt.pix.height)));

    void* address = device_->Mmap(NULL, buffer.length, PROT_READ | PROT_WRITE,
                                  MAP_SHARED, buffer.m.offset);
    if (address == MAP_FAILED) {
      PLOG(ERROR) << __func__ << ": mmap() failed";
      PostNotifyError(kInvalidBitstreamBufferId, PLATFORM_FAILURE);
      return false;
    }
    output_buffer_map_[i].address = address;
    output_buffer_map_[i].length = buffer.length;
  }

  return true;
}

void V4L2JpegDecodeAccelerator::DestroyInputBuffers() {
  DCHECK(decoder_task_runner_->BelongsToCurrentThread());
  DCHECK(!input_streamon_);

  if (input_streamon_) {
    __u32 type = V4L2_BUF_TYPE_VIDEO_OUTPUT;
    IOCTL_OR_ERROR_RETURN(VIDIOC_STREAMOFF, &type);
    input_streamon_ = false;
  }

  for (size_t i = 0; i < input_buffer_map_.size(); ++i) {
    BufferRecord& input_record = input_buffer_map_[i];
    device_->Munmap(input_record.address, input_record.length);
  }

  struct v4l2_requestbuffers reqbufs;
  memset(&reqbufs, 0, sizeof(reqbufs));
  reqbufs.count = 0;
  reqbufs.type = V4L2_BUF_TYPE_VIDEO_OUTPUT;
  reqbufs.memory = V4L2_MEMORY_MMAP;
  IOCTL_OR_LOG_ERROR(VIDIOC_REQBUFS, &reqbufs);

  input_buffer_map_.clear();
  free_input_buffers_.clear();
}

void V4L2JpegDecodeAccelerator::DestroyOutputBuffers() {
  DCHECK(decoder_task_runner_->BelongsToCurrentThread());
  DCHECK(!output_streamon_);

  if (output_streamon_) {
    __u32 type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    IOCTL_OR_ERROR_RETURN(VIDIOC_STREAMOFF, &type);
    output_streamon_ = false;
  }

  for (size_t i = 0; i < output_buffer_map_.size(); ++i) {
    BufferRecord& output_record = output_buffer_map_[i];
    device_->Munmap(output_record.address, output_record.length);
  }

  struct v4l2_requestbuffers reqbufs;
  memset(&reqbufs, 0, sizeof(reqbufs));
  reqbufs.count = 0;
  reqbufs.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  reqbufs.memory = V4L2_MEMORY_MMAP;
  IOCTL_OR_LOG_ERROR(VIDIOC_REQBUFS, &reqbufs);

  output_buffer_map_.clear();
  free_output_buffers_.clear();
}

void V4L2JpegDecodeAccelerator::DevicePollTask() {
  DCHECK(device_poll_task_runner_->BelongsToCurrentThread());

  bool event_pending;
  if (!device_->Poll(true, &event_pending)) {
    PLOG(ERROR) << __func__ << ": Poll device error.";
    PostNotifyError(kInvalidBitstreamBufferId, PLATFORM_FAILURE);
    return;
  }

  // All processing should happen on ServiceDeviceTask(), since we shouldn't
  // touch decoder state from this thread.
  decoder_task_runner_->PostTask(
      FROM_HERE, base::Bind(&V4L2JpegDecodeAccelerator::ServiceDeviceTask,
                            base::Unretained(this), event_pending));
}

bool V4L2JpegDecodeAccelerator::DequeueSourceChangeEvent() {
  DCHECK(decoder_task_runner_->BelongsToCurrentThread());

  struct v4l2_event ev;
  memset(&ev, 0, sizeof(ev));

  if (device_->Ioctl(VIDIOC_DQEVENT, &ev) == 0) {
    if (ev.type == V4L2_EVENT_SOURCE_CHANGE) {
      DVLOG(3) << __func__ << ": got source change event: "
               << ev.u.src_change.changes;
      if (ev.u.src_change.changes &
          (V4L2_EVENT_SRC_CH_RESOLUTION | V4L2_EVENT_SRC_CH_PIXELFORMAT)) {
        return true;
      }
      LOG(ERROR) << __func__ << ": unexpected source change event.";
    } else {
      LOG(ERROR) << __func__ << ": got an event (" << ev.type
                 << ") we haven't subscribed to.";
    }
  } else {
    LOG(ERROR) << __func__ << ": dequeue event failed.";
  }
  PostNotifyError(kInvalidBitstreamBufferId, PLATFORM_FAILURE);
  return false;
}

void V4L2JpegDecodeAccelerator::ServiceDeviceTask(bool event_pending) {
  DCHECK(decoder_task_runner_->BelongsToCurrentThread());
  // If DestroyTask() shuts |device_poll_thread_| down, we should early-out.
  if (!device_poll_thread_.IsRunning())
    return;

  if (!running_jobs_.empty())
    Dequeue();

  if (ShouldRecreateInputBuffers() && !RecreateInputBuffers())
    return;

  if (event_pending) {
    if (!DequeueSourceChangeEvent()) return;
    if (!RecreateOutputBuffers()) return;
  }

  EnqueueInput();
  EnqueueOutput();

  if (!running_jobs_.empty()) {
    device_poll_task_runner_->PostTask(
        FROM_HERE, base::Bind(&V4L2JpegDecodeAccelerator::DevicePollTask,
                              base::Unretained(this)));
  }

  DVLOG(2) << __func__ << ": buffer counts: INPUT["
           << input_jobs_.size() << "] => DEVICE["
           << free_input_buffers_.size() << "/"
           << input_buffer_map_.size() << "->"
           << free_output_buffers_.size() << "/"
           << output_buffer_map_.size() << "]";
}

void V4L2JpegDecodeAccelerator::EnqueueInput() {
  DCHECK(decoder_task_runner_->BelongsToCurrentThread());
  while (!input_jobs_.empty() && !free_input_buffers_.empty()) {
    // If input buffers are required to re-create, do not enqueue input record
    // until all pending frames are handled by device.
    if (ShouldRecreateInputBuffers())
      break;
    if (!EnqueueInputRecord())
      return;
  }
  // Check here because we cannot STREAMON before QBUF in earlier kernel.
  // (kernel version < 3.14)
  if (!input_streamon_ && InputBufferQueuedCount()) {
    __u32 type = V4L2_BUF_TYPE_VIDEO_OUTPUT;
    IOCTL_OR_ERROR_RETURN(VIDIOC_STREAMON, &type);
    input_streamon_ = true;
  }
}

void V4L2JpegDecodeAccelerator::EnqueueOutput() {
  DCHECK(decoder_task_runner_->BelongsToCurrentThread());
  // Output record can be enqueued because the output coded sizes of the frames
  // currently in the pipeline are all the same.
  while (running_jobs_.size() > OutputBufferQueuedCount() &&
      !free_output_buffers_.empty()) {
    if (!EnqueueOutputRecord())
      return;
  }
  // Check here because we cannot STREAMON before QBUF in earlier kernel.
  // (kernel version < 3.14)
  if (!output_streamon_ && OutputBufferQueuedCount()) {
    __u32 type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    IOCTL_OR_ERROR_RETURN(VIDIOC_STREAMON, &type);
    output_streamon_ = true;
  }
}

static bool CopyOutputImage(const uint32_t src_pixelformat,
                            const void* src_addr,
                            const gfx::Size& src_coded_size,
                            const scoped_refptr<media::VideoFrame>& dst_frame) {
  media::VideoPixelFormat format =
      V4L2Device::V4L2PixFmtToVideoPixelFormat(src_pixelformat);
  size_t src_size = media::VideoFrame::AllocationSize(format, src_coded_size);
  uint8_t* dst_y = dst_frame->data(media::VideoFrame::kYPlane);
  uint8_t* dst_u = dst_frame->data(media::VideoFrame::kUPlane);
  uint8_t* dst_v = dst_frame->data(media::VideoFrame::kVPlane);
  size_t dst_y_stride = dst_frame->stride(media::VideoFrame::kYPlane);
  size_t dst_u_stride = dst_frame->stride(media::VideoFrame::kUPlane);
  size_t dst_v_stride = dst_frame->stride(media::VideoFrame::kVPlane);

  // If the source format is I420, ConvertToI420 will simply copy the frame.
  if (libyuv::ConvertToI420(static_cast<uint8_t*>(const_cast<void*>(src_addr)),
                            src_size,
                            dst_y, dst_y_stride,
                            dst_u, dst_u_stride,
                            dst_v, dst_v_stride,
                            0, 0,
                            src_coded_size.width(),
                            src_coded_size.height(),
                            dst_frame->coded_size().width(),
                            dst_frame->coded_size().height(),
                            libyuv::kRotate0,
                            src_pixelformat)) {
    LOG(ERROR) << "ConvertToI420 failed. Source format: " << src_pixelformat;
    return false;
  }
  return true;
}

void V4L2JpegDecodeAccelerator::Dequeue() {
  DCHECK(decoder_task_runner_->BelongsToCurrentThread());

  // Dequeue completed input (VIDEO_OUTPUT) buffers,
  // and recycle to the free list.
  struct v4l2_buffer dqbuf;
  while (InputBufferQueuedCount() > 0) {
    DCHECK(input_streamon_);
    memset(&dqbuf, 0, sizeof(dqbuf));
    dqbuf.type = V4L2_BUF_TYPE_VIDEO_OUTPUT;
    dqbuf.memory = V4L2_MEMORY_MMAP;
    if (device_->Ioctl(VIDIOC_DQBUF, &dqbuf) != 0) {
      if (errno == EAGAIN) {
        // EAGAIN if we're just out of buffers to dequeue.
        break;
      }
      PLOG(ERROR) << "ioctl() failed: input buffer VIDIOC_DQBUF failed.";
      PostNotifyError(kInvalidBitstreamBufferId, PLATFORM_FAILURE);
      return;
    }
    BufferRecord& input_record = input_buffer_map_[dqbuf.index];
    DCHECK(input_record.at_device);
    input_record.at_device = false;
    free_input_buffers_.push_back(dqbuf.index);

    if (dqbuf.flags & V4L2_BUF_FLAG_ERROR) {
      DVLOG(1) << "Dequeue input buffer error.";
      PostNotifyError(kInvalidBitstreamBufferId, UNSUPPORTED_JPEG);
      running_jobs_.pop();
    }
  }

  // Dequeue completed output (VIDEO_CAPTURE) buffers, recycle to the free list.
  // Return the finished buffer to the client via the job ready callback.
  // If dequeued input buffer has an error, the error frame has removed from
  // |running_jobs_|. We only have to dequeue output buffer when we actually
  // have pending frames in |running_jobs_| and also enqueued output buffers.
  while (!running_jobs_.empty() && OutputBufferQueuedCount() > 0) {
    DCHECK(output_streamon_);
    memset(&dqbuf, 0, sizeof(dqbuf));
    dqbuf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    // From experiments, using MMAP and memory copy is still faster than
    // USERPTR. Also, client doesn't need to consider the buffer alignment and
    // JpegDecodeAccelerator API will be simpler.
    dqbuf.memory = V4L2_MEMORY_MMAP;
    if (device_->Ioctl(VIDIOC_DQBUF, &dqbuf) != 0) {
      if (errno == EAGAIN) {
        // EAGAIN if we're just out of buffers to dequeue.
        break;
      }
      PLOG(ERROR) << "ioctl() failed: output buffer VIDIOC_DQBUF failed.";
      PostNotifyError(kInvalidBitstreamBufferId, PLATFORM_FAILURE);
      return;
    }
    BufferRecord& output_record = output_buffer_map_[dqbuf.index];
    DCHECK(output_record.at_device);
    output_record.at_device = false;
    free_output_buffers_.push_back(dqbuf.index);

    // Jobs are always processed in FIFO order.
    linked_ptr<JobRecord> job_record = running_jobs_.front();
    running_jobs_.pop();

    if (dqbuf.flags & V4L2_BUF_FLAG_ERROR) {
      DVLOG(1) << "Dequeue output buffer error.";
      PostNotifyError(kInvalidBitstreamBufferId, UNSUPPORTED_JPEG);
    } else {
      // Copy the decoded data from output buffer to the buffer provided by the
      // client. Do format conversion when output format is not
      // V4L2_PIX_FMT_YUV420.
      if (!CopyOutputImage(output_buffer_pixelformat_, output_record.address,
                           output_buffer_coded_size_, job_record->out_frame)) {
        PostNotifyError(job_record->bitstream_buffer.id(), PLATFORM_FAILURE);
        return;
      }

      DVLOG(3) << "Decoding finished, returning bitstream buffer, id="
               << job_record->bitstream_buffer.id();

      child_task_runner_->PostTask(
          FROM_HERE,
          base::Bind(&V4L2JpegDecodeAccelerator::VideoFrameReady, weak_ptr_,
                     job_record->bitstream_buffer.id()));
    }
  }
}

static bool AddHuffmanTable(const void* input_ptr,
                            size_t input_size,
                            void* output_ptr,
                            size_t output_size) {
  DCHECK(input_ptr);
  DCHECK(output_ptr);
  DCHECK_LE((input_size + sizeof(kDefaultDhtSeg)), output_size);

  base::BigEndianReader reader(static_cast<const char*>(input_ptr), input_size);
  bool has_marker_dht = false;
  bool has_marker_sos = false;
  uint8_t marker1, marker2;
  READ_U8_OR_RETURN_FALSE(reader, &marker1);
  READ_U8_OR_RETURN_FALSE(reader, &marker2);
  if (marker1 != media::JPEG_MARKER_PREFIX || marker2 != media::JPEG_SOI) {
    DLOG(ERROR) << __func__ << ": The input is not a Jpeg";
    return false;
  }

  // copy SOI marker (0xFF, 0xD8)
  memcpy(output_ptr, input_ptr, 2);
  size_t current_offset = 2;

  while (!has_marker_sos && !has_marker_dht) {
    const char* start_addr = reader.ptr();
    READ_U8_OR_RETURN_FALSE(reader, &marker1);
    if (marker1 != media::JPEG_MARKER_PREFIX) {
      DLOG(ERROR) << __func__ << ": marker1 != 0xFF";
      return false;
    }
    do {
      READ_U8_OR_RETURN_FALSE(reader, &marker2);
    } while (marker2 == media::JPEG_MARKER_PREFIX);  // skip fill bytes

    uint16_t size;
    READ_U16_OR_RETURN_FALSE(reader, &size);
    // The size includes the size field itself.
    if (size < sizeof(size)) {
      DLOG(ERROR) << __func__ << ": Ill-formed JPEG. Segment size (" << size
                  << ") is smaller than size field (" << sizeof(size) << ")";
      return false;
    }
    size -= sizeof(size);

    switch (marker2) {
      case media::JPEG_DHT: {
        has_marker_dht = true;
        break;
      }
      case media::JPEG_SOS: {
        if (!has_marker_dht) {
          memcpy(static_cast<uint8_t*>(output_ptr) + current_offset,
                 kDefaultDhtSeg, sizeof(kDefaultDhtSeg));
          current_offset += sizeof(kDefaultDhtSeg);
        }
        has_marker_sos = true;
        break;
      }
      default:
        break;
    }

    if (!reader.Skip(size)) {
      DLOG(ERROR) << __func__ << ": Ill-formed JPEG. Remaining size ("
                  << reader.remaining()
                  << ") is smaller than header specified (" << size << ")";
      return false;
    }

    size_t segment_size = static_cast<size_t>(reader.ptr() - start_addr);
    memcpy(static_cast<uint8_t*>(output_ptr) + current_offset, start_addr,
           segment_size);
    current_offset += segment_size;
  }
  if (reader.remaining()) {
    memcpy(static_cast<uint8_t*>(output_ptr) + current_offset, reader.ptr(),
           reader.remaining());
  }
  return true;
}

bool V4L2JpegDecodeAccelerator::EnqueueInputRecord() {
  DCHECK(!input_jobs_.empty());
  DCHECK(!free_input_buffers_.empty());

  // Enqueue an input (VIDEO_OUTPUT) buffer for an input video frame.
  linked_ptr<JobRecord> job_record = input_jobs_.front();
  input_jobs_.pop();
  const int index = free_input_buffers_.back();
  BufferRecord& input_record = input_buffer_map_[index];
  DCHECK(!input_record.at_device);

  // It will add default huffman segment if it's missing.
  if (!AddHuffmanTable(job_record->shm->memory(),
                       job_record->bitstream_buffer.size(),
                       input_record.address, input_record.length)) {
    PostNotifyError(job_record->bitstream_buffer.id(), PARSE_JPEG_FAILED);
    return false;
  }

  struct v4l2_buffer qbuf;
  memset(&qbuf, 0, sizeof(qbuf));
  qbuf.index = index;
  qbuf.type = V4L2_BUF_TYPE_VIDEO_OUTPUT;
  qbuf.memory = V4L2_MEMORY_MMAP;
  IOCTL_OR_ERROR_RETURN_FALSE(VIDIOC_QBUF, &qbuf);
  input_record.at_device = true;
  running_jobs_.push(job_record);
  free_input_buffers_.pop_back();

  DVLOG(3) << __func__ << ": enqueued frame id="
           << job_record->bitstream_buffer.id() << " to device.";
  return true;
}

bool V4L2JpegDecodeAccelerator::EnqueueOutputRecord() {
  DCHECK(!free_output_buffers_.empty());

  // Enqueue an output (VIDEO_CAPTURE) buffer.
  const int index = free_output_buffers_.back();
  BufferRecord& output_record = output_buffer_map_[index];
  DCHECK(!output_record.at_device);
  struct v4l2_buffer qbuf;
  memset(&qbuf, 0, sizeof(qbuf));
  qbuf.index = index;
  qbuf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  qbuf.memory = V4L2_MEMORY_MMAP;
  IOCTL_OR_ERROR_RETURN_FALSE(VIDIOC_QBUF, &qbuf);
  output_record.at_device = true;
  free_output_buffers_.pop_back();
  return true;
}

void V4L2JpegDecodeAccelerator::StartDevicePoll() {
  DVLOG(3) << __func__ << ": starting device poll";
  DCHECK(decoder_task_runner_->BelongsToCurrentThread());
  DCHECK(!device_poll_thread_.IsRunning());

  if (!device_poll_thread_.Start()) {
    LOG(ERROR) << __func__ << ": Device thread failed to start";
    PostNotifyError(kInvalidBitstreamBufferId, PLATFORM_FAILURE);
    return;
  }
  device_poll_task_runner_ = device_poll_thread_.task_runner();
}

bool V4L2JpegDecodeAccelerator::StopDevicePoll() {
  DVLOG(3) << __func__ << ": stopping device poll";
  // Signal the DevicePollTask() to stop, and stop the device poll thread.
  if (!device_->SetDevicePollInterrupt()) {
    LOG(ERROR) << __func__ << ": SetDevicePollInterrupt failed.";
    PostNotifyError(kInvalidBitstreamBufferId, PLATFORM_FAILURE);
    return false;
  }

  device_poll_thread_.Stop();

  // Clear the interrupt now, to be sure.
  if (!device_->ClearDevicePollInterrupt())
    return false;

  return true;
}

}  // namespace content