text:
layout: page
title: G(k) Space
navigation: 4
---

## Basics

The Euclidean geometric algebra Gₖ space is the basic space of this project. The main operations of the space, that is, the _Clifford_ or _geometric_ product, the _inner_, _outer_ and _scalar_ products, the _reverse_, _dual_, _projection_ and _rejection_ of elements of this space are programmed and ready for use.

To create an element of this space is necessary to call the ___types___ which have only elements of type ```kbasis``` in their composition, that is, the elements of the _type_ ```kbasis``` itself, the ```kmultvec``` and the ```kblade``` _types_.

## Functions and Operations

Here we will give an explanation of how each _function_ works, in terms of what is taken as the _input_ parameter and what the _function_ will return, so that some detailed examples are given later in order to simplify the understanding of the program and avoid possible mistakes.

### Operations

#### Geometric Product - ```geoprod(a,b)``` or ```a ∘ b```

As in the literature, the _Clifford_ or _geometric product_ is the main operation of the space, and is the basis for most of the other operations. It takes two elements of the _type_ ```kbasis```, ```kmultvec``` or ```kblade``` and return their _geometric product_.

     geoprod(a::kbasis, b::kbasis)
     geoprod(X::kmultvec, Y::kmultvec)
     geoprod(A::kblade, B::kblade)

To simplify the operation _input_ it can be used the base operator ```∘``` instead of call the _function_ ```geoprod```.

     Base.:∘(a::kbasis, b::kbasis)
     Base.:∘(X::kmultvec, Y::kmultvec)
     Base.:∘(A::kblade, B::kblade)

In order to obtain the _geometric product_ of elements of different _types_,as long as the operator is used, it is not necessary to convert them before . As explained above, since a generic element of _geometric algebra_ is a _multivector_, the elements of type ```kbasis``` and ```kblade``` can be converted to the _type_ ```kmultvec``` and thus can be apply the _geometric product_ operation. These conversions are done automatically when two parameters of different _types_ are used as input.

See __Examples__ section below to better understand the _input_ and _output_ of operations.

#### Inner Product - ```inner(a,b)``` or ```a ⋅ b```

The _input_ parameters for the _inner product_ are of the same _types_ as for the _geometric product_, so to obtain the _inner product_ between two elements of _type_ ```kbasis```, ```kmultvec``` or ```kblade``` just use the ```inner``` _function_.

     inner(a::kbasis, b::kbasis)
     inner(X::kmultvec, Y::kmultvec)
     inner(A::kblade, B::kblade)

As for the _geometric product_, to obtain the _inner product_ is sufficient to use a base operator, in this case, the operator ```⋅``` instead of call the ```inner``` _function_.

     Base.:⋅(a::kbasis, b::kbasis)
     Base.:⋅(X::kmultvec, Y::kmultvec)
     Base.:⋅(A::kblade, B::kblade)

#### Outer Product - ```outer(a,b)``` or ```a ^ b```

As for the _geometric_ and _inner_ products, one can use the _function_ ```outer``` to obtain the _outer product_ between two elements of _type_ ```kbasis```, ```kmultvec``` or ```kblade```.

     outer(a::kbasis, b::kbasis)
     outer(X::kmultvec, Y::kmultvec)
     outer(A::kblade, B::kblade)

The base operator that can be used instead of call the _function_ in this case is the ```^``` symbol.

     Base.:^(a::kbasis, b::kbasis)
     Base.:^(X::kmultvec, Y::kmultvec)
     Base.:^(A::kblade, B::kblade)

#### Scalar Product - ```scalar(a,b)``` or ```a * b```

The ```scalar``` _function_ is not different from the other three mentioned above, in order to obtain the _scalar product_ between two elements of _type_ ```kbasis```, ```kmultvec``` or ```kblade``` just use the _function_ ```inner```.

     outer(a::kbasis, b::kbasis)
     outer(X::kmultvec, Y::kmultvec)
     outer(A::kblade, B::kblade)

Or using the base operator ```*```.

     Base.:*(a::kbasis, b::kbasis)
     Base.:*(X::kmultvec, Y::kmultvec)
     Base.:* (A::kblade, B::kblade)

__In this operation, unlike the previous ones, the output parameter will always be of _type_ ```Number```.__

#### Sum and difference - ```mvsum(a,b)``` or ```a + b``` and ```a - b```

This _function_ has a particularity in the _type_ of _output_, since the _sum_ of two elements of _type_ ```kbasis``` will only be of _type_ ```kbasis``` if they are l.d, otherwise the output will be of _type_ ```kmultvec```.

To obtain the _sum_ of two elements of _types_ ```kbasis```,  ```kmultvec``` or ```kblade```, one can call the _function_ ```mvsum```, as well as the previous functions,

     mvsum(a::kbasis, b::kbasis)
     mvsum(X::kmultvec, Y::kmultvec)
     mvsum(A::kblade, B::kblade)

or using the base operator ```+```

     Base.:+(a::kbasis, b::kbasis)
     Base.:+(X::kmultvec, Y::kmultvec)
     Base.:+(A::kblade, B::kblade)

but, to make it easier, in addition to the base operator ```+```, it can be used the base operator ```-``` which convert the second element to its _additive inverse_.

     Base.:-(a::kbasis, b::kbasis)
     Base.:-(X::kmultvec, Y::kmultvec)
     Base.:-(A::kblade, B::kblade)

thus obtaining the _difference_ between the two elements.

### Functions

#### Grade - ```grade(a)```

The _grade_ _function_ take as _input_ an element of the _type_ ```kbasis``` and return its grade which is an element of the _type_ ```Int```, it's used more as an auxiliary _function_.

     grade(a::kbasis)

#### Dual - ```dual(a)```

The _dual_ _function_, as the name suggests, returns its dual element, taking as _input_ elements of _types_ ```kbasis```,  ```kmultvec``` or ```kblade```.

     dual(a::kbasis)
     dual(X::kmultvec)
     dual(A::kblade)

As for the _products_ and _sum_, in case the _input_ of the ```kblade``` the _output_ will be of the _type_ ```kmultvec```.

#### Reverse - ```mvreverse(a)```

Returns the _reverse_ of the _input_ element, but, unlike other _functions_, this will always return an element of the same _input type_, being it ```kbasis```,  ```kmultvec``` or ```kblade```.

     mvreverse(a::kbasis)
     mvreverse(X::kmultvec)
     mvreverse(A::kblade)

The conjugation _function_ isn't necessary in Gₖ space, since its depends of negative grade.

#### Magnitude

The _magnitude function_ receives as _input_ an element of type ```kbasis```,  ```kmultvec``` or ```kblade``` and returns its magnitude of the _type_ ```Ǹumber```.

     magnitude(a::kbasis)
     magnitude(X::kmultvec)
     magnitude(A::kblade)

### Special functions

In this space, some _functions_ will work only with elements of the _type_ ```kblade```, one being the _inversion function_ and the other two depending on the first one, since not every multivector of Gₖ has inverse with respect to the _geometric product_.

#### Inversion

This _function_ returns the _inverse_ element of the _input_ with respect to the _geometric product_.

     inverse(A::kblade)

The _output type_ will also be ```kblade```.

#### Projection

The _projection_ is a simple _function_ that depends on two elements of the _type_ ```kblade```

     projection(A::kblade, N::kblade)

and it returns, in this case, the _projection_ of ```A``` onto ```N```, which will be an element of the _type_ ```kmultvec```.

#### Rejection

The _rejection function_ also receives two elements of the _type_ ```kblade``` as input

     rejection(A::kblade, N::kblade)

and, as for the _projection_, it returns an element of the _type_ ```kmultvec``` which will be the _rejection_ of the ```kblade``` ```A``` from the ```kblade```  ```N```.

## Examples

All of the following examples are based on ```layout(3)```, that is, the space generated will be G₃ depending on the objects ```id```, ```e1```, ```e2```, ```e3```, ```e12```, ```e13```, ```e23``` and ```e123```, however everything follows in the same way for other dimensions.

#### Grade

The grade _function_ is the most basic of them, as mentioned above, it's used more like an auxiliary _function_ for the other and it returns the grade of a ```kbasis``` element as follows:

     grade(kbasis(e12, 1.0))

it returns

     2

which is the grade of ```e12```.

Another way to do this is by calling the element before the _function_

     a = kbasis(e123, -2.3)

and then use the grade _function_

     grade(a)

and it returns

     3

which is the grade of ```-2.3e123```.

#### Geometric, inner, outer and scalar products

The _geometric, inner and outer products_ in case the _input_ elements are of _type_ ```kd``` or ```kmultvec```, will always return the same type, even if the result is a _scalar_ or a _basis blade_, that is, if the following elements are called:

     a = kbasis(e3, 2.0)
     b = kbasis(e12, -1.0)
     c = kbasis(id, 0.0)
     d = kbasis(e123)

when operated, for example

     geoprod(a, b)

it returns

     -2.0e123

which is a ```kbasis``` element, although when operated

     inner(a, b)

it returns

     0.0

this element is seen as an object of _type_ ```kbasis```.
Note that if a second parameter is not placed when called the ```kbasis``` type it will be generated with the scalar 1.0.

As mentioned before, we can use the base operators ```∘```, ```⋅``` and ```^``` to calculate these products instead of call the functions

     a ^ c

will return

     0.0

and

     b ⋅ d

will return

     e3

The same is true if the input is of the type kmultvec as follows:

     X = kmultvec([kbasis(e12,2.0),kbasis(e123,-1.5),kbasis(e3,4.0)])
     Y = kmultvec([a, b, kbasis(id, 2.0)])
     Z = kmultvec(d)

which will generate the respective elements

     2.0e12 + -1.5e123 + 4.0e3
     2.0e3 + -1.0e12 + 2.0
     e123

and these can be operated in the same way as the previous ones

     X ∘ Y
     Y ⋅ Z
     Y ^ Z

will return respectively

     -3.0e123 + e12 + 10.0 + 6.5e3
     2.0e12 + e3 + 2.0e123
     2.0e123

Now, in the case of ```kblade``` _type_, everything follows like the previous cases, the difference is in the _output_ of the _function_. For example, if we call the following ```kblade``` elements

     A = kblade([kmultvec([kbasis(e1)]), kmultvec([kbasis(e2)]), kmultvec([kbasis(e3)])])
     B = kblade([kmultvec([kbasis(e1, 2.0), a]), kmultvec([kbasis(e1, 3.0)])])
     C = kblade([kmultvec(a)])

which created the respective elements

     (e1)∧(e2)∧(e3)
     (2.0e1 + 2.0e3)∧(3.0e1)
     (2.0e3)

and then

     A ⋅ B

returns an element of the _type_  ```kmultvec```, which in this case is

     -6.0e2

the same will happen for the other operations

     B ^ C

returns

     0.0

and

     B ∘ C

returns

     -12.0e1

The _scalar product_ follows a different rule, in all cases the _output_ will always be of _Number_. For example, if we want to calculate the _scalar product_ between the ```kbasis``` element ```d``` and the ```kblade``` ```A``` previously called simply do as follows:

     d * A

and it returns

     -1.00

remember that this is an element of _type_ ```Number```.

You can operate any other elements of _types_ ```kbasis```, ```kmultvec``` and ```kblade```,

     a * a
     b * X
     B * B
     X * A

it will return

     4.00
     2.00
     -36.0
     1.50

respectively.

#### Sum and difference

The _mvsum_ operation works in the same way as the previous ones with respect to the _input_ parameters, the difference is in the _output_ parameters, which in the case of the _sum_ of elements of the _type_ ```kbasis``` the _output_ there are two possible _outputs_

     mvsum(kbasis(e23, 2.3), kbasis(e23, 2.7))

in this case, it may be noted that the parameter ```e23``` is used in the construction of both _inputs_, then the it returns

     5.0e23

which is of the _type_ ```kbasis```, however, if we calculate the following sum

     a + b

it returns

     2.0e3 + -e12

which is of the _type_ ```kmultvec```, remembering that ```a``` and ```b``` are the elements ```kbasis(e3, 2.0)``` and ```kbasis(e12, -1.0)``` called above.

