text:
package org.jetbrains.plugins.gradle.frameworkSupport;

import com.intellij.framework.FrameworkTypeEx;
import com.intellij.framework.addSupport.FrameworkSupportInModuleProvider;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.externalSystem.model.project.ProjectId;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.roots.ModifiableModelsProvider;
import com.intellij.openapi.roots.ModifiableRootModel;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;

public class KotlinDslGradleJavaFrameworkSupportProvider extends KotlinDslGradleFrameworkSupportProvider {

  public static final String ID = "java";

  @NotNull
  @Override
  public FrameworkTypeEx getFrameworkType() {
    return new FrameworkTypeEx(ID) {
      @NotNull
      @Override
      public FrameworkSupportInModuleProvider createProvider() {
        return KotlinDslGradleJavaFrameworkSupportProvider.this;
      }

      @NotNull
      @Override
      public String getPresentableName() {
        return "Java";
      }

      @NotNull
      @Override
      public Icon getIcon() {
        return AllIcons.Nodes.Module;
      }
    };
  }

  @Override
  public void addSupport(@NotNull ProjectId projectId,
                         @NotNull Module module,
                         @NotNull ModifiableRootModel rootModel,
                         @NotNull ModifiableModelsProvider modifiableModelsProvider,
                         @NotNull BuildScriptDataBuilder buildScriptData) {
    buildScriptData
      .addPluginDefinitionInPluginsGroup("java")
      .addOther("configure<JavaPluginConvention> {\n    sourceCompatibility = JavaVersion.VERSION_1_8\n}")
      .addRepositoriesDefinition("mavenCentral()")
      .addDependencyNotation("testCompile(\"junit\", \"junit\", \"4.12\")");
  }
}


text:
<?php

namespace SMSManager;

require("Config.php");
require("HTTPRequest.php");

class SMSManagerException extends \Exception
{
	function __construct($code = 0)
	{
		if(intval($code) > 900)
		{
			$code = 900;
		}

		$codes = array
		(
			"101" => "Neexistující data požadavku (chybí XMLDATA parametr u XML API)",
			"102" => "Metoda neexistuje",
			"103" => "Neplatné uživatelské jméno nebo heslo",
			"104" => "Neplatný parametr gateway",
			"105" => "Nedostatek kreditu pro prepaid",
			"201" => "Žádná platná telefonní čísla v požadavku",
			"202" => "Text zprávy neexistuje nebo je příliš dlouhý",
			"203" => "Neplatný parametr sender (odesílatele nejprve nastavte ve webovém rozhraní)",
			"900" => "Systémová chyba (informujte se na support@smsmanager.cz)"
		);

		if(empty($codes[$code]))
		{
			parent::__construct("SMSManager API vrátilo neznámou chybu", $code);
		}
		else
		{
			parent::__construct("SMSManager API vrátilo chybu: ".$codes[$code], $code);
		}

		if(Config::logging)
		{
			error_log((string)$self);
		}
	}
}

class SMSManager
{
	protected $request;
	protected $username;
	protected $password;

	function __construct($username = Config::username, $password = Config::password)
	{
		$this->username = $username;
		$this->password = sha1($password);

		$this->request = new HTTPRequest($this->username, $this->password);
	}

	public function prepareMessage($numbers, $text, $type = Config::gateway_type)
	{
		$message = new \stdClass;

		if(!is_array($numbers))
		{
			$numbers = array($numbers);
		}

		$message->numbers = $numbers;
		$message->text = $text;
		$message->type = $type;

		return $message;
	}

	public function send($messages)
	{
		if(!is_array($messages))
		{
			$messages = array($messages);
		}

		//who the hell uses XML these days... :-(
		$xml = new \DOMDocument("1.0", "utf-8");

		$requestDocument = $xml->appendChild($xml->createElement("RequestDocument"));

		//RequestHeader
		$requestHeader = $requestDocument->appendChild($xml->createElement("RequestHeader"));
		$requestHeader->appendChild($xml->createElement("Username", $this->username));
		$requestHeader->appendChild($xml->createElement("Password", $this->password));

		//RequestList
		$requestList = $xml->createElement("RequestList");

		//for each message create new request
		foreach($messages as $message)
		{
			//request type
			$request = $xml->createElement("Request");
			$request->setAttribute("Type", $message->type);

			//message
			$msg = $xml->createElement("Message", $message->text);
			$msg->setAttribute("Type", "Text");
			$request->appendChild($msg);

			//numbers
			$numbersList = $xml->createElement("NumbersList");

			//for each number in the message
			foreach($message->numbers as $number)
			{
				$num = $xml->createElement("Number", $number);
				$numbersList->appendChild($num);
			}

			$request->appendChild($numbersList);
			$requestList->appendChild($request);
		}

		$requestDocument->appendChild($requestList);

		try
		{
			$responseXML = $this->request->post("Send", $xml->saveXML());
		}
		catch(\Exception $e)
		{
			//just make sure we log this exception
			if(Config::logging)
			{
				error_log((string)$e);
			}

			throw $e;
		}

		$response = simplexml_load_string($responseXML);

		$attr = (array)$response->Response;
		if($attr["@attributes"]["Type"] != "OK")
		{
			throw new SMSManagerException($attr["@attributes"]["ID"]);
		}

		$out = array();

		$responseRequests = $response->ResponseRequestList;
		foreach($responseRequests->ResponseRequest as $responseRequest)
		{
			$o = new \stdClass;

			$o->id = (string)$responseRequest->RequestID;

			$numbers = $responseRequest->ResponseNumbersList;
			foreach($numbers->Number as $number)
			{
				$o->numbers[] = (string)$number;
			}

			$out[] = $o;
		}

		return $out;
	}

	public function requestList()
	{
		$responses = $this->request->get("RequestList");

		$out = array();
		foreach($responses as $response)
		{
			$o = new \stdClass;
			list(
				$o->id,
				$o->gateway,
				$o->sent,
				$o->expires,
				$o->sender,
				$o->remainingRecipients,
				$o->requestState
			) = $response;

			$out[] = $o;
		}

		return $out;
	}

	public function requestStatus($requestId)
	{
		$response = $this->request->get("RequestStatus", array("requestID" => $requestId));

		$o = new \stdClass;
		list(
			$o->number,
			$o->sentState,
			$o->remainingConfirmations,
			$o->receivedState
		) = $response[0];

		return $o;
	}

	public function getUserInfo()
	{
		$response = $this->request->get("GetUserInfo", array("requestID" => $requestId));

		$o = new \stdClass;
		list(
			$o->credit,
			$o->sender,
			$o->gateway
		) = $response[0];

		$o->credit = floatval($o->credit);

		return $o;
	}
}

?>

redpajama_set_name: RedPajamaGithub


text:
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveGeneric #-}

module Main where

import QueryProcessor

import Web.Scotty
import Database.PostgreSQL.Simple
import Data.Text.Lazy
import System.IO
import Network.Wai.Middleware.Static
import Control.Monad.IO.Class

import Data.String

apiServer :: Connection -> ScottyM()
apiServer connection = do
    get "/api/getCommonCompetitions" $ do
        name1 <- param "name1"
        name2 <- param "name2"
        rows <- liftIO $ getCommonCompetitionsRows connection name1 name2
        json rows
    get "/api/getAthleteList" $ do
        list <- liftIO $ getAthleteList connection
        json list
    get "/api/getAllRaces" $ do
        list <- liftIO $ getAllRaces connection
        json list
    get "/api/completeAthleteName" $ do
        name <- param "name"
        list <- liftIO $ completeAthleteName connection name
        json list

main :: IO ()
main = do
    -- connect to the database
    password <- getLine
    dbConnection <- connectPostgreSQL $ fromString ("host='pellefant.db.elephantsql.com' user='qfjtuala' dbname='qfjtuala' password='" ++ password ++ "'")
    {-dbConnection <- connectPostgreSQL $ fromString ("host='192.168.124.244' user='postgres' dbname='another' password='password'")-}
    scotty 1234 $ do
        middleware $ staticPolicy (noDots >-> addBase "src/front") -- get static files (index.html, *.js, etc)
        apiServer dbConnection
    return ()


text:
project_path: /web/_project.yaml
book_path: /web/fundamentals/_book.yaml
description: Antes de o navegador renderizar conteúdo para a tela, ele precisa criar as árvores DOM e CSSOM. Para isso, precisamos garantir que o HTML e o CSS sejam entregues ao navegador o mais rápido possível.

