text:
namespace testing {

exceptions_internal::NoThrowTag nothrow_ctor;

exceptions_internal::StrongGuaranteeTagType strong_guarantee;

namespace exceptions_internal {

int countdown = -1;

ConstructorTracker* ConstructorTracker::current_tracker_instance_ = nullptr;

void MaybeThrow(absl::string_view msg, bool throw_bad_alloc) {
  if (countdown-- == 0) {
    if (throw_bad_alloc) throw TestBadAllocException(msg);
    throw TestException(msg);
  }
}

testing::AssertionResult FailureMessage(const TestException& e,
                                        int countdown) noexcept {
  return testing::AssertionFailure() << "Exception thrown from " << e.what();
}

std::string GetSpecString(TypeSpec spec) {
  std::string out;
  absl::string_view sep;
  const auto append = [&](absl::string_view s) {
    absl::StrAppend(&out, sep, s);
    sep = " | ";
  };
  if (static_cast<bool>(TypeSpec::kNoThrowCopy & spec)) {
    append("kNoThrowCopy");
  }
  if (static_cast<bool>(TypeSpec::kNoThrowMove & spec)) {
    append("kNoThrowMove");
  }
  if (static_cast<bool>(TypeSpec::kNoThrowNew & spec)) {
    append("kNoThrowNew");
  }
  return out;
}

std::string GetSpecString(AllocSpec spec) {
  return static_cast<bool>(AllocSpec::kNoThrowAllocate & spec)
             ? "kNoThrowAllocate"
             : "";
}

}  // namespace exceptions_internal

}  // namespace testing


text:
The HTTP storage plugin lets you query APIs over HTTP/REST. The plugin
expects JSON responses.

The HTTP plugin is new in Drill 1.18 and is an Alpha feature. It works well, and we
encourage you to use it and provide feedback. However, we reserve the right to change
the plugin based on that feedback.

## Configuration

To configure the plugin, create a new storage plugin, and add the following configuration options which apply to ALL connections defined in this plugin:

```json
{
  "type": "http",
  "cacheResults": true,
  "connections": {},
  "timeout": 0,
  "proxyHost": null,
  "proxyPort": 0,
  "proxyType": null,
  "proxyUsername": null,
  "proxyPassword": null,
  "enabled": true
}
```
The required options are:

* `type`:  This should be `http`
* `cacheResults`:  Enable caching of the HTTP responses.  Defaults to `false`
* `timeout`:  Sets the response timeout in seconds. Defaults to `0` which is no timeout.
* `connections`:  This field contains the details for individual connections. See the section *Configuring API Connections for Details*.

You can configure Drill to work behind a corporate proxy. Details are listed below.

### Configuring the API Connections

The HTTP Storage plugin allows you to configure multiple APIS which you can query directly from this plugin. To do so, first add a `connections` parameter to the configuration
. Next give the connection a name, which will be used in queries.  For instance `stockAPI` or `jira`.

The `connection` property can accept the following options.

#### URL

`url`: The base URL which Drill will query.

##### Parameters in the URL
Many APIs require parameters to be passed directly in the URL instead of as query arguments.  For example, github's API allows you to query an organization's repositories with the following
URL:  https://github.com/orgs/{org}/repos

As of Drill 1.20.0, you can simply set the URL in the connection using the curly braces.  If your API includes URL parameters you must include them in the `WHERE` clause in your
query, or specify a default value in the configuration.

As an example, the API above, you would have to query as shown below:

```sql
SELECT *
FROM api.github
WHERE org = 'apache'
```

This query would replace the `org`in the URL with the value from the `WHERE` clause, in this case `apache`.  You can specify a default value as follows:  `https://someapi.com/
{param1}/{param2=default}`.  In this case, the default would be used if and only if there isn't a parameter supplied in the query.

#### Limitations on URL Parameters
* Drill does not support boolean expressions of URL parameters in queries.  For instance, for the above example, if you were to include `WHERE org='apache' OR org='linux'`,
  these parameters could not be pushed down in the current state.
* All URL parameter clauses must be equality only.

### Passing Parameters in the Query
`requireTail`: Set to `true` if the query must contain an additional part of the service
URL as a table name, `false` if the URL needs no additional suffix other than that
provided by `WHERE` clause filters. (See below.)

If your service requires parameters, you have three choices. Suppose your connection is called
`sunrise`. First, can include them directly in your URL if the parameters a fixed for a given
service:

```json
url: "https://api.sunrise-sunset.org/json?lat=36.7201600&lng=-4.4203400&date=2019-10-02",
requireTail: false
```

Query your table like this:

```sql
SELECT * FROM api.sunrise;
```

Second, you can specify the base URL here and the full URL in your query. Use this form if the
parameters define a table-like concept (the set of data to return):

```json
url: "https://api.sunrise-sunset.org/json",
requireTail: true
```

SQL query:

```sql
SELECT * FROM api.sunrise.`?lat=36.7201600&lng=-4.4203400&date=2019-10-02`
```

If the URL requires a tail, specify it as if it were a table name. (See example
below.) Drill directly appends the "tail" to the base URL to create the final URL.

Third, you can use the `params` field below to specify the parameters as filters
if the parameters specify which data sets to return:

```json
url: "https://api.sunrise-sunset.org/json",
requireTail: false,
params: ["lat", "lng", "date"]
```

SQL query:

```sql
SELECT * FROM api.sunrise
WHERE `lat` = 36.7201600 AND `lng` = -4.4203400 AND `date` = '2019-10-02'
```

In this case, Drill appends the parameters to the URL, adding a question mark
to separate the two.

#### Method

`method`: The request method. Must be `GET` or `POST`. Other methods are not allowed and will default to `GET`.

`postBody`: Contains data, in the form of key value pairs, which are sent during a `POST` request.
The post body should be in the of a block of text with key/value pairs:

```json
postBody: "key1=value1
key2=value2"
```

`postBodyLocation`:  If the API uses the `POST` method, you can send parameters in several different ways:
* `query_string`:  Parameters from the query are pushed down to the query string.  Static parameters are pushed to the post body.
* `post_body`:  Both static and parameters from the query are pushed to the post body as key/value pairs
* `json_body`:  Both static and parameters from the query are pushed to the post body as json.

#### Headers

`headers`: Often APIs will require custom headers as part of the authentication. This field allows
you to define key/value pairs which are submitted with the http request. The format is:

```json
headers: {
   "key1": "Value1",
   "key2": "Value2"
   }
```

#### Query Parmeters as Filters

* `params`: Allows you to map SQL `WHERE` clause conditions to query parameters.

```json
url: "https://api.sunrise-sunset.org/json",
params: ["lat", "lng", "date"]
```

SQL query:

```sql
SELECT * FROM api.sunrise
WHERE `lat` = 36.7201600 AND `lng` = -4.4203400 AND `date` = '2019-10-02'
```

HTTP parameters are untyped; Drill converts any value you provide into a string.
Drill allows you to use any data type which can convert unambiguously to a string:
`BIT`, `INT`, `BIGINT`, `FLOAT4`, `FLOAT8`, `VARDECIMAL`, `VARCHAR`. The `BIT` type
is translated to `true` and `false`. Note that none of the date or interval types
are allowed: each of those requires formatting.

Note the need for back-tick quotes around the names;
`date` is a reserved word. Notice also that the date is a string because of
the formatting limitation mentioned above.

Only equality conditions can be translated to parameters. The above filters are
translated to:

```
lat=36.7201600&lng=-4.4203400&date=2019-10-02
```

If your query contains other conditions (`!=`, `<`, etc.) then those conditions are applied
in Drill after the REST service returns the data.

Only fields listed in the `params` config filed will become parameters, all other
expressions are handled within Drill as explained above.

At present, Drill requires the values to be literals (constants). Drill does not
currently allow expressions. That is, the following will not become an HTTP parameter:

```sql
WHERE `lat` = 36 + 0.7201600
```

Drill will add parameters to the URL in the order listed in the config. Use this
feature if the API is strict about parameter ordering.

At present Drill does not enforce that parameters are provided in the query: Drill
assumes parameters are optional.

### Data Path

REST responses often have structure beyond the data you want to query. For example:

```json
 "results":
 {
   "sunrise":"7:27:02 AM",
   "sunset":"5:05:55 PM",
   "solar_noon":"12:16:28 PM",
   "day_length":"9:38:53",
   "civil_twilight_begin":"6:58:14 AM",
   "civil_twilight_end":"5:34:43 PM",
   "nautical_twilight_begin":"6:25:47 AM",
   "nautical_twilight_end":"6:07:10 PM",
   "astronomical_twilight_begin":"5:54:14 AM",
   "astronomical_twilight_end":"6:38:43 PM"
 },
  "status":"OK"
}
```

Drill can handle JSON structures such as the above; you can use SQL to obtain the
results you want. However, the SQL will be simpler if we skip over the portions we
don't want and simply read the `results` fields as our SQL fields. We do that with
the `dataPath` configuration:

```json
dataPath: "results"
```

The `dataPath` can contain any number of fields, for example: `"response/content/data"`.
Drill will ignore all JSON content outside of the data path.

At present, there is no provision to check the `status` code in a response such
as that shown above. Drill assumes that the server will uses HTTP status codes to
indicate a bad request or other error.

#### Input Type
The REST plugin accepts three different types of input: `json`, `csv` and `xml`.  The default is `json`.  If you are using `XML` as a data type, there is an additional
configuration option called `xmlDataLevel` which reduces the level of unneeded nesting found in XML files.  You can find more information in the documentation for Drill's XML
format plugin.

#### JSON Configuration
[Read the documentation for configuring json options, including schema provisioning.](JSON_Options.md)

#### Authorization

`authType`: If your API requires authentication, specify the authentication
type. Defaults to `none`.
If the `authType` is set to `basic`, `username` and `password` must be set in the configuration as well.

`username`: The username for basic authentication.

`password`: The password for basic authentication.

##### Global Credentials
If you have an HTTP plugin with multiple endpoints that all use the same credentials, you can set the `authType` to `basic` and set global
credentials in the storage plugin configuration.

Simply add the following to the storage plugin configuration:
```json
 "credentialsProvider": {
    "credentialsProviderType": "PlainCredentialsProvider",
    "credentials": {
      "username": "user1",
      "password": "user1Pass"
    }
  }
```
Note that the `authType` still must be set to `basic` and that any endpoint credentials will override the global credentials.

#### Limiting Results
Some APIs support a query parameter which is used to limit the number of results returned by the API.  In this case you can set the `limitQueryParam` config variable to the query parameter name and Drill will automatically include this in your query.  For instance, if you have an API which supports a limit query parameter called `maxRecords` and you set the abovementioned config variable then execute the following query:

```sql
SELECT <fields>
FROM api.limitedApi
LIMIT 10
```
Drill will send the following request to your API:
```
https://<api>?maxRecords=10
```

### OAuth2.0
If the API which you are querying requires OAuth2.0 for authentication [read the documentation for configuring Drill to use OAuth2.0](OAuth.md).

