text:
require 'spec_helper'
describe JSONAPIonify do
  # ---
  # version: 1.0
  # ---
  #
  # Introduction
  # ============
  #
  # JSON API is a specification for how a client should request that resources be
  # fetched or modified, and how a server should respond to those requests.
  #
  # JSON API is designed to minimize both the number of requests and the amount of
  # data transmitted between clients and servers. This efficiency is achieved
  # without compromising readability, flexibility, or discoverability.
  #
  # JSON API requires use of the JSON API media type
  # ([`application/vnd.api+json`](http://www.iana.org/assignments/media-types/application/vnd.api+json))
  # for exchanging data.
  #
  # Conventions
  # ===========
  #
  # The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD",
  # "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be
  # interpreted as described in RFC 2119
  # [[RFC2119](http://tools.ietf.org/html/rfc2119)].
  #
  # Content Negotiation
  # ===================
  #
  # Client Responsibilities
  # -----------------------
  #
  # Todo: Should implement client responsibilities.
  #
  # Clients **MUST** send all JSON API data in request documents with the header
  # `Content-Type: application/vnd.api+json` without any media type parameters.
  #
  # Clients that include the JSON API media type in their `Accept` header **MUST**
  # specify the media type there at least once without any media type parameters.
  #
  # Clients **MUST** ignore any parameters for the `application/vnd.api+json`
  # media type received in the `Content-Type` header of response documents.
  #
  # Server Responsibilities
  # -----------------------
  #
  # Todo: Should implement server responsibilities.
  #
  # Servers **MUST** send all JSON API data in response documents with the header
  # `Content-Type: application/vnd.api+json` without any media type parameters.
  #
  # Servers **MUST** respond with a `415 Unsupported Media Type` status code if
  # a request specifies the header `Content-Type: application/vnd.api+json`
  # with any media type parameters.
  #
  # Servers **MUST** respond with a `406 Not Acceptable` status code if a
  # request's `Accept` header contains the JSON API media type and all instances
  # of that media type are modified with media type parameters.
  #
  # > Note: The content negotiation requirements exist to allow future versions
  # of this specification to use media type parameters for extension negotiation
  # and versioning.

  # Fetching Data
  # =============
  #
  # Data, including resources and relationships, can be fetched by sending a
  # `GET` request to an endpoint.
  #
  # Responses can be further refined with the optional features described below.
  #
  # Fetching Resources
  # ==================
  #
  # A server **MUST** support fetching resource data for every URL provided as:
  #
  # * a `self` link as part of the top-level links object
  # * a `self` link as part of a resource-level links object
  # * a `related` link as part of a relationship-level links object
  #
  # For example, the following request fetches a collection of articles:
  #
  # ```http
  # GET /articles HTTP/1.1
  # Accept: application/vnd.api+json
  # ```
  #
  # The following request fetches an article:
  #
  # ```http
  # GET /articles/1 HTTP/1.1
  # Accept: application/vnd.api+json
  # ```
  #
  # And the following request fetches an article's author:
  #
  # ```http
  # GET /articles/1/author HTTP/1.1
  # Accept: application/vnd.api+json
  # ```
  #
  # Responses
  # =========
  #
  # 200 OK
  # ======
  #
  # A server **MUST** respond to a successful request to fetch an individual
  # resource or resource collection with a `200 OK` response.
  #
  # A server **MUST** respond to a successful request to fetch a resource
  # collection with an array of [resource objects] or an empty array (`[]`) as
  # the response document's primary data.
  #
  # For example, a `GET` request to a collection of articles could return:
  #
  # ```http
  # HTTP/1.1 200 OK
  # Content-Type: application/vnd.api+json
  #
  # {
  #   "links": {
  #     "self": "http://example.com/articles"
  #   },
  #   "data": [{
  #     "type": "articles",
  #     "id": "1",
  #     "attributes": {
  #       "title": "JSON API paints my bikeshed!"
  #     }
  #   }, {
  #     "type": "articles",
  #     "id": "2",
  #     "attributes": {
  #       "title": "Rails is Omakase"
  #     }
  #   }]
  # }
  # ```
  #
  # A similar response representing an empty collection would be:
  #
  # ```http
  # HTTP/1.1 200 OK
  # Content-Type: application/vnd.api+json
  #
  # {
  #   "links": {
  #     "self": "http://example.com/articles"
  #   },
  #   "data": []
  # }
  # ```
  #
  # A server **MUST** respond to a successful request to fetch an individual
  # resource with a [resource object][resource objects] or `null` provided as
  # the response document's primary data.
  #
  # `null` is only an appropriate response when the requested URL is one that
  # might correspond to a single resource, but doesn't currently.
  #
  # > Note: Consider, for example, a request to fetch a to-one related resource link.
  # This request would respond with `null` when the relationship is empty (such that
  # the link is corresponding to no resources) but with the single related resource's
  # [resource object][resource objects] otherwise.
  #
  # For example, a `GET` request to an individual article could return:
  #
  # ```http
  # HTTP/1.1 200 OK
  # Content-Type: application/vnd.api+json
  #
  # {
  #   "links": {
  #     "self": "http://example.com/articles/1"
  #   },
  #   "data": {
  #     "type": "articles",
  #     "id": "1",
  #     "attributes": {
  #       "title": "JSON API paints my bikeshed!"
  #     },
  #     "relationships": {
  #       "author": {
  #         "links": {
  #           "related": "http://example.com/articles/1/author"
  #         }
  #       }
  #     }
  #   }
  # }
  # ```
  #
  # If the above article's author is missing, then a `GET` request to that related
  # resource would return:
  #
  # ```http
  # HTTP/1.1 200 OK
  # Content-Type: application/vnd.api+json
  #
  # {
  #   "links": {
  #     "self": "http://example.com/articles/1/author"
  #   },
  #   "data": null
  # }
  # ```
  #
  # 404 Not Found
  # =============
  #
  # A server **MUST** respond with `404 Not Found` when processing a request to
  # fetch a single resource that does not exist, except when the request warrants a
  # `200 OK` response with `null` as the primary data (as described above).
  #
  # Other Responses
  # ===============
  #
  # A server **MAY** respond with other HTTP status codes.
  #
  # A server **MAY** include [error details] with error responses.
  #
  # A server **MUST** prepare responses, and a client **MUST** interpret
  # responses, in accordance with
  # [`HTTP semantics`](http://tools.ietf.org/html/rfc7231).
  #
  # Fetching Relationships
  # ======================
  #
  # A server **MUST** support fetching relationship data for every relationship URL
  # provided as a `self` link as part of a relationship's `links` object.
  #
  # For example, the following request fetches data about an article's comments:
  #
  # ```http
  # GET /articles/1/relationships/comments HTTP/1.1
  # Accept: application/vnd.api+json
  # ```
  #
  # And the following request fetches data about an article's author:
  #
  # ```http
  # GET /articles/1/relationships/author HTTP/1.1
  # Accept: application/vnd.api+json
  # ```
  #
  # Responses
  # =========
  #
  # 200 OK
  # ======
  #
  # A server **MUST** respond to a successful request to fetch a relationship
  # with a `200 OK` response.
  #
  # The primary data in the response document **MUST** match the appropriate
  # value for [resource linkage], as described above for
  # [relationship objects][relationships].
  #
  # The top-level [links object][links] **MAY** contain `self` and `related` links,
  # as described above for [relationship objects][relationships].
  #
  # For example, a `GET` request to a URL from a to-one relationship link could
  # return:
  #
  # ```http
  # HTTP/1.1 200 OK
  # Content-Type: application/vnd.api+json
  #
  # {
  #   "links": {
  #     "self": "/articles/1/relationships/author",
  #     "related": "/articles/1/author"
  #   },
  #   "data": {
  #     "type": "people",
  #     "id": "12"
  #   }
  # }
  # ```
  #
  # If the above relationship is empty, then a `GET` request to the same URL would
  # return:
  #
  # ```http
  # HTTP/1.1 200 OK
  # Content-Type: application/vnd.api+json
  #
  # {
  #   "links": {
  #     "self": "/articles/1/relationships/author",
  #     "related": "/articles/1/author"
  #   },
  #   "data": null
  # }
  # ```
  #
  # A `GET` request to a URL from a to-many relationship link could return:
  #
  # ```http
  # HTTP/1.1 200 OK
  # Content-Type: application/vnd.api+json
  #
  # {
  #   "links": {
  #     "self": "/articles/1/relationships/tags",
  #     "related": "/articles/1/tags"
  #   },
  #   "data": [
  #     { "type": "tags", "id": "2" },
  #     { "type": "tags", "id": "3" }
  #   ]
  # }
  # ```
  #
  # If the above relationship is empty, then a `GET` request to the same URL would
  # return:
  #
  # ```http
  # HTTP/1.1 200 OK
  # Content-Type: application/vnd.api+json
  #
  # {
  #   "links": {
  #     "self": "/articles/1/relationships/tags",
  #     "related": "/articles/1/tags"
  #   },
  #   "data": []
  # }
  # ```
  #
  # 404 Not Found
  # =============
  #
  # A server **MUST** return `404 Not Found` when processing a request to fetch
  # a relationship link URL that does not exist.
  #
  # > Note: This can happen when the parent resource of the relationship
  # does not exist. For example, when `/articles/1` does not exist, request to
  # `/articles/1/relationships/tags` returns `404 Not Found`.
  #
  # If a relationship link URL exists but the relationship is empty, then
  # `200 OK` **MUST** be returned, as described above.
  #
  # Other Responses
  # ===============
  #
  # A server **MAY** respond with other HTTP status codes.
  #
  # A server **MAY** include [error details] with error responses.
  #
  # A server **MUST** prepare responses, and a client **MUST** interpret
  # responses, in accordance with
  # [`HTTP semantics`](http://tools.ietf.org/html/rfc7231).
  #
  # Inclusion of Related Resources
  # ==============================
  #
  # An endpoint **MAY** return resources related to the primary data by default.
  #
  # An endpoint **MAY** also support an `include` request parameter to allow the
  # client to customize which related resources should be returned.
  #
  # If an endpoint does not support the `include` parameter, it must respond with
  # `400 Bad Request` to any requests that include it.
  #
  # If an endpoint supports the `include` parameter and a client supplies it,
  # the server **MUST NOT** include unrequested [resource objects] in the `included`
  # section of the [compound document].
  #
  # The value of the `include` parameter **MUST** be a comma-separated (U+002C
  # COMMA, ",") list of relationship paths. A relationship path is a dot-separated
  # (U+002E FULL-STOP, ".") list of [relationship][relationships] names.
  #
  # If a server is unable to identify a relationship path or does not support
  # inclusion of resources from a path, it **MUST** respond with 400 Bad Request.
  #
  # > Note: For example, a relationship path could be `comments.author`, where
  # `comments` is a relationship listed under a `articles` [resource object][resource objects], and
  # `author` is a relationship listed under a `comments` [resource object][resource objects].
  #
  # For instance, comments could be requested with an article:
  #
  # ```http
  # GET /articles/1?include=comments HTTP/1.1
  # Accept: application/vnd.api+json
  # ```
  #
  # In order to request resources related to other resources, a dot-separated path
  # for each relationship name can be specified:
  #
  # ```http
  # GET /articles/1?include=comments.author HTTP/1.1
  # Accept: application/vnd.api+json
  # ```
  #
  # > Note: Because [compound documents][compound document] require full linkage,
  # intermediate resources in a multi-part path must be returned along with the leaf
  # nodes. For example, a response to a request for `comments.author` should
  # include `comments` as well as the `author` of each of those `comments`.
  #
  # > Note: A server may choose to expose a deeply nested relationship such as
  # `comments.author` as a direct relationship with an alias such as
  # `comment-authors`. This would allow a client to request
  # `/articles/1?include=comment-authors` instead of
  # `/articles/1?include=comments.author`. By abstracting the nested
  # relationship with an alias, the server can still provide full linkage in
  # compound documents without including potentially unwanted intermediate
  # resources.
  #
  # Multiple related resources can be requested in a comma-separated list:
  #
  # ```http
  # GET /articles/1?include=author,comments.author HTTP/1.1
  # Accept: application/vnd.api+json
  # ```
  #
  # Furthermore, related resources can be requested from a relationship endpoint:
  #
  # ```http
  # GET /articles/1/relationships/comments?include=comments.author HTTP/1.1
  # Accept: application/vnd.api+json
  # ```
  #
  # In this case, the primary data would be a collection of
  # [resource identifier objects][resource identifier object] that represent linkage to comments for an article,
  # while the full comments and comment authors would be returned as included data.
  #
  # > Note: This section applies to any endpoint that responds with primary
  # data, regardless of the request type. For instance, a server could support
  # the inclusion of related resources along with a `POST` request to create a
  # resource or relationship.
  #
  # Sparse Fieldsets
  # ================
  #
  # A client **MAY** request that an endpoint return only specific [fields] in the
  # response on a per-type basis by including a `fields[TYPE]` parameter.
  #
  # The value of the `fields` parameter **MUST** be a comma-separated (U+002C
  # COMMA, ",") list that refers to the name(s) of the fields to be returned.
  #
  # If a client requests a restricted set of [fields], an endpoint **MUST NOT**
  # include additional [fields] in the response.
  #
  # ```http
  # GET /articles?include=author&fields[articles]=title,body&fields[people]=name HTTP/1.1
  # Accept: application/vnd.api+json
  # ```
  #
  # > Note: The above example URI shows unencoded `[` and `]` characters simply for
  # readability. In practice, these characters must be percent-encoded, per the
  # requirements [in RFC 3986](http://tools.ietf.org/html/rfc3986#section-3.4).
  #
  # > Note: This section applies to any endpoint that responds with resources as
  # primary or included data, regardless of the request type. For instance, a
  # server could support sparse fieldsets along with a `POST` request to create
  # a resource.
  #
  # Sorting
  # =======
  #
  # A server **MAY** choose to support requests to sort resource collections
  # according to one or more criteria ("sort fields").
  #
  # > Note: Although recommended, sort fields do not necessarily need to
  # correspond to resource attribute and association names.
  #
  # > Note: It is recommended that dot-separated (U+002E FULL-STOP, ".") sort
  # fields be used to request sorting based upon relationship attributes. For
  # example, a sort field of `author.name` could be used to request that the
  # primary data be sorted based upon the `name` attribute of the `author`
  # relationship.
  #
  # An endpoint **MAY** support requests to sort the primary data with a `sort`
  # query parameter. The value for `sort` **MUST** represent sort fields.
  #
  # ```http
  # GET /people?sort=age HTTP/1.1
  # Accept: application/vnd.api+json
  # ```
  #
  # An endpoint **MAY** support multiple sort fields by allowing comma-separated
  # (U+002C COMMA, ",") sort fields. Sort fields **SHOULD** be applied in the
  # order specified.
  #
  # ```http
  # GET /people?sort=age,name HTTP/1.1
  # Accept: application/vnd.api+json
  # ```
  #
  # The sort order for each sort field **MUST** be ascending unless it is prefixed
  # with a minus (U+002D HYPHEN-MINUS, "-"), in which case it **MUST** be descending.
  #
  # ```http
  # GET /articles?sort=-created,title HTTP/1.1
  # Accept: application/vnd.api+json
  # ```
  #
  # The above example should return the newest articles first. Any articles
  # created on the same date will then be sorted by their title in ascending
  # alphabetical order.
  #
  # If the server does not support sorting as specified in the query parameter
  # `sort`, it **MUST** return `400 Bad Request`.
  #
  # If sorting is supported by the server and requested by the client via query
  # parameter `sort`, the server **MUST** return elements of the top-level
  # `data` array of the response ordered according to the criteria specified.
  # The server **MAY** apply default sorting rules to top-level `data` if
  # request parameter `sort` is not specified.
  #
  # > Note: This section applies to any endpoint that responds with a resource
  # collection as primary data, regardless of the request type.
  #
  # Pagination
  # ==========
  #
  # A server **MAY** choose to limit the number of resources returned in a response
  # to a subset ("page") of the whole set available.
  #
  # A server **MAY** provide links to traverse a paginated data set ("pagination
  # links").
  #
  # Pagination links **MUST** appear in the links object that corresponds to a
  # collection. To paginate the primary data, supply pagination links in the
  # top-level `links` object. To paginate an included collection returned in
  # a [compound document], supply pagination links in the corresponding links
  # object.
  #
  # The following keys **MUST** be used for pagination links:
  #
  # * `first`: the first page of data
  # * `last`: the last page of data
  # * `prev`: the previous page of data
  # * `next`: the next page of data
  #
  # Keys **MUST** either be omitted or have a `null` value to indicate that a
  # particular link is unavailable.
  #
  # Concepts of order, as expressed in the naming of pagination links, **MUST**
  # remain consistent with JSON API's [sorting rules](#fetching-sorting).
  #
  # The `page` query parameter is reserved for pagination. Servers and clients
  # **SHOULD** use this key for pagination operations.
  #
  # > Note: JSON API is agnostic about the pagination strategy used by a server.
  # Effective pagination strategies include (but are not limited to):
  # page-based, offset-based, and cursor-based. The `page` query parameter can
  # be used as a basis for any of these strategies. For example, a page-based
  # strategy might use query parameters such as `page[number]` and `page[size]`,
  # an offset-based strategy might use `page[offset]` and `page[limit]`, while a
  # cursor-based strategy might use `page[cursor]`.
  #
  # > Note: The example query parameters above use unencoded `[` and `]` characters
  # simply for readability. In practice, these characters must be percent-encoded,
  # per the requirements in [RFC 3986](http://tools.ietf.org/html/rfc3986#section-3.4).
  #
  # > Note: This section applies to any endpoint that responds with a resource
  # collection as primary data, regardless of the request type.
  #
  # Filtering
  # =========
  #
  # The `filter` query parameter is reserved for filtering data. Servers and clients
  # **SHOULD** use this key for filtering operations.
  #
  # > Note: JSON API is agnostic about the strategies supported by a server. The
  # `filter` query parameter can be used as the basis for any number of filtering
  # strategies.
  #
  # Creating, Updating and Deleting Resources
  # =========================================
  #
  # A server **MAY** allow resources of a given type to be created. It **MAY**
  # also allow existing resources to be modified or deleted.
  #
  # A request **MUST** completely succeed or fail (in a single "transaction"). No
  # partial updates are allowed.
  #
  # > Note: The `type` member is required in every [resource object][resource objects] throughout requests and
  # responses in JSON API. There are some cases, such as when `POST`ing to an
  # endpoint representing heterogenous data, when the `type` could not be inferred
  # from the endpoint. However, picking and choosing when it is required would be
  # confusing; it would be hard to remember when it was required and when it was
  # not. Therefore, to improve consistency and minimize confusion, `type` is
  # always required.
  #
  # Creating Resources
  # ==================
  #
  # A resource can be created by sending a `POST` request to a URL that represents
  # a collection of resources. The request **MUST** include a single [resource object][resource objects]
  # as primary data. The [resource object][resource objects] **MUST** contain at least a `type` member.
  #
  # For instance, a new photo might be created with the following request:
  #
  # ```http
  # POST /photos HTTP/1.1
  # Content-Type: application/vnd.api+json
  # Accept: application/vnd.api+json
  #
  # {
  #   "data": {
  #     "type": "photos",
  #     "attributes": {
  #       "title": "Ember Hamster",
  #       "src": "http://example.com/images/productivity.png"
  #     },
  #     "relationships": {
  #       "photographer": {
  #         "data": { "type": "people", "id": "9" }
  #       }
  #     }
  #   }
  # }
  # ```
  #
  # If a relationship is provided in the `relationships` member of the
  # [resource object][resource objects], its value **MUST** be a relationship object with a `data`
  # member. The value of this key represents the linkage the new resource is to
  # have.
  #
  # Client-Generated IDs
  # ====================
  #
  # A server **MAY** accept a client-generated ID along with a request to create
  # a resource. An ID **MUST** be specified with an `id` key, the value of
  # which **MUST** be a universally unique identifier. The client **SHOULD** use
  # a properly generated and formatted *UUID* as described in RFC 4122
  # [[RFC4122](http://tools.ietf.org/html/rfc4122.html)].
  #
  # > NOTE: In some use-cases, such as importing data from another source, it
  # may be possible to use something other than a UUID that is still guaranteed
  # to be globally unique. Do not use anything other than a UUID unless you are
  # 100% confident that the strategy you are using indeed generates globally
  # unique identifiers.
  #
  # For example:
  #
  # ```http
  # POST /photos HTTP/1.1
  # Content-Type: application/vnd.api+json
  # Accept: application/vnd.api+json
  #
  # {
  #   "data": {
  #     "type": "photos",
  #     "id": "550e8400-e29b-41d4-a716-446655440000",
  #     "attributes": {
  #       "title": "Ember Hamster",
  #       "src": "http://example.com/images/productivity.png"
  #     }
  #   }
  # }
  # ```
  #
  # A server **MUST** return `403 Forbidden` in response to an unsupported request
  # to create a resource with a client-generated ID.
  #
  # Responses
  # =========
  #
  # 201 Created
  # ===========
  #
  # If a `POST` request did not include a [Client-Generated
  # ID](#crud-creating-client-ids) and the requested resource has been created
  # successfully, the server **MUST** return a `201 Created` status code.
  #
  # The response **SHOULD** include a `Location` header identifying the location
  # of the newly created resource.
  #
  # The response **MUST** also include a document that contains the primary
  # resource created.
  #
  # If the [resource object][resource objects] returned by the response contains a `self` key in its
  # `links` member and a `Location` header is provided, the value of the `self`
  # member **MUST** match the value of the `Location` header.
  #
  # ```http
  # HTTP/1.1 201 Created
  # Location: http://example.com/photos/550e8400-e29b-41d4-a716-446655440000
  # Content-Type: application/vnd.api+json
  #
  # {
  #   "data": {
  #     "type": "photos",
  #     "id": "550e8400-e29b-41d4-a716-446655440000",
  #     "attributes": {
  #       "title": "Ember Hamster",
  #       "src": "http://example.com/images/productivity.png"
  #     },
  #     "links": {
  #       "self": "http://example.com/photos/550e8400-e29b-41d4-a716-446655440000"
  #     }
  #   }
  # }
  # ```
  #
  # 202 Accepted
  # ============
  #
  # If a request to create a resource has been accepted for processing, but the
  # processing has not been completed by the time the server responds, the
  # server **MUST** return a `202 Accepted` status code.
  #
  # 204 No Content
  # ==============
  #
  # If a `POST` request *did* include a [Client-Generated
  # ID](#crud-creating-client-ids) and the requested resource has been created
  # successfully, the server **MUST** return either a `201 Created` status code
  # and response document (as described above) or a `204 No Content` status code
  # with no response document.
  #
  # > Note: If a `204` response is received the client should consider the resource
  # object sent in the request to be accepted by the server, as if the server
  # had returned it back in a `201` response.
  #
  # 403 Forbidden
  # =============
  #
  # A server **MAY** return `403 Forbidden` in response to an unsupported request
  # to create a resource.
  #
  # 409 Conflict
  # ============
  #
  # A server **MUST** return `409 Conflict` when processing a `POST` request to
  # create a resource with a client-generated ID that already exists.
  #
  # A server **MUST** return `409 Conflict` when processing a `POST` request in
  # which the [resource object][resource objects]'s `type` is not among the type(s) that constitute the
  # collection represented by the endpoint.
  #
  # A server **SHOULD** include error details and provide enough information to
  # recognize the source of the conflict.
  #
  # Other Responses
  # ===============
  #
  # A server **MAY** respond with other HTTP status codes.
  #
  # A server **MAY** include [error details] with error responses.
  #
  # A server **MUST** prepare responses, and a client **MUST** interpret
  # responses, in accordance with
  # [`HTTP semantics`](http://tools.ietf.org/html/rfc7231).
  #
  # Updating Resources
  # ==================
  #
  # A resource can be updated by sending a `PATCH` request to the URL that
  # represents the resource.
  #
  # The URL for a resource can be obtained in the `self` link of the resource
  # object. Alternatively, when a `GET` request returns a single [resource object][resource objects] as
  # primary data, the same request URL can be used for updates.
  #
  # The `PATCH` request **MUST** include a single [resource object][resource objects] as primary data.
  # The [resource object][resource objects] **MUST** contain `type` and `id` members.
  #
  # For example:
  #
  # ```http
  # PATCH /articles/1 HTTP/1.1
  # Content-Type: application/vnd.api+json
  # Accept: application/vnd.api+json
  #
  # {
  #   "data": {
  #     "type": "articles",
  #     "id": "1",
  #     "attributes": {
  #       "title": "To TDD or Not"
  #     }
  #   }
  # }
  # ```
  #
  # Updating a Resource's Attributes
  # ================================
  #
  # Any or all of a resource's [attributes] **MAY** be included in the resource
  # object included in a `PATCH` request.
  #
  # If a request does not include all of the [attributes] for a resource, the server
  # **MUST** interpret the missing [attributes] as if they were included with their
  # current values. The server **MUST NOT** interpret missing attributes as `null`
  # values.
  #
  # For example, the following `PATCH` request is interpreted as a request to
  # update only the `title` and `text` attributes of an article:
  #
  # ```http
  # PATCH /articles/1 HTTP/1.1
  # Content-Type: application/vnd.api+json
  # Accept: application/vnd.api+json
  #
  # {
  #   "data": {
  #     "type": "articles",
  #     "id": "1",
  #     "attributes": {
  #       "title": "To TDD or Not",
  #       "text": "TLDR; It's complicated... but check your test coverage regardless."
  #     }
  #   }
  # }
  # ```
  #
  # Updating a Resource's Relationships
  # ===================================
  #
  # Any or all of a resource's [relationships] **MAY** be included in the resource
  # object included in a `PATCH` request.
  #
  # If a request does not include all of the [relationships] for a resource, the server
  # **MUST** interpret the missing [relationships] as if they were included with their
  # current values. It **MUST NOT** interpret them as `null` or empty values.
  #
  # If a relationship is provided in the `relationships` member of a resource
  # object in a `PATCH` request, its value **MUST** be a relationship object
  # with a `data` member. The relationship's value will be replaced with the
  # value specified in this member.
  #
  # For instance, the following `PATCH` request will update the `author` relationship of an article:
  #
  # ```http
  # PATCH /articles/1 HTTP/1.1
  # Content-Type: application/vnd.api+json
  # Accept: application/vnd.api+json
  #
  # {
  #   "data": {
  #     "type": "articles",
  #     "id": "1",
  #     "relationships": {
  #       "author": {
  #         "data": { "type": "people", "id": "1" }
  #       }
  #     }
  #   }
  # }
  # ```
  #
  # Likewise, the following `PATCH` request performs a complete replacement of
  # the `tags` for an article:
  #
  # ```http
  # PATCH /articles/1 HTTP/1.1
  # Content-Type: application/vnd.api+json
  # Accept: application/vnd.api+json
  #
  # {
  #   "data": {
  #     "type": "articles",
  #     "id": "1",
  #     "relationships": {
  #       "tags": {
  #         "data": [
  #           { "type": "tags", "id": "2" },
  #           { "type": "tags", "id": "3" }
  #         ]
  #       }
  #     }
  #   }
  # }
  # ```
  #
  # A server **MAY** reject an attempt to do a full replacement of a to-many
  # relationship. In such a case, the server **MUST** reject the entire update,
  # and return a `403 Forbidden` response.
  #
  # > Note: Since full replacement may be a very dangerous operation, a server
  # may choose to disallow it. For example, a server may reject full replacement if
  # it has not provided the client with the full list of associated objects, and
  # does not want to allow deletion of records the client has not seen.
  #
  # Responses
  # =========
  #
  # 202 Accepted
  # ============
  #
  # If an update request has been accepted for processing, but the processing
  # has not been completed by the time the server responds, the server **MUST**
  # return a `202 Accepted` status code.
  #
  # 200 OK
  # ======
  #
  # If a server accepts an update but also changes the resource(s) in ways other
  # than those specified by the request (for example, updating the `updated-at`
  # attribute or a computed `sha`), it **MUST** return a `200 OK` response. The
  # response document **MUST** include a representation of the updated
  # resource(s) as if a `GET` request was made to the request URL.
  #
  # A server **MUST** return a `200 OK` status code if an update is successful,
  # the client's current attributes remain up to date, and the server responds
  # only with top-level [meta] data. In this case the server **MUST NOT**
  # include a representation of the updated resource(s).
  #
  # 204 No Content
  # ==============
  #
  # If an update is successful and the server doesn't update any attributes besides
  # those provided, the server **MUST** return either a `200 OK` status code and
  # response document (as described above) or a `204 No Content` status code with no
  # response document.
  #
  # 403 Forbidden
  # =============
  #
  # A server **MUST** return `403 Forbidden` in response to an unsupported request
  # to update a resource or relationship.
  #
  # 404 Not Found
  # =============
  #
  # A server **MUST** return `404 Not Found` when processing a request to modify
  # a resource that does not exist.
  #
  # A server **MUST** return `404 Not Found` when processing a request that
  # references a related resource that does not exist.
  #
  # 409 Conflict
  # ============
  #
  # A server **MAY** return `409 Conflict` when processing a `PATCH` request to
  # update a resource if that update would violate other server-enforced
  # constraints (such as a uniqueness constraint on a property other than `id`).
  #
  # A server **MUST** return `409 Conflict` when processing a `PATCH` request in
  # which the resource object's `type` and `id` do not match the server's endpoint.
  #
  # A server **SHOULD** include error details and provide enough information to
  # recognize the source of the conflict.
  #
  # Other Responses
  # ===============
  #
  # A server **MAY** respond with other HTTP status codes.
  #
  # A server **MAY** include [error details] with error responses.
  #
  # A server **MUST** prepare responses, and a client **MUST** interpret
  # responses, in accordance with
  # [`HTTP semantics`](http://tools.ietf.org/html/rfc7231).
  #
  # Updating Relationships
  # ======================
  #
  # Although relationships can be modified along with resources (as described
  # above), JSON API also supports updating of relationships independently at
  # URLs from [relationship links][relationships].
  #
  # > Note: Relationships are updated without exposing the underlying server
  # semantics, such as foreign keys. Furthermore, relationships can be updated
  # without necessarily affecting the related resources. For example, if an article
  # has many authors, it is possible to remove one of the authors from the article
  # without deleting the person itself. Similarly, if an article has many tags, it
  # is possible to add or remove tags. Under the hood on the server, the first
  # of these examples might be implemented with a foreign key, while the second
  # could be implemented with a join table, but the JSON API protocol would be
  # the same in both cases.
  #
  # > Note: A server may choose to delete the underlying resource if a
  # relationship is deleted (as a garbage collection measure).
  #
  # Updating To-One Relationships
  # =============================
  #
  # A server **MUST** respond to `PATCH` requests to a URL from a to-one
  # [relationship link][relationships] as described below.
  #
  # The `PATCH` request **MUST** include a top-level member named `data` containing
  # one of:
  #
  # * a [resource identifier object] corresponding to the new related resource.
  # * `null`, to remove the relationship.
  #
  # For example, the following request updates the author of an article:
  #
  # ```http
  # PATCH /articles/1/relationships/author HTTP/1.1
  # Content-Type: application/vnd.api+json
  # Accept: application/vnd.api+json
  #
  # {
  #   "data": { "type": "people", "id": "12" }
  # }
  # ```
  #
  # And the following request clears the author of the same article:
  #
  # ```http
  # PATCH /articles/1/relationships/author HTTP/1.1
  # Content-Type: application/vnd.api+json
  # Accept: application/vnd.api+json
  #
  # {
  #   "data": null
  # }
  # ```
  #
  # If the relationship is updated successfully then the server **MUST** return
  # a successful response.
  #
  # Updating To-Many Relationships
  # ==============================
  #
  # A server **MUST** respond to `PATCH`, `POST`, and `DELETE` requests to a
  # URL from a to-many [relationship link][relationships] as described below.
  #
  # For all request types, the body **MUST** contain a `data` member whose value
  # is an empty array or an array of [resource identifier objects][resource identifier object].
  #
  # If a client makes a `PATCH` request to a URL from a to-many
  # [relationship link][relationships], the server **MUST** either completely
  # replace every member of the relationship, return an appropriate error response
  # if some resources can not be found or accessed, or return a `403 Forbidden`
  # response if complete replacement is not allowed by the server.
  #
  # For example, the following request replaces every tag for an article:
  #
  # ```http
  # PATCH /articles/1/relationships/tags HTTP/1.1
  # Content-Type: application/vnd.api+json
  # Accept: application/vnd.api+json
  #
  # {
  #   "data": [
  #     { "type": "tags", "id": "2" },
  #     { "type": "tags", "id": "3" }
  #   ]
  # }
  # ```
  #
  # And the following request clears every tag for an article:
  #
  # ```http
  # PATCH /articles/1/relationships/tags HTTP/1.1
  # Content-Type: application/vnd.api+json
  # Accept: application/vnd.api+json
  #
  # {
  #   "data": []
  # }
  # ```
  #
  # If a client makes a `POST` request to a URL from a
  # [relationship link][relationships], the server **MUST** add the specified
  # members to the relationship unless they are already present. If a given `type`
  # and `id` is already in the relationship, the server **MUST NOT** add it again.
  #
  # > Note: This matches the semantics of databases that use foreign keys for
  # has-many relationships. Document-based storage should check the has-many
  # relationship before appending to avoid duplicates.
  #
  # If all of the specified resources can be added to, or are already present
  # in, the relationship then the server **MUST** return a successful response.
  #
  # > Note: This approach ensures that a request is successful if the server's
  # state matches the requested state, and helps avoid pointless race conditions
  # caused by multiple clients making the same changes to a relationship.
  #
  # In the following example, the comment with ID `123` is added to the list of
  # comments for the article with ID `1`:
  #
  # ```http
  # POST /articles/1/relationships/comments HTTP/1.1
  # Content-Type: application/vnd.api+json
  # Accept: application/vnd.api+json
  #
  # {
  #   "data": [
  #     { "type": "comments", "id": "123" }
  #   ]
  # }
  # ```
  #
  # If the client makes a `DELETE` request to a URL from a
  # [relationship link][relationships] the server **MUST** delete the specified
  # members from the relationship or return a `403 Forbidden` response. If all of
  # the specified resources are able to be removed from, or are already missing
  # from, the relationship then the server **MUST** return a successful response.
  #
  # > Note: As described above for `POST` requests, this approach helps avoid
  # pointless race conditions between multiple clients making the same changes.
  #
  # Relationship members are specified in the same way as in the `POST` request.
  #
  # In the following example, comments with IDs of `12` and `13` are removed
  # from the list of comments for the article with ID `1`:
  #
  # ```http
  # DELETE /articles/1/relationships/comments HTTP/1.1
  # Content-Type: application/vnd.api+json
  # Accept: application/vnd.api+json
  #
  # {
  #   "data": [
  #     { "type": "comments", "id": "12" },
  #     { "type": "comments", "id": "13" }
  #   ]
  # }
  # ```
  #
  # > Note: RFC 7231 specifies that a DELETE request may include a body, but
  # that a server may reject the request. This spec defines the semantics of a
  # server, and we are defining its semantics for JSON API.
  #
  # Responses
  # =========
  #
  # 202 Accepted
  # ============
  #
  # If a relationship update request has been accepted for processing, but the
  # processing has not been completed by the time the server responds, the
  # server **MUST** return a `202 Accepted` status code.
  #
  # 204 No Content
  # ==============
  #
  # A server **MUST** return a `204 No Content` status code if an update is
  # successful and the representation of the resource in the request matches the
  # result.
  #
  # > Note: This is the appropriate response to a `POST` request sent to a URL
  # from a to-many [relationship link][relationships] when that relationship already
  # exists. It is also the appropriate response to a `DELETE` request sent to a URL
  # from a to-many [relationship link][relationships] when that relationship does
  # not exist.
  #
  # 200 OK
  # ======
  #
  # If a server accepts an update but also changes the targeted relationship(s)
  # in other ways than those specified by the request, it **MUST** return a `200
  # OK` response. The response document **MUST** include a representation of the
  # updated relationship(s).
  #
  # A server **MUST** return a `200 OK` status code if an update is successful,
  # the client's current data remain up to date, and the server responds
  # only with top-level [meta] data. In this case the server **MUST NOT**
  # include a representation of the updated relationship(s).
  #
  # 403 Forbidden
  # =============
  #
  # A server **MUST** return `403 Forbidden` in response to an unsupported request
  # to update a relationship.
  #
  # Other Responses
  # ===============
  #
  # A server **MAY** respond with other HTTP status codes.
  #
  # A server **MAY** include [error details] with error responses.
  #
  # A server **MUST** prepare responses, and a client **MUST** interpret
  # responses, in accordance with
  # [`HTTP semantics`](http://tools.ietf.org/html/rfc7231).
  #
  # Deleting Resources
  # ==================
  #
  # An individual resource can be *deleted* by making a `DELETE` request to the
  # resource's URL:
  #
  # ```http
  # DELETE /photos/1 HTTP/1.1
  # Accept: application/vnd.api+json
  # ```
  #
  # Responses
  # =========
  #
  # 202 Accepted
  # ============
  #
  # If a deletion request has been accepted for processing, but the processing has
  # not been completed by the time the server responds, the server **MUST**
  # return a `202 Accepted` status code.
  #
  # 204 No Content
  # ==============
  #
  # A server **MUST** return a `204 No Content` status code if a deletion
  # request is successful and no content is returned.
  #
  # 200 OK
  # ======
  #
  # A server **MUST** return a `200 OK` status code if a deletion request is
  # successful and the server responds with only top-level [meta] data.
  #
  # Other Responses
  # ===============
  #
  # A server **MAY** respond with other HTTP status codes.
  #
  # A server **MAY** include [error details] with error responses.
  #
  # A server **MUST** prepare responses, and a client **MUST** interpret
  # responses, in accordance with
  # [`HTTP semantics`](http://tools.ietf.org/html/rfc7231).
  #
  # Query Parameters
  # ================
  #
  # Implementation specific query parameters **MUST** adhere to the same constraints
  # as [member names] with the additional requirement that they **MUST** contain at
  # least one non a-z character (U+0061 to U+007A). It is **RECOMMENDED** that a
  # U+002D HYPHEN-MINUS, "-", U+005F LOW LINE, "_", or capital letter is used
  # (e.g. camelCasing).
  #
  # If a server encounters a query parameter that does not follow the naming
  # conventions above, and the server does not know how to proccess it as a query
  # parameter from this specification, it **MUST** return `400 Bad Request`.
  #
  # > Note: This is to preserve the ability of JSON API to make additive additions
  # to standard query parameters without conflicting with existing implementations.
  #
  # Errors
  # ======
  #
  # Processing Errors
  # =================
  #
  # A server **MAY** choose to stop processing as soon as a problem is encountered,
  # or it **MAY** continue processing and encounter multiple problems. For instance,
  # a server might process multiple attributes and then return multiple validation
  # problems in a single response.
  #
  # When a server encounters multiple problems for a single request, the most
  # generally applicable HTTP error code **SHOULD** be used in the response. For
  # instance, `400 Bad Request` might be appropriate for multiple 4xx errors
  # or `500 Internal Server Error` might be appropriate for multiple 5xx errors.