{# wf_updated_on: 2014-09-11 #}
{# wf_published_on: 2014-03-31 #}

# Criação do modelo de objeto {: .page-title }

{% include "web/_shared/contributors/ilyagrigorik.html" %}

Antes de o navegador renderizar a página, ele precisa criar as árvores DOM e CSSOM. Para isso, precisamos garantir que o HTML e o CSS sejam entregues ao navegador o mais rápido possível.

### TL;DR {: .hide-from-toc }
- Bytes → caracteres → tokens → nós → modelo de objeto.
- A marcação HTML é transformada em um modelo de objeto de documento (DOM, na sigla em inglês), a marcação CSS é transformada em um modelo de objeto de CSS (CSSOM, na sigla em inglês).
- DOM e CSSOM são estruturas de dados independentes.
- O Chrome DevTools Timeline possibilita capturar e inspecionar os custos de criação e processamento de DOM e CSSOM.

## Document Object Model (DOM)

{% includecode content_path="web/fundamentals/performance/critical-rendering-path/_code/basic_dom.html" region_tag="full" adjust_indentation="auto" %}

Comecemos com o caso mais simples possível: uma página HTML sem formatação com texto e uma única imagem. O que o navegador precisa fazer para processar esta simples página?

1. **Conversão:** o navegador lê os bytes brutos do HTML do disco ou da rede e os traduz em caracteres individuais baseados na codificação determinada do arquivo (por exemplo, UTF-8).
2. **Criação de tokens:** o navegador converte as strings de caracteres em tokens distintos especificados pelo [padrão W3C HTML5](http://www.w3.org/TR/html5/){: .external }, por exemplo, `<html>`, `<body>` e outras strings nos `colchetes angulares`. Cada token tem um significado e conjunto de regras especiais.
3. **Lexicalização:** os tokens emitidos são convertidos em `objetos` que definem suas propriedades e regras.
4. **Criação do DOM:** por último, como a marcação de HTML define as relações entre diferentes tags (algumas tags estão contidas em outras tags), os objetos criados são vinculados em uma estrutura de dados em forma de árvore que também captura as relações pai-filho definidas na marcação original: o objeto _HTML_ é pai do objeto _body_, _body_ é pai do objeto _paragraph_ e assim por diante.

**O resultado final deste processo é o Document Object Model, ou o `DOM` de nossa página simples, que o navegador usa para todo o processamento restante da página.**

Sempre que o navegador tem de processar a marcação HTML, ele precisa concluir as etapas acima: converter bytes em caracteres, identificar tokens, converter tokens em nós e criar a árvore de DOM. O processo completo pode levar algum tempo, especialmente se for necessário processar uma grande quantidade de HTML.

Note: Suporemos que você sabe um pouco de Chrome DevTools, ou seja, que sabe como capturar uma cascata de rede ou gravar uma linha do tempo. Se você precisa de um atualizador rápido, confira a documentação do Chrome DevTools, ou se você é novo no DevTools, recomendamos fazer o curso Explore e domine Chrome DevTools, da Codeschool.

Se você abrir o Chrome DevTools e gravar uma linha do tempo enquanto a página é carregada, poderá ver o tempo real necessário para que essa etapa seja realizada. No exemplo acima, levamos aproximadamente 5 ms para converter um bloco de bytes de HTML em uma árvore de DOM. Logicamente, se a página fosse maior, como a maioria das páginas costuma ser, esse processo poderia levar muito mais tempo. Você verá em nossas sessões futuras sobre a criação de animações suaves que isso pode se tornar um recurso de afunilamento se o navegador tiver de processar grandes quantidades de HTML.

Com a árvore de DOM criada, será que temos informações o suficiente para renderizar a página para a tela? Ainda não. A árvore de DOM captura as propriedades e as relações da marcação do documento, mas não diz nada sobre a aparência que o elemento deve ter quando for renderizado. Isso é de responsabilidade do CSSOM, que nós conheceremos a seguir.

## CSS Object Model (CSSOM)

Enquanto o navegador criava o DOM de nossa página simples, ele encontrou uma tag de link na seção de cabeçalho do documento fazendo referência a uma folha de estilos CSS externa: style.css. Ao perceber que precisaria desse recurso para renderizar a página, o navegador imediatamente envia uma solicitação para esse recurso, que volta com o seguinte conteúdo:

{% includecode content_path="web/fundamentals/performance/critical-rendering-path/_code/style.css" region_tag="full"   adjust_indentation="auto" %}

Poderíamos ter declarado nossos estilos diretamente na marcação de HTML (in-line), mas manter a CSS independente do HTML nos possibilita abordar conteúdo e design como preocupações distintas: os designers podem trabalhar em CSS enquanto os desenvolvedores podem focar-se em HTML e assim por diante.

Assim como ocorre com HTML, precisamos converter as regras de CSS recebidas em algo que o navegador possa entender e com o qual consiga trabalhar. Portanto, novamente, repetimos um processo muito semelhante ao usado com HTML:

Os bytes de CSS são convertidos em caracteres, depois em tokens e nós e, por último, são vinculados em uma estrutura de árvore conhecida como `objeto de modelo de CSS` ou CSSOM:

Por que o CSSOM tem uma estrutura de árvore? Ao computar o conjunto final de estilos para qualquer objeto na página, o navegador começa pela regra mais geral que pode ser aplicada àquele nó (por exemplo, caso seja o filho de um elemento de corpo, então todos os estilos de corpo podem ser aplicados) e repetidamente refina os estilos computados aplicando regras mais específicas, ou seja, as regras se aplicam em uma cascata para baixo.

Para tornar isso mais palpável, considere a árvore CSSOM acima. Qualquer texto contido na tag _span_ que esteja posicionado no elemento de corpo terá um tamanho de fonte de 16 pixels e será vermelho. A diretiva font-size adota a forma de cascata para baixo do corpo para a dimensão. No entanto, se uma tag de dimensão for filha de uma tag de parágrafo (p), seus conteúdos não serão exibidos.

Além disso, a árvore acima não é a árvore CSSOM completa e só mostra os estilos que decidimos substituir em nossa folha de estilos. Cada navegador fornece um conjunto padrão de estilos, também conhecidos como `estilos de user-agent`. Isso é o que vemos ao deixar de fornecer um conjunto próprio, e nossos estilos simplesmente substituem esses padrões (por exemplo, [estilos IE padrão](http://www.iecss.com/){: .external }). Se você já inspecionou seus `estilos computados` no Chrome DevTools e se perguntou de onde surgiram todos esses estilos, aí está a sua resposta.

Curioso para saber quanto tempo levou o processamento de CSS? Grave uma linha do tempo no DevTools e procure o evento `Recalculate Style` (Recalcular estilo): diferentemente da análise de DOM, a linha do tempo não exibe uma entrada `Parse CSS` (Analisar CSS) separada. Em vez disso, ela captura a análise e a criação da árvore CSSOM mais o cálculo repetido dos estilos computados nesse evento único.

Nossa folha de estilos trivial leva aproximadamente 0,6 ms para ser processada e afeta oito elementos na página. Não é muito, mas não está livre. Entretanto, de onde vieram os oito elementos? CSSOM e DOM são estruturas de dados independentes. Acontece que o navegador oculta uma etapa muito importante. A seguir, falaremos sobre a árvore de renderização que vincula o DOM e o CSSOM um ao outro.


text:
/**
 * Created by Loki.Luo on 2017/3/8.
 */
var gulp = require('gulp'),
    concatCss = require('gulp-concat-css'),
    cssmin = require('gulp-cssmin'),
    sass = require('gulp-sass'),
    sourcemaps = require('gulp-sourcemaps'),
    rename = require('gulp-rename'),

    config = require('../config');// gulp公共配置

exports.task = function () {
    return gulp.src(config.paths.css)
        .pipe(sass().on('error', sass.logError))
        .pipe(sourcemaps.init({loadMaps: true}))
        .pipe(concatCss("main.css"))
        .pipe(gulp.dest(config.output))
        .pipe(cssmin())
        .pipe(rename({suffix:'.min'}))
        .pipe(sourcemaps.write('./'))
        .pipe(gulp.dest(config.output+'/main'))
};


text:
orchidParentSuggestions = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    remote: {url: window.relative_url_root + '/orchids/parent_suggestions?term=%QUERY',
        replace: function(url,query) {
            return window.relative_url_root + '/orchids/parent_suggestions?' +
                'orchid_id=' + $('#orchid-parent-typeahead').attr('data-orchid-id') + '&' +
                'term=' + encodeURIComponent(query.replace(/\|.*/,''))
        }
    },
    limit: 100
});

orchidParentSuggestions.initialize();


text:
using Newtonsoft.Json;
using System.Net;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http;
using Thinktecture.IdentityServer.Core.Logging;
using Thinktecture.IdentityServer.Core.Models;

namespace Thinktecture.IdentityServer.Core.Results
{
    internal class TokenResult : IHttpActionResult
    {
        private readonly static ILog Logger = LogProvider.GetCurrentClassLogger();
        private readonly static JsonMediaTypeFormatter Formatter = new JsonMediaTypeFormatter
        {
            SerializerSettings = { DefaultValueHandling = DefaultValueHandling.Ignore }
        };

        private readonly TokenResponse _response;

        public TokenResult(TokenResponse response)
        {
            _response = response;
        }

        public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
        {
            return Task.FromResult(Execute());
        }

        private HttpResponseMessage Execute()
        {
            var dto = new TokenResponseDto
            {
                id_token = _response.IdentityToken,
                access_token = _response.AccessToken,
                refresh_token = _response.RefreshToken,
                expires_in = _response.AccessTokenLifetime,
                token_type = Constants.TokenTypes.Bearer
            };

            var response = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new ObjectContent<TokenResponseDto>(dto, Formatter)
            };

            Logger.Info("Returning token response.");
            return response;
        }

        internal class TokenResponseDto
        {
            public string id_token { get; set; }
            public string access_token { get; set; }
            public int expires_in { get; set; }
            public string token_type { get; set; }
            public string refresh_token { get; set; }
        }
    }
}


text:
#ifndef INCLUDE_STB_WINGRAPH_H
#define INCLUDE_STB_WINGRAPH_H

#ifdef STB_WINMAIN
   #ifndef STB_DEFINE
      #define STB_DEFINE
      #define STB_WINGRAPH_DISABLE_DEFINE_AT_END
   #endif
#endif

#ifdef STB_DEFINE
   #pragma comment(lib, "opengl32.lib")
   #pragma comment(lib, "glu32.lib")
   #pragma comment(lib, "winmm.lib")
   #pragma comment(lib, "gdi32.lib")
   #pragma comment(lib, "user32.lib")
#endif

#ifdef __cplusplus
#define STB_EXTERN extern "C"
#else
#define STB_EXTERN
#endif

#ifdef STB_DEFINE
#ifndef _WINDOWS_
   #ifdef APIENTRY
   #undef APIENTRY
   #endif
   #ifdef WINGDIAPI
   #undef WINGDIAPI
   #endif
   #define _WIN32_WINNT 0x0400  // WM_MOUSEWHEEL
   #include <windows.h>
#endif
#include <stdio.h>
#include <math.h>
#include <time.h>
#include <string.h>
#include <assert.h>
#endif

typedef void * stbwingraph_hwnd;
typedef void * stbwingraph_hinstance;

enum
{
   STBWINGRAPH_unprocessed = -(1 << 24),
   STBWINGRAPH_do_not_show,
   STBWINGRAPH_winproc_exit,
   STBWINGRAPH_winproc_update,
   STBWINGRAPH_update_exit,
   STBWINGRAPH_update_pause,
};

typedef enum
{
   STBWGE__none=0,

   STBWGE_create,
   STBWGE_create_postshow,
   STBWGE_draw,
   STBWGE_destroy,
   STBWGE_char,
   STBWGE_keydown,
   STBWGE_syskeydown,
   STBWGE_keyup,
   STBWGE_syskeyup,
   STBWGE_deactivate,
   STBWGE_activate,
   STBWGE_size,

   STBWGE_mousemove ,
   STBWGE_leftdown  , STBWGE_leftup  ,
   STBWGE_middledown, STBWGE_middleup,
   STBWGE_rightdown , STBWGE_rightup ,
   STBWGE_mousewheel,
} stbwingraph_event_type;

typedef struct
{
   stbwingraph_event_type type;

   // for input events (mouse, keyboard)
   int mx,my; // mouse x & y
   int dx,dy;
   int shift, ctrl, alt;

   // for keyboard events
   int key;

   // for STBWGE_size:
   int width, height;

   // for STBWGE_crate
   int did_share_lists;  // if true, wglShareLists succeeded

   void *handle;

} stbwingraph_event;

typedef int (*stbwingraph_window_proc)(void *data, stbwingraph_event *event);

extern stbwingraph_hinstance   stbwingraph_app;
extern stbwingraph_hwnd        stbwingraph_primary_window;
extern int                     stbwingraph_request_fullscreen;
extern int                     stbwingraph_request_windowed;

STB_EXTERN void stbwingraph_ods(char *str, ...);
STB_EXTERN int stbwingraph_MessageBox(stbwingraph_hwnd win, unsigned int type,
                                              char *caption, char *text, ...);
STB_EXTERN int stbwingraph_ChangeResolution(unsigned int w, unsigned int h,
                                      unsigned int bits, int use_message_box);
STB_EXTERN int stbwingraph_SetPixelFormat(stbwingraph_hwnd win, int color_bits,
            int alpha_bits, int depth_bits, int stencil_bits, int accum_bits);
STB_EXTERN int stbwingraph_DefineClass(void *hinstance, char *iconname);
STB_EXTERN void stbwingraph_SwapBuffers(void *win);
STB_EXTERN void stbwingraph_Priority(int n);

STB_EXTERN void stbwingraph_MakeFonts(void *window, int font_base);
STB_EXTERN void stbwingraph_ShowWindow(void *window);
STB_EXTERN void *stbwingraph_CreateWindow(int primary, stbwingraph_window_proc func, void *data, char *text, int width, int height, int fullscreen, int resizeable, int dest_alpha, int stencil);
STB_EXTERN void *stbwingraph_CreateWindowSimple(stbwingraph_window_proc func, int width, int height);
STB_EXTERN void *stbwingraph_CreateWindowSimpleFull(stbwingraph_window_proc func, int fullscreen, int ww, int wh, int fw, int fh);
STB_EXTERN void stbwingraph_DestroyWindow(void *window);
STB_EXTERN void stbwingraph_ShowCursor(void *window, int visible);
STB_EXTERN float stbwingraph_GetTimestep(float minimum_time);
STB_EXTERN void stbwingraph_SetGLWindow(void *win);
typedef int (*stbwingraph_update)(float timestep, int real, int in_client);
STB_EXTERN int stbwingraph_MainLoop(stbwingraph_update func, float mintime);

#ifdef STB_DEFINE
stbwingraph_hinstance   stbwingraph_app;
stbwingraph_hwnd        stbwingraph_primary_window;
int stbwingraph_request_fullscreen;
int stbwingraph_request_windowed;

void stbwingraph_ods(char *str, ...)
{
   char buffer[1024];
   va_list v;
   va_start(v,str);
   vsprintf(buffer, str, v);
   va_end(v);
   OutputDebugString(buffer);
}

int stbwingraph_MessageBox(stbwingraph_hwnd win, unsigned int type, char *caption, char *text, ...)
{
   va_list v;
   char buffer[1024];
   va_start(v, text);
   vsprintf(buffer, text, v);
   va_end(v);
   return MessageBox(win, buffer, caption, type);
}

void stbwingraph_Priority(int n)
{
   int p;
   switch (n) {
      case -1: p = THREAD_PRIORITY_BELOW_NORMAL; break;
      case 0: p = THREAD_PRIORITY_NORMAL; break;
      case 1: p = THREAD_PRIORITY_ABOVE_NORMAL; break;
      default:
         if (n < 0) p = THREAD_PRIORITY_LOWEST;
         else p = THREAD_PRIORITY_HIGHEST;
   }
   SetThreadPriority(GetCurrentThread(), p);
}

static void stbwingraph_ResetResolution(void)
{
   ChangeDisplaySettings(NULL, 0);
}

static void stbwingraph_RegisterResetResolution(void)
{
   static int done=0;
   if (!done) {
      done = 1;
      atexit(stbwingraph_ResetResolution);
   }
}

int stbwingraph_ChangeResolution(unsigned int w, unsigned int h, unsigned int bits, int use_message_box)
{
   DEVMODE mode;
   int res;

   int i, tries=0;
   for (i=0; ; ++i) {
      int success = EnumDisplaySettings(NULL, i, &mode);
      if (!success) break;
      if (mode.dmBitsPerPel == bits && mode.dmPelsWidth == w && mode.dmPelsHeight == h) {
         ++tries;
         success = ChangeDisplaySettings(&mode, CDS_FULLSCREEN);
         if (success == DISP_CHANGE_SUCCESSFUL) {
            stbwingraph_RegisterResetResolution();
            return TRUE;
         }
         break;
      }
   }

   if (!tries) {
      if (use_message_box)
         stbwingraph_MessageBox(stbwingraph_primary_window, MB_ICONERROR, NULL, "The resolution %d x %d x %d-bits is not supported.", w, h, bits);
      return FALSE;
   }

   // we tried but failed, so try explicitly doing it without specifying refresh rate

   // Win95 support logic
   mode.dmBitsPerPel = bits;
   mode.dmPelsWidth = w;
   mode.dmPelsHeight = h;
   mode.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;

   res = ChangeDisplaySettings(&mode, CDS_FULLSCREEN);

   switch (res) {
      case DISP_CHANGE_SUCCESSFUL:
         stbwingraph_RegisterResetResolution();
         return TRUE;

      case DISP_CHANGE_RESTART:
         if (use_message_box)
            stbwingraph_MessageBox(stbwingraph_primary_window, MB_ICONERROR, NULL, "Please set your desktop to %d-bit color and then try again.");
         return FALSE;

      case DISP_CHANGE_FAILED:
         if (use_message_box)
            stbwingraph_MessageBox(stbwingraph_primary_window, MB_ICONERROR, NULL, "The hardware failed to change modes.");
         return FALSE;

      case DISP_CHANGE_BADMODE:
         if (use_message_box)
            stbwingraph_MessageBox(stbwingraph_primary_window, MB_ICONERROR, NULL, "The resolution %d x %d x %d-bits is not supported.", w, h, bits);
         return FALSE;

      default:
         if (use_message_box)
            stbwingraph_MessageBox(stbwingraph_primary_window, MB_ICONERROR, NULL, "An unknown error prevented a change to a %d x %d x %d-bit display.", w, h, bits);
         return FALSE;
   }
}

int stbwingraph_SetPixelFormat(stbwingraph_hwnd win, int color_bits, int alpha_bits, int depth_bits, int stencil_bits, int accum_bits)
{
   HDC dc = GetDC(win);
   PIXELFORMATDESCRIPTOR pfd = { sizeof(pfd) };
   int                   pixel_format;

   pfd.nVersion = 1;
   pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER;
   pfd.dwLayerMask = PFD_MAIN_PLANE;
   pfd.iPixelType = PFD_TYPE_RGBA;
   pfd.cColorBits = color_bits;
   pfd.cAlphaBits = alpha_bits;
   pfd.cDepthBits = depth_bits;
   pfd.cStencilBits = stencil_bits;
   pfd.cAccumBits = accum_bits;

   pixel_format = ChoosePixelFormat(dc, &pfd);
   if (!pixel_format) return FALSE;

   if (!DescribePixelFormat(dc, pixel_format, sizeof(PIXELFORMATDESCRIPTOR), &pfd))
      return FALSE;
   SetPixelFormat(dc, pixel_format, &pfd);

   return TRUE;
}

typedef struct
{
   // app data
   stbwingraph_window_proc func;
   void *data;
   // creation parameters
   int   color, alpha, depth, stencil, accum;
   HWND  share_window;
   HWND  window;
   // internal data
   HGLRC rc;
   HDC   dc;
   int   hide_mouse;
   int   in_client;
   int   active;
   int   did_share_lists;
   int   mx,my; // last mouse positions
} stbwingraph__window;

static void stbwingraph__inclient(stbwingraph__window *win, int state)
{
   if (state != win->in_client) {
      win->in_client = state;
      if (win->hide_mouse)
         ShowCursor(!state);
   }
}

static void stbwingraph__key(stbwingraph_event *e, int type, int key, stbwingraph__window *z)
{
   e->type  = type;
   e->key   = key;
   e->shift = (GetKeyState(VK_SHIFT)   < 0);
   e->ctrl  = (GetKeyState(VK_CONTROL) < 0);
   e->alt   = (GetKeyState(VK_MENU)    < 0);
   if  (z) {
      e->mx    = z->mx;
      e->my    = z->my;
   } else {
      e->mx = e->my = 0;
   }
   e->dx = e->dy = 0;
}

static void stbwingraph__mouse(stbwingraph_event *e, int type, WPARAM wparam, LPARAM lparam, int capture, void *wnd, stbwingraph__window *z)
{
   static int captured = 0;
   e->type = type;
   e->mx = (short) LOWORD(lparam);
   e->my = (short) HIWORD(lparam);
   if (!z || z->mx == -(1 << 30)) {
      e->dx = e->dy = 0;
   } else {
      e->dx = e->mx - z->mx;
      e->dy = e->my - z->my;
   }
   e->shift = (wparam & MK_SHIFT) != 0;
   e->ctrl  = (wparam & MK_CONTROL) != 0;
   e->alt   = (wparam & MK_ALT) != 0;
   if (z) {
      z->mx = e->mx;
      z->my = e->my;
   }
   if (capture) {
      if (!captured && capture == 1)
         SetCapture(wnd);
      captured += capture;
      if (!captured && capture == -1)
         ReleaseCapture();
      if (captured < 0) captured = 0;
   }
}

static void stbwingraph__mousewheel(stbwingraph_event *e, int type, WPARAM wparam, LPARAM lparam, int capture, void *wnd, stbwingraph__window *z)
{
   // lparam seems bogus!
   static int captured = 0;
   e->type = type;
   if (z) {
      e->mx = z->mx;
      e->my = z->my;
   }
   e->dx = e->dy = 0;
   e->shift = (wparam & MK_SHIFT) != 0;
   e->ctrl  = (wparam & MK_CONTROL) != 0;
   e->alt   = (GetKeyState(VK_MENU)    < 0);
   e->key = ((int) wparam >> 16);
}

int stbwingraph_force_update;
static int WINAPI stbwingraph_WinProc(HWND wnd, UINT msg, WPARAM wparam, LPARAM lparam)
{
   int allow_default = TRUE;
   stbwingraph_event e = { STBWGE__none };
   // the following line is wrong for 64-bit windows, but VC6 doesn't have GetWindowLongPtr
   stbwingraph__window *z = (stbwingraph__window *) GetWindowLong(wnd, GWL_USERDATA);

   switch (msg) {

      case WM_CREATE:
      {
         LPCREATESTRUCT lpcs = (LPCREATESTRUCT) lparam;
         assert(z == NULL);
         z = (stbwingraph__window *) lpcs->lpCreateParams;
         SetWindowLong(wnd, GWL_USERDATA, (LONG) z);
         z->dc = GetDC(wnd);
         if (stbwingraph_SetPixelFormat(wnd, z->color, z->alpha, z->depth, z->stencil, z->accum)) {
            z->rc = wglCreateContext(z->dc);
            if (z->rc) {
               e.type = STBWGE_create;
               z->did_share_lists = FALSE;
               if (z->share_window) {
                  stbwingraph__window *y = (stbwingraph__window *) GetWindowLong(z->share_window, GWL_USERDATA);
                  if (wglShareLists(z->rc, y->rc))
                     z->did_share_lists = TRUE;
               }
               wglMakeCurrent(z->dc, z->rc);
               return 0;
            }
         }
         return -1;
      }

      case WM_PAINT: {
         PAINTSTRUCT ps;
         HDC hdc = BeginPaint(wnd, &ps);
         SelectObject(hdc, GetStockObject(NULL_BRUSH));
         e.type = STBWGE_draw;
         e.handle = wnd;
         z->func(z->data, &e);
         EndPaint(wnd, &ps);
         return 0;
      }

      case WM_DESTROY:
         e.type = STBWGE_destroy;
         e.handle = wnd;
         if (z && z->func)
            z->func(z->data, &e);
         wglMakeCurrent(NULL, NULL) ;
         if (z) {
            if (z->rc) wglDeleteContext(z->rc);
            z->dc = 0;
            z->rc = 0;
         }
         if (wnd == stbwingraph_primary_window)
            PostQuitMessage (0);
         return 0;

      case WM_CHAR:         stbwingraph__key(&e, STBWGE_char   , wparam, z); break;
      case WM_KEYDOWN:      stbwingraph__key(&e, STBWGE_keydown, wparam, z); break;
      case WM_KEYUP:        stbwingraph__key(&e, STBWGE_keyup  , wparam, z); break;

      case WM_NCMOUSEMOVE:  stbwingraph__inclient(z,0); break;
      case WM_MOUSEMOVE:    stbwingraph__inclient(z,1); stbwingraph__mouse(&e, STBWGE_mousemove,  wparam, lparam,0,wnd, z); break;
      case WM_LBUTTONDOWN:  stbwingraph__mouse(&e, STBWGE_leftdown,   wparam, lparam,1,wnd, z); break;
      case WM_MBUTTONDOWN:  stbwingraph__mouse(&e, STBWGE_middledown, wparam, lparam,1,wnd, z); break;
      case WM_RBUTTONDOWN:  stbwingraph__mouse(&e, STBWGE_rightdown,  wparam, lparam,1,wnd, z); break;
      case WM_LBUTTONUP:    stbwingraph__mouse(&e, STBWGE_leftup,     wparam, lparam,-1,wnd, z); break;
      case WM_MBUTTONUP:    stbwingraph__mouse(&e, STBWGE_middleup,   wparam, lparam,-1,wnd, z); break;
      case WM_RBUTTONUP:    stbwingraph__mouse(&e, STBWGE_rightup,    wparam, lparam,-1,wnd, z); break;
      case WM_MOUSEWHEEL:   stbwingraph__mousewheel(&e, STBWGE_mousewheel, wparam, lparam,0,wnd, z); break;

      case WM_ACTIVATE:
         allow_default = FALSE;
         if (LOWORD(wparam)==WA_INACTIVE ) {
            wglMakeCurrent(z->dc, NULL);
            e.type = STBWGE_deactivate;
            z->active = FALSE;
         } else {
            wglMakeCurrent(z->dc, z->rc);
            e.type = STBWGE_activate;
            z->active = TRUE;
         }
         e.handle = wnd;
         z->func(z->data, &e);
         return 0;

      case WM_SIZE: {
         RECT rect;
         allow_default = FALSE;
         GetClientRect(wnd, &rect);
         e.type = STBWGE_size;
         e.width = rect.right;
         e.height = rect.bottom;
         e.handle = wnd;
         z->func(z->data, &e);
         return 0;
      }

      default:
         return DefWindowProc (wnd, msg, wparam, lparam);
   }

   if (e.type != STBWGE__none) {
      int n;
      e.handle = wnd;
      n = z->func(z->data, &e);
      if (n == STBWINGRAPH_winproc_exit) {
         PostQuitMessage(0);
         n = 0;
      }
      if (n == STBWINGRAPH_winproc_update) {
         stbwingraph_force_update = TRUE;
         return 1;
      }
      if (n != STBWINGRAPH_unprocessed)
         return n;
   }
   return DefWindowProc (wnd, msg, wparam, lparam);
}

int stbwingraph_DefineClass(HINSTANCE hInstance, char *iconname)
{
   WNDCLASSEX  wndclass;

   stbwingraph_app = hInstance;

   wndclass.cbSize        = sizeof(wndclass);
   wndclass.style         = CS_OWNDC;
   wndclass.lpfnWndProc   = (WNDPROC) stbwingraph_WinProc;
   wndclass.cbClsExtra    = 0;
   wndclass.cbWndExtra    = 0;
   wndclass.hInstance     = hInstance;
   wndclass.hIcon         = LoadIcon(hInstance, iconname);
   wndclass.hCursor       = LoadCursor(NULL,IDC_ARROW);
   wndclass.hbrBackground = GetStockObject(NULL_BRUSH);
   wndclass.lpszMenuName  = "zwingraph";
   wndclass.lpszClassName = "zwingraph";
   wndclass.hIconSm       = NULL;

   if (!RegisterClassEx(&wndclass))
      return FALSE;
   return TRUE;
}

void stbwingraph_ShowWindow(void *window)
{
   stbwingraph_event e = { STBWGE_create_postshow };
   stbwingraph__window *z = (stbwingraph__window *) GetWindowLong(window, GWL_USERDATA);
   ShowWindow(window, SW_SHOWNORMAL);
   InvalidateRect(window, NULL, TRUE);
   UpdateWindow(window);
   e.handle = window;
   z->func(z->data, &e);
}

void *stbwingraph_CreateWindow(int primary, stbwingraph_window_proc func, void *data, char *text,
           int width, int height, int fullscreen, int resizeable, int dest_alpha, int stencil)
{
   HWND win;
   DWORD dwstyle;
   stbwingraph__window *z = (stbwingraph__window *) malloc(sizeof(*z));

   if (z == NULL) return NULL;
   memset(z, 0, sizeof(*z));
   z->color = 24;
   z->depth = 24;
   z->alpha = dest_alpha;
   z->stencil = stencil;
   z->func = func;
   z->data = data;
   z->mx = -(1 << 30);
   z->my = 0;

   if (primary) {
      if (stbwingraph_request_windowed)
         fullscreen = FALSE;
      else if (stbwingraph_request_fullscreen)
         fullscreen = TRUE;
   }

   if (fullscreen) {
      #ifdef STB_SIMPLE
      stbwingraph_ChangeResolution(width, height, 32, 1);
      #else
      if (!stbwingraph_ChangeResolution(width, height, 32, 0))
         return NULL;
      #endif
      dwstyle = WS_POPUP | WS_CLIPSIBLINGS;
   } else {
      RECT rect;
      dwstyle = WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX;
      if (resizeable)
         dwstyle |= WS_SIZEBOX | WS_MAXIMIZEBOX;
      rect.top = 0;
      rect.left = 0;
      rect.right = width;
      rect.bottom = height;
      AdjustWindowRect(&rect, dwstyle, FALSE);
      width = rect.right - rect.left;
      height = rect.bottom - rect.top;
   }

   win = CreateWindow("zwingraph", text ? text : "sample", dwstyle,
                      CW_USEDEFAULT,0, width, height,
                      NULL, NULL, stbwingraph_app, z);

   if (win == NULL) return win;

   if (primary) {
      if (stbwingraph_primary_window)
         stbwingraph_DestroyWindow(stbwingraph_primary_window);
      stbwingraph_primary_window = win;
   }

   {
      stbwingraph_event e = { STBWGE_create };
      stbwingraph__window *z = (stbwingraph__window *) GetWindowLong(win, GWL_USERDATA);
      z->window = win;
      e.did_share_lists = z->did_share_lists;
      e.handle = win;
      if (z->func(z->data, &e) != STBWINGRAPH_do_not_show)
         stbwingraph_ShowWindow(win);
   }

   return win;
}

void *stbwingraph_CreateWindowSimple(stbwingraph_window_proc func, int width, int height)
{
   int fullscreen = 0;
   #ifndef _DEBUG
   if (width ==  640 && height ==  480) fullscreen = 1;
   if (width ==  800 && height ==  600) fullscreen = 1;
   if (width == 1024 && height ==  768) fullscreen = 1;
   if (width == 1280 && height == 1024) fullscreen = 1;
   if (width == 1600 && height == 1200) fullscreen = 1;
   //@TODO: widescreen widths
   #endif
   return stbwingraph_CreateWindow(1, func, NULL, NULL, width, height, fullscreen, 1, 0, 0);
}

void *stbwingraph_CreateWindowSimpleFull(stbwingraph_window_proc func, int fullscreen, int ww, int wh, int fw, int fh)
{
   if (fullscreen == -1) {
   #ifdef _DEBUG
      fullscreen = 0;
   #else
      fullscreen = 1;
   #endif
   }

   if (fullscreen) {
      if (fw) ww = fw;
      if (fh) wh = fh;
   }
   return stbwingraph_CreateWindow(1, func, NULL, NULL, ww, wh, fullscreen, 1, 0, 0);
}

void stbwingraph_DestroyWindow(void *window)
{
   stbwingraph__window *z = (stbwingraph__window *) GetWindowLong(window, GWL_USERDATA);
   DestroyWindow(window);
   free(z);
   if (stbwingraph_primary_window == window)
      stbwingraph_primary_window = NULL;
}

void stbwingraph_ShowCursor(void *window, int visible)
{
   int hide;
   stbwingraph__window *win;
   if (!window)
      window = stbwingraph_primary_window;
   win = (stbwingraph__window *) GetWindowLong((HWND) window, GWL_USERDATA);
   hide = !visible;
   if (hide != win->hide_mouse) {
      win->hide_mouse = hide;
      if (!hide)
         ShowCursor(TRUE);
      else if (win->in_client)
         ShowCursor(FALSE);
   }
}

float stbwingraph_GetTimestep(float minimum_time)
{
   float elapsedTime;
   double thisTime;
   static double lastTime = -1;

   if (lastTime == -1)
      lastTime = timeGetTime() / 1000.0 - minimum_time;

   for(;;) {
      thisTime = timeGetTime() / 1000.0;
      elapsedTime = (float) (thisTime - lastTime);
      if (elapsedTime >= minimum_time) {
         lastTime = thisTime;
         return elapsedTime;
      }
      #if 1
      Sleep(2);
      #endif
   }
}

void stbwingraph_SetGLWindow(void *win)
{
   stbwingraph__window *z = (stbwingraph__window *) GetWindowLong(win, GWL_USERDATA);
   if (z)
      wglMakeCurrent(z->dc, z->rc);
}

void stbwingraph_MakeFonts(void *window, int font_base)
{
   wglUseFontBitmaps(GetDC(window ? window : stbwingraph_primary_window), 0, 256, font_base);
}

// returns 1 if WM_QUIT, 0 if 'func' returned 0
int stbwingraph_MainLoop(stbwingraph_update func, float mintime)
{
   int needs_drawing = FALSE;
   MSG msg;

   int is_animating = TRUE;
   if (mintime <= 0) mintime = 0.01f;

   for(;;) {
      int n;

      is_animating = TRUE;
      // wait for a message if: (a) we're animating and there's already a message
      // or (b) we're not animating
      if (!is_animating || PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE)) {
         stbwingraph_force_update = FALSE;
         if (GetMessage(&msg, NULL, 0, 0)) {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
         } else {
            return 1;   // WM_QUIT
         }

         // only force a draw for certain messages...
         // if I don't do this, we peg at 50% for some reason... must
         // be a bug somewhere, because we peg at 100% when rendering...
         // very weird... looks like NVIDIA is pumping some messages
         // through our pipeline? well, ok, I guess if we can get
         // non-user-generated messages we have to do this
         if (!stbwingraph_force_update) {
            switch (msg.message) {
               case WM_MOUSEMOVE:
               case WM_NCMOUSEMOVE:
                  break;
               case WM_CHAR:
               case WM_KEYDOWN:
               case WM_KEYUP:
               case WM_LBUTTONDOWN:
               case WM_MBUTTONDOWN:
               case WM_RBUTTONDOWN:
               case WM_LBUTTONUP:
               case WM_MBUTTONUP:
               case WM_RBUTTONUP:
               case WM_TIMER:
               case WM_SIZE:
               case WM_ACTIVATE:
                  needs_drawing = TRUE;
                  break;
            }
         } else
            needs_drawing = TRUE;
      }

      // if another message, process that first
      // @TODO: i don't think this is working, because I can't key ahead
      // in the SVT demo app
      if (PeekMessage(&msg, NULL, 0,0, PM_NOREMOVE))
         continue;

      // and now call update
      if (needs_drawing || is_animating) {
         int real=1, in_client=1;
         if (stbwingraph_primary_window) {
            stbwingraph__window *z = (stbwingraph__window *) GetWindowLong(stbwingraph_primary_window, GWL_USERDATA);
            if (z && !z->active) {
               real = 0;
            }
            if (z)
               in_client = z->in_client;
         }

         if (stbwingraph_primary_window)
            stbwingraph_SetGLWindow(stbwingraph_primary_window);
         n = func(stbwingraph_GetTimestep(mintime), real, in_client);
         if (n == STBWINGRAPH_update_exit)
            return 0; // update_quit

         is_animating = (n != STBWINGRAPH_update_pause);

         needs_drawing = FALSE;
      }
   }
}

void stbwingraph_SwapBuffers(void *win)
{
   stbwingraph__window *z;
   if (win == NULL) win = stbwingraph_primary_window;
   z = (stbwingraph__window *) GetWindowLong(win, GWL_USERDATA);
   if (z && z->dc)
      SwapBuffers(z->dc);
}
#endif

#ifdef STB_WINMAIN
void stbwingraph_main(void);

char *stb_wingraph_commandline;

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
   {
      char buffer[1024];
      // add spaces to either side of the string
      buffer[0] = ' ';
      strcpy(buffer+1, lpCmdLine);
      strcat(buffer, " ");
      if (strstr(buffer, " -reset ")) {
         ChangeDisplaySettings(NULL, 0);
         exit(0);
      }
      if (strstr(buffer, " -window ") || strstr(buffer, " -windowed "))
         stbwingraph_request_windowed = TRUE;
      else if (strstr(buffer, " -full ") || strstr(buffer, " -fullscreen "))
         stbwingraph_request_fullscreen = TRUE;
   }
   stb_wingraph_commandline = lpCmdLine;

   stbwingraph_DefineClass(hInstance, "appicon");
   stbwingraph_main();

   return 0;
}
#endif

