text:
=begin
Copyright (c) 2008, Pat Sissons
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice,
      this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice,
      this list of conditions and the following disclaimer in the documentation
      and/or other materials provided with the distribution.
    * Neither the name of the DHX Software nor the names of its contributors may
      be used to endorse or promote products derived from this software without
      specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
=end

require 'open-uri'
require 'timeout'

class Show
    attr_accessor :id, :regex, :season, :episodes, :postdlcmd, :feeds

    def initialize(main, id, regex, season, min_episode, opts)
        @logger = LogManager.Instance
        @logger.ftrace {'ENTER'}
        @main = main
        @id = id
        @regex = regex
        @season = season.to_i
        # episodes is a list of episodes that have been downloaded, we must convert each string to an int with map
        @episodes = Array.new
        min_episode.to_i.downto(1) { |i| @episodes.unshift(i.to_i) }
        if opts.nil?
            raise 'Catastrophic Failure!'
        else
            # add post download command if it exists in opts
            @postdlcmd = opts.length >= 1 ? opts.shift : []
            @postdlcmd = nil if @postdlcmd.empty?
            # build list of feeds from opts if they exist
            @feeds = opts.empty? ? nil : opts.map { |f| main.feeds[f] }.compact
        end
        @logger.ftrace {'LEAVE'}
    end

    # utility function to grab
    def conf
        ConfigFile.Instance
    end

    # check if this show this show is only part of a specific feed or feeds
    def belongs_to?(feed)
        @logger.ftrace {'ENTER'}
        @logger.debug {"Checking If Feed #{feed.id} Belongs to #{@id}"}
        ret = @feeds.nil? or @feeds.include?(feed)
        @logger.ftrace {'LEAVE'}
        ret
    end

    # perform a generic regex match on the provided string
    def rxmatch(rx, string, cs = nil)
        @logger.ftrace {'ENTER'}
        @logger.debug {"Matching '#{string}' with regex '#{rx}'"}
        ret = cs.nil? ? Regexp.new(rx, Regexp::IGNORECASE).match(string) : Regexp.new(rx).match(string)
        @logger.ftrace {'LEAVE'}
        ret
    end

    # check if the provided title is considered a new show (something that has not yet been downloaded)
    def new_show?(title)
        @logger.ftrace {'ENTER'}
        ret = nil
        @logger.debug {"Checking If '#{title}' Is A New Show"}
        # we have to check each of the season/ep regex strings provided in the config file
        @main.rxSeasonEp.each do |rx|
            m = rxmatch(rx, title)
            # if m is nil then there was no match
            if m.nil?
                @logger.debug {"#{id} didn't match #{title} (#{rx})"}
            # if we did match, then we must extract the season/ep data
            # m[1] = season, m[2] = episode
            else
                @logger.debug {"#{id} Matches #{title} (#{rx})"}
                # remove non numeric characters from season and episode
                season = m[1].gsub(/[^0-9]/, '').to_i
                episode = m[2].gsub(/[^0-9]/, '').to_i
                # check if either we are in the same season and we haven't downloaded the provided episode, or if a new season has started
                @logger.debug {"'#{title}' is season #{season}, episode #{episode}"}
                if ((season == @season.to_i and not @episodes.include?(episode)) or season > @season.to_i)
                    @logger.info(false) {"Found New Show For #{@id}: Season #{season}, Episode #{episode} (#{@season}:#{@episodes.join(',')})"}
                    # all good, return the season and episode
                    ret = [true, season, episode]
                else
                    @logger.debug {"'#{title}' Is Old (S#{sprintf("%02d", @season)}, E:#{@episodes.join(',')})"}
                    ret = [false, season, episode]
                end
                break
            end
        end
        @logger.ftrace {'LEAVE'}
        ret
    end

    # check if title should be rejected based on the reject regex strings
    def reject?(title)
        @logger.ftrace {'ENTER'}
        ret = false
        @logger.debug {"Checking if '#{title}' should be rejected"}
        @main.rxReject.each do |rx|
            m = rxmatch(rx, title)
            unless m.nil?
                @logger.debug {"'#{title}' is rejected"}
                ret = true
                break
            end
        end

        @logger.ftrace {'LEAVE'}
        ret
    end

    def proper?(title, episode)
        @logger.ftrace {'ENTER'}
        ret = false
        if conf.has_key?('proper_override')
            @logger.debug {'Checking for PROPER release'}
            if title.upcase.include?('PROPER') and @episodes.include?(episode) == false
                ret = true
            end
        end
        @logger.ftrace{'LEAVE'}
        ret
    end

    # this is the main function that matches an input show title to *THIS* show object
    # i = feed item
    def match(i)
        @logger.ftrace {'ENTER'}
        ret = review = nil
        dlpath, review, ep_info = match_title(i.title)
        # if dlpath was set, then download that bitch! (with a timeout of course)
        Timeout::timeout(@main.torTimeout) { ret = download(i.link, dlpath) } unless dlpath.nil?
        # precedence to the download return state, then the review state
        ret = ret.nil? ? nil : review ? nil : ret
        # if nothing has gone wrong, update our status
        unless ret.nil?
            if (ep_info[1].to_i > @season)
                # new season detected, clear the current ep list
                @episodes.clear
            end
            @season = ep_info[1].to_i
            @episodes.push(ep_info[2]).sort!

            # finally, save the state to disk
            @main.save_state
        end
        @logger.ftrace {'LEAVE'}
        ret
    end

    def match_title(title)
        @logger.ftrace {'ENTER'}
        ret = nil
        @logger.debug {"Matching '#{title}' With '#{@regex}'"}
        m = rxmatch(@regex, title)
        # we didn't match
        if m.nil?
            @logger.debug {"#{@id} doesn't match"}
            ret = nil
        # we matched, so now we have to do the successful match logic
        else
            @logger.debug {"#{@id} matches '#{title}'"}
            # first check if the show is new
            ep_info = new_show?(title.gsub(m[m.length - 1], ''))
            dlpath = nil
            review = false
            dl = true
            # show's title doesn't have season/ep info, we download it anyways, but to the review dir
            if ep_info.nil?
                @logger.warn {"Couldn't Determine Season and Episode Info For '#{title}'"}
                dlpath = File.join(File.expand_path(conf['download_path_review']), "REVIEW-#{title.gsub(/[^\w]/, '_').gsub(/_+/, '_')}.torrent")
                review = true
            # if it is old, then we have nothing to do
            elsif ep_info[0] == false
                # download anyways if we want to override proper releases
                if proper?(title, ep_info[2] + 0.1)
                    @logger.notice(false) {"#{title} is a PROPER release, downloading even though it is old"}
                    dlpath = File.join(File.expand_path(conf['download_path']), "#{title.gsub(/[^\w]/, '_').gsub(/_+/, '_')}.torrent")
                    ep_info[2] += 0.1
                else
                    @logger.info {"#{title} is old, skipping"}
                    ret = nil
                end
            # make sure the show shouldn't be rejected, if it is a reject we still download it to the review dir
            elsif reject?(title)
                @logger.notice(false) {"'#{title}' Was Rejected"}
                dlpath = File.join(File.expand_path(conf['download_path_review']), "REVIEW-#{title.gsub(/[^\w]/, '_').gsub(/_+/, '_')}.torrent")
                review = true
            # otherwise, everything is good.  try and download the file
            else
                dlpath = File.join(File.expand_path(conf['download_path']), "#{title.gsub(/[^\w]/, '_').gsub(/_+/, '_')}.torrent")
                @logger.notice(false) {"Show '#{title}' has a new epidsode ready for download"}
            end
            ret = [dlpath, review, ep_info]
        end
        @logger.ftrace {'LEAVE'}
        ret
    end

    # download from uri to dlpath
    def download(uri, dlpath)
        @logger.ftrace {'ENTER'}
        ret = nil
        begin
            # make sure a file of the same path doesn't already exist
            unless File.size?(dlpath).nil?
                @logger.warn {"'#{dlpath}' already exists, not downloading"}
                ret = nil
            else
                @logger.debug {"Downloading #{uri} to #{dlpath}"}
                # download the uri
                uri = URI.escape(uri, '[]')
                @logger.info {"Escaped URI => #{uri}"}
                File.open(dlpath, 'w') do |f|
                    f.write(open(uri).read)
                    f.close
                end
                ret = dlpath
            end
        rescue => e
            @logger.error {"Download Error: #{e}\r\n#{e.backtrace}"}
            ret = nil
        end
        @logger.ftrace {'LEAVE'}
        ret
    end

    # load the state from the provided state item (from the state file)
    def load_state(si)
        @logger.ftrace {'ENTER'}
        return if si.length != 2
        @logger.debug {"Loading State For #{@id}: #{si.join(';')}"}
        @season = si[0].to_i
        @episodes = si[1].split(/,/).map { |e| e.to_i }.uniq
        @logger.ftrace {'LEAVE'}
        nil
    end

    # get the state
    def get_state
        @logger.ftrace {'ENTER'}
        @logger.debug {"State For #{@id}: #{@season};#{@episodes.join(',')}"}
        ret = "#{@season};#{@episodes.join(',')}"
        @logger.ftrace {'LEAVE'}
        ret
    end

    def to_s
<<EOF
------------------------
Show
------------------------
Show     : #{@id}
Regex    : #{@regex}
Season   : #{@season}
Episodes : #{@episodes.join(',')}
CMD      : #{@postdlcmd.nil? ? 'N/A' : @postdlcmd}
Feeds    : #{@feeds.nil? ? 'ALL' : @feeds.each_value.map { |f| f.id }.join(',')}
========================
EOF
    end
end


text:
using NUnit.Framework;