end


text:
@interface ProcessingViewController : UIViewController <VEVideoEditorDelegate, UIAlertViewDelegate>  {
    IBOutlet UIProgressView *progressView;
    IBOutlet UILabel *progressLabel;

    UIAlertView *informationAlertView;

    VEVideoEditor *videoEditor;
    NSDate *startDate;
    NSInteger progressCount;

    NSMutableArray *memories;
    float sumUsedMemory;
    float samplingTime;
}

@property (nonatomic, retain) VEVideoEditor *videoEditor;

@end

redpajama_set_name: RedPajamaGithub


text:
<!doctype html>
<html>
<head>
<title>$title</title>
<meta charset="utf-8">
<link rel="stylesheet" href="skin/reset-font-min.css">
<link rel="stylesheet" href="skin/clearfix.css">
</head>
<body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="js/prefixfree.min.js"></script>
<script src="js/script.js"></script>
<script>
var str = $.trim('a a a a', true);
console.log(str);

</script>
</body>
</html>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BusinessObjects.Documents
{
    public partial class cDocuments_TravelOrder_OtherExpenses
    {
        public void MarkChild()
        {
            this.MarkAsChild();
        }
    }
}


text:
//This file is automatically rebuilt by the Cesium build process.
/*global define*/
define(function() {
    "use strict";
    return "/**\n\
 * Determines if a time interval is empty.\n\
 *\n\
 * @name czm_isEmpty\n\
 * @glslFunction \n\
 * \n\
 * @param {czm_raySegment} interval The interval to test.\n\
 * \n\
 * @returns {bool} true if the time interval is empty; otherwise, false.\n\
 *\n\
 * @example\n\
 * bool b0 = czm_isEmpty(czm_emptyRaySegment);      // true\n\
 * bool b1 = czm_isEmpty(czm_raySegment(0.0, 1.0)); // false\n\
 * bool b2 = czm_isEmpty(czm_raySegment(1.0, 1.0)); // false, contains 1.0.\n\
 */\n\
bool czm_isEmpty(czm_raySegment interval)\n\
{\n\
    return (interval.stop < 0.0);\n\
}\n\
";
});


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<resources>
  <resource name="oTest" type="RESOURCE"/>