#undef STB_EXTERN
#ifdef STB_WINGRAPH_DISABLE_DEFINE_AT_END
#undef STB_DEFINE
#endif

#endif // INCLUDE_STB_WINGRAPH_H


text:
describe "Application 'disgustingnoises'" do
  before do
    @app = UIApplication.sharedApplication
  end

  it "has one window" do
    @app.windows.size.should == 1
  end
end


text:
/**
 * @class Bar
 */
'use strict';

Object.defineProperty(exports, '__esModule', {
  value: true
});

var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }

var Bar = (function () {

  /**
   * @constructor
   * @param string id Container ID that should be assigned
   */

  function Bar(id) {
    _classCallCheck(this, Bar);

    this.id = id;
  }

  /**
   * @return DOMElement
   */

  _createClass(Bar, [{
    key: 'getContainer',
    value: function getContainer() {
      return this.container;
    }

    /**
     * @param DOMElement container
     * @return Bar
     */
  }, {
    key: 'setContainer',
    value: function setContainer(container) {
      this.container = container;
      this.container.id = this.id;
      return this;
    }

    /**
     * @param boolean returnResult
     * @return String
     */
  }, {
    key: 'render',
    value: function render(returnResult) {
      return '';
    }
  }]);

  return Bar;
})();

exports['default'] = Bar;
module.exports = exports['default'];


