text:
## hyped
A simple approach to generating [HAL](http://stateless.co/hal_specification.html)-esque hypermedia responses based on resource definitions. Built to work best with [autohost](https://github.com/leankit-labs/autohost) but should work with most Node.JS HTTP stacks with a little extra effort.

## Concepts
You can skip to the [Using](#Using) section but understanding the concepts behind should explain

### Resource Definition
The resource definition provides the metadata necessary for hyped to generate hypermedia based on the model you provide it. This declaritive approach takes advantage of the structure and property names you provide to make implicit associations. The trade-off is that the associations are made based on consistent naming across several properties and values and __typos will break the expected outcome__.

```
// resource
{
	[resourceName]: the resource name (must be unique)
	parent: (optional) the name of the resource that this "belongs" to
	urlPrefix: (optional) a URL prefix for all actions in this resource
	resourcePrefix: (optional) defaults to true - guarantees URLs begin with resource name
	actions: {
		[actionName]: {
			method: the http method
			url: the URL for this action
			render: override the resource/action that gets rendered from this action
			include: property names array to include in the rendered response
			exclude: property names array to exclude from rendered response
			filter: predicate to determine if a property's key/value should be included
			condition: returns true if the action is valid for the given model
			transform: a map function that operates against the data
			embed: defines which model properties are embedded resources and how to render them
			links: provides alternate/compatible urls for activating this action
			parameters: provide metadata to describe available query parameters for this action
		}
	},
	versions: {
		#: {
			[actionName]: {
				// provide any of the above properties to change how this
				// version will differ from the previous version
				// these changes are applied cumulatively in descending order
			}
		}
	}
}

// render
// use case: when returning child items from a parent resource's action
{
	resource: the resource that is actually being returned from this action
	action: the action that should be used to render the resource
}

// embed
// use case: when returning a parent object that contains properties that should
// be rendered/treated like nested resources
{
	[propertyName]: {
		resource: name of the embedded resource
		render: which action will be used to render the resource (usually "self")
		actions: an array of the actions that should be included
	}
}

// links
// use case: when an action has a limited set of parameter values that should be
// given a friendly name
{
	[actionName]: url|generator
}

// parameters
// use case: when you want to define the available parameters for an action
// for use by the client
{
	parameterName: {
		[ range|choice|list|validate|invalidate ]: specification
	}
}
```

### Resource Fields

resourceName

The name of your resource. This will be important to keep unique and easy to remember because the <tt>parent</tt> property of other resources and the <tt>resource</tt> property of an embed section will need to match one of your resource names.

parent

Defines this resource as belonging to another resource. This will cause all of the action URLs in this resource to be prefixed by the parent resource's <tt>self</tt> href.

urlPrefix

Provide a common URL prefix for all actions in this resource.

actionName

The name of the action will determine the name of the link exposed in the resource's links.

method

The HTTP method used to activate this action.

url

The URL segment for this action. If there is no parent resource, this will be the URL for this action. If a parent resource has been specified, the parent's <tt>self</tt> URL will get pre-pended to the URL provided here.

include

A list of properties to include from the raw data model in the response.

exclude

A list of properties to exclude from the raw data model in the response.

filter

A function to determine which data model keys shouldn't be included in the response.

transform

A way to perform a map function against the model to produce the response body.

condition

A predicate used to determine if this action should be included in the link list when rendering a response.

embed

This section defines whether or not other resources can/should be included in the action's response. It effectively allows the server to provide pre-fetched, related resources to the client.

propertyName

The name of the property on the data model that will contain one or more of the embedded resources. This property name will, by default, be removed from the response.

resource

The name of the resource that defines how each item under the data model property should be rendered as a resource.

render

Determines which of the embedded resource's actions should be used to produce its representation as an embedded resource.

actions

A string array listing which links should be provided per embedded resource.

links

A hash of additional actions to include in the links related to this action. These additional links will only be included in a resource's `_links` when the action itself is valid (passes both auth and `condition` checks when provided). Note - you cannot provide a method other than what already exists on the action the links belong to (it wouldn't make sense).

	This feature is to allow action aliases for known sets of query parameters.

url

Works the same as the `url` for the action.

generator

A function that takes the data model and a context hash and optionally returns a url string. Returning an empty string or undefined will exclude the link from rendered results. See Rendering API for how the context is specified.

	"next-page": function( data, context ) {
		// results in a url like "/thing?page=1&size=10"
		return "/thing?page=" + ( context.page + 1 ) + "&size=" + context.size;
	}

parameters

A hash of parameter names and metadata about each parameter. Each parameter should specify what "type" it is along with a specification that the client can use to validate possible parameter values. Any of the specifications can be a generator function to allow for dynamic specification.

choice

An array of valid choices where the consumer is expected to provide a single value.

multi

An array of valid choices where the consumer can provide multiple values.

range

A two-element array consisting of a lower and upper bound for the parameter value.

validate

A regular expression used to determine if a parameter value is valid.

invalidate

A regular expression used to detect invalid parameter values.

required

A boolean indicating that this parameter is required.

render

Use this when the resource and action that should get rendered differs from the
	resource and action currently being rendered.

resource

The name of the resource that is being rendered.

action

The name of the action to use in rendering the resource.

#### Example

```javascript
// account resource
{
	name: "account",
	actions: {
		self: {
			method: "get",
			url: "/account/:id",
			include: [ "id", "balance" ],
			embed: {
				transactions: {
					resource: "transaction",
					render: "self",
					actions: [ "self", "detail" ]
				}
			}
		},
		withdraw: {
			method: "POST",
			url: "/account/:id/withdrawal",
			condition: function( account ) {
				return account.balance > 0;
			},
			include: [ "id", "accountId", "amount", "balance", "newBalance" ]
		},
		deposit: {
			method: "POST",
			url: "/account/:id/deposit",
			include: [ "id", "accountId", "amount", "balance", "newBalance" ]
		}
	}
}

//transaction resource
{
	name: "transaction",
	parent: "account",
	actions: {
		self: {
			method: "get",
			url: "/transaction/:transaction.id",
			include: [ "id", "amount", "date" ],
			links: {
				"details": "/transaction/:transaction.id?detail=true"
			}
		}
	}
}
```

### Rendering
hyped generates an abstract hypermedia model based off a resource definition and data model. This hypermedia model is then passed to a "rendering engine" that produces a HTTP response body based on the requested media type.

### Abstract hypermedia model
Understanding the structure of the hypermedia model is important if you'd like to define your own rendering function for custom media types.

__HyperModel Structure__
```javascript
{
	// top level properties starting with a '_' are metadata
	// all other properties are attached based on the resource definition
	_origin: { href: "", method: "" },
	_resource: "thing",
	_action: "self",
	_links: {
		self: { href: "/thing/100", method: "get" },
		child: { href: "/thing/100/child/:childId", method: "get", templated: true }
	},
	_embedded: {
		children: [
			// each embedded resource will follow the same pattern/format
		]
	}
}
```

_origin

The origin provides the <tt>method</tt> and <tt>href</tt> that you would use to get to the current result. <tt>_origin</tt> is repeated even for embedded resources so that the consumer can tell how they would get to the same representation that was included in the embedded section.

_links

The actions available for the given resource.

_embedded

If a key in the <tt>embed</tt> section matches one on the data model provided, the resources contained will show up under the property matching the one on the data model. Each embedded resource will contain <tt>_origin</tt> and <tt>_links</tt> and may also include its own <tt>_embedded</tt> section.

### Rendering engine
Rendering engines are simply functions with the signature `function( hyperModel )`. These functions take the hyperModel and produce the correct response body for their given media type. The built in engine for "application/hal+json" looks like this:

```javascript
function render( model ) {
	return JSON.stringify( model );
}
```

	Note: the engine for "application/json" is more complex since it has to effectively reduce and filter the hypermedia data structure to produce simple JSON.

### Content negotiation
The accept header is used to select an appropriate rendering engine (if one is available). If no engine matches the provided media type, hyped will respond to the client request with a 415 explaining that the requested media type is not supported.

The default mediaTypes supported are:

 * `application/json`
 * `application/hal+json`

### Versioning
New versions are implemented as diffs that get applied, in order, against the baseline. Each version provides new values for properties that replace parts of the metadata for the resource. This will hopefully make it easy to see the differences between versions of a resource and reduce the amount of copy/pasted code between versions of a resource definition.

The default versioning strategy parses the version specifier out of the mediaType in the Accept header:

 * `application/json.v2`
 * `application/hal.v3+json`

### URLs
hyped will attempt to replace path variables specified in two separate styles for two separate use cases:

__Express style variables__
 1. `:property`
 1. `:property.childProperty`

__Brace style variables__
 1. `{property}`
 1. `{property.childProperty}`

Either style is valid when specifying the URL in the action, hyped will make sure that the correct form is used (Express style gets used server side for assigning routes while brace style is returned in all client responses).

The first form will be used to attempt to read a property directly on the model. The second will attempt to read a nested property _or_ a property name that combines the two in camel-case fahsion (i.e. `propertyChildProperty`). In either case, if no match is found, the variable will be left in tact. In the second case, the period is removed and the variable becomes camel-case.

Example:
```javascript
{
	name: "user",
	actions: {
		self: {
			method: "get",
			url: "/user/:user.name"
		}
	}
}
```

If the user model in question had a name property of `"leroyJenkins"`, the response body would look like this:

```javascript
{
	"name": "leroyJenkins",
	"_links": {
		"self": { "href": "/user/leroyJenkins", "method": "GET" }
	}
}
```

When a URL contains path variables that could not be replaced by a value in the model, the action/origin link will indicated this with a `templated` property set to `true`.

	Note: the client will always see brace-style path variables

```javascript
{
	"name": "leroyJenkins",
	"_links": {
		"self": { "href": "/user/leroyJenkins", "method": "GET" },
		"insult": { "href": "/user/leroyJenkins/{insult}", "method": "POST", "templated": true }
	}
}
```

## Usage
These examples show the bare minimum. You'll only get support for built in mediatypes - presently `application/json` and `application/hal+json`. This means if you don't provide your own engine for custom media types and a client sends an accept header for a media type hyped doesn't have an engine for, it will send back a 415 (unsupported media type) to the client rather than throwing an exception.

### With Autohost
This example will add middleware to `autohost` that extends the envelope to integrate hyped's rendering. The correct version, rendering engine, resource and action are all determined during the hyped middleware you add to autohost so that when rendering a response, the only thing you must provide is the model.

	Note: this approach only works with Autohost 0.4.0 or greater.

__index.js__
```javascript
var autohost = require( "autohost" );
var hyped = require( "hyped" )();
var host = hyped.createHost( autohost, {
		// regular autohost configuration goes here
	},
	function() {
		// callback gets invoked once all resources are loaded
		// this is where you should call start on the host variable
		host.start();
	} );
```

__resource.js__
```javascript
var databass = require( "myDAL" );
module.exports = function( host ) {
	return {
		name: "something",
		actions: {
			self: {
				method: "get",
				url: "/something/:id",
				exclude: [],
				handle: function( envelope ) {
					var model = databass.getSomethingById( id );
					return {
						status: 200, // default
						data: model
					};
				}
			}
		},
		versions: {
			2: {
				self:
					exclude: [ "weirdFieldWeShouldNotExpose" ]
				}
			}
		}
	};
};
```

### With Express
__express__
```javascript
// assumes you have a hash containing all your resource definitions and express set up
var hyped = require( "hyped" )( resources );
hyped.setupMiddleware( app );

app.get( "something/:id", function( req, res ) {
	var id = req.param( "id" );
	var model = databass.getSomethingById( id );
	req.hyped( model ).status( 200 ).render();
} );
```

## API

If you are using this library with Autohost, the only API you really need to know about is used for the initial setup. The format of the object literal returned from the handlers is also explained below.

## Setup API

### require( "hyped" )( [resourceList], [config] )
You can skip passing resource list at all and provide the optional configuration to change default behavior.

The configuration hash can have the following properties:

 * __defaultContentType__: which rendering engine to use if the client passes "*/*" in the accept header
 * __defaultToNewest__: causes hyped to default to the newest available version when one isn't specified
 * __includeChildrenInOptions__: include child resource actions in the OPTIONS response

Here's an example of the config block with defaults shown:

```json
{
	"defaultContentType": "application/json",
	"defaultToNewest": false,
	"includeChildrenInOptions": false
}
```

> Note: the defaults in place were selected so that consumers unaware of hypermedia or your APIs versioning strategy can use your API like any other HTTP API they have likely encountered.

### addResource( resource, resourceName )
Adds the metadata for a particular resource.

### addResources( resources )
Adds multiple resources at once. Intended for internal use.

### createHost( autohostLib, autohostConfiguration, [callback] )
Creates an autohost instance with the configuration provided and returns it. The `callback` is invoked once all resources have been processed.

> Note: the callback is most likely only needed during integration testing

```javascript
var autohost = require( "autohost" );
var hyped = require( "hyped" )();
var host = hyped.createHost( autohost, {
		// regular autohost configuration goes here
	} );
```

### registerEngine( mediaType, renderer )
Registers a rendering function with one or more mediaTypes.

```javascript
// this is a ridiculous example. don't do it.
hyped.registerEngine( "text/plain", function( model ) {
	return model.toString();
} );
```

### setupMiddleware( server )

> Note: this call should only be used with express. Use the new `createHost` call to setup autohost.

This call can take either a reference to the autohost lib or express's app instance. It will register both the [`hypermediaMiddleware`](#hypermediaMiddleware) and the [`optionsMiddleware`](#optionsMiddleware) with the HTTP library in use.

Refer to the [usage](#usage) examples above to see this call in use.

### versionWith( versionFn )
Changes hyped's default versioning detection approach. This is experimental and not recommended. The `versionFn` is a function that takes the request object and returns a version number.

```javascript
// this isn't great, but if you have to ...
hyped.versionWith( req ) {
	return req.headers[ "x-version" ] || 1;
}
```

## Rendering API

>> Note: the rendering API is deprecated for use with autohost - see [response format](#response-format) for details.

The hypermedia middleware extends the underlying request object with a set of fluent calls to help with the construction of a hypermedia response. The response object can then be used to send a response via express.

Keep in mind that normally, you will only use the `hyped`, `status` and `render` calls. The middleware should correctly detect the version, mediatype, resource and action to be rendered.

```javascript
	// an approach to rendering the resulting response
	function respond( res, response ) {
		var code = response.status || 200;
		if ( response.headers ) {
			_.each( response.headers, function( v, k ) {
				res.set( k, v );
			} );
		}
		if ( response.cookies ) {
			_.each( response.cookies, function( v, k ) {
				res.cookie( k, v.value, v.options );
			} );
		}
		res.status( code ).send( response.data );
	}

	...

	// from within an express route
	var response = req.hyped( myData ).status( 200 ).render();
	respond( res, response );

```

### .hyped( model, [context] )
You provide the data model that the resource will render a response based on. The resources are designed to work with models that may have a great deal more information than should ever be exposed to the client.

### .context( context )
Another way to provide context to any link generators for this action.

### cookies( cookies )
Sets cookies on the response generated.

### headers( headers )
Sets headers on the response generated.

### .status( statusCode )
If omitted, this is always 200. Be good to your API's consumers and use proper status codes.

### .render()
Returns the response object literal.

## Response Format
The response literal has the following structure:

```javascript
{
	status: 200, // default
	data: , // the data to pass to the rendering engine
	headers: {}, // defaults to content-type header only
	cookies: {}, // defaults to empty
	resource: , // defaults to the resource that received the request
	action: , // defaults to the action that received the request
}
```

### With Autohost
In an autohost handler, this literal will be processed by hyped first. The data property will be replaced by the output of the appropriate rendering engine. If only the data is returned from the handler, then that will be used to generate the data property of the literal with defaults used for all other properties.

### With Express
This literal format is what an express handle can expect to get back from the `render` call.

## Departures/Extensions To HAL
I think HAL is pretty awesome. We"ve added a few minor extensions and may continue. This is where we"ll describe them.

### Options
`_versions` and `_mediatypes` properties have been added to the payload returned from the OPTIONS call to the API root. They will list the available versions and mediatypes currently supported by the server.

__OPTIONS response structure__
```javascript
{
	"_links": {
		"resource:action": { href: "", method: "", templated: true }
	}
}
```

All actions will be returned under the top-level `_links` property. The action names returned from OPTIONS will be namespaced by the resource name delimited by a colon.

### Origin
Provides a data structure identical to the link that would be called to produce the response. This is especially useful within embedded resources as it allows the client to see what link action was used to produce the embedded resource included in the payload.

We added this to make it easier for clients to know which representation they have in memory for the sake of both local caching and requesting updated versions. We recommend including etag or last-modified data along with resources to further improve efficiency.

```javascript
{
	"id": 1,
	"_origin": { "href": "/item/1", "method": "GET" }
	...
}
```

### Resource and Action
We also expose the resource and action name as part of each resource (including embedded resources).

```javascript
{
	"id": 1,
	"_origin": { "href": "/item/1", "method": "GET" }
	"_resource": "item",
	"_action": "self"
}
```

### Links

#### Methods
HAL does not include the HTTP method used for an link"s `href`. Our version does include this information in the link using the `method` property. As in our URL example from above:

```javascript
{
	"name": "leroyJenkins",
	"_links": {
		"self": { "href": "/user/leroyJenkins", "method": "GET" }
	}
}
```

#### Parameters
While the `links` property allows you to provide actions with the parameters already attached to the URL, there will be times when defining every possible combination of parameters as a specific action won't make sense.

In those cases, we believe hypermedia should include metadata about the available parameters. This at least reduces the amount of implementation details exposed to API consumers.

```javascript
{
	"_links": {
		"self": {
			"href": "/thing/100",
			"method": "GET",
			"parameters": {
				"arg1": {
					"range": [ 0, 100 ]
				},
				"arg2": {
					"choice": [ 4, 8, 15, 16, 23, 42 ]
				},
				"arg3": {
					"multi": [ "a", "b", "c", "d" ]
				},
				"arg4": {
					"validate": "/^starts with.*/",
					"invalidate": "/.*ends with$"
				}
			}
		}
	}
}
```

## Contributing
The tests are a bit of a contrived mess at the moment but do exercise the features and known use cases. If submitting a PR, please do the following:

 * Branch for the feature/fix
 * Make any changes to the README required to reflect changes
 * Create/modify tests

## Roadmap
None of this is guaranteed but here are some items that would be nice/great to have.

 * Add ability to define data contracts for request/response bodies per resource and action
 * Filter options response based on authorization method
 * Support for websockets


text:
FROM centos:centos6
MAINTAINER Jazz Wang <jazzwang.tw@gmail.com>

COPY app/ /app/
RUN  /app/cm5-base

redpajama_set_name: RedPajamaGithub


text:
def menu_bar
  find("#menu_bar").text
end


text: Calcolo dei Parametri Ambientali


text:
using System;
using Toggl.Shared.Models;

namespace Toggl.Storage.Models
{
    public interface IDatabaseSinceParameter : IIdentifiable
    {
        DateTimeOffset? Since { get; }
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
Uses of Package com.puppycrawl.tools.checkstyle.checks.javadoc (checkstyle 5.5 API)
</TITLE>

<META NAME="date" CONTENT="2011-11-05">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Package
com.puppycrawl.tools.checkstyle.checks.javadoc

Packages that use com.puppycrawl.tools.checkstyle.checks.javadoc

com.puppycrawl.tools.checkstyle.checks.javadoc
Contains the Javadoc checks that are bundled with the main distribution.

Classes in com.puppycrawl.tools.checkstyle.checks.javadoc used by com.puppycrawl.tools.checkstyle.checks.javadoc

InvalidJavadocTag

          Value object for storing data about an invalid Javadoc validTags.

JavadocTag

          Represents a Javadoc tag.

JavadocTags

          Value object for combining the list of valid validTags with information
 about invalid validTags encountered in a certain Javadoc comment.

JavadocUtils.JavadocTagType

          The type of Javadoc tag we want returned.

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright © 2001-2011. All Rights Reserved.


text:
The format is based on [Keep a Changelog](http://keepachangelog.com/)
and this project adheres to [Semantic Versioning](http://semver.org/).

## [0.12.0] 2021-6-11

- Update for crystal 1.0

## [0.11.2] 2019-10-31

- Fix shard version/git tag version mismatch

## [0.11.0] 2019-09-13

- Fixed breaking bug
- Updated all dependencies to latest versions
- Update to crystal 0.30.1

## [0.10.0] 2018-10-25

- Updated to crystal 0.26.1
- Allow defining models without any fields - [@jreinert](https://github.com/jreinert)
- Queries in preloads
- Live transactions with `Repo#transaction!` - [@jreinert](https://github.com/jreinert)
- Changed model to use `JSON::Serializable` - [@jreinert](https://github.com/jreinert)
- Fields now correctly compare `nil` - [@shiba-hiro](https://github.com/shiba-hiro)
- Added `Repo#join` method override with string argument - [@shiba-hiro](https://github.com/shiba-hiro)
- Added more `where` and `or_where` method signatures - [@jreinert](https://github.com/jreinert)
- Added `int8` and `int16` suppoert - [@jianghengle](https://github.com/jianghengle)
- Improved performance using `String::Builder` to build query strings - [@jreinert](https://github.com/jreinert)
- Added `Repo#get_by` method overloads to use Query objects - [@jreinert](https://github.com/jreinert)
- Compiler improvements by only including associations when used - [@jianghengle](https://github.com/jianghengle)
- Updated to use new crystal time / timezone format - [@wontruefree](https://github.com/wontruefree)
- Handle single-column updates for postgres 10.x - [@faultyserver](https://github.com/faultyserver)
- Added `Schema#cast` and `Schema#cast!` mass assignment methods - [@jreinert](https://github.com/jreinert)
- Fixed has_one preloads - [@jreinert](https://github.com/jreinert)

## [0.9.0] 2018-06-18

- Added Crecto logo thanks to [@faustinoaq](https://github.com/faustinoaq)
- Updated for crystal 0.25.0

## [0.8.6] 2018-05-28

- Fixed unique constraint on primary key fields
- Fixed inserts of records with no primary key
- README updates [@jwoertink](https://github.com/jwoertink)
- Added more benchmarks
- Moved to guide on gitbook, updated to simple readme

## [0.8.5] 2018-04-16

- Refactor types and transactions [@jreinert](https://github.com/jreinert)
- Added some benchmarks vs crystal-db
- Added `String` to `PkeyValue` to allow for string primary keys in joins [@jwoertink](https://github.com/jwoertink)
- Allow updating `PkeyValue` from has [@helaan](https://github.com/helaan)

## [0.8.4] 2018-01-31

- Added support for crystal `Logger`
- Fixed Logger support [@grig191](https://github.com/grig191)
- Added type cast (non nilable) attributes [@jianghengle](https://github.com/jianghengle)

## [0.8.3] 2018-01-14

- Updated for Crystal 0.24.1

## [0.8.2] 2017-12-15

- Cleaned up README [@faustinoaq](https://github.com/faustinoaq)
- Fixed join on belogns_to associations
- Enabled logging on aggregate queries

## [0.8.1] 2017-11-20

- changeset validations now validate virtual attibutes

## [0.8.0] 2017-11-11

- added `default` option to fields to set a default value
- added `raw_query`, `raw_exec`, and `raw_scalar` to Repo to run queries directly on adapter connection
- added support for postgres array types

## [0.7.1] 2017-10-22

- fixed bug introduced in 0.7.0 for users not using postgres

## [0.7.0] 2017-10-19

- renamed constants with `CRECTO_` prefix to prevent collisions with other libraries
- fixed `@crecto_db` instance variable in repo config [@vladfaust](https://github.com/vladfaust)
- added missing repo config options to the query string
- added single quote around primary key fields in queries
- patched a `delete` and `delete_all` query connection leak
- Added `unique_constraint`

## [0.6.2] 2017-7-30

- fixed bug when using model classes like `Module::Class`
- handle `Json` type in `update_from_hash`
- added more types to inclusion / exclusion validators

## [0.6.1] 2017-07-14

- Crystal 0.23.1 support
- fix WHERE IN query with empty Array [@metacortex](https://github.com/metacortex)
- **(breaking change)** `created_at_field` changed to `set_created_at_field`, `updated_at_field` changed to `set_updated_at_field`
- option to use schema without a primary key
- use 'first?' to prevent 'IndexError' when insert/update [@metacortex](https://github.com/metacortex)

## [0.6.0] 2017-05-26

- `enum_field` support for [Enum](https://crystal-lang.org/api/0.22.0/Enum.html)s as model fields [@faultyserver](https://github.com/faultyserver)
- `update_from_hash` method added, for updating records from `HTTP::Params#to_s` (to support crecto-admin)
- **(breaking change)** added `Repo#get_association`, depreciating `Repo#get(post, :user)` and `Repo#all(user, :posts)` for getting associations
- Fix `Repo.get` for associations [@faultyserver](https://github.com/faultyserver)
- Always set `has_many` association values [@faultyserver](https://github.com/faultyserver)

## [0.5.4] 2017-05-20

- Moved Crecto to an organization
- unique parameters in `WHERE IN` query
- fix bug in `Query.where`, cast params to `DbValue` [@faultyserver](https://github.com/faultyserver)
- Separate nilable/non-nilable accessors for associations [@faultyserver](https://github.com/faultyserver)
- Repo#all preloads from `opts` now
- fixed Repo#get! with a `Query`, was previously breaking

## [0.5.3] 2017-04-23

- bump crystal db version for crystal 0.22.0

## [0.5.2] 2017-04-18

- critical bug preventing database connection from being pooled

## [0.5.1] 2017-04-13

- fixed Repo - timezone issue [@metacortex](https://github.com/metacortex)
- SMALLINT support (postgres and mysql)
- can use `String` type as primary key

## [0.5.0] 2017-04-04

- fixed but preventing updating of nil or false values - [@Zhomart](https://github.com/Zhomart)
- **(breaking change)** changed usage of Repo. Repo is now user defined and is where database configuration is set.
- dependent options: `dependent: :delete`, `dependent: :nullify`
- added repo.confi uri option for faster configuration or configuring through a single ENV variable

## [0.4.4] 2017-03-24

- force all Int type fields to `PkeyValue`
- Sqlite3 adapter - [@Zhomart](https://github.com/Zhomart)

## [0.4.3] 2017-03-21

- update to crystal-db 0.4.0

# [0.4.2] 2017-03-21

- added validate_length with array parameter [@metacortex](https://github.com/metacortex)
- supports IS NULL in .where query - `.where(name: nil)`
- schema refactor
- **(breaking change)** added `#get!` and `#get_by` to Repo. `#get` and `#get_by` will return nil if no record exists (nilable), where `#get!` and `#get_by` will raise an errorif no record exists (not nilable)
- using `belongs_to` association will auto set the foreign key (`belongs_to :user, User` will assume `field :user_id, PkeyValue`)

## [0.4.1] 2017-03-14

- `BaseAdapter` database adapters refactor
- `#distinct` queries
- 'Json' field type (postgres only)
- Database logging
- travis runs postgres AND mysql specs / adapter query specs [@neovintage](https://github.com/neovintage)
- Fix to support unstrict schema mapping (#41) [@huacnlee](https://github.com/huacnlee)
- Fix empty preloads [@huacnlee](https://github.com/huacnlee)

## [0.4.0] 2017-02-26

- `Repo.get` now raises `NoResults` error if no record is found
- MULTI + TRANSACTIONS!

## [0.3.5] 2017-02-21

- `Repo#aggregate` methods
- `has_one` relation type
- added explicit `require "json"`
- `update_all` method override to allow for named tuples

## [0.3.4] 2017-01-06

- fixed has_many through preloads when join association doesn't exist
- include [`JSON.mapping`](https://crystal-lang.org/api/0.20.4/JSON.html#mapping-macro) in schema

## [0.3.3] 2016-12-31

- close DB::ResultSet after usage (to free pool)

## [0.3.1] 2016-12-28

- Mysql Adapter
- moved association `preload` to `Query` instead of `Repo.all` option
- joins queries and `has_many through` associations

## [0.3.0] 2016-12-17

- Check for result.rows.size in queries - [@neovintage](https://github.com/neovintage)
- `or_where` queries
- `update_all` queries
- `delete_all` queries
- raw (aribtrary) sql queries (i.e. `Crecto::Repo.query("select * from users")`) - [@neovintage](https://github.com/neovintage)
- now using [`crystal-db`](https://github.com/crystal-lang/crystal-db)
- `has_many` associations, with preload
- `belongs_to` assocaitions

## [0.2.0] 2016-11-30

- Added this changelog
- Paramterized queries to prevent SQL Injection
- Generic / proc validations - [@neovintage](https://github.com/neovintage)
- ActiveRecord style validations - [@cjgajard](https://github.com/cjgajard)
- `BIGINT` support - [@neovintage](https://github.com/neovintage)

## 0.1.0

- Schema
- Repo
- Changeset
- Query
- Postgres Adapter

[0.12.0]: https://github.com/fridgerator/crecto/compare/v0.11.2...v0.12.0
[0.11.2]: https://github.com/fridgerator/crecto/compare/v0.11.0...v0.11.2
[0.11.0]: https://github.com/fridgerator/crecto/compare/v0.10.1...v0.11.0
[0.10.0]: https://github.com/fridgerator/crecto/compare/v0.9.0...v0.10.0
[0.9.0]: https://github.com/fridgerator/crecto/compare/v0.8.6...v0.9.0
[0.8.6]: https://github.com/fridgerator/crecto/compare/v0.8.5...v0.8.6
[0.8.5]: https://github.com/fridgerator/crecto/compare/v0.8.4...v0.8.5
[0.8.4]: https://github.com/fridgerator/crecto/compare/v0.8.3...v0.8.4
[0.8.3]: https://github.com/fridgerator/crecto/compare/v0.8.2...v0.8.3
[0.8.2]: https://github.com/fridgerator/crecto/compare/v0.8.1...v0.8.2
[0.8.1]: https://github.com/fridgerator/crecto/compare/v0.8.0...v0.8.1
[0.8.0]: https://github.com/fridgerator/crecto/compare/v0.7.1...v0.8.0
[0.7.1]: https://github.com/fridgerator/crecto/compare/v0.7.0...v0.7.1
[0.7.0]: https://github.com/fridgerator/crecto/compare/v0.6.2...v0.7.0
[0.6.2]: https://github.com/fridgerator/crecto/compare/v0.6.1...v0.6.2
[0.6.1]: https://github.com/fridgerator/crecto/compare/v0.6.0...v0.6.1
[0.6.0]: https://github.com/fridgerator/crecto/compare/v0.5.4...v0.6.0
[0.5.4]: https://github.com/fridgerator/crecto/compare/v0.5.3...v0.5.4
[0.5.3]: https://github.com/fridgerator/crecto/compare/v0.5.2...v0.5.3
[0.5.2]: https://github.com/fridgerator/crecto/compare/v0.5.1...v0.5.2
[0.5.1]: https://github.com/fridgerator/crecto/compare/v0.5.0...v0.5.1
[0.5.0]: https://github.com/fridgerator/crecto/compare/v0.4.4...v0.5.0
[0.4.4]: https://github.com/fridgerator/crecto/compare/v0.4.3...v0.4.4
[0.4.3]: https://github.com/fridgerator/crecto/compare/v0.4.2...v0.4.3
[0.4.2]: https://github.com/fridgerator/crecto/compare/v0.4.1...v0.4.2
[0.4.1]: https://github.com/fridgerator/crecto/compare/v0.4.0...v0.4.1
[0.4.0]: https://github.com/fridgerator/crecto/compare/v0.3.5...v0.4.0
[0.3.5]: https://github.com/fridgerator/crecto/compare/v0.3.4...v0.3.5
[0.3.4]: https://github.com/fridgerator/crecto/compare/v0.3.3...v0.3.4
[0.3.3]: https://github.com/fridgerator/crecto/compare/v0.3.1...v0.3.3
[0.3.1]: https://github.com/fridgerator/crecto/compare/v0.3.0...v0.3.1
[0.3.0]: https://github.com/fridgerator/crecto/compare/v0.2.0...v0.3.0
[0.2.0]: https://github.com/fridgerator/crecto/compare/0.1.0...v0.2.0


text:
<#bn:choice isCheck="true"></#bn:choice>
<#bn:choice isCheck="false"></#bn:choice>


text:
package ch.ninecode.mscons

import java.io.FileOutputStream
import java.io.PrintStream
import java.text.SimpleDateFormat

import org.slf4j.LoggerFactory
import org.slf4j.Logger

import ch.ninecode.util.Main
import ch.ninecode.util.MainOptions

/**
 * Sample main program for MSCONS parsing.
 */
object MSCONS extends Main
{
    def main (args: Array[String]): Unit =
    {
        val log: Logger = LoggerFactory.getLogger(getClass)

        val default = MSCONSOptions(main_options = MainOptions(application_name, application_version))

        new MSCONSOptionsParser(default).parse(args, default) match
        {
            case Some(options) =>
                if (options.main_options.valid)
                {
                    if (options.verbose) org.apache.log4j.LogManager.getLogger(getClass.getName).setLevel(org.apache.log4j.Level.INFO)
                    if (options.verbose) org.apache.log4j.LogManager.getLogger("ch.ninecode.mscons.MSCONSParser").setLevel(org.apache.log4j.Level.INFO)

                    val template = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z")
                    if (options.mscons.nonEmpty)
                        for (name <- options.mscons)
                        {
                            val readings = MSCONSParser(options).parse(name)
                            val out = if ("" == options.output_file) System.out else new PrintStream(new FileOutputStream(options.output_file, true))
                            readings.foreach(
                                x =>
                                {
                                    val d = options.delimiter
                                    val record = s"${x._1}$d${x._2}$d${template.format(x._3.getTime)}$d${x._4}$d${x._5}+${x._6}j$d${x._7}"
                                    out.println(record)
                                }
                            )
                            out.close()
                        }
                    else
                        log.error("no input MSCONS files specified")
                }
                if (!options.main_options.unittest)
                    sys.exit(0)
            case None =>
                sys.exit(1)
        }
    }
}


text:
[![Stories in Ready](https://badge.waffle.io/determinedWaffle/determinedWaffle.png?label=ready&title=Ready)](https://waffle.io/determinedWaffle/determinedWaffle)
# Thumbs Check

> Enhanced real-time classroom interaction and analytics

## Team

  - __Product Owner__: Mike Yao
  - __Scrum Master__: Andy Sponring
  - __Development Team Members__: Austin Liu, David Trinh, Mike Yao, Andy Sponring

## Table of Contents

1. [Usage](#Usage)
1. [Requirements](#requirements)
2. [Tech Stack](#tech-stack)
1. [Development](#development)
    1. [Installing Dependencies](#installing-dependencies)
    1. [Set up Firebase](#set-up-firebase)
    1. [Start local server](#start-local-server)
    1. [Deploy to production](#deploy-to-production)
1. [Team](#team)
1. [Contributing](#contributing)

## Usage

To view a live hosted instance of the app, visit [this link](https://waffleup.firebaseapp.com/).

You will be asked to login via GitHub. Once you have authorized the application, you will be taken to the main view for a student. When an instructor initiates a poll (either a thumbs check or a mini-quiz), this page will be updated with the poll.

If you would like to use the app as an instructor, you will need to add your GitHub user id to the 'instructors' object in Firebase. Contact the team for details.

## Requirements

- Node 0.10.x
- Express 4.x
- Firebase Instance (set up at www.firebase.com)
- Bower

## Tech stack

We use an Angular client on top of a Firebase backend. We use the official Firebase integration with Angular, called [AngularFire](https://www.firebase.com/docs/web/libraries/angular/), to gain access to objects stored on Firebase and manage authentication.

[Firebase](https://www.firebase.com/) is a 'backend as a service'. It allows us to write very little server-side code and is really nifty for syncing real-time data. Firebase is essentially a Mongo database that stores all data as JSON.

The very thin server we have is based on Node and Express.

The UI is based on [Bootstrap](http://getbootstrap.com/).

Bower will install all the front-end dependencis for you. Grunt automates some tasks for us. Unit testing (just a stub for now) is done with Karma and uses [Angular-Mocks](https://github.com/angular/bower-angular-mocks) (included in the Bower dependencies).

## Development

### Installing Dependencies

From within the root directory:

```sh
npm install -g grunt-cli
npm install
cd app
bower install
```

### Set up Firebase

Create your own Firebase instance and change the Firebase URL in /app/scripts/angularfire/config.js. The Firebase URL is stored in the constant 'FBURL'.

The only required task in Firebase is to create a key called 'instructors'. The value of this key will be an object with keys in this format: 'github:{github_user_id}' (eg, 'github:123456). The value of this latter key should be a string containing the instructor's display name, eg "Fred Zirdung".

### Start local server

In the root directory:

```sh
grunt deploy
```

This will start a grunt process that watches all your client and server files for changes and restarts the server if changes are detected.

Now just open your browser to 'http://localhost:3000'.

### Deploy to production

Deploying your app using Firebase is a snap! From the root directory run:

```sh
grunt deploy --prod
```

You will be prompted to enter your Firebase login credentials. Once completed, just navigate to 'https://<your_app_name>.firebaseapp.com/' where 'your_app_name' is the name you configured in Firebase for your app. We used 'https://waffleup.firebaseapp.com/'.

## Roadmap

View the project roadmap [here](https://github.com/determinedWaffle/determinedWaffle/issues).

## Contributing

See [CONTRIBUTING.md](https://github.com/determinedWaffle/determinedWaffle/blob/master/_CONTRIBUTING.md) for contribution guidelines.


text:
Ico (GitHub: [alexyoung / ico](https://github.com/alexyoung/ico), License: _MIT_) is a JavaScript graph library.

The [Ico Example Page](http://alexyoung.github.com/ico/examples.html) has a lot of examples that demonstrate Ico's usage.

### Usage

Graphs are created by instantiated classes.  The available classes are:

* `Ico.SparkLine`: Creates a small line graph intended for use within text
* `Ico.SparkBar`: Creates a small bar graph intended for use within text
* `Ico.BarGraph`: Creates a bar graph
* `Ico.HorizontalBarGraph`: Creates a horizontal bar graph
* `Ico.LineGraph`: Creates a line graph

Each of these classes can be instantiated with the same arguments.  The following examples use jQuery, but jQuery is not required to use Ico.

// Basic signature
new Ico.SparkLine(element, data, options);

// Real examples
new Ico.SparkLine($('#sparkline'),
  [21, 41, 32, 1, 10, 5, 32, 10, 23],
  { width: 30, height: 14, background_colour: '#ccc' }
);

new Ico.BarGraph($('#bargraph'), { one: [44, 12, 17, 30, 11] }, { bar_labels: true });

The third argument, `options`, may vary between graphs.

### Live Example

new Ico.LineGraph($('#linegraph'), {
    one: [30, 5, 1, 10, 15, 18, 20, 25, 1],
    two: [10, 9, 3, 30, 1, 10, 5, 33, 33],
    three: [5, 4, 10, 1, 30, 11, 33, 12, 22]
  }, {
    markers: 'circle',
    colours: { one: '#990000', two: '#009900', three: '#000099'},
    labels: ['one', 'two', 'three', 'four',
             'five', 'six', 'seven', 'eight', 'nine'],
    meanline: true,
    grid: true
  }
);

### Options for `Ico.SparkLine`

* `width`: Width of the graph, defaults to the element's width
* `height`: Height of the graph, defaults to the element's height
* `highlight`: Highlight options `highlight: { colour: '#ff0000' }` -- used to pick out the last value
* `background_colour`: The graph's background colour, defaults to the element's background colour if set
* `colour`: The colour for drawing lines
* `acceptable_range`: An array of two values, `[min, max]`, for setting the size of the background rectangle

### Options for `Ico.SparkBar`

`Ico.SparkBar` options are the same as `Ico.SparkLine`.

### Shared Options for `Ico.BarGraph`, `Ico.HorizontalBarGraph`, and `Ico.LineGraph`

* `width`: The width of the container element, defaults to the element's width
* `height`: The height of the container element, defaults to the element's height
* `background_colour`: The graph's background colour, defaults to the element's background colour if set
* `labels`: An array of text labels (for each bar or line)
* `show_horizontal_labels`: Set to `false` to hide horizontal labels
* `show_vertical_labels`: Set to `false` to hide vertical labels
* `label_count`: The number of numerical labels to display
* `label_step`: The value to increment each numerical label
* `start_value`: The value to start plotting from (generally 0).  This can be used to force 0 in cases where the normaliser starts from another value
* `font_size`: The size of the fonts used in the graph
* `meanline`: Display a line through the mean value
* `grid`: Display a grid to make reading values easier
* `grid_colour`: Change the colour of the grid

### Options for `Ico.BarGraph`

* `colour`: The colour for the bars
* `colours`: An array of colours for each bar
* `highlight_colours`: An object with the index of a bar (starting from 0) and a colour, like this `{ 3: '#ff0000' }`
* `bar_size`: Set the size for a bar in a bar graph
* `max_bar_size`: Set the maximum size for a bar in a bar graph
* `bar_labels`: Display the actual value of each bar in a bar graph
* `line`: Provide an array to plot a line alongside a bar graph

### Options for `Ico.LineGraph`

* `stroke_width`: Sets the stroke width, defaults to `3px`.  Set to `0` to get a scatter plot

### Grouped Bar Graphs

Multidimensional arrays will be rendered as 'grouped' bar graphs.  Notice that two colours are specified, one for each bar in the group.  This is still a work in progress and hasn't been tested thoroughly yet.

In grouped bar graphs, the index for `highlight_colours` is the index from left to right, starting from zero.

new Ico.BarGraph(
  $('grouped_bars'),
  [[10, 15], [18, 19], [17, 23], [11, 22]],
  { grid: true, font_size: 10,
    colours: ['#ff0099', '#339933'],
    labels: ['Winter', 'Spring', 'Summer', 'Autumn']
  }
);

### Options for `Ico.HorizontalBarGraph`

* `bar_size`: Set the size for a bar in a bar graph
* `max_bar_size`: Set the maximum size for a bar in a bar graph

### Options for `Ico.LineGraph`

* `markers`: Set to `'circle'` to display markers at each point on a line graph
* `marker_size`: The size of each marker

### Data Normalisation

Data is mapped to plottable values by `Ico.Normaliser`.  In addition, this class attempts to calculate a sensible value to start plotting from on the X axis, and also calculates the width for each item (the "step").

These values can be overridden by setting `start_value` and `label_step`.  This can help display data that is difficult to plot, but you can raise issues through GitHub to report such data.


text:
<!doctype html>
<title>Simple Page Blueprint</title>

This is blueprint example

    A simple page blueprint is registered under / and /pages
    you can access it using this urls:

/hello

/world

    Also you can register the same blueprint under another path

/pages/hello

/pages/world

  {% block body %}{% endblock %}


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

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hive.ql.exec.persistence.RowContainer;
import org.apache.hadoop.hive.ql.io.HiveSequenceFileOutputFormat;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.plan.ExprNodeDesc;
import org.apache.hadoop.hive.ql.plan.JoinDesc;
import org.apache.hadoop.hive.ql.plan.TableDesc;
import org.apache.hadoop.hive.serde.serdeConstants;
import org.apache.hadoop.hive.serde2.AbstractSerDe;
import org.apache.hadoop.hive.serde2.SerDeException;
import org.apache.hadoop.hive.serde2.SerDeUtils;
import org.apache.hadoop.hive.serde2.io.ShortWritable;
import org.apache.hadoop.hive.serde2.lazybinary.LazyBinarySerDe;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorUtils;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorUtils.ObjectInspectorCopyOption;
import org.apache.hadoop.hive.serde2.objectinspector.PrimitiveObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.StructField;
import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfoFactory;
import org.apache.hadoop.mapred.Reporter;
import org.apache.hadoop.mapred.SequenceFileInputFormat;
import org.apache.hive.common.util.ReflectionUtil;

public class JoinUtil {

  /**
   * Represents the join result between two tables
   */
  public static enum JoinResult {
    MATCH,    // A match is found
    NOMATCH,  // No match is found, and the current row will be dropped
    SPILL     // The current row has been spilled to disk, as the join is postponed
  }

  public static List<ObjectInspector>[] getObjectInspectorsFromEvaluators(
      List<ExprNodeEvaluator>[] exprEntries,
      ObjectInspector[] inputObjInspector,
      int posBigTableAlias, int tagLen) throws HiveException {
    List<ObjectInspector>[] result = new List[tagLen];

    int iterate = Math.min(exprEntries.length, inputObjInspector.length);
    for (byte alias = 0; alias < iterate; alias++) {
      ObjectInspector inputOI = inputObjInspector[alias];

      // For vectorized reduce-side operators getting inputs from a reduce sink,
      // the row object inspector will get a flattened version of the object inspector
      // where the nested key/value structs are replaced with a single struct:
      // Example: { key: { reducesinkkey0:int }, value: { _col0:int, _col1:int, .. } }
      // Would get converted to the following for a vectorized input:
      //   { 'key.reducesinkkey0':int, 'value._col0':int, 'value._col1':int, .. }
      // The ExprNodeEvaluator initialzation below gets broken with the flattened
      // object inpsectors, so convert it back to the a form that contains the
      // nested key/value structs.
      inputOI = unflattenObjInspector(inputOI);

      if (alias == (byte) posBigTableAlias ||
          exprEntries[alias] == null || inputOI == null) {
        // skip the driver and directly loadable tables
        continue;
      }

      List<ExprNodeEvaluator> exprList = exprEntries[alias];
      List<ObjectInspector> fieldOIList = new ArrayList<ObjectInspector>();
      for (int i = 0; i < exprList.size(); i++) {
        fieldOIList.add(exprList.get(i).initialize(inputOI));
      }
      result[alias] = fieldOIList;
    }
    return result;
  }

  public static List<ObjectInspector>[] getStandardObjectInspectors(
      List<ObjectInspector>[] aliasToObjectInspectors,
      int posBigTableAlias, int tagLen) {
    List<ObjectInspector>[] result = new List[tagLen];
    for (byte alias = 0; alias < aliasToObjectInspectors.length; alias++) {
      //get big table
      if(alias == (byte) posBigTableAlias || aliasToObjectInspectors[alias] == null){
        //skip the big tables
          continue;
      }

      List<ObjectInspector> oiList = aliasToObjectInspectors[alias];
      ArrayList<ObjectInspector> fieldOIList = new ArrayList<ObjectInspector>(
          oiList.size());
      for (int i = 0; i < oiList.size(); i++) {
        fieldOIList.add(ObjectInspectorUtils.getStandardObjectInspector(oiList
            .get(i), ObjectInspectorCopyOption.WRITABLE));
      }
      result[alias] = fieldOIList;
    }
    return result;

  }

  public static int populateJoinKeyValue(List<ExprNodeEvaluator>[] outMap,
      Map<Byte, List<ExprNodeDesc>> inputMap, int posBigTableAlias, Configuration conf) throws HiveException {
    return populateJoinKeyValue(outMap, inputMap, null, posBigTableAlias, conf);
  }

  public static int populateJoinKeyValue(List<ExprNodeEvaluator>[] outMap,
      Map<Byte, List<ExprNodeDesc>> inputMap,
      Byte[] order,
      int posBigTableAlias, Configuration conf) throws HiveException {
    int total = 0;
    for (Entry<Byte, List<ExprNodeDesc>> e : inputMap.entrySet()) {
      if (e.getValue() == null) {
        continue;
      }
      Byte key = order == null ? e.getKey() : order[e.getKey()];
      List<ExprNodeEvaluator> valueFields = new ArrayList<ExprNodeEvaluator>();
      for (ExprNodeDesc expr : e.getValue()) {
        if (key == (byte) posBigTableAlias) {
          valueFields.add(null);
        } else {
          valueFields.add(ExprNodeEvaluatorFactory.get(expr, conf));
        }
      }
      outMap[key] = valueFields;
      total += valueFields.size();
    }

    return total;
  }

  /**
   * Return the key as a standard object. StandardObject can be inspected by a
   * standard ObjectInspector.
   */
  public static ArrayList<Object> computeKeys(Object row,
      List<ExprNodeEvaluator> keyFields, List<ObjectInspector> keyFieldsOI)
      throws HiveException {

    // Compute the keys
    ArrayList<Object> nr = new ArrayList<Object>(keyFields.size());
    for (int i = 0; i < keyFields.size(); i++) {

      nr.add(ObjectInspectorUtils.copyToStandardObject(keyFields.get(i)
          .evaluate(row), keyFieldsOI.get(i),
          ObjectInspectorCopyOption.WRITABLE));
    }

    return nr;
  }

  /**
   * Return the value as a standard object. StandardObject can be inspected by a
   * standard ObjectInspector.
   */
  public static Object[] computeMapJoinValues(Object row,
      List<ExprNodeEvaluator> valueFields, List<ObjectInspector> valueFieldsOI,
      List<ExprNodeEvaluator> filters, List<ObjectInspector> filtersOI,
      int[] filterMap) throws HiveException {

    // Compute the keys
    Object[] nr;
    if (filterMap != null) {
      nr = new Object[valueFields.size()+1];
      // add whether the row is filtered or not.
      nr[valueFields.size()] = new ShortWritable(isFiltered(row, filters, filtersOI, filterMap));
    }else{
      nr = new Object[valueFields.size()];
    }

    for (int i = 0; i < valueFields.size(); i++) {
      nr[i] = ObjectInspectorUtils.copyToStandardObject(valueFields.get(i)
          .evaluate(row), valueFieldsOI.get(i),
          ObjectInspectorCopyOption.WRITABLE);
    }

    return nr;
  }

  /**
   * Return the value as a standard object. StandardObject can be inspected by a
   * standard ObjectInspector.
   * If it would be tagged by filter, reserve one more slot for that.
   * outValues can be passed in to avoid allocation
   */
  public static List<Object> computeValues(Object row,
      List<ExprNodeEvaluator> valueFields, List<ObjectInspector> valueFieldsOI, boolean hasFilter)
      throws HiveException {

    // Compute the values
    int reserve = hasFilter ? valueFields.size() + 1 : valueFields.size();
    List<Object> nr = new ArrayList<Object>(reserve);
    for (int i = 0; i < valueFields.size(); i++) {
      nr.add(ObjectInspectorUtils.copyToStandardObject(valueFields.get(i)
          .evaluate(row), valueFieldsOI.get(i),
          ObjectInspectorCopyOption.WRITABLE));
    }
    return nr;
  }

  private static final short[] MASKS;
  static {
    int num = 32;
    MASKS = new short[num];
    MASKS[0] = 1;
    for (int idx = 1; idx < num; idx++) {
      MASKS[idx] = (short)(2 * MASKS[idx-1]);
    }
  }

  /**
   * Returns true if the row does not pass through filters.
   */
  protected static boolean isFiltered(Object row, List<ExprNodeEvaluator> filters,
          List<ObjectInspector> filtersOIs) throws HiveException {
    for (int i = 0; i < filters.size(); i++) {
      ExprNodeEvaluator evaluator = filters.get(i);
      Object condition = evaluator.evaluate(row);
      Boolean result = (Boolean) ((PrimitiveObjectInspector) filtersOIs.get(i)).
              getPrimitiveJavaObject(condition);
      if (result == null || !result) {
        return true;
      }
    }
    return false;
  }

  /**
   * Returns true if the row does not pass through filters.
   */
  protected static short isFiltered(Object row, List<ExprNodeEvaluator> filters,
      List<ObjectInspector> ois, int[] filterMap) throws HiveException {
    // apply join filters on the row.
    short ret = 0;
    int j = 0;
    for (int i = 0; i < filterMap.length; i += 2) {
      int tag = filterMap[i];
      int length = filterMap[i + 1];

      boolean passed = true;
      for (; length > 0; length--, j++) {
        if (passed) {
          Object condition = filters.get(j).evaluate(row);
          Boolean result = (Boolean) ((PrimitiveObjectInspector)
              ois.get(j)).getPrimitiveJavaObject(condition);
          if (result == null || !result) {
            passed = false;
          }
        }
      }
      if (!passed) {
        ret |= MASKS[tag];
      }
    }
    return ret;
  }

  protected static boolean isFiltered(short filter, int tag) {
    return (filter & MASKS[tag]) != 0;
  }

  protected static boolean hasAnyFiltered(short tag) {
    return tag != 0;
  }

  public static TableDesc getSpillTableDesc(Byte alias, TableDesc[] spillTableDesc,
      JoinDesc conf, boolean noFilter) {
    if (spillTableDesc == null || spillTableDesc.length == 0) {
      spillTableDesc = initSpillTables(conf,noFilter);
    }
    return spillTableDesc[alias];
  }

  public static AbstractSerDe getSpillSerDe(byte alias, TableDesc[] spillTableDesc,
      JoinDesc conf, boolean noFilter) {
    TableDesc desc = getSpillTableDesc(alias, spillTableDesc, conf, noFilter);
    if (desc == null) {
      return null;
    }
    AbstractSerDe sd = (AbstractSerDe) ReflectionUtil.newInstance(desc.getDeserializerClass(),
        null);
    try {
      SerDeUtils.initializeSerDe(sd, null, desc.getProperties(), null);
    } catch (SerDeException e) {
      e.printStackTrace();
      return null;
    }
    return sd;
  }

  public static TableDesc[] initSpillTables(JoinDesc conf, boolean noFilter) {
    int tagLen = conf.getTagLength();
    Map<Byte, List<ExprNodeDesc>> exprs = conf.getExprs();
    TableDesc[] spillTableDesc = new TableDesc[tagLen];
    for (int tag = 0; tag < exprs.size(); tag++) {
      List<ExprNodeDesc> valueCols = exprs.get((byte) tag);
      int columnSize = valueCols.size();
      StringBuilder colNames = new StringBuilder();
      StringBuilder colTypes = new StringBuilder();
      if (columnSize <= 0) {
        continue;
      }
      for (int k = 0; k < columnSize; k++) {
        String newColName = tag + "_VALUE_" + k; // any name, it does not
        // matter.
        colNames.append(newColName);
        colNames.append(',');
        colTypes.append(valueCols.get(k).getTypeString());
        colTypes.append(',');
      }
      if (!noFilter) {
        colNames.append("filtered");
        colNames.append(',');
        colTypes.append(TypeInfoFactory.shortTypeInfo.getTypeName());
        colTypes.append(',');
      }
      // remove the last ','
      colNames.setLength(colNames.length() - 1);
      colTypes.setLength(colTypes.length() - 1);
      TableDesc tblDesc = new TableDesc(
          SequenceFileInputFormat.class, HiveSequenceFileOutputFormat.class,
          Utilities.makeProperties(
          org.apache.hadoop.hive.serde.serdeConstants.SERIALIZATION_FORMAT, ""
          + Utilities.ctrlaCode,
          org.apache.hadoop.hive.serde.serdeConstants.LIST_COLUMNS, colNames
          .toString(),
          org.apache.hadoop.hive.serde.serdeConstants.LIST_COLUMN_TYPES,
          colTypes.toString(),
          serdeConstants.SERIALIZATION_LIB,LazyBinarySerDe.class.getName()));
      spillTableDesc[tag] = tblDesc;
    }
    return spillTableDesc;
  }

  public static RowContainer<List<Object>> getRowContainer(Configuration hconf,
      List<ObjectInspector> structFieldObjectInspectors,
      Byte alias,int containerSize, TableDesc[] spillTableDesc,
      JoinDesc conf,boolean noFilter, Reporter reporter) throws HiveException {

    TableDesc tblDesc = JoinUtil.getSpillTableDesc(alias,spillTableDesc,conf, noFilter);
    AbstractSerDe serde = JoinUtil.getSpillSerDe(alias, spillTableDesc, conf, noFilter);

    if (serde == null) {
      containerSize = -1;
    }

    RowContainer<List<Object>> rc = new RowContainer<List<Object>>(containerSize, hconf, reporter);
    StructObjectInspector rcOI = null;
    if (tblDesc != null) {
      // arbitrary column names used internally for serializing to spill table
      List<String> colNames = Utilities.getColumnNames(tblDesc.getProperties());
      // object inspector for serializing input tuples
      rcOI = ObjectInspectorFactory.getStandardStructObjectInspector(colNames,
          structFieldObjectInspectors);
    }

    rc.setSerDe(serde, rcOI);
    rc.setTableDesc(tblDesc);
    return rc;
  }

  private static String KEY_FIELD_PREFIX = (Utilities.ReduceField.KEY + ".").toLowerCase();
  private static String VALUE_FIELD_PREFIX = (Utilities.ReduceField.VALUE + ".").toLowerCase();

  /**
   * Create a new struct object inspector for the list of struct fields, first removing the
   * prefix from the field name.
   * @param fields
   * @param prefixToRemove
   * @return
   */
  private static ObjectInspector createStructFromFields(List<StructField> fields, String prefixToRemove) {
    int prefixLength = prefixToRemove.length() + 1; // also remove the '.' after the prefix
    ArrayList<String> fieldNames = new ArrayList<String>();
    ArrayList<ObjectInspector> fieldOIs = new ArrayList<ObjectInspector>();
    for (StructField field : fields) {
      fieldNames.add(field.getFieldName().substring(prefixLength));
      fieldOIs.add(field.getFieldObjectInspector());
    }
    return ObjectInspectorFactory.getStandardStructObjectInspector(fieldNames, fieldOIs);
  }

  /**
   * Checks the input object inspector to see if it is in for form of a flattened struct
   * like the ones generated by a vectorized reduce sink input:
   *   { 'key.reducesinkkey0':int, 'value._col0':int, 'value._col1':int, .. }
   * If so, then it creates an "unflattened" struct that contains nested key/value
   * structs:
   *   { key: { reducesinkkey0:int }, value: { _col0:int, _col1:int, .. } }
   *
   * @param oi
   * @return unflattened object inspector if unflattening is needed,
   *         otherwise the original object inspector
   */
  private static ObjectInspector unflattenObjInspector(ObjectInspector oi) {
    if (oi instanceof StructObjectInspector) {
      // Check if all fields start with "key." or "value."
      // If so, then unflatten by adding an additional level of nested key and value structs
      // Example: { "key.reducesinkkey0":int, "key.reducesinkkey1": int, "value._col6":int }
      // Becomes
      //   { "key": { "reducesinkkey0":int, "reducesinkkey1":int }, "value": { "_col6":int } }
      ArrayList<StructField> keyFields = new ArrayList<StructField>();
      ArrayList<StructField> valueFields = new ArrayList<StructField>();
      for (StructField field : ((StructObjectInspector) oi).getAllStructFieldRefs()) {
        String fieldNameLower = field.getFieldName().toLowerCase();
        if (fieldNameLower.startsWith(KEY_FIELD_PREFIX)) {
          keyFields.add(field);
        } else if (fieldNameLower.startsWith(VALUE_FIELD_PREFIX)) {
          valueFields.add(field);
        } else {
          // Not a flattened struct, no need to unflatten
          return oi;
        }
      }

      // All field names are of the form "key." or "value."
      // Create key/value structs and add the respective fields to each one
      ArrayList<ObjectInspector> reduceFieldOIs = new ArrayList<ObjectInspector>();
      reduceFieldOIs.add(createStructFromFields(keyFields, Utilities.ReduceField.KEY.toString()));
      reduceFieldOIs.add(createStructFromFields(valueFields, Utilities.ReduceField.VALUE.toString()));

      // Finally create the outer struct to contain the key, value structs
      return ObjectInspectorFactory.getStandardStructObjectInspector(
          Utilities.reduceFieldNameList,
          reduceFieldOIs);
    }

    return oi;
  }
}


text:
"""Helper functions for a git build."""
from __future__ import absolute_import
from __future__ import print_function
import re
import os
import errno

from .error import Error, GitError
from . import utils
from . import constants

def is_git(package_dir):
    """Determine whether a given directory is part of a git repo."""
    # If package_dir is a URL, not a directory, then we can't cd into it to
    # check. Assume False for now.
    if utils.is_url(package_dir):
        return False
    # TODO: Allow specifying a git URL to build from.
    pwd = os.getcwd()
    try:
        try:
            os.chdir(package_dir)
        except OSError as ose:
            if ose.errno == errno.ENOENT:
                raise Error("%s is not a valid package directory\n(%s)" % (package_dir, ose))
        command = ["git", "status", "--porcelain"]
        try:
            err = utils.sbacktick(command, err2out=True)[1]
        except OSError as ose:
            if ose.errno != errno.ENOENT:
                raise
            err = 1
        if err:
            return False
    finally:
        os.chdir(pwd)
    return True

def get_branch(package_dir):
    """Return the current git branch for a given directory."""
    top_dir = os.path.split(os.path.abspath(package_dir))[0]
    command = ["git", "--work-tree", top_dir, "--git-dir", os.path.join(top_dir, ".git"), "branch"]
    out, err = utils.sbacktick(command, err2out=True)
    if err:
        raise GitError("Exit code %d getting git branch for directory %s.  Output:\n%s" % (err, package_dir, out))
    out = out.strip()
    if not out:
        raise GitError("'git branch' returned no output.")
    return out.split()[-1]

def get_known_remote(package_dir):
    """Return the first remote in the current directory's list of remotes which
       is on osg-build's configured whitelist of remotes."""
    top_dir = os.path.split(os.path.abspath(package_dir))[0]
    command = ["git", "--work-tree", top_dir, "--git-dir", os.path.join(top_dir, ".git"), "remote", "-v"]
    out, err = utils.sbacktick(command, err2out=True)
    if err:
        raise GitError("Exit code %d getting git status for directory %s. Output:\n%s" % (err, package_dir, out))
    for line in out.splitlines():
        info = line.strip().split()
        if len(info) != 3:
            continue
        if info[2] != '(fetch)':
            continue
        if info[1] in constants.KNOWN_GIT_REMOTES:
            return info[0], info[1]
    raise GitError("OSG remote not found for directory %s; are remotes configurated correctly?" % package_dir)

def get_fetch_url(package_dir, remote):
    """Return a fetch url
       is on osg-build's configured whitelist of remotes."""
    top_dir = os.path.split(os.path.abspath(package_dir))[0]
    command = ["git", "--work-tree", top_dir, "--git-dir", os.path.join(top_dir, ".git"), "remote", "-v"]
    out, err = utils.sbacktick(command, err2out=True)
    if err:
        raise GitError("Exit code %d getting git status for directory %s. Output:\n%s" % (err, package_dir, out))
    for line in out.splitlines():
        info = line.strip().split()
        if len(info) != 3:
            continue
        if info[2] != '(fetch)':
            continue
        if info[0] == remote:
            return constants.GIT_REMOTE_MAPS.setdefault(info[1], info[1])

    raise GitError("Remote URL not found for remote %s in directory %s; are remotes " \
        "configured correctly?" % (remote, package_dir))

def get_current_branch_remote(package_dir):
    """Return the configured remote for the current branch."""
    branch = get_branch(package_dir)

    top_dir = os.path.split(os.path.abspath(package_dir))[0]
    command = ["git", "--work-tree", top_dir, "--git-dir", os.path.join(top_dir, ".git"),
               "config", "branch.%s.remote" % branch]
    out, err = utils.sbacktick(command, err2out=True)
    if err:
        raise GitError("Exit code %d getting git branch %s remote for directory '%s'. Output:\n%s" % \
                       (err, branch, package_dir, out))

    return out.strip()

def is_uncommitted(package_dir):
    """Return True if there are uncommitted changes or files in the git working dir."""
    top_dir = os.path.split(os.path.abspath(package_dir))[0]
    command = ["git", "--work-tree", top_dir, "--git-dir", os.path.join(top_dir, ".git"), "status", "--porcelain"]
    out, err = utils.sbacktick(command, err2out=True)
    if err:
        raise GitError("Exit code %d getting git status for directory %s. Output:\n%s" % (err, package_dir, out))
    if out:
        print("The following uncommitted changes exist:")
        print(out)
        print("Please commit these first.")
        return True

    remote = get_current_branch_remote(package_dir)

    branch = get_branch(package_dir)
    branch_ref = "refs/heads/%s" % branch
    origin_ref = "refs/remotes/%s/%s" % (remote, branch)

    command = ["git", "--work-tree", top_dir, "--git-dir", os.path.join(top_dir, ".git"), "show-ref"]
    out, err = utils.sbacktick(command, err2out=True)
    if err:
        raise GitError("Exit code %d getting git references for directory %s.  Output:\n%s" % (err, package_dir, out))
    branch_hash = ''
    origin_hash = ''
    for line in out.splitlines():
        info = line.split()
        if len(info) != 2:
            continue
        if info[1] == branch_ref:
            branch_hash = info[0]
        if info[1] == origin_ref:
            origin_hash = info[0]

    if not branch_hash and not origin_hash:
        raise GitError("Could not find either local or remote hash for directory %s." % package_dir)
    if branch_hash != origin_hash:
        raise GitError("Local hash (%s) does not match remote hash "
            "(%s) for directory %s.  Perhaps you need to perform 'git push'?" % \
            (branch_hash, origin_hash, package_dir))

    return False

def is_outdated(package_dir):
    """Return True if the package has been changed since the revision in the
    local git repo.

    """
    remote = get_current_branch_remote(package_dir)
    branch = get_branch(package_dir)
    branch_ref = "refs/heads/%s" % branch
    branch_hash = ''

    top_dir = os.path.split(os.path.abspath(package_dir))[0]
    command = ["git", "--work-tree", top_dir, "--git-dir", os.path.join(top_dir, ".git"), "show-ref"]
    out, err = utils.sbacktick(command, err2out=True)
    if err:
        raise GitError("Exit code %d getting git references for directory %s.  Output:\n%s" % (err, package_dir, out))
    for line in out.splitlines():
        info = line.strip().split()
        if len(info) != 2:
            continue
        if info[1] == branch_ref:
            branch_hash = info[0]
            break
    if not branch_hash:
        raise GitError("Unable to determine local branch's hash.")

    out, err = utils.sbacktick(["git", "--work-tree", top_dir, "--git-dir", os.path.join(top_dir, ".git"),
                                "ls-remote", "--heads", remote])
    if err:
        raise GitError("Exit code %d getting remote git status for directory %s. Output:\n%s" % (err, package_dir, out))

    remote_hash = ''
    for line in out.splitlines():
        info = line.strip().split()
        if len(info) != 2:
            continue
        if info[1] == branch_ref:
            remote_hash = info[0]
            break
    if not remote_hash:
        raise GitError("Unable to determine remote branch's hash.")

    if remote_hash == branch_hash:
        return False

    print("Remote hash (%s) does not match local hash (%s) for branch %s." % (remote_hash, branch_hash, branch))
    return True

def verify_working_dir(pkg):
    """Verify if a package working directory has uncommitted changes or is
    outdated and ask the user what to do. Return True if it's ok to continue.

    """
    if is_uncommitted(pkg):
        if not utils.ask_yn("""\
Package working directory %s has uncommitted changes that will not be included
in the git build.
Continue (yes/no)?""" % pkg):
            return False
    if is_outdated(pkg):
        if not utils.ask_yn("""\
Package working directory %s is out of date and its contents may not reflect
what will be built.
Continue (yes/no)?""" % pkg):
            return False
    return True

def verify_package_dir(package_dir):
    """Check if package_dir points to a valid package dir (i.e. contains
    at least an osg/ dir or an upstream/ dir) and is in a git repo.
    """
    top_dir = os.path.split(os.path.abspath(package_dir))[0]
    command = ["git", "--work-tree", top_dir, "--git-dir", os.path.join(top_dir, ".git"),
               "rev-parse", "--show-toplevel"]
    out, err = utils.sbacktick(command, err2out=True)
    if err:
        raise GitError("Exit code %d getting git top-level directory of %s. Output:\n%s" % (err, package_dir, out))
    if top_dir != out.strip():
        raise GitError("Specified package directory (%s) is not a top-level directory in the git repo (%s)." % \
                       (package_dir, top_dir))
    command = ["git", "--work-tree", top_dir, "--git-dir", os.path.join(top_dir, ".git"), "ls-files", "osg", "upstream"]
    out, err = utils.sbacktick(command, err2out=True)
    if err:
        raise GitError("Exit code %d getting git subdirectories of %s. Output:\n%s" % (err, package_dir, out))
    for line in out.split("\n"):
        if line.startswith('osg/') or line.startswith('upstream/'):
            return True
    return False

def verify_git_svn_commit(package_dir):
    """Verify the last commit in the git repo actually came from git-svn."""
    top_dir = os.path.split(os.path.abspath(package_dir))[0]
    command = ["git", "--work-tree", top_dir, "--git-dir", os.path.join(top_dir, ".git"), "log", "-n", "1"]
    out, err = utils.sbacktick(command, err2out=True)
    if err:
        raise GitError("Exit code %d getting git log for directory %s. Output:\n%s" % (err, package_dir, out))

    for line in out.splitlines():
        if line.find("git-svn-id:") >= 0:
            return

    raise GitError("Last git commit not from SVN - possible inconsistency between git and SVN!")

def verify_correct_remote(package_dir):
    """Verify the current branch remote is one of the known remotes."""
    remote = get_current_branch_remote(package_dir)
    known_remote = get_known_remote(package_dir)[0]
    if remote != known_remote:
        raise GitError("Remote %s for directory %s is not an officially known remote." % (remote, package_dir))

def verify_correct_branch(package_dir, buildopts):
    """Check that the user is not trying to build from trunk into upcoming, or
    vice versa.
    """
    branch = get_branch(package_dir)
    remote = get_known_remote(package_dir)[1]

    verify_correct_remote(package_dir)

    # We only have branching rules for OSG and HCC repos
    if remote not in constants.KNOWN_GIT_REMOTES:
        return

    if remote in [constants.OSG_REMOTE, constants.OSG_AUTH_REMOTE]:
        verify_git_svn_commit(package_dir)

    for dver in buildopts['enabled_dvers']:
        target = buildopts['targetopts_by_dver'][dver]['koji_target']
        if target.startswith("hcc-"):
            if "master" not in branch:
                raise Error("""\
Error: Incorrect branch for koji build
Only allowed to build into the HCC repo from the
master branch!  You must switch branches.""")
            if remote not in [constants.HCC_REMOTE, constants.HCC_AUTH_REMOTE]:
                raise Error("""\
Error: You must build into the HCC repo when building from
a HCC git checkout.  You must switch git repos or build targets.""")
        elif re.search(r"osg(?:-\d+\.\d+)?-upcoming$", target):
            if remote not in [constants.OSG_REMOTE, constants.OSG_AUTH_REMOTE]:
                raise Error("""\
Error: You may not build into the OSG repo when building from
a non-OSG target.  You must switch git repos or build targets.
Try adding "--repo=hcc" to the command line.""")
            if "master" in branch:
                raise Error("""\
Error: Incorrect branch for koji build
Not allowed to build into the upcoming targets from
master branch!  You must switch branches or build targets.""")
        elif "osg" in target:
            if remote not in [constants.OSG_REMOTE, constants.OSG_AUTH_REMOTE]:
                raise Error("""\
Error: You may not build into the OSG repo when building from
a non-OSG target.  You must switch git repos or build targets.
Try adding "--repo=hcc" to the command line.""")
            if "upcoming" in branch:
                raise Error("""\
Error: Incorrect branch for koji build
Only allowed to build packages from one of the upcoming branches
into the upcoming targets.  Either switch the branch to master,
 or pass the appropriate --upcoming or --3.X-upcoming flag.""")

def koji(package_dir, koji_obj, buildopts):
    """koji task with a git build."""
    package_dir = os.path.abspath(package_dir)
    verify_package_dir(package_dir)
    package_name = os.path.basename(package_dir)
    if not re.match(r"\w+", package_name): # sanity check
        raise Error("Package directory '%s' gives invalid package name '%s'" % (package_dir, package_name))
    if not buildopts.get('scratch'):
        koji_obj.add_pkg(package_name)

    remote = get_fetch_url(package_dir, get_known_remote(package_dir)[0])
    top_dir = os.path.split(os.path.abspath(package_dir))[0]
    command = ["git", "--work-tree", top_dir, "--git-dir", os.path.join(top_dir, ".git"),
               "log", "-1", "--pretty=format:%H"]
    out, err = utils.sbacktick(command, err2out=True)
    if err:
        raise GitError("Exit code %d getting git hash for directory %s. Output:\n%s" % (err, package_dir, out))
    rev = out.strip()

    return koji_obj.build_git(remote,
                              rev,
                              package_name)


text:
<?php
/**
 * User: MReal
 * Date: 3/30/14
 * Time: 6:16 AM
 */

namespace vMReal\steamWebApi\service;

use vMReal\steamWebApi\methods\dota2\Heroes;
use vMReal\steamWebApi\methods\dota2\Rarities;

class Dota2 extends Service
{

	/**
	 * A list of heroes within Dota 2.
	 * @return Heroes
	 */
	public function getHeroes() {
		return new Heroes($this->getMediator(), 'GetHeroes', 'V001');
	}

	/**
	 * Dota 2 item rarity list.
	 * @return Rarities
	 */
	public function getRarities() {
		return new Rarities($this->getMediator(), 'GetRarities', 'V001');
	}
}


text:
package org.jboss.weld.bean.proxy;

import static org.jboss.classfilewriter.util.DescriptorUtils.isPrimitive;
import static org.jboss.classfilewriter.util.DescriptorUtils.isWide;

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.security.AccessController;
import java.util.HashSet;
import java.util.Set;

import org.jboss.classfilewriter.ClassFile;
import org.jboss.classfilewriter.ClassMethod;
import org.jboss.classfilewriter.DuplicateMemberException;
import org.jboss.classfilewriter.code.CodeAttribute;
import org.jboss.classfilewriter.util.Boxing;
import org.jboss.classfilewriter.util.DescriptorUtils;
import org.jboss.weld.annotated.enhanced.MethodSignature;
import org.jboss.weld.annotated.enhanced.jlr.MethodSignatureImpl;
import org.jboss.weld.bean.proxy.InterceptionDecorationContext.Stack;
import org.jboss.weld.exceptions.WeldException;
import org.jboss.weld.injection.InterceptionFactoryImpl;
import org.jboss.weld.logging.BeanLogger;
import org.jboss.weld.security.GetDeclaredMethodsAction;
import org.jboss.weld.util.bytecode.BytecodeUtils;
import org.jboss.weld.util.bytecode.MethodInformation;
import org.jboss.weld.util.bytecode.RuntimeMethodInformation;

/**
 * Generates proxies used to apply interceptors to custom bean instances and return values of producer methods.
 *
 * @author Martin Kouba
 *
 * @param <T>
 * @see InterceptionFactoryImpl
 */
public class InterceptedProxyFactory<T> extends ProxyFactory<T> {

    public static final String PROXY_SUFFIX = "InterceptedProxy";

    private static final String JAVA_LANG_OBJECT = "java.lang.Object";

    private final Set<MethodSignature> enhancedMethodSignatures;

    private final Set<MethodSignature> interceptedMethodSignatures;

    private final String suffix;

    public InterceptedProxyFactory(String contextId, Class<?> proxiedBeanType, Set<? extends Type> typeClosure, Set<MethodSignature> enhancedMethodSignatures,
            Set<MethodSignature> interceptedMethodSignatures, String suffix) {
        super(contextId, proxiedBeanType, typeClosure, null);
        this.enhancedMethodSignatures = enhancedMethodSignatures;
        this.interceptedMethodSignatures = interceptedMethodSignatures;
        this.suffix = suffix;
    }

    protected String getProxyNameSuffix() {
        return PROXY_SUFFIX + suffix;
    }

    @Override
    protected void addMethodsFromClass(ClassFile proxyClassType, ClassMethod staticConstructor) {
        try {

            final Set<MethodSignature> finalMethods = new HashSet<MethodSignature>();
            final Set<MethodSignature> processedBridgeMethods = new HashSet<MethodSignature>();

            // Add all methods from the class hierarchy
            Class<?> cls = getBeanType();
            while (cls != null) {
                Set<MethodSignature> declaredBridgeMethods = new HashSet<MethodSignature>();
                for (Method method : AccessController.doPrivileged(new GetDeclaredMethodsAction(cls))) {

                    final MethodSignatureImpl methodSignature = new MethodSignatureImpl(method);

                    if (isMethodAccepted(method, getProxySuperclass()) && enhancedMethodSignatures.contains(methodSignature)
                            && !finalMethods.contains(methodSignature) && !processedBridgeMethods.contains(methodSignature)) {
                        try {
                            final MethodInformation methodInfo = new RuntimeMethodInformation(method);
                            ClassMethod classMethod = proxyClassType.addMethod(method);

                            if (interceptedMethodSignatures.contains(methodSignature)) {
                                // this method is intercepted

                                final CodeAttribute b = classMethod.getCodeAttribute();

                                b.aload(0);
                                getMethodHandlerField(classMethod.getClassFile(), b);

                                // get the Stack
                                b.invokestatic(InterceptionDecorationContext.class.getName(), "getStack", "()" + DescriptorUtils.makeDescriptor(Stack.class));

                                b.aload(0);
                                DEFAULT_METHOD_RESOLVER.getDeclaredMethod(classMethod, methodInfo.getDeclaringClass(), method.getName(),
                                        methodInfo.getParameterTypes(), staticConstructor);
                                b.dup();
                                // Params
                                b.iconst(method.getParameterTypes().length);
                                b.anewarray(JAVA_LANG_OBJECT);
                                int localVariableCount = 1;
                                for (int i = 0; i < method.getParameterTypes().length; ++i) {
                                    String typeString = methodInfo.getParameterTypes()[i];
                                    b.dup(); // duplicate the array reference
                                    b.iconst(i);
                                    // load the parameter value
                                    BytecodeUtils.addLoadInstruction(b, typeString, localVariableCount);
                                    // box the parameter if necessary
                                    Boxing.boxIfNessesary(b, typeString);
                                    // and store it in the array
                                    b.aastore();
                                    if (isWide(typeString)) {
                                        localVariableCount = localVariableCount + 2;
                                    } else {
                                        localVariableCount++;
                                    }
                                }

                                b.invokeinterface(StackAwareMethodHandler.class.getName(), INVOKE_METHOD_NAME, LJAVA_LANG_OBJECT,
                                        InterceptedSubclassFactory.INVOKE_METHOD_PARAMETERS);

                                if (methodInfo.getReturnType().equals(BytecodeUtils.VOID_CLASS_DESCRIPTOR)) {
                                    b.returnInstruction();
                                } else if (isPrimitive(methodInfo.getReturnType())) {
                                    Boxing.unbox(b, classMethod.getReturnType());
                                    b.returnInstruction();
                                } else {
                                    b.checkcast(BytecodeUtils.getName(methodInfo.getReturnType()));
                                    b.returnInstruction();
                                }
                                BeanLogger.LOG.addingMethodToProxy(method);
                            } else {

                                final CodeAttribute b = classMethod.getCodeAttribute();

                                b.aload(0);
                                getMethodHandlerField(classMethod.getClassFile(), b);

                                b.aload(0);
                                DEFAULT_METHOD_RESOLVER.getDeclaredMethod(classMethod, methodInfo.getDeclaringClass(), method.getName(),
                                        methodInfo.getParameterTypes(), staticConstructor);
                                b.aconstNull();

                                b.iconst(method.getParameterTypes().length);
                                b.anewarray(JAVA_LANG_OBJECT);

                                int localVariableCount = 1;

                                for (int i = 0; i < method.getParameterTypes().length; ++i) {
                                    String typeString = methodInfo.getParameterTypes()[i];
                                    b.dup(); // duplicate the array reference
                                    b.iconst(i);
                                    // load the parameter value
                                    BytecodeUtils.addLoadInstruction(b, typeString, localVariableCount);
                                    // box the parameter if necessary
                                    Boxing.boxIfNessesary(b, typeString);
                                    // and store it in the array
                                    b.aastore();
                                    if (isWide(typeString)) {
                                        localVariableCount = localVariableCount + 2;
                                    } else {
                                        localVariableCount++;
                                    }
                                }

                                b.invokeinterface(MethodHandler.class.getName(), INVOKE_METHOD_NAME, LJAVA_LANG_OBJECT,
                                        new String[] { LJAVA_LANG_OBJECT, LJAVA_LANG_REFLECT_METHOD, LJAVA_LANG_REFLECT_METHOD, "[" + LJAVA_LANG_OBJECT });

                                if (methodInfo.getReturnType().equals(BytecodeUtils.VOID_CLASS_DESCRIPTOR)) {
                                    b.returnInstruction();
                                } else if (isPrimitive(methodInfo.getReturnType())) {
                                    Boxing.unbox(b, classMethod.getReturnType());
                                    b.returnInstruction();
                                } else {
                                    b.checkcast(BytecodeUtils.getName(methodInfo.getReturnType()));
                                    b.returnInstruction();
                                }
                            }

                        } catch (DuplicateMemberException e) {
                            // do nothing. This will happen if superclass methods have
                            // been overridden
                        }
                    } else {
                        if (Modifier.isFinal(method.getModifiers())) {
                            finalMethods.add(methodSignature);
                        }
                        if (method.isBridge()) {
                            declaredBridgeMethods.add(methodSignature);
                        }
                    }
                }
                processedBridgeMethods.addAll(declaredBridgeMethods);
                cls = cls.getSuperclass();
            }
        } catch (Exception e) {
            throw new WeldException(e);
        }
    }

    @Override
    protected boolean isMethodAccepted(Method method, Class<?> proxySuperclass) {
        return super.isMethodAccepted(method, proxySuperclass) && CommonProxiedMethodFilters.NON_PRIVATE.accept(method, proxySuperclass) && !method.isBridge();
    }

}


text:
package core

import (
	"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/oci/oci-go-sdk/v43/common"
	"net/http"
)

// ListFastConnectProviderVirtualCircuitBandwidthShapesRequest wrapper for the ListFastConnectProviderVirtualCircuitBandwidthShapes operation
//
// # See also
//
// Click https://docs.cloud.oracle.com/en-us/iaas/tools/go-sdk-examples/latest/core/ListFastConnectProviderVirtualCircuitBandwidthShapes.go.html to see an example of how to use ListFastConnectProviderVirtualCircuitBandwidthShapesRequest.
type ListFastConnectProviderVirtualCircuitBandwidthShapesRequest struct {

	// The OCID (https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm) of the provider service.
	ProviderServiceId *string `mandatory:"true" contributesTo:"path" name:"providerServiceId"`

	// For list pagination. The maximum number of results per page, or items to return in a paginated
	// "List" call. For important details about how pagination works, see
	// List Pagination (https://docs.cloud.oracle.com/iaas/Content/API/Concepts/usingapi.htm#nine).
	// Example: `50`
	Limit *int `mandatory:"false" contributesTo:"query" name:"limit"`

	// For list pagination. The value of the `opc-next-page` response header from the previous "List"
	// call. For important details about how pagination works, see
	// List Pagination (https://docs.cloud.oracle.com/iaas/Content/API/Concepts/usingapi.htm#nine).
	Page *string `mandatory:"false" contributesTo:"query" name:"page"`

	// Unique Oracle-assigned identifier for the request.
	// If you need to contact Oracle about a particular request, please provide the request ID.
	OpcRequestId *string `mandatory:"false" contributesTo:"header" name:"opc-request-id"`

	// Metadata about the request. This information will not be transmitted to the service, but
	// represents information that the SDK will consume to drive retry behavior.
	RequestMetadata common.RequestMetadata
}

func (request ListFastConnectProviderVirtualCircuitBandwidthShapesRequest) String() string {
	return common.PointerString(request)
}

// HTTPRequest implements the OCIRequest interface
func (request ListFastConnectProviderVirtualCircuitBandwidthShapesRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser) (http.Request, error) {

	return common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)
}

// BinaryRequestBody implements the OCIRequest interface
func (request ListFastConnectProviderVirtualCircuitBandwidthShapesRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {

	return nil, false

}

// RetryPolicy implements the OCIRetryableRequest interface. This retrieves the specified retry policy.
func (request ListFastConnectProviderVirtualCircuitBandwidthShapesRequest) RetryPolicy() *common.RetryPolicy {
	return request.RequestMetadata.RetryPolicy
}

// ListFastConnectProviderVirtualCircuitBandwidthShapesResponse wrapper for the ListFastConnectProviderVirtualCircuitBandwidthShapes operation
type ListFastConnectProviderVirtualCircuitBandwidthShapesResponse struct {

	// The underlying http response
	RawResponse *http.Response

	// A list of []VirtualCircuitBandwidthShape instances
	Items []VirtualCircuitBandwidthShape `presentIn:"body"`

	// For list pagination. When this header appears in the response, additional pages
	// of results remain. For important details about how pagination works, see
	// List Pagination (https://docs.cloud.oracle.com/iaas/Content/API/Concepts/usingapi.htm#nine).
	OpcNextPage *string `presentIn:"header" name:"opc-next-page"`

	// Unique Oracle-assigned identifier for the request. If you need to contact
	// Oracle about a particular request, please provide the request ID.
	OpcRequestId *string `presentIn:"header" name:"opc-request-id"`
}

func (response ListFastConnectProviderVirtualCircuitBandwidthShapesResponse) String() string {
	return common.PointerString(response)
}

// HTTPResponse implements the OCIResponse interface
func (response ListFastConnectProviderVirtualCircuitBandwidthShapesResponse) HTTPResponse() *http.Response {
	return response.RawResponse
}


text:
package de.oliver_heger.linedj.extract.id3.model

import de.oliver_heger.linedj.extract.metadata.MetaDataProvider

/**
  * An implementation of the ''ID3TagProvider'' trait based on an ID3v2 frame.
  *
  * This class is passed a sequence with tag names and an underlying
  * [[ID3Frame]] object at construction time. The access methods for specific
  * tags defined by the ''MetaDataProvider'' trait are simply mapped to tag
  * names in the sequence.
  *
  * Note: This class is used internally only, therefore it does not implement
  * sophisticated parameter checks.
  *
  * @param frame    the underlying ID3v2 frame
  * @param tagNames the tag names corresponding to the specific access methods
  */
private class ID3v2TagProvider(val frame: ID3Frame, tagNames: IndexedSeq[String])
  extends MetaDataProvider {
  def title: Option[String] = get(0)

  def artist: Option[String] = get(1)

  def album: Option[String] = get(2)

  def inceptionYearString: Option[String] = get(3)

  def trackNoString: Option[String] = get(4)

  /**
    * Obtains the value of the tag with the given index in the array of tag
    * names.
    *
    * @param idx the index
    * @return an option with the value of this tag
    */
  private def get(idx: Int): Option[String] =
    frame.tags.get(tagNames(idx)) map (_.asString)
}


text:
string(REPLACE "\"" "" qhp ${QHP_FILE})
string(REPLACE "\"" "" stripped ${STRIPPED_FILE})

file(STRINGS ${qhp} seclines REGEX "<section.*ref=\"docpage-.*./>")
string(REGEX REPLACE ";" "\n" newSecLines "${seclines}")

file(STRINGS ${qhp} docFilelines REGEX "<file>docpage-.*html</file>")
string(REGEX REPLACE ";" "\n" newDocFilelines "${docFilelines}")

file(STRINGS ${qhp} filelines REGEX "<file>.*\\.(css|png|jpeg|jpg)</file>")
string(REGEX REPLACE ";" "\n" newFilelines "${filelines}")

file(STRINGS ${qhp} namespacelines REGEX "<namespace>.*</namespace>")
string(REGEX REPLACE ";" "\n" newNamespacelines "${namespacelines}")

set(file "\
<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<QtHelpProject version=\"1.0\">
${newNamespacelines}
  <virtualFolder>doc</virtualFolder>
  <filterSection>
    <filterAttribute>doxygen</filterAttribute>
    <toc>
${newSecLines}
    </toc>
    <keywords>
    </keywords>
    <files>
${newDocFilelines}
${newFilelines}
    </files>
  </filterSection>
</QtHelpProject>
")

file(WRITE ${stripped} ${file})