</resources>


text:
// When symbols are longer than 255 characters, the warning is disabled.
#pragma warning( disable:4786 )

#include "GreaterOperation.h"	// Class definition.

// Includes.
#include <string>

using namespace std;

#include "Number.h"

///////////////////////////////////////////////////////////////////////////////
// Construction and destruction

// default constructor
//						==================================
						GreaterOperation::GreaterOperation()
//						==================================
{
	// Fill the set of operator values with the allowed values of
	// the 'greater than'-operator.
	m_sstrOperators.insert( ">" );
	m_sstrOperators.insert( "gt" );
	m_sstrOperators.insert( "greater than" );
	m_sstrOperators.insert( "größer als" );
	m_sstrOperators.insert( "groesser als" );
	m_sstrOperators.insert( "supérieur à" );
	m_sstrOperators.insert( "superieur a" );
	m_sstrOperators.insert( "groter dan" );
}

// destructor
//						===================================
						GreaterOperation::~GreaterOperation()
//						===================================
{
	// Empty.
}

///////////////////////////////////////////////////////////////////////////////
// Public interface

//						==========================
bool					GreaterOperation::Evaluate
//						==========================
(
	const string&		strLeft,
	const string&		strRight
)
{
	bool bResult = false;

	// Create Number objects for both operands.
	Number numLeft( strLeft );
	Number numRight( strRight );

	// Determine if both operand values can be interpreted as numbers.
	if ( numLeft.IsNumber() && numRight.IsNumber() )
	{
		// Determine if the numerical value of the left operand is greater than
		// that of the right operand.
		if ( numLeft.GetNumValue() > numRight.GetNumValue() )
		{
			// The 'greater than'-relation is positive.
			bResult = true;
		}
	}
	else
	{
		// The strings can not be interpreted as numbers; determine if the
		// left operand comes alphabetically after the right operand.
		if ( strLeft > strRight )
		{
			// The 'greater than'-relation is positive.
			bResult = true;
		}
	}

	return bResult;
}