text:
package types

import (
	"math/big"
	"DNA/vm/avm/interfaces"
)

type Boolean struct {
	value bool
}

func NewBoolean(value bool) *Boolean{
	var b Boolean
	b.value = value
	return &b
}

func (b *Boolean) Equals(other StackItemInterface) bool{
	if _, ok := other.(*Boolean); !ok {
		return false
	}
	if b.value != other.GetBoolean() {
		return false
	}
	return true
}

func (b *Boolean) GetBigInteger() *big.Int {
	if b.value {
		return big.NewInt(1)
	}
	return big.NewInt(0)
}

func (b *Boolean) GetBoolean() bool{
	return b.value
}

func (b *Boolean) GetByteArray() []byte {
	if b.value {
		return []byte{1}
	}
	return []byte{0}
}

func (b *Boolean) GetInterface() interfaces.IInteropInterface {
	return nil
}

func (b *Boolean) GetArray() []StackItemInterface {
	return []StackItemInterface{b}
}


text:
import "babel-polyfill";

import React from "react";
import ReactDOM from "react-dom";
import {Provider} from "react-redux";
import {createStore, applyMiddleware} from "redux";
import createSagaMiddleware from 'redux-saga'
import allReducers from "./reducers";
import App from "./components/app";

const sagaMiddleware = createSagaMiddleware();

