text:
![m-validate](m-validate-logo.png)

[![npm](https://img.shields.io/npm/v/m-validate.svg?maxAge=2592000&style=flat-square)](https://www.npmjs.com/package/m-validate)
[![npm](https://img.shields.io/npm/dt/m-validate.svg?maxAge=2592000&style=flat-square)](https://www.npmjs.com/package/m-validate)
[![stars](https://img.shields.io/github/stars/moblets/m-validate.svg?maxAge=2592000&style=flat-square)](https://github.com/moblets/m-validate)
[![GitHub forks](https://img.shields.io/github/forks/moblets/m-validate.svg?maxAge=2592000&style=flat-square)](https://github.com/moblets/m-validate/network)
[![license](https://img.shields.io/badge/license-MIT-blue.svg?maxAge=2592000&style=flat-square)](https://github.com/moblets/m-validate#license)

Moblets' NodeJS simple validation to validate data based on a definition JSon.

<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
**Table of Contents**  *generated with [DocToc](https://github.com/thlorenz/doctoc)*

- [Installation](#installation)
- [Available validations](#available-validations)
  - [Input type validation](#input-type-validation)
    - [number](#number)
    - [select, radio and checkbox](#select-radio-and-checkbox)
    - [color](#color)
    - [date](#date)
    - [time](#time)
    - [email](#email)
    - [url](#url)
    - [tel](#tel)
  - [Value validation](#value-validation)
    - [lessThan and moreThan](#lessthan-and-morethan)
    - [lessThanOrEqual and moreThanOrEqual](#lessthanorequal-and-morethanorequal)
  - [Length validation](#length-validation)
    - [minLength and maxLength](#minlength-and-maxlength)
  - [Required validation](#required-validation)
    - [required](#required)
  - [String validations](#string-validations)
    - [alpha](#alpha)
    - [alphaSpace](#alphaspace)
    - [alphaDash](#alphadash)
    - [alphaSymbol](#alphasymbol)
    - [alphaNumeric](#alphanumeric)
    - [alphaNumericSpace](#alphanumericspace)
    - [alphaNumericDash](#alphanumericdash)
    - [alphaNumericSymbol](#alphanumericsymbol)
    - [numeric](#numeric)
    - [numericFloat](#numericfloat)
    - [numericDash](#numericdash)
    - [numericSymbol](#numericsymbol)
- [Pre requisites](#pre-requisites)
- [Usage](#usage)
- [License](#license)

<!-- END doctoc generated TOC please keep comment here to allow auto update -->

## Installation

```
$ npm install --save m-validate
```

## Available validations
Validations were created for **input type**, **length**, **required**, **value** and **string**.

### Input type validation
These are all HTML 5 input type validations.

#### number
Check input type number for integers.

**Usage**

Definition JSon
```json
{
  "name": "Number of friends",
  "type": "number"
}
```

**Error response:** *not_a_number*

#### select, radio and checkbox
Check if the response belongs to the possible values.

**Usage**

Definition JSon

```json
{
  "name": "position",
  "type": "radio",
  "values": {
    "left": "value_left",
    "right": "value_right",
    "up": "value_up",
    "down": "value_down"
  }
}
```
If the value is _left, right, up or down_, it will be validated.

**Error response:** *not_in_the_select_list*, *not_in_the_radio_list* or *not_in_the_checkbox_list*

#### color
Check if the response is a valid HTML 5, hexadecimal color, like '#FF0033'.

**Usage**

Definition JSon
```json
{
  "name": "themeColor",
  "type": "color"
}
```

**Error response:** *not_a_color*

#### date
Check if the response is a valid HTML 5, 'YYYY-MM-DD' date.

**Usage**

Definition JSon
```json
{
  "name": "birthDay",
  "type": "date"
}
```
**Error response:** *not_a_date*

#### time
Check if the response is a valid HTML 5, 'H:mm' time.

**Usage**

Definition JSon
```json
{
  "name": "arrival",
  "type": "time"
}
```
**Error response:** *not_a_time*

#### email
Check if the response is a valid email.

**Usage**

Definition JSon
```json
{
  "name": "userEmail",
  "type": "email"
}
```
**Error response:** *not_an_email*

#### url
Check if the response is a valid url.

**Usage**

Definition JSon
```json
{
  "name": "siteUrl",
  "type": "url"
}
```
**Error response:** *not_an_url*

#### tel
Check if the response is a phone. It's a generic phone validator that accepts international (with plus sign) and local phones (with or without paranthesis).

**Usage**

Definition JSon
```json
{
  "name": "cellNumber",
  "type": "tel"
}
```
**Error response:** *not_a_tel*

### Value validation
These four validations are for numbers to define it's min and max values.

#### lessThan and moreThan
These validations require the data to be a number (int or float) that is 'less than' and/or 'more than' the chosen values.

**Usage**

Definition JSon

```json
{
  "name": "zoom",
  "more-than": 0.1,
  "less-than": 10.4
}
```

**Error response:** *must_be_more_than: 0.1* or *must_be_less_than: 10.4*

#### lessThanOrEqual and moreThanOrEqual
These validations require the data to be a number (int or float) that is 'less than or equal' and/or 'more than or equal' the chosen values.

**Usage**

Definition JSon

```json
{
  "name": "precision",
  "more-than-or-equal": 3,
  "less-than-or-equal": 8.6
}
```

**Error response:** *must_be_more_than_or_equal: 3* or *must_be_less_than_or_equal: 8.6*

### Length validation
These two validations are for generic strings to define it's min and max length.

#### minLength and maxLength
These validations require the data to be a string that has a minimux or maximum number of characters.

**Usage**

Definition JSon

```json
{
  "name": "pinCode",
  "min-length": 4,
  "max-length": 8
}
```

**Error response:** *must_be_min: 4* or *must_be_max: 8*

### Required validation
This validation checks if the required value is available in the POST JSon.

#### required
These validations can be used in any kind of field

**Usage**

Definition JSon

```json
{
  "name": "name",
  "required": true
}
```

**Error response:** *field_is_required*

### String validations
These are validations for specific kinds of strings, that must help creating validations tom many field types.

#### alpha
This validation require the data to be only letters and accented letters (A-z and À-ÿ).

**Usage**

Definition JSon

```json
{
  "name": "firstName",
  "type": "text",
  "string": "alpha"
}
```

**Error response:** *not_an_alpha*

#### alphaSpace
This validation require the data to be only letters, accented letters and spaces (A-z, À-ÿ and ' ').

**Usage**

Definition JSon

```json
{
  "name": "fullName",
  "type": "text",
  "string": "alphaSpace"
}
```

**Error response:** *not_an_alpha_space*

#### alphaDash
This validation require the data to be only letters, accented letters and dashes (A-z, À-ÿ, - and \_).

**Usage**

Definition JSon

```json
{
  "name": "serialNumber",
  "type": "text",
  "string": "alphaDash"
}
```
**Error response:** *not_an_alpha_dash*

#### alphaSymbol
This validation require the data to be letters, accented letters and many symbols:

|  A-z  |  À-ÿ  |   \-   |   _   | . | , | ! | @ |
|-------|-------|-------|-------|-------|-------|-------|-------|
| **#** | **$** | **%** | **^** | **{** | **}** | **[** | **]** |
| **&** | **\*** | **(** | **)** | **<** | **>** | **+** | **=** |
| **?** | **:** | **;** | **" "** |

**Usage**

Definition JSon

```json
{
  "name": "address",
  "type": "text",
  "string": "alphaSymbol"
}
```
**Error response:** *not_an_alpha_symbol*

#### alphaNumeric
This validation require the data to be letters, accented letters and numbers (A-z, À-ÿ and 0-9).

**Usage**

Definition JSon

```json
{
  "name": "code",
  "type": "text",
  "string": "alphaNumeric"
}
```
**Error response:** *not_an_alpha_numeric*

#### alphaNumericSpace
This validation require the data to be letters, accented letters, numbers and space (A-z, À-ÿ, 0-9 and ' ').

**Usage**

Definition JSon

```json
{
  "name": "keyCode",
  "type": "text",
  "string": "alphaNumericSpace"
}
```
**Error response:** *not_an_alpha_numeric_space*

#### alphaNumericDash
This validation require the data to be letters, accented letters, numbers and space (A-z, À-ÿ, 0-9, - and \_).

**Usage**

Definition JSon

```json
{
  "name": "serialNumber",
  "type": "text",
  "string": "alphaNumericDash"
}
```

**Error response:** *not_an_alpha_numeric_dash*

#### alphaNumericSymbol
This validation require the data to be letters, accented letters, numbers and many symbols:

|  A-z  |  À-ÿ  |   0-9   |   " "   | . | , | ! | @ |
|-------|-------|-------|-------|-------|-------|-------|-------|
| **#** | **$** | **%** | **^** | **&** | **\*** | **(** | **)** |
| **{** | **}** | **[** | **]** | **<** | **>** | **+** | **=** |
| **?** | **:** | **;** | **-** | **\_** |  |  |  |

**Usage**

Definition JSon

```json
{
  "name": "serialNumber",
  "type": "text",
  "string": "alphaNumericSymbol"
}
```

**Error response:** *not_an_alpha_numeric_symbol*

#### numeric
This validation require the data to be numbers (0-9).

**Usage**

Definition JSon

```json
{
  "name": "products",
  "type": "text",
  "string": "numeric"
}
```

**Error response:** *not_a_numeric*

#### numericFloat
This validation require the data to be numbers, -, . and , (0-9.,-).

**Usage**

Definition JSon

```json
{
  "name": "price",
  "type": "text",
  "string": "numericFloat"
}
```

**Error response:** *not_a_numeric_float*

#### numericDash
This validation require the data to be numbers, -, \_, . and , (0-9.,-\_).

**Usage**

Definition JSon

```json
{
  "name": "balance",
  "type": "text",
  "string": "numericDash"
}
```

**Error response:** *not_a_numeric_dash*

#### numericSymbol
This validation require the data to be numbers and many symbols:

|  0-9  |  " "  |   0-9   |   _   | . | , | ! | @ |
|-------|-------|-------|-------|-------|-------|-------|-------|
| **#** | **$** | **%** | **^** | **&** | **\*** | **(** | **)** |
| **{** | **}** | **[** | **]** | **<** | **>** | **+** | **=** |
| **?** | **:** | **;** | **-** |

**Usage**

Definition JSon

```json
{
  "name": "code",
  "type": "text",
  "string": "numericSymbol"
}
```

**Error response:** *not_a_numeric_symbol*

## Pre requisites

You must have a definition json like this:

```json
{
  "fields": [
    {
      "name": "name",
      "type": "text",
      "min-length": 3
    },
    {
      "name": "password",
      "type": "number",
      "max-length": 4,
      "min-length": 4,
      "required": true
    },
    {
      "name": "description",
      "type": "text-area"
    },
    {
      "name": "quantity",
      "type": "select",
      "values": {
        "0": "value_3",
        "1": "value_6",
        "2": "value_9"
      }
    },
    {
      "name": "themeColor",
      "type": "color"
    },
    {
      "name": "birthDay",
      "type": "date"
    },
    {
      "name": "arrival",
      "type": "time"
    }
  ]
}
```

This definition must have all the fields and the validations.

And you must have the data to be validated:

```json
{
  "password": "1232",
  "description": "A great fidelity card",
  "quantity": "0"
}
```

## Usage

First, you need to configure the language (m-validate uses [i18n-2](https://www.npmjs.com/package/i18n-2)) passing a config object and the language you want your response.

i18n-2 will create the language files as they are needed, but you can set all translations using [this base file](https://raw.githubusercontent.com/moblets/m-validate/master/spec/locales/en-US.json).

```javascript
var MValidate = require('../m-validate');
// The object is a i18n-2 config object. The second parameter is the locale
var validator = new MValidate({
  locales: [
    'en-US',
    'pt-BR'
  ],
  directory: './locales',
  extension: '.json'
},
 'pt-BR');

var fs = require('fs');

// Get the definition json here
var definitionPath = 'form.json';
var definitionContent = fs.readFileSync(definitionPath, 'utf8');
var definition = JSON.parse(definitionContent);
var definitionFields = definition.fields;

// Assuming the data comes from a post
var content = req.body;

// Response variable will have the result
var response = validator.validate(content, mobletDefinitionFields);
```

The validation response will be an object with two items: a **boolean** and an **object**.

The **boolean** is called **"error"** and will be true if **any of the validations did not pass**.

The **object** is called **"result"** and will have all the **validated fields** as an object. If any validation failed, this object will have the translated validation type and the result, for instance:

```javascript
{
  error: true,
  response: {
    name: {},
    password: {
      required: 'field_is_required',
      'max-length': 'must_be_more_than_chars: 4'
    },
    description: {},
    quantity: {},
    position: {},
    color: {},
    themeColor: {
      type: 'not_a_color'
    },
    birthDay: {},
    arrival: {},
    email: {},
    siteaddress: {
      type: 'not_an_url'
    },
    phone: {
      type: 'not_a_tel'
    },
    cell: {}
  }
}
```

You can check the [tests](https://github.com/moblets/m-validate/tree/develop/spec) to see it in action.

## License

The MIT License (MIT)

Copyright (c) 2016 Moblets

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


text:
/*
###################################################################################################
DOM MANIPULATION CHALLENGE

WE WORKED ON THIS CHALLENGE: Bruno Zatta & Lars Johnson

PLEASE NOTE THAT WE ALSO COMPLETED CHALLENGE 9.3.2: INTRODUCTION TO JQUERY (IN A SEPARATE DIRECTORY)

THIS FILE ADDS JAVASCRIPT TO HOME-PAGE.HTML

###################################################################################################
RELEASE 1
*/

document.getElementById("release-0").className = "done";

/*
###################################################################################################
RELEASE 2
*/

document.getElementById("release-1").style.display = "none";

/*
###################################################################################################
RELEASE 3
*/

document.getElementsByTagName("h1")[0].innerHTML = "I completed Release 2";

/*
###################################################################################################
RELEASE 4
*/

document.getElementById("release-3").style.backgroundColor = "#955251";

/*
###################################################################################################
RELEASE 5
*/

var release4 = document.getElementsByClassName("release-4");
for (var x = 0; x < release4.length; x++) {
    release4[x].style.fontSize = "2em";
}

/*
###################################################################################################
RELEASE 6
*/

var tmpl = document.getElementById('hidden');
document.body.appendChild(tmpl.content.cloneNode(true));

/*
###################################################################################################
REFLECTION

1. What did you learn about the DOM?

    Everything we did with DOM in this challenge was new to me and I really enjoyed it. One thing
    that stood out to me is that when selecting multiple elements they get put into an array so
    they can be worked on individually. Very neat.

2. What are some useful methods to use to manipulate the DOM?

    We used getElementByID, getElementsByClass, and getElementbyTagName which are all useful for
    selecting elements of the DOM. We also used className, style.Display, style.fontSize, style.backgroundColor, and appendChild to manipulate it.

PLEASE NOTE THAT WE ALSO COMPLETED CHALLENGE 9.3.2: INTRODUCTION TO JQUERY (IN A SEPARATE DIRECTORY)

*/

redpajama_set_name: RedPajamaGithub


text:
require 'test_helper'

module Byebug
  #
  # Tests help command without arguments
  #
  class HelpAloneTest < TestCase
    def setup
      super

      enter 'help'
      debug_code(minimal_program)
    end

    def test_shows_summary_for_break_command
      check_output_includes(/Sets breakpoints in the source code/)
    end

    def test_shows_summary_for_catch_command
      check_output_includes(/Handles exception catchpoints/)
    end

    def test_shows_summary_for_condition_command
      check_output_includes(/Sets conditions on breakpoints/)
    end

    def test_shows_summary_for_continue_command
      check_output_includes(
        /Runs until program ends, hits a breakpoint or reaches a line/)
    end

    def test_shows_summary_for_delete_command
      check_output_includes(/Deletes breakpoints/)
    end

    def test_shows_summary_for_disable_command
      check_output_includes(/Disables breakpoints or displays/)
    end

    def test_shows_summary_for_display_command
      check_output_includes(
        /Evaluates expressions every time the debugger stops/)
    end

    def test_shows_summary_for_down_command
      check_output_includes(/Moves to a lower frame in the stack trace/)
    end

    def test_shows_summary_for_edit_command
      check_output_includes(/Edits source files/)
    end

    def test_shows_summary_for_enable_command
      check_output_includes(/Enables breakpoints or displays/)
    end

    def test_shows_summary_for_ps_command
      check_output_includes(
        /Evaluates an expression and prettyprints & sort the result/)
    end

    def test_shows_summary_for_finish_command
      check_output_includes(/Runs the program until frame returns/)
    end

    def test_shows_summary_for_frame_command
      check_output_includes(/Moves to a frame in the call stack/)
    end

    def test_shows_summary_for_help_command
      check_output_includes(/Helps you using byebug/)
    end

    def test_shows_summary_for_history_command
      check_output_includes(/Shows byebug's history of commands/)
    end

    def test_shows_summary_for_info_command
      check_output_includes(
        /Shows several informations about the program being debugged/)
    end

    def test_shows_summary_for_interrupt_command
      check_output_includes(/Interrupts the program/)
    end

    def test_shows_summary_for_irb_command
      check_output_includes(/Starts an IRB session/)
    end

    def test_shows_summary_for_kill_command
      check_output_includes(/Sends a signal to the current process/)
    end

    def test_shows_summary_for_list_command
      check_output_includes(/Lists lines of source code/)
    end

    def test_shows_summary_for_method_command
      check_output_includes(/Shows methods of an object, class or module/)
    end

    def test_shows_summary_for_next_command
      check_output_includes(/Runs one or more lines of code/)
    end

    def test_shows_summary_for_pry_command
      check_output_includes(/Starts a Pry session/)
    end

    def test_shows_summary_for_quit_command
      check_output_includes(/Exits byebug/)
    end

    def test_shows_summary_for_restart_command
      check_output_includes(/Restarts the debugged program/)
    end

    def test_shows_summary_for_save_command
      check_output_includes(/Saves current byebug session to a file/)
    end

    def test_shows_summary_for_set_command
      check_output_includes(/Modifies byebug settings/)
    end

    def test_shows_summary_for_show_command
      check_output_includes(/Shows byebug settings/)
    end

    def test_shows_summary_for_source_command
      check_output_includes(/Restores a previously saved byebug session/)
    end

    def test_shows_summary_for_step_command
      check_output_includes(/Steps into blocks or methods one or more times/)
    end

    def test_shows_summary_for_thread_command
      check_output_includes(/Commands to manipulate threads/)
    end

    def test_shows_summary_for_tracevar_command
      check_output_includes(/Enables tracing of a global variable/)
    end

    def test_shows_summary_for_undisplay_command
      check_output_includes(
        /Stops displaying all or some expressions when program stops/)
    end

    def test_shows_summary_for_untrace_command
      check_output_includes(/Stops tracing a global variable/)
    end

    def test_shows_summary_for_up_command
      check_output_includes(/Moves to a higher frame in the stack trace/)
    end

    def test_shows_summary_for_var_command
      check_output_includes(/Shows variables and its values/)
    end

    def test_shows_summary_for_where_command
      check_output_includes(/Displays the backtrace/)
    end
  end

  #
  # Tests help command with arguments
  #
  class HelpWithArgsTest < TestCase
    def test_help_help_shows_help_for_help_command_itself
      with_setting :width, 50 do
        enter 'help help'
        debug_code(minimal_program)

        expected_output = split_lines <<-TXT

          h[elp][ <cmd>[ <subcmd>]]

          help                -- prints a summary of all commands
          help <cmd>          -- prints help on command <cmd>
          help <cmd> <subcmd> -- prints help on <cmd>'s subcommand <subcmd>

        TXT

        check_output_includes(*expected_output)
      end
    end

    def test_help_with_specific_command_shows_help_for_it
      enter 'help break'
      debug_code(minimal_program)

      expected_output = split_lines <<-TXT
        b[reak] [file:]line [if expr]
        b[reak] [module::...]class(.|#)method [if expr]

        Sets breakpoints in the source code
      TXT

      check_output_includes(*expected_output)
    end

    def test_help_with_undefined_command_shows_an_error
      enter 'help foobar'
      debug_code(minimal_program)

      check_error_includes "Unknown command 'foobar'. Try 'help'"
    end

    def test_help_with_undefined_subcommand_shows_an_error
      enter 'help info foobar'
      debug_code(minimal_program)

      check_error_includes "Unknown command 'info foobar'. Try 'help info'"
    end

    def test_help_with_command_and_subcommand_shows_subcommands_help
      enter 'help info breakpoints'
      debug_code(minimal_program)

      check_output_includes('Status of user settable breakpoints')
    end

    def test_help_set_shows_help_for_set_command_and_includes_settings
      enter 'help set'
      debug_code(minimal_program)

      check_output_includes('Modifies byebug settings',
                            'List of supported settings:')
    end

    def test_help_show_shows_help_for_show_command_and_includes_settings
      enter 'help show'
      debug_code(minimal_program)

      check_output_includes('Shows byebug settings',
                            'List of supported settings:')
    end
  end
end


text:
package com.daedafusion.events.providers;

import com.daedafusion.sf.Provider;

import java.util.Optional;
import java.util.Set;

/**
 * Created by mphilpot on 7/6/14.
 */
public interface EventHandlerProvider extends Provider
{
    // Optional for exchange level providers (rabbitmq)
    Optional<String> getExchange();

    // Topic or Routing
    String getTopic();

    void handle(byte[] bytes);
}


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="false"
        android:color="@color/flat_disabled_text"/>
    <item android:color="@color/flat_normal_text"/>
</selector>


text:
require "rubysl/net/protocol/version"
require "rubysl/net/protocol/protocol"


text:
using System.Collections.Generic;
using MathSite.Db.DataSeeding.StaticData;
using MathSite.Entities;
using Microsoft.Extensions.Logging;

namespace MathSite.Db.DataSeeding.Seeders
{
    public class GroupTypeSeeder : AbstractSeeder<GroupType>
    {
        /// <inheritdoc />
        public GroupTypeSeeder(ILogger logger, MathSiteDbContext context) : base(logger, context)
        {
        }

        /// <inheritdoc />
        public override string SeedingObjectName { get; } = nameof(GroupType);

        /// <inheritdoc />
        protected override void SeedData()
        {
            var userGroupType = CreateGroupType("Users", "Site user", GroupTypeAliases.User);
            var studentGroupType = CreateGroupType("Students", "Site student", GroupTypeAliases.Student);
            var employeeGroupType = CreateGroupType("Employees", "Site teacher or employee", GroupTypeAliases.Employee);

            var groupsTypes = new[]
            {
                userGroupType,
                studentGroupType,
                employeeGroupType
            };

            Context.GroupTypes.AddRange(groupsTypes);
        }

        private static GroupType CreateGroupType(string name, string description, string alias)
        {
            return new GroupType
            {
                Name = name,
                Description = description,
                Alias = alias,
                Groups = new List<Group>()
            };
        }
    }
}


text:
SIP-WebRTC
================

This is a Rails application built on top of the Devise authentication framework. This application is a proof of concept that demonstrates how you can take incoming calls over SIP or WeRTC and forward them to a WebRTC client.

The application handles user managment and mainipulates Twilio APIs but does not handle any call media.


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width initial-scale=1" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Recursos sobre SVG</title>
    <meta name="description" content="Un blog sobre SVG · CSS3 · HTML5">
    <meta name="generator" content="Jekyll v3.8.5">
    <link rel="stylesheet" href="/blog/css/styles.css">
    <link rel="canonical" href="http://jorgeatgu.com/blog/recursos-sobre-svg/">
    <link href="https://fonts.googleapis.com/css?family=IBM+Plex+Serif:400,500|Rubik:400,500" rel="stylesheet">

            WEB
            BLOG
            CATEGORIAS
            RSS

            GitHub
            Twitter
            Carto
            CodePen

Recursos sobre SVG

            <time datetime="2014-09-23 00:00:00 +0200">
                El
                23 de

                septiembre

                de
                2014
            </time>

        Archivado en:

            SVG

El sábado me llego a través de twitter un enlace a un repositorio de GitHub llamado Awesome SVG, una gran recopilación con un montón de información sobre SVG.

No hace mucho Chris Coyier publicaba algo similar en CSS-Tricks.

Lo bueno que tiene Awesome SVG es que al estar en GitHub podemos colaborar con la lista, yo ya he mandado un par de pull-requets con un montón de enlaces que tengo guardados en favoritos. Así que si tenéis algún link interesante sobre SVG y no esta en la lista colaborad con ella.

La idea de Awesome SVG es de Willian Justen

        SCALABLE, un libro sobre SVGA lo largo de 15 capítulos, 120 páginas y más de 70 ejemplos vamos a ver todo lo que podemos hacer con SVG.
            Tu pones el precio, disponible desde 0$ para descargar desde LeanPub(PDF, ePUB y MOBI).

    Artículo posterior

    Artículo anterior

Boira por Jorge Aznar

GitHub · Carto · Twitter · CodePen


text:
import xs, {Stream} from '../../src/index';
import * as assert from 'assert';

describe('xs.combine', () => {
  it('should combine AND-style two streams together', (done: any) => {
    const stream1 = xs.periodic(100).take(2);
    const stream2 = xs.periodic(120).take(2);
    const stream = xs.combine(stream1, stream2);
    let expected = [[0,0], [1,0], [1,1]];
    stream.addListener({
      next: (x) => {
        const e = expected.shift();
        if (e) {
          assert.equal(x[0], e[0]);
          assert.equal(x[1], e[1]);
        } else {
          assert.fail('e should be defined');
        }
      },
      error: done,
      complete: () => {
        assert.equal(expected.length, 0);
        done();
      },
    });
  });

  it('should have correct TypeScript signature', (done: any) => {
    const stream1 = xs.create<string>({
      start: listener => {},
      stop: () => {}
    });

    const stream2 = xs.create<string>({
      start: listener => {},
      stop: () => {}
    });

    const combined: Stream<[string, string]> = xs.combine(stream1, stream2);
    done();
  });

  it('should complete only when all member streams have completed', (done: any) => {
    const stream1 = xs.periodic(30).take(1);
    const stream2 = xs.periodic(50).take(4);
    const stream = xs.combine(stream1, stream2).map(arr => arr.join(''))
    let expected = ['00', '01', '02', '03'];
    stream.addListener({
      next: (x) => {
        assert.equal(x, expected.shift());
      },
      error: done,
      complete: () => {
        assert.equal(expected.length, 0);
        done();
      },
    });
  });

  it('should emit an empty array if combining zero streams', (done: any) => {
    const stream = xs.combine();

    stream.addListener({
      next: (a) => {
        assert.equal(Array.isArray(a), true);
        assert.equal(a.length, 0);
      },
      error: done,
      complete: () => {
        done();
      },
    });
  });

  it('should just wrap the value if combining one stream', (done: any) => {
    const source = xs.periodic(100).take(3);
    const stream = xs.combine(source);
    let expected = [[0], [1], [2]];

    stream.addListener({
      next: (x) => {
        const e = expected.shift();
        if (e) {
          assert.equal(x[0], e[0]);
        } else {
          assert.fail('e should be defined');
        }
      },
      error: done,
      complete: () => {
        assert.equal(expected.length, 0);
        done();
      },
    });
  });

  it('should not break future listeners when CombineProducer tears down', (done: any) => {
    //     --0--1-2--|  innerA
    //     ---0---1--|  innerB
    // ----0----1-2--|  outer
    const innerA = xs.create<number>();
    const innerB = xs.create<number>();
    const outer = xs.create<number>();
    const arrayInners: Array<Stream<number>> = [];
    const stream = outer
      .map(x => {
        return xs.combine(...arrayInners)
          .map(combination => `${x}${combination.join('')}`);
      })
      .flatten();
    const expected = ['00'];

    setTimeout(() => {
      arrayInners.push(innerA);
      outer.shamefullySendNext(0);
    }, 100);
    setTimeout(() => {
      innerA.shamefullySendNext(0);
    }, 150);
    setTimeout(() => {
      innerB.shamefullySendNext(0);
    }, 175);
    setTimeout(() => {
      arrayInners.push(innerB);
      outer.shamefullySendNext(1);
      innerA.shamefullySendNext(1);
    }, 200);
    setTimeout(() => {
      innerA.shamefullySendNext(2);
      outer.shamefullySendNext(2);
      innerB.shamefullySendNext(1);
    }, 250);
    setTimeout(() => {
      innerA.shamefullySendComplete();
      innerB.shamefullySendComplete();
      outer.shamefullySendComplete();
    }, 550);

    stream.addListener({
      next: (x: string) => {
        assert.equal(x, expected.shift());
      },
      error: (err: any) => done(err),
      complete: () => {
        assert.equal(expected.length, 0);
        done();
      },
    });
  });

  it('should return a Stream when combining a MemoryStream with a Stream', (done: any) => {
    const input1 = xs.periodic(50).take(4).remember();
    const input2 = xs.periodic(80).take(3);
    const stream: Stream<[number, number]> = xs.combine(input1, input2);
    assert.strictEqual(stream instanceof Stream, true);
    done();
  });

  it('should return a Stream when combining a MemoryStream with a MemoryStream', (done: any) => {
    const input1 = xs.periodic(50).take(4).remember();
    const input2 = xs.periodic(80).take(3).remember();
    const stream: Stream<[number, number]> = xs.combine(input1, input2);
    assert.strictEqual(stream instanceof Stream, true);
    done();
  });
});


text:
<?xml version="1.0" encoding="utf-8"?>
<selector
  xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="false" android:color="?textColorSecondaryInverse" android:state_activated="true" android:alpha="?disabledAlpha" />
    <item android:state_enabled="false" android:color="?textColorSecondary" android:alpha="?disabledAlpha" />
    <item android:color="?textColorSecondaryInverse" android:state_activated="true" />
    <item android:color="?textColorSecondary" />
</selector>


text:
/*
 * smooth_opengl3.c, based on smooth.c, which is (c) by SGI, see below.
 * This program demonstrates smooth shading in a way which is fully
 * OpenGL-3.1-compliant.
 * A smooth shaded polygon is drawn in a 2-D projection.
 */

/*
 * Original copyright notice from smooth.c:
 *
 * License Applicability. Except to the extent portions of this file are
 * made subject to an alternative license as permitted in the SGI Free
 * Software License B, Version 1.1 (the "License"), the contents of this
 * file are subject only to the provisions of the License. You may not use
 * this file except in compliance with the License. You may obtain a copy
 * of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
 * Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
 *
 * http://oss.sgi.com/projects/FreeB
 *
 * Note that, as provided in the License, the Software is distributed on an
 * "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
 * DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
 * CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
 * PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
 *
 * Original Code. The Original Code is: OpenGL Sample Implementation,
 * Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
 * Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc.
 * Copyright in any portions created by third parties is as indicated
 * elsewhere herein. All Rights Reserved.
 *
 * Additional Notice Provisions: The application programming interfaces
 * established by SGI in conjunction with the Original Code are The
 * OpenGL(R) Graphics System: A Specification (Version 1.2.1), released
 * April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version
 * 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X
 * Window System(R) (Version 1.3), released October 19, 1998. This software
 * was created using the OpenGL(R) version 1.2.1 Sample Implementation
 * published by SGI, but has not been independently verified as being
 * compliant with the OpenGL(R) version 1.2.1 Specification.
 *
 */

#include <GL/freeglut.h>
#include <stdlib.h>
#include <stdio.h>
#include <stddef.h>
#include <string.h>

/* report GL errors, if any, to stderr */
void checkError(const char *functionName)
{
   GLenum error;
   while (( error = glGetError() ) != GL_NO_ERROR) {
      fprintf (stderr, "GL error 0x%X detected in %s\n", error, functionName);
   }
}

/* extension #defines, types and entries, avoiding a dependency on additional
   libraries like GLEW or the GL/glext.h header */
#ifndef GL_ARRAY_BUFFER
#define GL_ARRAY_BUFFER 0x8892
#endif

#ifndef GL_STATIC_DRAW
#define GL_STATIC_DRAW 0x88E4
#endif

#ifndef GL_FRAGMENT_SHADER
#define GL_FRAGMENT_SHADER 0x8B30
#endif

#ifndef GL_VERTEX_SHADER
#define GL_VERTEX_SHADER 0x8B31
#endif

#ifndef GL_SHADING_LANGUAGE_VERSION
#define GL_SHADING_LANGUAGE_VERSION 0x8B8C
#endif

#ifndef GL_COMPILE_STATUS
#define GL_COMPILE_STATUS 0x8B81
#endif

#ifndef GL_LINK_STATUS
#define GL_LINK_STATUS 0x8B82
#endif

#ifndef GL_INFO_LOG_LENGTH
#define GL_INFO_LOG_LENGTH 0x8B84
#endif

typedef ptrdiff_t ourGLsizeiptr;
typedef char ourGLchar;

#ifndef APIENTRY
#define APIENTRY
#endif

#ifndef GL_ARB_vertex_array_object
typedef void (APIENTRY *PFNGLGENVERTEXARRAYSPROC) (GLsizei n, GLuint *arrays);
typedef void (APIENTRY *PFNGLBINDVERTEXARRAYPROC) (GLuint array);
#endif
#ifndef GL_VERSION_1_5
typedef void (APIENTRY *PFNGLGENBUFFERSPROC) (GLsizei n, GLuint *buffers);
typedef void (APIENTRY *PFNGLBINDBUFFERPROC) (GLenum target, GLuint buffer);
typedef void (APIENTRY *PFNGLBUFFERDATAPROC) (GLenum target, ourGLsizeiptr size, const GLvoid *data, GLenum usage);
#endif
#ifndef GL_VERSION_2_0
typedef GLuint (APIENTRY *PFNGLCREATESHADERPROC) (GLenum type);
typedef void (APIENTRY *PFNGLSHADERSOURCEPROC) (GLuint shader, GLsizei count, const ourGLchar **string, const GLint *length);
typedef void (APIENTRY *PFNGLCOMPILESHADERPROC) (GLuint shader);
typedef GLuint (APIENTRY *PFNGLCREATEPROGRAMPROC) (void);
typedef void (APIENTRY *PFNGLATTACHSHADERPROC) (GLuint program, GLuint shader);
typedef void (APIENTRY *PFNGLLINKPROGRAMPROC) (GLuint program);
typedef void (APIENTRY *PFNGLUSEPROGRAMPROC) (GLuint program);
typedef void (APIENTRY *PFNGLGETSHADERIVPROC) (GLuint shader, GLenum pname, GLint *params);
typedef void (APIENTRY *PFNGLGETSHADERINFOLOGPROC) (GLuint shader, GLsizei bufSize, GLsizei *length, ourGLchar *infoLog);
typedef void (APIENTRY *PFNGLGETPROGRAMIVPROC) (GLenum target, GLenum pname, GLint *params);
typedef void (APIENTRY *PFNGLGETPROGRAMINFOLOGPROC) (GLuint program, GLsizei bufSize, GLsizei *length, ourGLchar *infoLog);
typedef GLint (APIENTRY *PFNGLGETATTRIBLOCATIONPROC) (GLuint program, const ourGLchar *name);
typedef void (APIENTRY *PFNGLVERTEXATTRIBPOINTERPROC) (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid *pointer);
typedef void (APIENTRY *PFNGLENABLEVERTEXATTRIBARRAYPROC) (GLuint index);
typedef GLint (APIENTRY *PFNGLGETUNIFORMLOCATIONPROC) (GLuint program, const ourGLchar *name);
typedef void (APIENTRY *PFNGLUNIFORMMATRIX4FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
#endif

PFNGLGENVERTEXARRAYSPROC gl_GenVertexArrays;
PFNGLBINDVERTEXARRAYPROC gl_BindVertexArray;
PFNGLGENBUFFERSPROC gl_GenBuffers;
PFNGLBINDBUFFERPROC gl_BindBuffer;
PFNGLBUFFERDATAPROC gl_BufferData;
PFNGLCREATESHADERPROC gl_CreateShader;
PFNGLSHADERSOURCEPROC gl_ShaderSource;
PFNGLCOMPILESHADERPROC gl_CompileShader;
PFNGLCREATEPROGRAMPROC gl_CreateProgram;
PFNGLATTACHSHADERPROC gl_AttachShader;
PFNGLLINKPROGRAMPROC gl_LinkProgram;
PFNGLUSEPROGRAMPROC gl_UseProgram;
PFNGLGETSHADERIVPROC gl_GetShaderiv;
PFNGLGETSHADERINFOLOGPROC gl_GetShaderInfoLog;
PFNGLGETPROGRAMIVPROC gl_GetProgramiv;
PFNGLGETPROGRAMINFOLOGPROC gl_GetProgramInfoLog;
PFNGLGETATTRIBLOCATIONPROC gl_GetAttribLocation;
PFNGLVERTEXATTRIBPOINTERPROC gl_VertexAttribPointer;
PFNGLENABLEVERTEXATTRIBARRAYPROC gl_EnableVertexAttribArray;
PFNGLGETUNIFORMLOCATIONPROC gl_GetUniformLocation;
PFNGLUNIFORMMATRIX4FVPROC gl_UniformMatrix4fv;

void initExtensionEntries(void)
{
   gl_GenVertexArrays = (PFNGLGENVERTEXARRAYSPROC) glutGetProcAddress ("glGenVertexArrays");
   gl_BindVertexArray = (PFNGLBINDVERTEXARRAYPROC) glutGetProcAddress ("glBindVertexArray");
   if (!gl_GenVertexArrays || !gl_BindVertexArray)
   {
       fprintf (stderr, "glGenVertexArrays or glBindVertexArray not found");
       exit(1);
   }
   gl_GenBuffers = (PFNGLGENBUFFERSPROC) glutGetProcAddress ("glGenBuffers");
   gl_BindBuffer = (PFNGLBINDBUFFERPROC) glutGetProcAddress ("glBindBuffer");
   gl_BufferData = (PFNGLBUFFERDATAPROC) glutGetProcAddress ("glBufferData");
   if (!gl_GenBuffers || !gl_BindBuffer || !gl_BufferData)
   {
       fprintf (stderr, "glGenBuffers, glBindBuffer or glBufferData not found");
       exit(1);
   }
   gl_CreateShader = (PFNGLCREATESHADERPROC) glutGetProcAddress ("glCreateShader");
   gl_ShaderSource = (PFNGLSHADERSOURCEPROC) glutGetProcAddress ("glShaderSource");
   gl_CompileShader = (PFNGLCOMPILESHADERPROC) glutGetProcAddress ("glCompileShader");
   gl_CreateProgram = (PFNGLCREATEPROGRAMPROC) glutGetProcAddress ("glCreateProgram");
   gl_AttachShader = (PFNGLATTACHSHADERPROC) glutGetProcAddress ("glAttachShader");
   gl_LinkProgram = (PFNGLLINKPROGRAMPROC) glutGetProcAddress ("glLinkProgram");
   gl_UseProgram = (PFNGLUSEPROGRAMPROC) glutGetProcAddress ("glUseProgram");
   gl_GetShaderiv = (PFNGLGETSHADERIVPROC) glutGetProcAddress ("glGetShaderiv");
   gl_GetShaderInfoLog = (PFNGLGETSHADERINFOLOGPROC) glutGetProcAddress ("glGetShaderInfoLog");
   gl_GetProgramiv = (PFNGLGETPROGRAMIVPROC) glutGetProcAddress ("glGetProgramiv");
   gl_GetProgramInfoLog = (PFNGLGETPROGRAMINFOLOGPROC) glutGetProcAddress ("glGetProgramInfoLog");
   gl_GetAttribLocation = (PFNGLGETATTRIBLOCATIONPROC) glutGetProcAddress ("glGetAttribLocation");
   gl_VertexAttribPointer = (PFNGLVERTEXATTRIBPOINTERPROC) glutGetProcAddress ("glVertexAttribPointer");
   gl_EnableVertexAttribArray = (PFNGLENABLEVERTEXATTRIBARRAYPROC) glutGetProcAddress ("glEnableVertexAttribArray");
   gl_GetUniformLocation = (PFNGLGETUNIFORMLOCATIONPROC) glutGetProcAddress ("glGetUniformLocation");
   gl_UniformMatrix4fv = (PFNGLUNIFORMMATRIX4FVPROC) glutGetProcAddress ("glUniformMatrix4fv");
   if (!gl_CreateShader || !gl_ShaderSource || !gl_CompileShader || !gl_CreateProgram || !gl_AttachShader || !gl_LinkProgram || !gl_UseProgram || !gl_GetShaderiv || !gl_GetShaderInfoLog || !gl_GetProgramiv || !gl_GetProgramInfoLog || !gl_GetAttribLocation || !gl_VertexAttribPointer || !gl_EnableVertexAttribArray || !gl_GetUniformLocation || !gl_UniformMatrix4fv)
   {
       fprintf (stderr, "glCreateShader, glShaderSource, glCompileShader, glCreateProgram, glAttachShader, glLinkProgram, glUseProgram, glGetShaderiv, glGetShaderInfoLog, glGetProgramiv, glGetProgramInfoLog, glGetAttribLocation, glVertexAttribPointer, glEnableVertexAttribArray, glGetUniformLocation or glUniformMatrix4fv not found");
       exit(1);
   }
}

/* vertex array data for a colored 2D triangle, consisting of RGB color values
   and XY coordinates */
const GLfloat varray[] = {
   1.0f, 0.0f, 0.0f, /* red */
   5.0f, 5.0f,       /* lower left */

   0.0f, 1.0f, 0.0f, /* green */
   25.0f, 5.0f,      /* lower right */

   0.0f, 0.0f, 1.0f, /* blue */
   5.0f, 25.0f       /* upper left */
};

/* ISO C somehow enforces this silly use of 'enum' for compile-time constants */
enum {
  numColorComponents = 3,
  numVertexComponents = 2,
  stride = sizeof(GLfloat) * (numColorComponents + numVertexComponents),
  numElements = sizeof(varray) / stride
};

/* the name of the vertex buffer object */
GLuint vertexBufferName;
GLuint vertexArrayName;

void initBuffer(void)
{
   /* Need to setup a vertex array as otherwise invalid operation errors can
    * occur when accessing vertex buffer (OpenGL 3.3 has no default zero named
    * vertex array)
    */
   gl_GenVertexArrays(1, &vertexArrayName);
   gl_BindVertexArray(vertexArrayName);

   gl_GenBuffers (1, &vertexBufferName);
   gl_BindBuffer (GL_ARRAY_BUFFER, vertexBufferName);
   gl_BufferData (GL_ARRAY_BUFFER, sizeof(varray), varray, GL_STATIC_DRAW);
   checkError ("initBuffer");
}

const ourGLchar *vertexShaderSource[] = {
   "#version 140\n",
   "uniform mat4 fg_ProjectionMatrix;\n",
   "in vec4 fg_Color;\n",
   "in vec4 fg_Vertex;\n",
   "smooth out vec4 fg_SmoothColor;\n",
   "void main()\n",
   "{\n",
   "   fg_SmoothColor = fg_Color;\n",
   "   gl_Position = fg_ProjectionMatrix * fg_Vertex;\n",
   "}\n"
};

const ourGLchar *fragmentShaderSource[] = {
   "#version 140\n",
   "smooth in vec4 fg_SmoothColor;\n",
   "out vec4 fg_FragColor;\n",
   "void main(void)\n",
   "{\n",
   "   fg_FragColor = fg_SmoothColor;\n",
   "}\n"
};

void compileAndCheck(GLuint shader)
{
   GLint status;
   gl_CompileShader (shader);
   gl_GetShaderiv (shader, GL_COMPILE_STATUS, &status);
   if (status == GL_FALSE) {
     GLint infoLogLength;
     ourGLchar *infoLog;
     gl_GetShaderiv (shader, GL_INFO_LOG_LENGTH, &infoLogLength);
     infoLog = (ourGLchar*) malloc (infoLogLength);
     gl_GetShaderInfoLog (shader, infoLogLength, NULL, infoLog);
     fprintf (stderr, "compile log: %s\n", infoLog);
     free (infoLog);
   }
}

GLuint compileShaderSource(GLenum type, GLsizei count, const ourGLchar **string)
{
   GLuint shader = gl_CreateShader (type);
   gl_ShaderSource (shader, count, string, NULL);
   compileAndCheck (shader);
   return shader;
}

void linkAndCheck(GLuint program)
{
   GLint status;
   gl_LinkProgram (program);
   gl_GetProgramiv (program, GL_LINK_STATUS, &status);
   if (status == GL_FALSE) {
     GLint infoLogLength;
     ourGLchar *infoLog;
     gl_GetProgramiv (program, GL_INFO_LOG_LENGTH, &infoLogLength);
     infoLog = (ourGLchar*) malloc (infoLogLength);
     gl_GetProgramInfoLog (program, infoLogLength, NULL, infoLog);
     fprintf (stderr, "link log: %s\n", infoLog);
     free (infoLog);
   }
}

GLuint createProgram(GLuint vertexShader, GLuint fragmentShader)
{
   GLuint program = gl_CreateProgram ();
   if (vertexShader != 0) {
      gl_AttachShader (program, vertexShader);
   }
   if (fragmentShader != 0) {
      gl_AttachShader (program, fragmentShader);
   }
   linkAndCheck (program);
   return program;
}

GLuint fgProjectionMatrixIndex;
GLuint fgColorIndex;
GLuint fgVertexIndex;

void initShader(void)
{
   const GLsizei vertexShaderLines = sizeof(vertexShaderSource) / sizeof(ourGLchar*);
   GLuint vertexShader =
     compileShaderSource (GL_VERTEX_SHADER, vertexShaderLines, vertexShaderSource);

   const GLsizei fragmentShaderLines = sizeof(fragmentShaderSource) / sizeof(ourGLchar*);
   GLuint fragmentShader =
     compileShaderSource (GL_FRAGMENT_SHADER, fragmentShaderLines, fragmentShaderSource);

   GLuint program = createProgram (vertexShader, fragmentShader);

   gl_UseProgram (program);

   fgProjectionMatrixIndex = gl_GetUniformLocation(program, "fg_ProjectionMatrix");

   fgColorIndex = gl_GetAttribLocation(program, "fg_Color");
   gl_EnableVertexAttribArray (fgColorIndex);

   fgVertexIndex = gl_GetAttribLocation(program, "fg_Vertex");
   gl_EnableVertexAttribArray (fgVertexIndex);

   checkError ("initShader");
}

void initRendering(void)
{
   glClearColor (0.0, 0.0, 0.0, 0.0);
   checkError ("initRendering");
}

void init(void)
{
   initExtensionEntries ();
   initBuffer ();
   initShader ();
   initRendering ();
}

void dumpInfo(void)
{
   printf ("Vendor: %s\n", glGetString (GL_VENDOR));
   printf ("Renderer: %s\n", glGetString (GL_RENDERER));
   printf ("Version: %s\n", glGetString (GL_VERSION));
   printf ("GLSL: %s\n", glGetString (GL_SHADING_LANGUAGE_VERSION));
   checkError ("dumpInfo");
}

const GLvoid *bufferObjectPtr (GLsizei index)
{
   return (const GLvoid *) (((char *) NULL) + index);
}

GLfloat projectionMatrix[16];

void triangle(void)
{
   gl_UniformMatrix4fv (fgProjectionMatrixIndex, 1, GL_FALSE, projectionMatrix);

   gl_BindBuffer (GL_ARRAY_BUFFER, vertexBufferName);
   gl_VertexAttribPointer (fgColorIndex, numColorComponents, GL_FLOAT, GL_FALSE,
                           stride, bufferObjectPtr (0));
   gl_VertexAttribPointer (fgVertexIndex, numVertexComponents, GL_FLOAT, GL_FALSE,
                           stride, bufferObjectPtr (sizeof(GLfloat) * numColorComponents));
   glDrawArrays(GL_TRIANGLES, 0, numElements);
   checkError ("triangle");
}

void display(void)
{
   glClear (GL_COLOR_BUFFER_BIT);
   triangle ();
   glFlush ();
   checkError ("display");
}

void loadOrthof(GLfloat *m, GLfloat l, GLfloat r, GLfloat b, GLfloat t,
                GLfloat n, GLfloat f)
{
   m[ 0] = 2.0f / (r - l);
   m[ 1] = 0.0f;
   m[ 2] = 0.0f;
   m[ 3] = 0.0f;

   m[ 4] = 0.0f;
   m[ 5] = 2.0f / (t - b);
   m[ 6] = 0.0f;
   m[ 7] = 0.0f;

   m[ 8] = 0.0f;
   m[ 9] = 0.0f;
   m[10] = -2.0f / (f - n);
   m[11] = 0.0f;

   m[12] = -(r + l) / (r - l);
   m[13] = -(t + b) / (t - b);
   m[14] = -(f + n) / (f - n);
   m[15] = 1.0f;
}

void loadOrtho2Df(GLfloat *m, GLfloat l, GLfloat r, GLfloat b, GLfloat t)
{
   loadOrthof (m, l, r, b, t, -1.0f, 1.0f);
}

void reshape (int w, int h)
{
   glViewport (0, 0, (GLsizei) w, (GLsizei) h);
   if (w <= h) {
      loadOrtho2Df (projectionMatrix, 0.0f, 30.0f, 0.0f, 30.0f * (GLfloat) h/(GLfloat) w);
   } else {
      loadOrtho2Df (projectionMatrix, 0.0f, 30.0f * (GLfloat) w/(GLfloat) h, 0.0f, 30.0f);
   }
   checkError ("reshape");
}

void keyboard(unsigned char key, int x, int y)
{
   switch (key) {
      case 27:
         exit(0);
         break;
   }
}

void samplemenu(int menuID)
{}

int main(int argc, char** argv)
{
   int menuA;
   glutInit(&argc, argv);
   glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);
   /* add command line argument "classic" for a pre-3.x context */
   if ((argc != 2) || (strcmp (argv[1], "classic") != 0)) {
      glutInitContextVersion (3, 1);
      glutInitContextFlags (GLUT_FORWARD_COMPATIBLE | GLUT_DEBUG);
   }
   glutInitWindowSize (500, 500);
   glutInitWindowPosition (100, 100);
   glutCreateWindow (argv[0]);
   dumpInfo ();
   init ();
   glutDisplayFunc(display);
   glutReshapeFunc(reshape);
   glutKeyboardFunc (keyboard);

   /* Add a menu. They have their own context and should thus work with forward compatible main windows too. */
   menuA = glutCreateMenu(samplemenu);
   glutAddMenuEntry("Sub menu A1 (01)",1);
   glutAddMenuEntry("Sub menu A2 (02)",2);
   glutAddMenuEntry("Sub menu A3 (03)",3);
   glutSetMenu(menuA);
   glutAttachMenu(GLUT_RIGHT_BUTTON);

   glutMainLoop();
   return 0;
}


text:
#ifndef __vtkHierarchicalBoxDataSetInternal_h
#define __vtkHierarchicalBoxDataSetInternal_h

#include "vtkHierarchicalDataSetInternal.h"
#include "vtkAMRBox.h"

struct vtkHierarchicalBoxDataSetInternal
{
  vtkstd::vector<int> RefinementRatios;
};

#endif


text:
var compiler = require('weex-template-compiler')
var transpile = require('vue-template-es2015-compiler')
// var loaderUtils = require('loader-utils')
var beautify = require('js-beautify').js_beautify
// var normalize = require('./normalize')
// var hotReloadAPIPath = normalize.dep('vue-hot-reload-api')

// // vue compiler module for using transforming `<tag>:<attribute>` to `require`
// var defaultTransformToRequire = {
//   img: 'src'
// }
// var transformToRequire = defaultTransformToRequire
// var defaultCompileOptions = {
//   modules: [{
//     postTransformNode (el) {
//       for (var tag in transformToRequire) {
//         if (el.tag === tag && el.attrs) {
//           var attributes = transformToRequire[tag]
//           if (typeof attributes === 'string') {
//             el.attrs.some(attr => rewrite(attr, attributes))
//           } else if (Array.isArray(attributes)) {
//             attributes.forEach(item => el.attrs.some(attr => rewrite(attr, item)))
//           }
//         }
//       }
//     }
//   }]
// }

// function rewrite (attr, name) {
//   if (attr.name === name) {
//     var value = attr.value
//     var isStatic = value.charAt(0) === '"' && value.charAt(value.length - 1) === '"'
//     if (!isStatic) {
//       return
//     }
//     var firstChar = value.charAt(1)
//     if (firstChar === '.' || firstChar === '~') {
//       if (firstChar === '~') {
//         value = '"' + value.slice(2)
//       }
//       attr.value = `require(${value})`
//     }
//     return true
//   }
// }

module.exports = function (html) {
  this.cacheable()
  var isProduction = this.minimize || process.env.NODE_ENV === 'production'
  // var query = loaderUtils.parseQuery(this.query)
  // var isServer = this.options.target === 'node'
  // var isServer = false
  var vueOptions = this.options.__vueOptions__
  // if (vueOptions.transformToRequire) {
  //   transformToRequire = Object.assign(
  //     {},
  //     defaultTransformToRequire,
  //     vueOptions.transformToRequire
  //   )
  // }
  // var compiled = compiler.compile(html, Object.assign({
  //   preserveWhitespace: vueOptions.preserveWhitespace
  // }, defaultCompileOptions))
  var compiled = compiler.compile(html)
  var code
  if (compiled.errors.length) {
    var self = this
    compiled.errors.forEach(function (err) {
      self.emitError('template syntax error ' + err)
    })
    code = 'module.exports={render:function(){},staticRenderFns:[]}'
  } else {
    var bubleOptions = vueOptions.buble
    code = transpile('module.exports={' +
      'render:' + toFunction(compiled.render) + ',' +
      'staticRenderFns: [' + compiled.staticRenderFns.map(toFunction).join(',') + ']' +
    '}', bubleOptions)
    // mark with stripped (this enables Vue to use correct runtime proxy detection)
    if (!isProduction && (
      !bubleOptions ||
      !bubleOptions.transforms ||
      bubleOptions.transforms.stripWith !== false
    )) {
      code += `\nmodule.exports.render._withStripped = true`
    }
  }
  // hot-reload
  // if (!isServer &&
  //     !this.minimize &&
  //     process.env.NODE_ENV !== 'production') {
  //   code +=
  //     '\nif (module.hot) {\n' +
  //     '  module.hot.accept()\n' +
  //     '  if (module.hot.data) {\n' +
  //     '     require("' + hotReloadAPIPath + '").rerender("' + query.id + '", module.exports)\n' +
  //     '  }\n' +
  //     '}'
  // }
  return code
}

function toFunction (code) {
  return 'function (){' + beautify(code, { indent_size: 2 }) + '}'
}


text:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping default-lazy="false">
<!--
    Created by the Middlegen Hibernate plugin 2.1

    http://boss.bekk.no/boss/middlegen/
    http://www.hibernate.org/
-->

<class
    name="gov.nih.nci.security.dao.hibernate.RolePrivilege"
    table="CSM_ROLE_PRIVILEGE"
>

    <id
        name="rolePrivilegeId"
        type="java.lang.Long"
        column="ROLE_PRIVILEGE_ID"
        unsaved-value="0"
    >
        <generator class="native">
		 <param name="sequence">CSM_ROLE_PRIV_ROLE_PRIVILE_SEQ</param>
	 </generator>
    </id>

    <!-- Associations -->

    <!-- bi-directional many-to-one association to Privilege -->
    <many-to-one
        name="privilege"
        class="gov.nih.nci.security.authorization.domainobjects.Privilege"
        not-null="true"
    >
        <column name="PRIVILEGE_ID" />
    </many-to-one>
    <!-- bi-directional many-to-one association to Role -->
    <many-to-one
        name="role"
        class="gov.nih.nci.security.authorization.domainobjects.Role"
        not-null="true"
    >
        <column name="ROLE_ID" />
    </many-to-one>

</class>
</hibernate-mapping>


text:
clifford.Layout
===============

.. currentmodule:: clifford

.. autoclass:: Layout
  :members:
  :member-order: bysource
  :undoc-members:


text:
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using OfficeOpenXml.Style;
using System.Globalization;
namespace OfficeOpenXml.Drawing.Chart
{
    /// <summary>
    /// Position of the axis.
    /// </summary>
    public enum eAxisPosition
    {
        Left = 0,
        Bottom = 1,
        Right = 2,
        Top = 3
    }
    /// <summary>
    /// Position of the Y-Axis
    /// </summary>
    public enum eYAxisPosition
    {
        Left = 0,
        Right = 2,
    }
    /// <summary>
    /// Position of the X-Axis
    /// </summary>
    public enum eXAxisPosition
    {
        Bottom = 1,
        Top = 3
    }
    /// <summary>
    /// Axis orientaion
    /// </summary>
    public enum eAxisOrientation
    {
        MaxMin,
        MinMax
    }
    /// <summary>
    /// How the axis are crossed
    /// </summary>
    public enum eCrossBetween
    {
        /// <summary>
        /// Specifies the value axis shall cross the category axis between data markers
        /// </summary>
        Between,
        /// <summary>
        /// Specifies the value axis shall cross the category axis at the midpoint of a category.
        /// </summary>
        MidCat
    }
    /// <summary>
    /// Where the axis cross.
    /// </summary>
    public enum eCrosses
    {
        /// <summary>
        /// (Axis Crosses at Zero) The category axis crosses at the zero point of the valueaxis (if possible), or the minimum value (if theminimum is greater than zero) or the maximum (if the maximum is less than zero).
        /// </summary>
        AutoZero,
        /// <summary>
        /// The axis crosses at the maximum value
        /// </summary>
        Max,
        /// <summary>
        /// (Axis crosses at the minimum value of the chart.
        /// </summary>
        Min
    }
    /// <summary>
    /// Tickmarks
    /// </summary>
    public enum eAxisTickMark
    {
        /// <summary>
        /// Specifies the tick marks shall cross the axis.
        /// </summary>
        Cross,
        /// <summary>
        /// Specifies the tick marks shall be inside the plot area.
        /// </summary>
        In,
        /// <summary>
        /// Specifies there shall be no tick marks.
        /// </summary>
        None,
        /// <summary>
        /// Specifies the tick marks shall be outside the plot area.
        /// </summary>
        Out
    }
    /// <summary>
    /// An axis for a chart
    /// </summary>
    public sealed class ExcelChartAxis : XmlHelper
    {
        /// <summary>
        /// Type of axis
        /// </summary>
        internal enum eAxisType
        {
            /// <summary>
            /// Value axis
            /// </summary>
            Val,
            /// <summary>
            /// Category axis
            /// </summary>
            Cat,
            /// <summary>
            /// Date axis
            /// </summary>
            Date
        }
        internal ExcelChartAxis(XmlNamespaceManager nameSpaceManager, XmlNode topNode) :
            base(nameSpaceManager, topNode)
        {
            SchemaNodeOrder = new string[] { "axId", "scaling", "logBase", "orientation", "max", "min", "delete", "axPos", "majorGridlines", "title", "numFmt", "majorTickMark", "minorTickMark", "tickLblPos", "spPr", "txPr", "crossAx", "crossesAt", "crosses", "crossBetween", "auto", "lblOffset", "majorUnit", "minorUnit", "dispUnits", "spPr", "txPr" };
        }
        internal string Id
        {
            get
            {
                return GetXmlNodeString("c:axId/@val");
            }
        }
        const string _majorTickMark = "c:majorTickMark/@val";
        /// <summary>
        /// majorTickMark
        /// This element specifies the major tick marks for the axis.
        /// </summary>
        public eAxisTickMark MajorTickMark
        {
            get
            {
                return (eAxisTickMark)Enum.Parse( typeof( eAxisTickMark ), GetXmlNodeString( _majorTickMark ) );
            }
            set
            {
                SetXmlNodeString( _majorTickMark, value.ToString().ToLower() );
            }
        }

        const string _minorTickMark = "c:minorTickMark/@val";
        /// <summary>
        /// minorTickMark
        /// This element specifies the minor tick marks for the axis.
        /// </summary>
        public eAxisTickMark MinorTickMark
        {
            get
            {
                return (eAxisTickMark)Enum.Parse(typeof(eAxisTickMark), GetXmlNodeString( _minorTickMark ) );
            }
            set
            {
                SetXmlNodeString(_minorTickMark, value.ToString().ToLower());
            }
        }
         /// <summary>
        /// Type of axis
        /// </summary>
        internal eAxisType AxisType
        {
            get
            {
                try
                {
                    return (eAxisType)Enum.Parse(typeof(eAxisType), TopNode.LocalName.Substring(0,3), true);
                }
                catch
                {
                    return eAxisType.Val;
                }
            }
        }
        private string AXIS_POSITION_PATH = "c:axPos/@val";
        /// <summary>
        /// Where the axis is located
        /// </summary>
        public eAxisPosition AxisPosition
        {
            get
            {
                switch(GetXmlNodeString(AXIS_POSITION_PATH))
                {
                    case "b":
                        return eAxisPosition.Bottom;
                    case "r":
                        return eAxisPosition.Right;
                    case "t":
                        return eAxisPosition.Top;
                    default:
                        return eAxisPosition.Left;
                }
            }
            internal set
            {
                SetXmlNodeString(AXIS_POSITION_PATH, value.ToString().ToLower().Substring(0,1));
            }
        }
        const string _crossesPath = "c:crosses/@val";
        /// <summary>
        /// Where the axis cross
        /// </summary>
        public eCrosses Crosses
        {
            get
            {
                return (eCrosses)Enum.Parse(typeof(eCrosses), GetXmlNodeString(_crossesPath), true);
            }
            set
            {
                var v = value.ToString();
                v = v.Substring(1).ToLower() + v.Substring(1, v.Length - 1);
                SetXmlNodeString(_crossesPath, v);
            }

        }
        const string _crossBetweenPath = "c:crossBetween/@val";
        /// <summary>
        /// How the axis are crossed
        /// </summary>
        public eCrossBetween CrossBetween
        {
            get
            {
                return (eCrossBetween)Enum.Parse(typeof(eCrossBetween), GetXmlNodeString(_crossBetweenPath), true);
            }
            set
            {
                var v = value.ToString();
                v = v.Substring(1).ToLower() + v.Substring(1, v.Length - 1);
                SetXmlNodeString(_crossBetweenPath, v);
            }

        }
        const string _crossesAtPath = "c:crossesAt/@val";
        /// <summary>
        /// The value where the axis cross.
        /// Null is automatic
        /// </summary>
        public double? CrossesAt
        {
            get
            {
                return GetXmlNodeDoubleNull(_crossesAtPath);
            }
            set
            {
                if (value == null)
                {
                    DeleteNode(_crossesAtPath);
                }
                else
                {
                    SetXmlNodeString(_crossesAtPath, ((double)value).ToString(CultureInfo.InvariantCulture));
                }
            }
        }
        const string _formatPath = "c:numFmt/@formatCode";
        /// <summary>
        /// Numberformat
        /// </summary>
        public string Format
        {
            get
            {
                return GetXmlNodeString(_formatPath);
            }
            set
            {
                SetXmlNodeString(_formatPath,value);
            }
        }

        const string _lblPos = "c:tickLblPos/@val";
        /// <summary>
        /// Position of the labels
        /// </summary>
        public eTickLabelPosition LabelPosition
        {
            get
            {
                return (eTickLabelPosition)Enum.Parse(typeof(eTickLabelPosition), GetXmlNodeString(_lblPos), true);
            }
            set
            {
                string lp = value.ToString();
                SetXmlNodeString(_lblPos, lp.Substring(0, 1).ToLower() + lp.Substring(1, lp.Length - 1));
            }
        }
        ExcelDrawingFill _fill = null;
        /// <summary>
        /// Access to fill properties
        /// </summary>
        public ExcelDrawingFill Fill
        {
            get
            {
                if (_fill == null)
                {
                    _fill = new ExcelDrawingFill(NameSpaceManager, TopNode, "c:spPr");
                }
                return _fill;
            }
        }
        ExcelDrawingBorder _border = null;
        /// <summary>
        /// Access to border properties
        /// </summary>
        public ExcelDrawingBorder Border
        {
            get
            {
                if (_border == null)
                {
                    _border = new ExcelDrawingBorder(NameSpaceManager, TopNode, "c:spPr/a:ln");
                }
                return _border;
            }
        }
        ExcelTextFont _font = null;
        /// <summary>
        /// Access to font properties
        /// </summary>
        public ExcelTextFont Font
        {
            get
            {
                if (_font == null)
                {
                    if (TopNode.SelectSingleNode("c:txPr", NameSpaceManager) == null)
                    {
                        CreateNode("c:txPr/a:bodyPr");
                        CreateNode("c:txPr/a:lstStyle");
                    }
                    _font = new ExcelTextFont(NameSpaceManager, TopNode, "c:txPr/a:p/a:pPr/a:defRPr", new string[] { "pPr", "defRPr", "solidFill", "uFill", "latin", "cs", "r", "rPr", "t" });
                }
                return _font;
            }
        }
        /// <summary>
        /// If the axis is deleted
        /// </summary>
        public bool Deleted
        {
            get
            {
                return GetXmlNodeBool("c:delete/@val");
            }
            set
            {
                SetXmlNodeBool("c:delete/@val", value);
            }
        }
        const string _ticLblPos_Path = "c:tickLblPos/@val";
        /// <summary>
        /// Position of the Lables
        /// </summary>
        public eTickLabelPosition TickLabelPosition
        {
            get
            {
                string v = GetXmlNodeString(_ticLblPos_Path);
                if (v == "")
                {
                    return eTickLabelPosition.None;
                }
                else
                {
                    return (eTickLabelPosition)Enum.Parse(typeof(eTickLabelPosition), v, true);
                }
            }
            set
            {
                string v = value.ToString();
                v=v.Substring(0, 1).ToLower() + v.Substring(1, v.Length - 1);
                SetXmlNodeString(_ticLblPos_Path,v);
            }
        }
        ExcelChartTitle _title = null;
        /// <summary>
        /// Chart axis title
        /// </summary>
        public ExcelChartTitle Title
        {
            get
            {
                if (_title == null)
                {
                    var node = TopNode.SelectSingleNode("c:title", NameSpaceManager);
                    if (node == null)
                    {
                        CreateNode("c:title");
                        node = TopNode.SelectSingleNode("c:title", NameSpaceManager);
                        node.InnerXml = "<c:tx><c:rich><a:bodyPr /><a:lstStyle /><a:p><a:r><a:t /></a:r></a:p></c:rich></c:tx><c:layout /><c:overlay val=\"0\" />";
                    }
                    _title = new ExcelChartTitle(NameSpaceManager, TopNode);
                }
                return _title;
            }
        }
        #region "Scaling"
        const string _minValuePath = "c:scaling/c:min/@val";
        /// <summary>
        /// Minimum value for the axis.
        /// Null is automatic
        /// </summary>
        public double? MinValue
        {
            get
            {
                return GetXmlNodeDoubleNull(_minValuePath);
            }
            set
            {
                if (value == null)
                {
                    DeleteNode(_minValuePath);
                }
                else
                {
                    SetXmlNodeString(_minValuePath, ((double)value).ToString(CultureInfo.InvariantCulture));
                }
            }
        }
        const string _maxValuePath = "c:scaling/c:max/@val";
        /// <summary>
        /// Max value for the axis.
        /// Null is automatic
        /// </summary>
        public double? MaxValue
        {
            get
            {
                return GetXmlNodeDoubleNull(_maxValuePath);
            }
            set
            {
                if (value == null)
                {
                    DeleteNode(_maxValuePath);
                }
                else
                {
                    SetXmlNodeString(_maxValuePath, ((double)value).ToString(CultureInfo.InvariantCulture));
                }
            }
        }
        const string _majorUnitPath = "c:majorUnit/@val";
        const string _majorUnitCatPath = "c:tickLblSkip/@val";
        /// <summary>
        /// Major unit for the axis.
        /// Null is automatic
        /// </summary>
        public double? MajorUnit
        {
            get
            {
                if (AxisType == eAxisType.Cat)
                {
                    return GetXmlNodeDoubleNull(_majorUnitCatPath);
                }
                else
                {
                    return GetXmlNodeDoubleNull(_majorUnitPath);
                }
            }
            set
            {
                if (value == null)
                {
                    DeleteNode(_majorUnitPath);
                    DeleteNode(_majorUnitCatPath);
                }
                else
                {
                    if (AxisType == eAxisType.Cat)
                    {
                        SetXmlNodeString(_majorUnitCatPath, ((double)value).ToString(CultureInfo.InvariantCulture));
                    }
                    else
                    {
                        SetXmlNodeString(_majorUnitPath, ((double)value).ToString(CultureInfo.InvariantCulture));
                    }
                }
            }
        }
        const string _minorUnitPath = "c:minorUnit/@val";
        const string _minorUnitCatPath = "c:tickMarkSkip/@val";
        /// <summary>
        /// Minor unit for the axis.
        /// Null is automatic
        /// </summary>
        public double? MinorUnit
        {
            get
            {
                if (AxisType == eAxisType.Cat)
                {
                    return GetXmlNodeDoubleNull(_minorUnitCatPath);
                }
                else
                {
                    return GetXmlNodeDoubleNull(_minorUnitPath);
                }
            }
            set
            {
                if (value == null)
                {
                    DeleteNode(_minorUnitPath);
                    DeleteNode(_minorUnitCatPath);
                }
                else
                {
                    if (AxisType == eAxisType.Cat)
                    {
                        SetXmlNodeString(_minorUnitCatPath, ((double)value).ToString(CultureInfo.InvariantCulture));
                    }
                    else
                    {
                        SetXmlNodeString(_minorUnitPath, ((double)value).ToString(CultureInfo.InvariantCulture));
                    }
                }
            }
        }
        const string _logbasePath = "c:scaling/c:logBase/@val";
        /// <summary>
        /// The base for a logaritmic scale
        /// Null for a normal scale
        /// </summary>
        public double? LogBase
        {
            get
            {
                return GetXmlNodeDoubleNull(_logbasePath);
            }
            set
            {
                if (value == null)
                {
                    DeleteNode(_logbasePath);
                }
                else
                {
                    double v = ((double)value);
                    if (v < 2 || v > 1000)
                    {
                        throw(new ArgumentOutOfRangeException("Value must be between 2 and 1000"));
                    }
                    SetXmlNodeString(_logbasePath, v.ToString("0.0", CultureInfo.InvariantCulture));
                }
            }
        }
        const string _orientationPath = "c:scaling/c:orientation/@val";
        /// <summary>
        ///
        /// </summary>
        public eAxisOrientation Orientation
        {
            get
            {
                string v = GetXmlNodeString(_orientationPath);
                if (v == "")
                {
                    return eAxisOrientation.MinMax;
                }
                else
                {
                    return (eAxisOrientation)Enum.Parse(typeof(eAxisOrientation), v, true);
                }
            }
            set
            {
                string s=value.ToString();
                s=s.Substring(0,1).ToLower() + s.Substring(1,s.Length-1);
                SetXmlNodeString(_orientationPath, s);
            }
        }
        #endregion
    }
}


text:
package org.apache.hadoop.hive.ql.qoption;

import org.apache.hadoop.hive.ql.QTestUtil;
import org.apache.hadoop.hive.ql.session.SessionState;

/**
 * QTest authorizer option
 *
 * Enables authorization for the qtest.
 *
 * Example:
 * --! qt:authorizer
 */
public class QTestAuthorizerHandler implements QTestOptionHandler {
  private boolean enabled;

  @Override
  public void processArguments(String arguments) {
    enabled = true;
  }

  @Override
  public void beforeTest(QTestUtil qt) throws Exception {
    if (enabled) {
      qt.getConf().set("hive.test.authz.sstd.hs2.mode", "true");
      qt.getConf().set("hive.security.authorization.manager",
          "org.apache.hadoop.hive.ql.security.authorization.plugin.sqlstd.SQLStdHiveAuthorizerFactoryForTest");
      qt.getConf().set("hive.security.authenticator.manager",
          "org.apache.hadoop.hive.ql.security.SessionStateConfigUserAuthenticator");
      qt.getConf().set("hive.security.authorization.enabled", "true");
      SessionState.get().setAuthenticator(null);
      SessionState.get().setAuthorizer(null);
    }
  }

  @Override
  public void afterTest(QTestUtil qt) throws Exception {
    enabled = false;
  }

}


text:
<?php

class SeoRecordBehavior extends CActiveRecordBehavior
{
	/**
	 * @property string the route used for SEO.
	 */
	public $route;
	/**
	 * @property array GET parameters used for SEO.
	 */
	public $params = array();

	/**
	 * Returns the URL for this model.
	 * @param array $params additional GET parameters (name=>value)
	 * @return string the URL
	 */
	public function getUrl($params=array())
	{
		return Yii::app()->createUrl($this->route, CMap::mergeArray($params, $this->params));
	}

	/**
	 * Returns the absolute URL for this model.
	 * @param array $params additional GET parameters (name=>value)
	 * @return string the URL
	 */
	public function getAbsoluteUrl($params=array())
	{
		return Yii::app()->createAbsoluteUrl($this->route, CMap::mergeArray($params, $this->params));
	}
}


text:
package net.sourceforge.tess4j;

import com.sun.jna.Pointer;
import com.sun.jna.StringArray;
import com.sun.jna.ptr.PointerByReference;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.*;
import java.util.Arrays;
import javax.imageio.ImageIO;

import net.sourceforge.tess4j.ITessAPI.*;
import net.sourceforge.tess4j.util.ImageIOHelper;
import net.sourceforge.tess4j.util.Utils;
import com.ochafik.lang.jnaerator.runtime.NativeSize;
import com.sun.jna.NativeLong;
import com.sun.jna.ptr.IntByReference;
import static net.sourceforge.tess4j.ITessAPI.FALSE;
import static net.sourceforge.tess4j.ITessAPI.TRUE;

import org.junit.*;
import static org.junit.Assert.*;

public class TessAPI1Test {

    String datapath = ".";
    String language = "eng";
    String expOCRResult = "The (quick) [brown] {fox} jumps!\nOver the $43,456.78 <lazy> #90 dog";

    TessBaseAPI handle;

    @BeforeClass
    public static void setUpClass() throws Exception {
    }

    @AfterClass
    public static void tearDownClass() throws Exception {
    }

    @Before
    public void setUp() {
        handle = TessAPI1.TessBaseAPICreate();
    }

    @After
    public void tearDown() {
        TessAPI1.TessBaseAPIDelete(handle);
    }

    /**
     * Test of TessBaseAPIRect method, of class TessDllAPI1.
     *
     * @throws java.lang.Exception
     */
    @Test
    public void testTessBaseAPIRect() throws Exception {
        System.out.println("TessBaseAPIRect");
        String expResult = expOCRResult;
        File tiff = new File("eurotext.tif");
        BufferedImage image = ImageIO.read(tiff); // require jai-imageio lib to read TIFF
        ByteBuffer buf = ImageIOHelper.convertImageData(image);
        int bpp = image.getColorModel().getPixelSize();
        int bytespp = bpp / 8;
        int bytespl = (int) Math.ceil(image.getWidth() * bpp / 8.0);
        TessAPI1.TessBaseAPIInit3(handle, datapath, language);
        TessAPI1.TessBaseAPISetPageSegMode(handle, TessPageSegMode.PSM_AUTO);
        Pointer utf8Text = TessAPI1.TessBaseAPIRect(handle, buf, bytespp, bytespl, 0, 0, image.getWidth(), image.getHeight());
        String result = utf8Text.getString(0);
        TessAPI1.TessDeleteText(utf8Text);
        System.out.println(result);
        assertEquals(expResult, result.substring(0, expResult.length()));
    }

    /**
     * Test of TessBaseAPIGetUTF8Text method, of class TessDllAPI1.
     *
     * @throws java.lang.Exception
     */
    @Test
    public void testTessBaseAPIGetUTF8Text() throws Exception {
        System.out.println("TessBaseAPIGetUTF8Text");
        String expResult = expOCRResult;
        File tiff = new File("eurotext.tif");
        BufferedImage image = ImageIO.read(new FileInputStream(tiff)); // require jai-imageio lib to read TIFF
        ByteBuffer buf = ImageIOHelper.convertImageData(image);
        int bpp = image.getColorModel().getPixelSize();
        int bytespp = bpp / 8;
        int bytespl = (int) Math.ceil(image.getWidth() * bpp / 8.0);
        TessAPI1.TessBaseAPIInit3(handle, datapath, language);
        TessAPI1.TessBaseAPISetPageSegMode(handle, TessPageSegMode.PSM_AUTO);
        TessAPI1.TessBaseAPISetImage(handle, buf, image.getWidth(), image.getHeight(), bytespp, bytespl);
        TessAPI1.TessBaseAPISetRectangle(handle, 0, 0, 1024, 800);
        Pointer utf8Text = TessAPI1.TessBaseAPIGetUTF8Text(handle);
        String result = utf8Text.getString(0);
        TessAPI1.TessDeleteText(utf8Text);
        System.out.println(result);
        assertEquals(expResult, result.substring(0, expResult.length()));
    }

    /**
     * Test of TessVersion method, of class TessAPI1.
     */
    @Test
    public void testTessVersion() {
        System.out.println("TessVersion");
        String expResult = "3.03";
        String result = TessAPI1.TessVersion();
        System.out.println(result);
        assertTrue(result.startsWith(expResult));
    }

    /**
     * Test of TessBaseAPISetInputName method, of class TessAPI1.
     */
    @Test
    public void testTessBaseAPISetInputName() {
        System.out.println("TessBaseAPISetInputName");
        String name = "eurotext.tif";
        TessAPI1.TessBaseAPISetInputName(handle, name);
    }

    /**
     * Test of TessBaseAPISetOutputName method, of class TessAPI1.
     */
    @Test
    public void testTessBaseAPISetOutputName() {
        System.out.println("TessBaseAPISetOutputName");
        String name = "out";
        TessAPI1.TessBaseAPISetOutputName(handle, name);
    }

    /**
     * Test of TessBaseAPISetVariable method, of class TessAPI1.
     */
    @Test
    public void testTessBaseAPISetVariable() {
        System.out.println("TessBaseAPISetVariable");
        String name = "tessedit_create_hocr";
        String value = "1";
        int expResult = 1;
        int result = TessAPI1.TessBaseAPISetVariable(handle, name, value);
        assertEquals(expResult, result);
    }

    /**
     * Test of TessBaseAPIGetBoolVariable method, of class TessAPI1.
     */
    @Test
    public void testTessBaseAPIGetBoolVariable() {
        System.out.println("TessBaseAPIGetBoolVariable");
        String name = "tessedit_create_hocr";
        TessAPI1.TessBaseAPISetVariable(handle, name, "1");
        IntBuffer value = IntBuffer.allocate(1);
        int result = -1;
        if (TessAPI1.TessBaseAPIGetBoolVariable(handle, "tessedit_create_hocr", value) == TRUE) {
            result = value.get(0);
        }
        int expResult = 1;
        assertEquals(expResult, result);
    }

    /**
     * Test of TessBaseAPIPrintVariables method, of class TessAPI1.
     *
     * @throws java.lang.Exception
     */
    @Test
    public void testTessBaseAPIPrintVariablesToFile() throws Exception {
        System.out.println("TessBaseAPIPrintVariablesToFile");
        String var = "tessedit_char_whitelist";
        String value = "0123456789";
        TessAPI1.TessBaseAPISetVariable(handle, var, value);
        String filename = "printvar.txt";
        TessAPI1.TessBaseAPIPrintVariablesToFile(handle, filename); // will crash if not invoked after some method
        File file = new File(filename);
        BufferedReader input = new BufferedReader(new FileReader(file));
        StringBuilder strB = new StringBuilder();
        String line;
        String EOL = System.getProperty("line.separator");
        while ((line = input.readLine()) != null) {
            strB.append(line).append(EOL);
        }
        input.close();
        file.delete();
        assertTrue(strB.toString().contains(var + "\t" + value));
    }

    /**
     * Test of TessBaseAPIInit1 method, of class TessAPI1.
     */
    @Test
    public void testTessBaseAPIInit1() {
        System.out.println("TessBaseAPIInit1");
        int oem = TessOcrEngineMode.OEM_DEFAULT;
        String[] args = {"hocr"};
        StringArray sarray = new StringArray(args);
        PointerByReference configs = new PointerByReference();
        configs.setPointer(sarray);
        int configs_size = args.length;
        int expResult = 0;
        int result = TessAPI1.TessBaseAPIInit1(handle, datapath, language, oem, configs, configs_size);
        assertEquals(expResult, result);
    }

    /**
     * Test of TessBaseAPIInit2 method, of class TessAPI1.
     */
    @Test
    public void testTessBaseAPIInit2() {
        System.out.println("TessBaseAPIInit2");
        int oem = TessOcrEngineMode.OEM_DEFAULT;
        int expResult = 0;
        int result = TessAPI1.TessBaseAPIInit2(handle, datapath, language, oem);
        assertEquals(expResult, result);
    }

    /**
     * Test of TessBaseAPIInit3 method, of class TessAPI1.
     */
    @Test
    public void testTessBaseAPIInit3() {
        System.out.println("TessBaseAPIInit3");
        int expResult = 0;
        int result = TessAPI1.TessBaseAPIInit3(handle, datapath, language);
        assertEquals(expResult, result);
    }

    /**
     * Test of TessBaseAPIInit4 method, of class TessAPI1.
     */
    @Test
    public void testTessBaseAPIInit4() {
        System.out.println("TessBaseAPIInit4");
        int oem = TessOcrEngineMode.OEM_DEFAULT;
        PointerByReference configs = null;
        int configs_size = 0;

        // disable loading dictionaries
        String[] args = new String[]{"load_system_dawg", "load_freq_dawg"};
        StringArray sarray = new StringArray(args);
        PointerByReference vars_vec = new PointerByReference();
        vars_vec.setPointer(sarray);

        args = new String[]{"F", "F"};
        sarray = new StringArray(args);
        PointerByReference vars_values = new PointerByReference();
        vars_values.setPointer(sarray);

        NativeSize vars_vec_size = new NativeSize(args.length);

        int expResult = 0;
        int result = TessAPI1.TessBaseAPIInit4(handle, datapath, language, oem, configs, configs_size, vars_vec, vars_values, vars_vec_size, FALSE);
        assertEquals(expResult, result);
    }

    /**
     * Test of TessBaseAPIGetInitLanguagesAsString method, of class TessAPI1.
     */
    @Test
    public void testTessBaseAPIGetInitLanguagesAsString() {
        System.out.println("TessBaseAPIGetInitLanguagesAsString");
        String expResult = "";
        String result = TessAPI1.TessBaseAPIGetInitLanguagesAsString(handle);
        assertEquals(expResult, result);
    }

    /**
     * Test of TessBaseAPIGetLoadedLanguagesAsVector method, of class TessAPI1.
     */
    @Test
    public void testTessBaseAPIGetLoadedLanguagesAsVector() {
        System.out.println("TessBaseAPIGetLoadedLanguagesAsVector");
        TessAPI1.TessBaseAPIInit3(handle, datapath, language);
        String[] expResult = {"eng"};
        String[] result = TessAPI1.TessBaseAPIGetLoadedLanguagesAsVector(handle).getPointer().getStringArray(0);
        assertArrayEquals(expResult, result);
    }

    /**
     * Test of TessBaseAPIGetAvailableLanguagesAsVector method, of class
     * TessAPI1.
     */
    @Test
    public void testTessBaseAPIGetAvailableLanguagesAsVector() {
        System.out.println("TessBaseAPIGetAvailableLanguagesAsVector");
        TessAPI1.TessBaseAPIInit3(handle, datapath, language);
        String[] expResult = {"eng"};
        String[] result = TessAPI1.TessBaseAPIGetAvailableLanguagesAsVector(handle).getPointer().getStringArray(0);
        assertTrue(Arrays.asList(result).containsAll(Arrays.asList(expResult)));
    }

    /**
     * Test of TessBaseAPIGetPageSegMode method, of class TessAPI1.
     */
    @Test
    public void testTessBaseAPIGetPageSegMode() {
        System.out.println("TessBaseAPIGetPageSegMode");
        TessAPI1.TessBaseAPISetPageSegMode(handle, TessPageSegMode.PSM_SINGLE_CHAR);
        int expResult = TessPageSegMode.PSM_SINGLE_CHAR;
        int result = TessAPI1.TessBaseAPIGetPageSegMode(handle);
        assertEquals(expResult, result);
    }

    /**
     * Test of TessBaseAPIProcessPages method, of class TessAPI1.
     */
    @Test
    public void testTessBaseAPIProcessPages() {
        System.out.println("TessBaseAPIProcessPages");
        String expResult = expOCRResult;
        String filename = "eurotext.tif";
        String retry_config = null;
        int timeout_millisec = 0;
        TessAPI1.TessBaseAPIInit3(handle, datapath, language);
        Pointer utf8Text = TessAPI1.TessBaseAPIProcessPages(handle, filename, retry_config, timeout_millisec);
        String result = utf8Text.getString(0);
        TessAPI1.TessDeleteText(utf8Text);
        assertTrue(result.startsWith(expResult));
    }

    /**
     * Test of TessBaseAPIProcessPages1 method, of class TessAPI.
     */
    @Test
    public void testTessBaseAPIProcessPages1() {
        System.out.println("TessBaseAPIProcessPages1");
        String filename = "eurotext.tif";
        String retry_config = null;
        int timeout_millisec = 0;
        TessAPI1.TessBaseAPIInit3(handle, datapath, language);
        String expResult = expOCRResult;
        TessResultRenderer renderer = TessAPI1.TessTextRendererCreate();
        TessAPI1.TessResultRendererBeginDocument(renderer, filename);
        TessAPI1.TessBaseAPIProcessPages1(handle, filename, retry_config, timeout_millisec, renderer);
        TessAPI1.TessResultRendererEndDocument(renderer);
        PointerByReference data = new PointerByReference();
        IntByReference dataLength = new IntByReference();
        TessAPI1.TessResultRendererGetOutput(renderer, data, dataLength);
        int length = dataLength.getValue();
        String result = data.getValue().getString(0);
        assertTrue(result.startsWith(expResult));
//        api.TessDeleteResultRenderer(renderer);
    }

    /**
     * Test of TessBaseAPIGetHOCRText method, of class TessAPI1.
     *
     * @throws java.lang.Exception
     */
    @Test
    public void testTessBaseAPIGetHOCRText() throws Exception {
        System.out.println("TessBaseAPIGetHOCRText");
        File tiff = new File("eurotext.tif");
        BufferedImage image = ImageIO.read(new FileInputStream(tiff)); // require jai-imageio lib to read TIFF
        ByteBuffer buf = ImageIOHelper.convertImageData(image);
        int bpp = image.getColorModel().getPixelSize();
        int bytespp = bpp / 8;
        int bytespl = (int) Math.ceil(image.getWidth() * bpp / 8.0);
        TessAPI1.TessBaseAPISetPageSegMode(handle, TessPageSegMode.PSM_AUTO);
        TessAPI1.TessBaseAPIInit3(handle, datapath, language);
        TessAPI1.TessBaseAPISetImage(handle, buf, image.getWidth(), image.getHeight(), bytespp, bytespl);
        int page_number = 0;
        Pointer utf8Text = TessAPI1.TessBaseAPIGetHOCRText(handle, page_number);
        String result = utf8Text.getString(0);
        TessAPI1.TessDeleteText(utf8Text);
        assertTrue(result.contains("<div class='ocr_page'"));
    }

    /**
     * Test of Orientation and script detection (OSD).
     *
     * @throws java.lang.Exception
     */
    @Test
    public void testOSD() throws Exception {
        System.out.println("OSD");
        int expResult = TessPageSegMode.PSM_AUTO_OSD;
        IntBuffer orientation = IntBuffer.allocate(1);
        IntBuffer direction = IntBuffer.allocate(1);
        IntBuffer order = IntBuffer.allocate(1);
        FloatBuffer deskew_angle = FloatBuffer.allocate(1);
        File tiff = new File("eurotext.tif");
        BufferedImage image = ImageIO.read(new FileInputStream(tiff)); // require jai-imageio lib to read TIFF
        ByteBuffer buf = ImageIOHelper.convertImageData(image);
        int bpp = image.getColorModel().getPixelSize();
        int bytespp = bpp / 8;
        int bytespl = (int) Math.ceil(image.getWidth() * bpp / 8.0);
        TessAPI1.TessBaseAPIInit3(handle, datapath, language);
        TessAPI1.TessBaseAPISetPageSegMode(handle, expResult);
        int actualResult = TessAPI1.TessBaseAPIGetPageSegMode(handle);
        System.out.println("PSM: " + Utils.getConstantName(actualResult, TessPageSegMode.class));
        TessAPI1.TessBaseAPISetImage(handle, buf, image.getWidth(), image.getHeight(), bytespp, bytespl);
        int success = TessAPI1.TessBaseAPIRecognize(handle, null);
        if (success == 0) {
            TessPageIterator pi = TessAPI1.TessBaseAPIAnalyseLayout(handle);
            TessAPI1.TessPageIteratorOrientation(pi, orientation, direction, order, deskew_angle);
            System.out.println(String.format("Orientation: %s\nWritingDirection: %s\nTextlineOrder: %s\nDeskew angle: %.4f\n",
                    Utils.getConstantName(orientation.get(), TessOrientation.class),
                    Utils.getConstantName(direction.get(), TessWritingDirection.class),
                    Utils.getConstantName(order.get(), TessTextlineOrder.class),
                    deskew_angle.get()));
        }
        assertEquals(expResult, actualResult);
    }

    /**
     * Test of ResultIterator and PageIterator.
     *
     * @throws Exception
     */
    @Test
    public void testResultIterator() throws Exception {
        System.out.println("TessBaseAPIGetIterator");
        File tiff = new File("eurotext.tif");
        BufferedImage image = ImageIO.read(new FileInputStream(tiff)); // require jai-imageio lib to read TIFF
        ByteBuffer buf = ImageIOHelper.convertImageData(image);
        int bpp = image.getColorModel().getPixelSize();
        int bytespp = bpp / 8;
        int bytespl = (int) Math.ceil(image.getWidth() * bpp / 8.0);
        TessAPI1.TessBaseAPIInit3(handle, datapath, language);
        TessAPI1.TessBaseAPISetPageSegMode(handle, TessPageSegMode.PSM_AUTO);
        TessAPI1.TessBaseAPISetImage(handle, buf, image.getWidth(), image.getHeight(), bytespp, bytespl);
        ETEXT_DESC monitor = new ETEXT_DESC();
        TimeVal timeout = new TimeVal();
        timeout.tv_sec = new NativeLong(0L); // time > 0 causes blank ouput
        monitor.end_time = timeout;
        ProgressMonitor pmo = new ProgressMonitor(monitor);
        pmo.start();
        TessAPI1.TessBaseAPIRecognize(handle, monitor);
        System.err.println("Message: " + pmo.getMessage());
        TessResultIterator ri = TessAPI1.TessBaseAPIGetIterator(handle);
        TessPageIterator pi = TessAPI1.TessResultIteratorGetPageIterator(ri);
        TessAPI1.TessPageIteratorBegin(pi);
        System.out.println("Bounding boxes:\nchar(s) left top right bottom confidence font-attributes");
        int level = TessAPI1.TessPageIteratorLevel.RIL_WORD;

//        int height = image.getHeight();
        do {
            Pointer ptr = TessAPI1.TessResultIteratorGetUTF8Text(ri, level);
            String word = ptr.getString(0);
            TessAPI1.TessDeleteText(ptr);
            float confidence = TessAPI1.TessResultIteratorConfidence(ri, level);
            IntBuffer leftB = IntBuffer.allocate(1);
            IntBuffer topB = IntBuffer.allocate(1);
            IntBuffer rightB = IntBuffer.allocate(1);
            IntBuffer bottomB = IntBuffer.allocate(1);
            TessAPI1.TessPageIteratorBoundingBox(pi, level, leftB, topB, rightB, bottomB);
            int left = leftB.get();
            int top = topB.get();
            int right = rightB.get();
            int bottom = bottomB.get();
            System.out.print(String.format("%s %d %d %d %d %f", word, left, top, right, bottom, confidence));
//            System.out.println(String.format("%s %d %d %d %d", str, left, height - bottom, right, height - top)); // training box coordinates

            IntBuffer boldB = IntBuffer.allocate(1);
            IntBuffer italicB = IntBuffer.allocate(1);
            IntBuffer underlinedB = IntBuffer.allocate(1);
            IntBuffer monospaceB = IntBuffer.allocate(1);
            IntBuffer serifB = IntBuffer.allocate(1);
            IntBuffer smallcapsB = IntBuffer.allocate(1);
            IntBuffer pointSizeB = IntBuffer.allocate(1);
            IntBuffer fontIdB = IntBuffer.allocate(1);
            String fontName = TessAPI1.TessResultIteratorWordFontAttributes(ri, boldB, italicB, underlinedB,
                    monospaceB, serifB, smallcapsB, pointSizeB, fontIdB);
            boolean bold = boldB.get() == TRUE;
            boolean italic = italicB.get() == TRUE;
            boolean underlined = underlinedB.get() == TRUE;
            boolean monospace = monospaceB.get() == TRUE;
            boolean serif = serifB.get() == TRUE;
            boolean smallcaps = smallcapsB.get() == TRUE;
            int pointSize = pointSizeB.get();
            int fontId = fontIdB.get();
            System.out.println(String.format("  font: %s, size: %d, font id: %d, bold: %b,"
                    + " italic: %b, underlined: %b, monospace: %b, serif: %b, smallcap: %b",
                    fontName, pointSize, fontId, bold, italic, underlined, monospace, serif, smallcaps));
        } while (TessAPI1.TessPageIteratorNext(pi, level) == TRUE);

        assertTrue(true);
    }

    /**
     * Test of ResultRenderer method, of class TessAPI1.
     *
     * @throws java.lang.Exception
     */
    @Test
    public void testResultRenderer() throws Exception {
        System.out.println("TessResultRenderer");
        String image = "eurotext.tif";
        String output = "capi-test.txt";
        int set_only_init_params = FALSE;
        int oem = TessOcrEngineMode.OEM_DEFAULT;
        PointerByReference configs = null;
        int configs_size = 0;

        String[] params = {"load_system_dawg", "tessedit_char_whitelist"};
        String vals[] = {"F", ""}; //0123456789-.IThisalotfpnex
        PointerByReference vars_vec = new PointerByReference();
        vars_vec.setPointer(new StringArray(params));
        PointerByReference vars_values = new PointerByReference();
        vars_values.setPointer(new StringArray(vals));
        NativeSize vars_vec_size = new NativeSize(params.length);

        TessAPI1.TessBaseAPISetOutputName(handle, output);

        int rc = TessAPI1.TessBaseAPIInit4(handle, datapath, language,
                oem, configs, configs_size, vars_vec, vars_values, vars_vec_size, set_only_init_params);

        if (rc != 0) {
            TessAPI1.TessBaseAPIDelete(handle);
            System.err.println("Could not initialize tesseract.");
            return;
        }

        TessResultRenderer renderer = TessAPI1.TessHOcrRendererCreate();
        TessAPI1.TessResultRendererInsert(renderer, TessAPI1.TessBoxTextRendererCreate());
        TessAPI1.TessResultRendererInsert(renderer, TessAPI1.TessTextRendererCreate());
        String dataPath = TessAPI1.TessBaseAPIGetDatapath(handle);
        TessAPI1.TessResultRendererInsert(renderer, TessAPI1.TessPDFRendererCreate(dataPath));
        TessAPI1.TessResultRendererBeginDocument(renderer, image);
        int result = TessAPI1.TessBaseAPIProcessPages1(handle, image, null, 0, renderer);
        TessAPI1.TessResultRendererEndDocument(renderer);

//        if (result == FALSE) {
//            System.err.println("Error during processing.");
//            return;
//        }
        String outputbase = "test/results/outputbase1";

        for (; renderer != null; renderer = TessAPI1.TessResultRendererNext(renderer)) {
            String ext = TessAPI1.TessResultRendererExtention(renderer).getString(0);
            System.out.println(String.format("TessResultRendererExtention: %s\nTessResultRendererTitle: %s\nTessResultRendererImageNum: %d",
                    ext,
                    TessAPI1.TessResultRendererTitle(renderer).getString(0),
                    TessAPI1.TessResultRendererImageNum(renderer)));

            PointerByReference data = new PointerByReference();
            IntByReference dataLength = new IntByReference();
            result = TessAPI1.TessResultRendererGetOutput(renderer, data, dataLength);
            if (result == TRUE) {
                if (ext.equals("pdf")) {
                    int length = dataLength.getValue();
                    byte[] bytes = data.getValue().getByteArray(0, length);
                    try {
                        File file = new File(outputbase + "." + ext);

                        // create parent dirs when necessary
                        if (file.getParentFile() != null) {
                            file.getParentFile().mkdirs();
                        }

                        FileOutputStream bw = new FileOutputStream(file.getAbsoluteFile());
                        bw.write(bytes);
                        bw.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else {
                    String result1 = data.getValue().getString(0);
                    System.out.println(result1);
                }
            }
        }

        TessAPI1.TessDeleteResultRenderer(renderer);
        assertTrue(new File(outputbase + ".pdf").exists());
    }

    /**
     * Test of TessBaseAPIClear method, of class TessAPI1.
     */
    @Test
    public void testTessBaseAPIClear() {
        System.out.println("TessBaseAPIClear");
        TessAPI1.TessBaseAPIClear(handle);
    }

    /**
     * Test of TessBaseAPIEnd method, of class TessAPI1.
     */
    @Test
    public void testTessBaseAPIEnd() {
        System.out.println("TessBaseAPIEnd");
        TessAPI1.TessBaseAPIEnd(handle);
    }
}