text:
from functools import wraps
import sys
from time import time

class Singleton(type):

    """ Implement singleton pattern. """

    _instances = {}

    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super(
                Singleton, cls).__call__(*args, **kwargs)
        return cls._instances[cls]

def log_methods_time(logger=None):
    """ Decorator for log and timing execution method.

    :return func: a decorator

    """
    if not logger:
        logger = lambda _: _
        logger.debug = sys.stdout.write

    def decorator(fn):
        @wraps(fn)
        def wrapper(*args, **kwargs):
            t0 = time()
            logger.debug("timeit --> method `{}`".format(fn.__name__))
            result = fn(*args, **kwargs)
            logger.debug("timeit --> method `{}` is finished "
                         "(elapsed: {:.3f}s)".format(fn.__name__, time() - t0))
            return result
        return wrapper
    return decorator


text:
<?php

App::uses('CakeBaseReporter', 'TestSuite/Reporter');
App::uses('TextCoverageReport', 'TestSuite/Coverage');

/**
 * CakeTextReporter contains reporting features used for plain text based output
 *
 * @package       Cake.TestSuite.Reporter
 */
class CakeTextReporter extends CakeBaseReporter {

/**
 * Sets the text/plain header if the test is not a CLI test.
 *
 * @return void
 */
	public function paintDocumentStart() {
		if (!headers_sent()) {
			header('Content-type: text/plain');
		}
	}

/**
 * Paints a pass
 *
 * @return void
 */
	public function paintPass() {
		echo '.';
	}

/**
 * Paints a failing test.
 *
 * @param $message PHPUnit_Framework_AssertionFailedError $message Failure object displayed in
 *   the context of the other tests.
 * @return void
 */
	public function paintFail($message) {
		$context = $message->getTrace();
		$realContext = $context[3];
		$context = $context[2];

		printf(
			"FAIL on line %s\n%s in\n%s %s()\n\n",
			$context['line'], $message->toString(), $context['file'], $realContext['function']
		);
	}

/**
 * Paints the end of the test with a summary of
 * the passes and failures.
 *
 * @param PHPUnit_Framework_TestResult $result Result object
 * @return void
 */
	public function paintFooter($result) {
		if ($result->failureCount() + $result->errorCount() == 0) {
			echo "\nOK\n";
		} else {
			echo "FAILURES!!!\n";
		}

		echo "Test cases run: " . $result->count() .
			"/" . ($result->count() - $result->skippedCount()) .
			', Passes: ' . $this->numAssertions .
			', Failures: ' . $result->failureCount() .
			', Exceptions: ' . $result->errorCount() . "\n";

		echo 'Time: ' . $result->time() . " seconds\n";
		echo 'Peak memory: ' . number_format(memory_get_peak_usage()) . " bytes\n";

		if (isset($this->params['codeCoverage']) && $this->params['codeCoverage']) {
			$coverage = $result->getCodeCoverage()->getSummary();
			echo $this->paintCoverage($coverage);
		}
	}

/**
 * Paints the title only.
 *
 * @param string $test_name Name class of test.
 * @return void
 */
	public function paintHeader() {
		$this->paintDocumentStart();
		flush();
	}

/**
 * Paints a PHP exception.
 *
 * @param Exception $exception Exception to describe.
 * @return void
 */
	public function paintException($exception) {
		$message = 'Unexpected exception of type [' . get_class($exception) .
			'] with message [' . $exception->getMessage() .
			'] in [' . $exception->getFile() .
			' line ' . $exception->getLine() . ']';
		echo $message . "\n\n";
	}

/**
 * Prints the message for skipping tests.
 *
 * @param string $message Text of skip condition.
 * @return void
 */
	public function paintSkip($message) {
		printf("Skip: %s\n", $message->getMessage());
	}

/**
 * Paints formatted text such as dumped variables.
 *
 * @param string $message Text to show.
 * @return void
 */
	public function paintFormattedMessage($message) {
		echo "$message\n";
		flush();
	}

/**
 * Generate a test case list in plain text.
 * Creates as series of url's for tests that can be run.
 * One case per line.
 *
 * @return void
 */
	public function testCaseList() {
		$testCases = parent::testCaseList();
		$app = $this->params['app'];
		$plugin = $this->params['plugin'];

		$buffer = "Core Test Cases:\n";
		$urlExtra = '';
		if ($app) {
			$buffer = "App Test Cases:\n";
			$urlExtra = '&app=true';
		} elseif ($plugin) {
			$buffer = Inflector::humanize($plugin) . " Test Cases:\n";
			$urlExtra = '&plugin=' . $plugin;
		}

		if (1 > count($testCases)) {
			$buffer .= "EMPTY";
			echo $buffer;
		}

		foreach ($testCases as $testCaseFile => $testCase) {
			$buffer .= $_SERVER['SERVER_NAME'] . $this->baseUrl() . "?case=" . $testCase . "&output=text\n";
		}

		$buffer .= "\n";
		echo $buffer;
	}

/**
 * Generates a Text summary of the coverage data.
 *
 * @param array $coverage Array of coverage data.
 * @return string
 */
	public function paintCoverage($coverage) {
		$reporter = new TextCoverageReport($coverage, $this);
		echo $reporter->report();
	}

}