const store = createStore(
  allReducers,
  applyMiddleware(
    sagaMiddleware // lets add asynchronious sagas into the mix
  )
);

import rootSaga from './sagas/root-saga'
sagaMiddleware.run(rootSaga);

ReactDOM.render(
    <Provider store={store}>
        <App />
    </Provider>,
    document.getElementById('root')
);


text:
/**
 * Function to send Permissions via Ajax to Com-Config Application Controller
 */
function sendPermissions(event) {
	// set the icon while storing the values
	var icon = document.getElementById('icon_' + this.id);
	icon.removeAttribute('class');
	icon.setAttribute('style', 'background: url(../media/system/images/modal/spinner.gif); display: inline-block; width: 16px; height: 16px');

	//get values and prepare GET-Parameter
	var asset = 'not';
	var component = getUrlParam('component');
	var extension = getUrlParam('extension');
	var option = getUrlParam('option');
	var view = getUrlParam('view');
	var title = component;
	var value = this.value;

	if (option == 'com_config' && component == false && extension == false)
	{
		asset = 'root.1';
	}
	else if (extension == false && view == 'component'){
		asset = component;
	}
	else if (extension != false && view != false){
		asset = extension + '.' + view + '.' + getUrlParam('id');
		title = document.getElementById('jform_title').value;
	}
	else if (extension == false && view != false){
		asset = option + '.' + view + '.' + getUrlParam('id');
		title = document.getElementById('jform_title').value;
	}

	var id = this.id.replace('jform_rules_', '');
	var lastUnderscoreIndex = id.lastIndexOf('_');

	var permission_data = {
		comp   : asset,
		action : id.substring(0, lastUnderscoreIndex),
		rule   : id.substring(lastUnderscoreIndex + 1),
		value  : value,
		title  : title
	};

	// Remove js messages, if they exist.
	Joomla.removeMessages();

	// doing ajax request
	jQuery.ajax({
		method: "POST",
		url: document.getElementById('permissions-sliders').getAttribute('data-ajaxuri'),
		data: permission_data,
		datatype: 'json'
	})
	.fail(function (jqXHR, textStatus, error) {
		// Remove the spinning icon.
		icon.removeAttribute('style');

		Joomla.renderMessages(Joomla.ajaxErrorsMessages(jqXHR, textStatus, error));

		window.scrollTo(0, 0);

		icon.setAttribute('class', 'icon-cancel');
	})
	.done(function (response) {
		// Remove the spinning icon.
		icon.removeAttribute('style');

		if (response.data)
		{
			// Check if everything is OK
			if (response.data.result == true)
			{
				icon.setAttribute('class', 'icon-save');

				jQuery(event.target).parents().next('td').find('span')
					.removeClass().addClass(response.data.class)
					.html(response.data.text);
			}
		}

		// Render messages, if any. There are only message in case of errors.
		if (typeof response.messages == 'object' && response.messages !== null)
		{
			Joomla.renderMessages(response.messages);

			if (response.data && response.data.result == true)
			{
				icon.setAttribute('class', 'icon-save');
			}
			else
			{
				icon.setAttribute('class', 'icon-cancel');
			}

			window.scrollTo(0, 0);
		}
	});
}

/**
 * Function to get parameters out of the url
 */
function getUrlParam(variable) {
	var query = window.location.search.substring(1);
	var vars = query.split('&');
	for (var i=0;i<vars.length;i++)
	{
		var pair = vars[i].split('=');
		if (pair[0] == variable)
		{
			return pair[1];
		}
	}
	return false;
}


text:
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.Model;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;

namespace FireflySoft.Excel
{
    public class NPOIOperator
    {
        /// <summary>
        /// Excel数据文件物理路径
        /// </summary>
        private string dataFilePath = null;

        /// <summary>
        /// Excel模板文件物理路径,根据模板生成时需要
        /// </summary>
        private string templateFilePath = null;

        /// <summary>
        /// NPOI Excel工作簿操作接口
        /// </summary>
        private IWorkbook workbook = null;

        /// <summary>
        /// 内容样式字典
        /// </summary>
        private Dictionary<string, ICellStyle> cellStyleDictionary;

        /// <summary>
        /// 标题样式
        /// </summary>
        private ICellStyle titleStyle;

        /// <summary>
        /// 写入时是否使用内置样式
        /// </summary>
        private bool isUseBuiltInStyle;

        /// <summary>
        /// 初始化构造函数
        /// </summary>
        /// <param name="dataFilePath">Excel数据文件物理路径</param>
        public NPOIOperator(string dataFilePath, bool isUseBuiltInStyle)
            : this(string.Empty, dataFilePath, isUseBuiltInStyle)
        {
        }

        /// <summary>
        /// 初始化构造函数
        /// </summary>
        /// <param name="templateFilePath">Excel模板文件物理路径</param>
        /// <param name="dataFilePath">Excel数据文件物理路径</param>
        public NPOIOperator(string templateFilePath, string dataFilePath, bool isUseBuiltInStyle)
        {
            this.isUseBuiltInStyle = isUseBuiltInStyle;
            this.dataFilePath = dataFilePath;
            this.templateFilePath = templateFilePath;

            CreateWorkbook();

            InitTitleStyle();
            InitContentStyle();
        }

        /// <summary>
        /// 初始化内容样式
        /// </summary>
        private void InitContentStyle()
        {
            cellStyleDictionary = new Dictionary<string, ICellStyle>();

            // 内容字体
            IFont contentFont = workbook.CreateFont();
            contentFont.FontHeightInPoints = 9;
            contentFont.FontName = "宋体";

            IDataFormat format = workbook.CreateDataFormat();

            // 日期样式
            ICellStyle dateStyle = workbook.CreateCellStyle();
            dateStyle.SetFont(contentFont);
            dateStyle.WrapText = false;
            dateStyle.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;
            dateStyle.DataFormat = format.GetFormat("yyyy-MM-dd");
            cellStyleDictionary.Add("date", dateStyle);

            // 日期时间样式
            ICellStyle dateTimeStyle = workbook.CreateCellStyle();
            dateTimeStyle.SetFont(contentFont);
            dateTimeStyle.WrapText = false;
            dateTimeStyle.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;
            dateTimeStyle.DataFormat = format.GetFormat("yyyy-MM-dd HH:mm:ss");
            cellStyleDictionary.Add("datetime", dateStyle);

            // Money样式
            ICellStyle doubleStyle = workbook.CreateCellStyle();
            doubleStyle.SetFont(contentFont);
            doubleStyle.WrapText = false;
            doubleStyle.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;
            doubleStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("0.00");
            cellStyleDictionary.Add("double", doubleStyle);

            // 文本样式
            ICellStyle textStyle = workbook.CreateCellStyle();
            textStyle.SetFont(contentFont);
            textStyle.WrapText = false;
            textStyle.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;
            cellStyleDictionary.Add("text", textStyle);
        }

        /// <summary>
        /// 初始化标题样式
        /// </summary>
        private void InitTitleStyle()
        {
            // 标题字体
            IFont titleFont = workbook.CreateFont();
            titleFont.FontHeightInPoints = 9;
            titleFont.FontName = "宋体";
            titleFont.Boldweight = (short)FontBoldWeight.Bold;

            // 标题样式
            titleStyle = workbook.CreateCellStyle();
            titleStyle.WrapText = false;
            titleStyle.SetFont(titleFont);
            titleStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Left;
            titleStyle.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;
        }

        /// <summary>
        /// 获取Excel工作簿
        /// </summary>
        /// <returns></returns>
        public IWorkbook GetWorkBook()
        {
            return workbook;
        }

        /// <summary>
        /// 根据Sheet表名称获取Sheet表
        /// </summary>
        /// <param name="sheetName"></param>
        /// <returns></returns>
        public ISheet GetSheet(string sheetName)
        {
            if (string.IsNullOrWhiteSpace(sheetName))
            {
                throw new ArgumentNullException("sheetName为空");
            }

            return workbook.GetSheet(sheetName);
        }