### Pagination
If you want to use automatic pagination in Drill, [click here to read the documentation for pagination](Pagination.md).

#### errorOn400
When a user makes HTTP calls, the response code will be from 100-599.  400 series error codes can contain useful information and in some cases you would not want Drill to throw
errors on 400 series errors.  This option allows you to define Drill's behavior on 400 series error codes.  When set to `true`, Drill will throw an exception and halt execution
on 400 series errors, `false` will return an empty result set (with implicit fields populated).

#### verifySSLCert
Default is `true`, but when set to false, Drill will trust all SSL certificates.  Useful for debugging or on internal corporate networks using self-signed certificates or
private certificate authorities.

## Usage

This plugin is different from other plugins in that it the table component of the `FROM` clause
is different. In normal Drill queries, the `FROM` clause is constructed as follows:

```sql
FROM <storage plugin>.<schema>.<table>
```
For example, you might have:

```sql
FROM dfs.test.`somefile.csv`

-- or

FROM mongo.stats.sales_data
```

The HTTP/REST plugin the `FROM` clause enables you to pass arguments to your REST call if you
set the `requireTail` property to `true`. The structure is:

```sql
FROM <plugin>.<connection>.<arguments>
--Actual example:
FROM http.sunrise.`/json?lat=36.7201600&lng=-4.4203400&date=today`
```

Or, as explained above, you can have the URL act like a table and pass parameters
using a `WHERE` clause "filter" conditions.

## Proxy Setup

Some users access HTTP services from behind a proxy firewall. Drill provides three ways specify proxy
configuration.

### Proxy Environment Variables

Drill recognizes the usual Linux proxy environment variables:

* `http_proxy`, `HTTP_PROXY`
* `https_proxy`, `HTTP_PROXY`
* `all_proxy`, `ALL_PROXY`

This technique works well if your system is already configured to
handle proxies.

### Boot Configuration

You can also specify proxy configuration in the `drill-override.conf` file.
See `drill-override-example.conf` for a template. Use the boot configuration
is an attribute of your network environment. Doing so will ensure every
Drillbit and every HTTP/HTTPS request uses the same proxy configuration.

First, you can use the same form of URL you would use with the environment
variables:

```
drill.exec.net_proxy.http_url: "http://foo.com/1234"
```

There is one setting for HTTP, another for HTTPS.

Alternatively, you can specify each field separately:

```
drill.exec.net_proxy.http: {
      type: "none", # none, http, socks. Blank same as none.
      host: "",
      port: 80,
      user_name: "",
      password: ""
    },
```

The valid proxy types are `none`, `http` and `socks`. Blank is the same
as `none`.

Again, there is a parallel section for HTTPS.

### In the HTTP Storage Plugin Config

The final way to configure proxy is in the HTTP storage plugin itself. The proxy
applies to all connections defined in that plugin. Use this approach if the proxy
applies only to some external services, or if each service has a different proxy
(defined by creating a separate plugin config for each service.)

```json
      proxy_type: "direct",
      proxy_host: "",
      proxy_port: 80,
      proxy_user_name: "",
      proxy_password: ""
```

The valid proxy types are `direct`, `http` or `socks`. Blank is the same
as `direct`.

## Examples

### Example 1: Reference Data, A Sunrise/Sunset API

The API sunrise-sunset.org returns data in the following format:

 ```json
 "results":
 {
   "sunrise":"7:27:02 AM",
   "sunset":"5:05:55 PM",
   "solar_noon":"12:16:28 PM",
   "day_length":"9:38:53",
   "civil_twilight_begin":"6:58:14 AM",
   "civil_twilight_end":"5:34:43 PM",
   "nautical_twilight_begin":"6:25:47 AM",
   "nautical_twilight_end":"6:07:10 PM",
   "astronomical_twilight_begin":"5:54:14 AM",
   "astronomical_twilight_end":"6:38:43 PM"
 },
  "status":"OK"
}
```

To query this API, set the configuration as follows:

```json
{
  "type": "http",
  "cacheResults": false,
  "enabled": true,
  "timeout": 5,
  "connections": {
    "sunrise": {
      "url": "https://api.sunrise-sunset.org/json",
      "requireTail": true,
      "method": "GET",
      "headers": null,
      "authType": "none",
      "userName": null,
      "password": null,
      "postBody": null,
      "inputType": "json",
       "errorOn400": true
    }
  }

```

Then, to execute a query:

```sql
SELECT api_results.results.sunrise AS sunrise,
       api_results.results.sunset AS sunset
FROM   http.sunrise.`?lat=36.7201600&lng=-4.4203400&date=today` AS api_results;
```
Which yields the following results:
```
+------------+------------+
|  sunrise   |   sunset   |
+------------+------------+
| 7:17:46 AM | 5:01:33 PM |
+------------+------------+
1 row selected (0.632 seconds)
```

#### Using Parameters

We can improvide the above configuration to use `WHERE` clause filters and
a `dataPath` to skip over the unwanted parts of the message
body. Set the configuration as follows:

```json
{
  "type": "http",
  "cacheResults": false,
  "enabled": true,
  "timeout": 5,
  "connections": {
    "sunrise": {
      "url": "https://api.sunrise-sunset.org/json",
      "requireTail": false,
      "method": "GET",
      "dataPath": "results",
      "headers": null,
      "params": [ "lat", "lng", "date" ],
      "authType": "none",
      "userName": null,
      "password": null,
      "postBody": null,
       "errorOn400": true
    }
  }

```
Then, to execute a query:

```sql
SELECT sunrise, sunset
FROM   http.sunrise
WHERE  `lat` = 36.7201600 AND `lng` = -4.4203400 AND `date` = 'today'
```

Which yields the same results as before.

### Example 2: JIRA