text:
package org.gradle.logging;

import org.gradle.internal.Actions;
import org.gradle.cli.CommandLineConverter;
import org.gradle.internal.Factory;
import org.gradle.internal.TimeProvider;
import org.gradle.internal.TrueTimeProvider;
import org.gradle.internal.service.DefaultServiceRegistry;
import org.gradle.logging.internal.*;
import org.gradle.logging.internal.logback.LogbackLoggingConfigurer;

/**
 * A {@link org.gradle.internal.service.ServiceRegistry} implementation that provides the logging services. To use this:
 *
 *

 *
Create an instance using one of the static factory methods below.

 *
Create an instance of {@link LoggingManagerInternal}.

 *
Configure the logging manager as appropriate.

 *
Start the logging manager using {@link org.gradle.logging.LoggingManagerInternal#start()}.

 *
When finished, stop the logging manager using {@link LoggingManagerInternal#stop()}.

 *

 */
public abstract class LoggingServiceRegistry extends DefaultServiceRegistry {
    private TextStreamOutputEventListener stdoutListener;

    /**
     * Creates a set of logging services which are suitable to use in a command-line process. In particular:
     *
     *

     *
Replaces System.out and System.err with implementations that route output through the logging system.

     *
Configures slf4j, logback, log4j and java util logging to route log messages through the logging system.

     *
Routes logging output to the original System.out and System.err.

     *

     *
     *
Does nothing until started.

     *
     *
Allows dynamic and colored output to be written to the console. Use {@link LoggingManagerInternal#attachConsole(boolean)} to enable this.

     */
    public static LoggingServiceRegistry newCommandLineProcessLogging() {
        return new CommandLineLogging();
    }

    /**
     * Creates a set of logging services which are suitable to use globally in a process. In particular:
     *
     *

     *
Replaces System.out and System.err with implementations that route output through the logging system.

     *
Configures slf4j, logback, log4j and java util logging to route log messages through the logging system.

     *
Routes logging output to the original System.out and System.err.

     *

     *
     *
Does nothing until started.

     */
    public static LoggingServiceRegistry newProcessLogging() {
        return new ChildProcessLogging();
    }

    /**
     * Creates a set of logging services which are suitable to use embedded in another application. In particular:
     *
     *

     *
Routes logging output to System.out and System.err.

     *
Configures slf4j and logback.

     *

     *
     *
Does not:

     *
     *

     *
Replace System.out and System.err to capture output written to these destinations.

     *
Configure log4j or java util logging.

     *

     *
     *
Does nothing until started.

     */
    public static LoggingServiceRegistry newEmbeddableLogging() {
        return new EmbeddedLogging();
    }

    /**
     * Creates a set of logging services to set up a new logging scope. Does not configure any static state.
     */
    public LoggingServiceRegistry newLogging() {
        return new NestedLogging();
    }

    protected CommandLineConverter<LoggingConfiguration> createCommandLineConverter() {
        return new LoggingCommandLineConverter();
    }

    protected TimeProvider createTimeProvider() {
        return new TrueTimeProvider();
    }

    protected StyledTextOutputFactory createStyledTextOutputFactory() {
        return new DefaultStyledTextOutputFactory(getStdoutListener(), get(TimeProvider.class));
    }

    protected TextStreamOutputEventListener getStdoutListener() {
        if (stdoutListener == null) {
            stdoutListener = new TextStreamOutputEventListener(get(OutputEventListener.class));
        }
        return stdoutListener;
    }

    protected ProgressLoggerFactory createProgressLoggerFactory() {
        return new DefaultProgressLoggerFactory(new ProgressLoggingBridge(get(OutputEventListener.class)), get(TimeProvider.class));
    }

    protected abstract Factory<LoggingManagerInternal> createLoggingManagerFactory();

    protected OutputEventRenderer createOutputEventRenderer() {
        OutputEventRenderer renderer = new OutputEventRenderer(Actions.doNothing());
        renderer.addStandardOutputAndError();
        return renderer;
    }

    private static class ChildProcessLogging extends LoggingServiceRegistry {
        protected Factory<LoggingManagerInternal> createLoggingManagerFactory() {
            OutputEventRenderer renderer = get(OutputEventRenderer.class);
            // Configure logback and java util logging, and capture stdout and stderr
            LoggingSystem stdout = new DefaultStdOutLoggingSystem(getStdoutListener(), get(TimeProvider.class));
            LoggingSystem stderr = new DefaultStdErrLoggingSystem(new TextStreamOutputEventListener(get(OutputEventListener.class)), get(TimeProvider.class));
            return new DefaultLoggingManagerFactory(
                    new DefaultLoggingConfigurer(renderer,
                            new LogbackLoggingConfigurer(renderer),
                            new JavaUtilLoggingConfigurer()),
                    renderer,
                    stdout,
                    stderr);
        }
    }

    private static class CommandLineLogging extends ChildProcessLogging {
        protected OutputEventRenderer createOutputEventRenderer() {
            OutputEventRenderer renderer = new OutputEventRenderer(new ConsoleConfigureAction());
            renderer.addStandardOutputAndError();
            return renderer;
        }
    }

    private static class EmbeddedLogging extends LoggingServiceRegistry {
        protected Factory<LoggingManagerInternal> createLoggingManagerFactory() {
            OutputEventRenderer renderer = get(OutputEventRenderer.class);
            // Configure logback only
            return new DefaultLoggingManagerFactory(
                    new DefaultLoggingConfigurer(renderer,
                            new LogbackLoggingConfigurer(renderer)),
                    renderer,
                    new NoOpLoggingSystem(),
                    new NoOpLoggingSystem());
        }
    }

    private static class NestedLogging extends LoggingServiceRegistry {
        protected Factory<LoggingManagerInternal> createLoggingManagerFactory() {
            OutputEventRenderer renderer = get(OutputEventRenderer.class);
            // Don't configure anything
            return new DefaultLoggingManagerFactory(renderer,
                    renderer,
                    new NoOpLoggingSystem(),
                    new NoOpLoggingSystem());
        }
    }
}


text:
@fasm.exe optionbox.asm optionbox
@pause


text:
package notifier;

import framework.Validator;

public interface ErrorNotifier {

	public void notifyError(Validator validator);

}


text:
require 'active_support/concern'
require 'active_model/naming'

require 'ripple/core_ext'

require 'ripple/properties'
require 'ripple/attribute_methods'
require 'ripple/associations'
require 'ripple/callbacks'
require 'ripple/inspection'

require 'ripple/document/bucket_access'
require 'ripple/document/key'
require 'ripple/document/persistence'
require 'ripple/document/finders'

module Ripple
  module Document
    extend ActiveSupport::Concern

    included do
      #extend ActiveModel::Naming
      extend BucketAccess
      include Ripple::Document::Key
      include Ripple::Document::Persistence
      extend Ripple::Properties
      include Ripple::Document::Finders

      include Ripple::AttributeMethods
      include Ripple::Associations
      include Ripple::Callbacks

      include Ripple::Inspection
    end

    module ClassMethods
      def embeddable?
        false
      end
    end

    def initialize(attrs = nil)

    end
  end
end