        /// <summary>
        /// 根据Sheet表索引位置获取Sheet表
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        public ISheet GetSheet(int index)
        {
            if (index >= 0)
            {
                if (workbook.NumberOfSheets >= index + 1)
                {
                    return workbook.GetSheetAt(index);
                }
            }

            return null;
        }

        /// <summary>
        /// 创建指定名称的Sheet表
        /// </summary>
        /// <param name="sheetName"></param>
        /// <returns></returns>
        public ISheet CreateSheet(string sheetName)
        {
            if (string.IsNullOrWhiteSpace(sheetName))
            {
                throw new ArgumentNullException("sheetName为空");
            }

            return workbook.CreateSheet(sheetName);
        }

        /// <summary>
        /// 获取Sheet表数量
        /// </summary>
        /// <returns></returns>
        public int GetSheetCount()
        {
            return workbook.NumberOfSheets;
        }

        #region 写数据
        /// <summary>
        /// 将DataTable数据写入到Sheet表,默认从Sheet表的第0行开始
        /// </summary>
        /// <param name="sheetName">Sheet表名</param>
        /// <param name="data">DataTable数据</param>
        /// <param name="isWriteTitle">是否写入DataTable列名作为Sheet表标题</param>
        /// <returns>写入的最后行号</returns>
        public int WriteSheet(string sheetName, DataTable data, bool isWriteTitle)
        {
            if (workbook == null)
            {
                throw new NullReferenceException("workbook为null,请先调用Open方法初始化workbook");
            }

            ISheet sheet = GetSheet(sheetName);
            if (sheet == null)
            {
                sheet = CreateSheet(sheetName);
            }

            return WriteSheet(sheet, data, isWriteTitle);
        }

        /// <summary>
        /// 将DataTable数据写入到Sheet表,默认从Sheet表的第0行开始
        /// </summary>
        /// <param name="sheet">Sheet表</param>
        /// <param name="data">DataTable数据</param>
        /// <param name="isWriteTitle">是否写入DataTable列名作为Sheet表标题</param>
        /// <returns>写入的最后行号</returns>
        public int WriteSheet(ISheet sheet, DataTable data, bool isWriteTitle)
        {
            return WriteSheet(sheet, data, isWriteTitle, 0);
        }

        /// <summary>
        /// 将DataTable数据写入到Sheet表
        /// </summary>
        /// <param name="sheet">Sheet表</param>
        /// <param name="data">DataTable数据</param>
        /// <param name="isWriteTitle">是否写入DataTable列名作为Sheet表标题</param>
        /// <param name="startRowNumber">开始写入数据的行号(有效索引从0开始)</param>
        /// <returns>写入的最后行号</returns>
        public int WriteSheet(ISheet sheet, DataTable data, bool isWriteTitle, int startRowNumber)
        {
            int endRowNumber = 0;

            // 创建标题行
            if (isWriteTitle == true)
            {
                IRow titleRow = sheet.CreateRow(startRowNumber);
                WriteTitle(titleRow, data.Columns);
                startRowNumber++;
            }

            // 创建数据行
            endRowNumber = WriteContent(sheet, data, startRowNumber);

            // 自动适应列宽
            AutoFitColumnWidth(sheet, data.Columns.Count);

            return endRowNumber;
        }

        /// <summary>
        /// 写入数据到Sheet表标题
        /// </summary>
        /// <param name="sheet"></param>
        /// <param name="columns"></param>
        public void WriteTitle(ISheet sheet, DataColumnCollection columns)
        {
            IRow row = sheet.CreateRow(0);

            WriteTitle(row, columns);
        }

        /// <summary>
        /// 写入数据到Row
        /// </summary>
        /// <param name="row"></param>
        /// <param name="columns"></param>
        public void WriteTitle(IRow row, DataColumnCollection columns)
        {
            for (int j = 0; j < columns.Count; j++)
            {
                var cell = row.CreateCell(j);
                cell.SetCellValue(columns[j].ColumnName);
                cell.CellStyle = titleStyle;
            }
        }

        /// <summary>
        /// 写入数据到内容
        /// </summary>
        /// <param name="sheet"></param>
        /// <param name="data"></param>
        /// <param name="strartRowNumber"></param>
        /// <returns></returns>
        public int WriteContent(ISheet sheet, DataTable data, int strartRowNumber)
        {
            return WriteContent(sheet, data, strartRowNumber, 0);
        }

        /// <summary>
        /// 写入数据到内容
        /// </summary>
        /// <param name="sheet"></param>
        /// <param name="data"></param>
        /// <param name="strartRowNumber"></param>
        /// <param name="startColNumber"></param>
        /// <returns></returns>
        public int WriteContent(ISheet sheet, DataTable data, int strartRowNumber, int startColNumber)
        {
            // 创建内容行
            for (int i = 0; i < data.Rows.Count; i++)
            {
                IRow row = sheet.CreateRow(strartRowNumber);
                row.Height = 26 * 20;

                WriteRow(row, startColNumber, data.Columns, data.Rows[i]);

                strartRowNumber++;
            }

            return strartRowNumber;
        }

        /// <summary>
        /// 写入数据到某一行
        /// </summary>
        /// <param name="row"></param>
        /// <param name="data"></param>
        /// <param name="cols"></param>
        public void WriteRow(IRow row, DataColumnCollection cols, DataRow data)
        {
            WriteRow(row, 0, cols, data);
        }

        /// <summary>
        /// 写入数据到某一行
        /// </summary>
        /// <param name="row"></param>
        /// <param name="startColNumber"></param>
        /// <param name="data"></param>
        /// <param name="cols"></param>
        public void WriteRow(IRow row, int startColNumber, DataColumnCollection cols, DataRow data)
        {
            for (int j = 0; j < cols.Count; j++)
            {
                var cell = row.CreateCell(startColNumber + j);

                CellDataType cellDataType = CellDataType.None;
                if (data[j] != null)
                {
                    cellDataType = GetCellDataTypeByColumn(cols[j]);
                }

                WriteCell(cell, data[j], cellDataType);
            }
        }

        /// <summary>
        /// 写入数据到单元格
        /// </summary>
        /// <param name="sheet">要写入数据的sheet表实例</param>
        /// <param name="rowNumber">要写入数据的行号</param>
        /// <param name="columnNumber">要写入数据的列号</param>
        /// <param name="value">要写入的数据</param>
        /// <param name="dataType">要写入数据的类型</param>
        public void WriteCell(ISheet sheet, int rowNumber, int columnNumber, object value, CellDataType dataType)
        {
            var row = sheet.GetRow(rowNumber);
            if (row == null)
            {
                row = sheet.CreateRow(rowNumber);
            }

            WriteCell(row, columnNumber, value, dataType);
        }

        /// <summary>
        /// 写入数据到单元格
        /// </summary>
        /// <param name="row">要写入数据的行实例</param>
        /// <param name="columnNumber">要写入数据的列号</param>
        /// <param name="value">要写入的数据</param>
        /// <param name="dataType">要写入数据的类型</param>
        public void WriteCell(IRow row, int columnNumber, object value, CellDataType dataType)
        {
            var cell = row.GetCell(columnNumber);
            if (cell == null)
            {
                cell = row.CreateCell(columnNumber);
            }

            WriteCell(cell, value, dataType);
        }

        /// <summary>
        /// 写入数据到单元格
        /// </summary>
        /// <param name="cell">要写入数据的单元格实例</param>
        /// <param name="value">要写入的数据</param>
        /// <param name="dataType">要写入数据的类型</param>
        public void WriteCell(ICell cell, object value, CellDataType dataType)
        {
            if (dataType == CellDataType.None || dataType == CellDataType.Null || value == null || value == DBNull.Value)
            {
                cell.SetCellType(CellType.Blank);
                return;
            }

            if (value is DateTime)
            {
                cell.SetCellValue((DateTime)value);
            }
            else if (value is int)
            {
                cell.SetCellValue((int)value);
            }
            else if (value is double)
            {
                cell.SetCellValue((double)value);
            }
            else if (value is decimal)
            {
                cell.SetCellValue(Convert.ToDouble(value));
            }
            else
            {
                cell.SetCellValue(value.ToString());
            }

            if (dataType != CellDataType.None)
            {
                switch (dataType)
                {
                    case CellDataType.Date:
                        cell.CellStyle = cellStyleDictionary["date"];
                        break;
                    case CellDataType.DateTime:
                        cell.CellStyle = cellStyleDictionary["datetime"];
                        break;
                    case CellDataType.Double:
                        cell.CellStyle = cellStyleDictionary["double"];
                        break;
                    default:
                        cell.CellStyle = cellStyleDictionary["text"];
                        break;
                }
            }
        }

        /// <summary>
        /// 将内存中的数据写入到Excel数据文件
        /// </summary>
        public void Flush()
        {
            using (var dataFileStream = new FileStream(dataFilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite))
            {
                workbook.Write(dataFileStream);
            }
        }
        #endregion

        #region 读数据
        /// <summary>
        /// 自动适应列宽
        /// </summary>
        /// <param name="sheet">需要自适应列宽的sheet表</param>
        /// <param name="columnCount">列数</param>
        public void AutoFitColumnWidth(ISheet sheet, int columnCount)
        {
            //列宽自适应,只对英文和数字有效
            for (int ci = 0; ci < columnCount; ci++)
            {
                sheet.AutoSizeColumn(ci);
            }
            //获取当前列的宽度,然后对比本列的长度,取最大值
            for (int columnNum = 0; columnNum < columnCount; columnNum++)
            {
                int columnWidth = sheet.GetColumnWidth(columnNum) / 256;
                for (int rowNum = 0; rowNum < sheet.LastRowNum; rowNum++)
                {
                    if (rowNum == 0 || rowNum == sheet.LastRowNum - 1 || rowNum == sheet.LastRowNum / 2)
                    {
                        IRow currentRow;

                        //当前行未被使用过
                        if (sheet.GetRow(rowNum) == null)
                        {
                            currentRow = sheet.CreateRow(rowNum);
                        }
                        else
                        {
                            currentRow = sheet.GetRow(rowNum);
                        }

                        if (currentRow.GetCell(columnNum) != null)
                        {
                            ICell currentCell = currentRow.GetCell(columnNum);
                            int length = Encoding.Default.GetBytes(currentCell.ToString()).Length;
                            if (columnWidth < length)
                            {
                                columnWidth = length;
                            }
                        }
                    }
                }

                if (columnWidth > 255)
                {
                    columnWidth = 255;
                }

                sheet.SetColumnWidth(columnNum, columnWidth * 256);
            }
        }

        /// <summary>
        /// 将Sheet表数据读取到DataTable
        /// </summary>
        /// <param name="sheetName">Excel Sheet表名</param>
        /// <param name="isReadTitle">是否将Sheet表标题作为DataTable列名</param>
        /// <returns>读取到的数据,如果Sheet表不存在则返回null</returns>
        public DataTable ReadSheet(string sheetName, bool isReadTitle)
        {
            ISheet sheet = null;
            DataTable data = null;

            if (workbook == null)
            {
                throw new NullReferenceException("workbook为null,请先调用Open方法初始化workbook");
            }

            if (!string.IsNullOrWhiteSpace(sheetName))
            {
                sheet = GetSheet(sheetName);
            }

            if (sheet != null)
            {
                data = ReadSheet(sheet, isReadTitle);
            }

            return data;
        }