Other than that, the rest follows as before

     A + B
     X - C
     d + Y
     a + d

will return the respective _output_

     e123 + -6.0e13
     2.0e12 + -1.5e123 + 2.0e3
     e123 + -2.0e3 + -e12 + 2.0
     -2.0e3 + e123

Note that here we can use either the base operator ```+``` or ```-```.

Again, the _output_ when applied the _sum_ and the _difference_  between elements of the _type_ ```kblade``` will be of the _type_ ```kmultvec```.

#### Dual

The _dual function_ returns the dual of the _input_ element as follows

     dual(a)
     dual(X)
     dual(A)

will return

     2.0e12
     2.0e3 + -1.5 + -4.0e12
     1.0

As for the previous operations, except for the _scalar product_, in case the _input_ is of _type_ ```kblade``` the _output_ will be of _type_ ```kmultvec```.

#### Reverse

Unlike other _functions_ and _operations_ the _mvreverse_ function returns an element of the same _type_ as the _input_, be it ```kbasis```, ```kmultvec``` or ```kblade```

     mvreverse(a)
     mvreverse(X)
     mvreverse(A)

will return

     -2.0e3
     -2.0e12 + 1.5e123 + 4.0e3
     (e3)∧(e2)∧(e1)

respectively.

#### Magnitude

The _magnitude_ in Gₖ is nothing more than the square root of the _scalar product_ of an element by its reverse, so it is, like the scalar product, always returns an element of _type_ ```Number```. For example,

     magnitude(a)
     magnitude(X)
     magnitude(A)

returns the elements

     2.00
     4.71…
     1.00

which are both of _type_ ```Number```.

#### Inversion

This is one of the three special functions, since it can only be used with ```kblade``` as input parameter,

     inverse(A)
     inverse(B)
     inverse(C)

it returns the inverse elements of ```A```,```B``` and ```C```,

     (e3)∧(e2)∧(e1)
     (0.08333333333333333e1)∧(2.0e1 + -2.0e3)
     (-0.5e3)

we can test the function using the _geometric product_ of a ```kblade``` by its _inverse_, and it should return 1.0

     B ∘ inverse(B)

will return as expected

     1.0

Note that as mentioned when dealing with the _geometric product_, this is a element of _type_ ```kmultvec```

#### Projection

This function depends on the _inversion_, so it can also only be used with elements of _type_ ```kblades``` as _input_. For example,

     projection(A, B)
     projection(B, A)
     projection(A, C)

will return

     e123
     6.0e13
     e123

these _output_ elements are of _type_ ```kmultvec```

#### Rejection

Like the above functions, the rejection receives an element of _type_ ```kblade``` and returns an element of _type_ ```kmultvec``` which is the _rejection_ of the first _input_ parameter from the second.

     rejection(B, kblade([kmultvec(kbasis(e2))]))

will return

     6.0e13

which is the difference between the ```kblade``` ```B``` and the projection ```rejection(B, kblade([kmultvec(kbasis(e2))]))```.


text:
Thu Aug 27 15:43:48 2015  Aaron Patterson <tenderlove@ruby-lang.org>

	* Tempfiles are automatically closed in the case that there were too
	many posted.

Mon Aug 24 18:05:23 2015  Aaron Patterson <tenderlove@ruby-lang.org>

	* Introduce Util.get_byte_ranges that will parse the value of the
	HTTP_RANGE string passed to it without depending on the `env` hash.
	`byte_ranges` is deprecated in favor of this method.

Sat Aug 22 17:49:49 2015  Aaron Patterson <tenderlove@ruby-lang.org>

	* Change Session internals to use Request objects for looking up
	session information. This allows us to only allocate one request
	object when dealing with session objects (rather than doing it every
	time we need to manipulate cookies, etc).

Fri Aug 21 16:30:51 2015  Aaron Patterson <tenderlove@ruby-lang.org>

	* Add `Rack::Request#initialize_copy` so that the env is duped when
	the request gets duped.

Thu Aug 20 16:20:58 2015  Aaron Patterson <tenderlove@ruby-lang.org>

	* Added methods for manipulating request specific data.  This includes
	data set as CGI parameters, and just any arbitrary data the user wants
	to associate with a particular request.  New methods:

	  * Rack::Request#get_header
	  * Rack::Request#set_header
	  * Rack::Request#has_header?
	  * Rack::Request#each_header

Thu Jun 18 16:00:05 2015  Aaron Patterson <tenderlove@ruby-lang.org>

	*  lib/rack/utils.rb: add a method for constructing "delete" cookie
	headers.  This allows us to construct cookie headers without depending
	on the side effects of mutating a hash.

Fri Jun 12 11:37:41 2015  Aaron Patterson <tenderlove@ruby-lang.org>

	* Prevent extremely deep parameters from being parsed. CVE-2015-3225

