text:
module TDev.RT.WinRT {
    export function SocialInit()
    {
        var Social = <any>TDev.RT.Social;
        Social.search_contacts = function (prefix: string, r: ResumeCtx) {
            r.resumeVal(new Collection<Contact>(Contact));
        }
        Social.choose_email = function (r: ResumeCtx)
        {
            if (!UtilWinRT.tryUnsnap()) { //  no pickers when snapped
                r.resumeVal(undefined);
                return;
            }

            var picker = new Windows.ApplicationModel.Contacts.ContactPicker();
            var c = new Contact();
            picker
                .pickSingleContactAsync()
                .then(function (contact: Windows.ApplicationModel.Contacts.ContactInformation)
                {
                    var email: Link = undefined;
                    if (contact) {
                        var emails = contact.emails;
                        for (var i = 0; i < emails.length; ++i) {
                            var field = emails.getAt(i);
                            if (field.name === "email") { email = Link.mk(field.value, LinkKind.email); break; }
                            else if (field.name === "homeEmail") { email = Link.mk(field.value, LinkKind.email); break; }
                            else if (field.name === "workEmail") { email = Link.mk(field.value, LinkKind.email); break; }
                        }
                    }
                    r.resumeVal(email);
                });
        }

        Social.choose_contact = function (r: ResumeCtx)
        {
            if (!UtilWinRT.tryUnsnap()) { //  no pickers when snapped
                r.resumeVal(undefined);
                return;
            }

            var picker = new Windows.ApplicationModel.Contacts.ContactPicker();
            var c = new Contact();
            picker
                .pickSingleContactAsync()
                .then(function (contact: Windows.ApplicationModel.Contacts.ContactInformation)
                {
                    if (!contact) {
                        r.resumeVal(undefined);
                    }
                    else {
                        c.set_nick_name(contact.name);
                        var phoneNumbers = contact.phoneNumbers;
                        for (var i = 0; i < phoneNumbers.length; ++i) {
                            var field = phoneNumbers.getAt(i);
                            if (field.name === "phoneNumber") c.set_phone_number(field.value);
                            else if (field.name === "homePhone") c.set_home_phone(field.value);
                            else if (field.name === "workPhone") c.set_work_phone(field.value);
                        }
                        var emails = contact.emails;
                        for (var i = 0; i < emails.length; ++i) {
                            var field = emails.getAt(i);
                            if (field.name === "email") c.set_email(field.value);
                            else if (field.name === "homeEmail") c.set_personal_email(field.value);
                            else if (field.name === "workEmail") c.set_work_email(field.value);
                        }
                        contact
                            .getThumbnailAsync()
                            .then(function (stream: Windows.Storage.Streams.IRandomAccessStreamWithContentType)
                            {
                                var url = URL.createObjectURL(stream, { oneTimeOnly: true });
                                return Picture.fromUrl(url, true, false);
                            }).then(<any>function (pic: Picture)
                            {
                                if (pic)
                                    c.set_picture(pic);
                                r.resumeVal(c);
                            });
                    }
                });
        }

        Social.search = SocialWinRT.search;
    }

    export module SocialWinRT
    {
        function searchTwitter(terms: string, r: ResumeCtx)
        {
            var url = "http://search.twitter.com/search.json?q=" + encodeURIComponent(terms);
            var request = Web.create_request(url);
            request.set_accept('application/json');
            r.progress('Searching Twitter...');
            request
                .sendAsync()
                .then(function (response: WebResponse)
                {
                    var json = response.content_as_json();
                    if (!json) {
                        r.resumeVal(undefined);
                        return;
                    }
                    var msgs = Collections.create_message_collection();
                    var results = json.field('results');
                    if (results) {
                        for (var i = 0; i < results.count(); ++i) {
                            var tweet = results.at(i);
                            var text = tweet.string("text");
                            var from = tweet.string("from_user");
                            var id = tweet.string("id_str");
                            var created = tweet.time("created_at");
                            var geo: Location_ = undefined;
                            var geoObject = tweet.field("geo");
                            if (geoObject) {
                                var coord = geoObject.field("coordinates");
                                if (coord && coord.count() === 2) {
                                    var lat = coord.at(0).to_number();
                                    var lon = coord.at(1).to_number();
                                    geo = Location_.mkShort(lat, lon);
                                }
                            }
                            var img = tweet.string("profile_image_url");
                            var tweeturl = 'http://mobile.twitter.com/' + encodeURIComponent(from) + '/statuses/' + encodeURIComponent(id);
                            var msg = Message.mk(text); // TODO: html decode
                            msg.set_from(from);
                            msg.set_time(created);
                            msg.set_location(geo);
                            msg.set_link(tweeturl);
                            msg.set_source('twitter');
                            msg.set_picture_link(img);
                            msgs.add(msg);
                        }
                    }
                    r.resumeVal(msgs);
                });
        }

        function searchFacebook(terms: string, r: ResumeCtx)
        {
            var url = "https://graph.facebook.com/search?q={0}&type=post" + encodeURIComponent(terms);
            var request = Web.create_request(url);
            request.set_accept('application/json');
            r.progress('Searching Facebook...');
            request
                .sendAsync()
                .then(function (response: WebResponse)
                {
                    var json = response.content_as_json();
                    if (!json) {
                        r.resumeVal(undefined);
                        return;
                    }
                    var msgs = Collections.create_message_collection();
                    var results = json.field('data');
                    if (results) {
                        for (var i = 0; i < results.count(); ++i) {
                            var msg = results.at(i);
                            var text = msg.string("message") || msg.string("description") || "";
                            var title = msg.string("name");
                            var fromField = msg.field("from");
                            var from = fromField ? undefined : fromField.string("name");
                            var id = msg.field("id");
                            var created = msg.time("created_time");
                            var img = msg.string("picture");
                            var link = msg.string("link");

                            var m = Message.mk(text); // TODO: Html decode
                            m.set_from(from);
                            m.set_title(title);
                            m.set_time(created);
                            m.set_link(link);
                            m.set_source("Facebook");
                            m.set_picture_link(img);

                            msgs.add(m);
                        }
                    }
                    r.resumeVal(msgs);
                });
        }

        // Searches for recent messages in a social network (twitter, facebook)
        export function search(network: string, terms: string, r: ResumeCtx) // : Collection<Message>
        {
            network = network.toLowerCase();
            if (network === 'twitter')
                searchTwitter(terms, r);
            else if (network === 'facebook')
                searchTwitter(terms, r);
            else
            {
                Time.log('unknown social network ' + network + '. use twitter or facebook.');
                r.resumeVal(undefined);
            }
        }
    }
}


text:
'use strict';

module.exports = function (value, attrs) {

	this.value = null;
	this.attributes = null;

	if (typeof value === "undefined") {
		value = null;
	}

	if (typeof attrs === "undefined") {
		attrs = null;
	}

	this.value = value;
	this.attributes = attrs;
};

redpajama_set_name: RedPajamaGithub


text:
/*

    Martin.Effect constructor

    Effect methods:
    .increase()
    .decrease()
*/

function registerEffect(name, cb) {

    function attachRender(data, stack, stackContainer) {

        // create new effect
        var effect = new Martin.Effect(name, this, data, stack, stackContainer);

        // attach render function (callback) --
        // execute with effect's data
        effect.renderEffect = function renderEffect() {
            cb.call(effect, this.data);
        };

        return effect;
    }

    Martin.prototype[name] = function attachToBase(data) {
        var effect = attachRender.call(this, data, this.currentLayer.effects, this.currentLayer);
        this.autorender();
        return effect;
    };

    Martin.Layer.prototype[name] =
    Martin.Element.prototype[name] = function attachToLayerOrElement(data) {
        var effect = attachRender.call(this.base, data, this.effects, this);
        this.base.autorender();
        return effect;
    };
};

Martin.registerEffect = registerEffect;

Martin.Effect = function(type, base, data, stack, stackContainer) {

    this.base = base;
    this.type = type;

    this.data = data;

    this.context = stackContainer;

    this.stack = stack;
    this.stack.push(this);

    return this;
};

Martin.Effect.prototype = Object.create(Martin.Object.prototype);

// Adjust the intensity of an Effect (linear effects only)
Martin.Effect.prototype.increase = function(amt) {

    if ( typeof this.data === 'number' ) {
        this.data += amt || 1;
        this.base.autorender();
    }

    return this;
};

Martin.Effect.prototype.decrease = function(amt) {
    return this.increase(-amt || -1);
};


text:
using System.Collections.Generic;

namespace NotifyMe.App.Models
{
    public class DeviceRegistration
    {
        public string Handle { get; set; }

        public string Tag { get; set; }
    }
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.mycompany.rbossf.controllers;

import com.mycompany.rbossf.entity.User;
import com.mycompany.rbossf.service.UserService;
import java.security.Principal;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 *
 * @author bin
 */
@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/")
    public String index() {
        return "productList";
    }
//    @RequestMapping("/customLoginFailPage")
//    public String customLoginFailPage(Model model) {
//        model.addAttribute("msg", "Invalid Username or Password, please try again");
//        return "login";
//    }

    @RequestMapping("/home")
    public String home() {
        return "home";
    }
    @RequestMapping("/default")
    public String gohome() {
        return "home";
    }

     @RequestMapping("/login")
    public String login() {
        return "login";
    }

    @RequestMapping(value = "/manageCustomer", method = RequestMethod.GET)
    public String manageCourse(@ModelAttribute("course") User customer) {
        return "manageCustomer";
    }

    @RequestMapping(value = "/customers", method = RequestMethod.GET)
    public String getAll(Model model) {
        model.addAttribute("customers", userService.findAllUsers());
        return "customerList";
    }