        /// <summary>
        /// 将Sheet表数据读取到DataTable
        /// </summary>
        /// <param name="sheet">Sheet表</param>
        /// <param name="isReadTitle">是否将Sheet表标题作为DataTable列名</param>
        /// <returns>读取到的数据,如果Sheet表不存在则返回null</returns>
        public DataTable ReadSheet(ISheet sheet, bool isReadTitle)
        {
            return ReadSheet(sheet, isReadTitle, 0);
        }

        /// <summary>
        /// 将Sheet表数据读取到DataTable
        /// </summary>
        /// <param name="sheet">Sheet表</param>
        /// <param name="isReadTitle">是否将Sheet表标题作为DataTable列名</param>
        /// <param name="startRowNumber">起始行号</param>
        /// <returns>读取到的数据,如果Sheet表不存在则返回null</returns>
        public DataTable ReadSheet(ISheet sheet, bool isReadTitle, int startRowNumber)
        {
            return ReadSheet(sheet, isReadTitle, false, startRowNumber);
        }

        /// <summary>
        /// 将Sheet表数据读取到DataTable
        /// </summary>
        /// <param name="sheet">Sheet表</param>
        /// <param name="isReadTitle">是否将Sheet表标题作为DataTable列名</param>
        /// <param name="useCellType">是否使用单元格的数据类型格式化数据,如果列中的数据类型都是一致的可以设置为true,否则使用DataTable中列的数据类型读取数据。</param>
        /// <param name="startRowNumber">起始行号</param>
        /// <param name="startColNumber">起始列号</param>
        /// <returns>读取到的数据,如果Sheet表不存在则返回null</returns>
        public DataTable ReadSheet(ISheet sheet, bool isReadTitle, bool useCellType, int startRowNumber, int? startColNumber = null)
        {
            // TODO:添加读取结束行号和结束列号参数

            DataTable data = null;

            if (sheet != null)
            {
                data = new DataTable();

                // 是否读取标题行
                if (isReadTitle)
                {
                    IRow titleRow = sheet.GetRow(startRowNumber);
                    var cols = ReadTitle(titleRow, startColNumber);
                    if (cols != null)
                    {
                        data.Columns.AddRange(cols);
                    }

                    startRowNumber++;
                }
                else
                {
                    // 如果不读取标题行,则从数据第一行获取列数
                    var row = sheet.GetRow(startRowNumber);
                    if (row != null)
                    {
                        if (!startColNumber.HasValue)
                        {
                            startColNumber = row.FirstCellNum;
                        }

                        var colCount = row.LastCellNum - startColNumber.Value;
                        for (int i = 0; i < colCount; i++)
                        {
                            data.Columns.Add("列" + (i + 1));
                        }
                    }

                }

                // 读取数据
                ReadContent(sheet, startRowNumber, data, useCellType);
            }

            return data;
        }

        /// <summary>
        /// 获取Sheet表的标题,读取第一行
        /// </summary>
        /// <param name="sheet">sheet表</param>
        /// <returns>标题列数组</returns>
        public DataColumn[] ReadTitle(ISheet sheet)
        {
            IRow firstRow = sheet.GetRow(0);
            if (firstRow == null)
            {
                return new DataColumn[0];
            }

            return ReadTitle(firstRow);
        }

        /// <summary>
        /// 从Row实例获取标题
        /// </summary>
        /// <param name="row">Row实例</param>
        /// <param name="startColNumber">起始列号</param>
        /// <returns>标题列数组</returns>
        public DataColumn[] ReadTitle(IRow row, int? startColNumber = null)
        {
            if (!startColNumber.HasValue)
            {
                startColNumber = row.FirstCellNum;
            }

            int cellCount = row.LastCellNum - startColNumber.Value;
            DataColumn[] cols = new DataColumn[cellCount];

            int j = 0;
            for (int i = startColNumber.Value; i < row.LastCellNum; i++)
            {
                DataColumn column = new DataColumn(row.GetCell(i).StringCellValue);
                cols[j] = column;
                j++;
            }

            return cols;
        }

        /// <summary>
        /// 读取sheet表数据到DataTable中
        /// </summary>
        /// <param name="sheet">sheet表</param>
        /// <param name="startRowNumber">起始行号</param>
        /// <param name="table">要读入数据的DataTable</param>
        /// <returns>读取的数据行数</returns>
        public int ReadContent(ISheet sheet, int startRowNumber, DataTable table)
        {
            return ReadContent(sheet, startRowNumber, table, false);
        }

        /// <summary>
        /// 读取sheet表数据到DataTable中
        /// </summary>
        /// <param name="sheet">sheet表</param>
        /// <param name="startRowNumber">起始行号</param>
        /// <param name="table">要读入数据的DataTable</param>
        /// <param name="useCellType">是否使用单元格的数据类型格式化数据,如果列中的数据类型都是一致的可以设置为true,否则使用DataTable中列的数据类型读取数据。</param>
        /// <returns>读取的数据行数</returns>
        public int ReadContent(ISheet sheet, int startRowNumber, DataTable table, bool useCellType)
        {
            int endRowNumber = sheet.LastRowNum;
            return ReadContent(sheet, startRowNumber, endRowNumber, table, useCellType);
        }

        /// <summary>
        /// 读取sheet表数据到DataTable中
        /// </summary>
        /// <param name="sheet">sheet表</param>
        /// <param name="startRowNumber">起始行号</param>
        /// <param name="endRowNumber">终止行号</param>
        /// <param name="table">要读入数据的DataTable</param>
        /// <returns>读取的数据行数</returns>
        public int ReadContent(ISheet sheet, int startRowNumber, int endRowNumber, DataTable table)
        {
            return ReadContent(sheet, startRowNumber, endRowNumber, table, false);
        }

        /// <summary>
        /// 读取sheet表数据到DataTable中
        /// </summary>
        /// <param name="sheet">sheet表</param>
        /// <param name="startRowNumber">起始行号</param>
        /// <param name="endRowNumber">终止行号</param>
        /// <param name="table">要读入数据的DataTable</param>
        /// <param name="useCellType">是否使用单元格的数据类型格式化数据,如果列中的数据类型都是一致的可以设置为true,否则使用DataTable中列的数据类型读取数据。</param>
        /// <returns>读取的数据行数</returns>
        public int ReadContent(ISheet sheet, int startRowNumber, int endRowNumber, DataTable table, bool useCellType)
        {
            int columnCount = table.Columns.Count;
            int rowCount = 0;
            for (int i = startRowNumber; i <= endRowNumber; i++)
            {
                IRow row = sheet.GetRow(i);
                if (row == null) continue;

                var rowData = ReadRow(row, table.Columns, useCellType);
                if (rowData != null)
                {
                    if (useCellType)
                    {
                        if (i == startRowNumber)
                        {
                            InitColumnTypeWithCellType(table.Columns, rowData);
                        }
                    }

                    DataRow dataRow = table.NewRow();
                    for (int j = 0; j < rowData.Length; j++)
                    {
                        dataRow[j] = rowData[j];
                    }

                    table.Rows.Add(dataRow);
                }

                rowCount++;
            }

            return rowCount;
        }

        /// <summary>
        /// 读取一行数据
        /// </summary>
        /// <param name="row"></param>
        /// <param name="cols"></param>
        /// <returns></returns>
        public object[] ReadRow(IRow row, DataColumnCollection cols)
        {
            return ReadRow(row, cols, false);
        }

        /// <summary>
        /// 读取一行数据
        /// </summary>
        /// <param name="row">行对象</param>
        /// <param name="cols">列集合</param>
        /// <param name="useCellType">是否使用单元格的数据类型格式化数据,如果列中的数据类型都是一致的可以设置为true,否则使用DataTable中列的数据类型读取数据。</param>
        /// <returns></returns>
        public object[] ReadRow(IRow row, DataColumnCollection cols, bool useCellType)
        {
            if (cols.Count == 0)
            {
                return null;
            }

            var lastCellNum = row.FirstCellNum + cols.Count - 1;

            int i = 0;
            object[] data = new object[cols.Count];
            for (int j = row.FirstCellNum; j <= lastCellNum; j++)
            {
                var cell = row.GetCell(j);
                if (cell != null)
                {
                    CellDataType cellDataType = CellDataType.Text;

                    if (useCellType)
                    {
                        cellDataType = GetCellDataTypeByCell(cell);
                    }
                    else
                    {
                        cellDataType = GetCellDataTypeByColumn(cols[i]);
                    }

                    data[i] = ReadCell(cell, cellDataType);
                }

                i++;
            }

            return data;
        }

        /// <summary>
        /// 读取单元格数据
        /// </summary>
        /// <param name="sheet">要读取数据的sheet表实例</param>
        /// <param name="rowNumber">要读取数据的行号</param>
        /// <param name="columnNumber">要读取数据的列号</param>
        public object ReadCell(ISheet sheet, int rowNumber, int columnNumber, CellDataType cellDataType)
        {
            var row = sheet.GetRow(rowNumber);
            if (row != null)
            {
                return ReadCell(row, columnNumber, cellDataType);
            }

            return null;
        }

        /// <summary>
        /// 读取单元格数据
        /// </summary>
        /// <param name="row">要读取数据的行实例</param>
        /// <param name="columnNumber">要读取数据的列号</param>
        public object ReadCell(IRow row, int columnNumber, CellDataType cellDataType)
        {
            var cell = row.GetCell(columnNumber);
            if (cell != null)
            {
                return ReadCell(cell, cellDataType);
            }

            return null;
        }

        /// <summary>
        /// 读取单元格数据
        /// </summary>
        /// <param name="cell">要读取数据的单元格</param>
        public object ReadCell(ICell cell, CellDataType cellDataType)
        {
            if (cellDataType == CellDataType.Boolean)
            {
                return cell.BooleanCellValue;
            }
            else if (cellDataType == CellDataType.Date)
            {
                return cell.DateCellValue;
            }
            else if (cellDataType == CellDataType.DateTime)
            {
                return cell.DateCellValue;
            }
            else if (cellDataType == CellDataType.Double)
            {
                return cell.NumericCellValue;
            }
            else if (cellDataType == CellDataType.Formula)
            {
                return cell.CellFormula;
            }
            else if (cellDataType == CellDataType.Int)
            {
                return (int)cell.NumericCellValue;
            }
            else if (cellDataType == CellDataType.RichText)
            {
                return cell.RichStringCellValue;
            }
            else if (cellDataType == CellDataType.Text)
            {
                return cell.ToString();
            }
            else if (cellDataType == CellDataType.None)
            {
                return string.Empty;
            }
            else if (cellDataType == CellDataType.Null)
            {
                return null;
            }

            return null;
        }
        #endregion