text:
<?xml version="1.0" encoding="ISO-8859-1"?>
<?xml-stylesheet href="latest_ob.xsl" type="text/xsl"?>
<current_observation version="1.0"
	 xmlns:xsd="http://www.w3.org/2001/XMLSchema"
	 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	 xsi:noNamespaceSchemaLocation="http://www.weather.gov/view/current_observation.xsd">
	<credit>NOAA's National Weather Service</credit>
	<credit_URL>http://weather.gov/</credit_URL>
	<image>
		<url>http://weather.gov/images/xml_logo.gif</url>
		<title>NOAA's National Weather Service</title>
		<link>http://weather.gov</link>
	</image>
	<suggested_pickup>15 minutes after the hour</suggested_pickup>
	<suggested_pickup_period>60</suggested_pickup_period>
	<location>Dubuque, Dubuque Regional Airport, IA</location>
	<station_id>KDBQ</station_id>
	<latitude>42.39778</latitude>
	<longitude>-90.70361</longitude>
	<observation_time>Last Updated on Jan 4 2016, 8:53 pm CST</observation_time>
        <observation_time_rfc822>Mon, 04 Jan 2016 20:53:00 -0600</observation_time_rfc822>
	<weather>Fair</weather>
	<temperature_string>15.0 F (-9.4 C)</temperature_string>
	<temp_f>15.0</temp_f>
	<temp_c>-9.4</temp_c>
	<relative_humidity>80</relative_humidity>
	<wind_string>Calm</wind_string>
	<wind_dir>North</wind_dir>
	<wind_degrees>0</wind_degrees>
	<wind_mph>0.0</wind_mph>
	<wind_kt>0</wind_kt>
	<pressure_string>1034.6 mb</pressure_string>
	<pressure_mb>1034.6</pressure_mb>
	<pressure_in>30.49</pressure_in>
	<dewpoint_string>10.0 F (-12.2 C)</dewpoint_string>
	<dewpoint_f>10.0</dewpoint_f>
	<dewpoint_c>-12.2</dewpoint_c>
	<visibility_mi>10.00</visibility_mi>
 	<icon_url_base>http://forecast.weather.gov/images/wtf/small/</icon_url_base>
	<two_day_history_url>http://www.weather.gov/data/obhistory/KDBQ.html</two_day_history_url>
	<icon_url_name>nskc.png</icon_url_name>
	<ob_url>http://www.weather.gov/data/METAR/KDBQ.1.txt</ob_url>
	<disclaimer_url>http://weather.gov/disclaimer.html</disclaimer_url>
	<copyright_url>http://weather.gov/disclaimer.html</copyright_url>
	<privacy_policy_url>http://weather.gov/notice.html</privacy_policy_url>
</current_observation>


text:
package com.datatorrent.lib.logs;

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

import org.apache.commons.lang.mutable.MutableDouble;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.datatorrent.lib.logs.MultiWindowDimensionAggregation.AggregateOperation;
import com.datatorrent.lib.testbench.CollectorTestSink;

/**
 * <p>
 * MultiWindowDimensionAggregationTest class.
 * </p>
 *
 */
public class MultiWindowDimensionAggregationTest
{

  private static Logger logger = LoggerFactory.getLogger(MultiWindowDimensionAggregationTest.class);

  /**
   * Test node logic emits correct results
   */
  @Test
  public void testNodeProcessing() throws Exception
  {
    testNodeProcessingSchema(new MultiWindowDimensionAggregation());

  }

  @SuppressWarnings({ "rawtypes", "unchecked" })
  public void testNodeProcessingSchema(MultiWindowDimensionAggregation oper)
  {

    oper.setWindowSize(3);
    List<int[]> dimensionArrayList = new ArrayList<int[]>();
    int[] dimensionArray = { 0, 1 };
    int[] dimensionArray_2 = { 0 };
    dimensionArrayList.add(dimensionArray);
    dimensionArrayList.add(dimensionArray_2);
    oper.setDimensionArray(dimensionArrayList);

    oper.setTimeBucket("m");
    oper.setDimensionKeyVal("0");

    oper.setOperationType(AggregateOperation.AVERAGE);
    oper.setup(null);
    CollectorTestSink sortSink = new CollectorTestSink();
    oper.output.setSink(sortSink);

    oper.beginWindow(0);
    Map<String, Map<String, Number>> data_0 = new HashMap<String, Map<String, Number>>();
    Map<String, Number> input_0 = new HashMap<String, Number>();

    input_0.put("0", new MutableDouble(9));
    input_0.put("1", new MutableDouble(9));
    input_0.put("2", new MutableDouble(9));
    data_0.put("m|20130823131512|0:abc|1:ff", input_0);
    data_0.put("m|20130823131512|0:abc", input_0);
    data_0.put("m|20130823131512|0:abc|1:ie", input_0);
    Map<String, Number> input_new = new HashMap<String, Number>();
    input_new.put("0", new MutableDouble(19));
    input_new.put("1", new MutableDouble(19));
    input_new.put("2", new MutableDouble(19));
    data_0.put("m|20130823131512|0:def|1:ie", input_new);
    oper.data.process(data_0);
    oper.endWindow();

    Map<String, Map<String, Number>> data_1 = new HashMap<String, Map<String, Number>>();
    Map<String, Number> input_1 = new HashMap<String, Number>();
    oper.beginWindow(1);

    input_1.put("0", new MutableDouble(9));
    input_1.put("1", new MutableDouble(9));
    input_1.put("2", new MutableDouble(9));
    data_1.put("m|20130823131513|0:def|1:ff", input_1);
    data_1.put("m|20130823131513|0:abc|1:ie", input_1);
    oper.data.process(data_1);
    oper.endWindow();

    Map<String, Map<String, Number>> data_2 = new HashMap<String, Map<String, Number>>();
    Map<String, Number> input_2 = new HashMap<String, Number>();
    oper.beginWindow(2);

    input_2.put("0", new MutableDouble(19));
    input_2.put("1", new MutableDouble(19));
    input_2.put("2", new MutableDouble(19));
    data_2.put("m|20130823131514|0:def|1:ff", input_2);
    data_2.put("m|20130823131514|0:abc|1:ie", input_2);
    oper.data.process(data_2);
    oper.endWindow();

    Map<String, Map<String, Number>> data_3 = new HashMap<String, Map<String, Number>>();
    Map<String, Number> input_3 = new HashMap<String, Number>();
    oper.beginWindow(3);
    input_3.put("0", new MutableDouble(19));
    input_3.put("1", new MutableDouble(19));
    input_3.put("2", new MutableDouble(19));
    data_3.put("m|20130823131514|0:def|1:ff", input_3);
    data_3.put("m|20130823131514|0:abc|1:ie", input_3);
    oper.data.process(data_3);
    oper.endWindow();

    Assert.assertEquals("number emitted tuples", 16, sortSink.collectedTuples.size());
    for (Object o : sortSink.collectedTuples) {
      logger.debug(o.toString());
    }
    logger.debug("Done testing round\n");
  }
}