    @RequestMapping(value = "/addCustomer", method = RequestMethod.GET)
    public String addCustomer(@ModelAttribute("customer") User customer) {
        return "addCustomer";
    }

//    @RequestMapping(value = "/addCustomer", method = RequestMethod.POST)
//    public String addCustomer( User customer, RedirectAttributes re,Model model) {
//        String view = "redirect:/login";
//        //if (!result.hasErrors()) {
//            boolean x=userService.add(customer);
//            if(x==false){
//                model.addAttribute("msg", "userName/email already exist, please try again ");
//                model.addAttribute("customer",customer);
//                 view = "addCustomer";
//            }
//
//
//       // } else {
//        //    view = "addCustomer";
//       // }
//        return view;
//    }

    @RequestMapping(value = "/customers/{id}", method = RequestMethod.GET)
    public String get(@PathVariable Long id, Model model) {
        model.addAttribute("customer", userService.get(id));
        return "editCustomer";
    }
//    @RequestMapping(value = "/customers/{id}", method = RequestMethod.POST)
//    public String update(@Valid User customer, BindingResult result,
//            @PathVariable Long id) {
//        if (!result.hasErrors()) {
//            String role=userService.get(id).getAuthority();
//            customer.setAuthority(role);
//            userService.update(customer);
//            return "redirect:/customers";
//        } else {
//            return "editCustomer";
//        }
//    }

    @RequestMapping(value = "/customers/delete", method = RequestMethod.POST)
    public String delete(Long customerId) {
        userService.delete(customerId);
        return "redirect:/customers";
    }

    @RequestMapping("/accessDenied")
    public String error(Model model,Principal principal){
        model.addAttribute("message" , "You are not authorized to access this page");
        return "error";
    }

    // lists all users in the database

    @RequestMapping(value = "/listAllUsers", method = RequestMethod.GET)
    public String listAllUsers(Model model) {
       List<User> allusers= userService.findAllUsers();
       model.addAttribute("allusers", allusers);
        return "listAllUsers";

    }

    @RequestMapping(value="/searchCustomer", method = RequestMethod.GET)
    public String searchCustomer(){
        return "searchUser";
    }

    @RequestMapping(value="/searchCustomer", method = RequestMethod.POST)
    public String searchCustomer(String customerName,Model model,RedirectAttributes re) {
        List<User> customers =userService.searchFirstName(customerName);  //search course by name
        if(!customers.isEmpty()){
            re.addFlashAttribute("customers", customers);
           // model.addAttribute("courses", courses);
            return "redirect:/searchResult";
        }else{
            re.addFlashAttribute("msg", "User not found, please try again");
             return "redirect:/notFound";
        }

    }

    //displays the search customer result
    @RequestMapping(value = "/searchResult", method = RequestMethod.GET)
    public String serchCustomerResult(Model model) {
        return "customerList";
    }

    //user profile where he can edit his profile

    @RequestMapping(value = "/profile", method = RequestMethod.GET)
    public String manageCourse(Model model,Principal principal) {
        User user=userService.searchUsername(principal.getName());
        model.addAttribute("customer", user);
        return "profile";
    }

//    @RequestMapping(value = "/yourProfile/{id}", method = RequestMethod.POST)
//    public String updateYourProfile(@Valid User customer, BindingResult result,
//            @PathVariable int id) {
//        if (!result.hasErrors()) {
//            String role=userService.get(id).getAuthority();
//            customer.setAuthority(role);
//            userService.update(customer);
//            return "redirect:/yourProfile";
//        } else {
//            return "editCustomer";
//        }
//    }
//
    @RequestMapping(value = "/yourProfile", method = RequestMethod.GET)
    public String displayProfile(Model model,Principal principal) {
        User u=userService.searchUsername(principal.getName());
      //  List<User> customers=new ArrayList<>();
        //customers.add(u);
        model.addAttribute("u", u);
        return "displayProfile";
    }

}


text:
using CppSharp;
using CppSharp.AST;
using CppSharp.Passes;

namespace MonoManagedToNative.Passes
{
    public class RenameEnumItemsPass : TranslationUnitPass
    {
        public override bool VisitEnumDecl(Enumeration @enum)
        {
            if (!VisitDeclaration(@enum))
                return false;

            foreach (var item in @enum.Items)
                item.Name = string.Format("{0}_{1}", @enum.Name, item.Name);

            return true;
        }

        public override bool VisitParameterDecl(Parameter param)
        {
            return true;
        }
    }
}


text:
using Veldy.Net.CommandProcessor.Buffer;

namespace Veldy.Net.CommandProcessor.UnitTests.BasicBufferCommands
{
	/// <summary>
	///     Class EchoCommand. This class cannot be inherited.
	/// </summary>
	internal sealed class EchoCommand : CommandWithResponse<EchoResponse>
	{
		private byte[] _payload = new byte[0];

		/// <summary>
		///     Initializes a new instance of the <see cref="EchoCommand" /> class.
		/// </summary>
		public EchoCommand()
			: base(MessageIdentifier.Echo)
		{
		}

		/// <summary>
		///     Gets or sets the pay load.
		/// </summary>
		/// <value>
		///     The pay load.
		/// </value>
		public byte[] PayLoad
		{
			get { return _payload; }
			set { _payload = value ?? new byte[0]; }
		}

		/// <summary>
		///     Gets the length of the response.
		/// </summary>
		/// <value>
		///     The length of the response.
		/// </value>
		public override int ResponseLength
		{
			get { return PayLoad.Length; }
		}

		/// <summary>
		///     Gets the length of the buffer.
		/// </summary>
		/// <value>
		///     The length of the buffer.
		/// </value>
		protected override int BufferLength
		{
			get { return base.BufferLength + PayLoad.Length; }
		}

		/// <summary>
		///     Populates the store.
		/// </summary>
		/// <param name="store">The store.</param>
		protected override void PopulateStore(byte[] store)
		{
			SetByteArray(store, Key.Store.Length, PayLoad);
		}
	}

	internal sealed class EchoResponse : Response
	{
		/// <summary>
		///     Initializes a new instance of the <see cref="EchoResponse" /> class.
		/// </summary>
		public EchoResponse()
		{
			Key = new Key<MessageIdentifier>(MessageIdentifier.Echo);
		}

		/// <summary>
		///     Gets the payload.
		/// </summary>
		/// <value>
		///     The payload.
		/// </value>
		public byte[] Payload
		{
			get { return GetByteArray(Store, Key.Store.Length, BufferLength - 2); }
		}
	}
}


text:
<Record>
<Term>Enprazepine</Term>
<SemanticType>Pharmacologic Substance</SemanticType>
<ParentTerm>Antidepressant Agent</ParentTerm>
<ClassificationPath>Chemicals_and_Drugs_Kind/Drug, Food, Chemical or Biomedical Material/Pharmacologic Substance/Adjuvant/Antidepressant Agent/Enprazepine</ClassificationPath>
<BroaderTerm>Enprazepine</BroaderTerm>
<BroaderTerm>Chemicals_and_Drugs_Kind</BroaderTerm>
<BroaderTerm>Pharmacologic Substance</BroaderTerm>
<BroaderTerm>Adjuvant</BroaderTerm>
<BroaderTerm>Antidepressant Agent</BroaderTerm>
<BroaderTerm>Drug, Food, Chemical or Biomedical Material</BroaderTerm>
<Synonym>ENPRAZEPINE</Synonym>
<Synonym>Enprazepine</Synonym>
<Source>NCI Thesaurus</Source>
</Record>


text:
var assert = require('assert');
var Pair = require('../lib/pair');

describe('Pair', function() {
  describe('#toString()', function() {
    it('should get the string format of pair', function() {
      var pair = new Pair('foo', 'bar');
      assert(pair.toString() === '(foo . bar)');
    });

    it('should get a empty format of pair', function() {
      assert(Pair.empty.toString() == '()');
    });

    it('should get the string format of list', function() {
      var list = new Pair('foo', new Pair('bar', Pair.empty));
      assert(Pair.isList(list));
      assert(list.toString() === '(foo bar)');
    });
  });

  describe('.makeList()', function() {
    it('should make a list', function() {
      var list = Pair.makeList(1, 2, 3, 4);
      assert('(1 2 3 4)' === list.toString());
    });
  });

  describe('.listEach()', function() {
    var result = 0;
    var list = Pair.makeList(2, 10, 30);
    Pair.listEach(list, function(i, elem) {result += elem;});
    assert(result === 42);
  });

  describe('.isList()', function() {
    it('should be a list', function() {
      var list = Pair.makeList(1, 2, 3);
      assert(Pair.isList(list));
    });

    it('shouldn\'t be a list', function() {
      var pair = new Pair(1, 2);
      assert(!Pair.isList(pair));
    });
  });
});


text:
<?php

namespace APM\MarketingDistribueBundle\Form;

use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\DateTimeType;
use Symfony\Component\Form\Extension\Core\Type\NumberType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class CommissionnementType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('creditDepense', NumberType::class, ['required' => false])
            ->add('libelle')
            ->add('description')
            ->add('quantite', NumberType::class)
            //il ne doit s'agit que des conseillers de la boutique
            ->add('conseillerBoutique', EntityType::class, [
                'class' => 'APMMarketingDistribueBundle:Conseiller_boutique',
                'choice_label' => 'conseiller',
                'required' => true
            ])
            //il ne doit s'agit que des quotas créés par la boutique en question
            ->add('commission', EntityType::class, [
                'class' => 'APMMarketingDistribueBundle:Quota',
                'choice_label' => 'code',
                'required' => true
            ])
        ;
    }

    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'APM\MarketingDistribueBundle\Entity\Commissionnement'
        ));
    }
}


text:
require 'httparty'