        /// <summary>
        /// 根据模板或数据excel文件创建工作簿实例
        /// </summary>
        /// <returns></returns>
        private IWorkbook CreateWorkbook()
        {
            if (!string.IsNullOrEmpty(templateFilePath))
            {
                using (var templateFile = new FileStream(templateFilePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    if (templateFilePath.IndexOf(".xlsx") > 0)
                    {
                        workbook = new XSSFWorkbook(templateFile);
                    }
                    else if (templateFilePath.IndexOf(".xls") > 0)
                    {
                        workbook = new HSSFWorkbook(templateFile);
                    }
                }
            }
            else
            {
                if (File.Exists(dataFilePath))
                {
                    using (var dataFile = new FileStream(dataFilePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        if (dataFilePath.IndexOf(".xlsx") > 0)
                        {
                            workbook = new XSSFWorkbook(dataFile);
                        }
                        else if (dataFilePath.IndexOf(".xls") > 0)
                        {
                            workbook = new HSSFWorkbook(dataFile);
                        }
                    }
                }
                else
                {
                    if (dataFilePath.IndexOf(".xlsx") > 0)
                    {
                        workbook = new XSSFWorkbook();
                    }
                    else if (dataFilePath.IndexOf(".xls") > 0)
                    {
                        workbook = new HSSFWorkbook();
                    }
                }
            }

            return workbook;
        }

        /// <summary>
        /// 使用CellType初始化列的数据类型
        /// </summary>
        /// <param name="cols"></param>
        /// <param name="rowData"></param>
        private static void InitColumnTypeWithCellType(DataColumnCollection cols, object[] rowData)
        {
            for (int k = 0; k < rowData.Length; k++)
            {
                var o = rowData[k];
                if (o != null)
                {
                    if (cols.Count > k)
                    {
                        cols[k].DataType = o.GetType();
                    }
                }
            }
        }

        /// <summary>
        /// 根据列属性获取数据类型
        /// </summary>
        /// <param name="column">列构造实例</param>
        /// <returns></returns>
        private CellDataType GetCellDataTypeByColumn(DataColumn column)
        {
            var cellDataType = CellDataType.None;

            if (isUseBuiltInStyle)
            {
                if (column.ExtendedProperties != null && column.ExtendedProperties.Count > 0)
                {
                    if (column.ExtendedProperties.ContainsKey("DataType"))
                    {
                        var propertyValue = column.ExtendedProperties["DataType"].ToString();
                        cellDataType = GetDataTypeFromColumnExtendedProperty(propertyValue);
                    }
                }
                else
                {
                    Type columnDataType = column.DataType;
                    cellDataType = GetDataTypeFromColumnDataType(columnDataType);
                }
            }

            return cellDataType;
        }

        /// <summary>
        /// 根据单元格类型获取数据类型
        /// </summary>
        /// <param name="cellType">单元格类型</param>
        /// <returns></returns>
        private CellDataType GetCellDataTypeByCell(ICell cell)
        {
            if (cell != null)
            {
                var cellType = cell.CellType;
                var cellDataType = CellDataType.None;
                var cellStyle = cell.CellStyle;
                var cellFormaStringt = cellStyle.GetDataFormatString();

                if (cellType == CellType.Blank)
                {
                    cellDataType = CellDataType.None;
                }
                else if (cellType == CellType.Boolean)
                {
                    cellDataType = CellDataType.Boolean;
                }
                else if (cellType == CellType.Error)
                {
                    cellDataType = CellDataType.Text;
                }
                else if (cellType == CellType.Formula)
                {
                    cellDataType = CellDataType.Formula;
                }
                else if (cellType == CellType.Numeric)
                {
                    cellDataType = CellDataType.Double;

                    // TODO:简单点可以尝试访问 cell.DateCellValue,不过可能引发异常
                    if (cellFormaStringt == "m/d/yy" || cellFormaStringt == "yyyy-MM-dd")
                    {
                        cellDataType = CellDataType.Date;
                    }
                    else if (cellFormaStringt == "m/d/yy h:mm" || cellFormaStringt == "yyyy-MM-dd HH:mm:ss")
                    {
                        cellDataType = CellDataType.DateTime;
                    }
                    else if (!cell.NumericCellValue.ToString().Contains("."))
                    {
                        cellDataType = CellDataType.Int;
                    }
                }
                else if (cellType == CellType.String)
                {
                    cellDataType = CellDataType.Text;
                }
                else if (cellType == CellType.Unknown)
                {
                    cellDataType = CellDataType.Text;
                }
                return cellDataType;
            }

            return CellDataType.None;
        }

        /// <summary>
        /// 从数据列的类型获取DataType
        /// </summary>
        /// <param name="type">数据类型</param>
        /// <returns>单元格数据类型</returns>
        private static CellDataType GetDataTypeFromColumnDataType(Type type)
        {
            var dataType = CellDataType.None;

            if (type == typeof(DateTime))
            {
                dataType = CellDataType.DateTime;
            }
            else if (type == typeof(int))
            {
                dataType = CellDataType.Int;
            }
            else if (type == typeof(double))
            {
                dataType = CellDataType.Double;
            }
            else if (type == typeof(decimal))
            {
                dataType = CellDataType.Double;
            }
            else if (type == typeof(bool))
            {
                dataType = CellDataType.Boolean;
            }
            else
            {
                dataType = CellDataType.Text;
            }

            return dataType;
        }

        /// <summary>
        /// 从列的扩展属性获取DataType
        /// </summary>
        /// <param name="propertyValue">属性值</param>
        /// <returns>单元格数据类型</returns>
        private static CellDataType GetDataTypeFromColumnExtendedProperty(string propertyValue)
        {
            var dataType = CellDataType.None;

            switch (propertyValue)
            {
                case "Null":
                    dataType = CellDataType.Null;
                    break;
                case "Date":
                    dataType = CellDataType.Date;
                    break;
                case "DateTime":
                    dataType = CellDataType.DateTime;
                    break;
                case "Int":
                    dataType = CellDataType.Int;
                    break;
                case "Double":
                    dataType = CellDataType.Double;
                    break;
                case "Boolean":
                    dataType = CellDataType.Boolean;
                    break;
                case "Formula":
                    dataType = CellDataType.Formula;
                    break;
                case "RichText":
                    dataType = CellDataType.RichText;
                    break;
                default:
                    dataType = CellDataType.Text;
                    break;
            }

            return dataType;
        }
    }
}


text:
.. automodule:: testcontainers.compose
   :members: DockerCompose


text:
package com.thoughtworks.xstream.io.binary;

import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.StreamException;
import com.thoughtworks.xstream.io.ExtendedHierarchicalStreamWriter;

import java.io.DataOutputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.util.Map;
import java.util.HashMap;

/**
 * @since 1.2
 */
public class BinaryStreamWriter implements ExtendedHierarchicalStreamWriter {

    private final IdRegistry idRegistry = new IdRegistry();
    private final DataOutputStream out;
    private final Token.Formatter tokenFormatter = new Token.Formatter();

    public BinaryStreamWriter(OutputStream outputStream) {
        out = new DataOutputStream(outputStream);
    }

    public void startNode(String name) {
        write(new Token.StartNode(idRegistry.getId(name)));
    }

    public void startNode(String name, Class clazz) {
        startNode(name);
    }

    public void addAttribute(String name, String value) {
        write(new Token.Attribute(idRegistry.getId(name), value));
    }

    public void setValue(String text) {
        write(new Token.Value(text));
    }

    public void endNode() {
        write(new Token.EndNode());
    }

    public void flush() {
        try {
            out.flush();
        } catch (IOException e) {
            throw new StreamException(e);
        }
    }

    public void close() {
        try {
            out.close();
        } catch (IOException e) {
            throw new StreamException(e);
        }
    }

    public HierarchicalStreamWriter underlyingWriter() {
        return this;
    }

    private void write(Token token) {
        try {
            tokenFormatter.write(out, token);
        } catch (IOException e) {
            throw new StreamException(e);
        }
    }

    private class IdRegistry {

        private long nextId = 0;
        private Map ids = new HashMap();

        public long getId(String value) {
            Long id = (Long) ids.get(value);
            if (id == null) {
                id = new Long(++nextId);
                ids.put(value, id);
                write(new Token.MapIdToValue(id.longValue(), value));
            }
            return id.longValue();
        }

    }
}


text:
"""CPU profiler that works by instrumenting all function calls (uses cProfile).

This profiler provides detailed function timings for all function calls
during a request.

This is just a simple wrapper for cProfile with result formatting. See
http://docs.python.org/2/library/profile.html for more.

PRO: since every function call is instrumented, you'll be sure to see
everything that goes on during a request. For code that doesn't have lots of
deeply nested function calls, this can be the easiest and most accurate way to
get an idea for which functions are taking lots of time.

CON: overhead is added to each function call due to this instrumentation. If
you're profiling code with deeply nested function calls or tight loops going
over lots of function calls, this perf overhead will add up.
"""

import cProfile
import pstats
import StringIO
import marshal
import base64

import util

class Profile(object):
    """Profiler that wraps cProfile for programmatic access and reporting."""
    def __init__(self):
        self.c_profile = cProfile.Profile()

    def results(self):
        """Return cProfile results in a dictionary for template context."""
        # Make sure nothing is printed to stdout
        output = StringIO.StringIO()
        stats = pstats.Stats(self.c_profile, stream=output)
        stats.sort_stats("cumulative")
        self.c_profile.create_stats()

        results = {
            "raw_stats": base64.b64encode(marshal.dumps(self.c_profile.stats)),
            "total_call_count": stats.total_calls,
            "total_time": util.seconds_fmt(stats.total_tt),
            "calls": []
        }

        width, list_func_names = stats.get_print_list([80])
        for func_name in list_func_names:
            primitive_call_count, total_call_count, total_time, cumulative_time, callers = stats.stats[func_name]

            func_desc = pstats.func_std_string(func_name)

            callers_names = map(lambda func_name: pstats.func_std_string(func_name), callers.keys())
            callers_desc = map(
                    lambda name: {"func_desc": name, "func_desc_short": util.short_method_fmt(name)},
                    callers_names)

            results["calls"].append({
                "primitive_call_count": primitive_call_count,
                "total_call_count": total_call_count,
                "cumulative_time": util.seconds_fmt(cumulative_time, 2),
                "total_time": util.seconds_fmt(total_time, 2),
                "per_call_cumulative": util.seconds_fmt(cumulative_time / primitive_call_count, 2) if primitive_call_count else "",
                "func_desc": func_desc,
                "func_desc_short": util.short_method_fmt(func_desc),
                "callers_desc": callers_desc,
            })

        output.close()

        return results

    def run(self, fxn):
        """Run function with cProfile enabled, saving results."""
        return self.c_profile.runcall(lambda *args, **kwargs: fxn(), None, None)


text:
var vows = require('vows'),
  path = require('path'),
  fs = require('fs'),
  assert = require('assert'),
  cleanCSS = require('../index');

var lineBreak = process.platform == 'win32' ? /\r\n/g : /\n/g;

var batchContexts = function() {
  var context = {};
  fs.readdirSync(path.join(__dirname, 'data')).forEach(function(filename) {
    if (/min.css$/.exec(filename)) return;
    var testName = filename.split('.')[0];

    context[testName] = {
      topic: function() {
        var plainPath = path.join(__dirname, 'data', testName + '.css');
        var minPath = path.join(__dirname, 'data', testName + '-min.css');

        return {
          plain: fs.readFileSync(plainPath, 'utf-8'),
          minimized: fs.readFileSync(minPath, 'utf-8')
        };
      }
    };
    context[testName]['minimizing ' + testName + '.css'] = function(data) {
      var processed = cleanCSS.process(data.plain, {
        removeEmpty: true,
        keepBreaks: true
      });

      var processedTokens = processed.split(lineBreak);
      var minimizedTokens = data.minimized.split(lineBreak);

      processedTokens.forEach(function(line, i) {
        assert.equal(line, minimizedTokens[i]);
      });
    };
  });

  return context;
};

vows.describe('clean-batch')
  .addBatch(batchContexts())
  .export(module);