namespace Lucene.Net.Attributes
{
    /// <summary>
    /// This test runs long and should be skipped in the 1st run.
    /// </summary>
    public class LongRunningTestAttribute : CategoryAttribute
    {
        public LongRunningTestAttribute() : base("LongRunningTest")
        {
            // nothing to do here but invoke the base contsructor.
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
Use this endpoint to:
- Get an `access_token` in order to call an API. You can, optionally, retrieve an `id_token` and a `refresh_token` as well.
- Refresh your access token, using a refresh token you got during authorization.

Note that the only OAuth 2.0 flows that can retrieve a refresh token are:
- [Authorization Code](/api-auth/grant/authorization-code)
- [Authorization Code with PKCE](/api-auth/grant/authorization-code-pkce)
- [Resource Owner Password](/api-auth/grant/password)

## Authorization Code

Examples

```http
POST https://${account.namespace}/oauth/token
Content-Type: 'application/json'
{
  "grant_type": "authorization_code",
  "client_id": "${account.clientId}",
  "client_secret": "${account.clientSecret}",
  "code": "AUTHORIZATION_CODE",
  "redirect_uri": ${account.callback}
}
```

```shell
curl --request POST \
  --url 'https://${account.namespace}/oauth/token' \
  --header 'content-type: application/json' \
  --data '{"grant_type":"authorization_code","client_id": "${account.clientId}","client_secret": "${account.clientSecret}","code": "AUTHORIZATION_CODE","redirect_uri": "${account.callback}"}'
```

```javascript
var request = require("request");

var options = { method: 'POST',
  url: 'https://${account.namespace}/oauth/token',
  headers: { 'content-type': 'application/json' },
  body:
   { grant_type: 'authorization_code',
     client_id: '${account.clientId}',
     client_secret: '${account.clientSecret}',
     code: 'AUTHORIZATION_CODE',
     redirect_uri: '${account.callback}' },
  json: true };

request(options, function (error, response, body) {
  if (error) throw new Error(error);

  console.log(body);
});
```

> RESPONSE SAMPLE:

```JSON
HTTP/1.1 200 OK
Content-Type: application/json
{
  "access_token":"eyJz93a...k4laUWw",
  "refresh_token":"GEbRxBN...edjnXbL",
  "id_token":"eyJ0XAi...4faeEoQ",
  "token_type":"Bearer",
  "expires_in":86400
}
```

<%= include('../../../_includes/_http-method', {
  "http_method": "POST",
  "path": "/oauth/token",
  "link": "#authorization-code"
}) %>

This is the OAuth 2.0 grant that regular web apps utilize in order to access an API. Use this endpoint to exchange an Authorization Code for a Token.

### Request Parameters

| Parameter        | Description |
|:-----------------|:------------|
| `grant_type`
Required | Denotes the flow you are using. For Authorization Code use  `authorization_code`. |
| `client_id`
Required | Your application's Client ID. |
| `client_secret`
Required | Your application's Client Secret. |
| `code`
Required | The Authorization Code received from the initial `/authorize` call. |
| `redirect_uri`| This is required only if it was set at the [GET /authorize](#authorization-code-grant) endpoint. The values must match. |

### Test with Postman

<%= include('../../../_includes/_test-with-postman') %>

### Test with Authentication API Debugger

<%= include('../../../_includes/_test-this-endpoint') %>

If you have just executed the [Authorization Code Grant](#authorization-code-grant) you should already have a code set at the **Authorization Code** field of the *OAuth2 / OIDC* tab. If so, click **OAuth2 Code Exchange**, otherwise follow the instructions.

1. At the *Configuration* tab, set the **Client** field to the client you want to use for the test.

1. Copy the **Callback URL** and set it as part of the **Allowed Callback URLs** of your [Client Settings](${manage_url}/#/clients/${account.clientId}/settings).

1. At the *OAuth2 / OIDC* tab, set the field **Authorization Code** to the code you retrieved from [Authorization Code Grant](#authorization-code-grant). Click **OAuth2 Code Exchange**.

### More Information

- [Calling APIs from Server-side Web Apps](/api-auth/grant/authorization-code)
- [Executing an Authorization Code Grant Flow](/api-auth/tutorials/authorization-code-grant)

## Authorization Code (PKCE)

Examples

```http
POST https://${account.namespace}/oauth/token
Content-Type: 'application/json'
{
  "grant_type": "authorization_code",
  "client_id": "${account.clientId}",
  "code_verifier": "CODE_VERIFIER",
  "code": "AUTHORIZATION_CODE",
  "redirect_uri": "com.myclientapp://myclientapp.com/callback"
}
```

```shell
curl --request POST \
  --url 'https://${account.namespace}/oauth/token' \
  --header 'content-type: application/json' \
  --data '{"grant_type":"authorization_code","client_id": "${account.clientId}","code_verifier": "CODE_VERIFIER","code": "AUTHORIZATION_CODE","redirect_uri": "com.myclientapp://myclientapp.com/callback"}'
```

```javascript
var request = require("request");

var options = { method: 'POST',
  url: 'https://${account.namespace}/oauth/token',
  headers: { 'content-type': 'application/json' },
  body: '{"grant_type":"authorization_code","client_id": "${account.clientId}","code_verifier": "CODE_VERIFIER","code": "AUTHORIZATION_CODE","redirect_uri": "com.myclientapp://myclientapp.com/callback", }' };

request(options, function (error, response, body) {
  if (error) throw new Error(error);

  console.log(body);
});
```

> RESPONSE SAMPLE:

```JSON
HTTP/1.1 200 OK
Content-Type: application/json
{
  "access_token":"eyJz93a...k4laUWw",
  "refresh_token":"GEbRxBN...edjnXbL",
  "id_token":"eyJ0XAi...4faeEoQ",
  "token_type":"Bearer",
  "expires_in":86400
}
```

<%= include('../../../_includes/_http-method', {
  "http_method": "POST",
  "path": "/oauth/token",
  "link": "#authorization-code-pkce-"
}) %>

This is the OAuth 2.0 grant that mobile apps utilize in order to access an API. Use this endpoint to exchange an Authorization Code for a Token.

### Request Parameters

| Parameter        | Description |
|:-----------------|:------------|
| `grant_type`
Required | Denotes the flow you are using. For Authorization Code (PKCE) use  `authorization_code`. |
| `client_id`
Required | Your application's Client ID. |
| `code`
Required | The Authorization Code received from the initial `/authorize` call. |
| `code_verifier`
Required | Cryptographically random key that was used to generate the `code_challenge` passed to `/authorize`. |
| `redirect_uri` | This is required only if it was set at the [GET /authorize](#authorization-code-grant-pkce-) endpoint. The values must match. |

### Test with Authentication API Debugger

<%= include('../../../_includes/_test-this-endpoint') %>

If you have just executed the [Authorization Code Grant (PKCE)](#authorization-code-grant-pkce-) you should already have the **Authorization Code** and **Code Verifier** fields, of the *OAuth2 / OIDC* tab, set. If so, click **OAuth2 Code Exchange**, otherwise follow the instructions.

1. At the *Configuration* tab, set the **Client** field to the client you want to use for the test.

1. Copy the **Callback URL** and set it as part of the **Allowed Callback URLs** of your [Client Settings](${manage_url}/#/clients/${account.clientId}/settings).

1. At the *OAuth2 / OIDC* tab, set the field **Authorization Code** to the code you retrieved from [Authorization Code Grant](#authorization-code-grant-pkce-), and the **Code Verifier** to the key. Click **OAuth2 Code Exchange**.

### More Information

- [Calling APIs from Mobile Apps](/api-auth/grant/authorization-code-pkce)
- [Executing an Authorization Code Grant Flow with PKCE](/api-auth/tutorials/authorization-code-grant-pkce)

## Client Credentials

Examples

```http
POST https://${account.namespace}/oauth/token
Content-Type: 'application/json'
{
  audience: "API_IDENTIFIER",
  grant_type: "client_credentials",
  client_id: "${account.clientId}",
  client_secret: "${account.clientSecret}"
}
```

```shell
curl --request POST \
  --url 'https://${account.namespace}/oauth/token' \
  --header 'content-type: application/json' \
  --data '{"audience":"API_IDENTIFIER", "grant_type":"client_credentials", "client_id":"${account.clientId}", "client_secret":"${account.clientSecret}"}'
```

```javascript
var request = require("request");

var options = { method: 'POST',
  url: 'https://${account.namespace}/oauth/token',
  headers: { 'content-type': 'application/json' },
  body:
   { client_id: '${account.clientId}',
     client_secret: '${account.clientSecret}',
     audience: 'API_IDENTIFIER',
     grant_type: 'client_credentials' },
  json: true };

request(options, function (error, response, body) {
  if (error) throw new Error(error);

  console.log(body);
});
```

> RESPONSE SAMPLE:

```JSON
HTTP/1.1 200 OK
Content-Type: application/json
{
  "access_token":"eyJz93a...k4laUWw",
  "token_type":"Bearer",
  "expires_in":86400
}
```

<%= include('../../../_includes/_http-method', {
  "http_method": "POST",
  "path": "/oauth/token",
  "link": "#client-credentials"
}) %>

This is the OAuth 2.0 grant that server processes utilize in order to access an API. Use this endpoint to directly request an `access_token` by using the Client Credentials (a Client Id and a Client Secret).

### Request Parameters

| Parameter        | Description |
|:-----------------|:------------|
| `grant_type`
Required | Denotes the flow you are using. For Client Credentials use `client_credentials`. |
| `client_id`
Required | Your application's Client ID. |
| `client_secret`
Required | Your application's Client Secret. |
| `audience`
Required | The unique identifier of the target API you want to access. |

### Test with Authentication API Debugger

<%= include('../../../_includes/_test-this-endpoint') %>

1. At the *Configuration* tab, set the **Client** field to the client you want to use for the test.

1. Copy the **Callback URL** and set it as part of the **Allowed Callback URLs** of your [Client Settings](${manage_url}/#/clients/${account.clientId}/settings).

1. At the *OAuth2 / OIDC* tab, click **OAuth2 Client Credentials**.

### More Information

- [Calling APIs from a Service](/api-auth/grant/client-credentials)
- [Setting up a Client Credentials Grant using the Management Dashboard](/api-auth/config/using-the-auth0-dashboard)
- [Asking for Access Tokens for a Client Credentials Grant](/api-auth/config/asking-for-access-tokens)

## Resource Owner Password

Examples

```http
POST https://${account.namespace}/oauth/token
Content-Type: 'application/json'
{
  "grant_type": "password",
  "username": "USERNAME",
  "password": "PASSWORD",
  "audience": "API_IDENTIFIER",
  "scope": "SCOPE",
  "client_id": "${account.clientId}",
  "client_secret": "${account.clientSecret}"
}
```

```shell
curl --request POST \
  --url 'https://${account.namespace}/oauth/token' \
  --header 'content-type: application/json' \
  --data '{"grant_type":"password", "username":"USERNAME", "password":"PASSWORD", "audience":"API_IDENTIFIER", "scope":"SCOPE", "client_id": "${account.clientId}", "client_secret": "${account.clientSecret}"
 }'
```

```javascript
var request = require("request");

var options = { method: 'POST',
  url: 'https://${account.namespace}/oauth/token',
  headers: { 'content-type': 'application/json' },
  body:
   { grant_type: 'password',
     username: 'USERNAME',
     password: 'PASSWORD',
     audience: 'API_IDENTIFIER',
     scope: 'SCOPE',
     client_id: '${account.clientId}',
     client_secret: '${account.clientSecret}' },
  json: true };

request(options, function (error, response, body) {
  if (error) throw new Error(error);

  console.log(body);
});
```

> RESPONSE SAMPLE:

```JSON
HTTP/1.1 200 OK
Content-Type: application/json
{
  "access_token":"eyJz93a...k4laUWw",
  "token_type":"Bearer",
  "expires_in":86400
}
```

<%= include('../../../_includes/_http-method', {
  "http_method": "POST",
  "path": "/oauth/token",
  "link": "#resource-owner-password"
}) %>

This is the OAuth 2.0 grant that highly trusted apps utilize in order to access an API. In this flow the end-user is asked to fill in credentials (username/password) typically using an interactive form in the user-agent (browser). This information is later on sent to the client and Auth0. It is therefore imperative that the client is absolutely trusted with this information.

### Request Parameters

| Parameter        | Description |
|:-----------------|:------------|
| `grant_type`
Required | Denotes the flow you are using. For Resource Owner Password use  `password`. To add realm support use `http://auth0.com/oauth/grant-type/password-realm`. |
| `client_id`
Required | Your application's Client ID. |
| `client_secret` | Your application's Client Secret. **Required** when the **Token Endpoint Authentication Method** field at your [Client Settings](${manage_url}/#/clients/${account.clientId}/settings) is `Post` or `Basic`. Do not set this parameter if your client is not highly trusted (for example, SPA). |
| `audience` | The unique identifier of the target API you want to access. |
| `username`
Required | Resource Owner's identifier. |
| `password`
Required | Resource Owner's secret. |
| `scope` | String value of the different scopes the client is asking for. Multiple scopes are separated with whitespace. |
| `realm` | String value of the realm the user belongs. Set this if you want to add realm support at this grant. For more information on what realms are refer to [Realm Support](/api-auth/grant/password#realm-support). |

### Test with Authentication API Debugger

<%= include('../../../_includes/_test-this-endpoint') %>

1. At the *Configuration* tab, set the **Client** field to the client you want to use for the test.

1. Copy the **Callback URL** and set it as part of the **Allowed Callback URLs** of your [Client Settings](${manage_url}/#/clients/${account.clientId}/settings).

1. At the *OAuth2 / OIDC* tab, set the **Username** and **Password**, and click **Password Grant**.

### Remarks

- The scopes issued to the client may differ from the scopes requested. In this case, a `scope` parameter will be included in the response JSON.
- To add realm support set the `grant_type` to `http://auth0.com/oauth/grant-type/password-realm`, and the `realm` to the realm the user belongs. This maps to a connection in Auth0. For example, if you have configured a database connection for your internal employees and you have named the connection `employees`, then use this value. For more information on how to implement this refer to: [Realm Support](/api-auth/tutorials/password-grant#realm-support).

### More Information

- [Calling APIs from Highly Trusted Clients](/api-auth/grant/password)
- [Executing the Resource Owner Password Grant](/api-auth/tutorials/password-grant)


text:
#ifndef WTIMEINTEGRATION_H
#define WTIMEINTEGRATION_H

#include "sph.h"
#include "wObject.h"
#include <iostream>
#include <vector>
#include <memory>

namespace sph
{

/**
 * @brief main sph TimeIntegration object
 */

class SPH_API TimeIntegration : public fwk::wObject
{
public:
    TimeIntegration();
    virtual ~TimeIntegration();

#ifndef SWIG
    virtual void write(std::ostream &out) const override;
#endif
};

} // namespace sph

#endif //WTIMEINTEGRATION_H


text:
<!DOCTYPE html>

    <title>background-position: 2-value on top of 4-value</title>


text:
[![Stories in Ready](https://badge.waffle.io/Shougo/neobundle.vim.png)](https://waffle.io/Shougo/neobundle.vim)

## About

NeoBundle is a next generation Vim plugin manager. This plugin is based on
Vundle(https://github.com/gmarik/vundle), but I renamed and added tons of
features,  while Vundle tends to stay simple.

Requirements:
* Vim 7.2.051 or above.
* "git" command in $PATH(if you want to install github or vim.org plugins)

Recommends:
* vimproc(if you want to install/update asynchronously)
https://github.com/Shougo/vimproc.vim

Note: Neobundle is not stable plugin manager.  If you want to stable plugin
manager, you should use Vundle plugin.  It is well works widely and more
tested.  If you want to use extended features, you can use neobundle.

Vundle features : Stable, simple, good for beginners
neobundle features : Early development(may break compatibility), very complex,
good for plugin power users(for example, 50+ plugins and over 1000 lines
.vimrc, ...)

## How it works

Plugins are defined in NeoBundle by calling `NeoBundle '<plugin repository
location>'`.  NeoBundle assumes Github as the default location for plugins, so
for most plugins you can simply use `NeoBundle 'username/plugin'` rather than
using the absolute URL of the plugin.  These calls should be made in your
.vimrc file.  Once you have defined these, you must call `NeoBundleInstall`,
and NeoBundle will clone all of the repos into the desired folder (generally
`~/.vim/bundle`) and load them into Vim.  If you want to update these
repositories, simply call `NeoBundleUpdate`.

A few other useful commands:
- `:NeoBundleList`          - list configured bundles
- `:NeoBundleInstall(!)`    - install(update) bundles
- `:NeoBundleClean(!)`      - confirm(or auto-approve) removal of unused bundles

Refer to `:help neobundle` for more examples and for a full list of commands.

## Quick start

### 1. Install NeoBundle

#### If you are using Unix/Linux or Mac OX.

1. Run below script.

     ```
     $ curl https://raw.githubusercontent.com/Shougo/neobundle.vim/master/bin/install.sh | sh
     ```
Complete.

#### If you want to install manually or you are using Windows.

1. Setup NeoBundle:

     ```
     $ mkdir -p ~/.vim/bundle
     $ git clone https://github.com/Shougo/neobundle.vim ~/.vim/bundle/neobundle.vim
     ```

2. Configure bundles:

     Sample `.vimrc`:

     ```vim
     if has('vim_starting')
       set nocompatible               " Be iMproved

       " Required:
       set runtimepath+=~/.vim/bundle/neobundle.vim/
     endif

     " Required:
     call neobundle#begin(expand('~/.vim/bundle/'))

     " Let NeoBundle manage NeoBundle
     " Required:
     NeoBundleFetch 'Shougo/neobundle.vim'

     " My Bundles here:
     NeoBundle 'Shougo/neosnippet.vim'
     NeoBundle 'Shougo/neosnippet-snippets'
     NeoBundle 'tpope/vim-fugitive'
     NeoBundle 'kien/ctrlp.vim'
     NeoBundle 'flazz/vim-colorschemes'

     " You can specify revision/branch/tag.
     NeoBundle 'Shougo/vimshell', { 'rev' : '3787e5' }

     call neobundle#end()

     " Required:
     filetype plugin indent on

     " If there are uninstalled bundles found on startup,
     " this will conveniently prompt you to install them.
     NeoBundleCheck
     ```

### 2. Install configured bundles

Launch `vim`, run `:NeoBundleInstall`, or `:Unite neobundle/install`(required unite.vim) Or Command run `bin/neoinstall`

## Advantages over Vundle

1. Plugin prefixed command name(:Bundle vs :NeoBundle).
2. Support for vimproc(asynchronous update/install).
3. Support for unite.vim interface(update/install/search).
4. Support for revision locking.
5. Support for multiple version control systems (Subversion/Git).
6. Support for lazy initialization for optimizing startup time.
7. and so on...

## Tips

If you use a single .vimrc across systems where build programs are
named differently (e.g. GNU Make is often `gmake` on non-GNU
systems), the following pattern is useful:

```vim
let g:make = 'gmake'
if system('uname -o') =~ '^GNU/'
        let g:make = 'make'
endif
NeoBundle 'Shougo/vimproc.vim', {'build': {'unix': g:make}}
```


text:
package transportation.Test.mocks;

import bank.gui.Bank;
import simcity.interfaces.Bank_Douglass;
import simcity.interfaces.Person;

public class mockPerson_Daron implements Person {

	String name;

	public mockPerson_Daron(String name) {
		this.name = name;
	}
	@Override
	public String getName() {
		return name;
	}

	@Override
	public void msgWakeUp() {
		// TODO Auto-generated method stub

	}

	@Override
	public void msgGoToSleep() {
		// TODO Auto-generated method stub

	}

	@Override
	public void msgSetHungry() {
		// TODO Auto-generated method stub

	}

	@Override
	public void msgGoToWork(int i) {
		// TODO Auto-generated method stub

	}

	@Override
	public void msgStopWork(double amount) {
		// TODO Auto-generated method stub

	}

	@Override
	public void msgDoneEntering() {
		// TODO Auto-generated method stub

	}

	@Override
	public void msgRentIsDue(double amount) {
		// TODO Auto-generated method stub

	}

	@Override
	public void msgHereIsRent(double amount) {
		// TODO Auto-generated method stub

	}

	@Override
	public void msgNeedMaintenance() {
		// TODO Auto-generated method stub

	}

	@Override
	public void msgFinishedMaintenance() {
		// TODO Auto-generated method stub

	}

	@Override
	public void msgFoodDone(boolean doneEating) {
		// TODO Auto-generated method stub

	}

	@Override
	public void msgDoneLeaving() {
		// TODO Auto-generated method stub

	}

	@Override
	public void msgReachedDestination(String destination) {
		// TODO Auto-generated method stub

	}

	@Override
	public void msgPayFare(double fare) {
		// TODO Auto-generated method stub

	}

	public void msgLeftBank(Bank theBank, int accountNumber, double change,
			double loanAmount, int loanTime) {
		// TODO Auto-generated method stub

	}

	@Override
	public void msgDoneEating(boolean success, double newMoneyOnHand) {
		// TODO Auto-generated method stub

	}

	@Override
	public void msgHereIsOrder(String order, int quantity) {
		// TODO Auto-generated method stub

	}
	@Override
	public void msgLeftBank(Bank_Douglass theBank, int accountNumber,
			double change, double loanAmount, int loanTime) {
		// TODO Auto-generated method stub

	}
	@Override
	public void msgCrash(boolean b) {
		// TODO Auto-generated method stub

	}

}


text:
'use strict';
const expect = require('chai').expect;
const sinon = require('sinon');

const cryptoLib = require('crypto');

const crypto = require('../../src/services/crypto');

describe('Crypto Tests', function () {
    beforeEach(() => {
        this.sandbox = new sinon.sandbox.create();
    });

    afterEach(() => {
        this.sandbox.restore();
    });

    it('should test the generateSalt method', (done) => {
        let password = null;
        let testSalt = [];
        const SALT_LENGTH = 32;
        for (let i = 0; i < SALT_LENGTH; i++) {
            testSalt.push(0);
        }
        const randomBytesStub = this.sandbox.stub(cryptoLib, 'randomBytes').callsFake((length) => {
            return new Uint8Array(length);
        });

        const createHmacStub = this.sandbox.stub(cryptoLib, 'createHmac').callsFake(() => {
            return {
                digest: () => {
                    return 'hash_success';
                },
                update: (pw) => {
                    password = pw;
                }
            };
        });

        const result = crypto.generateSaltAndHash('test_password');
        const test = testSalt.toString('hex').slice(SALT_LENGTH);
        expect(result.salt).to.eql(test, `Expected ${result} to be '${test}'`);
        expect(result.hash).to.eql('hash_success', `Expected ${result} to be 'hash_success'`);
        expect(randomBytesStub.calledOnce).to.eql(true, 'Expected randomBytesStub to be called once');
        expect(createHmacStub.calledOnce).to.eql(true, 'Expected createHmacStub to be called once');
        expect(password).to.eql('test_password', `Expected ${password} to be 'test_password`);
        done();
    });

    it('should test the verifyPassword method', (done) => {
        let password = null;
        const createHmacStub = this.sandbox.stub(cryptoLib, 'createHmac').callsFake(() => {
            return {
                digest: () => {
                    return 'hash_success';
                },
                update: (pw) => {
                    password = pw;
                }
            };
        });

        const result = crypto.verifyPassword('test_password', 'test', 'hash_success');
        expect(result).to.eql(true, `Expected ${result} to be true`);
        expect(createHmacStub.calledOnce).to.eql(true, 'Expected "createHmacStub" to be called once');
        expect(password).to.eql('test_password', `Expected ${password} to be 'test_password`);
        done();
    });
});


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

	<modelVersion>4.0.0</modelVersion>

	<groupId>com.github.ckwen</groupId>
	<artifactId>je-shiro</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>pom</packaging>

	<modules>
		<module>je-shiro-test</module>
	</modules>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

		<maven.compiler.plugin.version>3.2</maven.compiler.plugin.version>
		<maven.compiler.plugin.source>1.8</maven.compiler.plugin.source>
		<maven.compiler.plugin.target>1.8</maven.compiler.plugin.target>
	</properties>

	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
		</dependency>
		<dependency>
			<groupId>commons-logging</groupId>
			<artifactId>commons-logging</artifactId>
			<version>1.1.3</version>
		</dependency>
		<dependency>
			<groupId>org.apache.shiro</groupId>
			<artifactId>shiro-core</artifactId>
			<version>1.2.2</version>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>${maven.compiler.plugin.version}</version>
				<configuration>
					<source>${maven.compiler.plugin.source}</source>
					<target>${maven.compiler.plugin.target}</target>
					<encoding>${project.build.sourceEncoding}</encoding>
				</configuration>
			</plugin>
		</plugins>
	</build>

</project>


text:
DROP TABLE IF EXISTS user;
CREATE TABLE user (
	id INTEGER PRIMARY KEY autoincrement,
	username VARCHAR(30) NOT NULL,
	password VARCHAR(30) NOT NULL,
	rank_id_FK INTEGER NOT NULL REFERENCES rank(id)
);
DROP TABLE IF EXISTS rank;
CREATE TABLE rank (
	id INTEGER PRIMARY KEY autoincrement,
	role_name VARCHAR(20) NOT NULL
);

DROP TABLE IF EXISTS entry;
CREATE TABLE entry (
	id INTEGER NOT NULL,
    slug VARCHAR(80) NOT NULL,
	title VARCHAR(80) NOT NULL,
	body TEXT NOT NULL,
	creation_date DATE NOT NULL,
	last_date DATE,
	user_id_FK INTEGER NOT NULL REFERENCES user(id),
    PRIMARY KEY(id, slug)
);

DROP TABLE IF EXISTS entry_tags;
CREATE TABLE entry_tags (
	slug_entry_FK INTEGER REFERENCES entry(id),
	id_tag_FK INTEGER REFERENCES tag(id),
	PRIMARY KEY(slug_entry_FK, id_tag_FK)
);

DROP TABLE IF EXISTS tag;
CREATE TABLE tag (
	id INTEGER PRIMARY KEY autoincrement,
	name VARCHAR(10) NOT NULL
);


text:
sap.ui.define(["exports", "sap/ui/webc/common/thirdparty/base/config/Theme", "./v5/italic-text", "./v4/italic-text"], function (_exports, _Theme, _italicText, _italicText2) {
  "use strict";

  Object.defineProperty(_exports, "__esModule", {
    value: true
  });
  Object.defineProperty(_exports, "accData", {
    enumerable: true,
    get: function () {
      return _italicText.accData;
    }
  });
  _exports.default = void 0;
  Object.defineProperty(_exports, "ltr", {
    enumerable: true,
    get: function () {
      return _italicText.ltr;
    }
  });
  _exports.pathData = void 0;
  const pathData = (0, _Theme.isThemeFamily)("sap_horizon") ? _italicText.pathData : _italicText2.pathData;
  _exports.pathData = pathData;
  var _default = "italic-text";
  _exports.default = _default;
});


text:
<?php namespace MicroStatic;

/**
 * Class Middleware
 *
 * @package MicroStatic
 */
class Micro
{
    /**
     * @param $config
     * @param $closure
     *
     * @return bool
     * @internal param null $route
     *
     */
    public static function run($config, $closure)
    {
        Config::init($config['config'], $config['path']);

        Router::init();

        $closure();

        $route = Router::getRoute();

        Response::setContent(
            Middleware::dispatch(function () use ($route) {
                return FrontController::dispatch($route);
            }, $route->getMiddlewares())
        );

        Response::send();
    }

}


text:
<assembly
  xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation=
     "http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2
      http://maven.apache.org/xsd/assembly-1.1.2.xsd">

  <id>dist</id>
  <formats>
    <format>tar.gz</format>
    <format>tar.bz2</format>
    <format>zip</format>
  </formats>
  <fileSets>
    <fileSet>
      <directory>${project.basedir}</directory>
      <outputDirectory>/</outputDirectory>
      <includes>
        <include>README*</include>
        <include>LICENSE*</include>
        <include>NOTICE*</include>
      </includes>
    </fileSet>
    <fileSet>
      <directory>${project.build.directory}</directory>
      <outputDirectory>/</outputDirectory>
      <includes>
        <include>*.jar</include>
      </includes>
    </fileSet>
  </fileSets>
  <dependencySets>
    <dependencySet>
      <useProjectArtifact>false</useProjectArtifact>
      <outputDirectory>lib</outputDirectory>
    </dependencySet>
  </dependencySets>
</assembly>


text:
using System.Net;
using NUnit.Framework;
using SevenDigital.Api.Schema.User.Payment;
using SevenDigital.Api.Wrapper.Responses;
using SevenDigital.Api.Wrapper.Responses.Parsing;

namespace SevenDigital.Api.Wrapper.Unit.Tests.Parsing.User.Payment
{
	[TestFixture]
	public class AddCardsTests
	{
		private const string responseXml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
			"<response xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"http://api.7digital.com/1.2/static/7digitalAPI.xsd\" status=\"ok\" version=\"1.2\">" +
				"<card id=\"8154430\">" +
					"<type>Visa</type>" +
					"<last4digits>5485</last4digits>" +
					"<default>true</default>" +
					"<cardHolderName>MR I HUNT</cardHolderName>" +
					"<expiryDate>201202</expiryDate>" +
					"<country>NZ</country>" +
				"</card>" +
				"</response>";

		private readonly Response response = new Response(HttpStatusCode.OK, responseXml);

		[Test]
		public void can_deserialise_response_user_cards()
		{
			var xmlParser = new ResponseParser(new ApiResponseDetector());

			var deserializedCards = xmlParser.Parse<AddCard>(response);

			Assert.That(deserializedCards, Is.Not.Null);
		}
	}
}


text:
The main client used for HTTP/2 Tests is [cURL](http://curl.haxx.se/). This package required some dependencies but, we have deployed an installation script for make it easy on [this repository](https://github.com/jgm1986/HTTP2-Testing/tree/master/clients). There are more info about the installation process on the README.md file.

## How to use this client?

The binary file of this cURL version is under src/curl inside cURL installation directory.

```
/ # Repository main folder.
|
└───clients/
    |
    └───packages/
        |
        └───curl/	# cURL installation directory.
```

On the other hand, there are several input parameters for this client but I only explain the most useful for our tests:

### · https://URLs *(h2)*

This command allow open an h2 session for get the test template number 1 from our public test server.

```sh
$ src/curl --verbose --http2 https://testhttp2.bluevia.com/test/test_01.html
```

- **--verbose:** Verbose mode.
- **--http2:** Use HTTP/2 protocol.

### · http://URLs *(h2c Upgrade)*

The easy way to get the same test page but using HTTP/2 Clear Text is using this:

```sh
$ src/curl --verbose --http2 http://testhttp2.bluevia.com/test/test_01.html
```

- **--verbose:** Verbose mode.
- **--http2:** Use HTTP/2 protocol.

### · http://URLs *(h2c)*

Direct mode is not supported on this version of cURL.


text:
import logging
from modules.payload_builder import PayloadBuilder
import shutil
import os
from modules.obfuscate_names import ObfuscateNames
from modules.obfuscate_form import ObfuscateForm
from modules.obfuscate_strings import ObfuscateStrings
from modules.uac_bypass import UACBypass

class VBAGenerator(PayloadBuilder):
    """ Module used to generate VBA file from working dir content"""

    def transformAndObfuscate(self):
        """
        Call this method to apply transformation and obfuscation on the content of temp directory
        This method does obfuscation for all VBA and VBA like types

        """

        # Enable UAC bypass
        if self.mpSession.uacBypass:
            uacBypasser = UACBypass(self.mpSession)
            uacBypasser.run()

        # Macro obfuscation
        if self.mpSession.obfuscateNames:
            obfuscator = ObfuscateNames(self.mpSession)
            obfuscator.run()
        # Mask strings
        if self.mpSession.obfuscateStrings:
            obfuscator = ObfuscateStrings(self.mpSession)
            obfuscator.run()
        # Macro obfuscation
        if self.mpSession.obfuscateForm:
            obfuscator = ObfuscateForm(self.mpSession)
            obfuscator.run()

    def check(self):
        return True

    def printFile(self):
        """ Display generated code on stdout """
        logging.info(" [+] Generated VB code:\n")
        if len(self.getVBAFiles())==1:
            vbaFile = self.getMainVBAFile()
            with open(vbaFile,'r') as f:
                print(f.read())
        else:
            logging.info("   [!] More then one VB file generated")
            for vbaFile in self.getVBAFiles():
                with open(vbaFile,'r') as f:
                    print(" =======================  %s  ======================== " % vbaFile)
                    print(f.read())

    def generate(self):
        if len(self.getVBAFiles())>0:
            logging.info(" [+] Analyzing generated VBA files...")
            if len(self.getVBAFiles())==1:
                shutil.copy2(self.getMainVBAFile(), self.outputFilePath)
                logging.info("   [-] Generated VBA file: %s" % self.outputFilePath)
            else:
                logging.info("   [!] More then one VBA file generated, files will be copied in same dir as %s" % self.outputFilePath)
                for vbaFile in self.getVBAFiles():
                    if vbaFile != self.getMainVBAFile():
                        shutil.copy2(vbaFile, os.path.join(os.path.dirname(self.outputFilePath),os.path.basename(vbaFile)))
                        logging.info("   [-] Generated VBA file: %s" % os.path.join(os.path.dirname(self.outputFilePath),os.path.basename(vbaFile)))
                    else:
                        shutil.copy2(self.getMainVBAFile(), self.outputFilePath)
                        logging.info("   [-] Generated VBA file: %s" % self.outputFilePath)

    def getAutoOpenVbaFunction(self):
        return "AutoOpen"

    def getAutoOpenVbaSignature(self):
        return "Sub AutoOpen()"

    def resetVBAEntryPoint(self):
        """
        If macro has an autoopen like mechanism, this will replace the entry_point with what is given in newEntrPoin param
        Ex for Excel it will replace "Sub AutoOpen ()" with "Sub Workbook_Open ()"
        """
        mainFile = self.getMainVBAFile()
        if mainFile != "" and self.startFunction is not None:
            if self.startFunction != self.getAutoOpenVbaFunction() and self.startFunction in self.potentialStartFunctions: # we do not replace if non autopopen start function is used
                logging.info("   [-] Changing auto open function from %s to %s..." % (self.startFunction, self.getAutoOpenVbaFunction()))
                #1 Replace line in VBA
                f = open(mainFile)
                content = f.readlines()
                f.close()
                for n,line in enumerate(content):
                    if line.find(" " + self.startFunction) != -1:
                        #logging.info("     -> %s becomes %s" %(content[n], self.getAutoOpenVbaSignature()))
                        content[n] = self.getAutoOpenVbaSignature() + "\n"
                f = open(mainFile, 'w')
                f.writelines(content)
                f.close()
                # 2 Change  current module start function
                self._startFunction = self.getAutoOpenVbaFunction()


text:
package controllers

import models._
import play.api.mvc.{ Action, Controller }
import utils.Security.Authentication
import utils.semantic.Vocabulary.lwm

import scala.concurrent.Future
import scala.util.Random

object TestDataController extends Controller with Authentication {

  import scala.concurrent.ExecutionContext.Implicits.global

  def generateTestData() = hasPermissions(Permissions.AdminRole.permissions.toList: _*) {
    session ⇒
      import utils.Global._
      Action.async {
        implicit request ⇒

          val semesterFuture = Semesters.create(WinterSemester(2014))

          val courseFuture = Courses.create(Course("Algorithmen und Programmierung 1", "AP1", lwm.MediaInformaticsBachelor))

          val labworkFuture = for {
            semester ← semesterFuture
            course ← courseFuture
          } yield LabWorks.create(LabWork(course, semester))

          val studentsAffeFutures = for (i ← 1 to 500) yield Students.create(Student(
            s"mi_$i",
            s"Random_Bobbi_$i",
            s"Affe",
            s"${Random.nextInt(10000) + 11000000}",
            s"random_email_$i@gm.fh-koeln.de",
            s"${Random.nextInt(7726262)}",
            s"${lwm.MediaInformaticsBachelor.value}"
          ))

          val studentsSchweinFutures = for (i ← 501 to 1000) yield Students.create(Student(
            s"mi_$i",
            s"Random_Schwein_$i",
            s"Schweini",
            s"${Random.nextInt(10000) + 11000000}",
            s"random_email_$i@gm.fh-koeln.de",
            s"${Random.nextInt(7726262)}",
            s"${lwm.MediaInformaticsBachelor.value}"
          ))

          for {
            affeFuture ← studentsAffeFutures
          } yield {
            for {
              affe ← affeFuture
              lwf ← labworkFuture
              lw ← lwf
            } yield LabworkApplications.create(LabworkApplication(affe, lw.uri, Nil))
          }

          for {
            schweinFutures ← studentsSchweinFutures
          } yield {
            for {
              affe ← schweinFutures
              lwf ← labworkFuture
              lw ← lwf
            } yield LabworkApplications.create(LabworkApplication(affe, lw.uri, Nil))
          }

          val student1 = Students.create(Student(
            s"mi_1111",
            s"Random_Schwein_1111",
            s"Schweini",
            s"${Random.nextInt(10000) + 11000000}",
            s"random_email_1111@gm.fh-koeln.de",
            s"${Random.nextInt(7726262)}",
            s"${lwm.MediaInformaticsBachelor.value}"
          ))
          val student2 = Students.create(Student(
            s"mi_1112",
            s"Random_Schwein_1112",
            s"Schweini",
            s"${Random.nextInt(10000) + 11000000}",
            s"random_email_1111@gm.fh-koeln.de",
            s"${Random.nextInt(7726262)}",
            s"${lwm.MediaInformaticsBachelor.value}"
          ))
          val student3 = Students.create(Student(
            s"mi_1113",
            s"Random_Schwein_1113",
            s"Schweini",
            s"${Random.nextInt(10000) + 11000000}",
            s"random_email_1111@gm.fh-koeln.de",
            s"${Random.nextInt(7726262)}",
            s"${lwm.MediaInformaticsBachelor.value}"
          ))
          val student4 = Students.create(Student(
            s"mi_1114",
            s"Random_Schwein_1114",
            s"Schweini",
            s"${Random.nextInt(10000) + 11000000}",
            s"random_email_1111@gm.fh-koeln.de",
            s"${Random.nextInt(7726262)}",
            s"${lwm.MediaInformaticsBachelor.value}"
          ))

          val student5 = Students.create(Student(
            s"mi_1115",
            s"Random_Schwein_1115",
            s"Schweini",
            s"${Random.nextInt(10000) + 11000000}",
            s"random_email_1111@gm.fh-koeln.de",
            s"${Random.nextInt(7726262)}",
            s"${lwm.MediaInformaticsBachelor.value}"
          ))
          val student6 = Students.create(Student(
            s"mi_1116",
            s"Random_Schwein_1116",
            s"Schweini",
            s"${Random.nextInt(10000) + 11000000}",
            s"random_email_1111@gm.fh-koeln.de",
            s"${Random.nextInt(7726262)}",
            s"${lwm.MediaInformaticsBachelor.value}"
          ))

          for {
            s1 ← student1
            s2 ← student2
            s3 ← student3
            s4 ← student4
            s5 ← student5
            s6 ← student6
            lwf ← labworkFuture
            lw ← lwf
          } yield {

            LabworkApplications.create(LabworkApplication(s1, lw.uri, List(s5, s3, s4)))
            LabworkApplications.create(LabworkApplication(s2, lw.uri, List(s1, s3, s4)))
            LabworkApplications.create(LabworkApplication(s3, lw.uri, List(s2, s1, s4)))
            LabworkApplications.create(LabworkApplication(s4, lw.uri, List(s2, s3, s1)))
            LabworkApplications.create(LabworkApplication(s5, lw.uri, List(s1, s6)))
            LabworkApplications.create(LabworkApplication(s6, lw.uri, List(s6)))
          }

          Future.successful(Redirect(routes.StudentsManagement.index("1")))
      }
  }
}


text:
require 'test_helper'

class ServiceVersionTest < ActiveSupport::TestCase

  test 'validations' do
    # VALID_SPEC and INVALID_SPEC are loaded by test_helper
    valid_service_version = ServiceVersion.new(
      spec_file: StringIO.new(VALID_SPEC), service: services(:servicio_1), user: users(:perico))
    invalid_service_version = ServiceVersion.new(
      spec_file: StringIO.new(INVALID_SPEC), service: services(:servicio_2), user: users(:perico))
    assert valid_service_version.valid?
    assert_not invalid_service_version.valid?
    assert_not invalid_service_version.errors[:spec].blank?
  end

  test '#make_current_version create 3 versions backwards_compatible'\
        'and make each one current only one current must exist and the other'\
        'two must be outdated' do

    service = Service.create!(
      name: "Test Servicio 1",
      organization: organizations(:segpres),
      public: true,
      spec_file: StringIO.new(VALID_SPEC)
      )
    user = users(:pablito)
    version = service.service_versions.create!(spec_file: StringIO.new(VALID_SPEC),
                                     service: service,
                                     user: user,
                                     backwards_compatible: true)
    version.make_current_version
    version = service.service_versions.create!(spec_file: StringIO.new(VALID_SPEC),
                                     service: service,
                                     user: user,
                                     backwards_compatible: true)
    version.make_current_version
    version = service.service_versions.create!(spec_file: StringIO.new(VALID_SPEC),
                                     service: service,
                                     user: user,
                                     backwards_compatible: true)
    version.make_current_version

    assert_equal 2, service.service_versions.outdated.length
    assert_equal 1, service.service_versions.current.length
  end

  test '#make_current_version create 3 versions without backwards_compatible'\
        'and make each one current only one current must exist and the other'\
        'two must be retired' do

    service = Service.create!(
      name: "Test Servicio 1",
      organization: organizations(:segpres),
      public: true,
      spec_file: StringIO.new(VALID_SPEC)
      )
    user = users(:pablito)

    version = service.service_versions.create!(spec_file: StringIO.new(VALID_SPEC),
                                     service: service,
                                     user: user)
    version.make_current_version
    version = service.service_versions.create!(spec_file: StringIO.new(VALID_SPEC),
                                     service: service,
                                    user: user)
    version.make_current_version
    version = service.service_versions.create!(spec_file: StringIO.new(VALID_SPEC),
                                     service: service,
                                    user: user)
    version.make_current_version
    assert_equal 2, service.service_versions.retired.length
    assert_equal 1, service.service_versions.current.length
  end

  test '#reject_version create 3 versions and reject them all 3 must be rejected' do
    service = services(:servicio_1)
    service.service_versions.create!(spec_file: StringIO.new(VALID_SPEC),
                                     service: service,
                                    user: users(:pablito),
                                    backwards_compatible: true)
    service.last_version.reject_version
    service.service_versions.create!(spec_file: StringIO.new(VALID_SPEC),
                                     service: service,
                                    user: users(:pablito),
                                    backwards_compatible: true)
    service.last_version.reject_version
    service.service_versions.create!(spec_file: StringIO.new(VALID_SPEC),
                                     service: service,
                                    user: users(:pablito),
                                    backwards_compatible: true)
    service.last_version.reject_version
    assert_equal 3, service.service_versions.rejected.length
  end
=begin
  test "generate_zipped_code returns an URL where the code can be downloaded" do
    service = services(:servicio_1)
    service_version = service.service_versions.create!(
      spec_file: StringIO.new(VALID_SPEC),
      service: service,
      user: users(:pablito),
      backwards_compatible: true
    )
    url = service_version.generate_zipped_code(%w(java php csharp jaxrs-cxf slim aspnet5))
    assert !open(url).read.nil?
  end
=end
  test ".make_current_version take a proposed version an makes it approved and send a notification" do
    #def make_current_version
    #self.current!
    #update_old_versions_statuses
    #create_state_change_notification(I18n.t(:approved))

  end

  test ".reject_version take a proposed version an makes it rejected and send a notification" do
    #def reject_version
    #self.rejected!
    #create_state_change_notification(I18n.t(:rejected))
  end

  test ".create_new_notification generates a new notification about the service_version" do
    #def create_new_notification
    #org = Organization.where(dipres_id: "AB01")
    #if version_number == 1
    #  message = I18n.t(:create_new_service_notification, name: name)
    #else
    #  message = I18n.t(:create_new_version_notification, name: name, version: version_number.to_s)
    #end
    #Role.where(name: "Service Provider", organization: org).each do |role|
    #  role.user.notifications.create(subject: self,
    #    message: message
    #  )
    #end
  end

  test ".create_state_change_notification create a state change notification about to the service_version" do
    #def create_state_change_notification(status)
    #org = Organization.where(dipres_id: "AB01")
    #user.notifications.create(subject: self,
    #  message: I18n.t(:create_state_change_notification, name: name,
    #    version: self.version_number.to_s, status: status)
    #)
  end

  test ".retract_proposed mark al notification of older proposed versions as readed" do
    #def retract_proposed
    #service.service_versions.proposed.where(
    #  "version_number != ?", self.version_number).each do |version|
    #
    #    version.update(status: ServiceVersion.statuses[:retracted])
    #    version.notifications.update_all(read: true)
    #end
  end

end


text:
import pytac.load_csv
import pytac.epics

def main():
    lattice = pytac.load_csv.load('VMX', pytac.epics.EpicsControlSystem())
    print lattice.get_length()

if __name__=='__main__':
    main()


text:
package io.pslab.communication.sensors;

import android.util.Log;

import io.pslab.communication.ScienceLab;
import io.pslab.communication.peripherals.I2C;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;

/**
 * Created by akarshan on 4/15/17.
 */

public class TSL2561 {
    private String TAG = "TSL2561";
    private int VISIBLE = 2;  // channel 0 - channel 1
    private int INFRARED = 1;  // channel 1
    private int FULLSPECTRUM = 0;  // channel 0

    private int READBIT = 0x01;
    private int COMMAND_BIT = 0x80; // Must be 1

    private int CONTROL_POWERON = 0x03;
    private int CONTROL_POWEROFF = 0x00;

    private int REGISTER_CONTROL = 0x00;
    private int REGISTER_TIMING = 0x01;
    private int REGISTER_ID = 0x0A;

    private int INTEGRATIONTIME_13MS = 0x00;  // 13.7ms
    private int INTEGRATIONTIME_101MS = 0x01;  // 101ms
    private int INTEGRATIONTIME_402MS = 0x02;  // 402ms

    private int GAIN_1X = 0x00;     // No gain
    private int GAIN_16X = 0x10;    // 16x gain
    private int GAIN_OX;

    private int ADDRESS = 0x39;  // addr normal
    private int timing = INTEGRATIONTIME_13MS;
    private int gain = GAIN_16X;

    public String name = "TSL2561 Luminosity";
    public int NUMPLOTS = 3;
    public String[] PLOTNAMES = {"Full", "IR", "Visible"};

    private I2C i2c;
    private int full, infra;
    private ArrayList<Character> infraList, fullList;
    private ArrayList<java.io.Serializable> setGain = new ArrayList<java.io.Serializable>(Arrays.asList("1x", "16x"));
    private ArrayList<java.io.Serializable> setTiming = new ArrayList<java.io.Serializable>(Arrays.asList(0, 1, 2));

    public TSL2561(I2C i2c, ScienceLab scienceLab) throws IOException, InterruptedException {
        this.i2c = i2c;
        // set timing 101ms & 16x gain
        if (scienceLab.isConnected()) {
            enable();
            _wait();
            i2c.writeBulk(ADDRESS, new int[]{0x80 | 0x01, 0x01 | 0x10});
            //full scale luminosity
            infraList = i2c.readBulk(ADDRESS, 0x80 | 0x20 | 0x0E, 2);
            fullList = i2c.readBulk(ADDRESS, 0x80 | 0x20 | 0x0C, 2);
            full = (fullList.get(1) << 8) | fullList.get(0);
            infra = (infraList.get(1) << 8) | infraList.get(0);

            Log.v(TAG, "Full - " + Integer.toString(full));
            Log.v(TAG, "Infrared - " + Integer.toString(infra));
            Log.v(TAG, "Visible -" + Integer.toString(full - infra));
        }
    }

    public int getID() throws IOException {
        ArrayList<Character> _ID_ = i2c.readBulk(ADDRESS, REGISTER_ID, 1);
        int ID = Integer.parseInt(Character.getNumericValue(_ID_.get(0)) + "", 16);
        Log.d("ID", Integer.toString(ID));
        return ID;
    }

    public int[] getRaw() throws IOException {
        fullList = i2c.readBulk(ADDRESS, 0x80 | 0x20 | 0x0E, 2);
        infraList = i2c.readBulk(ADDRESS, 0x80 | 0x20 | 0x0C, 2);
        if (!infraList.isEmpty()) {
            full = (fullList.get(0) << 8) | fullList.get(0);
            infra = (infraList.get(0) << 8) | infraList.get(0);
            return (new int[]{full, infra, full - infra});
        } else
            return null;
    }

    public void setGain(String _gain_) throws IOException {
        if (_gain_.equals("1x"))
            gain = GAIN_1X;

        else if (_gain_.equals("16x"))
            gain = GAIN_16X;
        else
            gain = GAIN_OX;
        i2c.writeBulk(ADDRESS, new int[]{COMMAND_BIT | REGISTER_TIMING, gain | timing});
    }

    public void setTiming(int timing) throws IOException {
        Log.v(TAG, new int[]{13, 101, 404}[timing] + "mS");
        this.timing = timing;
        i2c.writeBulk(ADDRESS, new int[]{COMMAND_BIT | REGISTER_TIMING, gain | timing});
    }

    private void enable() throws IOException {
        i2c.writeBulk(ADDRESS, new int[]{COMMAND_BIT | REGISTER_CONTROL, CONTROL_POWERON});
    }

    public void disable() throws IOException {
        i2c.writeBulk(ADDRESS, new int[]{COMMAND_BIT | REGISTER_CONTROL, CONTROL_POWEROFF});
    }

    private void _wait() throws InterruptedException {
        if (timing == INTEGRATIONTIME_13MS) TimeUnit.MILLISECONDS.sleep(14);
        if (timing == INTEGRATIONTIME_101MS) TimeUnit.MILLISECONDS.sleep(102);
        if (timing == INTEGRATIONTIME_402MS) TimeUnit.MILLISECONDS.sleep(403);

    }

}


text:
/*
package message defines the Composer interface and a handful of
implementations which represent the structure for messages produced by grip.

Message Composers

The Composer interface provides a common way to define messages, with
two main goals:

1. Provide a common interface for representing structured and
unstructured logging data regardless of logging backend or interface.

2. Provide a method for *lazy* construction of log messages so they're
built *only* if a log message is over threshold.

The message package also contains many implementations of Composer
which should support most logging use cases. However, any package
using grip for logging may need to implement custom composer types.

The Composer implementations in the message package compose the Base
type to provide some common functionality around priority setting and
data collection.

The logging methods in the Journaler interface typically convert all
inputs into a reasonable Composer implementations.
*/
package message

// This file is intentionally documentation only.


text:
/**
 *
 */
package gov.va.med.imaging.storage.cache.interactive.commands;

import gov.va.med.imaging.storage.cache.Cache;
import gov.va.med.imaging.storage.cache.impl.CacheManagerImpl;
import gov.va.med.interactive.Command;
import gov.va.med.interactive.CommandProcessor;

/**
 * @author VHAISWBECKEC
 *
 */
public class StoreCommand
extends Command<CacheManagerImpl>
{

	/**
	 *
	 */
	public StoreCommand()
	{
		super();
		// TODO Auto-generated constructor stub
	}

	/* (non-Javadoc)
	 * @see gov.va.med.imaging.storage.cache.interactive.ValidCommandProcessor#processCommand(gov.va.med.imaging.storage.cache.interactive.CommandProcessor, gov.va.med.imaging.storage.cache.impl.CacheManagerImpl, gov.va.med.imaging.storage.cache.interactive.Command)
	 */
	@Override
	public void processCommand(CommandProcessor processor, CacheManagerImpl manager)
	throws Exception
	{
		Cache cache = manager.getActiveCache();
		manager.store(cache);
	}

}


text:
package org.kie.workbench.common.widgets.client.datamodel;

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

/**
 * An Oracle for all things "CEP" related
 */
public class CEPOracle {

    //CEP Operators
    private static final String[] WINDOW_CEP_OPERATORS = new String[]{
            "over window:time",
            "over window:length" };

    private static final String[] SIMPLE_CEP_OPERATORS = new String[]{
            "after",
            "before",
            "coincides" };

    private static final String[] COMPLEX_CEP_OPERATORS = new String[]{
            "during",
            "finishes",
            "finishedby",
            "includes",
            "meets",
            "metby",
            "overlaps",
            "overlappedby",
            "starts",
            "startedby" };

    private static final String[] SIMPLE_CEP_CONNECTIVES = new String[]{
            "|| after",
            "|| before",
            "|| coincides",
            "&& after",
            "&& before",
            "&& coincides" };

    private static final String[] COMPLEX_CEP_CONNECTIVES = new String[]{
            "|| during",
            "|| finishes",
            "|| finishedby",
            "|| includes",
            "|| meets",
            "|| metby",
            "|| overlaps",
            "|| overlappedby",
            "|| starts",
            "|| startedby",
            "&& during",
            "&& finishes",
            "&& finishedby",
            "&& includes",
            "&& meets",
            "&& metby",
            "&& overlaps",
            "&& overlappedby",
            "&& starts",
            "&& startedby" };

    private static final Map<String, List<Integer>> CEP_OPERATORS_PARAMETERS = new HashMap<String, List<Integer>>();

    static {
        CEP_OPERATORS_PARAMETERS.put( "after",
                                      Arrays.asList( new Integer[]{ 0, 1, 2 } ) );
        CEP_OPERATORS_PARAMETERS.put( "before",
                                      Arrays.asList( new Integer[]{ 0, 1, 2 } ) );
        CEP_OPERATORS_PARAMETERS.put( "coincides",
                                      Arrays.asList( new Integer[]{ 0, 1, 2 } ) );
        CEP_OPERATORS_PARAMETERS.put( "during",
                                      Arrays.asList( new Integer[]{ 0, 1, 2, 4 } ) );
        CEP_OPERATORS_PARAMETERS.put( "finishes",
                                      Arrays.asList( new Integer[]{ 0, 1 } ) );
        CEP_OPERATORS_PARAMETERS.put( "finishedby",
                                      Arrays.asList( new Integer[]{ 0, 1 } ) );
        CEP_OPERATORS_PARAMETERS.put( "includes",
                                      Arrays.asList( new Integer[]{ 0, 1, 2, 4 } ) );
        CEP_OPERATORS_PARAMETERS.put( "meets",
                                      Arrays.asList( new Integer[]{ 0, 1 } ) );
        CEP_OPERATORS_PARAMETERS.put( "metby",
                                      Arrays.asList( new Integer[]{ 0, 1 } ) );
        CEP_OPERATORS_PARAMETERS.put( "overlaps",
                                      Arrays.asList( new Integer[]{ 0, 1, 2 } ) );
        CEP_OPERATORS_PARAMETERS.put( "overlappedby",
                                      Arrays.asList( new Integer[]{ 0, 1, 2 } ) );
        CEP_OPERATORS_PARAMETERS.put( "starts",
                                      Arrays.asList( new Integer[]{ 0, 1 } ) );
        CEP_OPERATORS_PARAMETERS.put( "startedby",
                                      Arrays.asList( new Integer[]{ 0, 1 } ) );
    }

    /**
     * Check whether an operator is a CEP operator
     * @param operator
     * @return True if the operator is a CEP operator
     */
    public static boolean isCEPOperator( final String operator ) {
        if ( operator == null ) {
            return false;
        }

        String[] operators = OracleUtils.joinArrays( SIMPLE_CEP_OPERATORS,
                                                     COMPLEX_CEP_OPERATORS,
                                                     SIMPLE_CEP_CONNECTIVES,
                                                     COMPLEX_CEP_CONNECTIVES );

        for ( int i = 0; i < operators.length; i++ ) {
            if ( operator.equals( operators[ i ] ) ) {
                return true;
            }
        }
        return false;
    }

    /**
     * Get the parameter sets for the given CEP Operator (simple, or connective)
     * e.g. CEP operator "during" requires 0, 1, 2 or 4 parameters so the
     * returned list contains 0, 1, 2 and 4.
     * @param operator
     * @return
     */
    public static List<Integer> getCEPOperatorParameterSets( String operator ) {
        List<Integer> sets = new ArrayList<Integer>();
        if ( operator == null ) {
            return sets;
        }
        if ( operator.startsWith( "|| " ) || operator.startsWith( "&& " ) ) {
            operator = operator.substring( 3 );
        }
        if ( !CEP_OPERATORS_PARAMETERS.containsKey( operator ) ) {
            return sets;
        }

        return CEP_OPERATORS_PARAMETERS.get( operator );
    }

    /**
     * Return a list of operators applicable to CEP windows
     * @return
     */
    public static List<String> getCEPWindowOperators() {
        return Arrays.asList( WINDOW_CEP_OPERATORS );
    }

    /**
     * Check whether an operator is a CEP 'window' operator
     * @param operator
     * @return True if the operator is a CEP 'window' operator
     */
    public static boolean isCEPWindowOperator( String operator ) {
        if ( operator == null ) {
            return false;
        }

        for ( String cepWindowOperator : WINDOW_CEP_OPERATORS ) {
            if ( operator.equals( cepWindowOperator ) ) {
                return true;
            }
        }
        return false;
    }

    /**
     * Check if the operator is 'window over:time'
     * @param operator
     * @return if
     */
    public static boolean isCEPWindowOperatorTime( String operator ) {
        if ( operator == null ) {
            return false;
        }
        return WINDOW_CEP_OPERATORS[ 0 ].equals( operator );
    }

    /**
     * Check if the operator is 'window over:length'
     * @param operator
     * @return if
     */
    public static boolean isCEPWindowOperatorLength( String operator ) {
        if ( operator == null ) {
            return false;
        }
        return WINDOW_CEP_OPERATORS[ 1 ].equals( operator );
    }

}


text:
package com.conniffe.brezina.harvey;

import java.util.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import net.sf.json.*;
import java.net.*;
import twitter4j.*;
import twitter4j.auth.*;

public class GetURL extends HttpServlet {

    private static final String CONSUMER_KEY = "TWITTER-CONSUMER-KEY";
    private static final String CONSUMER_SECRET = "TWITTER-CONSUMER-SECRET";

    public void init(ServletConfig config) throws ServletException {
	super.init(config);
    }

    public void destroy() {}

    public String getServletInfo() {
	return "Gets authentication url";
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

	JSONObject jres = new JSONObject();

	try {
      	    Twitter twitter = new TwitterFactory().getInstance();
	    twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
	    RequestToken requestToken = twitter.getOAuthRequestToken();
	    String tokensecret = requestToken.getTokenSecret();
	    jres.put("TS", tokensecret);
	    jres.put("URL", requestToken.getAuthorizationURL());
	    jres.put("iserr", "NO");
	}

	catch(Exception e) {
	    e.printStackTrace();
	    jres.put("iserr", "YES");
	    jres.put("errtext", e.getMessage());
	}

	response.setContentType("application/json; charset=UTF-8");
	PrintWriter out = response.getWriter();
	out.println(jres);

    }
}


text:
meta is a C++11 library built on top of the type_traits standard library focused
on functional-style metaprogramming.

## Type Wrappers

__Type wrappers__ (otherwise known as __integral constant wrappers__) provide wrappers for
manipulating fundamental, arithmetic C++ types and their values for use in template
metaprograms.

### Example

```cpp
#include <iostream>
#include "meta.hh"

using namespace meta::typewrappers;

int main() {
  std::cout << plus<uint_<1>, uint_<1>>::value << std::endl; // == 2
  return 0;
}
```
Currently the following operations are supported:
* addition, subtraction, multiplication, division, modulo
* next, prev

The following type wrappers are implemented:
* A generic `type_` type.
* `bool_` (wrapper for `std::true_type` and `std::false_type`).
* `char_`, `uchar_`.
* `int_`, `uint_`.
* `long_`, `ulong_`.

## Lambda and apply

`apply` is a metafunction that accepts another metafunction and applies it with the arguments you give it:
```cpp
template <typename x, typename y>
struct sum_f : int_<x::value + y::value> {};
apply<sum_f, int_<1>, int_<1>>::type::value; // == 2
```
Using `lambda` you can turn metafunctions into metafunction classes and apply them as such:
```cpp
template <typename x, typename y>
struct sum_f : int_<x::value + y::value> {};
lambda<sum_f>::template apply<int_<1>, int_<1>>::type::value; // == 2
```

## Lists

Lists are fundamentally designed in the same way as in Scheme, by pairing a value and a list using `cons` to produce a list:
```scheme
(cons 1 (cons 2 (cons 3 '())))
```
in meta:
```cpp
cons<int_<1>, cons<int_<2>, cons<int_<3>, empty>>>
```
car and cdr operations are also defined in the same way as in Scheme:
```cpp
car<cons<int_<1>, empty>>::type::value // == 1
cdr<cons<int_<1>, cons<int_<2>, int_<3>>>>::type // == cons<int_<2>, int_<3>>
```
Since using cons creates a lot of syntactic noise, like in Scheme, there is also a `list` metafunction:
```cpp
list<int_<1>, int_<2>, int_<3>> // == cons<int_<1>, cons<int_<2>, int_<3>>>
```
Still, this ends up producing a lot of noise because of the integral constant wrappers, so `list_c` was invented:
```cpp
list_c<int, 1, 2, 3> // == list<int_<1>, int_<2>, int_<3>>
```
You can also operate on these lists, with a little help from `lambda`, incrementing each value in a list is easy:
```cpp
map<lambda<incr_f>, list_c<int, 1, 2, 3>> // == list_c<int, 2, 3, 4>
```

## Reflection

meta currently has limited support for reflection. Due to the way template metaprogramming works,
it's not possible to do much without introducing many macros into the code, but with `std:;type_traits` this makes some things now possible. Like the library, this section is a work in progress.

Here's an example of determining if a class has a `foo` member:
```cpp
META_DECLARE_CLASS_MEMBER(foo);
class FooFieldClass {
public:
  int foo;
};
class FooMethodClass {
public:
  void foo() {}
};
class EmptyClass {};
class_has_member_foo<EmptyClass>::type::value // == false
class_has_member_foo<FooFieldClass>::type::value // == true
class_has_member_foo<FooMethodClass>::type::value // == true
```
Unfortunately this isn't perfect since private and protected members return false. However, you can use `META_MAKE_FRIEND` to allow access to all members:
```cpp
META_DECLARE_CLASS_MEMBER(foo);
class FooClass {
  META_MAKE_FRIEND(FooClass, foo);
  void foo() {}
};
class_has_member_foo<FooClass>::type::value // == true
```

With meta you can also get types of methods and fields:
```cpp
class FooClass {
public:
  int foo;
  void bar() {}
};
META_GET_FIELD_TYPE(FooClass, foo); // == int
META_GET_METHOD_TYPE(FooClass, bar); // == void
```

# License

MIT

# Author

Anthony Calandra


text:
package iot.challenge.application.modele;

import iot.challenge.application.modele.swagger.Message;
import org.jongo.marshall.jackson.oid.MongoId;

public class MessageReçut extends Message {

}


text:
//snippet-sourcedescription:[sqs_receivemessage.js demonstrates how to receive and delete a message from an Amazon SQS queue.]
//snippet-service:[sqs]
//snippet-keyword:[JavaScript]
//snippet-sourcesyntax:[javascript]
//snippet-keyword:[Code Sample]
//snippet-keyword:[Amazon Simple Queue Service]
//snippet-sourcetype:[full-example]
//snippet-sourcedate:[2018-06-02]
//snippet-sourceauthor:[AWS-JSDG]

// ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at
// https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/sqs-examples-send-receive-messages.html

// snippet-start:[sqs.JavaScript.messages.receiveMessage]
// Load the AWS SDK for Node.js
var AWS = require('aws-sdk');
// Set the region
AWS.config.update({region: 'REGION'});

// Create an SQS service object
var sqs = new AWS.SQS({apiVersion: '2012-11-05'});

var queueURL = "SQS_QUEUE_URL";

var params = {
 AttributeNames: [
    "SentTimestamp"
 ],
 MaxNumberOfMessages: 10,
 MessageAttributeNames: [
    "All"
 ],
 QueueUrl: queueURL,
 VisibilityTimeout: 20,
 WaitTimeSeconds: 0
};

sqs.receiveMessage(params, function(err, data) {
  if (err) {
    console.log("Receive Error", err);
  } else if (data.Messages) {
    var deleteParams = {
      QueueUrl: queueURL,
      ReceiptHandle: data.Messages[0].ReceiptHandle
    };
    sqs.deleteMessage(deleteParams, function(err, data) {
      if (err) {
        console.log("Delete Error", err);
      } else {
        console.log("Message Deleted", data);
      }
    });
  }
});
// snippet-end:[sqs.JavaScript.messages.receiveMessage]


text:
// Copyright 2010 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ------------------------------------------------------------------------

#include <stdarg.h>
#include <string.h>
#include "fmt/fmt.h"
#include "fmt/fmtdef.h"

namespace Fmt {

/*
 * format a string into the output buffer
 * designed for formats which themselves call fmt,
 * but ignore any width flags
 */
int
Formatter::fmtvprint(State *f, const char *fmt, va_list *args)
{
	va_list *va;
	int n;

	f->flags = 0;
	f->width = 0;
	f->prec = 0;
	va = f->args;
	f->args = args;
	n = dofmt(this, f, fmt);
	f->flags = 0;
	f->width = 0;
	f->prec = 0;
	f->args = va;
	if(n >= 0)
		return 0;
	return n;
}

int
fmtvprint(State *f, const char *fmt, va_list *args)
{
	return _stdfmt.fmtvprint(f, fmt, args);
}

}  /* end namespace Fmt */


text:
"""
Tests compressed data parsing functionality for all
of the parsers defined in parsers.py
"""

import os
from pathlib import Path
import zipfile

import pytest

from pandas import DataFrame
import pandas._testing as tm

@pytest.fixture(params=[True, False])
def buffer(request):
    return request.param

@pytest.fixture
def parser_and_data(all_parsers, csv1):
    parser = all_parsers

    with open(csv1, "rb") as f:
        data = f.read()
    expected = parser.read_csv(csv1)

    return parser, data, expected

@pytest.mark.parametrize("compression", ["zip", "infer", "zip2"])
def test_zip(parser_and_data, compression):
    parser, data, expected = parser_and_data

    with tm.ensure_clean("test_file.zip") as path:
        with zipfile.ZipFile(path, mode="w") as tmp:
            tmp.writestr("test_file", data)

        if compression == "zip2":
            with open(path, "rb") as f:
                result = parser.read_csv(f, compression="zip")
        else:
            result = parser.read_csv(path, compression=compression)

        tm.assert_frame_equal(result, expected)

@pytest.mark.parametrize("compression", ["zip", "infer"])
def test_zip_error_multiple_files(parser_and_data, compression):
    parser, data, expected = parser_and_data

    with tm.ensure_clean("combined_zip.zip") as path:
        inner_file_names = ["test_file", "second_file"]

        with zipfile.ZipFile(path, mode="w") as tmp:
            for file_name in inner_file_names:
                tmp.writestr(file_name, data)

        with pytest.raises(ValueError, match="Multiple files"):
            parser.read_csv(path, compression=compression)

def test_zip_error_no_files(parser_and_data):
    parser, _, _ = parser_and_data

    with tm.ensure_clean() as path:
        with zipfile.ZipFile(path, mode="w"):
            pass

        with pytest.raises(ValueError, match="Zero files"):
            parser.read_csv(path, compression="zip")

def test_zip_error_invalid_zip(parser_and_data):
    parser, _, _ = parser_and_data

    with tm.ensure_clean() as path:
        with open(path, "rb") as f:
            with pytest.raises(zipfile.BadZipfile, match="File is not a zip file"):
                parser.read_csv(f, compression="zip")

@pytest.mark.parametrize("filename", [None, "test.{ext}"])
def test_compression(parser_and_data, compression_only, buffer, filename):
    parser, data, expected = parser_and_data
    compress_type = compression_only

    ext = "gz" if compress_type == "gzip" else compress_type
    filename = filename if filename is None else filename.format(ext=ext)

    if filename and buffer:
        pytest.skip("Cannot deduce compression from buffer of compressed data.")

    with tm.ensure_clean(filename=filename) as path:
        tm.write_to_compressed(compress_type, path, data)
        compression = "infer" if filename else compress_type

        if buffer:
            with open(path, "rb") as f:
                result = parser.read_csv(f, compression=compression)
        else:
            result = parser.read_csv(path, compression=compression)

        tm.assert_frame_equal(result, expected)

@pytest.mark.parametrize("ext", [None, "gz", "bz2"])
def test_infer_compression(all_parsers, csv1, buffer, ext):
    # see gh-9770
    parser = all_parsers
    kwargs = {"index_col": 0, "parse_dates": True}

    expected = parser.read_csv(csv1, **kwargs)
    kwargs["compression"] = "infer"

    if buffer:
        with open(csv1) as f:
            result = parser.read_csv(f, **kwargs)
    else:
        ext = "." + ext if ext else ""
        result = parser.read_csv(csv1 + ext, **kwargs)

    tm.assert_frame_equal(result, expected)

def test_compression_utf_encoding(all_parsers, csv_dir_path, utf_value, encoding_fmt):
    # see gh-18071, gh-24130
    parser = all_parsers
    encoding = encoding_fmt.format(utf_value)
    path = os.path.join(csv_dir_path, f"utf{utf_value}_ex_small.zip")

    result = parser.read_csv(path, encoding=encoding, compression="zip", sep="\t")
    expected = DataFrame(
        {
            "Country": ["Venezuela", "Venezuela"],
            "Twitter": ["Hugo Chávez Frías", "Henrique Capriles R."],
        }
    )

    tm.assert_frame_equal(result, expected)

@pytest.mark.parametrize("invalid_compression", ["sfark", "bz3", "zipper"])
def test_invalid_compression(all_parsers, invalid_compression):
    parser = all_parsers
    compress_kwargs = {"compression": invalid_compression}

    msg = f"Unrecognized compression type: {invalid_compression}"

    with pytest.raises(ValueError, match=msg):
        parser.read_csv("test_file.zip", **compress_kwargs)

def test_ignore_compression_extension(all_parsers):
    parser = all_parsers
    df = DataFrame({"a": [0, 1]})
    with tm.ensure_clean("test.csv") as path_csv:
        with tm.ensure_clean("test.csv.zip") as path_zip:
            # make sure to create un-compressed file with zip extension
            df.to_csv(path_csv, index=False)
            Path(path_zip).write_text(Path(path_csv).read_text())

            tm.assert_frame_equal(parser.read_csv(path_zip, compression=None), df)