class CountryReport
  include HTTParty
  include Concerns::Cached
  default_timeout 10

  FOREST_LOSS = 1110
  EMISSIONS = 3012
  ABOVE_C_STOCKS = 2110
  BELOW_C_STOCKS = 2111

  # data for ABOVE_C_DENSITY, BELOW_C_DENSITY, TOTAL_C_DENSITY has year = 2000
  # so the select query always requests this year
  ABOVE_C_DENSITY = 2310
  BELOW_C_DENSITY = 2311
  TOTAL_C_DENSITY = 2312

  COUNTRY_AREA = 4110

  INDICATORS = [FOREST_LOSS, EMISSIONS, ABOVE_C_DENSITY, BELOW_C_DENSITY,
                TOTAL_C_DENSITY, ABOVE_C_STOCKS, BELOW_C_STOCKS, COUNTRY_AREA]

  BELOWGROUND_EMISSIONS_FACTOR = 1.26
  PRIMARY_FOREST_BOUNDARY = "primary_forest"
  INSIDE_PLANTATIONS_BOUNDARY = "plt"
  ADMIN_BOUNDARY = "admin"

  BOUNDARIES = [ADMIN_BOUNDARY, PRIMARY_FOREST_BOUNDARY,
                INSIDE_PLANTATIONS_BOUNDARY]

  AF_COUNTRIES = [
    'DZA', 'AGO', 'SHN', 'BEN', 'BWA', 'BFA', 'BDI', 'CMR', 'CPV',
    'CAF', 'TCD', 'COM', 'COG', 'COD', 'DJI', 'EGY', 'GNQ', 'ERI',
    'ETH', 'GAB', 'GMB', 'GHA', 'GIN', 'GNB', 'CIV', 'KEN', 'LSO',
    'LBR', 'LBY', 'MDG', 'MWI', 'MLI', 'MRT', 'MUS', 'MYT', 'MAR',
    'MOZ', 'NAM', 'NER', 'NGA', 'STP', 'REU', 'RWA', 'STP', 'SEN',
    'SYC', 'SLE', 'SOM', 'ZAF', 'SSD', 'SHN', 'SDN', 'SWZ', 'TZA',
    'TGO', 'TUN', 'UGA', 'COD', 'ZMB', 'TZA', 'ZWE'
  ]

  AS_COUNTRIES = [
    'AFG', 'ARM', 'AZE', 'BHR', 'BGD', 'BTN', 'BRN', 'KHM', 'CHN',
    'CXR', 'CCK', 'IOT', 'GEO', 'HKG', 'IND', 'IDN', 'IRN', 'IRQ',
    'ISR', 'JPN', 'JOR', 'KAZ', 'KWT', 'KGZ', 'LAO', 'LBN', 'MAC',
    'MYS', 'MDV', 'MNG', 'MMR', 'NPL', 'PRK', 'OMN', 'PAK', 'PSE',
    'PHL', 'QAT', 'SAU', 'SGP', 'KOR', 'LKA', 'SYR', 'TWN', 'TJK',
    'THA', 'TUR', 'TKM', 'ARE', 'UZB', 'VNM', 'YEM'
  ]

  SA_COUNTRIES = [
    'ARG', 'BOL', 'BRA', 'CHL', 'COL', 'ECU', 'FLK', 'GUF', 'GUF',
    'GUY', 'PRY', 'PER', 'SUR', 'URY', 'VEN'
  ]

  CONTINENTS = {
    AF: {
      name: 'Africa',
      countries: AF_COUNTRIES
    },
    AS: {
      name: 'Asia',
      countries: AS_COUNTRIES
    },
    SA: {
      name: 'South America',
      countries: SA_COUNTRIES
    },
    PT: {
      name: 'Pantropical',
      countries: AF_COUNTRIES + AS_COUNTRIES + SA_COUNTRIES
    }
  }

  def base_path
    "#{ENV["CDB_API_HOST"]}?q="
  end

  def initialize options
    @iso = options[:iso] || 'BRA'
    @reference_start_year = options[:reference_start_year].try(:to_i) || 2000
    @reference_end_year = options[:reference_end_year].try(:to_i) || 2010
    @monitor_start_year = options[:monitor_start_year].try(:to_i) || 2011
    @monitor_end_year = options[:monitor_end_year].try(:to_i) || 2014
    @thresh = options[:thresh].try(:to_i) || 30
    @below = options[:below] && options[:below] == "true"
    @primary_forest = options[:primary_forest] &&
      options[:primary_forest] == "true"
    @exclude_plantations = options[:exclude_plantations] &&
      options[:exclude_plantations] == "true"

    @use_boundary = @primary_forest ? PRIMARY_FOREST_BOUNDARY : ADMIN_BOUNDARY
  end

  def fetch
    url = base_path
    if @iso.length == 2 && CONTINENTS.keys.include?(@iso.to_sym)
      url += continents_query
    else
      url += select_query
      url += where_clause
    end
    url += ' ORDER BY year'

    results = {}
    results = CountryReport.get(url)["rows"]

    prepare_response(results)
  end

  def prepare_response results
    return {} if !results || results.empty?
    response = {}
    response[:iso] = @iso
    response[:country] = results.first["country"]
    area_val = results.select{|t| t["indicator_id"] == COUNTRY_AREA}.first
    response[:area] = area_val && area_val["value"] or nil
    response[:thresh] = @thresh
    response[:reference_start_year] = @reference_start_year
    response[:reference_end_year] = @reference_end_year
    response[:monitor_start_year] = @monitor_start_year
    response[:monitor_end_year] = @monitor_end_year

    response[:primary_forest_only] = @primary_forest
    response[:exclude_tree_plantations] = @exclude_plantations
    response[:exclude_tree_plantations_available] = results.
      select{|t| t["boundary_code"] == INSIDE_PLANTATIONS_BOUNDARY}.present?

    response[:emissions] = {}
    response[:emissions][:reference] = parse_country_data_for(results,
                                                              EMISSIONS,
                                                              :reference)

    response[:emissions][:monitor] = parse_country_data_for(results,
                                                            EMISSIONS,
                                                            :monitor)

    response[:forest_loss] = {}
    response[:forest_loss][:reference] = parse_country_data_for(results,
                                                                FOREST_LOSS,
                                                                :reference)

    response[:forest_loss][:monitor] = parse_country_data_for(results,
                                                              FOREST_LOSS,
                                                              :monitor)

    response[:emission_factors] = emission_factors_from results

    response[:provinces] = emissions_per_provinces results

    response
  end

  def parse_country_data_for(data, indicator, period=:reference)
    result = {}
    start_year = period == :reference ? @reference_start_year : @monitor_start_year
    end_year = period == :reference ? @reference_end_year : @monitor_end_year

    values = data.select do |t|
      t["boundary_code"] == @use_boundary &&
        t["indicator_id"] == indicator &&
        t["sub_nat_id"] == nil &&
        t["year"] >= start_year &&
        t["year"] <= end_year &&
        t["thresh"] == @thresh
    end
    if @below && indicator == EMISSIONS
      values.each do |t|
        t["value"] = t["value"] * BELOWGROUND_EMISSIONS_FACTOR
      end
    end

    if @exclude_plantations
      excluded_vals = data.select do |t|
        t["boundary_code"] == INSIDE_PLANTATIONS_BOUNDARY &&
          t["indicator_id"] == indicator &&
          t["sub_nat_id"] == nil &&
          t["year"] >= start_year &&
          t["year"] <= end_year
      end
      values.each do |t|
        exclude = excluded_vals.select{|p| p["year"] == t["year"]}.first
        if exclude && exclude["value"]
          t["value"] = t["value"] - exclude["value"]
        end
      end
    end

    result[:years] = values.map{|t| t["year"]}
    result[:total] = values.inject(0){|sum,t| sum += t["value"]}
    result[:average] = values.empty? ? 0 : result[:total] / values.size
    result[:values] = values.map do |t|
      {
        indicator_id: t["indicator_id"],
        cartodb_id: t["cartodb_id"],
        year: t["year"],
        value: t["value"],
        country: t["country"],
        iso: t["iso"],
        boundary: t["boundary_code"],
        boundary_name: t["boundary_name"]
      }
    end
    result
  end

  def get_province_vals_for(data, indicator)

    values = data.select do |t|
      t["boundary_code"] == @use_boundary &&
        t["indicator_id"] == indicator &&
        !t["sub_nat_id"].nil? &&
        t["thresh"] == @thresh
    end.group_by{|t| t["sub_nat_id"]}

    provinces = []
    values.each do |sub_nat_id, vals|
      r = {}
      sample = vals.first

      r[:sub_nat_id] = sub_nat_id
      r[:province] = sample["province"]
      r[:indicator_id] = sample["indicator_id"]
      r[:boundary] = sample["boundary_code"]
      r[:thresh] = sample["thresh"]
      r[:boundary_name] = sample["boundary_name"]

      if @exclude_plantations
        excluded_vals = data.select do |t|
          t["boundary_code"] == INSIDE_PLANTATIONS_BOUNDARY &&
            t["indicator_id"] == indicator &&
            t["sub_nat_id"] == sub_nat_id
        end
        vals.each do |t|
          exclude = excluded_vals.select{|p| p["year"] == t["year"]}.first
          if exclude && exclude["value"]
            t["value"] = t["value"] - exclude["value"]
          end
        end
      end
      ref_vals = vals.select{|t| t["year"] >= @reference_start_year && t["year"] <= @reference_end_year }
      r[:reference_avg] = ref_vals.empty? ? nil : ref_vals.inject(0){|sum,t| sum += t["value"]} / ref_vals.size

      monit_vals = vals.select{|t| t["year"] >= @monitor_start_year && t["year"] <= @monitor_end_year }
      r[:monitor_avg] = monit_vals.empty? ? nil : monit_vals.inject(0){|sum,t| sum += t["value"]} / monit_vals.size

      next unless r[:reference_avg] && r[:monitor_avg] && r[:reference_avg] > 0

      r[:delta_perc] = (((r[:monitor_avg]-r[:reference_avg])/r[:reference_avg])*100)

      if @below && indicator == EMISSIONS
        r[:reference_avg] = r[:reference_avg] * BELOWGROUND_EMISSIONS_FACTOR
        r[:monitor_avg] = r[:monitor_avg] * BELOWGROUND_EMISSIONS_FACTOR
      end
      provinces << r
    end
    provinces.sort{|a,b| (b[:monitor_avg]-b[:reference_avg]) <=> (a[:monitor_avg]-a[:reference_avg])}
  end

  def emissions_per_provinces data
    result = {}

    result[:forest_loss] = {}
    provinces = get_province_vals_for(data, FOREST_LOSS)
    result[:forest_loss][:top_five] = provinces[0,5]

    result[:emissions] = {}
    provinces = get_province_vals_for(data, EMISSIONS)
    result[:emissions][:top_five] = provinces[0,5]

    result
  end

  def emission_factors_from data
    response = {}

    total = 0
    val = data.select do |t|
      t["boundary_code"] == @use_boundary &&
        t["indicator_id"] == ABOVE_C_DENSITY &&
        t["sub_nat_id"] == nil &&
        t["year"] = 2000
    end.first
    above = val && val["value"] or nil

    val = data.select do |t|
      t["boundary_code"] == @use_boundary &&
        t["indicator_id"] == TOTAL_C_DENSITY &&
        t["sub_nat_id"] == nil &&
        t["year"] = 2000
    end.first

    total = val && val["value"] or nil

    below = if @below
              val = data.select do |t|
                t["boundary_code"] == @use_boundary &&
                  t["indicator_id"] == BELOW_C_DENSITY &&
                  t["sub_nat_id"] == nil &&
                  t["year"] = 2000
              end.first
              val && val["value"] or nil
            else
              nil
            end

    response[:aboveground] = above
    response[:belowground] = below
    response[:total] = total
    response
  end

  def continents_query
    continent = CONTINENTS[@iso.to_sym]
    countries = continent[:countries]

    <<-SQL
      SELECT indicator_id, -1000 AS cartodb_id,
      '#{@iso}' AS iso, NULL AS sub_nat_id, values.boundary_code,
      values.thresh, '#{continent[:name]}' AS country, values.year,
      SUM(values.value) AS value, NULL AS province,
      boundaries.boundary_name
      FROM #{CDB_INDICATORS_VALUES_TABLE} AS values
      LEFT JOIN #{CDB_BOUNDARIES_TABLE} AS boundaries
      ON values.boundary_code = boundaries.boundary_code
      WHERE values.iso IN (#{countries.map{|t| "'#{t}'"}.join(",")})
        AND indicator_id IN (#{INDICATORS.join(",")})
        AND thresh IN (#{@thresh}, 0)
        AND values.boundary_code IN (#{BOUNDARIES.map{|t| "'#{t}'"}.join(",")})
        AND ((values.year >= #{@reference_start_year}
        AND values.year <= #{@monitor_end_year})
        OR values.year IN (0, 2000))
      GROUP BY indicator_id, values.boundary_code, thresh, year, boundary_name
    SQL
  end

  def select_query
    <<-SQL
      SELECT indicator_id, values.cartodb_id AS cartodb_id,
      values.iso, values.sub_nat_id, boundaries.boundary_name AS boundary, values.boundary_code,
      values.thresh, values.country, values.year,
      values.value, subnat.name_1 AS province,
      boundaries.boundary_name
      FROM #{CDB_INDICATORS_VALUES_TABLE} AS values
      LEFT JOIN #{CDB_SUBNAT_TABLE} AS subnat
      ON values.sub_nat_id  = subnat.id_1 AND values.iso = subnat.iso
      LEFT JOIN #{CDB_BOUNDARIES_TABLE} AS boundaries
      ON values.boundary_code = boundaries.boundary_code
    SQL
  end

  def where_clause
    <<-SQL
      WHERE values.iso = '#{@iso}'
        AND indicator_id IN (#{INDICATORS.join(",")})
        AND thresh IN (#{@thresh}, 0)
        AND values.boundary_code IN (#{BOUNDARIES.map{|t| "'#{t}'"}.join(",")})
        AND ((values.year >= #{@reference_start_year}
        AND values.year <= #{@monitor_end_year})
        OR values.year IN (0,2000))
    SQL
  end

  def name
    "country-report"
  end
end


text:
#include "modules/rtp_rtcp/source/tmmbr_help.h"

#include <stddef.h>

#include <limits>

#include "absl/algorithm/container.h"
#include "rtc_base/checks.h"

namespace webrtc {
std::vector<rtcp::TmmbItem> TMMBRHelp::FindBoundingSet(
    std::vector<rtcp::TmmbItem> candidates) {
  // Filter out candidates with 0 bitrate.
  for (auto it = candidates.begin(); it != candidates.end();) {
    if (!it->bitrate_bps())
      it = candidates.erase(it);
    else
      ++it;
  }

  if (candidates.size() <= 1)
    return candidates;

  size_t num_candidates = candidates.size();

  // 1. Sort by increasing packet overhead.
  absl::c_sort(candidates,
               [](const rtcp::TmmbItem& lhs, const rtcp::TmmbItem& rhs) {
                 return lhs.packet_overhead() < rhs.packet_overhead();
               });

  // 2. For tuples with same overhead, keep the one with the lowest bitrate.
  for (auto it = candidates.begin(); it != candidates.end();) {
    RTC_DCHECK(it->bitrate_bps());
    auto current_min = it;
    auto next_it = it + 1;
    // Use fact candidates are sorted by overhead, so candidates with same
    // overhead are adjusted.
    while (next_it != candidates.end() &&
           next_it->packet_overhead() == current_min->packet_overhead()) {
      if (next_it->bitrate_bps() < current_min->bitrate_bps()) {
        current_min->set_bitrate_bps(0);
        current_min = next_it;
      } else {
        next_it->set_bitrate_bps(0);
      }
      ++next_it;
      --num_candidates;
    }
    it = next_it;
  }

  // 3. Select and remove tuple with lowest bitrate.
  // (If more than 1, choose the one with highest overhead).
  auto min_bitrate_it = candidates.end();
  for (auto it = candidates.begin(); it != candidates.end(); ++it) {
    if (it->bitrate_bps()) {
      min_bitrate_it = it;
      break;
    }
  }

  for (auto it = min_bitrate_it; it != candidates.end(); ++it) {
    if (it->bitrate_bps() &&
        it->bitrate_bps() <= min_bitrate_it->bitrate_bps()) {
      // Get min bitrate.
      min_bitrate_it = it;
    }
  }

  std::vector<rtcp::TmmbItem> bounding_set;
  bounding_set.reserve(num_candidates);
  std::vector<float> intersection(num_candidates);
  std::vector<float> max_packet_rate(num_candidates);

  // First member of selected list.
  bounding_set.push_back(*min_bitrate_it);
  intersection[0] = 0;
  // Calculate its maximum packet rate (where its line crosses x-axis).
  uint16_t packet_overhead = bounding_set.back().packet_overhead();
  if (packet_overhead == 0) {
    // Avoid division by zero.
    max_packet_rate[0] = std::numeric_limits<float>::max();
  } else {
    max_packet_rate[0] =
        bounding_set.back().bitrate_bps() / static_cast<float>(packet_overhead);
  }
  // Remove from candidate list.
  min_bitrate_it->set_bitrate_bps(0);
  --num_candidates;

  // 4. Discard from candidate list all tuple with lower overhead
  // (next tuple must be steeper).
  for (auto it = candidates.begin(); it != candidates.end(); ++it) {
    if (it->bitrate_bps() &&
        it->packet_overhead() < bounding_set.front().packet_overhead()) {
      it->set_bitrate_bps(0);
      --num_candidates;
    }
  }

  bool get_new_candidate = true;
  rtcp::TmmbItem cur_candidate;
  while (num_candidates > 0) {
    if (get_new_candidate) {
      // 5. Remove first remaining tuple from candidate list.
      for (auto it = candidates.begin(); it != candidates.end(); ++it) {
        if (it->bitrate_bps()) {
          cur_candidate = *it;
          it->set_bitrate_bps(0);
          break;
        }
      }
    }

    // 6. Calculate packet rate and intersection of the current
    // line with line of last tuple in selected list.
    RTC_DCHECK_NE(cur_candidate.packet_overhead(),
                  bounding_set.back().packet_overhead());
    float packet_rate = static_cast<float>(cur_candidate.bitrate_bps() -
                                           bounding_set.back().bitrate_bps()) /
                        (cur_candidate.packet_overhead() -
                         bounding_set.back().packet_overhead());

    // 7. If the packet rate is equal or lower than intersection of
    //    last tuple in selected list,
    //    remove last tuple in selected list & go back to step 6.
    if (packet_rate <= intersection[bounding_set.size() - 1]) {
      // Remove last tuple and goto step 6.
      bounding_set.pop_back();
      get_new_candidate = false;
    } else {
      // 8. If packet rate is lower than maximum packet rate of
      // last tuple in selected list, add current tuple to selected
      // list.
      if (packet_rate < max_packet_rate[bounding_set.size() - 1]) {
        bounding_set.push_back(cur_candidate);
        intersection[bounding_set.size() - 1] = packet_rate;
        uint16_t packet_overhead = bounding_set.back().packet_overhead();
        RTC_DCHECK_NE(packet_overhead, 0);
        max_packet_rate[bounding_set.size() - 1] =
            bounding_set.back().bitrate_bps() /
            static_cast<float>(packet_overhead);
      }
      --num_candidates;
      get_new_candidate = true;
    }

    // 9. Go back to step 5 if any tuple remains in candidate list.
  }
  RTC_DCHECK(!bounding_set.empty());
  return bounding_set;
}

bool TMMBRHelp::IsOwner(const std::vector<rtcp::TmmbItem>& bounding,
                        uint32_t ssrc) {
  for (const rtcp::TmmbItem& item : bounding) {
    if (item.ssrc() == ssrc) {
      return true;
    }
  }
  return false;
}

uint64_t TMMBRHelp::CalcMinBitrateBps(
    const std::vector<rtcp::TmmbItem>& candidates) {
  RTC_DCHECK(!candidates.empty());
  uint64_t min_bitrate_bps = std::numeric_limits<uint64_t>::max();
  for (const rtcp::TmmbItem& item : candidates)
    if (item.bitrate_bps() < min_bitrate_bps)
      min_bitrate_bps = item.bitrate_bps();
  return min_bitrate_bps;
}
}  // namespace webrtc


text:
namespace Egs.ZkooTutorial
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Windows;
    using System.ComponentModel;

    class TutorialUpperSideMessageAreaViewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        protected virtual void OnPropertyChanged(string propertyName)
        {
            var t = PropertyChanged;
            if (t != null) { t(this, new PropertyChangedEventArgs(propertyName)); }
        }

        string _LeftTextBlockText;
        public string LeftTextBlockText
        {
            get { return _LeftTextBlockText; }
            set { _LeftTextBlockText = value; OnPropertyChanged(nameof(LeftTextBlockText)); }
        }
        string _RightTextBlockText;
        public string RightTextBlockText
        {
            get { return _RightTextBlockText; }
            set { _RightTextBlockText = value; OnPropertyChanged(nameof(RightTextBlockText)); }
        }
        Visibility _Visibility;
        public Visibility Visibility
        {
            get { return _Visibility; }
            set { _Visibility = value; OnPropertyChanged(nameof(Visibility)); }
        }

        public TutorialUpperSideMessageAreaViewModel()
        {
            _RightTextBlockText = "";
            _LeftTextBlockText = "";
            _Visibility = Visibility.Collapsed;
        }
    }

    class TutorialUpperSideMessageAreaViewModelExample : TutorialUpperSideMessageAreaViewModel
    {
        public TutorialUpperSideMessageAreaViewModelExample()
            : base()
        {
            // TODO: make localized string
            RightTextBlockText = $"{ApplicationCommonSettings.HostApplicationName} will be in the center of the screen.\n"
                + "Sit away 7ft.\n"
                + "Toward the front of the camera, in the middle.\n"
                + "To adjust the angle of the camera to see the Installation Guide.\n";
            LeftTextBlockText = "Well done.";
            Visibility = Visibility.Visible;
        }
    }
}


text:
package org.finos.waltz.model.actor;

import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import org.finos.waltz.model.command.EntityChangeCommand;
import org.finos.waltz.model.command.FieldChange;
import org.immutables.value.Value;

import java.util.Optional;

@Value.Immutable
@JsonSerialize(as = ImmutableActorChangeCommand.class)
@JsonDeserialize(as = ImmutableActorChangeCommand.class)
public abstract class ActorChangeCommand implements EntityChangeCommand {

    public abstract Optional<FieldChange<String>> name();

    public abstract Optional<FieldChange<String>> description();

    public abstract Optional<FieldChange<Boolean>> isExternal();

    public abstract Optional<FieldChange<String>> externalId();

 }


text:
const less = require('less')

module.exports = (data, filename) => {
    return less.render(data)
}


text:
package org.springframework.dao;

/**
 * Generic exception thrown when the current process was
 * a deadlock loser, and its transaction rolled back.
 *
 * @author Rod Johnson
 */
@SuppressWarnings("serial")
public class DeadlockLoserDataAccessException extends PessimisticLockingFailureException {

	/**
	 * Constructor for DeadlockLoserDataAccessException.
	 * @param msg the detail message
	 * @param cause the root cause from the data access API in use
	 */
	public DeadlockLoserDataAccessException(String msg, Throwable cause) {
		super(msg, cause);
	}

}


text:
void test_buffer_1()
{
  TRACE_ENTER;
  BUFFER v = buffer_alloc("", BUF_FLG_INTERNAL, 0, default_profile);

  if (buffer_capacity(v) != 1)
    failtest("capacity %d != 1", buffer_capacity(v));
  if (buffer_count(v) != 0)
    failtest("count %d != 0", buffer_count(v));

  buffer_free(v);

  if (marks_count() > 1)
    failtest("%d unfreed marks", marks_count());
  if (buffers_count() != 0)
    failtest("%d unfreed buffers", buffers_count());

  TRACE_EXIT;
}

// test appending single line
void test_buffer_2()
{
  TRACE_ENTER;
  struct line_t l;
  BUFFER v = buffer_alloc("", BUF_FLG_INTERNAL, 0, default_profile);

  cstr_initstr(&l.txt, "This is a test");
  l.flags = 0;

  buffer_appendline(v, &l);

  if (buffer_capacity(v) != 1)
    failtest("capacity %d != 1", buffer_capacity(v));
  if (buffer_count(v) != 1)
    failtest("count %d != 1", buffer_count(v));

  cstr_destroy(&l.txt);
  buffer_free(v);

  if (marks_count() > 1)
    failtest("%d unfreed marks", marks_count());
  if (buffers_count() != 0)
    failtest("%d unfreed buffers", buffers_count());
  TRACE_EXIT;
}

// test appending two lines
void test_buffer_3()
{
  TRACE_ENTER;
  struct line_t l;
  BUFFER v = buffer_alloc("", BUF_FLG_INTERNAL, 0, default_profile);

  cstr_initstr(&l.txt, "This is a test");
  l.flags = 0;
  buffer_appendline(v, &l);

  cstr_assignstr(&l.txt, "This is also a test");
  buffer_appendline(v, &l);

  if (buffer_capacity(v) != 2)
    failtest("capacity %d != 2", buffer_capacity(v));
  if (buffer_count(v) != 2)
    failtest("count %d != 2", buffer_count(v));

  cstr_destroy(&l.txt);
  buffer_free(v);

  if (marks_count() > 1)
    failtest("%d unfreed marks", marks_count());
  if (buffers_count() != 0)
    failtest("%d unfreed buffers", buffers_count());
  TRACE_EXIT;
}

// test appending three lines
void test_buffer_4()
{
  TRACE_ENTER;
  struct line_t l;
  BUFFER v = buffer_alloc("", BUF_FLG_INTERNAL, 0, default_profile);

  cstr_initstr(&l.txt, "This is a test");
  l.flags = 0;
  buffer_appendline(v, &l);

  cstr_assignstr(&l.txt, "This is also a test");
  buffer_appendline(v, &l);

  cstr_assignstr(&l.txt, "As is this");
  buffer_appendline(v, &l);

  if (buffer_capacity(v) != 4)
    failtest("capacity %d != 4", buffer_capacity(v));
  if (buffer_count(v) != 3)
    failtest("count %d != 3", buffer_count(v));

  cstr_destroy(&l.txt);
  buffer_free(v);

  if (marks_count() > 1)
    failtest("%d unfreed marks", marks_count());
  if (buffers_count() != 0)
    failtest("%d unfreed buffers", buffers_count());
  TRACE_EXIT;
}

// test get line
void test_buffer_5()
{
  TRACE_ENTER;
  struct line_t l;
  struct line_t* pl;
  BUFFER v = buffer_alloc("", BUF_FLG_INTERNAL, 0, default_profile);

  cstr_initstr(&l.txt, "This is a test");
  l.flags = 0;
  buffer_appendline(v, &l);

  cstr_assignstr(&l.txt, "This is also a test");
  buffer_appendline(v, &l);

  cstr_assignstr(&l.txt, "As is this");
  buffer_appendline(v, &l);

  pl = buffer_get(v, 0);
  if (cstr_comparestr(&pl->txt, "This is a test") != 0)
    failtest("line 0 != 'This is a test'\n");
  pl = buffer_get(v, 1);
  if (cstr_comparestr(&pl->txt, "This is also a test") != 0)
    failtest("line 0 != 'This is also a test'\n");
  pl = buffer_get(v, 2);
  if (cstr_comparestr(&pl->txt, "As is this") != 0)
    failtest("line 0 != 'As is this'\n");

  cstr_destroy(&l.txt);
  buffer_free(v);

  if (marks_count() > 1)
    failtest("%d unfreed marks", marks_count());
  if (buffers_count() != 0)
    failtest("%d unfreed buffers", buffers_count());
  TRACE_EXIT;
}

// test overwrite line text
void test_buffer_6()
{
  TRACE_ENTER;
  struct line_t l;
  struct line_t* pl;
  struct cstr_t s;
  BUFFER v = buffer_alloc("", BUF_FLG_INTERNAL, 0, default_profile);

  cstr_initstr(&s, "This is a test");
  cstr_initstr(&l.txt, "This is a test");

  l.flags = 0;
  buffer_appendline(v, &l);

  cstr_assignstr(&l.txt, "This is also a test");
  buffer_appendline(v, &l);

  cstr_assignstr(&l.txt, "As is this");
  buffer_appendline(v, &l);

  buffer_setcstr(v, 1, &s);

  pl = buffer_get(v, 1);
  if (cstr_comparestr(&pl->txt, "This is a test") != 0)
    failtest("line 1 != 'This is a test'\n");

  cstr_destroy(&l.txt);
  cstr_destroy(&s);
  buffer_free(v);

  if (marks_count() > 1)
    failtest("%d unfreed marks", marks_count());
  if (buffers_count() != 0)
    failtest("%d unfreed buffers", buffers_count());
  TRACE_EXIT;
}

// test remove multiple lines
void test_buffer_7()
{
  TRACE_ENTER;
  struct line_t l;
  //  struct line_t* pl;
  BUFFER v = buffer_alloc("", BUF_FLG_INTERNAL, 0, default_profile);

  cstr_initstr(&l.txt, "This is a test");
  l.flags = 0;
  buffer_appendline(v, &l);

  cstr_assignstr(&l.txt, "This is also a test");
  buffer_appendline(v, &l);

  cstr_assignstr(&l.txt, "As is this");
  buffer_appendline(v, &l);

  cstr_assignstr(&l.txt, "And this too");
  buffer_appendline(v, &l);

  if (buffer_count(v) != 4)
    failtest("count %d != 4", buffer_count(v));

  buffer_removelines(v, 1, 2, false);
  if (buffer_count(v) != 2)  // this was commented out for some reason
    failtest("count %d != 2", buffer_count(v)); //...

  cstr_destroy(&l.txt);
  buffer_free(v);

  if (marks_count() > 1)
    failtest("%d unfreed marks", marks_count());
  if (buffers_count() != 0)
    failtest("%d unfreed buffers", buffers_count());
  TRACE_EXIT;
}

// test insertchar
void test_buffer_8()
{
  TRACE_ENTER;
  struct line_t l;
  //struct line_t* pl;
  BUFFER v = buffer_alloc("", BUF_FLG_INTERNAL, 0, default_profile);

  cstr_initstr(&l.txt, "This is a test");
  l.flags = 0;
  buffer_appendline(v, &l);

  cstr_assignstr(&l.txt, "This is also a test");
  buffer_appendline(v, &l);

  buffer_insert(v, 1, 0, '*', false);
  if (strcmp(buffer_getbufptr(v, 1), "*This is also a test") != 0) {
    failtest("didn't insert '*'");
  }

  cstr_destroy(&l.txt);
  buffer_free(v);

  if (marks_count() > 1)
    failtest("%d unfreed marks", marks_count());
  if (buffers_count() != 0)
    failtest("%d unfreed buffers", buffers_count());
  TRACE_EXIT;
}

// test insert C string
void test_buffer_9()
{
  TRACE_ENTER;
  struct line_t l;
  //struct line_t* pl;
  BUFFER v = buffer_alloc("", BUF_FLG_INTERNAL, 0, default_profile);

  cstr_initstr(&l.txt, "This is a test");
  l.flags = 0;
  buffer_appendline(v, &l);

  cstr_assignstr(&l.txt, "This is also a test");
  buffer_appendline(v, &l);

  buffer_insertstrn(v, 1, 0, "*!@", 4, false);
  if (strcmp(buffer_getbufptr(v, 1), "*!@This is also a test") != 0)
    failtest("didn't insert '*!@', -> '%s'", buffer_getbufptr(v, 1));

  cstr_destroy(&l.txt);
  buffer_free(v);

  if (marks_count() > 1)
    failtest("%d unfreed marks", marks_count());
  if (buffers_count() != 0)
    failtest("%d unfreed buffers", buffers_count());
  TRACE_EXIT;
}

// test overwrite char
void test_buffer_10()
{
  TRACE_ENTER;
  struct line_t l;
  //struct line_t* pl;
  BUFFER v = buffer_alloc("", BUF_FLG_INTERNAL, 0, default_profile);

  cstr_initstr(&l.txt, "This is a test");
  l.flags = 0;
  buffer_appendline(v, &l);

  cstr_assignstr(&l.txt, "This is also a test");
  buffer_appendline(v, &l);

  buffer_setchar(v, 1, 0, '*');
  if (strcmp(buffer_getbufptr(v, 1), "*his is also a test") != 0)
    failtest("didn't set '*'");

  cstr_destroy(&l.txt);
  buffer_free(v);

  if (marks_count() > 1)
    failtest("%d unfreed marks", marks_count());
  if (buffers_count() != 0)
    failtest("%d unfreed buffers", buffers_count());
  TRACE_EXIT;
}

// test overwrite C string
void test_buffer_11()
{
  TRACE_ENTER;
  struct line_t l;
  //struct line_t* pl;
  BUFFER v = buffer_alloc("", BUF_FLG_INTERNAL, 0, default_profile);

  cstr_initstr(&l.txt, "This is a test");
  l.flags = 0;
  buffer_appendline(v, &l);

  cstr_assignstr(&l.txt, "This is also a test");
  buffer_appendline(v, &l);

  // setstrn should stop at the null, even though we said to use it
  buffer_setstrn(v, 1, 0, "*!@", 4, false);
  if (strcmp(buffer_getbufptr(v, 1), "*!@s is also a test") != 0)
    failtest("didn't set '*!@', -> '%s'", buffer_getbufptr(v, 1));

  cstr_destroy(&l.txt);
  buffer_free(v);

  if (marks_count() > 1)
    failtest("%d unfreed marks", marks_count());
  if (buffers_count() != 0)
    failtest("%d unfreed buffers", buffers_count());
  TRACE_EXIT;
}

// test remove char
void test_buffer_12()
{
  TRACE_ENTER;
  struct line_t l;
  //struct line_t* pl;
  BUFFER v = buffer_alloc("", BUF_FLG_INTERNAL, 0, default_profile);

  cstr_initstr(&l.txt, "This is a test");
  l.flags = 0;
  buffer_appendline(v, &l);

  cstr_assignstr(&l.txt, "This is also a test");
  buffer_appendline(v, &l);

  buffer_removechar(v, 1, 0, false);
  if (strcmp(buffer_getbufptr(v, 1), "his is also a test") != 0)
    failtest("didn't remove char");

  cstr_destroy(&l.txt);
  buffer_free(v);

  if (marks_count() > 1)
    failtest("%d unfreed marks", marks_count());
  if (buffers_count() != 0)
    failtest("%d unfreed buffers", buffers_count());
  TRACE_EXIT;
}

// test remove multiple chars on a line
void test_buffer_13()
{
  TRACE_ENTER;
  struct line_t l;
  //struct line_t* pl;
  BUFFER v = buffer_alloc("", BUF_FLG_INTERNAL, 0, default_profile);

  cstr_initstr(&l.txt, "This is a test");
  l.flags = 0;
  buffer_appendline(v, &l);

  cstr_assignstr(&l.txt, "This is also a test");
  buffer_appendline(v, &l);

  buffer_removechars(v, 1, 0, 3, false);
  if (strcmp(buffer_getbufptr(v, 1), "s is also a test") != 0)
    failtest("didn't remove chars");

  cstr_destroy(&l.txt);
  buffer_free(v);

  if (marks_count() > 1)
    failtest("%d unfreed marks", marks_count());
  if (buffers_count() != 0)
    failtest("%d unfreed buffers", buffers_count());
  TRACE_EXIT;
}

// test uppercase chars
void test_buffer_14()
{
  TRACE_ENTER;
  struct line_t l;
  //struct line_t* pl;
  BUFFER v = buffer_alloc("", BUF_FLG_INTERNAL, 0, default_profile);

  cstr_initstr(&l.txt, "This is a test");
  l.flags = 0;
  buffer_appendline(v, &l);

  cstr_assignstr(&l.txt, "This is also a test");
  buffer_appendline(v, &l);

  buffer_upperchars(v, 1, 0, 4);
  if (strcmp(buffer_getbufptr(v, 1), "THIS is also a test") != 0)
    failtest("didn't uppercase");

  cstr_destroy(&l.txt);
  buffer_free(v);

  if (marks_count() > 1)
    failtest("%d unfreed marks", marks_count());
  if (buffers_count() != 0)
    failtest("%d unfreed buffers", buffers_count());
  TRACE_EXIT;
}

// test lowercase chars
void test_buffer_15()
{
  TRACE_ENTER;
  struct line_t l;
  //struct line_t* pl;
  BUFFER v = buffer_alloc("", BUF_FLG_INTERNAL, 0, default_profile);

  cstr_initstr(&l.txt, "This is a test");
  l.flags = 0;
  buffer_appendline(v, &l);

  cstr_assignstr(&l.txt, "This is also a test");
  buffer_appendline(v, &l);

  buffer_lowerchars(v, 1, 0, 4);
  if (strcmp(buffer_getbufptr(v, 1), "this is also a test") != 0)
    failtest("didn't lowercase");

  cstr_destroy(&l.txt);
  buffer_free(v);

  if (marks_count() > 1)
    failtest("%d unfreed marks", marks_count());
  if (buffers_count() != 0)
    failtest("%d unfreed buffers", buffers_count());
  TRACE_EXIT;
}

// test copyinsertlines
void test_buffer_16()
{
  TRACE_ENTER;
  struct line_t l;
  BUFFER v = buffer_alloc("", BUF_FLG_INTERNAL, 0, default_profile);
  BUFFER u = buffer_alloc("", BUF_FLG_INTERNAL, 0, default_profile);

  cstr_initstr(&l.txt, "This is a test");
  l.flags = 0;
  buffer_appendline(v, &l);

  cstr_assignstr(&l.txt, "This is also a test");
  buffer_appendline(v, &l);

  cstr_assignstr(&l.txt, "As is this");
  buffer_appendline(u, &l);

  cstr_assignstr(&l.txt, "And this too");
  buffer_appendline(u, &l);

  if (buffer_count(v) != 2)
    failtest("count v %d != 2", buffer_count(v));

  if (buffer_count(u) != 2)
    failtest("count u %d != 2", buffer_count(u));

  buffer_copyinsertlines(v, 1, u, 0, 2, false);

  if (buffer_count(v) != 4)
    failtest("count v %d != 4", buffer_count(v));
  if (buffer_count(u) != 2)
    failtest("count u %d != 2", buffer_count(u));

  if (strcmp(buffer_getbufptr(v, 0), "This is a test") != 0)
    failtest("first line didn't copy correctly\n");
  if (strcmp(buffer_getbufptr(v, 1), "As is this") != 0)
    failtest("second line didn't copy correctly\n");
  if (strcmp(buffer_getbufptr(v, 2), "And this too") != 0)
    failtest("first line didn't copy correctly\n");
  if (strcmp(buffer_getbufptr(v, 3), "This is also a test") != 0)
    failtest("second line didn't copy correctly\n");

  cstr_destroy(&l.txt);
  buffer_free(u);
  buffer_free(v);

  if (marks_count() > 1)
    failtest("%d unfreed marks", marks_count());
  if (buffers_count() != 0)
    failtest("%d unfreed buffers", buffers_count());
  TRACE_EXIT;
}

// test moveinsertlines
// moveinsertlines been removed from buffer.c
void test_buffer_17()
{
  TRACE_ENTER;
  TRACE_EXIT;
}

// test buffer_load
void test_buffer_18()
{
  TRACE_ENTER;

  BUFFER v = buffer_alloc("", BUF_FLG_INTERNAL, 0, default_profile);
  cstr t1filename;
  cstr_initstr(&t1filename, "t1.txt");
  POE_ERR err = buffer_load(v, &t1filename, 1);
  if (err != POE_ERR_OK)
    failtest("error %d loading t1_rdonly.txt", err);

  if (strcmp(buffer_name(v), "t1.txt") != 0)
    failtest("t1.txt buffer has name '%s'\n", buffer_name(v));

  const char* master = "Four score and seven years ago our fathers brought forth on this continent";
  const char* s = buffer_getbufptr(v, 0);
  if (strcmp(s, master) != 0) {
    printf("%s: c3\n", __func__);
    failtest("first line didn't load correctly\n");
  }

  master = "                        this is the last line";
  //       |                        this is the last line

  int linect = buffer_count(v);
  const char* lastline = buffer_getbufptr(v, linect-1);
  if (strcmp(lastline, master) != 0) {
    if (strlen(master) != strlen(lastline))
      failtest("last line didn't load correctly, expected len %d got %d\n",
               strlen(master), strlen(lastline));
    int i, n = strlen(lastline);
    for (i = 0; i < n; i++) {
      if (master[i] != lastline[i]) {
        failtest("difference @ %d expected char %c(%d) vs %c(%d)\n",
                 i,
                 master[i], master[i],
                 lastline[i], lastline[i]);
      }
    }
  }

  if (buffer_tstflags(v, BUF_FLG_RDONLY)) {
    failtest("buffer should be writable\n");
  }

  buffer_free(v);
  cstr_destroy(&t1filename);

  if (marks_count() > 1)
    failtest("%d unfreed marks", marks_count());
  if (buffers_count() != 0)
    failtest("%d unfreed buffers", buffers_count());

  TRACE_EXIT;
}

// test buffer_load of rdonly file
void test_buffer_19()
{
  TRACE_ENTER;
  BUFFER v = buffer_alloc("", BUF_FLG_INTERNAL, 0, default_profile);
  cstr t1ro_filename;
  cstr_initstr(&t1ro_filename, "t1_rdonly.txt");
  POE_ERR err = buffer_load(v, &t1ro_filename, 1);
  if (err != POE_ERR_OK)
    failtest("error %d loading t1_rdonly.txt", err);

  if (strcmp(buffer_name(v), "t1_rdonly.txt") != 0)
    failtest("t1_rdonly.txt buffer has name '%s'\n", buffer_name(v));

  const char* master = "Four score and seven years ago our fathers brought forth on this continent";
  if (strcmp(buffer_getbufptr(v, 0), master) != 0)
    failtest("first line didn't load correctly\n");

  master = "                        this is the last line";
  int linect = buffer_count(v);
  const char* lastline = buffer_getbufptr(v, linect-1);
  if (strcmp(lastline, master) != 0) {
    if (strlen(master) != strlen(lastline))
      failtest("last line didn't load correctly, expected len %d got %d\n",
               strlen(master), strlen(lastline));
    int i, n = strlen(lastline);
    for (i = 0; i < n; i++) {
      if (master[i] != lastline[i]) {
        failtest("difference @ %d expected char %c(%d) vs %c(%d)\n",
                 i,
                 master[i], master[i],
                 lastline[i], lastline[i]);
      }
    }
  }

  if (!buffer_tstflags(v, BUF_FLG_RDONLY)) {
    failtest("buffer t1_rdonly.txt should be readonly\n");
  }

  buffer_free(v);
  cstr_destroy(&t1ro_filename);

  if (marks_count() > 1)
    failtest("%d unfreed marks", marks_count());
  if (buffers_count() != 0)
    failtest("%d unfreed buffers", buffers_count());
  TRACE_EXIT;
}

// test buffer_load of rdonly file, twice
void test_buffer_20()
{
  TRACE_ENTER;
  BUFFER v = buffer_alloc("", BUF_FLG_INTERNAL, 0, default_profile);
  cstr t1ro_filename;
  cstr_initstr(&t1ro_filename, "t1_rdonly.txt");
  POE_ERR err = buffer_load(v, &t1ro_filename, 1);
  if (err != POE_ERR_OK)
    failtest("error %d loading t1_rdonly.txt", err);

  BUFFER w = buffer_alloc("", BUF_FLG_INTERNAL, 0, default_profile);
  err = buffer_load(w, &t1ro_filename, 1);
  if (err != POE_ERR_OK)
    failtest("error %d loading t1_rdonly.txt the second time", err);

  if (strcmp(buffer_name(v), "t1_rdonly.txt") != 0)
    failtest("t1_rdonly.txt buffer has name '%s'\n", buffer_name(v));

  if (strcmp(buffer_name(w), "t1_rdonly.txt<2>") != 0)
    failtest("t1_rdonly.txt<2> buffer has name '%s'\n", buffer_name(v));

  // check first line
  const char* master = "Four score and seven years ago our fathers brought forth on this continent";
  if (strcmp(buffer_getbufptr(v, 0), master) != 0)
    failtest("first line didn't load correctly\n");

  // check line 27 (leading tabs + trailing tabs after quotation mark)
  master = "                        this is a test line with \"trailing\" tabs                                        ";
  int linect = buffer_count(v);
  const char* line27 = buffer_getbufptr(v, 27);
  if (strcmp(line27, master) != 0) {
    if (strlen(master) != strlen(line27))
      failtest("last line didn't load correctly, expected len %d got %d\n",
               strlen(master), strlen(line27));
    int i, n = strlen(line27);
    for (i = 0; i < n; i++) {
      if (master[i] != line27[i]) {
        failtest("difference @ %d expected char %c(%d) vs %c(%d)\n",
                 i,
                 master[i], master[i],
                 line27[i], line27[i]);
      }
    }
  }

  // check last line
  master = "                        this is the last line";
  linect = buffer_count(v);
  const char* lastline = buffer_getbufptr(v, linect-1);
  if (strcmp(lastline, master) != 0) {
    if (strlen(master) != strlen(lastline))
      failtest("last line didn't load correctly, expected len %d got %d\n",
               strlen(master), strlen(lastline));
    int i, n = strlen(lastline);
    for (i = 0; i < n; i++) {
      if (master[i] != lastline[i]) {
        failtest("difference @ %d expected char %c(%d) vs %c(%d)\n",
                 i,
                 master[i], master[i],
                 lastline[i], lastline[i]);
      }
    }
  }

  if (!buffer_tstflags(v, BUF_FLG_RDONLY)) {
    failtest("buffer t1_rdonly.txt should be readonly\n");
  }

  if (!buffer_tstflags(w, BUF_FLG_RDONLY)) {
    failtest("buffer t1_rdonly.txt should be readonly\n");
  }

  buffer_free(v);
  buffer_free(w);
  cstr_destroy(&t1ro_filename);

  if (marks_count() > 1)
    failtest("%d unfreed marks", marks_count());
  if (buffers_count() != 0)
    failtest("%d unfreed buffers", buffers_count());
  TRACE_EXIT;
}

// test buffer_load of rdonly file
void test_buffer_21()
{
  TRACE_ENTER;
  BUFFER v = buffer_alloc("", BUF_FLG_INTERNAL, 0, default_profile);
  cstr t1ro_filename;
  cstr_initstr(&t1ro_filename, "t1_rdonly.txt");
  POE_ERR err = buffer_load(v, &t1ro_filename, 1);
  if (err != POE_ERR_OK)
    failtest("error %d loading t1_rdonly.txt", err);

  cstr t1save_filename;
  cstr_initstr(&t1save_filename, "t1_save.txt");
  err = buffer_save(v, &t1save_filename, 1);
  if (err != POE_ERR_OK)
    failtest("error %d saving t1_save.txt", err);

  BUFFER w = buffer_alloc("", BUF_FLG_INTERNAL, 0, default_profile);
  err = buffer_load(w, &t1save_filename, 1);
  if (err != POE_ERR_OK)
    failtest("error %d loading t1_save.txt", err);

  cstr t1save2_filename;
  cstr_initstr(&t1save2_filename, "t1_save2.txt");
  err = buffer_save(w, &t1save2_filename, 1);
  if (err != POE_ERR_OK)
    failtest("error %d saving t1_save2.txt", err);

  // check the line counts
  if (buffer_count(v) != buffer_count(w))
    failtest("t1_rdonly.txt has %d lines, t1_save.txt has %d lines",
             buffer_count(v),
             buffer_count(w));

  // check the line contents
  int i;
  int n = buffer_count(v);
  for (i = 0; i < n; i++) {
    const char* a = buffer_getbufptr(v, i);
    const char* b = buffer_getbufptr(w, i);
    if (strlen(a) != strlen(b))
      failtest("line %d is %d chars long on t1_readonly.txt, but %d chars long on t1_save.txt",
               strlen(a), strlen(b));
    if (strcmp(a, b) != 0)
      failtest("line %d different between t1_readonly.txt and t1_save.txt", i);
  }

  unlink("t1_save.txt");
  unlink("t1_save2.txt");
  buffer_free(v);
  buffer_free(w);
  cstr_destroy(&t1ro_filename);
  cstr_destroy(&t1save_filename);
  cstr_destroy(&t1save2_filename);

  if (marks_count() > 1)
    failtest("%d unfreed marks", marks_count());
  if (buffers_count() != 0)
    failtest("%d unfreed buffers", buffers_count());
  TRACE_EXIT;
}


text:
import {
  getNumberFormatter,
  GenericDataType,
  getMetricLabel,
  extractTimegrain,
  QueryFormData,
} from '@superset-ui/core';
import { BigNumberTotalChartProps } from '../types';
import { getDateFormatter, parseMetricValue } from '../utils';

export default function transformProps(chartProps: BigNumberTotalChartProps) {
  const { width, height, queriesData, formData, rawFormData } = chartProps;
  const {
    headerFontSize,
    metric = 'value',
    subheader = '',
    subheaderFontSize,
    forceTimestampFormatting,
    timeFormat,
    yAxisFormat,
  } = formData;
  const { data = [], coltypes = [] } = queriesData[0];
  const granularity = extractTimegrain(rawFormData as QueryFormData);
  const metricName = getMetricLabel(metric);
  const formattedSubheader = subheader;
  const bigNumber =
    data.length === 0 ? null : parseMetricValue(data[0][metricName]);

  let metricEntry;
  if (chartProps.datasource && chartProps.datasource.metrics) {
    metricEntry = chartProps.datasource.metrics.find(
      metricItem => metricItem.metric_name === metric,
    );
  }

  const formatTime = getDateFormatter(
    timeFormat,
    granularity,
    metricEntry?.d3format,
  );

  const headerFormatter =
    coltypes[0] === GenericDataType.TEMPORAL ||
    coltypes[0] === GenericDataType.STRING ||
    forceTimestampFormatting
      ? formatTime
      : getNumberFormatter(yAxisFormat ?? metricEntry?.d3format ?? undefined);

  return {
    width,
    height,
    bigNumber,
    headerFormatter,
    headerFontSize,
    subheaderFontSize,
    subheader: formattedSubheader,
  };
}


text:
This guide describes the file-level mechanics of building and managing themes with
Sencha Cmd, which can automate several of the steps required to build a theme. Note
that developing themes or managing styles or SASS variables are not covered here -- these
are part of your application development process.

{@img ../command/sencha-command-128.png}

## Getting Started

First, in order to build themes from SASS, be sure to install [Compass](http://compass-style.org/)
on your system.

Most of this guide assumes you are working in an application generated by Sencha Cmd. If
that is not the case, many of these steps will change to reflect different paths and the
like. See the section below on "Managing Themes Manually".

All applications start with a "default" theme. Different pieces are stored in two folders:

 * `./resources/theme/default`
 * `./resources/theme/default/sass`

### Use of SASS

The majority of your work on themes is done in SASS. The starter files are generated for
you, and you edit them to complete your theme. When you compile your SASS, it should generate
a CSS file in `"./.res/default"` named `"app.css"`.

## Multiple Themes

If you need two or more themes (as described in [Using Sencha Cmd with Ext JS](#/guide/command_app)),
you can generate new themes with this command:

    sencha generate theme foo

This will generate the following:

 - `./resources/theme/foo/sass`

The SASS should be compiled to `"./.res/foo/app.css"`.

## Building an Application's Themes

The `sencha app build` command will produce full image sets for all themes in a given
application as part of the standard build process.  To achieve this, images from the
base framework theme are first staged into the `"resources/.img/<theme name>"` directory
under the application's root directory.  Then, sliced images for each theme are generated
using the technique described in the following section and overlaid over the theme images
provided by the framework.  Finally, user supplied images located in the application's
`"resources/images"` directory are overlaid into the output of the theme build operations to
produce the final image set.  The resultant application resource directory will have the
following structure:

    resources/
        images/             # application-wide image content and theme image overrides
            ...
        theme/
            default/
                sass/       # sass input files for the default theme
            ...
    .res/
        default/
            images/         # unified image content generate by build process
        ...

All output images are staged into a `".res"` directory under the application's source directory
to enable development-time viewing of a built theme. This `".res"` directory is then
copied to the application's build output folder to maintain relative paths for
deployment. As this generated `".res"` directory is generated to a file system location
commonly under revision control, it may be desirable to add this directory to the revision
control system's exclusion mechanism (such as a .gitignore entry).  Doing so should not
impact application behavior, as this folder is fully generated by Sencha Cmd and is copied
to the build  output location during the app build process.

## Extracting images for a single theme

Typically, your themes will be compiled and built by the `sencha app build` command, but
it is sometimes helpful to produce images for a single theme at a time. To compile a theme,
use the `compass compile` command in your SASS directory.

    cd /path/to/MyApp/resources/sass/default
    compass compile

This should produce the CSS in `"../../../../.res/default/app.css"` (or from the root of your
application folder, `".res/default/app.css"`).

The next step is to build the image slices needed for IE browsers. This is done with the
following command:

    cd /path/to/MyApp
    sencha theme build -out resources/sliced_images/default

This will place the sliced images in the `"./.res/default/images"` folder alongside the
CSS file generated by SASS. If the '-out' parameter is omitted, then sliced images will be placed
in a 'resources/images/default' directory under the default build output folder for the
application. All image paths are relative to the CSS file location to minimize the size
of the CSS file.

## Anatomy of a Theme

The `theme` folder is split in to two levels. For clarity, lets consider a `theme` folder
with two themes:

    theme/
        custom.js
        manifest.js
        render.js
        shortcuts.js
        default/
            theme.html
        gray/
            theme.html

### theme.html

The `"theme.html"` file is the entry point for the image generation phase of the theme
builder.

You should be able to open this file in Chrome or any other modern browser and see what the
base image will be for your theme. This is an ideal page to test your styling because every
component in every state will be present.

This is an example of what the `"resources/theme/default/theme.html"` file looks like:

    <html>
        <head>
            <title></title>
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

            <link rel="stylesheet" type="text/css" href="../../css/default/theme.css" />
            <link rel="stylesheet" type="text/css" href="../styles.css" />

            <script type="text/javascript" src="../../../sdk/ext-all.js"></script>
            <script type="text/javascript" src="../manifest.js"></script>
            <script type="text/javascript" src="../shortcuts.js"></script>
            <script type="text/javascript" src="../custom.js"></script>
            <script type="text/javascript" src="../render.js"></script>
        </head>
        <body class="ext-generator">
        </body>
    </html>

This file is designed to be edited as needed. This file will not be edited or regenerated
by Sencha Cmd.

**Important.** While this file is freely editable, be sure to keep the relative order of
the `link` and `script` tags. In particular `"custom.js"` must come after `"manifest.js"` and
`"shortcuts.js"` and before `"render.js"`.

The most likely things you might need to edit in this file are the relative paths. All of
the generated files included in the page need to be preserved. You can add `script` tags
or `link` tags as needed, but consider their order in the sequence of tags.

### Private Files

The following files should be considered private and should not be edited:

 -  `manifest.js` - The set of all components to render.
 - `shortcuts.js` - Reusable "templates" used by the manifest.
 - `styles.css` - Styles specific to the theme builder.
 - `render.js` - Renders the components described by the manifest and shortcuts.

### Customization

Add value to the process through the `"custom.js"` file. The primary use of this file is
to add new shortcuts or manifest entries that might be needed by custom components you
have created for your application. This file will not be regenerated by Sencha Cmd.

### Third Party Components

If you have received custom components from a third party, you should ask them to provide
a custom theme definition file so that you can include it in your `theme` folder and as a
`script` tag in your '"theme.html"'. The content of such a file should be the same as
described for a `"custom.js"` file.

You will probably also need SASS files (or at least CSS files) to add to your SASS theme
and/or as `link` tags in `"theme.html"`.

## Managing Themes Manually

Many applications existed before Sencha Cmd provided application management features or
for other reasons do not have the structure assumed by the simple commands described
here. While the commands to handle this case require more switches and understanding, it
is possible to use Sencha Cmd in these more complex situations.

**Important.** The new version of Sencha Cmd takes a different approach to theme building
than did previous versions (which called this mechanism the "slicer"). There is no longer
a `sencha slice` command. This is now handled by the new `sencha theme build` command.

### Creating Your Custom Theme

In order to produce sliced images for your theme, you need the necessary files that define
the theme. The easiest way to get these files is to generate an application in some temporary
folder and copy the `"./resources/theme"` folder to a location of your choosing using the
following:

    sencha generate app /temp/dummyApp

Then copy `"/temp/dummApp/resources/theme"` to your desired location. For example, let's say
that location is `"/path/to/MyApp/stuff/theme"`.

Following the above rules for customization of `"theme.html"` you can flatten the folders in
to a single folder and change the relative paths in `"theme.html"` accordingly. You can also
correct the relative paths to your CSS file(s) and the framework.

## Compiling Your Custom Theme

Once you have moved the theme files to `"/path/to/MyApp/stuff/theme"` and editing all of the
relative paths in `"theme.html"`, you can proceed to generate images. Let's assume you run
the command from the root of your application.

    cd /path/to/MyApp
    sencha theme build -page stuff/theme/theme.html -out images/theme

This will load `"stuff/theme/theme.html"` using an embedded WebKit instance and capture an
image of the content of the rendered page as well as a data object describing all of the
image slicing required. From those two results, the image slicing will proceed to generate
all of the images to the `"images/theme"` folder.

If something is wrong with the generated images, it can be helpful to keep the page image
and the data object for diagnostic purposes. This can be done by specifying their names in
the command:

    cd /path/to/MyApp
    sencha theme build -page stuff/theme/theme.html -out images/theme \
        -image image.png -data data.json

The image is always a PNG file because PNG is both lossless and has a proper alpha channel.
The data object is always in JSON format.