text:
## About the Literate file formats
The literate configuration format is a [CommonMark](http://spec.commonmark.org/) document that has embedded code
blocks for machine readable sections. This encourages easy-to-author documentation while permitting the specificity
desired when authoring and processing instructions.

### Notable Features

- Choose a specific version (or a valid range?) of AutoRest to run (discovery/acquring when necessary.)
- Specifiy the swagger files that it applies to.

### Continutity with pre-existing AutoRest scripts

Passing settings on the command line will be continue to be supported for continutity, the
preference going forward would be to build an accompanying file to drive the execution.

The implementation of the command line will be to translate the existing command-line-parameters into
an in-memory configuration document and feed that to the configuration processing system to ensure
that the rest of the system doesn't require any extra effort to process.

## The File Format

The Literate configuration file is a CommonMark (aka Markdown) file that has code blocks.

If the configuration file is actually named `Readme.md` it serves dual-purpose as both the documentation that
a user sees in github where instructuions for use can be, as well as the storage for configuration information.

A configuration file should also _document_ how to use the configuration file, without assuming that the user knows
how to use any of the tools required.

> Example: a configuration `readme.md` that starts off with instructions on how to use it.

> ~~~ markdown
> # My API
>
> ## Getting Started
> To build the SDKs for My API, simply [Install AutoRest](#Installing-AutoRest) and run:
> > `Autorest.exe readme.md`
>
> To see additional help and options, run:
> > `Autorest.exe help readme.md`
>
> ### Installing AutoRest
> AutoRest is most easily installed via the Node JS package `autorest`:
> > npm install -g autorest
>
> For other options on installation see [Installing AutoRest](https://aka.ms/installing-autorest.md) on the AutoRest github page.
>
> ## AutoRest configuration ...
> ``` yaml
> autorest:
>   minimum-version: 1.0 # specify the version of Autorest to use
>   # (more settings here...)
> ```
> ~~~

### Configuration element conventions

- all elements should be lower-case, singular tense, and use dashes to separate words. ie:

``` yaml
# not 'inputs'
input-file: foo.yaml

base-folder: c:/output/folder
```

- elements should be parsed to take either a single value, or an an array of values where possible, AutoRest should figure out what to do.

``` yaml
# specify a single swagger file
input-file: foo.swagger.yaml

# specify a set of swagger files
input-file:
  - foo.swagger.yaml
  - bar.swagger.yaml
```

- all elements should try to follow the `purpose-noun` style for compound element names:

``` yaml
output-folder: c:/my/output/folder
log-file: c:/my/output/logs.txt
```

- In order to decrease ambiguity, we shall have a list of preferred purposes and nouns that should be used if possible. In the case of a new purpose or noun, new ones should be considered and added to the master list.

> *Purposes*
> ``` yaml
> folder: Used to specify one or more directory, folder, file container
> file: used for one or more files
> ```

> *Nouns*
>

### Extending syntax thru meta variables

An r-value can specify the use of a `$` to prefix to indicate a value that is resolved at evaluation time.
This introduces the use of a *meta-variables* that the user can use to make paths relative, find nodes in the Swagger DOM, or accept values from the command line.

There are two basic formats for meta-variable resolution

#### Straight value replacement
Straight value replacement is a simple substitution of the target value. The format is: `$(VARIABLE-NAME)` where the `VARIABLE-NAME` is a meta-variable or value from the current literate document.

``` yaml
output-folder: "$(base-folder)/Generated" # relative to this file's actual location.
log-folder: "$(output-folder)/logs" # relative to the output folder specified above.
```

##### Ideas for some *S-R-V* Meta-variables
- `$(base-folder)` - the full path to the directory (or partial URL) that contains this file
   ideally, this should be the same as saying `.` (ie, `include-file: ./foo.json`)
- `$(current-directory)` - the full path to the current directory when AutoRest was run
- `$(random-number)` - a random number?
- `$(output-folder)` - the current value of the output folder (after all the layers of settings have been applied)

##### Setting the value of a meta-variable from the host environment
You can set (override) a value for a meta-variable in the host environment (cmdline, VSCode Extension, CI system, etc)

|Environment|Setting|Description|
|-----------|-------|-----------|
| via cmdline | `-some-value=true` | sets the `$(some-value)` meta variable to `true` |
| via VSCode | (via UI) |in the VSCode UI, a setting can be set via a property by a value in the editor preferences, or via the UI (like a toggle, etc) <br>As the VSCode exensibility improves to support custom UI, this can be enhanced further.
| via CI (environment?) | `$env:autorest-some-variable = true` | environment variables prefixed with `autorest-` are implicity added as metavariables|

> Idle thought:
> Should we support direct environment variable references in Literate Configuration?
>
> ie, `$(env:TMP)` to could resolve to the environment variable `TMP`

##### Additional Uses of Meta-variables

In addition to simple **macro-value** replacement, meta-variables can be used to control the evaluation of a code-block in a document. For example, take this literate document:

~~~ markdown
## Debug Version
When the `$(some-value)` is set to `true`, this section will be activated.

``` yaml enabled=$(some-value)
output-folder: "$(base-folder)/Generated/Debug"
log-folder: "$(output-folder)/logs"
log-level: debug
```
~~~

In the above case, the `some-value` meta-variable would have to evaluate to `true` before that codeblock would be included in the configuration.

From the command-line, this would look like:

> `AutoRest.exe readme.md -some-value=true`

#### JSONPath document reference

[JSONPath](http://goessner.net/articles/JsonPath/) will be used to reference nodes in the swagger document object model.

JSONPath is similar to XPath, but is designed for JSON (and YAML) documents. This will be used in conjunction with the [Swagger DOM Query Format](#Swagger-DOM-Query-Format)

> ### Excerpted from the [JSONPath website](http://goessner.net/articles/JsonPath/)
>
> JSONPath expressions always refer to a JSON structure in the same way as XPath expression are used in combination with an XML document. Since a JSON structure is usually anonymous and doesn't necessarily have a "root member object" JSONPath assumes the abstract name $ assigned to the outer level object.
>
>JSONPath expressions can use the dot–notation
>
>`$.store.book[0].title`
>
>or the bracket–notation
>
>`$['store']['book'][0]['title']`
>
>for input pathes. Internal or output pathes will always be converted to the more general bracket–notation.
>
>JSONPath allows the wildcard symbol * for member names and array indices. It borrows the descendant operator '..' from E4X and the array slice syntax proposal [start:end:step] from ECMASCRIPT 4.
>
>Expressions of the underlying scripting language (`<expr>`) can be used as an alternative to explicit names or indices as in
>
> `$.store.book[(@.length-1)].title`
>
>using the symbol '@' for the current object. Filter expressions are supported via the syntax ?(<boolean expr>) as in
>
>`$.store.book[?(@.price < 10)].title`
>
>Here is a complete overview and a side by side comparison of the JSONPath syntax elements with its XPath counterparts.
>
>|XPath|JSONPath|Description|
>|-----|--------|-----------|
>| `/` |	`$`  |the root object/element|
>| `.`	| `@`	 | the current object/element|
>| `/` |	`.` or `[]` | child operator|
>|`..`	| n/a	|parent operator|
>|`//`	|`..`	|recursive descent. JSONPath borrows this syntax from E4X.|
>|`*`|	`*`|	wildcard. All objects/elements regardless their names.|
>|`@`|	n/a|	attribute access. JSON structures don't have attributes.|
>|`[]`|`[]`|	subscript operator. XPath uses it to iterate over element collections and for predicates. In Javascript and JSON it is the native array operator.|
>| `|`|`[,]`|Union operator in XPath results in a combination of node sets. JSONPath allows alternate names or array indices as a set.|
>|n/a|	`[start:end:step]`|	array slice operator borrowed from ES4.|
>|`[]`	|`?()`|	applies a filter (script) expression.|
>|n/a	|`()`|	script expression, using the underlying script engine.|
>|`()`	|n/a	|grouping in XPath|

Among the many virtues of JSONPath, an expression can be virtually exactly as you'd expect to identify a specific node with JSON, ie:

``` yaml
# specifically refers to a single node in the Swagger DOM
# #/definitions/fooresource/properties/properties/provisioningState
some-node: $definitions.fooresource.properties.properties.provisioningState
```

Or you can use a more complex expression to identify a collection of nodes:

``` yaml
# selects all nodes in the 'paths' collection that have an node that has a property 'operationId' where the value starts with 'blob_'
some-nodes: $..paths[($..operationId["blob_*"])]
```

The applicability of the selected nodes is explained further in the section [Swagger DOM Query Format](#Swagger-DOM-Query-Format)

## The Swagger DOM

AutoRest has traditionally supported two 'modeler' implementations. The `swagger` modeler, which accepts a single swagger document, and a `composite` modeler that merges multiple swagger documents into a single DOM. The `composite` modeler suffers from a few unfortunate design limitations, and we will phase it's use out in favor of a more natural multi-document approach in AutoRest.

In the configuration file, you can specify the list of swagger documents that you wish to include.

``` yaml
input-file:
  - ./2015-01-02/swagger/foo.json   # referenced documents can be JSON, YAML or Markdown.
  - ./2016-02-03/swagger/bar.md
```

Once a file is loaded, it's never referred to in configuration by it's file name (which may be arbitrary, auto-generated , or even non-existent), but instead by it's Swagger `title` value. (You can think of this as the `namespace` for the swagger document)

> _Idle thought:_
>
> The impact/difference regarding multiple documents with a single namespace?
> The assumption is that those would be merged early in the document parsing phase as if the content were in the exact same file, and would be indistinguishable at that point.
>
> When the documents each have a different `namespace`, the nodes can be referred to seperately, even if the final output of AutoRest is a single, merged SDK.

## Configuration sections

The general layout of the Literate Configuration DOM is :

### Settings
Settings are top-level key-value pairs that AutoRest uses to create the Literate Swagger DOM and control the pipeline.

These generally include the things that have been traditionally passed on the cmdline. Ie:

``` yaml
namespace: MyApp.MyNameSpace
modeler : default # options are 'default' or 'composite'
output-folder : ./Generated
azure-arm: true # 'azure-arm' is a declaration that the swagger is an Azure arm resource (not specified as part of the generator name.)
input-file:
  - swagger/MySpec.json
  - swagger/MySpec2.json
```

### Per-language Settings
At the top-level of the Literate Configuration document, you may also specify a language, which performs two things:

- includes that language generator as a language target in the pipeline.
- allows specifying/overriding settings on a per-language basis.

``` yaml
csharp: # just having a 'csharp' node enables the use of the csharp generator.
  namespace: Microsoft.MyApp.MyNameSpace #override the namespace
  output-folder : $(output-folder)/csharp # relative to the global value.

ruby:
  namespace: Microsoft::Azure::MyApp::MyNameSpace # another alternative
  output-folder : $(output-folder)/ruby/sdk # relative to the global value.
```

### Swagger DOM Query Format
In order to make it possible to remove most of the AutoRest-specific extensions from
the Swagger DOM, it is necessary to be able to refer to one or more nodes in the
swagger document and apply options to those nodes.

#### Querying the swagger DOM.

In order to accurately query nodes in the Swagger DOM for a specific set, we have a JSON/YAML object that is used to specify what we're looking for.

The query is basically two things: the list of swagger documents and the nodes inside of those documents:

``` yaml
from: <swagger-document-selection> # based on swagger namespaces (aka, the swagger 'title')
where: <json-path-query>           # a JSONPath expression to select the nodes in the swagger DOM
```

If the `from` isn't set, the default is to apply the directive to all the Literate Swagger DOMs

If the `where` isn't set, the default is to apply the directive to all the nodes in the selected Literate Swagger DOMs

### Directives - global or per-language

Directives are nodes that change generation **behavior** based on the selection of a set of nodes in the Swagger DOM. See  [Swagger DOM Query Format](#Swagger-DOM-Query-Format)

Directives are specified as a collection of `directive` objects fall under the `directive:` setting.

A `directive` object appears as follows:

``` yaml
from: <swagger-document-selection> # based on swagger namespaces
where: <json-path-query>           # a JSONPath expression to select the nodes in the swagger DOM
set: <object>                      # an object that has a series of key-value settings to apply to the selected nodes.
<other-directive-targets> : <*>    # other directives that don't set properties on the node, but rather are directed towards parts of autorest.
```

If the `from` isn't set, the default is to apply the directive to all the Literate Swagger DOMs

If the `where` isn't set, the default is to apply the directive to all the nodes in the selected Literate Swagger DOMs

> Example: overriding a `method-group` name

``` yaml
directive: # an array of directive objects
  - from: My Spec # specify a specific document 'namespace' (aka title)
    where: $..[@operationId="blob_*"]
    set:
      method-group: Blobber # override the method-group for a given set of operations matching blob_*

csharp:
  directive:
    # change blob method group name to AzureBlob
    - from: My Spec # specify a specific document 'namespace' (aka title)
      where: $..[@operationId="blob_*"]
      set:
        method-group: AzureBlob # per-language (csharp) override for method-group name

    # change
    - from: My Spec # specify a specific document 'namespace' (aka title)
      where: $..[@operationId="glob_*_*"] # take nodes where it has more than one underscore
      transform:
        - mytransformer
```

``` js transformer=mytransformer
// assume that the nodes are given as a collection of nodes.
for( nodename in nodes ) {
  nodes[nodename].methodgroup = nodes[nodename].methodgroup.replace(/(glob_.*)_(.*)/ig,'AzureGlob_$1');
}

// return the nodes to the colllection.
return nodes;
```

> Example: disabling a validation for a couple of docs

``` yaml
directive:
  - from: # specify multiple document 'namespace's (aka title)
      - My API
      - SomeOther API
    suppress:
      - VE1025 # codes for validation suppression
      - VE1104
```

> Example: applying `x-ms` Swagger Extensions to the DOM:

``` yaml
directive:
  - where: definitions.myobject.properties.foo
    set:
      client-flatten: true    # you can omit the x-ms prefix, it's ok, we'll figure it out.
      x-ms-client-name: HELLO # or you can specify the x-ms prefix.
      enum:
        name: MyEnum
        modelAsString: false
```

In this example, rather than specifying the information in the swagger file (because it doesn't affect the wire data) we specify the extension usage as directives for code generation.

## AutoRest Settings

The collection of AutoRest settings that is currently available on the command line can be expressed in Literate Configuration.

#### Important additions:
The notion of the version/minimum/maximum version to use of AutoRest. The purpose of this is to get to the point where you don't have to ever actively install a given version of AutoRest.
Instead, you install any version of AutoRest that supports Literate Configuration, and if the configuration calls for a different version of AutoRest, we download and install AutoRest into a version-specific folder (in say `$env:AppData`...) and pass thru the work to that version.

Then, once you've installed AutoRest, you can use any arbitrary version by just specifying it.

#### Any-language settings

|Setting|Example|Purpose|
|-------|-------|-------|
|version|`version: 1.0.0-Nightly20170107` | Specify a specific version of AutoRest to use for the code generation (try to use `minimum-version` and `maximum-version` if possible) |
|minium-version|`version: 1.0` | Specify a minimum version of AutoRest to use for the code generation |
|maximum-version|`version: 1.999` | Specify a maximum version of AutoRest to use for the code generation |
|azure|`azure-arm:true` | specifies that that the generation is designed to create an Azure Resource Manager SDK |
|add-credentials| `add-credentials: true` | If true, the generated client includes a ServiceClientCredentials property and constructor parameter. Authentication behaviors are implemented by extending the ServiceClientCredentials type.|
|override-client-name| `override-client-name: MyClient ` |  Name to use for the generated client type. By default, uses the value of the 'Title' field from the Swagger input. |
|generation-mode| `generation-mode: ['rest-client', 'rest-server'] `| The code generation mode. Possible values: rest, rest-client, rest-server. Determines whether AutoRest generates the client or server side code for given spec.|
|header-text| `header-text: MIT` | Text to include as a header comment in generated files. Use NONE to suppress the default header. |
|input-file| `input-file: foo.json` | The location of the input specification. |
|modeler| `modeler: composite` |  The Modeler to use on the input. If not specified, defaults to Swagger.|
|models-name|`models-name: foo` |  Name to use for the generated client models namespace and folder name. Not supported by all code generators. |
|namespace|`namespace:Microsoft.Azure.MyLib`| The namespace to use for generated code.|
|output-folder| `output-folder: c:/output` | The location for generated files. If not specified, uses "Generated" as the default. |
|output-file| `output-file: foo.cs` | If set, will cause generated code to be output to a single file. Not supported by all code generators.|
|package-name|`package-name: somePackage`| Package name of then generated code package. Should be then names wanted for the package in then package manager. |
|package-version|`package-version: 1.0.5`| Package version of then generated code package. Should be then version wanted for the package in then package manager.|
|payload-flatteningthreshold|`payload-flatteningthreshold: 2`| The maximum number of properties in the request body. If the number of properties in the request body is less than or equal to this value, these properties will be represented as method arguments. |

#### CSharp Settings
|Setting|Example|Purpose|
|-------|-------|-------|
|disable-simplifier| `disable-simplfier:true` | Disables c# post-codegeneration simplifier|
|internal-constructors| `internal-constructors: true` | Indicates whether ctor needs to be generated with internal protection level. |
|sync-methods| `sync-methods: true `| Specifies mode for generating sync wrappers. |
|use-date-time-offset| `use-date-time-offset: true` | Indicates whether to use DateTimeOffset instead of DateTime to model date-time types |

#### NodeJS Settings:
|Setting|Example|Purpose|
|-------|-------|-------|
|disable-typescript|`disable-typescript: true` | Disables TypeScript generation. |


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Les Hyménomycètes ou description de tous les champignons (fungi) qui croissent en France (Alençon) 34 (1874)

#### Original name
Amanita caesarea var. aurantia Gillet

### Remarks
null

redpajama_set_name: RedPajamaGithub


text:
"""
Test that two targets with the same name generates an error.
"""

import os
import sys

import TestGyp
import TestCmd

# TODO(sbc): Remove the use of match_re below, done because scons
# error messages were not consistent with other generators.
# Also remove input.py:generator_wants_absolute_build_file_paths.

test = TestGyp.TestGyp()

stderr = ('gyp: Duplicate target definitions for '
          '.*duplicate_targets.gyp:foo#target\n')
test.run_gyp('duplicate_targets.gyp', status=1, stderr=stderr,
             match=TestCmd.match_re)

stderr = ('.*: Unable to find targets in build file .*missing_targets.gyp.*')
test.run_gyp('missing_targets.gyp', status=1, stderr=stderr,
             match=TestCmd.match_re_dotall)

stderr = ('gyp: rule bar exists in duplicate, target '
          '.*duplicate_rule.gyp:foo#target\n')
test.run_gyp('duplicate_rule.gyp', status=1, stderr=stderr,
             match=TestCmd.match_re)

stderr = ("gyp: Key 'targets' repeated at level 1 with key path '' while "
          "reading .*duplicate_node.gyp.*")
test.run_gyp('duplicate_node.gyp', '--check', status=1, stderr=stderr,
             match=TestCmd.match_re_dotall)

stderr = (".*target0.*target1.*target2.*target0.*")
test.run_gyp('dependency_cycle.gyp', status=1, stderr=stderr,
             match=TestCmd.match_re_dotall)

stderr = (".*file_cycle0.*file_cycle1.*file_cycle0.*")
test.run_gyp('file_cycle0.gyp', status=1, stderr=stderr,
             match=TestCmd.match_re_dotall)

stderr = 'gyp: Duplicate basenames in sources section, see list above\n'
test.run_gyp('duplicate_basenames.gyp', status=1, stderr=stderr)

# Check if '--no-duplicate-basename-check' works.
if ((test.format == 'make' and sys.platform == 'darwin') or
    (test.format == 'msvs' and
        int(os.environ.get('GYP_MSVS_VERSION', 2010)) < 2010)):
  stderr = 'gyp: Duplicate basenames in sources section, see list above\n'
  test.run_gyp('duplicate_basenames.gyp', '--no-duplicate-basename-check',
               status=1, stderr=stderr)
else:
  test.run_gyp('duplicate_basenames.gyp', '--no-duplicate-basename-check')

stderr = ("gyp: Dependency '.*missing_dep.gyp:missing.gyp#target' not found "
          "while trying to load target .*missing_dep.gyp:foo#target\n")
test.run_gyp('missing_dep.gyp', status=1, stderr=stderr,
             match=TestCmd.match_re)

# Make sure invalid <!() command invocations say what command it was and
# mention the gyp file name. Use a "random" command name to trigger an ENOENT.
stderr = (".*invalid-command-name-egtyevNif3.*netDurj9.*missing_command.gyp.*")
test.run_gyp('missing_command.gyp', status=1, stderr=stderr,
             match=TestCmd.match_re_dotall)

# Make sure <!() commands that error out result in a message that mentions
# the command and gyp file name
stderr = (".*python.*-c.*import sys.*sys.exit.*3.*error_command.gyp.*")
test.run_gyp('error_command.gyp', status=1, stderr=stderr,
             match=TestCmd.match_re_dotall)

test.pass_test()


text:
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type

from ansible.errors import AnsibleError
from ansible.module_utils.gcp_utils import GcpSession

class GcpMockModule(object):
    def __init__(self, params):
        self.params = params

    def fail_json(self, *args, **kwargs):
        raise AnsibleError(kwargs['msg'])

class GcpKmsFilter():
    def run(self, method, **kwargs):
        params = {
            'ciphertext': kwargs.get('ciphertext', None),
            'plaintext': kwargs.get('plaintext', None),
            'additional_authenticated_data': kwargs.get('additional_authenticated_data', None),
            'key_ring': kwargs.get('key_ring', None),
            'crypto_key': kwargs.get('crypto_key', None),
            'projects': kwargs.get('projects', None),
            'scopes': kwargs.get('scopes', None),
            'locations': kwargs.get('locations', 'global'),
            'auth_kind': kwargs.get('auth_kind', None),
            'service_account_file': kwargs.get('service_account_file', None),
            'service_account_email': kwargs.get('service_account_email', None),
        }
        if not params['scopes']:
            params['scopes'] = ['https://www.googleapis.com/auth/cloudkms']
        fake_module = GcpMockModule(params)
        if method == "encrypt":
            return self.kms_encrypt(fake_module)
        elif method == "decrypt":
            return self.kms_decrypt(fake_module)

    def kms_decrypt(self, module):
        payload = {"ciphertext": module.params['ciphertext']}

        if module.params['additional_authenticated_data']:
            payload['additionalAuthenticatedData'] = module.params['additional_authenticated_data']

        auth = GcpSession(module, 'cloudkms')
        url = "https://cloudkms.googleapis.com/v1/projects/{projects}/locations/{locations}/" \
            "keyRings/{key_ring}/cryptoKeys/{crypto_key}:decrypt".format(**module.params)
        response = auth.post(url, body=payload)
        return response.json()['plaintext']

    def kms_encrypt(self, module):
        payload = {"plaintext": module.params['plaintext']}

        if module.params['additional_authenticated_data']:
            payload['additionalAuthenticatedData'] = module.params['additional_authenticated_data']

        auth = GcpSession(module, 'cloudkms')
        url = "https://cloudkms.googleapis.com/v1/projects/{projects}/locations/{locations}/" \
            "keyRings/{key_ring}/cryptoKeys/{crypto_key}:encrypt".format(**module.params)
        response = auth.post(url, body=payload)
        return response.json()['ciphertext']

def gcp_kms_encrypt(plaintext, **kwargs):
    return GcpKmsFilter().run('encrypt', plaintext=plaintext, **kwargs)

def gcp_kms_decrypt(ciphertext, **kwargs):
    return GcpKmsFilter().run('decrypt', ciphertext=ciphertext, **kwargs)

class FilterModule(object):

    def filters(self):
        return {
            'gcp_kms_encrypt': gcp_kms_encrypt,
            'gcp_kms_decrypt': gcp_kms_decrypt
        }


text:
/***********************************************************************
created:    2014-08-22
author:     Luca Ebach <lucaebach@gmail.com>
*************************************************************************/
/***************************************************************************
*   Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team
*
*   Permission is hereby granted, free of charge, to any person obtaining
*   a copy of this software and associated documentation files (the
*   "Software"), to deal in the Software without restriction, including
*   without limitation the rights to use, copy, modify, merge, publish,
*   distribute, sublicense, and/or sell copies of the Software, and to
*   permit persons to whom the Software is furnished to do so, subject to
*   the following conditions:
*
*   The above copyright notice and this permission notice shall be
*   included in all copies or substantial portions of the Software.
*
*   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
*   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
*   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
*   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
*   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
*   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
*   OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
#ifndef _TabControlSample_h_
#define _TabControlSample_h_

#include "Sample.h"

using namespace CEGUI;

#define SKIN "TaharezLook"
// for this to work you'll have to change the .layout files
//#define SKIN "WindowsLook"

// Sample sub-class for ListboxTextItem that auto-sets the selection brush
// image.  This saves doing it manually every time in the code.
class TabControlListItem : public ListboxTextItem
{
public:
    TabControlListItem(const String& text) : ListboxTextItem(text)
    {
        setSelectionBrushImage(SKIN "/MultiListSelectionBrush");
    }
};

// Sample class
class TabControlSample : public Sample
{
public:
    TabControlSample();
    virtual ~TabControlSample() {}

    // method to initialse the samples windows and events.
    bool initialise(CEGUI::GUIContext* guiContext) override;

    // method to perform any required cleanup operations.
    void deinitialise() override;

    void refreshPageList();
    bool handleTabPanePos(const EventArgs& e);
    bool handleTabHeight(const EventArgs& e);
    bool handleTabPadding(const EventArgs& e);
    bool handleAddTab(const EventArgs&);
    bool handleGoto(const EventArgs&);
    bool handleShow(const EventArgs&);
    bool handleDel(const EventArgs&);

protected:
    TabControl* getTabControl(Window* root);
    ListWidget* getPageListWidget(Window* root);

    CEGUI::GUIContext* d_guiContext;
};

#endif // _TabControlSample_h_


text:
package org.apache.camel.component.xmlsecurity.api;

/**
 * This exception is thrown if the verification of an XML signature fails
 * because the signature value is invalid.
 */
public class XmlSignatureInvalidValueException extends XmlSignatureInvalidException {

    private static final long serialVersionUID = 1L;

    public XmlSignatureInvalidValueException(String message, Throwable cause) {
        super(message, cause);
    }

    public XmlSignatureInvalidValueException(String message) {
        super(message);
    }

}


text:
/*
* Inicia el servidor de la aplicacion. Hace el render (genera el html) que se envia al navegador.
**/
import http from 'http'
import React from 'react'
// React-dom tiene metodos para usar react en el servidor. Renderiza la aplicacion a un string en htlm
import { renderToString, renderToStaticMarkup } from 'react-dom/server'
import { StaticRouter } from 'react-router-dom'
import Pages from './pages/containers/Pages.jsx'

import Layout from './pages/components/Layout.jsx'

function requestHandler(req, res) {
  const context = {};
  const html = renderToString(
    <StaticRouter location={req.url} context={context}>
      <Pages/>
    </StaticRouter>
  );

  res.setHeader('Content-Type', 'text/html')

  if (context.url) {
  	res.writeHead(301, {
  		Location: context.url,
  	});
  	res.end();
  }
  res.write(
    renderToStaticMarkup(
      <Layout
        title="Aplication"
        content={html}
      />
    )
  )
  res.end()
  console.log('Server in port 3000')

}

const server = http.createServer(requestHandler);

server.listen(3000);


text:
#if !(NET35 || NET20 || WINDOWS_PHONE)
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;

namespace Newtonsoft.Json.Utilities
{
  internal class DynamicProxy<T>
  {
    public virtual IEnumerable<string> GetDynamicMemberNames(T instance)
    {
      return new string[0];
    }

    public virtual bool TryBinaryOperation(T instance, BinaryOperationBinder binder, object arg, out object result)
    {
      result = null;
      return false;
    }

    public virtual bool TryConvert(T instance, ConvertBinder binder, out object result)
    {
      result = null;
      return false;
    }

    public virtual bool TryCreateInstance(T instance, CreateInstanceBinder binder, object[] args, out object result)
    {
      result = null;
      return false;
    }

    public virtual bool TryDeleteIndex(T instance, DeleteIndexBinder binder, object[] indexes)
    {
      return false;
    }

    public virtual bool TryDeleteMember(T instance, DeleteMemberBinder binder)
    {
      return false;
    }

    public virtual bool TryGetIndex(T instance, GetIndexBinder binder, object[] indexes, out object result)
    {
      result = null;
      return false;
    }

    public virtual bool TryGetMember(T instance, GetMemberBinder binder, out object result)
    {
      result = null;
      return false;
    }

    public virtual bool TryInvoke(T instance, InvokeBinder binder, object[] args, out object result)
    {
      result = null;
      return false;
    }

    public virtual bool TryInvokeMember(T instance, InvokeMemberBinder binder, object[] args, out object result)
    {
      result = null;
      return false;
    }

    public virtual bool TrySetIndex(T instance, SetIndexBinder binder, object[] indexes, object value)
    {
      return false;
    }

    public virtual bool TrySetMember(T instance, SetMemberBinder binder, object value)
    {
      return false;
    }

    public virtual bool TryUnaryOperation(T instance, UnaryOperationBinder binder, out object result)
    {
      result = null;
      return false;
    }
  }
}
#endif


text:
class ARDrone2;
class Bebop;

class dronevisitor
{
	public:
		virtual ~dronevisitor() {}
		virtual drone::error visit(std::shared_ptr<ARDrone2> d) = 0;
		virtual drone::error visit(std::shared_ptr<Bebop> d) = 0;
};

#endif


text:
Shy is a small tool for managing shell (bash/zsh) confiuration that is split into several files. A "plugin" is merely a file with plain old shell aliases, functions, variables, or anything else - they work the same whether or not Shy is installed.

Using Shy allows you to do the following:

 * Organize your shell config into groups of related functionality (plugins) in a lightweight way
 * Quickly find where things (functions, aliases, variables) are defined
 * Open your editor with the appropriate file, to make a quick change
 * And (not much) more!

[Installation](#installation)
[Usage](#usage)
[Why Use This?](#why)
[Command Reference](#command-reference)
[Advanced Configuration](#advanced-configuration)
[Credits](#credits)

## Installation

1. Download the [shy script](https://raw2.github.com/aaronroyer/shy/master/shy) and place it somewhere on your PATH (make sure it is executable)
1. Add ```eval "$(shy init)"``` in .bashrc (or .zshrc if using zsh), somewhere after configuring your PATH
1. Add some plugins! See [usage](#usage) for more info.

## Usage

Once you're installed then you can used ```shy load``` to load plugin files. You will usually do this in your .bashrc/.zshrc file. Make sure Shy is initialized before loading plugins.

```
shy load ~/path/to/plugin.sh
```
Or maybe something like

```
for plugin in ~/.shell_plugins/* do
  shy load $plugin
done
```

Shy will source the files as normal, but also record all of the aliases, functions, and variables first defined in the file.

Now you can view a list of your plugins. The name of a plugin is the base file name with any extension removed.

![Shy printing loaded plugins](doc/list.png)

You can examine the details of a plugin.

![Shy printing the contents of a plugin](doc/show.png)

Use ```which``` if you want to know where something is defined.

```
 $ shy which glb
 glb is a function in the plugin git
 $ shy which gd
 gs is an alias in the plugin git
```

You can open a plugin (or anything else) in your EDITOR.

```
 $ shy edit git
 # (opens the git plugin source file in your editor)

 $ shy edit gs
 # (opens the git plugin source file, where the alias gs is defined)
```

## Why Use This?

You should try Shy if you like to maintain your own shell config, want to split things into separate files, want to be able to keep track of it all and make tweaks with ease, and don't want something heavy to do it.

If you want lots of crazy/awesome power-user features you might like something like [composure](https://github.com/erichs/composure) instead. If you use zsh and just want to dump a ton of functionality that someone else wrote into your shell and be done with it then you could use [oh-my-zsh](https://github.com/robbyrussell/oh-my-zsh).

I prefer to keep a set of often-used tools that I've put together myself (with little bits I've stolen) and manage them with simple tools.

## Command Reference

#### shy load <plugin_path>

Load a plugin file. This simply sources the file and Shy records the aliases, functions, and variables first defined in the file.

This should normally be used in your shell configuration files (like .bashrc or .zshrc) and not interactively.

---

#### shy list

List the plugins that that have previously been loaded with ```load```. Names of plugins are the plugin file names with any extension removed.

For example:

```~/.shell_plugins/git.sh``` is a plugin named ```git```

```~/.shell_plugins/rails``` is a plugin named ```rails```

---

#### shy show \<plugin_name\>

Show the details for the plugin. This prints the path of the plugin file, and lists the aliases, functions, and variables defined in the plugin.

---

#### shy edit \<plugin_or_other_item_name\>

Open a plugin file in your editor. When given a plugin name, the plugin file is opened. When given the name of an alias, function, or variable the plugin file where that item is defined is opened in the editor.

To find an editor to use, Shy first checks the variable ```SHY_EDITOR```, then ```EDITOR```, then falls back on ``vim```.

---

#### shy which \<item_name\>

Print what plugin an alias, function, or variable is defined in.

---

#### shy help \[\<command_name\>\]

Prints help for a specific command, or general help with no command name given.

<a name="advanced-configuration"/>
## Advanced Configuration

If you want everything to work even if Shy is not installed (like if you sync your dotfiles but don't sync Shy along with it) then you can add a fallback function that simply sources your plugin files. This way your shell works the same even if ```shy``` isn't on your ```PATH```.

```
if which shy &> /dev/null; then
  eval "$(shy init)"
else
  shy() { [ "$1" = 'load' ] && source "$2"; }
fi
```

### Environment Variables

```SHY_EDITOR``` - sets the editor to use with Shy

```SHY_DEBUG``` - prints debug info to standard out when loading plugins

```SHY_CACHE_DIR``` - Shy caches plugins in ```~/.shy_plugin_cache```for faster startup; this overrides the default location

```SHY_NO_COLOR``` - Set this to anything not empty to prevent Shy from coloring any output

## Credits

Shy uses [Bats](https://github.com/sstephenson/bats) for automated testing. You should check it out if you're doing anything non-trivial with Bash.

## License

Shy is MIT licensed


text:
shared_examples_for "A controller that has performance routes" do
  describe "#perf_chart_chooser" do
    it "routes with GET" do
      expect(get("/#{controller_name}/perf_chart_chooser")).to route_to("#{controller_name}#perf_chart_chooser")
    end

    it "routes with POST" do
      expect(post("/#{controller_name}/perf_chart_chooser")).to route_to("#{controller_name}#perf_chart_chooser")
    end
  end

  describe "#wait_for_task" do
    it "routes with POST" do
      expect(post("/#{controller_name}/wait_for_task")).to route_to("#{controller_name}#wait_for_task")
    end
  end
end


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Threading.Tasks;
using Dapper;
using MicroOrm.Dapper.Repositories.Extensions;
using MicroOrm.Dapper.Repositories.SqlGenerator;

namespace MicroOrm.Dapper.Repositories
{
    /// <summary>
    ///     Base Repository
    /// </summary>
    public partial class ReadOnlyDapperRepository<TEntity>
        where TEntity : class
    {
        /// <summary>
        ///     Execute Join query
        /// </summary>
        protected virtual IEnumerable<TEntity> ExecuteJoinQuery<TChild1, TChild2, TChild3, TChild4, TChild5, TChild6>(
            SqlQuery sqlQuery,
            IDbTransaction transaction,
            params Expression<Func<TEntity, object>>[] includes)
        {
            if (!SqlGenerator.KeySqlProperties.Any())
                throw new NotSupportedException("Join doesn't support without [Key] attribute");

            var type = typeof(TEntity);

            var childProperties = new List<PropertyInfo>();
            var childKeyProperties = new List<PropertyInfo>();
            var keyProperties = SqlGenerator.KeySqlProperties.Select(q => q.PropertyInfo).ToArray();

            foreach (var s in includes)
            {
                var prop = ExpressionHelper.GetPropertyName(s);
                var childProp = type.GetProperty(prop);

                if (childProp == null)
                    continue;

                childProperties.Add(childProp);
                var childType = childProp.PropertyType.IsGenericType ? childProp.PropertyType.GenericTypeArguments[0] : childProp.PropertyType;
                var properties = childType.FindClassProperties().Where(ExpressionHelper.GetPrimitivePropertiesPredicate());
                childKeyProperties.AddRange(properties.Where(p => p.GetCustomAttributes<KeyAttribute>().Any()));
            }

            if (!childKeyProperties.Any())
                throw new NotSupportedException("Join doesn't support without [Key] attribute");

            var lookup = new Dictionary<object, TEntity>();
            const bool buffered = true;

            var spiltOn = string.Join(",", childKeyProperties.Select(q => q.Name));

            switch (includes.Length)
            {
                case 1:
                    Connection.Query<TEntity, TChild1, TEntity>(sqlQuery.GetSql(), (entity, child1) =>
                            EntityJoinMapping<TChild1, TChild2, TChild3, TChild4, TChild5, TChild6>(lookup, keyProperties, childKeyProperties, childProperties, entity, child1),
                        sqlQuery.Param, transaction, buffered, spiltOn);
                    break;

                case 2:
                    Connection.Query<TEntity, TChild1, TChild2, TEntity>(sqlQuery.GetSql(), (entity, child1, child2) =>
                            EntityJoinMapping<TChild1, TChild2, TChild3, TChild4, TChild5, TChild6>(lookup, keyProperties, childKeyProperties, childProperties, entity, child1,
                                child2),
                        sqlQuery.Param, transaction, buffered, spiltOn);
                    break;

                case 3:
                    Connection.Query<TEntity, TChild1, TChild2, TChild3, TEntity>(sqlQuery.GetSql(), (entity, child1, child2, child3) =>
                            EntityJoinMapping<TChild1, TChild2, TChild3, TChild4, TChild5, TChild6>(lookup, keyProperties, childKeyProperties, childProperties, entity, child1,
                                child2, child3),
                        sqlQuery.Param, transaction, buffered, spiltOn);
                    break;

                case 4:
                    Connection.Query<TEntity, TChild1, TChild2, TChild3, TChild4, TEntity>(sqlQuery.GetSql(), (entity, child1, child2, child3, child4) =>
                            EntityJoinMapping<TChild1, TChild2, TChild3, TChild4, TChild5, TChild6>(lookup, keyProperties, childKeyProperties, childProperties, entity, child1,
                                child2, child3, child4),
                        sqlQuery.Param, transaction, buffered, spiltOn);
                    break;

                case 5:
                    Connection.Query<TEntity, TChild1, TChild2, TChild3, TChild4, TChild5, TEntity>(sqlQuery.GetSql(), (entity, child1, child2, child3, child4, child5) =>
                            EntityJoinMapping<TChild1, TChild2, TChild3, TChild4, TChild5, TChild6>(lookup, keyProperties, childKeyProperties, childProperties, entity, child1,
                                child2, child3, child4, child5),
                        sqlQuery.Param, transaction, buffered, spiltOn);
                    break;

                case 6:
                    Connection.Query<TEntity, TChild1, TChild2, TChild3, TChild4, TChild5, TChild6, TEntity>(sqlQuery.GetSql(),
                        (entity, child1, child2, child3, child4, child5, child6) =>
                            EntityJoinMapping<TChild1, TChild2, TChild3, TChild4, TChild5, TChild6>(lookup, keyProperties, childKeyProperties, childProperties, entity, child1,
                                child2, child3, child4, child5, child6),
                        sqlQuery.Param, transaction, buffered, spiltOn);
                    break;

                default:
                    throw new NotSupportedException();
            }

            return lookup.Values;
        }

        /// <summary>
        ///     Execute Join query
        /// </summary>
        protected virtual async Task<IEnumerable<TEntity>> ExecuteJoinQueryAsync<TChild1, TChild2, TChild3, TChild4, TChild5, TChild6>(
            SqlQuery sqlQuery,
            IDbTransaction transaction,
            params Expression<Func<TEntity, object>>[] includes)
        {

            if (!SqlGenerator.KeySqlProperties.Any())
                throw new NotSupportedException("Join doesn't support without [Key] attribute");

            var type = typeof(TEntity);

            var childProperties = new List<PropertyInfo>();
            var childKeyProperties = new List<PropertyInfo>();
            var keyProperties = SqlGenerator.KeySqlProperties.Select(q => q.PropertyInfo).ToArray();
            foreach (var s in includes)
            {
                var prop = ExpressionHelper.GetPropertyName(s);
                var childProp = type.GetProperty(prop);

                if (childProp == null)
                    continue;

                childProperties.Add(childProp);
                var childType = childProp.PropertyType.IsGenericType ? childProp.PropertyType.GenericTypeArguments[0] : childProp.PropertyType;
                var properties = childType.FindClassProperties().Where(ExpressionHelper.GetPrimitivePropertiesPredicate());
                childKeyProperties.AddRange(properties.Where(p => p.GetCustomAttributes<KeyAttribute>().Any()));
            }

            if (!childKeyProperties.Any())
                throw new NotSupportedException("Join doesn't support without [Key] attribute");

            var lookup = new Dictionary<object, TEntity>();
            const bool buffered = true;

            var spiltOn = string.Join(",", childKeyProperties.Select(q => q.Name));

            switch (includes.Length)
            {
                case 1:
                    await Connection.QueryAsync<TEntity, TChild1, TEntity>(sqlQuery.GetSql(), (entity, child1) =>
                            EntityJoinMapping<TChild1, TChild2, TChild3, TChild4, TChild5, TChild6>(lookup, keyProperties, childKeyProperties, childProperties, entity, child1),
                        sqlQuery.Param, transaction, buffered, spiltOn);
                    break;

                case 2:
                    await Connection.QueryAsync<TEntity, TChild1, TChild2, TEntity>(sqlQuery.GetSql(), (entity, child1, child2) =>
                            EntityJoinMapping<TChild1, TChild2, TChild3, TChild4, TChild5, TChild6>(lookup, keyProperties, childKeyProperties, childProperties, entity, child1,
                                child2),
                        sqlQuery.Param, transaction, buffered, spiltOn);
                    break;

                case 3:
                    await Connection.QueryAsync<TEntity, TChild1, TChild2, TChild3, TEntity>(sqlQuery.GetSql(), (entity, child1, child2, child3) =>
                            EntityJoinMapping<TChild1, TChild2, TChild3, TChild4, TChild5, TChild6>(lookup, keyProperties, childKeyProperties, childProperties, entity, child1,
                                child2, child3),
                        sqlQuery.Param, transaction, buffered, spiltOn);
                    break;

                case 4:
                    await Connection.QueryAsync<TEntity, TChild1, TChild2, TChild3, TChild4, TEntity>(sqlQuery.GetSql(), (entity, child1, child2, child3, child4) =>
                            EntityJoinMapping<TChild1, TChild2, TChild3, TChild4, TChild5, TChild6>(lookup, keyProperties, childKeyProperties, childProperties, entity, child1,
                                child2, child3, child4),
                        sqlQuery.Param, transaction, buffered, spiltOn);
                    break;

                case 5:
                    await Connection.QueryAsync<TEntity, TChild1, TChild2, TChild3, TChild4, TChild5, TEntity>(sqlQuery.GetSql(),
                        (entity, child1, child2, child3, child4, child5) =>
                            EntityJoinMapping<TChild1, TChild2, TChild3, TChild4, TChild5, TChild6>(lookup, keyProperties, childKeyProperties, childProperties, entity, child1,
                                child2, child3, child4, child5),
                        sqlQuery.Param, transaction, buffered, spiltOn);
                    break;

                case 6:
                    await Connection.QueryAsync<TEntity, TChild1, TChild2, TChild3, TChild4, TChild5, TChild6, TEntity>(sqlQuery.GetSql(),
                        (entity, child1, child2, child3, child4, child5, child6) =>
                            EntityJoinMapping<TChild1, TChild2, TChild3, TChild4, TChild5, TChild6>(lookup, keyProperties, childKeyProperties, childProperties, entity, child1,
                                child2, child3, child4, child5, child6),
                        sqlQuery.Param, transaction, buffered, spiltOn);
                    break;

                default:
                    throw new NotSupportedException();
            }

            return lookup.Values;
        }

        private static TEntity EntityJoinMapping<TChild1, TChild2, TChild3, TChild4, TChild5, TChild6>(IDictionary<object, TEntity> lookup, PropertyInfo[] keyProperties,
            IList<PropertyInfo> childKeyProperties, IList<PropertyInfo> childProperties, TEntity entity, params object[] childs)
        {
            var compositeKeyProperty = string.Join("|", keyProperties.Select(q => q.GetValue(entity).ToString()));

            if (!lookup.TryGetValue(compositeKeyProperty, out var target))
                lookup.Add(compositeKeyProperty, target = entity);

            for (var i = 0; i < childs.Length; i++)
            {
                var child = childs[i];
                var childProperty = childProperties[i];
                var childKeyProperty = childKeyProperties[i];

                if (childProperty.PropertyType.IsGenericType)
                {
                    var list = (IList) childProperty.GetValue(target);
                    if (list == null)
                    {
                        switch (i)
                        {
                            case 0:
                                list = new List<TChild1>();
                                break;

                            case 1:
                                list = new List<TChild2>();
                                break;

                            case 2:
                                list = new List<TChild3>();
                                break;

                            case 3:
                                list = new List<TChild4>();
                                break;

                            case 4:
                                list = new List<TChild5>();
                                break;

                            case 5:
                                list = new List<TChild6>();
                                break;

                            default:
                                throw new NotSupportedException();
                        }

                        childProperty.SetValue(target, list);
                    }

                    if (child == null)
                        continue;

                    var childKey = childKeyProperty.GetValue(child);
                    var exist = (from object item in list select childKeyProperty.GetValue(item)).Contains(childKey);
                    if (!exist)
                        list.Add(child);
                }
                else
                {
                    childProperty.SetValue(target, child);
                }
            }

            return target;
        }

        /// <summary>
        ///     Dummy type for excluding from multi-map
        /// </summary>
        // ReSharper disable once ClassNeverInstantiated.Local
        private class DontMap
        {
        }
    }
}


text:
import re
import os
from setuptools import setup

VERSION = re.search("__version__ = '([^']+)'", open(
    os.path.join(os.path.dirname(__file__), 'pynuts', '__init__.py')
).read().strip()).group(1)

setup(
    name="Pynuts",
    author="Kozea",
    version=VERSION,
    url="http://www.pynuts.org/",
    license="BSD",
    platforms="Any",
    packages=["pynuts"],
    package_data={'pynuts': ['templates/_pynuts/*.jinja2',
                             'static/javascript/*.js']}
)


text:
/*
 * CoordinateConverter.h
 *
 *  Created on: Mar 11, 2015
 *      Author: dwarf
 */

#ifndef COORDINATECONVERTER_H_
#define COORDINATECONVERTER_H_

#include "GraphicsOptions.h"
#include "Warp.h"

// The user has to free the returned array
float *screenToWorldSpace(float x, float y);

// The user has to free the returned array
float *worldToScreenSpace(float x, float y);

// The user has to free the returned array
float *pixelToScreenSpace(int x, int y);

// The user has to free the returned array
int *screenToPixelSpace(float x, float y);

// The user has to free the returned array
float *alignWorldToBlockSpace(float x, float y);

// The user has to free the returned array
int *screenToScissorSpace(float x, float y);

#endif /* COORDINATECONVERTER_H_ */


text:
@interface ComGoogleCommonIoCountingOutputStream () {
 @public
  jlong count_;
}

@end

@implementation ComGoogleCommonIoCountingOutputStream

- (instancetype)initWithJavaIoOutputStream:(JavaIoOutputStream *)outArg {
  ComGoogleCommonIoCountingOutputStream_initWithJavaIoOutputStream_(self, outArg);
  return self;
}

- (jlong)getCount {
  return count_;
}

- (void)writeWithByteArray:(IOSByteArray *)b
                   withInt:(jint)off
                   withInt:(jint)len {
  [((JavaIoOutputStream *) nil_chk(out_)) writeWithByteArray:b withInt:off withInt:len];
  count_ += len;
}

- (void)writeWithInt:(jint)b {
  [((JavaIoOutputStream *) nil_chk(out_)) writeWithInt:b];
  count_++;
}

- (void)close {
  [((JavaIoOutputStream *) nil_chk(out_)) close];
}

+ (const J2ObjcClassInfo *)__metadata {
  static J2ObjcMethodInfo methods[] = {
    { NULL, NULL, 0x1, -1, 0, -1, -1, -1, -1 },
    { NULL, "J", 0x1, -1, -1, -1, -1, -1, -1 },
    { NULL, "V", 0x1, 1, 2, 3, -1, -1, -1 },
    { NULL, "V", 0x1, 1, 4, 3, -1, -1, -1 },
    { NULL, "V", 0x1, -1, -1, 3, -1, -1, -1 },
  };
  #pragma clang diagnostic push
  #pragma clang diagnostic ignored "-Wobjc-multiple-method-names"
  methods[0].selector = @selector(initWithJavaIoOutputStream:);
  methods[1].selector = @selector(getCount);
  methods[2].selector = @selector(writeWithByteArray:withInt:withInt:);
  methods[3].selector = @selector(writeWithInt:);
  methods[4].selector = @selector(close);
  #pragma clang diagnostic pop
  static const J2ObjcFieldInfo fields[] = {
    { "count_", "J", .constantValue.asLong = 0, 0x2, -1, -1, -1, -1 },
  };
  static const void *ptrTable[] = { "LJavaIoOutputStream;", "write", "[BII", "LJavaIoIOException;", "I" };
  static const J2ObjcClassInfo _ComGoogleCommonIoCountingOutputStream = { "CountingOutputStream", "com.google.common.io", ptrTable, methods, fields, 7, 0x11, 5, 1, -1, -1, -1, -1, -1 };
  return &_ComGoogleCommonIoCountingOutputStream;
}

@end

void ComGoogleCommonIoCountingOutputStream_initWithJavaIoOutputStream_(ComGoogleCommonIoCountingOutputStream *self, JavaIoOutputStream *outArg) {
  JavaIoFilterOutputStream_initWithJavaIoOutputStream_(self, ComGoogleCommonBasePreconditions_checkNotNullWithId_(outArg));
}

ComGoogleCommonIoCountingOutputStream *new_ComGoogleCommonIoCountingOutputStream_initWithJavaIoOutputStream_(JavaIoOutputStream *outArg) {
  J2OBJC_NEW_IMPL(ComGoogleCommonIoCountingOutputStream, initWithJavaIoOutputStream_, outArg)
}

ComGoogleCommonIoCountingOutputStream *create_ComGoogleCommonIoCountingOutputStream_initWithJavaIoOutputStream_(JavaIoOutputStream *outArg) {
  J2OBJC_CREATE_IMPL(ComGoogleCommonIoCountingOutputStream, initWithJavaIoOutputStream_, outArg)
}

J2OBJC_CLASS_TYPE_LITERAL_SOURCE(ComGoogleCommonIoCountingOutputStream)


text:
package org.sakuli.loader;

import net.sf.sahi.report.Report;
import net.sf.sahi.rhino.RhinoScriptRunner;
import org.sakuli.actions.screenbased.ScreenshotActions;
import org.sakuli.actions.settings.ScreenBasedSettings;
import org.sakuli.datamodel.TestCase;
import org.sakuli.datamodel.TestCaseStep;
import org.sakuli.datamodel.TestSuite;
import org.sakuli.datamodel.actions.ImageLib;
import org.sakuli.datamodel.actions.Screen;
import org.sakuli.datamodel.properties.ActionProperties;
import org.sakuli.datamodel.properties.SahiProxyProperties;
import org.sakuli.datamodel.properties.SakuliProperties;
import org.sakuli.datamodel.properties.TestSuiteProperties;
import org.sakuli.exceptions.SakuliCheckedException;
import org.sakuli.exceptions.SakuliExceptionHandler;
import org.sakuli.services.cipher.CipherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.nio.file.Path;

/**
 * Loads all necessary objects for the {@link org.sakuli.actions.screenbased.ScreenshotActions}.
 *
 * @author tschneck Date: 18.10.13
 */
@Component
public class ScreenActionLoaderImpl implements ScreenActionLoader {

    @Qualifier(BaseActionLoaderImpl.QUALIFIER)
    @Autowired
    private BaseActionLoader baseLoader;

    @Autowired
    private ScreenBasedSettings settings;
    @Autowired
    private ScreenshotActions screenshotActions;
    @Autowired
    private Screen screen;

    @Override
    public Screen getScreen() {
        return screen;
    }

    public void setScreen(Screen screen) {
        this.screen = screen;
    }

    @Override
    public ScreenshotActions getScreenshotActions() {
        return screenshotActions;
    }

    public void setScreenshotActions(ScreenshotActions screenshotActions) {
        this.screenshotActions = screenshotActions;
    }

    @Override
    public BaseActionLoader getBaseLoader() {
        return baseLoader;
    }

    public void setBaseLoader(BaseActionLoader baseLoader) {
        this.baseLoader = baseLoader;
    }

    @Override
    public void loadSettingDefaults() {
        getSettings().setDefaults();
    }

    @Override
    public ScreenBasedSettings getSettings() {
        return settings;
    }

    public void setSettings(ScreenBasedSettings settings) {
        this.settings = settings;
    }

    @Override
    public CipherService getCipherService() {
        return baseLoader.getCipherService();
    }

    @Override
    public void init(String testCaseID, String... imagePaths) {
        baseLoader.init(testCaseID, imagePaths);
    }

    @Override
    public void init(String testCaseID, Path... imagePaths) {
        baseLoader.init(testCaseID, imagePaths);
    }

    @Override
    public void addImagePaths(Path... imagePaths) throws SakuliCheckedException {
        baseLoader.addImagePaths(imagePaths);
    }

    @Override
    public SakuliProperties getSakuliProperties() {
        return baseLoader.getSakuliProperties();
    }

    @Override
    public ActionProperties getActionProperties() {
        return baseLoader.getActionProperties();
    }

    @Override
    public SahiProxyProperties getSahiProxyProperties() {
        return baseLoader.getSahiProxyProperties();
    }

    @Override
    public TestSuiteProperties getTestSuitePropeties() {
        return baseLoader.getTestSuitePropeties();
    }

    @Override
    public SakuliExceptionHandler getExceptionHandler() {
        return baseLoader.getExceptionHandler();
    }

    @Override
    public TestSuite getTestSuite() {
        return baseLoader.getTestSuite();
    }

    @Override
    public TestCase getCurrentTestCase() {
        return baseLoader.getCurrentTestCase();
    }

    @Override
    public void setCurrentTestCase(TestCase testCase) {
        baseLoader.setCurrentTestCase(testCase);
    }

    @Override
    public TestCaseStep getCurrentTestCaseStep() {
        return baseLoader.getCurrentTestCaseStep();
    }

    @Override
    public ImageLib getImageLib() {
        return baseLoader.getImageLib();
    }

    @Override
    public RhinoScriptRunner getRhinoScriptRunner() {
        return baseLoader.getRhinoScriptRunner();
    }

    @Override
    public void setRhinoScriptRunner(RhinoScriptRunner scriptRunner) {
        baseLoader.setRhinoScriptRunner(scriptRunner);
    }

    @Override
    public Report getSahiReport() {
        return baseLoader.getSahiReport();
    }
}


text:
using System.Text.Json;
using Azure.Core;

namespace Azure.Communication.Email.Models
{
    public partial class SendStatusResult
    {
        internal static SendStatusResult DeserializeSendStatusResult(JsonElement element)
        {
            string messageId = default;
            SendStatus status = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("messageId"))
                {
                    messageId = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("status"))
                {
                    status = new SendStatus(property.Value.GetString());
                    continue;
                }
            }
            return new SendStatusResult(messageId, status);
        }
    }
}


text:
<?php

/**
 *
 * @package    swOptimizeRoutesPlugin
 * @subpackage output
 * @author     Thomas Rabaix <thomas.rabaix@soleoweb.com>
 * @version    SVN: $Id$
 */
class swOptimizeRoutingConfigHandler extends sfRoutingConfigHandler
{

  public function appendData(&$data, $route, $name)
  {

    $arguments = array();

    if($route instanceof sfRoute)
    {
      $route_instance = $route;
    }
    else
    {
      $r = new ReflectionClass($route[0]);
      $route_instance = $r->newInstanceArgs($route[1]);
    }

    $export = array(
      'route_class' => get_class($route_instance),
      'route_serialization' => $route_instance->serialize()
    );

    $data[] = sprintf('\'%s\' => %s,', $name, var_export($export, 1));
  }

  public function execute($configFiles)
  {
    $routes = $this->parse($configFiles);

    $data = array();

    foreach ($routes as $name => $route)
    {
      $r = new ReflectionClass($route[0]);
      if($r->isSubclassOf('sfRouteCollection'))
      {
        $collection_route = $r->newInstanceArgs($route[1]);

        foreach($collection_route->getRoutes() as $name => $route)
        {
          $this->appendData($data, $route, $name);
        }
      }
      else
      {
        $this->appendData($data, $route, $name);
      }
    }

    return sprintf("<?php\n".
                   "// auto-generated by swOptimizeRoutingConfigHandler\n".
                   "// date: %s\nreturn array(\n%s\n);\n", date('Y/m/d H:i:s'), implode("\n", $data)
    );
  }

//  public function evaluate($configFiles)
//  {
//
//    $routeDefinitions = $this->parse($configFiles);
//    foreach ($routeDefinitions as $name => $route)
//    {
//      $r = new ReflectionClass($route[0]);
//
//      if($r->isSubclassOf('sfRouteCollection'))
//      {
//       $collection_route = $r->newInstanceArgs($route[1]);
//
//        foreach($collection_route->getRoutes() as $name => $route)
//        {
//          $routes[$name] = new swOptimizeRoute($route);
//        }
//      }
//      else
//      {
//        $routes[$name] = new swOptimizeRoute($r->newInstanceArgs($route[1]));
//      }
//    }
//
//    return $routes;
//  }
}


text:
@import Foundation;
#import <ResearchKit/ORKDefines.h>
#import <ResearchKit/ORKActiveStepViewController.h>

NS_ASSUME_NONNULL_BEGIN

/**
 View controller corresponding to `ORKSpatialSpanMemoryStep`.
 */
ORK_CLASS_AVAILABLE
@interface ORKSpatialSpanMemoryStepViewController : ORKActiveStepViewController

@end

NS_ASSUME_NONNULL_END


text:
using namespace DirectX;
using namespace std;

extern "C" {
	// global variables which are accessed in Interceptor.asm and therefore need to be defined as 'extern "C"'
	LPBYTE g_cameraStructAddress = nullptr;
	LPBYTE g_fovStructAddress = nullptr;
	LPBYTE g_runFramesStructAddress = nullptr;
}

namespace IGCS::GameSpecific::CameraManipulator
{
	static float _originalRotationMatrixData[9];
	static float _originalCoordsData[3];
	static float _originalFoV;
	static bool _timeHasBeenStopped = false;
	static LPBYTE _showHudAddress = nullptr;
	static LPBYTE _stopTimeAddress = nullptr;

	void setShowHudAddress(LPBYTE address)
	{
		_showHudAddress = address;
	}

	void setStopTimeAddress(LPBYTE address)
	{
		_stopTimeAddress = address;
	}

	// newValue is the amount of frames to skip ahead when g_stopTime (via setStopTimeValue) is set to a value > 0
	void setRunFramesValue(BYTE newValue)
	{
		if (nullptr == g_runFramesStructAddress)
		{
			return;
		}
		*(g_runFramesStructAddress + RUNFRAMES_CVAR_IN_STRUCT_OFFSET) = newValue;
	}

	// newValue: 1 == time should be frozen, 0 == normal gameplay. There are 3 values possible for this variable (g_stopTime). 2 stops everything, also the player,
	// I opted for 1, as it leaves a bit freedom for what to do with the player after pausing the game.
	void setStopTimeValue(BYTE newValue)
	{
		if (nullptr == _stopTimeAddress)
		{
			return;
		}
		*_stopTimeAddress = newValue;
	}

	// 1== show hud, 0 is hide hud.
	void setShowHudValue(BYTE newValue)
	{
		if (nullptr == _showHudAddress)
		{
			return;
		}
		*_showHudAddress = newValue;
	}

	XMFLOAT3 getCurrentCameraCoords()
	{
		float* coordsInMemory = reinterpret_cast<float*>(g_cameraStructAddress + CAMERA_COORDS_IN_CAMERA_STRUCT_OFFSET);
		XMFLOAT3 currentCoords = XMFLOAT3(coordsInMemory);
		return currentCoords;
	}

	// newLookQuaternion: newly calculated quaternion of camera view space. Used here to construct a 4x4 matrix as the game uses a matrix instead of a quaternion
	// newCoords are the new coordinates for the camera in worldspace.
	void writeNewCameraValuesToGameData(XMVECTOR newLookQuaternion, XMFLOAT3 newCoords)
	{
		XMFLOAT4 qAsFloat4;
		XMStoreFloat4(&qAsFloat4, newLookQuaternion);

		// game uses a 3x3 matrix for look data. We have to calculate a rotation matrix from our quaternion and store the upper 3x3 matrix (_11-_33) in memory.
		XMMATRIX rotationMatrixPacked = XMMatrixRotationQuaternion(newLookQuaternion);
		XMFLOAT4X4 rotationMatrix;
		XMStoreFloat4x4(&rotationMatrix, rotationMatrixPacked);

		// 3x3 rotation part of matrix
		float* matrixInMemory = reinterpret_cast<float*>(g_cameraStructAddress + ROTATION_MATRIX_IN_CAMERA_STRUCT_OFFSET);
		matrixInMemory[0] = rotationMatrix._11;
		matrixInMemory[1] = rotationMatrix._12;
		matrixInMemory[2] = rotationMatrix._13;
		matrixInMemory[3] = rotationMatrix._21;
		matrixInMemory[4] = rotationMatrix._22;
		matrixInMemory[5] = rotationMatrix._23;
		matrixInMemory[6] = rotationMatrix._31;
		matrixInMemory[7] = rotationMatrix._32;
		matrixInMemory[8] = rotationMatrix._33;

		// Coords
		float* coordsInMemory = reinterpret_cast<float*>(g_cameraStructAddress + CAMERA_COORDS_IN_CAMERA_STRUCT_OFFSET);
		coordsInMemory[0] = newCoords.x;
		coordsInMemory[1] = newCoords.y;
		coordsInMemory[2] = newCoords.z;
	}

	// Waits for the interceptor to pick up the camera struct address. Should only return if address is found
	void waitForCameraStructAddresses()
	{
		Console::WriteLine("Waiting for camera struct interception...");
		while (nullptr == g_cameraStructAddress)
		{
			Sleep(100);
		}
		Console::WriteLine("Camera found.");

#ifdef _DEBUG
		cout << "Camera address: " << hex << (void*)g_cameraStructAddress << endl;
#endif
	}

	void resetFoV()
	{
		if (nullptr == g_fovStructAddress)
		{
			return;
		}
		float* fovInMemory = reinterpret_cast<float*>(g_fovStructAddress + FOV_IN_FOV_STRUCT_OFFSET);
		*fovInMemory = _originalFoV;
	}

	void changeFoV(float amount)
	{
		if (nullptr == g_fovStructAddress)
		{
			return;
		}
		float* fovInMemory = reinterpret_cast<float*>(g_fovStructAddress + FOV_IN_FOV_STRUCT_OFFSET);
		*fovInMemory += amount;
	}

	void restoreOriginalCameraValues()
	{
		if (nullptr == g_cameraStructAddress)
		{
			return;
		}
		float* matrixInMemory = reinterpret_cast<float*>(g_cameraStructAddress + ROTATION_MATRIX_IN_CAMERA_STRUCT_OFFSET);
		float* coordsInMemory = reinterpret_cast<float*>(g_cameraStructAddress + CAMERA_COORDS_IN_CAMERA_STRUCT_OFFSET);
		memcpy(matrixInMemory, _originalRotationMatrixData, 9 * sizeof(float));
		memcpy(coordsInMemory, _originalCoordsData, 3 * sizeof(float));
		if (nullptr != g_fovStructAddress)
		{
			float* floatInMemory = reinterpret_cast<float*>(g_fovStructAddress + FOV_IN_FOV_STRUCT_OFFSET);
			*floatInMemory = _originalFoV;
		}
	}

	void cacheOriginalCameraValues()
	{
		if (nullptr == g_cameraStructAddress)
		{
			return;
		}
		float* matrixInMemory = reinterpret_cast<float*>(g_cameraStructAddress + ROTATION_MATRIX_IN_CAMERA_STRUCT_OFFSET);
		float* coordsInMemory = reinterpret_cast<float*>(g_cameraStructAddress + CAMERA_COORDS_IN_CAMERA_STRUCT_OFFSET);
		memcpy(_originalRotationMatrixData, matrixInMemory, 9 * sizeof(float));
		memcpy(_originalCoordsData, coordsInMemory, 3 * sizeof(float));
		if (nullptr != g_fovStructAddress)
		{
			float* floatInMemory = reinterpret_cast<float*>(g_fovStructAddress + FOV_IN_FOV_STRUCT_OFFSET);
			_originalFoV = *floatInMemory;
		}
	}
}


text:
import datetime
import tempfile

from Crypto import Random
from Crypto.PublicKey import ElGamal
from Crypto.Random import random
from Crypto.Util.number import GCD

def encrypt(plaintext, key):
    while 1:
        k = random.StrongRandom().randint(1,key.p-1)
        if GCD(k,key.p-1)==1: break
    return key.encrypt(plaintext, k)

def encrypt_cipher(ciphertext, key):
    return (encrypt(ciphertext[0], key),
            encrypt(ciphertext[1], key))

def decrypt(ciphertext, key):
        return key.decrypt(ciphertext)

def scale(ciphertext, scalar):
    return ciphertext[0], scalar * ciphertext[1]

class User():

    def __init__(self, key=None):
        self.key = key

    def gen_key(self, key_len=4096):
        self.key = ElGamal.generate(key_len, Random.new().read)

    def export_key(self):
        return self.key.publickey()

    def bid(self, blob, value, bid_list, server_key, next_bidder_key, transaction):
        def make_garbage(chunks):
            for chunk in chunks:
                garbage = random.StrongRandom().randint(1, server_key.p-1)
                encrypted = encrypt(garbage, server_key)
                yield encrypt_cipher(encrypted, next_bidder_key)
        def place_bid(chunks, value):
            # chop value up into chunk-sized pieces
            for chunk in chunks:
                # tx_chunk = the resulst of converting this part of the tx to an int
                yield encrypt_cipher(scale(chunk, tx_chunk), next_bidder_key)
        def pass_through(chunks):
            for chunk in chunks:
                yield encrypt_cipher(chunk, next_bidder_key)

        ret = []
        for i, bid_blob in enumerate(blob):
            chunks = []
            for chunk in bid_blob:
                chunks.append((decrypt(chunk[0], self.key), decrypt(chunk[1], self.key)))
            if bid_list[i] < value:
                chunks = list(make_garbage(chunks))
            elif bid_list[i] == value:
                chunks = list(place_bid(chunks, transaction))
            else:
                chunks = list(pass_through(chunks))
            ret.append(chunks)
        return ret

    def final_bid(self, blob, value, bid_list, server_key, seller_address, transcation):
        def make_garbage(chunks):
            for chunk in chunks:
                garbage = random.StrongRandom().randint(1, server_key.p-1)
                yield encrypt(garbage, server_key)
        def place_bid(chunks, value):
            for chunk in chunks:
                yield scale(chunk, 0xBEEF)
        def pass_through(chunks):
            for chunk in chunks:
                yield chunk

        ret = []
        for i, bid_blob in enumerate(blob):
            chunks = []
            for chunk in bid_blob:
                chunks.append((decrypt(chunk[0], self.key), decrypt(chunk[1], self.key)))
            if bid_list[i] < value:
                chunks = list(make_garbage(chunks))
            elif bid_list[i] == value:
                chunks = list(place_bid(chunks, value))
            else:
                chunks = list(pass_through(chunks))
            ret.append(chunks)
        return ret

class Server():

    def __init__(self, num_bids, blocks_per_bid=4, key=None):
        self.num_bids = num_bids
        self.blocks_per_bid = blocks_per_bid
        self.key = key

    def gen_key(self, key_len=2048):
        self.key = ElGamal.generate(key_len, Random.new().read)

    def export_key(self):
        return self.key.publickey()

    def initialize(self, first_bidder_key):
        blob = []
        for _ in range(self.num_bids):
            bid_blob = []
            for _ in range(self.blocks_per_bid):
                value = 1
                encrypted = encrypt(value, self.key)
                double_encrypted = encrypt_cipher(encrypted, first_bidder_key)
                bid_blob.append(double_encrypted)
            blob.append(bid_blob)
        return blob

    def finalize(self, blob):
        ret = []
        for bid_blob in blob:
            chunks = []
            for chunk in bid_blob:
                chunks.append(decrypt(chunk, self.key))
            ret.append(chunks)
        return ret

def main():
    # do a test auction
    num_users = 3
    num_bids = 10
    users = [User() for _ in range(num_users)]
    server_key_len = 64
    for user in users:
        user.gen_key(server_key_len * 2)
    server = Server(num_bids, 1)
    server.gen_key(server_key_len)
    server_key = server.export_key()
    keyring = [user.export_key() for user in users]

    blob = server.initialize(keyring[0])

    blob = users[0].bid(blob, 5, range(num_bids), server_key, keyring[1])
    blob = users[1].bid(blob, 3, range(num_bids), server_key, keyring[2])
    blob = users[2].final_bid(blob, 8, range(num_bids), server_key)
    blob = server.finalize(blob)
    print(blob)

if __name__ == '__main__':
    main()


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.harvard.iq.dataverse.datasetutility;

import edu.harvard.iq.dataverse.Dataset;
import edu.harvard.iq.dataverse.DataverseSession;
import edu.harvard.iq.dataverse.DvObject;
import edu.harvard.iq.dataverse.FileMetadata;
import edu.harvard.iq.dataverse.PermissionServiceBean;
import edu.harvard.iq.dataverse.authorization.AuthenticationServiceBean;
import edu.harvard.iq.dataverse.authorization.Permission;
import edu.harvard.iq.dataverse.authorization.users.ApiToken;
import edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser;
import edu.harvard.iq.dataverse.authorization.users.GuestUser;
import edu.harvard.iq.dataverse.authorization.users.User;
import edu.harvard.iq.dataverse.settings.SettingsServiceBean;
import java.util.HashMap;
import java.util.Map;
import javax.faces.view.ViewScoped;
import javax.inject.Inject;
import javax.inject.Named;

/**
 *
 * @author rmp553

 */
@ViewScoped
@Named
public class TwoRavensHelper implements java.io.Serializable {

    @Inject SettingsServiceBean settingsService;
    @Inject PermissionServiceBean permissionService;
    @Inject AuthenticationServiceBean authService;

    @Inject
    DataverseSession session;

    private final Map<Long, Boolean> fileMetadataTwoRavensExploreMap = new HashMap<>(); // { FileMetadata.id : Boolean }

    public TwoRavensHelper(){

    }

     /**
     * Call this from a Dataset or File page
     *   - calls private method canSeeTwoRavensExploreButton
     *
     *  WARNING: Before calling this, make sure the user has download
     *  permission for the file!!  (See DatasetPage.canDownloadFile())
     *
     * @param fm
     * @return
     */
    public boolean canSeeTwoRavensExploreButtonFromAPI(FileMetadata fm, User user){

        if (fm == null){
            return false;
        }

        if (user == null){
            return false;
        }

        if (!this.permissionService.userOn(user, fm.getDataFile()).has(Permission.DownloadFile)){
            return false;
        }

        return this.canSeeTwoRavensExploreButton(fm, true);
    }

    /**
     * Call this from a Dataset or File page
     *   - calls private method canSeeTwoRavensExploreButton
     *
     *  WARNING: Before calling this, make sure the user has download
     *  permission for the file!!  (See DatasetPage.canDownloadFile())
     *
     * @param fm
     * @return
     */
    public boolean canSeeTwoRavensExploreButtonFromPage(FileMetadata fm){

        if (fm == null){
            return false;
        }

        return this.canSeeTwoRavensExploreButton(fm, true);
    }

    /**
     * Used to check whether a tabular file
     * may be viewed via TwoRavens
     *
     * @param fm
     * @return
     */
    public boolean canSeeTwoRavensExploreButton(FileMetadata fm, boolean permissionsChecked){
        if (fm == null){
            return false;
        }

        // This is only here as a reminder to the public method users
        if (!permissionsChecked){
            return false;
        }

        if (!fm.getDataFile().isTabularData()){
            this.fileMetadataTwoRavensExploreMap.put(fm.getId(), false);
            return false;
        }

        // Has this already been checked?
        if (this.fileMetadataTwoRavensExploreMap.containsKey(fm.getId())){
            // Yes, return previous answer
            //logger.info("using cached result for candownloadfile on filemetadata "+fid);
            return this.fileMetadataTwoRavensExploreMap.get(fm.getId());
        }

        // (1) Is TwoRavens active via the "setting" table?
        //      Nope: get out
        //
        if (!settingsService.isTrueForKey(SettingsServiceBean.Key.TwoRavensTabularView, false)){
            this.fileMetadataTwoRavensExploreMap.put(fm.getId(), false);
            return false;
        }

        //----------------------------------------------------------------------
        //(1a) Before we do any testing - if version is deaccessioned and user
        // does not have edit dataset permission then may download
        //---

        // (2) Is the DataFile object there and persisted?
        //      Nope: scat
        //
        if ((fm.getDataFile() == null)||(fm.getDataFile().getId()==null)){
            this.fileMetadataTwoRavensExploreMap.put(fm.getId(), false);
            return false;
        }

       if (fm.getDatasetVersion().isDeaccessioned()) {
           if (this.doesSessionUserHavePermission( Permission.EditDataset, fm)) {
               // Yes, save answer and return true
               this.fileMetadataTwoRavensExploreMap.put(fm.getId(), true);
               return true;
           } else {
               this.fileMetadataTwoRavensExploreMap.put(fm.getId(), false);
               return false;
           }
       }

        //Check for restrictions

        boolean isRestrictedFile = fm.isRestricted();

        // --------------------------------------------------------------------
        // Conditions (2) through (4) are for Restricted files
        // --------------------------------------------------------------------

        if (isRestrictedFile && session.getUser() instanceof GuestUser){
            this.fileMetadataTwoRavensExploreMap.put(fm.getId(), false);
            return false;
        }

        // --------------------------------------------------------------------
        // (3) Does the User have DownloadFile Permission at the **Dataset** level
        // --------------------------------------------------------------------

        if (isRestrictedFile && !this.doesSessionUserHavePermission(Permission.DownloadFile, fm)){
            // Yes, save answer and return true
            this.fileMetadataTwoRavensExploreMap.put(fm.getId(), false);
            return false;
        }

        // (3) Is there tabular data or is the ingest in progress?
        //      Yes: great
        //
        if ((fm.getDataFile().isTabularData())||(fm.getDataFile().isIngestInProgress())){
            this.fileMetadataTwoRavensExploreMap.put(fm.getId(), true);
            return true;
        }

        // Nope
        this.fileMetadataTwoRavensExploreMap.put(fm.getId(), false);
        return false;

        //       (empty fileMetadata.dataFile.id) and (fileMetadata.dataFile.tabularData or fileMetadata.dataFile.ingestInProgress)
        //                                        and DatasetPage.canDownloadFile(fileMetadata)
    }

    /**
     * Copied over from the dataset page - 9/21/2016
     *
     * @return
     */
    public String getDataExploreURL() {
        String TwoRavensUrl = settingsService.getValueForKey(SettingsServiceBean.Key.TwoRavensUrl);

        if (TwoRavensUrl != null && !TwoRavensUrl.equals("")) {
            return TwoRavensUrl;
        }

        return "";
    }

    /**
     * Copied over from the dataset page - 9/21/2016
     *
     * @param fileid
     * @param apiTokenKey
     * @return
     */
    public String getDataExploreURLComplete(Long fileid) {
        if (fileid == null){
            throw new NullPointerException("fileid cannot be null");
        }

        String TwoRavensUrl = settingsService.getValueForKey(SettingsServiceBean.Key.TwoRavensUrl);
        String TwoRavensDefaultLocal = "/dataexplore/gui.html?dfId=";

        if (TwoRavensUrl != null && !TwoRavensUrl.equals("")) {
            // If we have TwoRavensUrl set up as, as an optional
            // configuration service, it must mean that TwoRavens is sitting
            // on some remote server. And that in turn means that we must use
            // full URLs to pass data and metadata to it.
            // update: actually, no we don't want to use this "dataurl" notation.
            // switching back to the dfId=:
            // -- L.A. 4.1
            /*
            String tabularDataURL = getTabularDataFileURL(fileid);
            String tabularMetaURL = getVariableMetadataURL(fileid);
            return TwoRavensUrl + "?ddiurl=" + tabularMetaURL + "&dataurl=" + tabularDataURL + "&" + getApiTokenKey();
            */
            System.out.print("TwoRavensUrl Set up " + TwoRavensUrl + "?dfId=" + fileid + "&" + getApiTokenKey());

            return TwoRavensUrl + "?dfId=" + fileid + "&" + getApiTokenKey();
        }

        // For a local TwoRavens setup it's enough to call it with just
        // the file id:
        return TwoRavensDefaultLocal + fileid + "&" + getApiTokenKey();
    }

    private String getApiTokenKey() {
        ApiToken apiToken;
        if (session.getUser() == null) {
            return null;
        }
        if (isSessionUserAuthenticated()) {
            AuthenticatedUser au = (AuthenticatedUser) session.getUser();
            apiToken = authService.findApiTokenByUser(au);
            if (apiToken != null) {
                return "key=" + apiToken.getTokenString();
            }
            // Generate if not available?
            // Or should it just be generated inside the authService
            // automatically?
            apiToken = authService.generateApiTokenForUser(au);
            if (apiToken != null) {
                return "key=" + apiToken.getTokenString();
            }
        }
        return "";

    }

    public boolean isSessionUserAuthenticated() {

        if (session == null) {
            return false;
        }

        if (session.getUser() == null) {
            return false;
        }

        return session.getUser().isAuthenticated();

    }

    public boolean doesSessionUserHavePermission(Permission permissionToCheck, FileMetadata fileMetadata){
        if (permissionToCheck == null){
            return false;
        }

        DvObject objectToCheck = null;

        if (permissionToCheck.equals(Permission.EditDataset)){
            objectToCheck = fileMetadata.getDatasetVersion().getDataset();
        } else if (permissionToCheck.equals(Permission.DownloadFile)){
            objectToCheck = fileMetadata.getDataFile();
        }

        if (objectToCheck == null){
            return false;
        }

        // Check the permission
        //
        boolean hasPermission = this.permissionService.userOn(this.session.getUser(), objectToCheck).has(permissionToCheck);

        // return true/false
        return hasPermission;
    }
}


text:
#include <linux/capability.h>
#include <linux/io.h>

#include "b43.h"
#include "sysfs.h"
#include "main.h"
#include "phy_common.h"

#define GENERIC_FILESIZE	64

static int get_integer(const char *buf, size_t count)
{
	char tmp[10 + 1] = { 0 };
	int ret = -EINVAL;

	if (count == 0)
		goto out;
	count = min(count, (size_t) 10);
	memcpy(tmp, buf, count);
	ret = simple_strtol(tmp, NULL, 10);
      out:
	return ret;
}

static ssize_t b43_attr_interfmode_show(struct device *dev,
					struct device_attribute *attr,
					char *buf)
{
	struct b43_wldev *wldev = dev_to_b43_wldev(dev);
	ssize_t count = 0;

	if (!capable(CAP_NET_ADMIN))
		return -EPERM;

	mutex_lock(&wldev->wl->mutex);

	if (wldev->phy.type != B43_PHYTYPE_G) {
		mutex_unlock(&wldev->wl->mutex);
		return -ENOSYS;
	}

	switch (wldev->phy.g->interfmode) {
	case B43_INTERFMODE_NONE:
		count =
		    snprintf(buf, PAGE_SIZE,
			     "0 (No Interference Mitigation)\n");
		break;
	case B43_INTERFMODE_NONWLAN:
		count =
		    snprintf(buf, PAGE_SIZE,
			     "1 (Non-WLAN Interference Mitigation)\n");
		break;
	case B43_INTERFMODE_MANUALWLAN:
		count =
		    snprintf(buf, PAGE_SIZE,
			     "2 (WLAN Interference Mitigation)\n");
		break;
	default:
		B43_WARN_ON(1);
	}

	mutex_unlock(&wldev->wl->mutex);

	return count;
}

static ssize_t b43_attr_interfmode_store(struct device *dev,
					 struct device_attribute *attr,
					 const char *buf, size_t count)
{
	struct b43_wldev *wldev = dev_to_b43_wldev(dev);
	int err;
	int mode;

	if (!capable(CAP_NET_ADMIN))
		return -EPERM;

	mode = get_integer(buf, count);
	switch (mode) {
	case 0:
		mode = B43_INTERFMODE_NONE;
		break;
	case 1:
		mode = B43_INTERFMODE_NONWLAN;
		break;
	case 2:
		mode = B43_INTERFMODE_MANUALWLAN;
		break;
	case 3:
		mode = B43_INTERFMODE_AUTOWLAN;
		break;
	default:
		return -EINVAL;
	}

	mutex_lock(&wldev->wl->mutex);

	if (wldev->phy.ops->interf_mitigation) {
		err = wldev->phy.ops->interf_mitigation(wldev, mode);
		if (err) {
			b43err(wldev->wl, "Interference Mitigation not "
			       "supported by device\n");
		}
	} else
		err = -ENOSYS;

	mmiowb();
	mutex_unlock(&wldev->wl->mutex);

	return err ? err : count;
}

static DEVICE_ATTR(interference, 0644,
		   b43_attr_interfmode_show, b43_attr_interfmode_store);

int b43_sysfs_register(struct b43_wldev *wldev)
{
	struct device *dev = wldev->dev->dev;

	B43_WARN_ON(b43_status(wldev) != B43_STAT_INITIALIZED);

	return device_create_file(dev, &dev_attr_interference);
}

void b43_sysfs_unregister(struct b43_wldev *wldev)
{
	struct device *dev = wldev->dev->dev;

	device_remove_file(dev, &dev_attr_interference);
}


text:
title: "Localisation"
---

All the displayed text in the grid is customisable for the purposes of localisation. This is done by providing locale information to the grid for the required language. Either provide an object  of key/value pairs via the `localeText` property, or provide a `localeTextFunc` callback to hook the grid up to your application's localisation.

The default language of the grid is American English. The grid does not come with other locales. If you want to provide the grid in another language, you must provide to the grid the relevant  locale information.

## Creating a Locale

The grid by default does not need a locale. If no locale is provide, the grid will default to English. If a locale is provided but is missing values, the default English will be used for the missing values.

An example full locale file is provided below. To support other languages, the first step is to copy this file and translate the values into the required language.

`embed:examples/localisation/locale.en.js`

You can download the full file from [here](../../examples/localisation/localisation/locale.en.js).

There is one locale file for all of the grid. The file covers all modules across all of ag-Grid Enterprise and ag-Grid Free. This was done on purpose as having multiple files for each module would provide to much confusion. The decision was made to keep it simple in one file.

## Installing a Locale

To install a locale into the grid, set the locale object to the grid's `localeText` property. The example below shows this in action:

The example below shows installing a locale file. The example has two local files `locale.en.js` and `locale.zzz.js`. The second one is a dummy locale, it just adds "zzz" to the start of each value. This is done so that the example looks different - otherwise is would just display English as normal and there would be no way of knowing if the locale was working or not as English is the default.

This to try in the example are as follows:

1. Open up in Plunker.
1. Change the locale to English by changing `localeText = AG_GRID_LOCALE_ZZZ` to `localeText = AG_GRID_LOCALE_EN`.
1. Edit values in `locale.en.js` and observe the changes in the grid.

<grid-example title='Localisation' name='localisation' type='generated' options='{ "enterprise": true, "exampleHeight": 650 }'></grid-example>

## Changing Locale

The grid uses the locale as it is needed. It does not refresh as the locale changes. If your application allows changing the locale for the application, you must destroy and recreate the grid for it to use the new locale.

## Locale Callback

Providing a locale for the grid does not fit in with localisation libraries or localisation for a broader application. If you want the grid to take from an application wide locale, then implement the `localeTextFunc` to act as a bridge between the grid and the applications localisation.

The example below shows providing a callback for the grid's localisation. The example for simplicity just returns back the default value in upper case. In a real world application, the callback would use the applications localisation.

<grid-example title='Callback' name='callback' type='generated' options='{ "enterprise": true, "exampleHeight": 650 }'></grid-example>

In a real world application, the callback would look something like this:

```js
function localeTextFunc(key, defaultValue) {
    // to avoid key clash with external keys, we add 'grid' to the start of each key.
    var gridKey = 'grid.' + key;

    // look the value up using an application wide service
    return applicationLocaleService(gridKey);
}
```


text:
package com.google.ads.googleads.v12.enums;

public interface UserListFlexibleRuleOperatorEnumOrBuilder extends
    // @@protoc_insertion_point(interface_extends:google.ads.googleads.v12.enums.UserListFlexibleRuleOperatorEnum)
    com.google.protobuf.MessageOrBuilder {
}


text:
''' Script to check the online monitor.
'''

import sys
import unittest
import yaml
import subprocess
import time
import os
import psutil
from PyQt5 import QtWidgets

import online_monitor
from online_monitor import OnlineMonitor

# Get package path
# Get the absoulte path of the online_monitor installation
package_path = os.path.dirname(online_monitor.__file__)

# Set the script paths
converter_manager_path = os.path.join(package_path, 'start_converter.py')
producer_manager_path = os.path.join(package_path, 'start_producer_sim.py')

# creates a yaml config describing n_converter of type forwarder that are
# all connection to each other
def create_config_yaml():
    conf = {}
    # Add producer
    devices = {}
    devices['DAQ0'] = {'backend': 'tcp://127.0.0.1:6500',
                       'kind': 'example_producer_sim',
                       'delay': 0.02}
    devices['DAQ1'] = {'backend': 'tcp://127.0.0.1:6501',
                       'kind': 'example_producer_sim',
                       'delay': 0.02}
    conf['producer_sim'] = devices
    # Add converter
    devices = {}
    devices['DUT0'] = {
        'kind': 'example_converter',
        'frontend': 'tcp://127.0.0.1:6500',
        'backend': 'tcp://127.0.0.1:6600',
        'threshold': 8
    }
    devices['DUT1'] = {
        'kind': 'forwarder',
        'frontend': 'tcp://127.0.0.1:6600',
        'backend': 'tcp://127.0.0.1:6601',
    }
    conf['converter'] = devices
    # Add receiver
    devices = {}
    devices['DUT0'] = {
        'kind': 'example_receiver',
        'frontend': 'tcp://127.0.0.1:6600'
    }
    devices['DUT1'] = {
        'kind': 'example_receiver',
        'frontend': 'tcp://127.0.0.1:6601'
    }
    conf['receiver'] = devices
    return yaml.dump(conf, default_flow_style=False)

# kill process by id, including subprocesses; works for linux and windows
def kill(proc):
    process = psutil.Process(proc.pid)
    for child_proc in process.children(recursive=True):
        child_proc.kill()
    process.kill()

def run_script_in_shell(script, arguments, command=None):
    return subprocess.Popen("%s %s %s" % ('python' if not command else command, script, arguments),
                            shell=True,
                            creationflags=subprocess.CREATE_NEW_PROCESS_GROUP if os.name == 'nt' else 0)

class TestOnlineMonitor(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        # Set the config file path to the test folder, otherwise they are
        # created where nosetests are called
        cls.config_path = os.path.join(
            os.path.dirname(__file__), 'tmp_cfg.yml')

        with open(cls.config_path, 'w') as outfile:
            config_file = create_config_yaml()
            outfile.write(config_file)
        # linux CI travis runs headless, thus virtual x server is needed for
        # Start the simulation producer to create some fake data
        cls.producer_process = run_script_in_shell(
            producer_manager_path, cls.config_path)
        # Start converter
        cls.converter_manager_process = run_script_in_shell(
            converter_manager_path, cls.config_path)
        # Create Gui
        time.sleep(2)
        cls.app = QtWidgets.QApplication(sys.argv)
        cls.online_monitor = OnlineMonitor.OnlineMonitorApplication(
            cls.config_path)
        time.sleep(2)

    @classmethod
    def tearDownClass(cls):  # remove created files
        time.sleep(1)
        kill(cls.producer_process)
        kill(cls.converter_manager_process)
        time.sleep(1)
        os.remove(cls.config_path)
        cls.online_monitor.close()
        time.sleep(1)

    def test_receiver(self):
        self.app.processEvents()
        self.assertEqual(len(self.online_monitor.receivers),
                         2, 'Number of frontends wrong')
        self.app.processEvents()  # clear event queue
        # activate status widget, no data should be received
        self.online_monitor.tab_widget.setCurrentIndex(0)
        # event loop does not run in testss, thus we have to trigger the event
        # queue manually
        self.app.processEvents()
        time.sleep(3)
        self.app.processEvents()
        time.sleep(0.2)
        data_received_0 = []
        self.app.processEvents()
        for receiver in self.online_monitor.receivers:
            data_received_0.append(receiver.position_img.getHistogram())
        self.online_monitor.tab_widget.setCurrentIndex(1)
        self.app.processEvents()
        time.sleep(3)
        self.app.processEvents()
        time.sleep(0.2)
        data_received_1 = []
        for receiver in self.online_monitor.receivers:
            data_received_1.append(receiver.position_img.getHistogram(step=1))
        # activate DUT widget, receiver 2 should show data
        self.online_monitor.tab_widget.setCurrentIndex(2)
        self.app.processEvents()
        time.sleep(3)
        self.app.processEvents()
        time.sleep(0.2)
        data_received_2 = []
        for receiver in self.online_monitor.receivers:
            # Step has to be given to preven issue
            # https://github.com/pyqtgraph/pyqtgraph/issues/469
            data_received_2.append(receiver.position_img.getHistogram(step=1))

        self.assertListEqual(data_received_0, [(None, None), (None, None)])
        self.assertTrue(data_received_1[0][0] is not None)
        self.assertTupleEqual(data_received_0[1], (None, None))
        self.assertTrue(data_received_2[1][0] is not None)

    # start 10 forwarder in a chain and do "whisper down the lane"
    def test_ui(self):
        self.assertEqual(self.online_monitor.tab_widget.count(),
                         3, 'Number of tab widgets wrong')  # 2 receiver + status widget expected

if __name__ == '__main__':
    suite = unittest.TestLoader().loadTestsFromTestCase(TestOnlineMonitor)
    unittest.TextTestRunner(verbosity=2).run(suite)


text:
define(function(){
	function EditionModuleInterface() {
		this.setEditable = function(editable){
			this.controller.setEditable(editable);
		};
	}

	return EditionModuleInterface;
});