text:
$(function() {

	// Input field that contains gadget urls added by the user manually
	var newGadgetUrl = $('#gadgetUrl');

	// Input fields that contains EE gadget URL and EE context
	var eeUrl = $('#eeUrl');
	var eecontextPayload = $('#eecontextPayload');
	var eeHeight = $('#eeHeight');
	var eeWidth = $('#eeWidth');

	//  Input fields for container event testing
	var newEventTopic = $('#eventTopic');
	var newEventPayload = $('#eventPayload');

	// Base html template that is used for the gadget wrapper and site
	var gadgetTemplate = '
' +
				                '
sample to replace
' +
				                '

' +
	                     '
';

	//variable to keep track of gadget current view for collapse and expand gadget actions.
	var currentView = 'default';

	// ID used to associate gadget site
	var curId = 0;

	//  Load the default collections stored and update the options with the collection name
	$.ajax({
			url: './gadgetCollections.json',
			dataType: 'json',
			success: function(data) {
			  $.each(data.collections, function(i,data) {
				 var optionVal = [];
				 $.each(data.apps, function(i,data) {
				   if (data.url.indexOf('http') < 0 && data.url.indexOf('/') == 0) {
					 optionVal.push(urlBase + data.url);
				   }else {
					 optionVal.push(data.url);
				   }
				 });
			     $('#gadgetCollection').append('<option value="' + optionVal.toString() + '">' + data.name + '</option>');
			   });
			}
	});

	$.ajax({
		url: './viewsMenu.json',
		dataType: 'json',
		success: function(data) {
		  $.each(data.views, function(i,selection) {
		     $('#viewOptions').append('<option value="' + selection.value + '">' + selection.name + '</option>');
		  });
		}
	});

	//navigate to the new view and save it as current view
    navigateView = function(gadgetSite, gadgetURL, toView) {
    	//save the current view for collapse, expand gadget
    	currentView = toView;
    	CommonContainer.navigateView(gadgetSite, gadgetURL, toView);
    };

    //handle gadget collapse, expand, and remove gadget actions
    handleNavigateAction = function(portlet,gadgetSite,gadgetURL,actionId) {
      //remove button was click, remove the portlet/gadget
      if(typeof gadgetSite !== 'undefined'){
        if (actionId === 'remove') {
          if (confirm('This gadget will be removed, ok?')) {
            CommonContainer.closeGadget(gadgetSite);
            portlet.remove();
            delete siteToTitleMap[gadgetSite.getId()];
          }
        }else if (actionId === 'expand') {
          //navigate to currentView prior to colapse gadget
          CommonContainer.navigateView(gadgetSite, gadgetURL, currentView);
        }else if (actionId === 'collapse') {
          CommonContainer.collapseGadget(gadgetSite);
        }
      }
    };

    //RPC handler for the set-title feature
    window.setTitleHandler = function(rpcArgs, title) {
      var titleId = siteToTitleMap[rpcArgs.gs.id_];
      $('#' + titleId).text(title);
    };

    window.getNewGadgetElement = function(result, gadgetURL){
      result[gadgetURL] = result[gadgetURL] || {};
      var gadgetSiteString = "$(this).closest(\'.portlet\').find(\'.portlet-content\').data(\'gadgetSite\')";
      var viewItems = '';
      var gadgetViews = result[gadgetURL].views || {};
      for (var aView in gadgetViews) {
        viewItems = viewItems + '
' + aView + '
';
      }
      var newGadgetSite = gadgetTemplate;
      newGadgetSite = newGadgetSite.replace(/(gadget-site)/g, '$1-' + curId);
      siteToTitleMap['gadget-site-' + curId] = 'gadget-title-' + curId;
      var gadgetTitle = (result[gadgetURL] && result[gadgetURL]['modulePrefs'] && result[gadgetURL]['modulePrefs'].title) || 'Title not set';
      $(newGadgetSite).appendTo($('#gadgetArea')).addClass('ui-widget ui-widget-content ui-helper-clearfix ui-corner-all')
      .find('.portlet-header')
      .addClass('ui-widget-header ui-corner-all')
      .text('')
      .append('' + gadgetTitle + '' +
              '
' +
             '
' +
               '' +
             '
' +
               viewItems +
             '
' +
              '
' +
               '
')
      .append('')
      .append('')
      .append('');

      return $('#gadget-site-'+curId).get([0]);
    }

    //create a gadget with navigation tool bar header enabling gadget collapse, expand, remove, navigate to view actions.
    window.buildGadget = function(result,gadgetURL){
      result = result || {};
      var element =  window.getNewGadgetElement(result, gadgetURL);
      $(element).data('gadgetSite', CommonContainer.renderGadget(gadgetURL, curId));

       //determine which button was click and handle the appropriate event.
      $('.portlet-header .ui-icon').click(function() {
        handleNavigateAction($(this).closest('.portlet'), $(this).closest('.portlet').find('.portlet-content').data('gadgetSite'), gadgetURL, this.id);
      });
    };

	//  Publish the container event
	$('#pubEvent').click(function() {
		CommonContainer.inlineClient.publish(newEventTopic.val(), newEventPayload.val());

		//TODO:  Need to add in some additional logic in the Container to enable point to point for things like Embedded Experience...

		//var ppcont = CommonContainer.managedHub.getContainer("__gadget_1");
		//CommonContainer.managedHub.publishForClient(ppcont, newEventTopic.val(), newEventPayload.val());
		//ppcont.sendToClient('org.apache.shindig.random-number', '1111', ppcont.getClientID());
		//clear values
		newEventTopic.val('');
		newEventPayload.val('');
		    return true;
	});

	//  Preload then add a single gadget entered by user
	$('#preloadAndAddGadget').click(function() {
		CommonContainer.preloadGadget(newGadgetUrl.val(), function(result) {
		  for (var gadgetURL in result) {
		    if(!result[gadgetURL].error) {
			    window.buildGadget(result, gadgetURL);
			    curId++;
		    }
		  }

	      //Clear Values
	      newGadgetUrl.val('');
		});

		return true;
	});

	 //  Preload a single gadget entered by user (don't add it to the page)
  $('#preloadGadget').click(function() {
    CommonContainer.preloadGadget(newGadgetUrl.val(), function(result) {
      for (var gadgetURL in result) {
        if(!result[gadgetURL].error) {
          //window.buildGadget(result, gadgetURL);
          curId++;
        }
      }

        //Clear Values
        newGadgetUrl.val('');
    });

    return true;
  });

	//  Add a single gadget entered by user (no preloading)
	 $('#addGadget').click(function() {
	        window.buildGadget({}, newGadgetUrl.val());
	        curId++;

	        //Clear Values
	        newGadgetUrl.val('');
	        return true;
	    });

	//  Load the select collection of gadgets and render them the gadget test area
	$('#addGadgets').click(function() {

		//TODO:  This just provides and example to load configurations
		//var testGadgets=["http://localhost:8080/container/sample-pubsub-2-publisher.xml","http://localhost:8080/container/sample-pubsub-2-subscriber.xml"];
		var testGadgets = $('#gadgetCollection').val().split(',');
		CommonContainer.preloadGadgets(testGadgets, function(result) {
		  for (var gadgetURL in result) {
		    if(!result[gadgetURL].error) {
		      window.buildGadget(result, gadgetURL);
		      curId++;
		    }
		  }

		});
		return true;

	});

	$('#addEmbeddedExperience').click(function(){
	  CommonContainer.preloadGadgets(eeUrl.val(), function(result) {
	    for (var gadgetURL in result) {
	      if(!result[gadgetURL].error) {
	        var eeElement = window.getNewGadgetElement(result, gadgetURL);

	        var model = new Object();

	        model.context = gadgets.json.parse(eecontextPayload.val());
	        model.gadget = gadgetURL;

	        var params = [];
	        params[osapi.container.ee.RenderParam.GADGET_RENDER_PARAMS] = {
	            'height' : eeHeight.val(),
	            'width' : eeWidth.val()
	        };
	        var currentEESite = CommonContainer.ee.navigate(eeElement, model, params, null);
	        curId++;
	      }
	    }
	  });

	  return true;
	});

});


text:
package com.w3bshark.monolith.fragments;

import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.w3bshark.monolith.R;
import com.w3bshark.monolith.Util;
import com.w3bshark.monolith.activities.DetailActivity;
import com.w3bshark.monolith.activities.MainActivity;
import com.w3bshark.monolith.data.MovieContract.MovieEntry;
import com.w3bshark.monolith.data.MovieLoader;
import com.w3bshark.monolith.model.Movie;
import com.w3bshark.monolith.rest.MoviesHandler;
import com.w3bshark.monolith.rest.TmdbRestClient;
import com.w3bshark.monolith.widget.MoviesAdapter;
import com.w3bshark.monolith.widget.PreCachingGridLayoutManager;

import org.apache.http.Header;
import org.json.JSONObject;

import java.util.ArrayList;

/**
 * A custom fragment for displaying a grid/list of movies
 * This fragment is created within MainActivity
 */
public class MainActivityFragment extends Fragment implements LoaderManager.LoaderCallbacks<ArrayList<Movie>> {

    // Log tag to keep track of logs created against this class
    private static final String LOG_TAG = MainActivityFragment.class.getSimpleName();
    // Our recycler view used to display movies as card views
    private RecyclerView mRecyclerView;
    // Adapter used to bind movie data to our recycler view
    private MoviesAdapter mMoviesAdapter;
    // Custom-built GridLayoutManager for pre-caching picasso fetching of movie poster images
    private PreCachingGridLayoutManager mLayoutManager;
    // Layout that allows users to swipe down the screen to refresh data anytime
    private SwipeRefreshLayout mSwipeRefreshLayout;
    // Keep track of the user scrolling (loading new movies)
    private boolean viewIsLoading = true;
    // Counters to keep track of displayed movies
    private int pastVisibleItems, visibleItemCount, totalItemCount, visiblePages;
    // Ever-growing list of movies displayed (binded from our adapter)
    private ArrayList<Movie> movies;
    // If we're in a Master-Detail view
    private Boolean mTwoPanes;
    private Movie mSelectedMovie;
    // Movie parcelable key for saving instance state
    private static final String SAVED_MOVIES = "SAVED_MOVIES";
    // Counter key for saving instance state
    private static final String PAST_VISIBLE_ITEMS = "PAST_VISIBLE_ITEMS";
    // Counter key for saving instance state
    private static final String VISIBLE_ITEM_COUNT = "VISIBLE_ITEM_COUNT";
    // Counter key for saving instance state
    private static final String TOTAL_ITEM_COUNT = "TOTAL_ITEM_COUNT";
    // Counter key for saving instance state
    private static final String VISIBLE_PAGES = "VISIBLE_PAGES";

    private static final int MOVIES_LOADER = 0;

    public MainActivityFragment() {
    }

    /**
     * Handle creation of fragment view, fetch data via TmdbRestClient,
     * initialize our data adapter (RecylcerAdapter) and bind the data,
     * define our scroll listener, and bind the swipe refresh layout
     *
     * @param inflater           used for inflating the xml layout
     * @param container          view to inflate the xml layout into
     * @param savedInstanceState instance state of the application activity
     * @return main view displayed in the fragment
     */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);

        // Set up the xml layout
        View rootView = inflater.inflate(R.layout.fragment_main, container, false);
        mRecyclerView = (RecyclerView) rootView.findViewById(R.id.rv);
//        View mCoordinatorLayoutView = rootView.findViewById(R.id.main_coordinator_layout);

        // Improves performance if changes in content do not change
        // the layout size of the RecyclerView
        mRecyclerView.setHasFixedSize(true);

        // Set up our custom grid layout and define number of columns to display
        boolean isTablet = getResources().getBoolean(R.bool.isTablet);
        int spanCount;
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            // Display only 1 columns if phone; 2 columns if tablet
            spanCount = isTablet ? 3 : 1;
            int orientation = isTablet ? GridLayoutManager.VERTICAL : GridLayoutManager.HORIZONTAL;
            mLayoutManager = new PreCachingGridLayoutManager(getActivity(), spanCount, orientation, false);
        } else {
            // Display only 2 columns if phone; 2 columns if tablet
            spanCount = 2;
            mLayoutManager = new PreCachingGridLayoutManager(getActivity(), spanCount, GridLayoutManager.VERTICAL, false);
        }
        mLayoutManager.setExtraLayoutSpace(Util.getScreenHeight(getActivity()));
        mRecyclerView.setLayoutManager(mLayoutManager);

        // Attempt to restore movie data from savedInstanceState
        if (savedInstanceState != null) {
            pastVisibleItems = savedInstanceState.getInt(PAST_VISIBLE_ITEMS);
            visibleItemCount = savedInstanceState.getInt(VISIBLE_ITEM_COUNT);
            totalItemCount = savedInstanceState.getInt(TOTAL_ITEM_COUNT);
            visiblePages = savedInstanceState.getInt(VISIBLE_PAGES);
            movies = savedInstanceState.getParcelableArrayList(SAVED_MOVIES);
            if (mMoviesAdapter == null) {
                initializeAdapter();
            } else {
                mMoviesAdapter.notifyDataSetChanged();
            }
        }

        getLoaderManager().initLoader(MOVIES_LOADER, null, this);

        // Handle user continuously scrolling
        // Pages of new movies will be added in as user scrolls
        // TODO: Add inifinite scrolling back in, when we can better support it
//        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
//            @Override
//            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
//                visibleItemCount = mLayoutManager.getChildCount();
//                totalItemCount = mLayoutManager.getItemCount();
//                pastVisibleItems = mLayoutManager.findFirstVisibleItemPosition();
//
//                if (viewIsLoading) {
//                    // We'll want to add in new movies before the user can hit a "wall"
//                    // This will allow users to continuously scroll without having to stop
//                    // and wait for the app to GET new movies
//                    if ((visibleItemCount + pastVisibleItems) >= (totalItemCount)) {
//                        viewIsLoading = false;
//
//                        String sortUrl;
//                        SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext());
//                        String defValPref = "";
//                        String userSortPref = settings.getString(MainActivity.PREF_SORT, defValPref);
//                        if (userSortPref.equals(MainActivity.SortType.HighestRated.getSortType())) {
//                            sortUrl = MoviesHandler.MOVIES_RATING_DESC;
//                        }
//                        else {
//                            sortUrl = MoviesHandler.MOVIES_POPULARITY_DESC;
//                        }
//                        String url = sortUrl
//                                .concat(MoviesHandler.MOVIES_ADDPAGE)
//                                .concat(Integer.toString(++visiblePages));
//                        getMovies(url, true, true);
//                    }
//                    // TMDB has a limit on pages that can be requested
//                    // This limit is 1000, so we should stop the user from loading more than this
//                    if (visiblePages >= 1000) {
//                        viewIsLoading = false;
//                    }
//                }
//            }
//        });

        // Handle user pull-down to refresh
        mSwipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.main_swipe_refresh_layout);
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
//                // Set visible pages back to 1, because we'll be reloading all pages
                // TODO: Add inifinite scrolling back in, when we can better support it
//                visiblePages = 1;
                SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext());
                String defValPref = "";
                String userSortPref = settings.getString(MainActivity.PREF_SORT, defValPref);
                String getUrl;
                if (userSortPref.equals(MainActivity.SortType.HighestRated.getSortType())) {
                    getUrl = MoviesHandler.MOVIES_RATING_DESC;
                } else {
                    getUrl = MoviesHandler.MOVIES_POPULARITY_DESC;
                }
                getMovies(getUrl, false);