JIRA Cloud has a REST API which is
[documented here](https://developer.atlassian.com/cloud/jira/platform/rest/v3/?utm_source=%2Fcloud%2Fjira%2Fplatform%2Frest%2F&utm_medium=302).

To connect Drill to JIRA Cloud, use the following configuration:

```json
{
  "type": "http",
  "cacheResults": false,
  "timeout": 5,
  "connections": {
    "jira": {
      "url": "https://<project>.atlassian.net/rest/api/3/",
      "method": "GET",
      "dataPath": "issues",
      "headers": {
        "Accept": "application/json"
      },
      "authType": "basic",
      "userName": "<username>",
      "password": "<API Key>",
      "postBody": null
    }
  },
  "enabled": true
}
```

Once you've configured Drill to query the API, you can now easily access any of your data in JIRA.
The JIRA API returns highly nested data, however with a little preparation, it
is pretty straightforward to transform it into a more useful table. For instance, the
query below:

```sql
SELECT key,
       t.fields.issueType.name AS issueType,
       SUBSTR(t.fields.created, 1, 10) AS created,
       SUBSTR(t.fields.updated, 1, 10) AS updated,
       t.fields.assignee.displayName as assignee,
       t.fields.creator.displayName as creator,
       t.fields.summary AS summary,
       t.fields.status.name AS currentStatus,
       t.fields.priority.name AS priority,
       t.fields.labels AS labels,
       t.fields.subtasks AS subtasks
FROM http.jira.`search?jql=project%20%3D%20<project>&&maxResults=100 AS t`
```

The query below counts the number of issues by priority:

```sql
SELECT t.fields.priority.name AS priority,
       COUNT(*) AS issue_count
FROM http.jira.`search?jql=project%20%3D%20<project>&&maxResults=100` AS t
GROUP BY priority
ORDER BY issue_count DESC
```

<img src="images/issue_count.png"  alt="Issue Count by Priority"/>

## Limitations

1. The plugin is supposed to follow redirects, however if you are using authentication,
   you may encounter errors or empty responses if you are counting on the endpoint for
   redirection.

2. At this time, the plugin does not support any authentication other than basic authentication.

3. This plugin does not implement join filter pushdowns (only constant plushdowns are
   supported). Join pushdown has the potential to improve performance if you use the HTTP service
   joined to another table.

~~4. This plugin only reads JSON and CSV responses.~~

~~5. `POST` bodies can only be in the format of key/value pairs. Some APIs accept
    JSON based `POST` bodies but this is not currently supported.~~

6. When using `dataPath`, the returned message should a single JSON object. The field
   pointed to by the `dataPath` should contain a single JSON object or an array of objects.

7. When not using `dataPath`, the response should be a single JSON object, an array of
   JSON objects, or a series of line-delimited JSON objects (the so-called
   [jsonlines](http://jsonlines.org/) format.)

8. Parameters are considered optional; no error will be given if a query omits
   parameters. An enhancement would be to mark parameters as required: all are required
   or just some. If parameters are required, but omitted, the report service will
   likely return an error.

## Troubleshooting

If anything goes wrong, Drill will provide a detailed error message, including URL:

```
DATA_READ ERROR: Failed to read the HTTP response body

Error message: Read timed out
Connection: sunrise
Plugin: api
URL: https://api.sunrise-sunset.org/json?lat=36.7201600&lng=-4.4203400&date=today
Fragment: 0:0
```

If using a "tail" in the query, verify that the tail is quoted using back-ticks
as shown in the examples.

Check that the URL is correct. If not, check the plugin configuration properties
described above to find out why the pieces were assembled as you want.

If the query works but delivers unexpected results, check the Drill log file.
Drill logs a message like the following at the info level when opening the HTTP connection:

```
Connection: sunrise, Method: GET,
  URL: https://api.sunrise-sunset.org/json?lat=36.7201600&lng=-4.4203400&date=today
```

If the query runs, but produces odd results, try a simple `SELECT *` query. This may reveal
if there is unexpected message context in addition to the data. Use the `dataPath` property
to ignore the extra content.

## Implicit Fields
The HTTP plugin includes four implicit fields which can be used for debugging.  These fields do not appear in star queries.  They are:

* `_response_code`: The response code from the HTTP request.  This field is an `INT`.
* `_response_message`:  The response message.
* `_response_protocol`:  The response protocol.
* `_response_url`:  The actual URL sent to the API.

## Joining Data
There are some situations where a user might want to join data with an API result and the pushdowns prevent that from happening.  The main situation where this happens is when
an API has parameters which are part of the URL AND these parameters are dynamically populated via a join.

In this case, there are two functions `http_get_url` and `http_get` which you can use to faciliate these joins.

* `http_request('<storage_plugin_name>', <params>)`:  This function accepts a storage plugin as input and an optional list of parameters to include in a URL.
* `http_get(<url>, <params>)`:  This function works in the same way except that it does not pull any configuration information from existing storage plugins.  The input url for
  the `http_get` function must be a valid URL.

### Example Queries
Let's say that you have a storage plugin called `github` with an endpoint called `repos` which points to the url: https://github.com/orgs/{org}/repos.  It is easy enough to
write a query like this:

```sql
SELECT *
FROM github.repos
WHERE org='apache'
```
However, if you had a file with organizations and wanted to join this with the API, the query would fail.  Using the functions listed above you could get this data as follows:

```sql
SELECT http_request('github.repos', `org`)
FROM dfs.`some_data.csvh`
```
or
```sql
SELECT http_get('https://github.com/orgs/{org}/repos', `org`)
FROM dfs.`some_data.csvh`
```

** WARNING:  This functionality will execute an HTTP Request FOR EVERY ROW IN YOUR DATA.  Use with caution. **

redpajama_set_name: RedPajamaGithub


text:
package io.vertigo.rules;

import io.vertigo.dynamo.domain.model.DtObject;
import io.vertigo.dynamo.domain.stereotype.Field;
import io.vertigo.dynamo.domain.util.DtObjectUtil;
import io.vertigo.lang.Generated;

/**
 * This class is automatically generated.
 * DO NOT EDIT THIS FILE DIRECTLY.
 */
@Generated
public final class RuleConditionCriteria implements DtObject {
	private static final long serialVersionUID = 1L;

	private String field;
	private String value;

	/**
	 * Champ : DATA.
	 * Récupère la valeur de la propriété 'Field'.
	 * @return String field
	 */
	@Field(domain = "DO_RULES_FIELD", label = "Field")
	public String getField() {
		return field;
	}

	/**
	 * Champ : DATA.
	 * Définit la valeur de la propriété 'Field'.
	 * @param field String
	 */
	public void setField(final String field) {
		this.field = field;
	}

	/**
	 * Champ : DATA.
	 * Récupère la valeur de la propriété 'Value'.
	 * @return String value
	 */
	@Field(domain = "DO_RULES_EXPRESSION", label = "Value")
	public String getValue() {
		return value;
	}

	/**
	 * Champ : DATA.
	 * Définit la valeur de la propriété 'Value'.
	 * @param value String
	 */
	public void setValue(final String value) {
		this.value = value;
	}

	/** {@inheritDoc} */
	@Override
	public String toString() {
		return DtObjectUtil.toString(this);
	}
}


text:
using boost::asio::ip::tcp;

namespace third_party_lib {

// Simulation of a third party library that wants to perform read and write
// operations directly on a socket. It needs to be polled to determine whether
// it requires a read or write operation, and notified when the socket is ready
// for reading or writing.
class session
{
public:
  session(tcp::socket& socket)
    : socket_(socket)
  {
  }

  // Returns true if the third party library wants to be notified when the
  // socket is ready for reading.
  bool want_read() const
  {
    return state_ == reading;
  }

  // Notify that third party library that it should perform its read operation.
  void do_read(boost::system::error_code& ec)
  {
    if (std::size_t len = socket_.read_some(boost::asio::buffer(data_), ec))
    {
      write_buffer_ = boost::asio::buffer(data_, len);
      state_ = writing;
    }
  }

  // Returns true if the third party library wants to be notified when the
  // socket is ready for writing.
  bool want_write() const
  {
    return state_ == writing;
  }

  // Notify that third party library that it should perform its write operation.
  void do_write(boost::system::error_code& ec)
  {
    if (std::size_t len = socket_.write_some(
          boost::asio::buffer(write_buffer_), ec))
    {
      write_buffer_ = write_buffer_ + len;
      state_ = boost::asio::buffer_size(write_buffer_) > 0 ? writing : reading;
    }
  }

private:
  tcp::socket& socket_;
  enum { reading, writing } state_ = reading;
  std::array<char, 128> data_;
  boost::asio::const_buffer write_buffer_;
};

} // namespace third_party_lib

// The glue between asio's sockets and the third party library.
class connection
  : public std::enable_shared_from_this<connection>
{
public:
  connection(tcp::socket socket)
    : socket_(std::move(socket))
  {
  }

  void start()
  {
    // Put the socket into non-blocking mode.
    socket_.non_blocking(true);

    do_operations();
  }

private:
  void do_operations()
  {
    auto self(shared_from_this());

    // Start a read operation if the third party library wants one.
    if (session_impl_.want_read() && !read_in_progress_)
    {
      read_in_progress_ = true;
      socket_.async_wait(tcp::socket::wait_read,
          [this, self](boost::system::error_code ec)
          {
            read_in_progress_ = false;

            // Notify third party library that it can perform a read.
            if (!ec)
              session_impl_.do_read(ec);

            // The third party library successfully performed a read on the
            // socket. Start new read or write operations based on what it now
            // wants.
            if (!ec || ec == boost::asio::error::would_block)
              do_operations();

            // Otherwise, an error occurred. Closing the socket cancels any
            // outstanding asynchronous read or write operations. The
            // connection object will be destroyed automatically once those
            // outstanding operations complete.
            else
              socket_.close();
          });
    }

    // Start a write operation if the third party library wants one.
    if (session_impl_.want_write() && !write_in_progress_)
    {
      write_in_progress_ = true;
      socket_.async_wait(tcp::socket::wait_write,
          [this, self](boost::system::error_code ec)
          {
            write_in_progress_ = false;

            // Notify third party library that it can perform a write.
            if (!ec)
              session_impl_.do_write(ec);

            // The third party library successfully performed a write on the
            // socket. Start new read or write operations based on what it now
            // wants.
            if (!ec || ec == boost::asio::error::would_block)
              do_operations();

            // Otherwise, an error occurred. Closing the socket cancels any
            // outstanding asynchronous read or write operations. The
            // connection object will be destroyed automatically once those
            // outstanding operations complete.
            else
              socket_.close();
          });
    }
  }

private:
  tcp::socket socket_;
  third_party_lib::session session_impl_{socket_};
  bool read_in_progress_ = false;
  bool write_in_progress_ = false;
};

class server
{
public:
  server(boost::asio::io_context& io_context, unsigned short port)
    : acceptor_(io_context, {tcp::v4(), port})
  {
    do_accept();
  }

private:
  void do_accept()
  {
    acceptor_.async_accept(
        [this](boost::system::error_code ec, tcp::socket socket)
        {
          if (!ec)
          {
            std::make_shared<connection>(std::move(socket))->start();
          }

          do_accept();
        });
  }

  tcp::acceptor acceptor_;
};

int main(int argc, char* argv[])
{
  try
  {
    if (argc != 2)
    {
      std::cerr << "Usage: third_party_lib <port>\n";
      return 1;
    }

    boost::asio::io_context io_context;

    server s(io_context, std::atoi(argv[1]));

    io_context.run();
  }
  catch (std::exception& e)
  {
    std::cerr << "Exception: " << e.what() << "\n";
  }

  return 0;
}


text:
title: RFP Bid Evaluation
subtitle: Excel Template
layout: default
modal-id: 1
date: 2014-07-18
img: bid-evaluation-lg-min.png
thumbnail: tn_bid-evaluation-min.png
alt: rfp bid evaluation
project-date: September 2016
author: Purchasing Toolpak
category: Strategic Sourcing
description: Procurement uses the RFP bid evaluation template for evaluating multiple parts. Enter information by item and supplier to calculate total cost.

---


text:
import { Meteor } from 'meteor/meteor';
import Roles from '/imports/shared/roles';
import '../imports/api/achievs.js';

import '/imports/collections';

Meteor.startup(() => {

  // code to run on server at startup
});


text:
// This file was generated using Parlex's cpp_generator

#ifndef INCLUDED_UNIT_MULTIPLICATION_HPP
#define INCLUDED_UNIT_MULTIPLICATION_HPP

#include <optional>
#include <variant>
#include <vector>

#include "erased.hpp"

#include "parlex/detail/abstract_syntax_tree.hpp"
#include "parlex/detail/builtins.hpp"
#include "parlex/detail/document.hpp"

#include "plange_grammar.hpp"

namespace plc {

struct DIMENSION;

struct UNIT_MULTIPLICATION {
	erased<DIMENSION> field_1;

	parlex::detail::document::text<literal_0x2A_t> dontCare1;

	erased<DIMENSION> field_2;

	explicit UNIT_MULTIPLICATION(
		erased<DIMENSION> && field_1, parlex::detail::document::text<literal_0x2A_t> && dontCare1, erased<DIMENSION> && field_2) : field_1(std::move(field_1)), dontCare1(std::move(dontCare1)), field_2(std::move(field_2)) {}

	UNIT_MULTIPLICATION(UNIT_MULTIPLICATION const & other) = default;
	UNIT_MULTIPLICATION(UNIT_MULTIPLICATION && move) = default;

	static UNIT_MULTIPLICATION build(parlex::detail::ast_node const & n);
	static parlex::detail::state_machine const & state_machine();

};

} // namespace plc

#endif //INCLUDED_UNIT_MULTIPLICATION_HPP


text:
import clientFnTestRunTracker from '../../../../lib/client-functions/test-run-tracker';

fixture `In Promise.catch()`;

test('test', async () => {
    return Promise.resolve()
        .then(() => {
            throw new Error('yo')
        })
        .catch(() => clientFnTestRunTracker.getContextTestRunId());
});


text:
What else do you need to learn about deployment?

   {% include "choices/buttons/servers.html" %}

   {% include "choices/buttons/databases.html" %}

   {% include "choices/buttons/platform-as-a-service.html" %}


text:
Making the right choice for clouds

Choose a collaboration deployment model that best fits your strategy and future needs. Read the "To the cloud or not?" guide to learn about important considerations

    Download Now


text:
package speech

import (
	speechpb "google.golang.org/genproto/googleapis/cloud/speech/v1"
	longrunningpb "google.golang.org/genproto/googleapis/longrunning"
)

import (
	"flag"
	"fmt"
	"io"
	"log"
	"net"
	"os"
	"strings"
	"testing"

	"github.com/golang/protobuf/proto"
	"github.com/golang/protobuf/ptypes"
	"golang.org/x/net/context"
	"google.golang.org/api/option"
	status "google.golang.org/genproto/googleapis/rpc/status"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/metadata"
)

var _ = io.EOF
var _ = ptypes.MarshalAny
var _ status.Status

type mockSpeechServer struct {
	// Embed for forward compatibility.
	// Tests will keep working if more methods are added
	// in the future.
	speechpb.SpeechServer

	reqs []proto.Message

	// If set, all calls return this error.
	err error

	// responses to return if err == nil
	resps []proto.Message
}

func (s *mockSpeechServer) Recognize(ctx context.Context, req *speechpb.RecognizeRequest) (*speechpb.RecognizeResponse, error) {
	md, _ := metadata.FromIncomingContext(ctx)
	if xg := md["x-goog-api-client"]; len(xg) == 0 || !strings.Contains(xg[0], "gl-go/") {
		return nil, fmt.Errorf("x-goog-api-client = %v, expected gl-go key", xg)
	}
	s.reqs = append(s.reqs, req)
	if s.err != nil {
		return nil, s.err
	}
	return s.resps[0].(*speechpb.RecognizeResponse), nil
}

func (s *mockSpeechServer) LongRunningRecognize(ctx context.Context, req *speechpb.LongRunningRecognizeRequest) (*longrunningpb.Operation, error) {
	md, _ := metadata.FromIncomingContext(ctx)
	if xg := md["x-goog-api-client"]; len(xg) == 0 || !strings.Contains(xg[0], "gl-go/") {
		return nil, fmt.Errorf("x-goog-api-client = %v, expected gl-go key", xg)
	}
	s.reqs = append(s.reqs, req)
	if s.err != nil {
		return nil, s.err
	}
	return s.resps[0].(*longrunningpb.Operation), nil
}

func (s *mockSpeechServer) StreamingRecognize(stream speechpb.Speech_StreamingRecognizeServer) error {
	md, _ := metadata.FromIncomingContext(stream.Context())
	if xg := md["x-goog-api-client"]; len(xg) == 0 || !strings.Contains(xg[0], "gl-go/") {
		return fmt.Errorf("x-goog-api-client = %v, expected gl-go key", xg)
	}
	for {
		if req, err := stream.Recv(); err == io.EOF {
			break
		} else if err != nil {
			return err
		} else {
			s.reqs = append(s.reqs, req)
		}
	}
	if s.err != nil {
		return s.err
	}
	for _, v := range s.resps {
		if err := stream.Send(v.(*speechpb.StreamingRecognizeResponse)); err != nil {
			return err
		}
	}
	return nil
}

// clientOpt is the option tests should use to connect to the test server.
// It is initialized by TestMain.
var clientOpt option.ClientOption

var (
	mockSpeech mockSpeechServer
)

func TestMain(m *testing.M) {
	flag.Parse()

	serv := grpc.NewServer()
	speechpb.RegisterSpeechServer(serv, &mockSpeech)

	lis, err := net.Listen("tcp", "localhost:0")
	if err != nil {
		log.Fatal(err)
	}
	go serv.Serve(lis)

	conn, err := grpc.Dial(lis.Addr().String(), grpc.WithInsecure())
	if err != nil {
		log.Fatal(err)
	}
	clientOpt = option.WithGRPCConn(conn)

	os.Exit(m.Run())
}

func TestSpeechRecognize(t *testing.T) {
	var expectedResponse *speechpb.RecognizeResponse = &speechpb.RecognizeResponse{}

	mockSpeech.err = nil
	mockSpeech.reqs = nil

	mockSpeech.resps = append(mockSpeech.resps[:0], expectedResponse)

	var encoding speechpb.RecognitionConfig_AudioEncoding = speechpb.RecognitionConfig_FLAC
	var sampleRateHertz int32 = 44100
	var languageCode string = "en-US"
	var config = &speechpb.RecognitionConfig{
		Encoding:        encoding,
		SampleRateHertz: sampleRateHertz,
		LanguageCode:    languageCode,
	}
	var uri string = "gs://bucket_name/file_name.flac"
	var audio = &speechpb.RecognitionAudio{
		AudioSource: &speechpb.RecognitionAudio_Uri{
			Uri: uri,
		},
	}
	var request = &speechpb.RecognizeRequest{
		Config: config,
		Audio:  audio,
	}

	c, err := NewClient(context.Background(), clientOpt)
	if err != nil {
		t.Fatal(err)
	}

	resp, err := c.Recognize(context.Background(), request)

	if err != nil {
		t.Fatal(err)
	}

	if want, got := request, mockSpeech.reqs[0]; !proto.Equal(want, got) {
		t.Errorf("wrong request %q, want %q", got, want)
	}

	if want, got := expectedResponse, resp; !proto.Equal(want, got) {
		t.Errorf("wrong response %q, want %q)", got, want)
	}
}

func TestSpeechRecognizeError(t *testing.T) {
	errCode := codes.PermissionDenied
	mockSpeech.err = grpc.Errorf(errCode, "test error")

	var encoding speechpb.RecognitionConfig_AudioEncoding = speechpb.RecognitionConfig_FLAC
	var sampleRateHertz int32 = 44100
	var languageCode string = "en-US"
	var config = &speechpb.RecognitionConfig{
		Encoding:        encoding,
		SampleRateHertz: sampleRateHertz,
		LanguageCode:    languageCode,
	}
	var uri string = "gs://bucket_name/file_name.flac"
	var audio = &speechpb.RecognitionAudio{
		AudioSource: &speechpb.RecognitionAudio_Uri{
			Uri: uri,
		},
	}
	var request = &speechpb.RecognizeRequest{
		Config: config,
		Audio:  audio,
	}

	c, err := NewClient(context.Background(), clientOpt)
	if err != nil {
		t.Fatal(err)
	}

	resp, err := c.Recognize(context.Background(), request)

	if c := grpc.Code(err); c != errCode {
		t.Errorf("got error code %q, want %q", c, errCode)
	}
	_ = resp
}
func TestSpeechLongRunningRecognize(t *testing.T) {
	var expectedResponse *speechpb.LongRunningRecognizeResponse = &speechpb.LongRunningRecognizeResponse{}

	mockSpeech.err = nil
	mockSpeech.reqs = nil

	any, err := ptypes.MarshalAny(expectedResponse)
	if err != nil {
		t.Fatal(err)
	}
	mockSpeech.resps = append(mockSpeech.resps[:0], &longrunningpb.Operation{
		Name:   "longrunning-test",
		Done:   true,
		Result: &longrunningpb.Operation_Response{Response: any},
	})

	var encoding speechpb.RecognitionConfig_AudioEncoding = speechpb.RecognitionConfig_FLAC
	var sampleRateHertz int32 = 44100
	var languageCode string = "en-US"
	var config = &speechpb.RecognitionConfig{
		Encoding:        encoding,
		SampleRateHertz: sampleRateHertz,
		LanguageCode:    languageCode,
	}
	var uri string = "gs://bucket_name/file_name.flac"
	var audio = &speechpb.RecognitionAudio{
		AudioSource: &speechpb.RecognitionAudio_Uri{
			Uri: uri,
		},
	}
	var request = &speechpb.LongRunningRecognizeRequest{
		Config: config,
		Audio:  audio,
	}

	c, err := NewClient(context.Background(), clientOpt)
	if err != nil {
		t.Fatal(err)
	}

	respLRO, err := c.LongRunningRecognize(context.Background(), request)
	if err != nil {
		t.Fatal(err)
	}
	resp, err := respLRO.Wait(context.Background())

	if err != nil {
		t.Fatal(err)
	}

	if want, got := request, mockSpeech.reqs[0]; !proto.Equal(want, got) {
		t.Errorf("wrong request %q, want %q", got, want)
	}

	if want, got := expectedResponse, resp; !proto.Equal(want, got) {
		t.Errorf("wrong response %q, want %q)", got, want)
	}
}

func TestSpeechLongRunningRecognizeError(t *testing.T) {
	errCode := codes.PermissionDenied
	mockSpeech.err = nil
	mockSpeech.resps = append(mockSpeech.resps[:0], &longrunningpb.Operation{
		Name: "longrunning-test",
		Done: true,
		Result: &longrunningpb.Operation_Error{
			Error: &status.Status{
				Code:    int32(errCode),
				Message: "test error",
			},
		},
	})

	var encoding speechpb.RecognitionConfig_AudioEncoding = speechpb.RecognitionConfig_FLAC
	var sampleRateHertz int32 = 44100
	var languageCode string = "en-US"
	var config = &speechpb.RecognitionConfig{
		Encoding:        encoding,
		SampleRateHertz: sampleRateHertz,
		LanguageCode:    languageCode,
	}
	var uri string = "gs://bucket_name/file_name.flac"
	var audio = &speechpb.RecognitionAudio{
		AudioSource: &speechpb.RecognitionAudio_Uri{
			Uri: uri,
		},
	}
	var request = &speechpb.LongRunningRecognizeRequest{
		Config: config,
		Audio:  audio,
	}

	c, err := NewClient(context.Background(), clientOpt)
	if err != nil {
		t.Fatal(err)
	}

	respLRO, err := c.LongRunningRecognize(context.Background(), request)
	if err != nil {
		t.Fatal(err)
	}
	resp, err := respLRO.Wait(context.Background())

	if c := grpc.Code(err); c != errCode {
		t.Errorf("got error code %q, want %q", c, errCode)
	}
	_ = resp
}
func TestSpeechStreamingRecognize(t *testing.T) {
	var expectedResponse *speechpb.StreamingRecognizeResponse = &speechpb.StreamingRecognizeResponse{}

	mockSpeech.err = nil
	mockSpeech.reqs = nil

	mockSpeech.resps = append(mockSpeech.resps[:0], expectedResponse)

	var request *speechpb.StreamingRecognizeRequest = &speechpb.StreamingRecognizeRequest{}

	c, err := NewClient(context.Background(), clientOpt)
	if err != nil {
		t.Fatal(err)
	}

	stream, err := c.StreamingRecognize(context.Background())
	if err != nil {
		t.Fatal(err)
	}
	if err := stream.Send(request); err != nil {
		t.Fatal(err)
	}
	if err := stream.CloseSend(); err != nil {
		t.Fatal(err)
	}
	resp, err := stream.Recv()

	if err != nil {
		t.Fatal(err)
	}

	if want, got := request, mockSpeech.reqs[0]; !proto.Equal(want, got) {
		t.Errorf("wrong request %q, want %q", got, want)
	}

	if want, got := expectedResponse, resp; !proto.Equal(want, got) {
		t.Errorf("wrong response %q, want %q)", got, want)
	}
}

func TestSpeechStreamingRecognizeError(t *testing.T) {
	errCode := codes.PermissionDenied
	mockSpeech.err = grpc.Errorf(errCode, "test error")

	var request *speechpb.StreamingRecognizeRequest = &speechpb.StreamingRecognizeRequest{}

	c, err := NewClient(context.Background(), clientOpt)
	if err != nil {
		t.Fatal(err)
	}

	stream, err := c.StreamingRecognize(context.Background())
	if err != nil {
		t.Fatal(err)
	}
	if err := stream.Send(request); err != nil {
		t.Fatal(err)
	}
	if err := stream.CloseSend(); err != nil {
		t.Fatal(err)
	}
	resp, err := stream.Recv()

	if c := grpc.Code(err); c != errCode {
		t.Errorf("got error code %q, want %q", c, errCode)
	}
	_ = resp
}


text:
import Vue from 'vue';
import autoMergeFailedComponent from '~/vue_merge_request_widget/components/states/mr_widget_auto_merge_failed.vue';
import eventHub from '~/vue_merge_request_widget/event_hub';
import mountComponent from 'spec/helpers/vue_mount_component_helper';

describe('MRWidgetAutoMergeFailed', () => {
  let vm;
  const mergeError = 'This is the merge error';

  beforeEach(() => {
    const Component = Vue.extend(autoMergeFailedComponent);
    vm = mountComponent(Component, {
      mr: { mergeError },
    });
  });

  afterEach(() => {
    vm.$destroy();
  });

  it('renders failed message', () => {
    expect(vm.$el.textContent).toContain('This merge request failed to be merged automatically');
  });

  it('renders merge error provided', () => {
    expect(vm.$el.innerText).toContain(mergeError);
  });

  it('render refresh button', () => {
    expect(vm.$el.querySelector('button').textContent.trim()).toEqual('Refresh');
  });

  it('emits event and shows loading icon when button is clicked', (done) => {
    spyOn(eventHub, '$emit');
    vm.$el.querySelector('button').click();

    expect(eventHub.$emit.calls.argsFor(0)[0]).toEqual('MRWidgetUpdateRequested');

    Vue.nextTick(() => {
      expect(vm.$el.querySelector('button').getAttribute('disabled')).toEqual('disabled');
      expect(
        vm.$el.querySelector('button i').classList,
      ).toContain('fa-spinner');
      done();
    });
  });
});


text:
var Aria = require('ariatemplates/Aria');

var TemplateTestCase = require('ariatemplates/jsunit/TemplateTestCase');

require('./ErrorListCustomTemplate.tpl');

module.exports = Aria.classDefinition({
    $classpath: 'test.aria.widgets.errorlist.displayOptions.ErrorListDisplayOptionsTestCase',
    $extends: TemplateTestCase,

    $constructor: function () {
        this.$TemplateTestCase.$constructor.apply(this, arguments);

        var text = 'This is custom text passed to ErrorList widget instance\'s template through the displayOptions property';
        this._text = text;

        var elementId = 'error_list_template_content';
        this._elementId = elementId;

        this.setTestEnv({
            template: 'test.aria.widgets.errorlist.displayOptions.Tpl',
            data: {
                text: text,
                elementId: elementId
            }
        });
    },

    $prototype: {
        runTemplateTest: function () {
            var contentElement = Aria.$window.document.getElementById(this._elementId);

            this.assertTrue(contentElement != null, 'Custom id should have been passed and output to build the element.');

            this.end();
        }
    }
});


text:
package com.taobao.tddl.optimizer.core.expression.bean;

import com.taobao.tddl.optimizer.core.CanVisit;
import com.taobao.tddl.optimizer.core.PlanVisitor;

public class NullValue implements Comparable, CanVisit {

    private static NullValue instance = new NullValue();
    private String           str      = "null";

    public static NullValue getNullValue() {
        return instance;
    }

    private NullValue(){
    }

    public int compareTo(Object o) {
        if (o == this) {
            return 0;
        }
        if (o instanceof NullValue) {
            return 0;
        }
        return -1;

    }

    public String toString() {
        return str;
    }

    public void accept(PlanVisitor visitor) {
        visitor.visit(this);
    }

}


text:
from pathlib import Path
from mythril.solidity.soliditycontract import SolidityContract

# Recompiles all the to be tested contracts
root = Path(__file__).parent
input = root / "input_contracts"
output = root / "inputs"

for contract in input.iterdir():
    sol = SolidityContract(str(contract))
    code = sol.code

    output_file = output / "{}.o".format(contract.name)
    output_file.write_text(code)


text:
/**
 * Created by tomihei on 17/02/11.
 */

import * as AppType from '../../constants/App';

const initialState = {
    loginInfoRequest: false,
    loginInfoResult: false,
    nowLogin: false,
    token: "",
    error:false,
    message: {
      user_email: "",
      user_password: "",
      user_id:"",
      name: ""
    }
};

export default function loginInfo(state = initialState, action) {
  switch(action.type) {
    case AppType.LOGIN_INFO_REQUEST:
      return Object.assign({}, state, {
        loginInfoRequest: true,
        loginInfoResult: false,
        error: false,
        message: {
          user_email: "",
          user_password: "",
          name: "",
          user_id:""
        }
      });
    case AppType.LOGIN_INFO_RESULT:
      return Object.assign({}, state, {
        loginInfoRequest: false,
        loginInfoResult: true,
        nowLogin: action.login,
        token: action.token,
      });
    case AppType.LOGIN_FAILED:
      return Object.assign({}, state, {
        loginInfoRequest: false,
        loginInfoResult: true,
        error: true,
        message: {
          user_email: action.error.user_email,
          user_password: action.error.user_password,
          name: action.error.name,
          user_id: action.error.user_id,
        }
      });
    default:
      return state
  }
}


text: create index map_route_area_info on map_route(area_id, info_no);


text:
package com.microsoft.azure.management.advisor.v2017_04_19;

import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * A summary of the recommendation.
 */
public class ShortDescription {
    /**
     * The issue or opportunity identified by the recommendation.
     */
    @JsonProperty(value = "problem")
    private String problem;

    /**
     * The remediation action suggested by the recommendation.
     */
    @JsonProperty(value = "solution")
    private String solution;

    /**
     * Get the issue or opportunity identified by the recommendation.
     *
     * @return the problem value
     */
    public String problem() {
        return this.problem;
    }

    /**
     * Set the issue or opportunity identified by the recommendation.
     *
     * @param problem the problem value to set
     * @return the ShortDescription object itself.
     */
    public ShortDescription withProblem(String problem) {
        this.problem = problem;
        return this;
    }

    /**
     * Get the remediation action suggested by the recommendation.
     *
     * @return the solution value
     */
    public String solution() {
        return this.solution;
    }

    /**
     * Set the remediation action suggested by the recommendation.
     *
     * @param solution the solution value to set
     * @return the ShortDescription object itself.
     */
    public ShortDescription withSolution(String solution) {
        this.solution = solution;
        return this;
    }

}


text:
package org.apache.guacamole.auth.ban.status;

import org.apache.guacamole.GuacamoleException;
import org.apache.guacamole.net.auth.Credentials;

/**
 * AuthenticationFailureTracker implementation that does nothing. All requests
 * are ignored, regardless of status, and no tracking is performed.
 */
public class NullAuthenticationFailureTracker implements AuthenticationFailureTracker {

    @Override
    public void notifyAuthenticationRequestReceived(Credentials credentials)
            throws GuacamoleException {
        // Do nothing
    }

    @Override
    public void notifyAuthenticationSuccess(Credentials credentials)
            throws GuacamoleException {
        // Do nothing
    }

    @Override
    public void notifyAuthenticationFailed(Credentials credentials)
            throws GuacamoleException {
        // Do nothing
    }

}


text:
#ifndef PCL_GEOMETRY_BOOST_H
#define PCL_GEOMETRY_BOOST_H

#ifdef __GNUC__
  #pragma GCC system_header
#endif

#include <boost/iterator/iterator_facade.hpp>
#include <boost/utility/enable_if.hpp>
#include <boost/type_traits/add_const.hpp>
#include <boost/type_traits/conditional.hpp>
#include <boost/type_traits/integral_constant.hpp>
#include <boost/type_traits/is_const.hpp>
#include <boost/type_traits/is_convertible.hpp>

#endif // PCL_GEOMETRY_BOOST_H


text:
"""
Define a set of scopes to be used by COS Internal OAuth implementation, specifically tailored to work with APIv2.

List of scopes, nomenclature, and rationale can be found in the relevant "Login as OSF- phase 2" proposal document
"""

from collections import namedtuple

from website import settings

# Public scopes are described with 3 pieces of information: list of constituent scopes, a description, and whether or
#   not this scope is available to be requested by the general public

class scope(namedtuple('scope', ['parts_', 'description', 'is_public'])):
    """ Patch to add `ALWAYS_PUBLIC` scope to every selectable scope,
        ensuring that public endpoints are accessible with any token.
    """
    @property
    def parts(self):
        return frozenset((CoreScopes.ALWAYS_PUBLIC, )).union(self.parts_)

class CoreScopes(object):
    """
    The smallest units of permission that can be granted- all other scopes are built out of these.
    Each named constant is a single string."""
    # IMPORTANT: All views should be based on the smallest number of Core scopes required to describe
    # the data in that view

    USERS_READ = 'users_read'
    USERS_WRITE = 'users_write'
    USERS_CREATE = 'users_create'

    USER_SETTINGS_READ = 'user.settings_read'
    USER_SETTINGS_WRITE = 'user.settings_write'

    USER_EMAIL_READ = 'users.email_read'

    USER_ADDON_READ = 'users.addon_read'

    SUBSCRIPTIONS_READ = 'subscriptions_read'
    SUBSCRIPTIONS_WRITE = 'subscriptions_write'

    MEETINGS_READ = 'meetings.base_read'

    NODE_BASE_READ = 'nodes.base_read'
    NODE_BASE_WRITE = 'nodes.base_write'

    NODE_CHILDREN_READ = 'nodes.children_read'
    NODE_CHILDREN_WRITE = 'nodes.children_write'

    NODE_FORKS_READ = 'nodes.forks_read'
    NODE_FORKS_WRITE = 'nodes.forks_write'

    NODE_CONTRIBUTORS_READ = 'nodes.contributors_read'
    NODE_CONTRIBUTORS_WRITE = 'nodes.contributors_write'

    OSF_GROUPS_READ = 'osf_groups.groups_read'
    OSF_GROUPS_WRITE = 'osf_groups.groups_write'

    PREPRINT_CONTRIBUTORS_READ = 'preprints.contributors_read'
    PREPRINT_CONTRIBUTORS_WRITE = 'preprints.contributors_write'

    DRAFT_CONTRIBUTORS_READ = 'draft_registrations.contributors_read'
    DRAFT_CONTRIBUTORS_WRITE = 'draft_registrations.contributors_write'

    NODE_FILE_READ = 'nodes.files_read'
    NODE_FILE_WRITE = 'nodes.files_write'

    PREPRINT_FILE_READ = 'preprints.files_read'
    PREPRINT_FILE_WRITE = 'preprints.files_write'

    NODE_ADDON_READ = 'nodes.addon_read'
    NODE_ADDON_WRITE = 'nodes.addon_write'

    NODE_LINKS_READ = 'nodes.links_read'
    NODE_LINKS_WRITE = 'nodes.links_write'

    NODE_VIEW_ONLY_LINKS_READ = 'node.view_only_links_read'
    NODE_VIEW_ONLY_LINKS_WRITE = 'node.view_only_links_write'

    NODE_PREPRINTS_READ = 'node.preprints_read'
    NODE_PREPRINTS_WRITE = 'node.preprints_write'

    NODE_OSF_GROUPS_READ = 'node.osf_groups_read'
    NODE_OSF_GROUPS_WRITE = 'node.osf_groups_write'

    PREPRINTS_READ = 'preprint.preprints_read'
    PREPRINTS_WRITE = 'preprint.preprints_write'

    REGISTRATION_VIEW_ONLY_LINKS_READ = 'registration.view_only_links_read'
    REGISTRATION_VIEW_ONLY_LINKS_WRITE = 'registration.view_only_links_write'

    SCHEMA_READ = 'schemas.read'

    NODE_DRAFT_REGISTRATIONS_READ = 'nodes.draft_registrations_read'
    NODE_DRAFT_REGISTRATIONS_WRITE = 'nodes.draft_registrations_write'

    DRAFT_REGISTRATIONS_READ = 'draft_registrations.draft_registrations_read'
    DRAFT_REGISTRATIONS_WRITE = 'draft_registrations.draft_registrations_write'

    NODE_REGISTRATIONS_READ = 'nodes.registrations_read'
    NODE_REGISTRATIONS_WRITE = 'nodes.registrations_write'

    NODE_CITATIONS_READ = 'nodes.citations_read'
    NODE_CITATIONS_WRITE = 'nodes.citations_write'

    PREPRINT_CITATIONS_READ = 'preprints.citations_read'
    PREPRINT_CITATIONS_WRITE = 'preprints.citations_write'

    NODE_COMMENTS_READ = 'comments.data_read'
    NODE_COMMENTS_WRITE = 'comments.data_write'

    LICENSE_READ = 'license.data_read'

    COMMENT_REPORTS_READ = 'comments.reports_read'
    COMMENT_REPORTS_WRITE = 'comments.reports_write'

    APPLICATIONS_READ = 'applications_read'
    APPLICATIONS_WRITE = 'applications_write'

    NODE_LOG_READ = 'nodes.logs_read'
    TOKENS_READ = 'tokens_read'
    TOKENS_WRITE = 'tokens_write'

    ALERTS_READ = 'alerts_read'
    ALERTS_WRITE = 'alerts_write'

    INSTITUTION_READ = 'institutions_read'
    INSTITUTION_METRICS_READ = 'institutions_metrics_read'

    SCOPES_READ = 'scopes_read'

    SEARCH = 'search_read'

    ACTIONS_READ = 'actions_read'
    ACTIONS_WRITE = 'actions_write'

    MODERATORS_READ = 'moderators_read'
    MODERATORS_WRITE = 'moderators_write'

    NODE_REQUESTS_READ = 'node_requests_read'
    NODE_REQUESTS_WRITE = 'node_requests_write'

    NODE_SETTINGS_READ = 'node_settings_read'
    NODE_SETTINGS_WRITE = 'node_settings_write'

    PREPRINT_REQUESTS_READ = 'preprint_requests_read'
    PREPRINT_REQUESTS_WRITE = 'preprint_requests_write'

    REGISTRATION_REQUESTS_READ = 'registration_request_read'
    REGISTRATION_REQUESTS_WRITE = 'registration_request_write'

    PROVIDERS_WRITE = 'providers_write'

    CHRONOS_SUBMISSION_READ = 'chronos_submission_read'
    CHRONOS_SUBMISSION_WRITE = 'chronos_submission_write'

    NODE_REGISTRATIONS_READ = 'node.registrations_read'

    WAFFLE_READ = 'waffle_read'

    NULL = 'null'

    # NOTE: Use with extreme caution.
    # This should NEVER be assigned to endpoints:
    #    - with mutable data,
    #    - that might contain *anything* that could be personally-identifiable,
    #    - as a write scope
    ALWAYS_PUBLIC = 'always_public'

    ORGANIZER_COLLECTIONS_BASE_READ = 'collections.base_read'
    ORGANIZER_COLLECTIONS_BASE_WRITE = 'collections.base_write'

    COLLECTED_META_READ = 'collected_meta_read'
    COLLECTED_META_WRITE = 'collected_meta_write'

    GUIDS_READ = 'guids.base_read'

    WIKI_BASE_READ = 'wikis.base_read'
    WIKI_BASE_WRITE = 'wikis.base_write'

    IDENTIFIERS_READ = 'identifiers.data_read'
    IDENTIFIERS_WRITE = 'identifiers.data_write'

    METRICS_BASIC = 'metrics_basic'
    METRICS_RESTRICTED = 'metrics_restricted'

class ComposedScopes(object):
    """
    Composed scopes, listed in increasing order of access (most restrictive first). Each named constant is a tuple.
    """
    # IMPORTANT: Composed scopes exist only as an internal implementation detail.
    # All views should be based on selections from CoreScopes, above

    # Users collection
    USERS_READ = (CoreScopes.USERS_READ, CoreScopes.SUBSCRIPTIONS_READ, CoreScopes.ALERTS_READ, CoreScopes.USER_SETTINGS_READ)
    USERS_WRITE = USERS_READ + (CoreScopes.USERS_WRITE, CoreScopes.SUBSCRIPTIONS_WRITE, CoreScopes.ALERTS_WRITE, CoreScopes.USER_SETTINGS_WRITE)
    USERS_CREATE = USERS_READ + (CoreScopes.USERS_CREATE, )

    # User extensions
    USER_EMAIL_READ = (CoreScopes.USER_EMAIL_READ, )

    # Applications collection
    APPLICATIONS_READ = (CoreScopes.APPLICATIONS_READ, )
    APPLICATIONS_WRITE = APPLICATIONS_READ + (CoreScopes.APPLICATIONS_WRITE,)

    # Tokens collection
    TOKENS_READ = (CoreScopes.TOKENS_READ,)
    TOKENS_WRITE = TOKENS_READ + (CoreScopes.TOKENS_WRITE,)

    # Guid redirect view
    GUIDS_READ = (CoreScopes.GUIDS_READ, )

    # Metaschemas collection
    METASCHEMAS_READ = (CoreScopes.SCHEMA_READ, )

    # Draft registrations
    DRAFT_READ = (CoreScopes.NODE_DRAFT_REGISTRATIONS_READ, )
    DRAFT_WRITE = (CoreScopes.NODE_DRAFT_REGISTRATIONS_WRITE, )

    # OSF Groups
    GROUP_READ = (CoreScopes.OSF_GROUPS_READ, )
    GROUP_WRITE = (CoreScopes.OSF_GROUPS_WRITE, )

    # Identifier views
    IDENTIFIERS_READ = (CoreScopes.IDENTIFIERS_READ, )
    IDENTIFIERS_WRITE = (CoreScopes.IDENTIFIERS_WRITE, )

    # Comment reports collection
    COMMENT_REPORTS_READ = (CoreScopes.COMMENT_REPORTS_READ,)
    COMMENT_REPORTS_WRITE = COMMENT_REPORTS_READ + (CoreScopes.COMMENT_REPORTS_WRITE,)

    # Nodes collection.
    # Base node data includes node metadata, links, children, and preprints.
    NODE_METADATA_READ = (CoreScopes.NODE_BASE_READ, CoreScopes.NODE_CHILDREN_READ, CoreScopes.NODE_LINKS_READ,
                          CoreScopes.NODE_CITATIONS_READ, CoreScopes.NODE_COMMENTS_READ, CoreScopes.NODE_LOG_READ,
                          CoreScopes.NODE_FORKS_READ, CoreScopes.WIKI_BASE_READ, CoreScopes.LICENSE_READ,
                          CoreScopes.IDENTIFIERS_READ, CoreScopes.NODE_PREPRINTS_READ, CoreScopes.PREPRINT_REQUESTS_READ,
                          CoreScopes.REGISTRATION_REQUESTS_READ)
    NODE_METADATA_WRITE = NODE_METADATA_READ + \
                    (CoreScopes.NODE_BASE_WRITE, CoreScopes.NODE_CHILDREN_WRITE, CoreScopes.NODE_LINKS_WRITE, CoreScopes.IDENTIFIERS_WRITE,
                     CoreScopes.NODE_CITATIONS_WRITE, CoreScopes.NODE_COMMENTS_WRITE, CoreScopes.NODE_FORKS_WRITE,
                     CoreScopes.NODE_PREPRINTS_WRITE, CoreScopes.PREPRINT_REQUESTS_WRITE, CoreScopes.WIKI_BASE_WRITE,
                     CoreScopes.REGISTRATION_REQUESTS_WRITE)

    # Preprints collection
    # TODO: Move Metrics scopes to their own restricted composed scope once the Admin app can manage scopes on tokens/apps
    PREPRINT_METADATA_READ = (CoreScopes.PREPRINTS_READ, CoreScopes.PREPRINT_CITATIONS_READ, CoreScopes.IDENTIFIERS_READ, CoreScopes.METRICS_BASIC,)
    PREPRINT_METADATA_WRITE = PREPRINT_METADATA_READ + (CoreScopes.PREPRINTS_WRITE, CoreScopes.PREPRINT_CITATIONS_WRITE, CoreScopes.METRICS_RESTRICTED,)

    # Organizer Collections collection
    # Using Organizer Collections and the node links they collect. Reads Node Metadata.
    ORGANIZER_READ = (CoreScopes.ORGANIZER_COLLECTIONS_BASE_READ, CoreScopes.COLLECTED_META_READ,) + NODE_METADATA_READ
    ORGANIZER_WRITE = ORGANIZER_READ + (CoreScopes.ORGANIZER_COLLECTIONS_BASE_WRITE, CoreScopes.NODE_LINKS_WRITE, CoreScopes.COLLECTED_META_WRITE)

    # Privileges relating to editing content uploaded under that node
    NODE_DATA_READ = (CoreScopes.NODE_FILE_READ, CoreScopes.WIKI_BASE_READ)
    NODE_DATA_WRITE = NODE_DATA_READ + \
                        (CoreScopes.NODE_FILE_WRITE, CoreScopes.WIKI_BASE_WRITE)

    # Privileges relating to editing content uploaded under that preprint
    PREPRINT_DATA_READ = (CoreScopes.PREPRINT_FILE_READ,)
    PREPRINT_DATA_WRITE = PREPRINT_DATA_READ + \
                        (CoreScopes.PREPRINT_FILE_WRITE,)

    # Privileges relating to who can access a node (via contributors or registrations)
    NODE_ACCESS_READ = (CoreScopes.NODE_CONTRIBUTORS_READ, CoreScopes.NODE_REGISTRATIONS_READ,
                        CoreScopes.NODE_VIEW_ONLY_LINKS_READ, CoreScopes.REGISTRATION_VIEW_ONLY_LINKS_READ,
                        CoreScopes.NODE_REQUESTS_READ, CoreScopes.NODE_SETTINGS_READ, CoreScopes.NODE_OSF_GROUPS_READ)
    NODE_ACCESS_WRITE = NODE_ACCESS_READ + \
                            (CoreScopes.NODE_CONTRIBUTORS_WRITE, CoreScopes.NODE_REGISTRATIONS_WRITE,
                             CoreScopes.NODE_VIEW_ONLY_LINKS_WRITE, CoreScopes.REGISTRATION_VIEW_ONLY_LINKS_WRITE,
                             CoreScopes.NODE_REQUESTS_WRITE, CoreScopes.NODE_SETTINGS_WRITE, CoreScopes.NODE_OSF_GROUPS_WRITE)

    # Privileges relating to who can access a preprint via contributors
    PREPRINT_ACCESS_READ = (CoreScopes.PREPRINT_CONTRIBUTORS_READ,)
    PREPRINT_ACCESS_WRITE = PREPRINT_ACCESS_READ + \
                            (CoreScopes.PREPRINT_CONTRIBUTORS_WRITE,)

    # Combine all sets of node permissions into one convenience level
    NODE_ALL_READ = NODE_METADATA_READ + NODE_DATA_READ + NODE_ACCESS_READ
    NODE_ALL_WRITE = NODE_ALL_READ + NODE_METADATA_WRITE + NODE_DATA_WRITE + NODE_ACCESS_WRITE

    # Combine preprint permissions
    PREPRINT_ALL_READ = PREPRINT_METADATA_READ + PREPRINT_ACCESS_READ + PREPRINT_DATA_READ
    PREPRINT_ALL_WRITE = PREPRINT_ALL_READ + PREPRINT_METADATA_WRITE + PREPRINT_ACCESS_WRITE + PREPRINT_DATA_WRITE

    # Reviews
    REVIEWS_READ = (CoreScopes.ACTIONS_READ, CoreScopes.MODERATORS_READ)
    REVIEWS_WRITE = (CoreScopes.ACTIONS_WRITE, CoreScopes.MODERATORS_WRITE, CoreScopes.PROVIDERS_WRITE)

    # Full permissions: all routes intended to be exposed to third party API users
    FULL_READ = NODE_ALL_READ + USERS_READ + ORGANIZER_READ + GUIDS_READ + METASCHEMAS_READ + DRAFT_READ + REVIEWS_READ + PREPRINT_ALL_READ + GROUP_READ + (CoreScopes.MEETINGS_READ, CoreScopes.INSTITUTION_READ, CoreScopes.SEARCH, CoreScopes.SCOPES_READ)
    FULL_WRITE = FULL_READ + NODE_ALL_WRITE + USERS_WRITE + ORGANIZER_WRITE + DRAFT_WRITE + REVIEWS_WRITE + PREPRINT_ALL_WRITE + GROUP_WRITE

    # Admin permissions- includes functionality not intended for third-party use
    ADMIN_LEVEL = FULL_WRITE + APPLICATIONS_WRITE + TOKENS_WRITE + COMMENT_REPORTS_WRITE + USERS_CREATE + REVIEWS_WRITE +\
                    (CoreScopes.USER_EMAIL_READ, CoreScopes.USER_ADDON_READ, CoreScopes.NODE_ADDON_READ, CoreScopes.NODE_ADDON_WRITE, CoreScopes.WAFFLE_READ, )

# List of all publicly documented scopes, mapped to composed scopes defined above.
#   Return as sets to enable fast comparisons of provided scopes vs those required by a given node
# These are the ***only*** scopes that will be recognized from CAS
public_scopes = {
    'osf.full_read': scope(parts_=frozenset(ComposedScopes.FULL_READ),
                           description='View all information associated with this account, including for '
                                       'private projects.',
                           is_public=True),
    'osf.full_write': scope(parts_=frozenset(ComposedScopes.FULL_WRITE),
                            description='View and edit all information associated with this account, including for '
                                        'private projects.',
                            is_public=True),
    'osf.users.profile_read': scope(parts_=frozenset(ComposedScopes.USERS_READ),
                                description='Read your profile data.',
                                is_public=True),
    'osf.users.email_read': scope(parts_=frozenset(ComposedScopes.USER_EMAIL_READ),
                                        description='Read your primary email address.',
                                        is_public=True),
}

if settings.DEV_MODE:
    public_scopes.update({
        'osf.users.profile_write': scope(parts_=frozenset(ComposedScopes.USERS_WRITE),
                                     description='Read and edit your profile data.',
                                     is_public=True),

        'osf.nodes.metadata_read': scope(parts_=frozenset(ComposedScopes.NODE_METADATA_READ),
                                         description='Read a list of all public and private nodes accessible to this '
                                                     'account, and view associated metadata such as project descriptions '
                                                     'and titles.',
                                         is_public=True),
        'osf.nodes.metadata_write': scope(parts_=frozenset(ComposedScopes.NODE_METADATA_WRITE),
                                          description='Read a list of all public and private nodes accessible to this '
                                                      'account, and view and edit associated metadata such as project '
                                                      'descriptions and titles.',
                                          is_public=True),

        'osf.nodes.data_read': scope(parts_=frozenset(ComposedScopes.NODE_DATA_READ),
                                     description='List and view files associated with any public or private projects '
                                                 'accessible to this account.',
                                     is_public=True),
        'osf.nodes.data_write': scope(parts_=frozenset(ComposedScopes.NODE_DATA_WRITE),
                                      description='List, view, and update files associated with any public or private '
                                                  'projects accessible to this account.',
                                      is_public=True),

        'osf.nodes.access_read': scope(parts_=frozenset(ComposedScopes.NODE_ACCESS_READ),
                                       description='View the contributors list and any established registrations '
                                                   'associated with public or private projects.',
                                       is_public=True),
        'osf.nodes.access_write': scope(parts_=frozenset(ComposedScopes.NODE_ACCESS_WRITE),
                                        description='View and edit the contributors list associated with public or '
                                                    'private projects accessible to this account. Also view and create '
                                                    'registrations.',
                                        is_public=True),  # TODO: Language: Does registrations endpoint allow creation of registrations? Is that planned?

        'osf.nodes.full_read': scope(parts_=frozenset(ComposedScopes.NODE_ALL_READ),
                                    description='View all metadata, files, and access rights associated with all public '
                                                'and private projects accessible to this account.',
                                    is_public=True),
        'osf.nodes.full_write': scope(parts_=frozenset(ComposedScopes.NODE_ALL_WRITE),
                                     description='View and edit all metadata, files, and access rights associated with '
                                                 'all public and private projects accessible to this account.',
                                     is_public=True),

        # Undocumented scopes that can not be requested by third parties (per CAS restriction)
        'osf.users.create': scope(parts_=frozenset(ComposedScopes.USERS_CREATE),
                           description='This permission should only be granted to OSF collaborators. Allows a site to '
                                       'programmatically create new users with this account.',
                           is_public=False),

        'osf.admin': scope(parts_=frozenset(ComposedScopes.ADMIN_LEVEL),
                           description='This permission should only be granted to OSF administrators. Allows a site to '
                                       'create, read, edit, and delete all information associated with this account.',
                           is_public=False),
    })

def normalize_scopes(scopes):
    """
    Given a list of public-facing scope names from a CAS token, return the list of internal scopes

    This is useful for converting a single broad scope name (from CAS) into the small constituent parts
        (as used by views)

    :param list scopes: a list public facing scopes
    """
    all_scopes = set()
    for sc in scopes:
        try:
            scope_tuple = public_scopes[sc]
            all_scopes |= scope_tuple.parts
        except KeyError:
            pass
    return all_scopes

if __name__ == '__main__':
    # Print some data to console, to help audit what views/core scopes map to a given public/composed scope
    # Although represented internally as a set, print as a sorted list for readability.
    from pprint import pprint as pp
    pp({k: sorted(v.parts)
        for k, v in public_scopes.items()})


text:
<?php

// define the filenames used in the project
  define('FILENAME_ACTION_RECORDER', 'action_recorder.php');
  define('FILENAME_ADMINISTRATORS', 'administrators.php');
  define('FILENAME_BACKUP', 'backup.php');
  define('FILENAME_BANNER_MANAGER', 'banner_manager.php');
  define('FILENAME_BANNER_STATISTICS', 'banner_statistics.php');
  define('FILENAME_CACHE', 'cache.php');
  define('FILENAME_CATALOG_ACCOUNT_HISTORY_INFO', 'account_history_info.php');
  define('FILENAME_CATEGORIES', 'categories.php');
  define('FILENAME_CONFIGURATION', 'configuration.php');
  define('FILENAME_COUNTRIES', 'countries.php');
  define('FILENAME_CURRENCIES', 'currencies.php');
  define('FILENAME_CUSTOMERS', 'customers.php');
  define('FILENAME_DEFAULT', 'index.php');
  define('FILENAME_DEFINE_LANGUAGE', 'define_language.php');
  define('FILENAME_GEO_ZONES', 'geo_zones.php');
  define('FILENAME_LANGUAGES', 'languages.php');
  define('FILENAME_LOGIN', 'login.php');
  define('FILENAME_MAIL', 'mail.php');
  define('FILENAME_MANUFACTURERS', 'manufacturers.php');
  define('FILENAME_MODULES', 'modules.php');
  define('FILENAME_NEWSLETTERS', 'newsletters.php');
  define('FILENAME_ORDERS', 'orders.php');
  define('FILENAME_ORDERS_INVOICE', 'invoice.php');
  define('FILENAME_ORDERS_PACKINGSLIP', 'packingslip.php');
  define('FILENAME_ORDERS_STATUS', 'orders_status.php');
  define('FILENAME_POPUP_IMAGE', 'popup_image.php');
  define('FILENAME_PRODUCTS_ATTRIBUTES', 'products_attributes.php');
  define('FILENAME_PRODUCTS_EXPECTED', 'products_expected.php');
  define('FILENAME_REVIEWS', 'reviews.php');
  define('FILENAME_SEC_DIR_PERMISSIONS', 'sec_dir_permissions.php');
  define('FILENAME_SERVER_INFO', 'server_info.php');
  define('FILENAME_SHIPPING_MODULES', 'shipping_modules.php');
  define('FILENAME_SPECIALS', 'specials.php');
  define('FILENAME_STATS_CUSTOMERS', 'stats_customers.php');
  define('FILENAME_STATS_PRODUCTS_PURCHASED', 'stats_products_purchased.php');
  define('FILENAME_STATS_PRODUCTS_VIEWED', 'stats_products_viewed.php');
  define('FILENAME_STORE_LOGO', 'store_logo.php');
  define('FILENAME_TAX_CLASSES', 'tax_classes.php');
  define('FILENAME_TAX_RATES', 'tax_rates.php');
  define('FILENAME_VERSION_CHECK', 'version_check.php');
  define('FILENAME_WHOS_ONLINE', 'whos_online.php');
  define('FILENAME_ZONES', 'zones.php');
?>


text: logScript("external")


text: This directory is for testing PlzDedicatedWorker (https://crbug.com/906991).


text:
module SurveyorGui
  module Helpers
    module SurveyorGuiHelperMethods
      # Responses
      def response_for(response_set, question, answer = nil, response_group = nil, column_id = nil)
        return nil unless response_set && question && question.id
        result = response_set.responses.detect{|r|
          (r.question_id == question.id) &&
          (answer.blank? ? true : r.answer_id == answer.id) &&
          (r.response_group.blank? ? true : r.response_group.to_i == response_group.to_i) &&
          (r.column_id.blank? ? true : r.column_id == column_id.to_i)}
        result.blank? ? response_set.responses.build(
          question_id: question.id,
          response_group: response_group,
          column_id: column_id) : result
      end
    end
  end
end


text:
"""
Created on Feb 25, 2012

@author: Bilel Msekni
@contact: bilel.msekni@telecom-sudparis.eu
@author: Houssem Medhioub
@contact: houssem.medhioub@it-sudparis.eu
@organization: Institut Mines-Telecom - Telecom SudParis
@license: Apache License, Version 2.0
"""

import pyocni.pyocni_tools.config as config
import commands

# getting the Logger
logger = config.logger

class backend_interface(object):
    '''

    A simple and empty backend

    '''

    local_identifier = 'a'

    def create(self, entity):
        '''

        Create an entity (Resource or Link)

        '''
        logger.debug('The create operation is not implemented yet')

    def read(self, entity):
        '''

        Get the Entity's information

        '''
        logger.debug('The read operation is not implemented yet')

    def update(self, old_entity, new_entity):
        '''

        Update an Entity's information

        '''
        logger.debug('The update operation is not implemented yet')

    def delete(self, entity):
        '''

        Delete an Entity

        '''
        logger.debug('The delete operation is not implemented yet')

    def action(self, entity, action, attributes):
        '''

        Perform an action on an Entity

        '''
        logger.debug('The Entity\'s action operation is not implemented yet')

if __name__ == '__main__':
    pass


text:
{%  macro login_button(provider='') -%}
{% if provider == 'google-oauth2' %}
 Google
{% elif provider == 'github' %}
 Github
{% else %}
{{ provider }}
{% endif %}
{% endmacro -%}

{%  macro logout_button(provider='', id=None) -%}
<form action="{{ url_for("social.disconnect", backend=provider, association_id=id) }}" method="POST" class="nobox">
<button type="submit" class="btn btn-link btn-lg" data-confirm="{{ _('Do you want to disconnect this service from your profile?')}}" data-title="{{ _('Are you sure?') }}">
{% if provider == 'google-oauth2' %}
 Google
{% elif provider == 'github' %}
 Github
{% else %}
{{ provider }}
{% endif %}</button>
</form>

{% endmacro -%}


text:
export const CREATE_CATEGORY = 'Category/CREATE_CATEGORY';
export const CREATE_CATEGORY_REQUEST = 'Category/CREATE_CATEGORY_REQUEST';
export const CLOSE_CATEGORY = 'Category/CLOSE_CATEGORY';
export const CREATE_CATEGORY_FAILED = 'Category/CREATE_CATEGORY_FAILED';
export const CREATE_CATEGORY_SUCCESSFUL = 'Category/CREATE_CATEGORY_SUCCESSFUL';
export const STORE_CATEGORY = 'Category/STORE_CATEGORY';

export const FETCH_CATEGORIES = 'Category/FETCH_CATEGORIES';
export const FETCH_CATEGORIES_FAILED = 'Category/FETCH_CATEGORIES_FAILED';
export const FETCH_CATEGORIES_SUCCESS = 'Category/FETCH_CATEGORIES_SUCCESS';

export const SHOW_HIDE = 'Category/SHOW_HIDE';

export const REQUEST_DELETE = 'Category/REQUEST_DELETE';

export const HIDE_MODAL = 'Category/HIDE_MODAL';
export const DELETE_CATEGORY = 'Category/DELETE_CATEGORY';
export const DELETE_CATEGORY_SUCCESS = 'Category/DELETE_CATEGORY_SUCCESS';
export const DELETE_CATEGORY_FAILED = 'Category/DELETE_CATEGORY_FAILED';

export const EDIT_CATEGORY = 'Category/EDIT_CATEGORY';
export const HIDE_EDIT_MODAL = 'Category/HIDE_EDIT_MODAL';
export const UPDATE_CATEGORY_SUCCESS = 'Category/UPDATE_CATEGORY_SUCCESS';
export const UPDATE_CATEGORY_FAILED = 'Category/UPDATE_CATEGORY_FAILED';
export const EDIT_CATEGORY_REQUEST = 'Category/EDIT_CATEGORY_REQUEST';


text:
using System;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Input.Events;
using osu.Game.Graphics.Containers;
using osu.Game.Graphics.UserInterface;
using osu.Game.Online;
using osu.Game.Online.API.Requests.Responses;
using osu.Game.Overlays;

namespace osu.Game.Beatmaps.Drawables.Cards
{
    public abstract class BeatmapCard : OsuClickableContainer
    {
        public const float TRANSITION_DURATION = 400;
        public const float CORNER_RADIUS = 10;

        protected const float WIDTH = 430;

        public IBindable<bool> Expanded { get; }

        public readonly APIBeatmapSet BeatmapSet;

        protected readonly Bindable<BeatmapSetFavouriteState> FavouriteState;

        protected abstract Drawable IdleContent { get; }
        protected abstract Drawable DownloadInProgressContent { get; }

        protected readonly BeatmapDownloadTracker DownloadTracker;

        protected BeatmapCard(APIBeatmapSet beatmapSet, bool allowExpansion = true)
            : base(HoverSampleSet.Button)
        {
            Expanded = new BindableBool { Disabled = !allowExpansion };

            BeatmapSet = beatmapSet;
            FavouriteState = new Bindable<BeatmapSetFavouriteState>(new BeatmapSetFavouriteState(beatmapSet.HasFavourited, beatmapSet.FavouriteCount));
            DownloadTracker = new BeatmapDownloadTracker(beatmapSet);
        }

        [BackgroundDependencyLoader(true)]
        private void load(BeatmapSetOverlay? beatmapSetOverlay)
        {
            Action = () => beatmapSetOverlay?.FetchAndShowBeatmapSet(BeatmapSet.OnlineID);

            AddInternal(DownloadTracker);
        }

        protected override void LoadComplete()
        {
            base.LoadComplete();

            DownloadTracker.State.BindValueChanged(_ => UpdateState());
            Expanded.BindValueChanged(_ => UpdateState(), true);
            FinishTransforms(true);
        }

        protected override bool OnHover(HoverEvent e)
        {
            UpdateState();
            return base.OnHover(e);
        }

        protected override void OnHoverLost(HoverLostEvent e)
        {
            UpdateState();
            base.OnHoverLost(e);
        }

        protected virtual void UpdateState()
        {
            bool showProgress = DownloadTracker.State.Value == DownloadState.Downloading || DownloadTracker.State.Value == DownloadState.Importing;

            IdleContent.FadeTo(showProgress ? 0 : 1, TRANSITION_DURATION, Easing.OutQuint);
            DownloadInProgressContent.FadeTo(showProgress ? 1 : 0, TRANSITION_DURATION, Easing.OutQuint);
        }

        /// <summary>
        /// Creates a beatmap card of the given <paramref name="size"/> for the supplied <paramref name="beatmapSet"/>.
        /// </summary>
        public static BeatmapCard Create(APIBeatmapSet beatmapSet, BeatmapCardSize size, bool allowExpansion = true)
        {
            switch (size)
            {
                case BeatmapCardSize.Normal:
                    return new BeatmapCardNormal(beatmapSet, allowExpansion);

                case BeatmapCardSize.Extra:
                    return new BeatmapCardExtra(beatmapSet, allowExpansion);

                default:
                    throw new ArgumentOutOfRangeException(nameof(size), size, @"Unsupported card size");
            }
        }
    }
}


text:
+++ native_client/site_scons/site_init.py	2014-06-03 22:13:58.818977057 -0500
@@ -40,10 +40,10 @@
   target_platform tool for your environments.  When you call
   BuildEnvironments(), only environments with the current host platform will be
   built.  If for some reason you really need to examine the host platform,
-  check env.Bit('host_windows') / env.Bit('host_linux') / env.Bit('host_mac').
+  check env.Bit('host_windows') / env.Bit('host_linux') / env.Bit('host_freebsd') / env.Bit('host_mac').

   Returns:
-    The host platform name - one of ('WINDOWS', 'LINUX', 'MAC').
+    The host platform name - one of ('WINDOWS', 'LINUX', 'FREEBSD', 'MAC').
   """

   platform_map = {
@@ -52,6 +52,8 @@
       'linux': 'LINUX',
       'linux2': 'LINUX',
       'linux3': 'LINUX',
+      'freebsd': 'FREEBSD',
+      'freebsd11': 'FREEBSD',
       'darwin': 'MAC',
   }

@@ -149,6 +151,8 @@
       'cygwin': 'win',
       'linux': 'linux',
       'linux2': 'linux',
+      'freebsd': 'freebsd',
+      'freebsd11': 'freebsd',
       'darwin': 'mac',
       }
   if sys.platform in platform_map:


text:
import re
from ephem import *
from numpy import *
import sys

userInp   = sys.argv[1:]

if len(userInp) == 0:
    print ""
    print "# rfcBand.py takes input from AstroGeo rfc_20*.txt files and selects"
    print "# sources of interest from a required band [s, c, x, u or k]. It"
    print "# also allows you to define the minimum astrometric error."
    print ""
    print "-->$ rfcBand.py band flux_threshold [err=dd.dd]"
    print ""
    exit()

#=====================================================================
#                   Define variables:
#
ints      = '\s+([+-]?\d+)'
floats    = '\s+([+-]?\d+.\d+)'

bandDict  = {'s':13,                   # Columns in rfc file according to the harvest algorithm below
             'c':15,
             'x':17,
             'u':19,
             'k':21}

userBand  =       userInp[1].lower()   # s, c, x, u or k band
userVal   = float(userInp[2])          # Minimum required flux unresolved flux density
fileCol   = int(bandDict[userBand])
firstLine = True                       # For printing the header during output
lastLine  = False                      # For printing the footer during output

for i in userInp:
    errRequest = re.search('err='+'(\d+.\d+)',i)
    if errRequest:
        requiredAstrometry = float(errRequest.group(1))
    else:
        requiredAstrometry = 0.25      # mas

#=====================================================================
#                   Main script starts here:
#
with open(userInp[0]) as file:
    for line in file:
        # Harvest begins here:
        requiredInfo = re.search( '\s+\S+\s'
                                 +'(J\d+[+-]?\d+\s+)' #  1    Source name
                                 + ints               #  2    HH
                                 + ints               #  3    MM
                                 + floats             #  4    SS.SSSSSS
                                 + ints               #  5    DD
                                 + ints               #  6    MM
                                 + floats             #  7    SS.SSSSS
                                 + 3*floats           #  8-10 Error in RA/Dec (mas) and correlation RA/Dec
                                 + ints               # 11    Number of observations
                                 + 10*floats          # 12-21 Band: S (13), C (15), X (17), U (19), K or X/S (21) flux
                                 +'\s+(\S+)\s+'       # 22    Band: S     , C     , X     , U     , K or X/S
                                 +'rfc_\S+'
                                 , line)
        if requiredInfo:
            sourName =             requiredInfo.group(1)
            fileFlux =       float(requiredInfo.group(fileCol))
            fileBand =         str(requiredInfo.group(22)).lower()
            err      =  sqrt(float(requiredInfo.group(8))**2 + float(requiredInfo.group(9))**2)

            if fileFlux >= userVal and fileBand == userBand and err <= requiredAstrometry:
                if firstLine:
                    print ""
                    print " Source Name    Mean positional error    Unresolved flux density    Band"
                    print ""
                    firstLine = False
                else:
                    print "  %s %22.2f %22.3f %12s"%(sourName,err,fileFlux,fileBand.upper())
                    lastLine = True
file.close()

if lastLine:
    print ""


text:
import { Component } from '@angular/core';

@Component({
    selector: 'my-app',
    template: `
      <lifecycle [valorInicial]="valorInicial" *ngIf="deletarConteudo != true"></lifecycle>
      <button (click)="valorInicial = 20">Mudar o valor</button>
      <button (click)="deletarConteudo = true">Deletar tag life cycle</button>
      <exemplo-data-binding></exemplo-data-binding>
    `
})
export class AppComponent {

  deletarConteudo = false;
  valorInicial = 15;

}