### May 6th, 2015, Thirty seventh public release 1.6.1
  - Fix CVE-2014-9490, denial of service attack in OkJson ([8cd610](https://github.com/rack/rack/commit/8cd61062954f70e0a03e2855704e95ff4bdd4f6e))
  - Use a monotonic time for Rack::Runtime, if available ([d170b2](https://github.com/rack/rack/commit/d170b2363c949dce60871f9d5a6bfc83da2bedb5))
  - RACK_MULTIPART_LIMIT changed to RACK_MULTIPART_PART_LIMIT (RACK_MULTIPART_LIMIT is deprecated and will be removed in 1.7.0) ([c096c5](https://github.com/rack/rack/commit/c096c50c00230d8eee13ad5f79ad027d9a3f3ca9))
  - See the full [git history](https://github.com/rack/rack/compare/1.6.0...1.6.1) and [milestone tag](https://github.com/rack/rack/issues?utf8=%E2%9C%93&q=milestone%3A%22Rack+1.6%22)

### May 6th, 2015, Thirty seventh public release 1.5.3
  - Fix CVE-2014-9490, denial of service attack in OkJson ([99f725](https://github.com/rack/rack/commit/99f725b583b357376ffbb7b3b042c5daa3106ad6))
  - Backport bug fixes to 1.5 series ([#585](https://github.com/rack/rack/pull/585), [#711](https://github.com/rack/rack/pull/711), [#756](https://github.com/rack/rack/pull/756))
  - See the full [git history](https://github.com/rack/rack/compare/1.5.2...1.5.3) and [milestone tag](https://github.com/rack/rack/issues?utf8=%E2%9C%93&q=milestone%3A%22Rack+1.5.3%22)

### December 18th, 2014, Thirty sixth public release 1.6.0
  - Response#unauthorized? helper ([#580](https://github.com/rack/rack/pull/580))
  - Deflater now accepts an options hash to control compression on a per-request level ([#457](https://github.com/rack/rack/pull/457))
  - Builder#warmup method for app preloading ([#617](https://github.com/rack/rack/pull/617))
  - Request#accept_language method to extract HTTP_ACCEPT_LANGUAGE ([#623](https://github.com/rack/rack/pull/623))
  - Add quiet mode of rack server, rackup --quiet ([#674](https://github.com/rack/rack/pull/674))
  - Update HTTP Status Codes to RFC 7231 ([#754](https://github.com/rack/rack/pull/754))
  - Less strict header name validation according to [RFC 2616](https://tools.ietf.org/html/rfc2616) ([#399](https://github.com/rack/rack/pull/399))
    - SPEC updated to specify headers conform to RFC7230 specification ([6839fc](https://github.com/rack/rack/commit/6839fc203339f021cb3267fb09cba89410f086e9))
  - Etag correctly marks etags as weak ([#681](https://github.com/rack/rack/issues/681))
  - Request#port supports multiple x-http-forwarded-proto values ([#669](https://github.com/rack/rack/pull/669))
  - Utils#multipart_part_limit configures the maximum number of parts a request can contain ([#684](https://github.com/rack/rack/pull/684))
  - Default host to localhost when in development mode ([#514](https://github.com/rack/rack/pull/514))
  - Various bugfixes and performance improvements (See the full [git history](https://github.com/rack/rack/compare/1.5.2...1.6.0) and [milestone tag](https://github.com/rack/rack/issues?utf8=%E2%9C%93&q=milestone%3A%22Rack+1.6%22))

### February 7th, 2013, Thirty fifth public release 1.5.2
  - Fix CVE-2013-0263, timing attack against Rack::Session::Cookie
  - Fix CVE-2013-0262, symlink path traversal in Rack::File
  - Add various methods to Session for enhanced Rails compatibility
  - Request#trusted_proxy? now only matches whole stirngs
  - Add JSON cookie coder, to be default in Rack 1.6+ due to security concerns
  - URLMap host matching in environments that don't set the Host header fixed
  - Fix a race condition that could result in overwritten pidfiles
  - Various documentation additions

### February 7th, 2013, Thirty fifth public release 1.4.5
  - Fix CVE-2013-0263, timing attack against Rack::Session::Cookie
  - Fix CVE-2013-0262, symlink path traversal in Rack::File

### February 7th, Thirty fifth public release 1.1.6, 1.2.8, 1.3.10
  - Fix CVE-2013-0263, timing attack against Rack::Session::Cookie

### January 28th, 2013: Thirty fourth public release 1.5.1
  - Rack::Lint check_hijack now conforms to other parts of SPEC
  - Added hash-like methods to Abstract::ID::SessionHash for compatibility
  - Various documentation corrections

### January 21st, 2013: Thirty third public release 1.5.0
  - Introduced hijack SPEC, for before-response and after-response hijacking
  - SessionHash is no longer a Hash subclass
  - Rack::File cache_control parameter is removed, in place of headers options
  - Rack::Auth::AbstractRequest#scheme now yields strings, not symbols
  - Rack::Utils cookie functions now format expires in RFC 2822 format
  - Rack::File now has a default mime type
  - rackup -b 'run Rack::File.new(".")', option provides command line configs
  - Rack::Deflater will no longer double encode bodies
  - Rack::Mime#match? provides convenience for Accept header matching
  - Rack::Utils#q_values provides splitting for Accept headers
  - Rack::Utils#best_q_match provides a helper for Accept headers
  - Rack::Handler.pick provides convenience for finding available servers
  - Puma added to the list of default servers (preferred over Webrick)
  - Various middleware now correctly close body when replacing it
  - Rack::Request#params is no longer persistent with only GET params
  - Rack::Request#update_param and #delete_param provide persistent operations
  - Rack::Request#trusted_proxy? now returns true for local unix sockets
  - Rack::Response no longer forces Content-Types
  - Rack::Sendfile provides local mapping configuration options
  - Rack::Utils#rfc2109 provides old netscape style time output
  - Updated HTTP status codes
  - Ruby 1.8.6 likely no longer passes tests, and is no longer fully supported

### January 13th, 2013: Thirty second public release 1.4.4, 1.3.9, 1.2.7, 1.1.5
  - [SEC] Rack::Auth::AbstractRequest no longer symbolizes arbitrary strings
  - Fixed erroneous test case in the 1.3.x series

### January 7th, 2013: Thirty first public release 1.4.3
  - Security: Prevent unbounded reads in large multipart boundaries

### January 7th, 2013: Thirtieth public release 1.3.8
  - Security: Prevent unbounded reads in large multipart boundaries

### January 6th, 2013: Twenty ninth public release 1.4.2
  - Add warnings when users do not provide a session secret
  - Fix parsing performance for unquoted filenames
  - Updated URI backports
  - Fix URI backport version matching, and silence constant warnings
  - Correct parameter parsing with empty values
  - Correct rackup '-I' flag, to allow multiple uses
  - Correct rackup pidfile handling
  - Report rackup line numbers correctly
  - Fix request loops caused by non-stale nonces with time limits
  - Fix reloader on Windows
  - Prevent infinite recursions from Response#to_ary
  - Various middleware better conforms to the body close specification
  - Updated language for the body close specification
  - Additional notes regarding ECMA escape compatibility issues
  - Fix the parsing of multiple ranges in range headers
  - Prevent errors from empty parameter keys
  - Added PATCH verb to Rack::Request
  - Various documentation updates
  - Fix session merge semantics (fixes rack-test)
  - Rack::Static :index can now handle multiple directories
  - All tests now utilize Rack::Lint (special thanks to Lars Gierth)
  - Rack::File cache_control parameter is now deprecated, and removed by 1.5
  - Correct Rack::Directory script name escaping
  - Rack::Static supports header rules for sophisticated configurations
  - Multipart parsing now works without a Content-Length header
  - New logos courtesy of Zachary Scott!
  - Rack::BodyProxy now explicitly defines #each, useful for C extensions
  - Cookies that are not URI escaped no longer cause exceptions

### January 6th, 2013: Twenty eighth public release 1.3.7
  - Add warnings when users do not provide a session secret
  - Fix parsing performance for unquoted filenames
  - Updated URI backports
  - Fix URI backport version matching, and silence constant warnings
  - Correct parameter parsing with empty values
  - Correct rackup '-I' flag, to allow multiple uses
  - Correct rackup pidfile handling
  - Report rackup line numbers correctly
  - Fix request loops caused by non-stale nonces with time limits
  - Fix reloader on Windows
  - Prevent infinite recursions from Response#to_ary
  - Various middleware better conforms to the body close specification
  - Updated language for the body close specification
  - Additional notes regarding ECMA escape compatibility issues
  - Fix the parsing of multiple ranges in range headers

### January 6th, 2013: Twenty seventh public release 1.2.6
  - Add warnings when users do not provide a session secret
  - Fix parsing performance for unquoted filenames

### January 6th, 2013: Twenty sixth public release 1.1.4
  - Add warnings when users do not provide a session secret

### January 22nd, 2012: Twenty fifth public release 1.4.1
  - Alter the keyspace limit calculations to reduce issues with nested params
  - Add a workaround for multipart parsing where files contain unescaped "%"
  - Added Rack::Response::Helpers#method_not_allowed? (code 405)
  - Rack::File now returns 404 for illegal directory traversals
  - Rack::File now returns 405 for illegal methods (non HEAD/GET)
  - Rack::Cascade now catches 405 by default, as well as 404
  - Cookies missing '--' no longer cause an exception to be raised
  - Various style changes and documentation spelling errors
  - Rack::BodyProxy always ensures to execute its block
  - Additional test coverage around cookies and secrets
  - Rack::Session::Cookie can now be supplied either secret or old_secret
  - Tests are no longer dependent on set order
  - Rack::Static no longer defaults to serving index files
  - Rack.release was fixed

### December 28th, 2011: Twenty fourth public release 1.4.0
  - Ruby 1.8.6 support has officially been dropped. Not all tests pass.
  - Raise sane error messages for broken config.ru
  - Allow combining run and map in a config.ru
  - Rack::ContentType will not set Content-Type for responses without a body
  - Status code 205 does not send a response body
  - Rack::Response::Helpers will not rely on instance variables
  - Rack::Utils.build_query no longer outputs '=' for nil query values
  - Various mime types added
  - Rack::MockRequest now supports HEAD
  - Rack::Directory now supports files that contain RFC3986 reserved chars
  - Rack::File now only supports GET and HEAD requests
  - Rack::Server#start now passes the block to Rack::Handler::<h>#run
  - Rack::Static now supports an index option
  - Added the Teapot status code
  - rackup now defaults to Thin instead of Mongrel (if installed)
  - Support added for HTTP_X_FORWARDED_SCHEME
  - Numerous bug fixes, including many fixes for new and alternate rubies

### December 28th, 2011: Twenty first public release: 1.1.3.
  - Security fix. http://www.ocert.org/advisories/ocert-2011-003.html
    Further information here: http://jruby.org/2011/12/27/jruby-1-6-5-1

### October 17, 2011: Twentieth public release 1.3.5
  - Fix annoying warnings caused by the backport in 1.3.4

### October 1, 2011: Nineteenth public release 1.3.4
  - Backport security fix from 1.9.3, also fixes some roundtrip issues in URI
  - Small documentation update
  - Fix an issue where BodyProxy could cause an infinite recursion
  - Add some supporting files for travis-ci

### September 16, 2011: Eighteenth public release 1.2.4
  - Fix a bug with MRI regex engine to prevent XSS by malformed unicode

### September 16, 2011: Seventeenth public release 1.3.3
  - Fix bug with broken query parameters in Rack::ShowExceptions
  - Rack::Request#cookies no longer swallows exceptions on broken input
  - Prevents XSS attacks enabled by bug in Ruby 1.8's regexp engine
  - Rack::ConditionalGet handles broken If-Modified-Since helpers

### July 16, 2011: Sixteenth public release 1.3.2
  - Fix for Rails and rack-test, Rack::Utils#escape calls to_s

### July 13, 2011: Fifteenth public release 1.3.1
  - Fix 1.9.1 support
  - Fix JRuby support
  - Properly handle $KCODE in Rack::Utils.escape
  - Make method_missing/respond_to behavior consistent for Rack::Lock,
    Rack::Auth::Digest::Request and Rack::Multipart::UploadedFile
  - Reenable passing rack.session to session middleware
  - Rack::CommonLogger handles streaming responses correctly
  - Rack::MockResponse calls close on the body object
  - Fix a DOS vector from MRI stdlib backport

### May 22nd, 2011: Fourteenth public release 1.2.3
  - Pulled in relevant bug fixes from 1.3
  - Fixed 1.8.6 support

### May 22nd, 2011: Thirteenth public release 1.3.0
  - Various performance optimizations
  - Various multipart fixes
  - Various multipart refactors
  - Infinite loop fix for multipart
  - Test coverage for Rack::Server returns
  - Allow files with '..', but not path components that are '..'
  - rackup accepts handler-specific options on the command line
  - Request#params no longer merges POST into GET (but returns the same)
  - Use URI.encode_www_form_component instead. Use core methods for escaping.
  - Allow multi-line comments in the config file
  - Bug L#94 reported by Nikolai Lugovoi, query parameter unescaping.
  - Rack::Response now deletes Content-Length when appropriate
  - Rack::Deflater now supports streaming
  - Improved Rack::Handler loading and searching
  - Support for the PATCH verb
  - env['rack.session.options'] now contains session options
  - Cookies respect renew
  - Session middleware uses SecureRandom.hex

### March 13th, 2011: Twelfth public release 1.2.2/1.1.2.
  - Security fix in Rack::Auth::Digest::MD5: when authenticator
    returned nil, permission was granted on empty password.

### June 15th, 2010: Eleventh public release 1.2.1.
  - Make CGI handler rewindable
  - Rename spec/ to test/ to not conflict with SPEC on lesser
    operating systems

### June 13th, 2010: Tenth public release 1.2.0.
  - Removed Camping adapter: Camping 2.0 supports Rack as-is
  - Removed parsing of quoted values
  - Add Request.trace? and Request.options?
  - Add mime-type for .webm and .htc
  - Fix HTTP_X_FORWARDED_FOR
  - Various multipart fixes
  - Switch test suite to bacon

### January 3rd, 2010: Ninth public release 1.1.0.
  - Moved Auth::OpenID to rack-contrib.
  - SPEC change that relaxes Lint slightly to allow subclasses of the
    required types
  - SPEC change to document rack.input binary mode in greator detail
  - SPEC define optional rack.logger specification
  - File servers support X-Cascade header
  - Imported Config middleware
  - Imported ETag middleware
  - Imported Runtime middleware
  - Imported Sendfile middleware
  - New Logger and NullLogger middlewares
  - Added mime type for .ogv and .manifest.
  - Don't squeeze PATH_INFO slashes
  - Use Content-Type to determine POST params parsing
  - Update Rack::Utils::HTTP_STATUS_CODES hash
  - Add status code lookup utility
  - Response should call #to_i on the status
  - Add Request#user_agent
  - Request#host knows about forwared host
  - Return an empty string for Request#host if HTTP_HOST and
    SERVER_NAME are both missing
  - Allow MockRequest to accept hash params
  - Optimizations to HeaderHash
  - Refactored rackup into Rack::Server
  - Added Utils.build_nested_query to complement Utils.parse_nested_query
  - Added Utils::Multipart.build_multipart to complement
    Utils::Multipart.parse_multipart
  - Extracted set and delete cookie helpers into Utils so they can be
    used outside Response
  - Extract parse_query and parse_multipart in Request so subclasses
    can change their behavior
  - Enforce binary encoding in RewindableInput
  - Set correct external_encoding for handlers that don't use RewindableInput

### October 18th, 2009: Eighth public release 1.0.1.
  - Bump remainder of rack.versions.
  - Support the pure Ruby FCGI implementation.
  - Fix for form names containing "=": split first then unescape components
  - Fixes the handling of the filename parameter with semicolons in names.
  - Add anchor to nested params parsing regexp to prevent stack overflows
  - Use more compatible gzip write api instead of "<<".
  - Make sure that Reloader doesn't break when executed via ruby -e
  - Make sure WEBrick respects the :Host option
  - Many Ruby 1.9 fixes.

### April 25th, 2009: Seventh public release 1.0.0.
  - SPEC change: Rack::VERSION has been pushed to [1,0].
  - SPEC change: header values must be Strings now, split on "\n".
  - SPEC change: Content-Length can be missing, in this case chunked transfer
    encoding is used.
  - SPEC change: rack.input must be rewindable and support reading into
    a buffer, wrap with Rack::RewindableInput if it isn't.
  - SPEC change: rack.session is now specified.
  - SPEC change: Bodies can now additionally respond to #to_path with
    a filename to be served.
  - NOTE: String bodies break in 1.9, use an Array consisting of a
    single String instead.
  - New middleware Rack::Lock.
  - New middleware Rack::ContentType.
  - Rack::Reloader has been rewritten.
  - Major update to Rack::Auth::OpenID.
  - Support for nested parameter parsing in Rack::Response.
  - Support for redirects in Rack::Response.
  - HttpOnly cookie support in Rack::Response.
  - The Rakefile has been rewritten.
  - Many bugfixes and small improvements.

### January 9th, 2009: Sixth public release 0.9.1.
  - Fix directory traversal exploits in Rack::File and Rack::Directory.

### January 6th, 2009: Fifth public release 0.9.
  - Rack is now managed by the Rack Core Team.
  - Rack::Lint is stricter and follows the HTTP RFCs more closely.
  - Added ConditionalGet middleware.
  - Added ContentLength middleware.
  - Added Deflater middleware.
  - Added Head middleware.
  - Added MethodOverride middleware.
  - Rack::Mime now provides popular MIME-types and their extension.
  - Mongrel Header now streams.
  - Added Thin handler.
  - Official support for swiftiplied Mongrel.
  - Secure cookies.
  - Made HeaderHash case-preserving.
  - Many bugfixes and small improvements.

### August 21st, 2008: Fourth public release 0.4.
  - New middleware, Rack::Deflater, by Christoffer Sawicki.
  - OpenID authentication now needs ruby-openid 2.
  - New Memcache sessions, by blink.
  - Explicit EventedMongrel handler, by Joshua Peek <josh@joshpeek.com>
  - Rack::Reloader is not loaded in rackup development mode.
  - rackup can daemonize with -D.
  - Many bugfixes, especially for pool sessions, URLMap, thread safety
    and tempfile handling.
  - Improved tests.
  - Rack moved to Git.

### February 26th, 2008: Third public release 0.3.
  - LiteSpeed handler, by Adrian Madrid.
  - SCGI handler, by Jeremy Evans.
  - Pool sessions, by blink.
  - OpenID authentication, by blink.
  - :Port and :File options for opening FastCGI sockets, by blink.
  - Last-Modified HTTP header for Rack::File, by blink.
  - Rack::Builder#use now accepts blocks, by Corey Jewett.
    (See example/protectedlobster.ru)
  - HTTP status 201 can contain a Content-Type and a body now.
  - Many bugfixes, especially related to Cookie handling.

### May 16th, 2007: Second public release 0.2.
  - HTTP Basic authentication.
  - Cookie Sessions.
  - Static file handler.
  - Improved Rack::Request.
  - Improved Rack::Response.
  - Added Rack::ShowStatus, for better default error messages.
  - Bug fixes in the Camping adapter.
  - Removed Rails adapter, was too alpha.

### March 3rd, 2007: First public release 0.1.

/* vim: set filetype=changelog */

redpajama_set_name: RedPajamaGithub


text:
include(LibFindMacros)

# Dependencies
libfind_package(GTK GDK)
libfind_package(GTK Cairo)
libfind_package(GTK Atk)
libfind_package(GTK GIO)
libfind_package(GTK Pango)

set(GTK_Version 2.0)

# Use pkg-config to get hints about paths
libfind_pkg_check_modules(GTK_PKGCONF gtk+-${GTK_Version})

# Main include dir
find_path(GTK_INCLUDE_DIR
  NAMES gtk/gtk.h
  PATHS ${GTK_PKGCONF_INCLUDE_DIRS}
  PATH_SUFFIXES gtk-${GTK_Version}
)

# Finally the library itself
find_library(GTK_LIBRARY
  NAMES gtk-x11-${GTK_Version} gtk-win32-${GTK_Version} gtk-${GTK_Version} gtk-${GTK_Version}
  PATHS ${GTK_PKGCONF_LIBRARY_DIRS}
)

# Set the include dir variables and the libraries and let libfind_process do the rest.
# NOTE: Singular variables for this library, plural for libraries this this lib depends on.
set(GTK_PROCESS_INCLUDES GTK_INCLUDE_DIR GDK_INCLUDE_DIRS Cairo_INCLUDE_DIRS Atk_INCLUDE_DIRS GIO_INCLUDE_DIRS Pango_INCLUDE_DIRS)
set(GTK_PROCESS_LIBS GTK_LIBRARY GDK_LIBRARIES Cairo_LIBRARIES Atk_LIBRARIES GIO_LIBRARIES Pango_LIBRARIES)
libfind_process(GTK)


text:
//convert
 /* ghost.utils.Objects.*/
import {Objects} from "ghost/utils/Objects";
//convert
 /* ghost.core.Root.*/
import {Root} from "ghost/core/Root";

///<module="framework/ghost/utils"/>
///<module="framework/browser/api"/>

    //convert-import
import {BufferFunction} from "ghost/utils/BufferFunction";
    //convert-import
import {Buffer} from "ghost/utils/Buffer";
    //convert-import
import {API} from "browser/api/API";
    //convert-import
import {APIExtended} from "browser/api/APIExtended";
    export class Watch
    {
        protected static _registered: any[];
        protected static _buffer: BufferFunction;
        public static promise(promise:Promise<any>):void
        {

            var time:number = this.now();

            var _self:any = this;
            promise.then(function()
            {
                var args:any = arguments;
                if(arguments.length == 1)
                {
                    args = arguments[0];
                }
                console.log("monitor done:"+ (_self.now()-time), args, promise);
            }, function()
            {
                console.error("monitor error done:"+ (_self.now()-time), arguments, promise);
            });

        }
        private static now():number{
            return Root.getRoot()["performance"] && Root.getRoot()["performance"].now?Root.getRoot()["performance"].now():Date.now();
        }
        private static addWatch(watch:any):void
        {
            if(Watch._registered == undefined)
            {
                Watch._registered = [];
                Watch._buffer = Buffer.throttle(Watch.onSend, 5000);
            }
            Watch._registered.push(watch);
            Watch._buffer();
        }
        private static onSend():void
        {
            var data: any[] = Watch._registered.slice();
            Watch._registered.length = 0;
            if(data && data.length)
                APIExtended.request().always(false).controller("statistics").action("watch").method("POST").param("stats", data).done();
        }

        protected _start: number;
        protected _stop: number;
        protected _name: string;
        protected _type: string;
        protected _mark: boolean;
        public constructor(name:string, type?:string)
        {
            this._name = name;
            this._type = type;
        }
        public start():void
        {
            this._start = Watch.now();
            if (this._mark)
            {
                window.performance.mark("start-"+(this._type?this._type+'-':'')+this._name);
            }
        }
        public cancel():void
        {
            delete this._start;
        }
        public stop(data?:any): void {
            if(this._start == undefined)
            {
                return;
            }
            this._stop = Watch.now();
            Watch.addWatch(this.getResult(data));
            if (this._mark) {
               window.performance.mark("stop-" + (this._type ? this._type + '-' : '') + this._name);
               window.performance.measure((this._type ? this._type + '-' : '') + this._name + " (" + ((((this._stop - this._start)*100)|0)/100)+"ms)", "start-" + (this._type ? this._type + '-' : '') + this._name, "stop-" + (this._type ? this._type + '-' : '') + this._name);
            }
        }
        public mark():void
        {
            if (window.performance && window.performance.mark && window.performance.measure)
                this._mark = true;
        }
        protected getResult(data:any):any
        {
            return Objects.merge({ name: this._name, time: (this._stop-this._start)|0, date:Date.now(), type:this._type }, data);
        }
    }


text:
module Saasu
  class Search
    VALID_SCOPES = %W(All Transactions Contacts InventoryItems)
    attr_accessor :scope, :keywords

    # allowed params:
    # :scope - All, Transactions, Contacts, InventoryItems
    # :transaction_type - Sale, Purchase, Journal, Payroll
    def initialize(keywords, params = {})
      if params.is_a?(Hash)
        @scope = params[:scope].presence || 'All'
        @transaction_type = "Transactions.#{params[:transaction_type]}" if params[:transaction_type].present?
      else
        @scope = params
      end

      @keywords = keywords

      validate_scope!
    end

    def perform
      perform_search!
      { contacts: search_results['TotalContactsFound'], invoices: search_results['TotalTransactionsFound'], items: search_results['TotalInventoryItemsFound'] }
    end

    def contacts
      search_results["Contacts"].map do |contact|
        Saasu::Contact.new(contact)
      end
    end

    def invoices
      search_results["Transactions"].map do |contact|
        Saasu::Invoice.new(contact)
      end
    end

    def items
      search_results["InventoryItems"].map do |contact|
        Saasu::Item.new(contact)
      end
    end

    private
    def search_params
      _params = { Scope: @scope, Keywords: @keywords, IncludeSearchTermHighlights: false }
      _params[:TransactionType] = @transaction_type if @transaction_type.present?
      _params
    end

    def perform_search!
      @search_results = Saasu::Client.request(:get, 'search', search_params)
    end

    def search_results
      @search_results ||= perform_search!
    end

    def validate_scope!
      unless @scope.in? VALID_SCOPES
        raise "Invalid scope argument. Valid values are: #{VALID_SCOPES.join(', ')}"
      end
    end
  end
end


text:
"""Prepare bcbio workflows from input YAML files.
"""
import copy
import pprint

import toolz as tz

ALWAYS_AVAILABLE = ["#description"]

def generate(variables, steps, final_outputs):
    """Generate all of the components of a CWL workflow from input steps.

    file_vs and std_vs are the list of world variables, split into those that
    reference files (and need declaration at each step) and those that don't
    and can be safely passed to each step. This function keeps track of these
    as they're added and updated by steps, passing this information on to
    creation of the CWL files.
    """
    file_vs, std_vs = _split_variables([_flatten_nested_input(v) for v in variables])
    parallel_ids = []
    for step in steps:
        if hasattr(step, "workflow"):
            wf_inputs = []
            wf_outputs = []
            wf_steps = []
            for i, wf_step in enumerate(step.workflow):
                inputs, parallel_ids, nested_inputs = _get_step_inputs(wf_step, file_vs, std_vs, parallel_ids, step)
                outputs, file_vs, std_vs = _get_step_outputs(wf_step, wf_step.outputs, file_vs, std_vs)
                parallel_ids = _find_split_vs(outputs, wf_step.parallel)
                wf_steps.append(("step", wf_step.name, wf_step.parallel, [_clean_record(x) for x in inputs],
                                 outputs, wf_step.programs, wf_step.disk))
                wf_inputs = _merge_wf_inputs(inputs, wf_inputs, wf_outputs, step.internal, wf_step.parallel,
                                             nested_inputs)
                wf_outputs = _merge_wf_outputs(outputs, wf_outputs, wf_step.parallel)
            yield "wf_start", wf_inputs
            for wf_step in wf_steps:
                yield wf_step
            wf_outputs = [v for v in wf_outputs
                          if v["id"] not in set(["#%s" % _get_string_vid(x) for x in step.internal])]
            yield "upload", wf_outputs
            wf_outputs, file_vs, std_vs = _get_step_outputs(step, wf_outputs, file_vs, std_vs)
            yield "wf_finish", step.name, step.parallel, wf_inputs, wf_outputs
            file_vs = _extract_from_subworkflow(file_vs, step)
            std_vs = _extract_from_subworkflow(std_vs, step)
        else:
            inputs, parallel_ids, nested_inputs = _get_step_inputs(step, file_vs, std_vs, parallel_ids)
            outputs, file_vs, std_vs = _get_step_outputs(step, step.outputs, file_vs, std_vs)
            parallel_ids = _find_split_vs(outputs, step.parallel)
            yield "step", step.name, step.parallel, inputs, outputs, step.programs, step.disk
    yield "upload", [_get_upload_output(x, file_vs) for x in final_outputs]

def _merge_wf_inputs(new, out, wf_outputs, to_ignore, parallel, nested_inputs):
    """Merge inputs for a sub-workflow, adding any not present inputs in out.

    Skips inputs that are internally generated or generated and ignored, keeping
    only as inputs those that we do not generate interally.
    """
    internal_generated_ids = []
    for vignore in to_ignore:
        vignore_id = "#%s" % _get_string_vid(vignore)
        # ignore anything we generate internally, but not those we need to pull in
        # from the external process'
        if vignore_id in [v["id"] for v in wf_outputs]:
            internal_generated_ids.append(vignore_id)
    ignore_ids = set(internal_generated_ids + [v["id"] for v in wf_outputs])
    cur_ids = set([v["id"] for v in out])
    for v in new:
        outv = copy.deepcopy(v)
        outv["id"] = "#%s" % get_base_id(v["id"])
        if outv["id"] not in cur_ids and outv["id"] not in ignore_ids:
            if nested_inputs and v["id"] in nested_inputs:
                outv = _flatten_nested_input(outv)
            out.append(outv)
    return out

def _merge_wf_outputs(new, cur, parallel):
    """Merge outputs for a sub-workflow, replacing variables changed in later steps.

    ignore_ids are those used internally in a sub-workflow but not exposed to subsequent steps
    """
    new_ids = set([])
    out = []
    for v in new:
        outv = {}
        outv["source"] = v["id"]
        outv["id"] = "#%s" % get_base_id(v["id"])
        outv["type"] = v["type"]
        if "secondaryFiles" in v:
            outv["secondaryFiles"] = v["secondaryFiles"]
        if tz.get_in(["outputBinding", "secondaryFiles"], v):
            outv["secondaryFiles"] = tz.get_in(["outputBinding", "secondaryFiles"], v)
        new_ids.add(outv["id"])
        if parallel in ["single-split", "batch-split"]:
            outv = _flatten_nested_input(outv)
        out.append(outv)
    for outv in cur:
        if outv["id"] not in new_ids:
            out.append(outv)
    return out

def _extract_from_subworkflow(vs, step):
    """Remove internal variable names when moving from sub-workflow to main.
    """
    substep_ids = set([x.name for x in step.workflow])
    out = []
    for var in vs:
        internal = False
        parts = var["id"].split(".")
        if len(parts) > 1:
            ns = parts[0].replace("#", "")
            if ns in substep_ids:
                internal = True
        if not internal:
            var.pop("source", None)
            out.append(var)
    return out

def _find_split_vs(out_vs, parallel):
    """Find variables created by splitting samples.
    """
    # split parallel job
    if parallel in ["single-parallel", "batch-parallel"]:
        return [v["id"] for v in out_vs]
    else:
        return []

def _get_step_inputs(step, file_vs, std_vs, parallel_ids, wf=None):
    """Retrieve inputs for a step from existing variables.

    Potentially nests inputs to deal with merging split variables. If
    we split previously and are merging now, then we only nest those
    combing from the split process.
    """
    inputs = []
    skip_inputs = set([])
    for orig_input in [_get_variable(x, file_vs) for x in _handle_special_inputs(step.inputs, file_vs)]:
        is_record_input = tz.get_in(["type", "type"], orig_input) == "record"
        if is_record_input:
            unpack_inputs = _unpack_record(orig_input)
            inputs.extend(unpack_inputs)
            skip_inputs = skip_inputs | set([get_base_id(v["id"]) for v in unpack_inputs])
        else:
            inputs.append(orig_input)
    inputs += [v for v in std_vs if get_base_id(v["id"]) not in skip_inputs]
    nested_inputs = []
    if step.parallel in ["single-merge", "batch-merge"]:
        if parallel_ids:
            inputs = [_nest_variable(x) if x["id"] in parallel_ids else x for x in inputs]
            nested_inputs = parallel_ids[:]
            parallel_ids = []
    elif step.parallel in ["multi-combined", "multi-batch"]:
        assert len(parallel_ids) == 0
        nested_inputs = [x["id"] for x in inputs]
        inputs = [_nest_variable(x) for x in inputs]
    return inputs, parallel_ids, nested_inputs

def _unpack_record(rec):
    """Unpack a record object, extracting individual elements.
    """
    out = []
    for field in rec["type"]["fields"]:
        out.append({"id": "#%s" % field["name"], "type": field["type"],
                    "source": rec["id"], "valueFrom": "$(self.%s)" % field["name"]})
    return out

def _clean_record(var):
    """Remove record source information from an input variant.
    """
    out = copy.deepcopy(var)
    for attr in ["source", "valueFrom"]:
        out.pop(attr, None)
    return out

def _get_step_outputs(step, outputs, file_vs, std_vs):
    if step.parallel in ["multi-batch"]:
        file_output = [_create_record(outputs, step.inputs, step.unlist, file_vs, std_vs)]
        std_output = []
    else:
        file_output, std_output = _split_variables([_create_variable(x, step, file_vs) for x in outputs])
        #file_output = [_clean_output_extras(x) for x in file_output]
    std_vs = _merge_variables([_clean_output(v) for v in std_output], std_vs)
    file_vs = _merge_variables([_clean_output(v) for v in file_output], file_vs)
    if step.parallel in ["single-split", "batch-split", "multi-combined", "multi-batch"]:
        file_output = [_nest_variable(x) for x in file_output]
        std_output = [_nest_variable(x) for x in std_output]
    return file_output + std_output, file_vs, std_vs

def _flatten_nested_input(v):
    """Flatten a parallel scatter input -- we only get one of them to tools.
    """
    v = copy.deepcopy(v)
    assert v["type"]["type"] == "array"
    v["type"] = v["type"]["items"]
    return v

def _nest_variable(v):
    """Nest a variable when moving from scattered back to consolidated.
    """
    v = copy.deepcopy(v)
    v["type"] = {"type": "array", "items": v["type"]}
    if "secondaryFiles" in v:
        v["type"]["secondaryFiles"] = v.pop("secondaryFiles")
    return v

def _clean_output(v):
    """Remove output specific variables to allow variables to be inputs to next steps.
    """
    out = copy.deepcopy(v)
    outb = out.pop("outputBinding", {})
    if "secondaryFiles" in outb:
        out["secondaryFiles"] = outb["secondaryFiles"]
    return out

def _get_string_vid(vid):
    assert isinstance(vid, (list, tuple)), vid
    return "__".join(vid)

def _get_variable(vid, variables):
    """Retrieve an input variable from our existing pool of options.
    """
    if isinstance(vid, basestring):
        vid = get_base_id(vid)
    else:
        vid = _get_string_vid(vid)
    for v in variables:
        if vid == get_base_id(v["id"]):
            return copy.deepcopy(v)
    raise ValueError("Did not find variable %s in \n%s" % (vid, pprint.pformat(variables)))

def _handle_special_inputs(inputs, variables):
    """Adjust input variables based on special cases.

    This case handles inputs where we are optional or can have flexible choices.

    XXX Need to better expose this at a top level definition.
    """
    optional = [["config", "algorithm", "coverage"],
                ["config", "algorithm", "variant_regions"],
                ["config", "algorithm", "validate"],
                ["config", "algorithm", "validate_regions"]]
    all_vs = set([get_base_id(v["id"]) for v in variables])
    out = []
    for input in inputs:
        if input == ["reference", "aligner", "indexes"]:
            found_indexes = False
            for v in variables:
                vid = get_base_id(v["id"]).split("__")
                if vid[0] == "reference" and vid[-1] == "indexes":
                    out.append(vid)
                    found_indexes = True
            assert found_indexes, "Found no aligner indexes in %s" % [v["id"] for v in variables]
        elif input in optional:
            if _get_string_vid(input) in all_vs:
                out.append(input)
        else:
            out.append(input)
    return out

def _clean_output_extras(v):
    """Remove extra variables we don't want in output.

    We want secondaryFiles nested in outputBinding.
    """
    out = copy.deepcopy(v)
    for not_in_output in ["secondaryFiles"]:
        if not_in_output in out and not_in_output in out.get("outputBinding", {}):
            out.pop(not_in_output, None)
    return out

def _get_upload_output(vid, variables):
    v = _nest_variable(_get_variable(vid, variables))
    v["source"] = v["id"]
    v["id"] = "#%s" % get_base_id(v["id"])
    v["linkMerge"] = "merge_flattened"
    v.pop("secondaryFiles", None)
    return _clean_output_extras(v)

def _create_record(name, inputs, unlist, file_vs, std_vs):
    """Create an input record by rearranging inputs.

    Batching processes create records that reformat the inputs for
    parallelization.
    """
    unlist = set([_get_string_vid(x) for x in unlist])
    fields = []
    input_vids = set([_get_string_vid(v) for v in inputs])
    for orig_v in std_vs + [v for v in file_vs if get_base_id(v["id"]) in input_vids]:
        cur_v = {}
        cur_v["name"] = get_base_id(orig_v["id"])
        cur_v["type"] = orig_v["type"]
        if cur_v["name"] in unlist:
            cur_v = _flatten_nested_input(cur_v)
        fields.append(_nest_variable(cur_v))

    return {"id": "#%s" % name,
            "type": {"name": name,
                     "type": "record",
                     "fields": fields}}

def _create_variable(orig_v, step, variables):
    """Create a new output variable, potentially over-writing existing or creating new.
    """
    # get current variable, and convert to be the output of our process step
    try:
        v = _get_variable(orig_v["id"], variables)
    except ValueError:
        v = copy.deepcopy(orig_v)
        if not isinstance(v["id"], basestring):
            v["id"] = "#" + _get_string_vid(v["id"])
    for key, val in orig_v.items():
        if key not in ["id", "type"]:
            v[key] = val
    if v.get("type") == "null" and orig_v.get("type") != "null":
        v["type"] = orig_v["type"]
    return _convert_to_step_id(v, step)

def _merge_variables(new, cur):
    """Add any new variables to the world representation in cur.

    Replaces any variables adjusted by previous steps.
    """
    new_added = set([])
    out = []
    for cur_var in cur:
        updated = False
        for new_var in new:
            if get_base_id(new_var["id"]) == get_base_id(cur_var["id"]):
                out.append(new_var)
                new_added.add(new_var["id"])
                updated = True
                break
        if not updated:
            out.append(cur_var)
    for new_var in new:
        if new_var["id"] not in new_added:
            out.append(new_var)
    return out

def get_base_id(vid):
    """Retrieve the base id for a variant, ignoring prefixes and steps.
    """
    assert vid[0] == "#", vid
    parts = vid[1:].split(".")
    return parts[-1]

def _convert_to_step_id(v, step):
    """Convert a variable to include the identifier of a specific step.
    """
    v["id"] = "#%s.%s" % (step.name, get_base_id(v["id"]))
    return v

def _split_variables(variables):
    """Split variables into always passed (std) and specified (file).

    We always pass some variables to each step but need to
    explicitly define file and algorithm variables so they can
    be linked in as needed.
    """
    file_vs = []
    std_vs = []
    for v in variables:
        cur_type = v["type"]
        while isinstance(cur_type, dict):
            cur_type = cur_type["items"]
        if (cur_type == "File" or cur_type == "null" or
              (isinstance(cur_type, (list, tuple)) and
               ("File" in cur_type or {'items': 'File', 'type': 'array'} in cur_type))):
            file_vs.append(v)
        elif v["id"] in ALWAYS_AVAILABLE:
            std_vs.append(v)
        else:
            file_vs.append(v)
    return file_vs, std_vs


text:
<?php

namespace Ludos\Action;

use Doctrine\ORM\EntityManager;
use Ludos\Entity\Game\Game;
use Ludos\Entity\PlayActivityEntry;
use Ludos\Entity\Repositories\GameRepository;
use Ludos\Entity\User;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Symfony\Component\Serializer\Serializer;
use Zend\Diactoros\Response\HtmlResponse;
use Zend\Expressive\Template\TemplateRendererInterface;

class ShowGame
{
    protected $entityManager;
    protected $templateRenderer;
    protected $serializer;

    public function __construct(
        TemplateRendererInterface $templateRenderer,
        EntityManager $entityManager,
        Serializer $serializer
    ) {
        $this->templateRenderer = $templateRenderer;
        $this->entityManager = $entityManager;
        $this->serializer = $serializer;
    }

    public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next = null)
    {
        $gameSlug = $request->getAttribute('gameSlug');
        $game = null;
        if ($gameSlug !== null) {
            /** @var Game $game */
            $game = $this->entityManager->getRepository(Game::class)->findOneBy(['slug' => $gameSlug]);
        }
        if ($game === null) {
            return $next($request, $response, 404);
        }

        $game->incrementPlays();
        $this->entityManager->persist($game);

        /** @var User|null $user */
        $user = $request->getAttribute('user');
        if ($user !== null) {
            /** @var PlayActivityEntry $playActivityEntry */
            $playActivityEntry = $this->entityManager
                ->getRepository(PlayActivityEntry::class)
                ->findOneBy(['user' => $user->getId(), 'game' => $game->getId()]);
            if ($playActivityEntry === null) {
                $playActivityEntry = new PlayActivityEntry($user, $game);
            } else {
                $playActivityEntry->updateTimestamps();
            }
            $this->entityManager->persist($playActivityEntry);
        } else {
            $playedGamesIds = json_decode($request->getCookieParams()['playedGames'] ?? [], true);
            if (!in_array($game->getId(), $playedGamesIds, true)) {
                $playedGamesIds[] = $game->getId();
            }
            setcookie('playedGames', json_encode($playedGamesIds), null, '/');
        }

        $this->entityManager->flush();

        /** @var GameRepository $gameRepository */
        $gameRepository = $this->entityManager->getRepository(Game::class);

        $topGames = [];
        $gameTags = $game->getTags();
        if (count($gameTags) !== 0) {
            $topGames = $gameRepository->paginateActiveByTag(
                $game->getTags()->first(),
                $request->getAttribute(DetectSupportedGames::class, null),
                GameRepository::SORT_TOP,
                1,
                6
            );
        }

        $params = [
            'serializedUser' => $this->serializer->serialize($user, 'json'),
            'game' => $game,
            'user' => $user,
            'topGames' => $topGames,
            'supportedGameTypes' => $request->getAttribute(DetectSupportedGames::class, []),
            'canonical' => $request->getUri()
        ];
        return new HtmlResponse($this->templateRenderer->render('app::game', $params));
    }
}


text:
var validations = require('./index'),
    db = require('../db')

exports.types = {
  ReturnConsumedCapacity: {
    type: 'String',
    enum: ['INDEXES', 'TOTAL', 'NONE'],
  },
  RequestItems: {
    type: 'Map<KeysAndAttributes>',
    notNull: true,
    lengthGreaterThanOrEqual: 1,
    keys: {
      lengthLessThanOrEqual: 255,
      lengthGreaterThanOrEqual: 3,
      regex: '[a-zA-Z0-9_.-]+',
    },
    children: {
      type: 'ValueStruct<KeysAndAttributes>',
      children: {
        Keys: {
          type: 'List',
          notNull: true,
          lengthGreaterThanOrEqual: 1,
          lengthLessThanOrEqual: 100,
          children: {
            type: 'ParameterizedMap',
            children: 'AttrStruct<ValueStruct>',
          },
        },
        AttributesToGet: {
          type: 'List',
          lengthGreaterThanOrEqual: 1,
          lengthLessThanOrEqual: 255,
          children: 'String',
        },
        ConsistentRead: 'Boolean',
        ProjectionExpression: {
          type: 'String',
        },
        ExpressionAttributeNames: {
          type: 'Map<java.lang.String>',
          children: 'String',
        },
      },
    },
  },
}

exports.custom = function(data) {
  var numReqs = 0

  for (var table in data.RequestItems) {
    var tableData = data.RequestItems[table]

    var msg = validations.validateExpressionParams(tableData, ['ProjectionExpression'], ['AttributesToGet'])
    if (msg) return msg

    if (tableData.AttributesToGet) {
      msg = validations.findDuplicate(tableData.AttributesToGet)
      if (msg) return 'One or more parameter values were invalid: Duplicate value in attribute name: ' + msg
    }

    msg = validations.validateExpressions(tableData)
    if (msg) return msg

    var seenKeys = Object.create(null)
    for (var i = 0; i < tableData.Keys.length; i++) {
      var key = tableData.Keys[i]

      for (var attr in key) {
        msg = validations.validateAttributeValue(key[attr])
        if (msg) return msg
      }

      // TODO: this is unnecessarily expensive
      var keyStr = Object.keys(key).sort().map(function(attr) { return db.toRangeStr(key[attr]) }).join('/')
      if (seenKeys[keyStr])
        return 'Provided list of item keys contains duplicates'
      seenKeys[keyStr] = true

      numReqs++
      if (numReqs > 100)
        return 'Too many items requested for the BatchGetItem call'
    }
  }
}


text:
package egovframework.com.cop.ncm.web;

import java.util.Map;

import egovframework.com.cmm.LoginVO;
import egovframework.com.cmm.annotation.IncludedInfo;
import egovframework.com.cmm.util.EgovUserDetailsHelper;
import egovframework.com.cop.ncm.service.EgovNcrdManageService;
import egovframework.com.cop.ncm.service.NameCard;
import egovframework.com.cop.ncm.service.NameCardUser;
import egovframework.com.cop.ncm.service.NameCardVO;

import egovframework.rte.fdl.property.EgovPropertyService;
import egovframework.rte.ptl.mvc.tags.ui.pagination.PaginationInfo;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.support.SessionStatus;
import org.springmodules.validation.commons.DefaultBeanValidator;

/**
 * 명함정보를 관리하기 위한 컨트롤러 클래스
 * @author 공통서비스개발팀 이삼섭
 * @since 2009.06.01
 * @version 1.0
 * @see
 *
 * <pre>
 * << 개정이력(Modification Information) >>
 *
 *   수정일      수정자           수정내용
 *  -------    --------    ---------------------------
 *   2009.3.30  이삼섭          최초 생성
 *   2011.8.26	정진오			IncludedInfo annotation 추가
 *
 * </pre>
 */

@Controller
public class EgovNcrdManageController {

    @Resource(name = "EgovNcrdManageService")
    private EgovNcrdManageService ncrdService;

    @Resource(name = "propertiesService")
    protected EgovPropertyService propertyService;

    @Autowired
    private DefaultBeanValidator beanValidator;

    //Logger log = Logger.getLogger(this.getClass());

    /**
     * 명함 정보에 대한 목록을 조회한다.
     *
     * @param ncrdVO
     * @param sessionVO
     * @param status
     * @param model
     * @return
     * @throws Exception
     */
    @IncludedInfo(name="명함관리",order = 370 ,gid = 40)
    @RequestMapping("/cop/ncm/selectNcrdInfs.do")
    public String selectNcrdItems(@ModelAttribute("searchVO") NameCardVO ncrdVO, SessionStatus status, ModelMap model) throws Exception {

	LoginVO user = (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser();
	Boolean isAuthenticated = EgovUserDetailsHelper.isAuthenticated();
	 // KISA 보안취약점 조치 (2018-12-10, 신용호)
    if(!isAuthenticated) {
        return "egovframework/com/uat/uia/EgovLoginUsr";
    }

	ncrdVO.setPageUnit(propertyService.getInt("pageUnit"));
	ncrdVO.setPageSize(propertyService.getInt("pageSize"));

	PaginationInfo paginationInfo = new PaginationInfo();

	paginationInfo.setCurrentPageNo(ncrdVO.getPageIndex());
	paginationInfo.setRecordCountPerPage(ncrdVO.getPageUnit());
	paginationInfo.setPageSize(ncrdVO.getPageSize());

	ncrdVO.setFirstIndex(paginationInfo.getFirstRecordIndex());
	ncrdVO.setLastIndex(paginationInfo.getLastRecordIndex());
	ncrdVO.setRecordCountPerPage(paginationInfo.getRecordCountPerPage());

	ncrdVO.setEmplyrId(user.getUniqId());

	Map<String, Object> map = ncrdService.selectNcrdItems(ncrdVO);
	int totCnt = Integer.parseInt((String)map.get("resultCnt"));

	paginationInfo.setTotalRecordCount(totCnt);

	model.addAttribute("uniqId", user.getUniqId());
	model.addAttribute("resultList", map.get("resultList"));
	model.addAttribute("resultCnt", map.get("resultCnt"));
	model.addAttribute("paginationInfo", paginationInfo);

	return "egovframework/com/cop/ncm/EgovNcrdList";
    }

    /**
     * 명함 정보를 삭제한다.
     *
     * @param nameCard
     * @param sessionVO
     * @param model
     * @return
     * @throws Exception
     */

    @RequestMapping("/cop/ncm/deleteNcrdInf.do")
    public String deleteNcrdItem(@ModelAttribute("searchVO") NameCardVO ncrdVO, SessionStatus status,
	    ModelMap model) throws Exception {

	LoginVO user = (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser();
	Boolean isAuthenticated = EgovUserDetailsHelper.isAuthenticated();
	 // KISA 보안취약점 조치 (2018-12-10, 신용호)
    if(!isAuthenticated) {
        return "egovframework/com/uat/uia/EgovLoginUsr";
    }

	ncrdVO.setEmplyrId(user.getUniqId());

	if (isAuthenticated) {
	    ncrdService.deleteNcrdItem(ncrdVO);
	}

	return "forward:/cop/ncm/selectNcrdInfs.do";
    }

    /**
     * 명함 정보 등록을 위한 등록페이지로 이동한다.
     *
     * @param nameCard
     * @param sessionVO
     * @param status
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping("/cop/ncm/addNcrdInf.do")
    public String addNcrdItem(@ModelAttribute("searchVO") NameCardVO ncrdVO, SessionStatus status, ModelMap model) throws Exception {
	return "egovframework/com/cop/ncm/EgovNcrdRegist";
    }

    /**
     * 명함 정보를 등록한다.
     *
     * @param nameCard
     * @param sessionVO
     * @param status
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping("/cop/ncm/insertNcrdInf.do")
    public String insertNcrdItem(@ModelAttribute("searchVO") NameCardVO ncrdVO, @ModelAttribute("nameCard") NameCard nameCard,
	    BindingResult bindingResult, SessionStatus status, ModelMap model) throws Exception {

	LoginVO user = (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser();
	Boolean isAuthenticated = EgovUserDetailsHelper.isAuthenticated();
	 // KISA 보안취약점 조치 (2018-12-10, 신용호)
    if(!isAuthenticated) {
        return "egovframework/com/uat/uia/EgovLoginUsr";
    }

	beanValidator.validate(nameCard, bindingResult);
	if (bindingResult.hasErrors()) {
	    return "egovframework/com/cop/ncm/EgovNcrdRegist";
	}

	nameCard.setAdres(nameCard.getZipCode() + " " + nameCard.getAdres());
	nameCard.setFrstRegisterId(user.getUniqId());

	if (isAuthenticated) {
	    ncrdService.insertNcrdItem(nameCard);
	}

	return "forward:/cop/ncm/selectMyNcrdUseInf.do";
    }

    /**
     * 명함 정보에 대한 상세정보를 조회한다
     *
     * @param nameCard
     * @param sessionVO
     * @param status
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping("/cop/ncm/selectNcrdInf.do")
    public String selectNcrdItem(@ModelAttribute("searchVO") NameCardVO ncrdVO, SessionStatus status, ModelMap model) throws Exception {

	LoginVO user = (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser();
	Boolean isAuthenticated = EgovUserDetailsHelper.isAuthenticated();
	// KISA 보안취약점 조치 (2018-12-10, 신용호)
    if(!isAuthenticated) {
        return "egovframework/com/uat/uia/EgovLoginUsr";
    }

	ncrdVO.setFrstRegisterId(user.getUniqId());

	NameCardVO vo = ncrdService.selectNcrdItem(ncrdVO);

	model.addAttribute("ncrdVO", vo);

	return "egovframework/com/cop/ncm/EgovNcrdUpdt";
    }

    /**
     * 명함 정보를 수정한다.
     *
     * @param nameCard
     * @param sessionVO
     * @param status
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping("/cop/ncm/updateNcrdInf.do")
    public String updateNcrdItem(@ModelAttribute("searchVO") NameCardVO ncrdVO, @RequestParam("ncrdNm") String ncrdNm,
	    @ModelAttribute("nameCard") NameCard nameCard, BindingResult bindingResult, SessionStatus status, ModelMap model) throws Exception {

	LoginVO user = (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser();
	Boolean isAuthenticated = EgovUserDetailsHelper.isAuthenticated();
	// KISA 보안취약점 조치 (2018-12-10, 신용호)
    if(!isAuthenticated) {
        return "egovframework/com/uat/uia/EgovLoginUsr";
    }

	beanValidator.validate(nameCard, bindingResult);
	if (bindingResult.hasErrors()) {
	    ncrdVO.setFrstRegisterId(user.getUniqId());

	    NameCardVO vo  = ncrdService.selectNcrdItem(ncrdVO);

	    model.addAttribute("ncrdVO", vo);

	    return "egovframework/com/cop/ncm/EgovNcrdUpdt";
	}

	if (!"".equals(nameCard.getZipCode())) {
	    nameCard.setAdres(nameCard.getZipCode() + " " + nameCard.getAdres());
	}

	nameCard.setLastUpdusrId(user.getUniqId());

	if (isAuthenticated) {
	    ncrdService.updateNcrdItem(nameCard);
	}

	return "forward:/cop/ncm/selectMyNcrdUseInf.do";
    }

    /**
     * 명함사용자 정보를 등록한다.
     *
     * @param ncrdUser
     * @param sessionVO
     * @param status
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping("/cop/ncm/insertNcrdUseInf.do")
    public String insertNcrdUseInf(@ModelAttribute("ncrdUser") NameCardUser ncrdUser, @ModelAttribute("ncrdVO") NameCardVO ncrdVO,
	    SessionStatus status, ModelMap model) throws Exception {

	LoginVO user = (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser();
	Boolean isAuthenticated = EgovUserDetailsHelper.isAuthenticated();
	 // KISA 보안취약점 조치 (2018-12-10, 신용호)
    if(!isAuthenticated) {
        return "egovframework/com/uat/uia/EgovLoginUsr";
    }

	ncrdUser.setEmplyrId(user.getUniqId());
	ncrdUser.setUseAt("Y");

	if (isAuthenticated) {
	    ncrdService.insertNcrdUseInf(ncrdUser);
	}
	return "forward:/cop/ncm/selectMyNcrdUseInf.do";
    }

    /**
     * 명함 정보에 대한 목록을 조회한다.
     *
     * @param ncrdUser
     * @param sessionVO
     * @param status
     * @param model
     * @return
     * @throws Exception
     */
    @IncludedInfo(name="내명함목록",order = 371 ,gid = 40)
    @RequestMapping("/cop/ncm/selectMyNcrdUseInf.do")
    public String selectNcrdUseInf(@ModelAttribute("searchVO") NameCardUser ncrdUser, SessionStatus status, ModelMap model) throws Exception {

	LoginVO user = (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser();
	Boolean isAuthenticated = EgovUserDetailsHelper.isAuthenticated();
	 // KISA 보안취약점 조치 (2018-12-10, 신용호)
    if(!isAuthenticated) {
        return "egovframework/com/uat/uia/EgovLoginUsr";
    }

	ncrdUser.setPageUnit(propertyService.getInt("pageUnit"));
	ncrdUser.setPageSize(propertyService.getInt("pageSize"));

	PaginationInfo paginationInfo = new PaginationInfo();

	paginationInfo.setCurrentPageNo(ncrdUser.getPageIndex());
	paginationInfo.setRecordCountPerPage(ncrdUser.getPageUnit());
	paginationInfo.setPageSize(ncrdUser.getPageSize());

	ncrdUser.setFirstIndex(paginationInfo.getFirstRecordIndex());
	ncrdUser.setLastIndex(paginationInfo.getLastRecordIndex());
	ncrdUser.setRecordCountPerPage(paginationInfo.getRecordCountPerPage());

	ncrdUser.setEmplyrId(user.getUniqId());

	Map<String, Object> map = ncrdService.selectNcrdUseInfs(ncrdUser);
	int totCnt = Integer.parseInt((String)map.get("resultCnt"));

	paginationInfo.setTotalRecordCount(totCnt);

	model.addAttribute("resultList", map.get("resultList"));
	model.addAttribute("resultCnt", map.get("resultCnt"));
	model.addAttribute("uniqId", user.getUniqId());
	model.addAttribute("paginationInfo", paginationInfo);

	return "egovframework/com/cop/ncm/EgovMyNcrdList";
    }

    /**
     * 명함사용자 정보를 수정한다.
     *
     * @param ncrdUser
     * @param sessionVO
     * @param status
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping("/cop/ncm/updateNcrdUseInf.do")
    public String updateNcrdUseInf(@ModelAttribute("ncrdUser") NameCardUser ncrdUser, @ModelAttribute("ncrdVO") NameCardVO ncrdVO,
	    SessionStatus status, ModelMap model) throws Exception {

	@SuppressWarnings("unused")
	LoginVO user = (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser();
	Boolean isAuthenticated = EgovUserDetailsHelper.isAuthenticated();

	ncrdUser.setUseAt("N");

	if (isAuthenticated) {
	    ncrdService.updateNcrdUseInf(ncrdUser);
	}

	return "forward:/cop/ncm/selectMyNcrdUseInf.do";
    }

    /**
     * 명함 정보에 대한 상세정보를 조회한다.
     *
     * @param ncrdVO
     * @param sessionVO
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping("/cop/ncm/selectNcrdInfPopup.do")
    public String selectNcrdItemforPop(@ModelAttribute("searchVO") NameCardVO ncrdVO, ModelMap model) throws Exception {

	LoginVO user = (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser();
	Boolean isAuthenticated = EgovUserDetailsHelper.isAuthenticated();
	// KISA 보안취약점 조치 (2018-12-10, 신용호)
    if(!isAuthenticated) {
        return "egovframework/com/uat/uia/EgovLoginUsr";
    }

	ncrdVO.setFrstRegisterId(user.getUniqId());

	NameCardVO vo = ncrdService.selectNcrdItem(ncrdVO);

	model.addAttribute("ncrdVO", vo);

	return "egovframework/com/cop/ncm/EgovNcrdInqirePopup";
    }
}


text:
#include <stddef.h>
#include "types.h"
#include "elf.h"
#include "string.h"
#include "stdio.h"
#include "page.h"
#include "ops.h"

#include "of.h"

static void *of_stdout_handle;

static int of_console_open(void)
{
	void *devp;

	if (((devp = of_finddevice("/chosen")) != NULL)
	    && (of_getprop(devp, "stdout", &of_stdout_handle,
			   sizeof(of_stdout_handle))
		== sizeof(of_stdout_handle)))
		return 0;

	return -1;
}

static void of_console_write(const char *buf, int len)
{
	of_call_prom("write", 3, 1, of_stdout_handle, buf, len);
}

void of_console_init(void)
{
	console_ops.open = of_console_open;
	console_ops.write = of_console_write;
}


text:
"use strict";

var U       = require('util');
var Base    = require('./base');

// ****************************************
// Utility functions - no use of vars
// ****************************************

exports.common = function() {
    var obj         = new Base.BaseObject();

    obj._now        = function () {
                        return Math.round( new Date().getTime() / 1000 );
                    };

    obj._json_pp    = function(data) {
                        return JSON.stringify( data , null, 2 );
                    };

    obj._error      = function(data) {
                        U.error( U.inspect( data, false, 5 ) );
                    };

    obj._log        = function(data) {
                        process.stderr.write( U.inspect( data, false, 5 ) + "\n" );
                    };

    obj._stats_pp = function(data) {
                        var copy = data || '';
                        // replace any characters that are invalid statsd output with
                        // an _. Then, replace multiple _ with a single one.
                        copy = copy.replace( /[^\w-.]/g, "_" );
                        copy = copy.replace( /_+/g, "_" );
                        return copy;
                    };

    // If debug or trace aren't enabled, create an optimized version
    // of the function so it performs better
    obj._debug      = function(data) {
                        // config is loaded, check if we have debug
                        // and then REDEFINE the function with an
                        // optimized version.
                        if( obj.config_object().config ) {
                            if( obj.config_object().config.debug ) {
                                this._debug = function(data) {
                                     process.stderr.write(
                                        "DEBUG: " + U.inspect( data, false, 5 ) + "\n" );
                                };
                                // And also call the function, as you wanted
                                // the data printed
                                this._debug( data );

                            // Debug isn't enabled, insert empty function
                            } else {
                                this._debug = function(){};
                            }
                        }
                    }.bind(obj);

    obj._trace      = function(data) {
                        // config is loaded, check if we have debug
                        // and then REDEFINE the function with an
                        // optimized version.
                        if( obj.config_object().config ) {
                            if( obj.config_object().config.trace ) {
                                this._trace = function(data) {
                                    process.stderr.write(
                                        "TRACE: " + U.inspect( data, false, 5 ) + "\n" );
                                };
                                // And also call the function, as you wanted
                                // the data printed
                                this._trace( data );

                            // Trace isn't enabled, insert empty function
                            } else {
                                this._trace = function(){};
                            }
                        }
                    }.bind(obj);
    return obj;
};


text:
package voting

import "testing"

type NastyError error

type MockedRegistry struct {
	AddCandidateFunc    func(name string) error
	RemoveCandidateFunc func(name string) error
}

func (mr *MockedRegistry) AddCandidate(name string) error {
	return mr.AddCandidateFunc(name)
}

func (mr *MockedRegistry) RemoveCandidate(name string) error {
	return mr.RemoveCandidateFunc(name)
}

func TestNewCandidatesCreatesInstanceWithGivenRegistry(t *testing.T) {
	registry := &MockedRegistry{}

	service := NewCandidates(registry)

	if service == nil {
		t.Error("New instance is nil.")
	}

	if service.registry != registry {
		t.Error("Registry is not the one passed to constructor.")
	}
}

func TestAddTrigersRegistryAddCandidate(t *testing.T) {
	var (
		expectedName = "Max"
		added        = false
	)
	registry := &MockedRegistry{
		AddCandidateFunc: func(name string) error {
			if name == expectedName {
				added = true
			}
			return nil
		},
	}

	svc := NewCandidates(registry)
	err := svc.Add(expectedName)
	if err != nil {
		t.Error("Error occurred did not expect that.")
	}

	if !added {
		t.Error("Candidate was not added.")
	}
}

func TestDelTrigersRegistryRemoveCandidate(t *testing.T) {
	var (
		expectedName = "Jonas"
		removed      = false
	)
	registry := &MockedRegistry{
		RemoveCandidateFunc: func(name string) error {
			if name == expectedName {
				removed = true
			}
			return nil
		},
	}

	svc := NewCandidates(registry)
	err := svc.Del(expectedName)
	if err != nil {
		t.Error("Error occurred did not expect that.")
	}

	if !removed {
		t.Error("Candidate was not removed.")
	}
}

func TestAddReturnsErrorIfRegistryDid(t *testing.T) {
	var errWithRegistry NastyError

	registry := &MockedRegistry{
		AddCandidateFunc: func(name string) error {
			return errWithRegistry
		},
	}

	svc := NewCandidates(registry)

	err := svc.Add("anything")

	if err != errWithRegistry {
		t.Error("Error differs from the one we expect.")
	}
}

func TestDelReturnsErrorIfRegistryDid(t *testing.T) {
	var errWithRegistry NastyError

	registry := &MockedRegistry{
		RemoveCandidateFunc: func(name string) error {
			return errWithRegistry
		},
	}

	svc := NewCandidates(registry)

	err := svc.Del("anything")

	if err != errWithRegistry {
		t.Error("Error differs from the one we expect.")
	}
}


text:
'''
This file is part of LIO(tm).
Copyright (c) 2011-2014 by Datera, Inc

Licensed under the Apache License, Version 2.0 (the "License"); you may
not use this file except in compliance with the License. You may obtain
a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations
under the License.
'''

from log import Log
from console import Console
from shell import ConfigShell
from node import ConfigNode, ExecutionError
from prefs import Prefs

__version__ = 'GIT_VERSION'
__author__ = "Jerome Martin <jxm@risingtidesystems.com>"
__url__ = "http://www.risingtidesystems.com"
__description__ = "A framework to implement simple but nice CLIs."
__license__ = __doc__


text:
package org.jenkinsci.plugins.ec2harness;

import static org.mockito.Mockito.when;
import hudson.Extension;
import hudson.model.Descriptor;
import hudson.plugins.ec2.EC2PrivateKey;
import hudson.plugins.ec2.Messages;
import hudson.plugins.ec2.AmazonEC2Cloud;
import hudson.slaves.Cloud;
import hudson.util.FormValidation;
import hudson.util.ListBoxModel;

import java.io.IOException;
import java.net.URL;
import java.util.*;

import javax.servlet.ServletException;

import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
import org.mockito.Mockito;

import com.amazonaws.AmazonClientException;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.model.KeyPair;

/// This class is the main entry point.  It is a new type
/// of Cloud.  It also wraps (technically: derives from)
/// the AmazonEC2Cloud class, and drives it.
/// It creates an instance of MockAmazonEC2, which is a mock
/// or 'stubbed' version of the AmazonEC2 interface
public class AmazonEC2CloudTester extends AmazonEC2Cloud
{
	static MockAmazonEC2 mockAmazonEC2;

    @DataBoundConstructor
    public AmazonEC2CloudTester(String accessId, String secretKey, String region, String privateKey, String instanceCapStr,
    		List<SlaveTemplateForTests> templates) {
        super("mockec2cloud_" + region, accessId, secretKey, privateKey,
         instanceCapStr, templates);
    }

	@Override
    public synchronized AmazonEC2 connect() throws AmazonClientException {
		if( connection == null ) {
			mockAmazonEC2 = new MockAmazonEC2();
			connection = mockAmazonEC2;
	    	mockAmazonEC2.setKeyName("testkeypair");
	    	try {
				mockAmazonEC2.setFingerprint(privateKey.getFingerprint());
			} catch (IOException e) {
				e.printStackTrace();
			}
	    	mockAmazonEC2.setPrivateKey(privateKey.getPrivateKey());
		}
		return connection;
	}

	@Extension
	public static class DescriptorImpl extends Descriptor<Cloud> {

		@Override
		public String getDisplayName() {
			return "AmazonEC2CloudTester";
		}

		public ListBoxModel doFillBidTypeItems( @QueryParameter String accessId,
				@QueryParameter String secretKey, @QueryParameter String region) throws IOException,
				ServletException {
			ListBoxModel model = new ListBoxModel();
			return model;
		}

		public ListBoxModel doFillRegionItems(@QueryParameter String accessId,
				@QueryParameter String secretKey, @QueryParameter String region) throws IOException,
				ServletException {
			ListBoxModel model = new ListBoxModel();
			model.add(AmazonEC2Cloud.DEFAULT_EC2_HOST);
			return model;
		}

        public FormValidation doTestConnection( URL ec2endpoint,
                String accessId, String secretKey, String privateKey) throws IOException, ServletException {
            return FormValidation.ok(Messages.EC2Cloud_Success());
        }
	}
}


text:
package org.onosproject.net.topology.impl;

import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.ReferenceCardinality;
import org.apache.felix.scr.annotations.Service;
import org.onosproject.net.DisjointPath;
import org.onosproject.net.provider.AbstractListenerProviderRegistry;
import org.onosproject.event.Event;
import org.onosproject.net.ConnectPoint;
import org.onosproject.net.DeviceId;
import org.onosproject.net.Link;
import org.onosproject.net.Path;
import org.onosproject.net.provider.AbstractProviderService;
import org.onosproject.net.topology.ClusterId;
import org.onosproject.net.topology.GraphDescription;
import org.onosproject.net.topology.LinkWeigher;
import org.onosproject.net.topology.LinkWeight;
import org.onosproject.net.topology.Topology;
import org.onosproject.net.topology.TopologyCluster;
import org.onosproject.net.topology.TopologyEvent;
import org.onosproject.net.topology.TopologyGraph;
import org.onosproject.net.topology.TopologyListener;
import org.onosproject.net.topology.TopologyProvider;
import org.onosproject.net.topology.TopologyProviderRegistry;
import org.onosproject.net.topology.TopologyProviderService;
import org.onosproject.net.topology.TopologyService;
import org.onosproject.net.topology.TopologyStore;
import org.onosproject.net.topology.TopologyStoreDelegate;
import org.slf4j.Logger;

import java.util.List;
import java.util.Set;
import java.util.stream.Stream;
import java.util.Map;

import static com.google.common.base.Preconditions.checkNotNull;
import static org.onosproject.net.topology.AdapterLinkWeigher.adapt;
import static org.onosproject.security.AppGuard.checkPermission;
import static org.slf4j.LoggerFactory.getLogger;
import static org.onosproject.security.AppPermission.Type.*;

/**
 * Provides basic implementation of the topology SB & NB APIs.
 */
@Component(immediate = true)
@Service
public class TopologyManager
        extends AbstractListenerProviderRegistry<TopologyEvent, TopologyListener,
        TopologyProvider, TopologyProviderService>
        implements TopologyService, TopologyProviderRegistry {

    private static final String TOPOLOGY_NULL = "Topology cannot be null";
    private static final String DEVICE_ID_NULL = "Device ID cannot be null";
    private static final String CLUSTER_ID_NULL = "Cluster ID cannot be null";
    private static final String CLUSTER_NULL = "Topology cluster cannot be null";
    private static final String CONNECTION_POINT_NULL = "Connection point cannot be null";
    private static final String LINK_WEIGHT_NULL = "Link weight cannot be null";

    private final Logger log = getLogger(getClass());

    private TopologyStoreDelegate delegate = new InternalStoreDelegate();

    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
    protected TopologyStore store;

    @Activate
    public void activate() {
        store.setDelegate(delegate);
        eventDispatcher.addSink(TopologyEvent.class, listenerRegistry);
        log.info("Started");
    }

    @Deactivate
    public void deactivate() {
        store.unsetDelegate(delegate);
        eventDispatcher.removeSink(TopologyEvent.class);
        log.info("Stopped");
    }

    @Override
    public Topology currentTopology() {
        checkPermission(TOPOLOGY_READ);
        return store.currentTopology();
    }

    @Override
    public boolean isLatest(Topology topology) {
        checkPermission(TOPOLOGY_READ);
        checkNotNull(topology, TOPOLOGY_NULL);
        return store.isLatest(topology);
    }

    @Override
    public Set<TopologyCluster> getClusters(Topology topology) {
        checkPermission(TOPOLOGY_READ);
        checkNotNull(topology, TOPOLOGY_NULL);
        return store.getClusters(topology);
    }

    @Override
    public TopologyCluster getCluster(Topology topology, ClusterId clusterId) {
        checkPermission(TOPOLOGY_READ);
        checkNotNull(topology, TOPOLOGY_NULL);
        checkNotNull(topology, CLUSTER_ID_NULL);
        return store.getCluster(topology, clusterId);
    }

    @Override
    public Set<DeviceId> getClusterDevices(Topology topology, TopologyCluster cluster) {
        checkPermission(TOPOLOGY_READ);
        checkNotNull(topology, TOPOLOGY_NULL);
        checkNotNull(topology, CLUSTER_NULL);
        return store.getClusterDevices(topology, cluster);
    }

    @Override
    public Set<Link> getClusterLinks(Topology topology, TopologyCluster cluster) {
        checkPermission(TOPOLOGY_READ);
        checkNotNull(topology, TOPOLOGY_NULL);
        checkNotNull(topology, CLUSTER_NULL);
        return store.getClusterLinks(topology, cluster);
    }

    @Override
    public TopologyGraph getGraph(Topology topology) {
        checkPermission(TOPOLOGY_READ);
        checkNotNull(topology, TOPOLOGY_NULL);
        return store.getGraph(topology);
    }

    @Override
    public Set<Path> getPaths(Topology topology, DeviceId src, DeviceId dst) {
        checkPermission(TOPOLOGY_READ);
        checkNotNull(topology, TOPOLOGY_NULL);
        checkNotNull(src, DEVICE_ID_NULL);
        checkNotNull(dst, DEVICE_ID_NULL);
        return store.getPaths(topology, src, dst);
    }

    @Override
    public Set<Path> getPaths(Topology topology, DeviceId src,
                              DeviceId dst, LinkWeight weight) {
        return getPaths(topology, src, dst, adapt(weight));
    }

    @Override
    public Set<Path> getPaths(Topology topology, DeviceId src,
                              DeviceId dst, LinkWeigher weigher) {
        checkPermission(TOPOLOGY_READ);

        checkNotNull(topology, TOPOLOGY_NULL);
        checkNotNull(src, DEVICE_ID_NULL);
        checkNotNull(dst, DEVICE_ID_NULL);
        checkNotNull(weigher, LINK_WEIGHT_NULL);
        return store.getPaths(topology, src, dst, weigher);
    }

    @Override
    public Set<Path> getKShortestPaths(Topology topology, DeviceId src,
                                       DeviceId dst, LinkWeigher weigher,
                                       int maxPaths) {
        checkPermission(TOPOLOGY_READ);

        checkNotNull(topology, TOPOLOGY_NULL);
        checkNotNull(src, DEVICE_ID_NULL);
        checkNotNull(dst, DEVICE_ID_NULL);
        checkNotNull(weigher, LINK_WEIGHT_NULL);
        return store.getKShortestPaths(topology, src, dst, weigher, maxPaths);
    }

    @Override
    public Stream<Path> getKShortestPaths(Topology topology,
                                          DeviceId src,
                                          DeviceId dst,
                                          LinkWeigher weigher) {
        checkPermission(TOPOLOGY_READ);

        checkNotNull(topology, TOPOLOGY_NULL);
        checkNotNull(src, DEVICE_ID_NULL);
        checkNotNull(dst, DEVICE_ID_NULL);
        checkNotNull(weigher, LINK_WEIGHT_NULL);
        return store.getKShortestPaths(topology, src, dst, weigher);
    }

    @Override
    public Set<DisjointPath> getDisjointPaths(Topology topology, DeviceId src,
                                              DeviceId dst) {
        checkPermission(TOPOLOGY_READ);
        checkNotNull(topology, TOPOLOGY_NULL);
        checkNotNull(src, DEVICE_ID_NULL);
        checkNotNull(dst, DEVICE_ID_NULL);
        return store.getDisjointPaths(topology, src, dst);
    }

    @Override
    public Set<DisjointPath> getDisjointPaths(Topology topology, DeviceId src,
                                              DeviceId dst,
                                              LinkWeight weight) {
        return getDisjointPaths(topology, src, dst, adapt(weight));
    }

    @Override
    public Set<DisjointPath> getDisjointPaths(Topology topology, DeviceId src,
                                              DeviceId dst,
                                              LinkWeigher weigher) {
        checkPermission(TOPOLOGY_READ);
        checkNotNull(topology, TOPOLOGY_NULL);
        checkNotNull(src, DEVICE_ID_NULL);
        checkNotNull(dst, DEVICE_ID_NULL);
        checkNotNull(weigher, LINK_WEIGHT_NULL);
        return store.getDisjointPaths(topology, src, dst, weigher);
    }

    @Override
    public Set<DisjointPath> getDisjointPaths(Topology topology, DeviceId src,
                                              DeviceId dst,
                                              Map<Link, Object> riskProfile) {
        checkPermission(TOPOLOGY_READ);
        checkNotNull(topology, TOPOLOGY_NULL);
        checkNotNull(src, DEVICE_ID_NULL);
        checkNotNull(dst, DEVICE_ID_NULL);
        return store.getDisjointPaths(topology, src, dst, riskProfile);
    }

    @Override
    public Set<DisjointPath> getDisjointPaths(Topology topology, DeviceId src,
                                              DeviceId dst, LinkWeight weight,
                                              Map<Link, Object> riskProfile) {
        return getDisjointPaths(topology, src, dst, adapt(weight), riskProfile);
    }

    @Override
    public Set<DisjointPath> getDisjointPaths(Topology topology, DeviceId src,
                                              DeviceId dst,
                                              LinkWeigher weigher,
                                              Map<Link, Object> riskProfile) {
        checkPermission(TOPOLOGY_READ);
        checkNotNull(topology, TOPOLOGY_NULL);
        checkNotNull(src, DEVICE_ID_NULL);
        checkNotNull(dst, DEVICE_ID_NULL);
        checkNotNull(weigher, LINK_WEIGHT_NULL);
        return store.getDisjointPaths(topology, src, dst, weigher, riskProfile);
    }

    @Override
    public boolean isInfrastructure(Topology topology, ConnectPoint connectPoint) {
        checkPermission(TOPOLOGY_READ);
        checkNotNull(topology, TOPOLOGY_NULL);
        checkNotNull(connectPoint, CONNECTION_POINT_NULL);
        return store.isInfrastructure(topology, connectPoint);
    }

    @Override
    public boolean isBroadcastPoint(Topology topology, ConnectPoint connectPoint) {
        checkPermission(TOPOLOGY_READ);
        checkNotNull(topology, TOPOLOGY_NULL);
        checkNotNull(connectPoint, CONNECTION_POINT_NULL);
        return store.isBroadcastPoint(topology, connectPoint);
    }

    // Personalized host provider service issued to the supplied provider.
    @Override
    protected TopologyProviderService createProviderService(TopologyProvider provider) {
        return new InternalTopologyProviderService(provider);
    }

    private class InternalTopologyProviderService
            extends AbstractProviderService<TopologyProvider>
            implements TopologyProviderService {

        InternalTopologyProviderService(TopologyProvider provider) {
            super(provider);
        }

        @Override
        public void topologyChanged(GraphDescription topoDescription,
                                    List<Event> reasons) {
            checkNotNull(topoDescription, "Topology description cannot be null");

            TopologyEvent event = store.updateTopology(provider().id(),
                                                       topoDescription, reasons);
            if (event != null) {
                log.info("Topology {} changed", event.subject());
                post(event);
            }
        }
    }

    // Store delegate to re-post events emitted from the store.
    private class InternalStoreDelegate implements TopologyStoreDelegate {
        @Override
        public void notify(TopologyEvent event) {
            post(event);
        }
    }
}