//                initializeAdapter();
                mRecyclerView.refreshDrawableState();
            }
        });
        mSwipeRefreshLayout.setColorSchemeResources(R.color.swiperefresh);
        //TODO: Set timeout on refresh in case we cannot connect to the TMDB API

        return rootView;
    }

    private void restartLoader() {
        getLoaderManager().restartLoader(MOVIES_LOADER, null, this);
    }

    private void getMovies(String url, final Boolean setViewIsLoading) {
        // Fetch movie data using our rest client and bind the data
        TmdbRestClient.get(url, null, new MoviesHandler() {
            @Override
            //TODO: handle deprecation: org.apache.http.Header is deprecated in API level 22
            // https://github.com/loopj/android-async-http/issues/833
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                int inserted = 0;
                if (this.getMoviesVector() != null && !this.getMoviesVector().isEmpty()) {
                    // Bulk insert fetched movies into DB
                    ContentValues[] cvArray = new ContentValues[getMoviesVector().size()];
                    getMoviesVector().toArray(cvArray);
                    inserted = getContext().getContentResolver().bulkInsert(MovieEntry.CONTENT_URI, cvArray);

                    Log.d(LOG_TAG, "MoviesHandler Complete. " + inserted + " Inserted");
                }

                // Now that we've fetched the latest movies, let's reload the data for the UI
                //  from our movies DB. If no new data was actually retrieved, don't attempt
                //  to restart the loader, because we might fall into an infinite loop that way.
//                if (inserted > 0)
                // Temporarily removed this check
                // if we don't remove this check, then views don't update with results, since our
                // provider class's bulkinsert ignores conflict inserts with CONFLICT_IGNORE
                //TODO: Check to make sure there are no infinite loops by not checking inserted > 0
                restartLoader();

                mSwipeRefreshLayout.setRefreshing(false);

                if (setViewIsLoading) {
                    viewIsLoading = true;
                }
            }

            //TODO: handle deprecation: org.apache.http.Header is deprecated in API level 22
            // https://github.com/loopj/android-async-http/issues/833
            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                super.onFailure(statusCode, headers, throwable, errorResponse);
                mSwipeRefreshLayout.setRefreshing(false);
            }
        });
    }

    /**
     * Set up our MoviesAdapter to bind the data to the RecyclerView and handle
     * user click of movie (CardView) in the RecyclerView
     */
    private void initializeAdapter() {
        // We must create the clicklistener here so that the adapter
        // can bind the data with the element that is clicked
        View.OnClickListener clickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int itemPosition = mRecyclerView.getChildLayoutPosition(v);
                // We must pull the most recent data for the selected movie from the database
                //  in case it has been updated to be a "favorite"
                String[] selectionArgs = new String[]{movies.get(itemPosition).getMovieId()};
                Cursor cursor = getContext().getContentResolver().query(
                        MovieEntry.CONTENT_URI,
                        MovieLoader.MOVIES_COLUMNS,
                        MovieEntry.COLUMN_MOVIE_ID + " = ? ",
                        selectionArgs,
                        null);
                Movie selectedMovie = null;
                if (cursor.moveToFirst()) {
                    selectedMovie = new Movie();
                    selectedMovie.setMovieId(cursor.getString(MovieLoader.COL_MOVIE_ID));
                    selectedMovie.setTitle(cursor.getString(MovieLoader.COL_MOVIE_TITLE));
                    selectedMovie.setDescription(cursor.getString(MovieLoader.COL_MOVIE_DESCR));
                    selectedMovie.setImageCode(cursor.getString(MovieLoader.COL_MOVIE_IMAGE_CODE));
                    selectedMovie.setReleaseDate(cursor.getString(MovieLoader.COL_MOVIE_RELEASE_DATE));
                    selectedMovie.setPopularity(cursor.getLong(MovieLoader.COL_MOVIE_POPULARITY));
                    selectedMovie.setVoteAverage(cursor.getDouble(MovieLoader.COL_MOVIE_VOTE_AVG));
                    selectedMovie.setFavorite(cursor.getString(MovieLoader.COL_MOVIE_FAVORITE));
                }
                cursor.close();

                // If, for whatever reason, we couldn't retrieve the movie from the DB,
                //  then, just use the movie from in-memory
                if (selectedMovie == null) {
                    selectedMovie = movies.get(itemPosition);
                }
                MainActivity mainAct = (MainActivity) getActivity();
                if (mainAct.getIsTwoPanes() != null) {
                    mTwoPanes = mainAct.getIsTwoPanes();
                }
                if (mTwoPanes) {
                    FragmentManager manager = getActivity().getSupportFragmentManager();
                    DetailActivityFragment newDetailActFrag = new DetailActivityFragment();
                    final Bundle bundle = new Bundle();
                    bundle.putParcelable(DetailActivityFragment.BUNDLE_SELECTED_MOVIE, selectedMovie);
                    bundle.putBoolean(MainActivity.BUNDLE_TWO_PANE, mTwoPanes);
                    newDetailActFrag.setArguments(bundle);
                    manager.beginTransaction().replace(R.id.detail_container, newDetailActFrag)
                            .commit();
                } else {
                    Intent detailIntent = new Intent(getActivity(), DetailActivity.class)
                        .putExtra(DetailActivity.EXTRASCURRENTMOVIE, selectedMovie);
                    startActivity(detailIntent);
                }
                mSelectedMovie = selectedMovie;
            }
        };

        // Initialize the MoviesAdapter and bind movies
        mMoviesAdapter = new MoviesAdapter(getActivity(), movies, clickListener);
        mRecyclerView.setAdapter(mMoviesAdapter);
    }

    /**
     * Fetch movie data from TMDB that is sorted by "Most Popular"
     */
    public void sortByMostPopular() {
        // Set the user shared preference to MostPopular
        SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext());
        SharedPreferences.Editor preferenceEditor = settings.edit();
        preferenceEditor.putString(MainActivity.PREF_SORT, MainActivity.SortType.MostPopular.getSortType());
        preferenceEditor.apply();

        // There's no reason to attempt to fetch data while offline, so if app does not
        //  have connectivity, then just restart the loader so that it can sort the data from
        //  storage in the correct manner
        if (Util.isNetworkAvailable(getContext())) {
            // Fetch the movie data
            String getUrl = MoviesHandler.MOVIES_POPULARITY_DESC;
            getMovies(getUrl, false);
        } else {
            restartLoader();
        }
    }

    /**
     * Fetch movie data from TMDB that is sorted by "Highest Rated"
     */
    public void sortByHighestRated() {
        // Set the user shared preference to HighestRated
        SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext());
        SharedPreferences.Editor preferenceEditor = settings.edit();
        preferenceEditor.putString(MainActivity.PREF_SORT, MainActivity.SortType.HighestRated.getSortType());
        preferenceEditor.apply();

        // There's no reason to attempt to fetch data while offline, so if app does not
        //  have connectivity, then just restart the loader so that it can sort the data from
        //  storage in the correct manner
        if (Util.isNetworkAvailable(getContext())) {
            // Fetch the movie data
            String getUrl = MoviesHandler.MOVIES_RATING_DESC;
            getMovies(getUrl, false);
        } else {
            restartLoader();
        }
    }

    public void showFavorites() {
        // Set the user shared preference to Favorites
        SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext());
        SharedPreferences.Editor preferenceEditor = settings.edit();
        preferenceEditor.putString(MainActivity.PREF_SORT, MainActivity.SortType.Favorites.getSortType());
        preferenceEditor.apply();

        restartLoader();
    }

    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
        if (movies != null) {
            savedInstanceState.putParcelableArrayList(SAVED_MOVIES, movies);
        }
        savedInstanceState.putInt(PAST_VISIBLE_ITEMS, pastVisibleItems);
        savedInstanceState.putInt(VISIBLE_ITEM_COUNT, visibleItemCount);
        savedInstanceState.putInt(TOTAL_ITEM_COUNT, totalItemCount);
        savedInstanceState.putInt(VISIBLE_PAGES, visiblePages);
        super.onSaveInstanceState(savedInstanceState);
    }

    @Override
    public Loader<ArrayList<Movie>> onCreateLoader(int i, Bundle bundle) {
        Uri moviesUri = MovieEntry.buildAllMoviesUri();
        return new MovieLoader(getActivity(), moviesUri);
    }

    @Override
    public void onLoadFinished(Loader<ArrayList<Movie>> loader, ArrayList<Movie> data) {

        SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext());
        String defValPref = "";
        String userSortPref = settings.getString(MainActivity.PREF_SORT, defValPref);

        // If there were no movies in the database  and the sort preference
        //   is not "Favorites", attempt to fetch them while online
        //   We don't need to fetch movie data if we're showing favorites
        if ((data == null || data.size() == 0)
                && !userSortPref.equals(MainActivity.SortType.Favorites.getSortType())) {
            // Initially we'll start with 1 page of movies (paging is a TMDB term)
            // Then, we'll slowly roll in more and more pages as needed by user
            // http://docs.themoviedb.apiary.io/#reference/discover/discovermovie
            // TODO: Add inifinite scrolling back in, when we can better support it
//            visiblePages = 1;
            // Find the user's preferred sort method and fetch the data in initializeData()
            String getUrl;
            if (userSortPref.equals(MainActivity.SortType.HighestRated.getSortType())) {
                getUrl = MoviesHandler.MOVIES_RATING_DESC;
            } else {
                getUrl = MoviesHandler.MOVIES_POPULARITY_DESC;
            }
            getMovies(getUrl, false);

            // Otherwise, add the movies from the database
        } else if (data != null) {
            if (movies == null) {
                movies = new ArrayList<>();
            }
            movies.clear();
            movies.addAll(data);
            if (mMoviesAdapter == null) {
                initializeAdapter();
            } else {
                mMoviesAdapter.notifyDataSetChanged();
            }
        }
    }

    @Override
    public void onLoaderReset(Loader<ArrayList<Movie>> loader) {
        if (movies != null) {
            this.movies.clear();
        }
        if (mMoviesAdapter != null) {
            mMoviesAdapter.notifyDataSetChanged();
        }
    }

    public Movie getSelectedMovie() {
        return mSelectedMovie;
    }
}


text:
package org.apereo.cas.configuration.model.support.pac4j.oidc;

import org.apereo.cas.configuration.support.RequiresModule;

import lombok.Getter;
import lombok.Setter;

/**
 * This is {@link Pac4jGenericOidcClientProperties}.
 *
 * @author Misagh Moayyed
 * @since 5.2.0
 */
@RequiresModule(name = "cas-server-support-pac4j-webflow")
@Getter
@Setter
public class Pac4jGenericOidcClientProperties extends BasePac4jOidcClientProperties {
    private static final long serialVersionUID = 3359382317533639638L;
}


text:
curl -v \
--header "x-api-key: $API_KEY" \
-XPOST "https://$API_ID.execute-api.eu-west-1.amazonaws.com/prod/list_event_brite_venues" \
-d @request.json


text:
/**
 * Created by lukas on 5-5-2017.
 */
angular.module('CWEE', ['ngMaterial', 'LocalStorageModule', 'CWEE.views', 'CWEE.elements', 'CWEE.services'])

.config(function(localStorageServiceProvider)
{
    localStorageServiceProvider.setPrefix('CWEE');
    localStorageServiceProvider.setStorageType('sessionStorage');
});

// it was once fortold that this code would start a revolution...
// ...now it's just in comments because canvas is not as usefull as the programmer thought.

// window.onload = function()
// {
//     // setupWindow();
//     // var game = new Game();
//     // game.startUp();
// };


text:
package com.gooddata.sdk.model.project;

/**
 * Optional property for project create, the property is ignored during project update.
 * Default value is {@link #PRODUCTION} which is also environment for all currently existing projects.<p>
 * Preffer {@link Environment} if possible.
 */
public enum ProjectEnvironment {
    /** Default value, projects are backed-up and archived. */
    PRODUCTION,
    /** no meaning yet and behavior is the same as for {@link #PRODUCTION} projects*/
    DEVELOPMENT,
    /** 'TESTING' projects are not backed-up and archived. */
    TESTING
}