text:
CREATE TABLE tother(a, b);
INSERT INTO tother VALUES(1, 3.7);
SELECT id, a FROM tbooking, tother WHERE id>a;

redpajama_set_name: RedPajamaGithub


text:
from pybrain.rl.agents.linearfa import LinearFA_Agent
from pybrain.rl.experiments import EpisodicExperiment

from environment import Environment
from tasks import LinearFATileCoding3456GoToTask
from training import LinearFATraining
from learners import SARSALambda_LinFA_ReplacingTraces

task = LinearFATileCoding3456GoToTask(only_steer=True, max_time=50.0)
learner = SARSALambda_LinFA_ReplacingTraces(task.nactions, task.outdim)
learner._lambda = 0.95
task.discount = learner.rewardDiscount
agent = LinearFA_Agent(learner)
# The state has a huge number of dimensions, and the logging causes me to run
# out of memory. We needn't log, since learning is done online.
agent.logging = False
agent.epsilonGreedy = True
performance_agent = LinearFA_Agent(learner)
performance_agent.logging = False
performance_agent.greedy = True
performance_agent.learning = False
experiment = EpisodicExperiment(task, agent)

# TODO PyBrain says that the learning rate needs to decay, but I don't see that
# described in Randlov's paper.
# A higher number here means the learning rate decays slower.
learner.learningRateDecay = 100000
# NOTE increasing this number above from the default of 100 is what got the
# learning to actually happen, and fixed the bug/issue where the performance
# agent's performance stopped improving.

tr = LinearFATraining('goto_sarsalambda_linfa_replacetrace_onlysteer',
        experiment, performance_agent, verbose=True)

tr.train(200000, performance_interval=10, n_performance_episodes=5)


text:
using System;
using System.ComponentModel;

namespace Azure.ResourceManager.Resources.Models
{
    /// <summary> The approver type. </summary>
    public readonly partial struct JitApproverType : IEquatable<JitApproverType>
    {
        private readonly string _value;

        /// <summary> Initializes a new instance of <see cref="JitApproverType"/>. </summary>
        /// <exception cref="ArgumentNullException"> <paramref name="value"/> is null. </exception>
        public JitApproverType(string value)
        {
            _value = value ?? throw new ArgumentNullException(nameof(value));
        }

        private const string UserValue = "user";
        private const string GroupValue = "group";

        /// <summary> user. </summary>
        public static JitApproverType User { get; } = new JitApproverType(UserValue);
        /// <summary> group. </summary>
        public static JitApproverType Group { get; } = new JitApproverType(GroupValue);
        /// <summary> Determines if two <see cref="JitApproverType"/> values are the same. </summary>
        public static bool operator ==(JitApproverType left, JitApproverType right) => left.Equals(right);
        /// <summary> Determines if two <see cref="JitApproverType"/> values are not the same. </summary>
        public static bool operator !=(JitApproverType left, JitApproverType right) => !left.Equals(right);
        /// <summary> Converts a string to a <see cref="JitApproverType"/>. </summary>
        public static implicit operator JitApproverType(string value) => new JitApproverType(value);

        /// <inheritdoc />
        [EditorBrowsable(EditorBrowsableState.Never)]
        public override bool Equals(object obj) => obj is JitApproverType other && Equals(other);
        /// <inheritdoc />
        public bool Equals(JitApproverType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase);

        /// <inheritdoc />
        [EditorBrowsable(EditorBrowsableState.Never)]
        public override int GetHashCode() => _value?.GetHashCode() ?? 0;
        /// <inheritdoc />
        public override string ToString() => _value;
    }
}


text:
layout: doc
title: SAML
---

*pac4j* allows you to login with any SAML identity provider using the SAML v2.0 protocol.

It has been tested with various SAML 2 providers: Okta, testshib.org, CAS SAML2 IdP, ...

## 1) Dependency

You need to use the following module: `pac4j-saml`.

**Example (Maven dependency):**

```xml
<dependency>
    <groupId>org.pac4j</groupId>
    <artifactId>pac4j-saml</artifactId>
    <version>${pac4j.version}</version>
</dependency>
```

## 2) Basic configuration

The [`SAML2Client`](https://github.com/pac4j/pac4j/blob/master/pac4j-saml/src/main/java/org/pac4j/saml/client/SAML2Client.java)
must be used to login with a SAML 2 identity provider.

First, if you don't have one, you need to generate a keystore for all signature and encryption operations:

```bash
keytool -genkeypair -alias pac4j-demo -keypass pac4j-demo-passwd -keystore samlKeystore.jks -storepass pac4j-demo-passwd -keyalg RSA -keysize 2048 -validity 3650
```

Alternatively, you can also let pac4j create the keystore for you. If the keystore resource does not exist and is writable, *pac4j* will attempt to generate a keystore and produce the relevant key pairs inside it.

Then, you must define a [`SAML2ClientConfiguration`](https://github.com/pac4j/pac4j/blob/master/pac4j-saml/src/main/java/org/pac4j/saml/client/SAML2ClientConfiguration.java):

```java
SAML2ClientConfiguration cfg = new SAML2ClientConfiguration(new ClassPathResource("samlKeystore.jks"),
                                        "pac4j-demo-passwd",
                                        "pac4j-demo-passwd",
                                        new ClassPathResource("testshib-providers.xml"));
```

The first parameter (`keystoreResource`) is the keystore defined as a Spring resource using:
- the `org.springframework.core.io.FileSystemResource` class for disk files
- the `org.springframework.core.io.ClassPathResource` class for classpath files
- the `org.springframework.core.io.UrlResource` class for URLs.

The second parameter (`keystorePassword`) is the value of the `-storepass` option for the keystore generation while the third parameter (`privateKeyPassword`) is the value of the `-keypass` option.

The fourth parameter (`identityProviderMetadataResource`) should point to your IdP metadata, assuming you can use the same kind of definition than for the keystore.

Or you can also use the "prefix mechanism" to define the `Resource`:

```java
SAML2ClientConfiguration cfg = new SAML2ClientConfiguration("resource:samlKeystore.jks",
                                        "pac4j-demo-passwd",
                                        "pac4j-demo-passwd",
                                        "resource:testshib-providers.xml");
```

These are the available prefixes:

- the `resource:` or the `classpath:` prefixes creates a `ClassPathResource` component
- the `http:` or the `https:` prefixes creates a `UrlResource` component
- the `file:` prefix or no prefix at all creates a `FileSystemResource` component.

Or you can even use the empty constructor and the appropriate setters:
- the `setKeystoreResource`, `setKeystoreResourceFilepath`, `setKeystoreResourceClasspath`, `setKeystoreResourceUrl` or `setKeystorePath` methods to define the keystore
- the `setKeystorePassword` method to define the keystore password
- the `setPrivateKeyPassword` method to set the private password of the keystore
- the `setIdentityProviderMetadataResource`, `setIdentityProviderMetadataResourceFilepath`, `setIdentityProviderMetadataResourceClasspath`, `setIdentityProviderMetadataResourceUrl` or `setIdentityProviderMetadataPath` methods to define the identity provider metadata.

Finally, you need to declare the `SAML2Client` based on the previous configuration:

```java
Saml2Client client = new Saml2Client(cfg);
```

After a successful authentication, a [`SAML2Profile`](https://github.com/pac4j/pac4j/blob/master/pac4j-saml/src/main/java/org/pac4j/saml/profile/SAML2Profile.java) is returned.

## 3) Additional configuration:

You can define the binding type via the `setDestinationBindingType` method:

```java
cfg.setDestinationBindingType(SAMLConstants.SAML2_REDIRECT_BINDING_URI);
// or cfg.setDestinationBindingType(SAMLConstants.SAML2_POST_BINDING_URI);
```

Once you have an authenticated web session on the Identity Provider, usually it won't prompt you again to enter your credentials and it will automatically generate a new assertion for you. By default, the SAML client will accept assertions based on a previous authentication for one hour. If you want to change this behaviour, set the `maximumAuthenticationLifetime` parameter:

```java
// lifetime in seconds
client.setMaximumAuthenticationLifetime(600);
```

By default, the entity ID of your application (the Service Provider) will be equals to the [callback url](clients.html#the-callback-url).
This can lead to problems with some IDP because of the query string not being accepted (like ADFS v2.0). So you can force your own
entity ID with the `serviceProviderEntityId` parameter:

```java
// custom SP entity ID
cfg.setServiceProviderEntityId("http://localhost:8080/callback?client_name=SAML2Client");
```

To configure the supported algorithms and digest methods for the initial authentication request, specify what is supported via the configuration object:

```java
cfg.setBlackListedSignatureSigningAlgorithms(...);
cfg.setSignatureAlgorithms(...);
cfg.setSignatureReferenceDigestMethods(...);
cfg.setSignatureCanonicalizationAlgorithm(...);
```

By default, assertions must be signed, but this may be disabled using:

```java
cfg.setWantsAssertionsSigned(false);
```

You may also force XML-signing of the authentication requests when using the redirect binding:

```java
cfg.setForceServiceProviderMetadataGeneration(true);
```

The final result will be determined based on the IdP metadata and the configuration above.
The IdP metadata will always be chosen in favor of the *pac4j* configuration, so if you need to purely rely on *pac4j*, you need to modify the metadata.

You can generate the SP metadata in two ways:
- either programmatically using the `SAML2Client`: `String spMetadata = client.getServiceProviderMetadataResolver().getMetadata();`
- or by defining the appropriate configuration: `cfg.setServiceProviderMetadata(new FileSystemResource("/tmp/sp-metadata.xml"));`

## 4) ADFS subtilities

You must follow these rules to successfully authenticate using Microsoft ADFS 2.0 / 3.0.

### a) Entity ID

You must always specify an explicit Entity ID that does not contain any question mark. By default, *pac4j* uses the same
Entity ID as the AssertionConsumerService location, which contains the client's name as a parameter after a question mark.
Unfortunately ADFS does not work well with such IDs and starts an infinite redirection loop when A SAML message with such a message arrives.

### b) Maximum authentication time

*pac4j* has the default maximum time set to 1 hour while ADFS has it set to 8 hours. Therefore it can happen that ADFS
sends an assertion which is still valid on ADFS side but evaluated as invalid on *pac4j* side.

You can see the following error message: `org.pac4j.saml.exceptions.SAMLException: Authentication issue instant is too old or in the future`

There are two possibilities how to make the values equal:

- change the value in ADFS management console in the trust properties dialog
- change the value on *pac4j* side using the `setMaximumAuthenticationLifetime` method.

### c) Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files

You must install the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files into your JRE/JDK
running *pac4j*. If you don't do it, you may encounter errors like this:

```
ERROR [org.opensaml.xml.encryption.Decrypter] - <Error decrypting the encrypted data element>
org.apache.xml.security.encryption.XMLEncryptionException: Illegal key size
ERROR [org.opensaml.xml.encryption.Decrypter] - <Failed to decrypt EncryptedData using either EncryptedData KeyInfoCredentialResolver or EncryptedKeyResolver + EncryptedKey KeyInfoCredentialResolver>
ERROR [org.opensaml.saml2.encryption.Decrypter] - <SAML Decrypter encountered an error decrypting element content>
```

Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files can be downloaded from Oracle's Java Download site.


text:
#include <list>
#include <string>

namespace script
{
    class Use;

    class Value
    {
        friend class Use;
    public:
        enum ValueTy {
            UndefVal,
            TableVal,
            ParamVal,
            UserClosureVal,
            ConstantVal,
            InstructionVal,
        };

        typedef std::list<Use*>::iterator use_iterator;

        Value(unsigned scid);
        virtual ~Value();

        use_iterator use_begin() { return uses.begin(); }
        use_iterator use_end() { return uses.end(); }
        size_t use_size() const { return uses.size(); }

        void set_value_name(const char *name);
        void set_value_name(const std::string &name);
        const std::string &get_value_name() const;

        void replace_all_uses_with(Value *value);
        void unchecked_replace_all_uses_with(Value *value);

        unsigned get_subclass_id() const { return subclass_id; }
        bool is_value() const { return !is_instr(); }
		bool is_undef() const { return get_subclass_id() == UndefVal; }
		bool is_table() const { return get_subclass_id() == TableVal; }
		bool is_param() const { return get_subclass_id() == ParamVal; }
		bool is_const() const { return get_subclass_id() == ConstantVal; }
		//bool is_funct() const { return get_subclass_id() == FunctionVal; }
		bool is_instr() const { return get_subclass_id() == InstructionVal; }
    protected:
        std::list<Use*> uses;
        std::string value_name;

    private:
        // These two methods should only used by the Use class.
        void add_use(Use *use);
        void kill_use(Use *use);

        const unsigned short subclass_id;
    };

    class Constant : public Value
    {
    public:
        enum { Null, Boolean, Character, Integer, Float, String, };

        Constant();
        Constant(int num);
        Constant(bool state);
        Constant(char c);
        Constant(float fnum);
        Constant(std::string str);

        unsigned type()         const { return type_; }
        int     getInteger()    const { return num_; }
        char    getChar()       const { return c_; }
        float   getFloat()      const { return fnum_; }
        bool    getBoolean()    const { return bool_; }
        const std::string &getString() const { return str_; }

    protected:
        unsigned    type_;
        int         num_;
        bool        bool_;
        char        c_;
        float       fnum_;
        std::string str_;
    };

    class Table : public Value
    {
    public:
        Table() : Value(ValueTy::TableVal) {}
        virtual ~Table() = default;
    };

    class Undef : public Value
    {
    public:
        Undef() : Value(ValueTy::UndefVal) {}
        virtual ~Undef() = default;
    };

    class UserClosure : public Value
    {
    public:
		UserClosure(const char *funcname)
            : Value(ValueTy::UserClosureVal)
        {
            this->set_value_name(funcname);
        }

		UserClosure(const std::string &name)
            : Value(ValueTy::UserClosureVal)
        {
            this->set_value_name(name.c_str());
        }

        const std::string &getClosureName() const
        {
            return get_value_name();
        }
    };

	class Param : public Value
	{
	public:
		Param(const std::string &name)
			: Value(ValueTy::ParamVal)
		{
			this->set_value_name(name);
		}

		virtual ~Param() = default;
		const std::string &getParamName() const
		{
			return get_value_name();
		}
	};
}


text:
extern "Java"
{
  namespace javax
  {
    namespace swing
    {
        class Action;
      namespace text
      {
          class JTextComponent;
          class JTextComponent$KeymapActionMap;
          class Keymap;
      }
    }
  }
}

class javax::swing::text::JTextComponent$KeymapActionMap : public ::javax::swing::ActionMap
{

public:
  JTextComponent$KeymapActionMap(::javax::swing::text::JTextComponent *, ::javax::swing::text::Keymap *);
  virtual ::javax::swing::Action * get(::java::lang::Object *);
  virtual jint size();
  virtual JArray< ::java::lang::Object * > * keys();
  virtual JArray< ::java::lang::Object * > * allKeys();
public: // actually package-private
  ::javax::swing::text::Keymap * __attribute__((aligned(__alignof__( ::javax::swing::ActionMap)))) map;
  ::javax::swing::text::JTextComponent * this$0;
public:
  static ::java::lang::Class class$;
};

#endif // __javax_swing_text_JTextComponent$KeymapActionMap__


text:
# Quick Start

zend-view provides the "View" layer of Zend Framework 2's MVC system. It is a
multi-tiered system allowing a variety of mechanisms for extension,
substitution, and more.

The components of the view layer are as follows:

- **Variables Containers** hold variables and callbacks that you wish to
  represent in the view.  Often-times, a Variables Container will also provide
  mechanisms for context-specific escaping of variables and more.
- **View Models** hold Variables Containers, specify the template to use (if
  any), and optionally provide rendering options (more on that below). View
  Models may be nested in order to represent complex structures.
- **Renderers** take View Models and provide a representation of them to return.
  zend-view ships with three renderers by default: a `PhpRenderer` which
  utilizes PHP templates in order to generate markup, a `JsonRenderer`, and a
  `FeedRenderer` for generating RSS and Atom feeds.
- **Resolvers** utilize Resolver Strategies to resolve a template name to a
  resource a Renderer may consume. As an example, a Resolver may take the name
  "blog/entry" and resolve it to a PHP view script.
- The **View** consists of strategies that map the current Request to a
  Renderer, and strategies for injecting the result of rendering to the
  Response.
- **Rendering Strategies** listen to the `Zend\View\ViewEvent::EVENT_RENDERER`
  event of the View and decide which Renderer should be selected based on the
  Request or other criteria.
- **Response Strategies** are used to inject the Response object with the
  results of rendering. That may also include taking actions such as setting
  Content-Type headers.

Additionally, zend-mvc integrates with zend-view via a number of event listeners
in the `Zend\Mvc\View` namespace.

This section of the manual is designed to show you typical usage patterns of the
view layer when using it with [zend-mvc](https://zendframework.github.io/zend-mvc/).
The assumption is that you are using the [service manager](https://zendframework.github.io/zend-servicemanager/)
and the default MVC view strategies.

## Configuration

The default configuration will typically work out-of-the-box. However, you will
still need to select Resolver Strategies and configure them, as well as
potentially indicate alternate template names for things like the site layout,
404 (not found) pages, and error pages. The code snippets below can be added to
your configuration to accomplish this. We recommend adding it to a
site-specific module, such as the "Application" module from the framework's
[ZendSkeletonApplication](https://github.com/zendframework/ZendSkeletonApplication),
or to one of your autoloaded configurations within the `config/autoload/`
directory.

```php
return [
    'view_manager' => [
        // The TemplateMapResolver allows you to directly map template names
        // to specific templates. The following map would provide locations
        // for a home page template ("application/index/index"), as well as for
        // the layout ("layout/layout"), error pages ("error/index"), and
        // 404 page ("error/404"), resolving them to view scripts.
        'template_map' => [
            'application/index/index' => __DIR__ .  '/../view/application/index/index.phtml',
            'site/layout'             => __DIR__ . '/../view/layout/layout.phtml',
            'error/index'             => __DIR__ . '/../view/error/index.phtml',
            'error/404'               => __DIR__ . '/../view/error/404.phtml',
        ],

        // The TemplatePathStack takes an array of directories. Directories
        // are then searched in LIFO order (it's a stack) for the requested
        // view script. This is a nice solution for rapid application
        // development, but potentially introduces performance expense in
        // production due to the number of static calls necessary.
        //
        // The following adds an entry pointing to the view directory
        // of the current module. Make sure your keys differ between modules
        // to ensure that they are not overwritten -- or simply omit the key!
        'template_path_stack' => [
            'application' => __DIR__ . '/../view',
        ],

        // This will be used as the default suffix for template scripts
        // resolving, it defaults to 'phtml'.
        'default_template_suffix' => 'php',

        // Set the template name for the site's layout.
        //
        // By default, the MVC's default Rendering Strategy uses the
        // template name "layout/layout" for the site's layout.
        // Here, we tell it to use the "site/layout" template,
        // which we mapped via the TemplateMapResolver above.
        'layout' => 'site/layout',

        // By default, the MVC registers an "exception strategy", which is
        // triggered when a requested action raises an exception; it creates
        // a custom view model that wraps the exception, and selects a
        // template. We'll set it to "error/index".
        //
        // Additionally, we'll tell it that we want to display an exception
        // stack trace; you'll likely want to disable this by default.
        'display_exceptions' => true,
        'exception_template' => 'error/index',

       // Another strategy the MVC registers by default is a "route not
       // found" strategy. Basically, this gets triggered if (a) no route
       // matches the current request, (b) the controller specified in the
       // route match cannot be found in the service locator, (c) the controller
       // specified in the route match does not implement the DispatchableInterface
       // interface, or (d) if a response from a controller sets the
       // response status to 404.
       //
       // The default template used in such situations is "error", just
       // like the exception strategy. Here, we tell it to use the "error/404"
       // template (which we mapped via the TemplateMapResolver, above).
       //
       // You can opt in to inject the reason for a 404 situation; see the
       // various `Application\:\:ERROR_*`_ constants for a list of values.
       // Additionally, a number of 404 situations derive from exceptions
       // raised during routing or dispatching. You can opt-in to display
       // these.
       'display_not_found_reason' => true,
       'not_found_template'       => 'error/404',
    ],
];
```

## Controllers and View Models

`Zend\View\View` consumes `ViewModel`s, passing them to the selected renderer.
Where do you create these, though?

The most explicit way is to create them in your controllers and return them.

```php
namespace Foo\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;

class BazBatController extends AbstractActionController
{
    public function doSomethingCrazyAction()
    {
        $view = new ViewModel([
            'message' => 'Hello world',
        ]);
        $view->setTemplate('foo/baz-bat/do-something-crazy');
        return $view;
    }
}
```

This sets a "message" variable in the View Model, and sets the template name
"foo/baz-bat/do-something-crazy". The View Model is then returned.

In most cases, you'll likely have a template name based on the module namespace,
controller, and action. Considering that, and if you're simply passing some
variables, could this be made simpler?  Definitely.

The MVC registers a couple of listeners for controllers to automate this. The
first will look to see if you returned an associative array from your
controller; if so, it will create a View Model and make this associative array
the Variables Container; this View Model then replaces the
[MvcEvent](http://zendframework.github.io/zend-mvc/mvc-event/)'s result. It will
also look to see if you returned nothing or `null`; if so, it will create a View
Model without any variables attached; this View Model also replaces the
`MvcEvent`'s result.

The second listener checks to see if the `MvcEvent` result is a View Model, and,
if so, if it has a template associated with it. If not, it will inspect the
controller matched during routing to determine the module namespace and the
controller class name, and, if available, it's "action" parameter in order to
create a template name. This will be `module/controller/action`, all normalized
to lowercase, dash-separated words.

As an example, the controller `Foo\Controller\BazBatController` with action
"doSomethingCrazyAction", would be mapped to the template
`foo/baz-bat/do-something-crazy`. As you can see, the words "Controller" and
"Action" are omitted.

In practice, that means our previous example could be re-written as follows:

```php
namespace Foo\Controller;

use Zend\Mvc\Controller\AbstractActionController;

class BazBatController extends AbstractActionController
{
    public function doSomethingCrazyAction()
    {
        return [
            'message' => 'Hello world',
        ];
    }
}
```

The above method will likely work for the majority of use cases. When you need
to specify a different template, explicitly create and return a View Model and
specify the template manually, as in the first example.

## Nesting View Models

The other use case you may have for setting explicit View Models is if you wish
to **nest** them. In other words, you might want to render templates to be
included within the main View you return.

As an example, you may want the View from an action to be one primary section
that includes both an "article" and a couple of sidebars; one of the sidebars
may include content from multiple Views as well:

```php
namespace Content\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;

class ArticleController extends AbstractActionController
{
    public function viewAction()
    {
        // get the article from the persistence layer, etc...

        $view = new ViewModel();

        // this is not needed since it matches "module/controller/action"
        $view->setTemplate('content/article/view');

        $articleView = new ViewModel(['article' => $article]);
        $articleView->setTemplate('content/article');

        $primarySidebarView = new ViewModel();
        $primarySidebarView->setTemplate('content/main-sidebar');

        $secondarySidebarView = new ViewModel();
        $secondarySidebarView->setTemplate('content/secondary-sidebar');

        $sidebarBlockView = new ViewModel();
        $sidebarBlockView->setTemplate('content/block');

        $secondarySidebarView->addChild($sidebarBlockView, 'block');

        $view->addChild($articleView, 'article')
             ->addChild($primarySidebarView, 'sidebar_primary')
             ->addChild($secondarySidebarView, 'sidebar_secondary');

        return $view;
    }
}
```

The above will create and return a View Model specifying the template
`content/article/view`. When the View is rendered, it will render three child
Views, the `$articleView`, `$primarySidebarView`, and `$secondarySidebarView`;
these will be captured to the `$view`'s `article`, `sidebar_primary`, and
`sidebar_secondary` variables, respectively, so that when it renders, you may
include that content. Additionally, the `$secondarySidebarView` will include an
additional View Model, `$sidebarBlockView`, which will be captured to its
`block` view variable.

To better visualize this, let's look at what the final content might look like,
with comments detailing where each nested view model is injected.

Here are the templates, rendered based on a 12-column grid:

```php
<?php // "content/article/view" template ?>
<!-- This is from the $view View Model, and the "content/article/view" template -->
<div class="row content">
    <?= $this->article ?>

    <?= $this->sidebar_primary ?>

    <?= $this->sidebar_secondary ?>
</div>
```

```php
<?php // "content/article" template ?>
    <!-- This is from the $articleView View Model, and the "content/article"
         template -->
    <article class="span8">
        <?= $this->escapeHtml('article') ?>
    </article>
```

```php
<?php // "content/main-sidebar" template ?>
    <!-- This is from the $primarySidebarView View Model, and the
         "content/main-sidebar" template -->
    <div class="span2 sidebar">
        sidebar content...
    </div>
```

```php
<?php // "content/secondary-sidebar template ?>
    <!-- This is from the $secondarySidebarView View Model, and the
         "content/secondary-sidebar" template -->
    <div class="span2 sidebar pull-right">
        <?= $this->block ?>
    </div>
```

```php
<?php // "content/block template ?>
        <!-- This is from the $sidebarBlockView View Model, and the
            "content/block" template -->
        <div class="block">
            block content...
        </div>
```

And here is the aggregate, generated content:

```html
<!-- This is from the $view View Model, and the "content/article/view" template -->
<div class="row content">
    <!-- This is from the $articleView View Model, and the "content/article"
         template -->
    <article class="span8">
        Lorem ipsum ....
    </article>

    <!-- This is from the $primarySidebarView View Model, and the
         "content/main-sidebar" template -->
    <div class="span2 sidebar">
        sidebar content...
    </div>

    <!-- This is from the $secondarySidebarView View Model, and the
         "content/secondary-sidebar" template -->
    <div class="span2 sidebar pull-right">
        <!-- This is from the $sidebarBlockView View Model, and the
            "content/block" template -->
        <div class="block">
            block content...
        </div>
    </div>
</div>
```

You can achieve very complex markup using nested Views, while simultaneously
keeping the details of rendering isolated from the Request/Response lifecycle of
the controller.

## Dealing with Layouts

Most sites enforce a cohesive look-and-feel which we typically call the site's
"layout". It includes the default stylesheets and JavaScript necessary, if any,
as well as the basic markup structure into which all site content will be
injected.

Within zend-mvc, layouts are handled via nesting of View Models ([see the
previous example](#nesting-view-models) for examples of View Model nesting). The
`Zend\Mvc\View\Http\ViewManager` composes a View Model which acts as the "root"
for nested View Models. As such, it should contain the skeleton (or layout)
template for the site. All other content is then rendered and captured to view
variables of this root View Model.

The `ViewManager` sets the layout template as `layout/layout` by default. To
change this, you can add some configuration to the `view_manager` area of your
[configuration](#configuration).

A listener on the controllers, `Zend\Mvc\View\Http\InjectViewModelListener`,
will take a View Model returned from a controller and inject it as a child of
the root (layout) View Model. By default, View Models will capture to the
"content" variable of the root View Model. This means you can do the following
in your layout view script:

```php
<html>
    <head>
        <title><?= $this->headTitle() ?></title>
    </head>
    <body>
        <?= $this->content; ?>
    </body>
</html>
```

If you want to specify a different View variable for which to capture,
explicitly create a view model in your controller, and set its "capture to"
value:

```php
namespace Foo\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;

class BazBatController extends AbstractActionController
{
    public function doSomethingCrazyAction()
    {
        $view = new ViewModel([
            'message' => 'Hello world',
        ]);

        // Capture to the layout view's "article" variable
        $view->setCaptureTo('article');

        return $view;
    }
}
```

There will be times you don't want to render a layout. For example, you might be
answering an API call which expects JSON or an XML payload, or you might be
answering an XHR request that expects a partial HTML payload. To do this,
explicitly create and return a view model from your controller, and mark it as
"terminal", which will hint to the MVC listener that normally injects the
returned View Model into the layout View Model, to instead replace the layout
view model.

```php
namespace Foo\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;

class BazBatController extends AbstractActionController
{
    public function doSomethingCrazyAction()
    {
        $view = new ViewModel([
            'message' => 'Hello world',
        ]);

        // Disable layouts; `MvcEvent` will use this View Model instead
        $view->setTerminal(true);

        return $view;
    }
}
```

[When discussing nesting View Models](#nesting-view-models), we detailed a
nested View Model which contained an article and sidebars. Sometimes, you may
want to provide additional View Models to the layout, instead of nesting in the
returned layout. This may be done by using the `layout()` controller plugin,
which returns the root View Model. You can then call the same `addChild()`
method on it as we did in that previous example.

```php
namespace Content\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;

class ArticleController extends AbstractActionController
{
    public function viewAction()
    {
        // get the article from the persistence layer, etc...

        // Get the "layout" view model and inject a sidebar
        $layout = $this->layout();
        $sidebarView = new ViewModel();
        $sidebarView->setTemplate('content/sidebar');
        $layout->addChild($sidebarView, 'sidebar');

        // Create and return a view model for the retrieved article
        $view = new ViewModel(['article' => $article]);
        $view->setTemplate('content/article');
        return $view;
    }
}
```

You could also use this technique to select a different layout, by calling the
`setTemplate()` method of the layout View Model:

```php
//In a controller
namespace Content\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;

class ArticleController extends AbstractActionController
{
    public function viewAction()
    {
        // get the article from the persistence layer, etc...

        // Get the "layout" view model and set an alternate template
        $layout = $this->layout();
        $layout->setTemplate('article/layout');

        // Create and return a view model for the retrieved article
        $view = new ViewModel(['article' => $article]);
        $view->setTemplate('content/article');
        return $view;
    }
}
```

Sometimes, you may want to access the layout from within your actual view
scripts when using the `PhpRenderer`. Reasons might include wanting to change
the layout template, or wanting to either access or inject layout view variables.
Similar to the `layout()` controller plugin, you can use the `layout()` View Helper.
If you provide a string argument to it, you will change the template; if you
provide no arguments, the root layout View Model is returned.

```php
//In a view script

// Change the layout:
$this->layout('alternate/layout'); // OR
$this->layout()->setTemplate('alternate/layout');

// Access a layout variable.
// Since access to the base view model is relatively easy, it becomes a
// reasonable place to store things such as API keys, which other view scripts
// may need.
$layout       = $this->layout();
$disqusApiKey = false;
if (isset($layout->disqusApiKey)) {
    $disqusApiKey = $layout->disqusApiKey;
}

// Set a layout variable
$this->layout()->footer = $this->render('article/footer');
```

Commonly, you may want to alter the layout based on the current **module**. This
requires (a) detecting if the controller matched in routing belongs to this
module, and then (b) changing the template of the View Model.

The place to do these actions is in a listener. It should listen either to the
`route` event at low (negative) priority, or on the `dispatch` event, at any
priority. Typically, you will register this during the bootstrap event.

```php
namespace Content;

class Module
{
    /**
     * @param  \Zend\Mvc\MvcEvent $e The MvcEvent instance
     * @return void
     */
    public function onBootstrap($e)
    {
        // Register a dispatch event
        $app = $e->getParam('application');
        $app->getEventManager()->attach('dispatch', [$this, 'setLayout']);
    }

    /**
     * @param  \Zend\Mvc\MvcEvent $e The MvcEvent instance
     * @return void
     */
    public function setLayout($e)
    {
        $matches    = $e->getRouteMatch();
        $controller = $matches->getParam('controller');
        if (false === strpos($controller, __NAMESPACE__)) {
            // not a controller from this module
            return;
        }

        // Set the layout template
        $viewModel = $e->getViewModel();
        $viewModel->setTemplate('content/layout');
    }
}
```

## Creating and Registering Alternate Rendering and Response Strategies

`Zend\View\View` does very little. Its workflow is essentially to martial a
`ViewEvent`, and then trigger two events, `renderer` and `response`. You can
attach "strategies" to these events, using the methods `addRenderingStrategy()`
and `addResponseStrategy()`, respectively. A Rendering Strategy introspects the
Request object (or any other criteria) in order to select a Renderer (or fail to
select one). A Response Strategy determines how to populate the Response based
on the result of rendering.

zend-view ships with three Rendering and Response Strategies that you can use
within your application.

- `Zend\View\Strategy\PhpRendererStrategy`. This strategy is a "catch-all" in
  that it will always return the `Zend\View\Renderer\PhpRenderer` and populate
  the Response body with the results of rendering.
- `Zend\View\Strategy\JsonStrategy`. This strategy inspects the `Accept` HTTP
  request header, if present, and determines if the client has indicated it
  accepts an `application/json` response. If so, it will return the
  `Zend\View\Renderer\JsonRenderer`, and populate the Response body with the
  JSON value returned, as well as set a `Content-Type` header with a value of
  `application/json`.
- `Zend\View\Strategy\FeedStrategy`. This strategy inspects the `Accept` HTTP
  header, if present, and determines if the client has indicated it accepts
  either an `application/rss+xml` or `application/atom+xml` response. If so, it
  will return the `Zend\View\Renderer\FeedRenderer`, setting the feed type to
  either "rss" or "atom", based on what was matched. Its Response strategy will
  populate the Response body with the generated feed, as well as set a
  `Content-Type` header with the appropriate value based on feed type.

By default, only the `PhpRendererStrategy` is registered, meaning you will need
to register the other Strategies yourself if you want to use them. Additionally,
it means that you will likely want to register these at higher priority to
ensure they match before the `PhpRendererStrategy`. As an example, let's
register the `JsonStrategy`:

```php
namespace Application;

class Module
{
    /**
     * @param  \Zend\Mvc\MvcEvent $e The MvcEvent instance
     * @return void
     */
    public function onBootstrap($e)
    {
        // Register a "render" event, at high priority (so it executes prior
        // to the view attempting to render)
        $app = $e->getApplication();
        $app->getEventManager()->attach('render', [$this, 'registerJsonStrategy'], 100);
    }

    /**
     * @param  \Zend\Mvc\MvcEvent $e The MvcEvent instance
     * @return void
     */
    public function registerJsonStrategy($e)
    {
        $app          = $e->getTarget();
        $locator      = $app->getServiceManager();
        $view         = $locator->get('Zend\View\View');
        $jsonStrategy = $locator->get('ViewJsonStrategy');

        // Attach strategy, which is a listener aggregate, at high priority
        $view->getEventManager()->attach($jsonStrategy, 100);
    }
}
```

The above will register the `JsonStrategy` with the "render" event, such that it
executes prior to the `PhpRendererStrategy`, and thus ensure that a JSON payload
is created when requested.

What if you want this to happen only in specific modules, or specific
controllers? One way is similar to the last example in the
[previous section on layouts](#dealing-with-layouts), where we detailed changing
the layout for a specific module:

```php
namespace Content;

class Module
{
    /**
     * @param  \Zend\Mvc\MvcEvent $e The MvcEvent instance
     * @return void
     */
    public function onBootstrap($e)
    {
        // Register a render event
        $app = $e->getParam('application');
        $app->getEventManager()->attach('render', [$this, 'registerJsonStrategy'], 100);
    }

    /**
     * @param  \Zend\Mvc\MvcEvent $e The MvcEvent instance
     * @return void
     */
    public function registerJsonStrategy($e)
    {
        $matches    = $e->getRouteMatch();
        $controller = $matches->getParam('controller');
        if (false === strpos($controller, __NAMESPACE__)) {
            // not a controller from this module
            return;
        }

        // Potentially, you could be even more selective at this point, and test
        // for specific controller classes, and even specific actions or request
        // methods.

        // Set the JSON strategy when controllers from this module are selected
        $app          = $e->getTarget();
        $locator      = $app->getServiceManager();
        $view         = $locator->get('Zend\View\View');
        $jsonStrategy = $locator->get('ViewJsonStrategy');

        // Attach strategy, which is a listener aggregate, at high priority
        $view->getEventManager()->attach($jsonStrategy, 100);
    }
}
```

While the above examples detail using the `JsonStrategy`, the same could be done
for the `FeedStrategy`.

What if you want to use a custom renderer? Or if your app might allow a
combination of JSON, Atom feeds, and HTML? At this point, you'll need to create
your own custom strategies. Below is an example that appropriately loops through
the HTTP `Accept` header, and selects the appropriate Renderer based on what is
matched first.

```php
namespace Content\View;

use Zend\EventManager\EventManagerInterface;
use Zend\EventManager\ListenerAggregateInterface;
use Zend\EventManager\ListenerAggregateTrait;
use Zend\Feed\Writer\Feed;
use Zend\View\Renderer\FeedRenderer;
use Zend\View\Renderer\JsonRenderer;
use Zend\View\Renderer\PhpRenderer;

class AcceptStrategy implements ListenerAggregateInterface
{
    use ListenerAggregateTrait;

    protected $feedRenderer;
    protected $jsonRenderer;
    protected $phpRenderer;

    public function __construct(
        PhpRenderer $phpRenderer,
        JsonRenderer $jsonRenderer,
        FeedRenderer $feedRenderer
    ) {
        $this->phpRenderer  = $phpRenderer;
        $this->jsonRenderer = $jsonRenderer;
        $this->feedRenderer = $feedRenderer;
    }

    public function attach(EventManagerInterface $events, $priority = 1)
    {
        $this->listeners[] = $events->attach('renderer', [$this, 'selectRenderer'], $priority);
        $this->listeners[] = $events->attach('response', [$this, 'injectResponse'], $priority);
    }

    /**
     * @param  \Zend\Mvc\MvcEvent $e The MvcEvent instance
     * @return \Zend\View\Renderer\RendererInterface
     */
    public function selectRenderer($e)
    {
        $request = $e->getRequest();
        $headers = $request->getHeaders();

        // No Accept header? return PhpRenderer
        if (!$headers->has('accept')) {
            return $this->phpRenderer;
        }

        $accept = $headers->get('accept');
        foreach ($accept->getPrioritized() as $mediaType) {
            if (0 === strpos($mediaType, 'application/json')) {
                return $this->jsonRenderer;
            }

            if (0 === strpos($mediaType, 'application/rss+xml')) {
                $this->feedRenderer->setFeedType('rss');
                return $this->feedRenderer;
            }

            if (0 === strpos($mediaType, 'application/atom+xml')) {
                $this->feedRenderer->setFeedType('atom');
                return $this->feedRenderer;
            }
        }

        // Nothing matched; return PhpRenderer. Technically, we should probably
        // return an HTTP 415 Unsupported response.
        return $this->phpRenderer;
    }

    /**
     * @param  \Zend\Mvc\MvcEvent $e The MvcEvent instance
     * @return void
     */
    public function injectResponse($e)
    {
        $renderer = $e->getRenderer();
        $response = $e->getResponse();
        $result   = $e->getResult();

        if ($renderer === $this->jsonRenderer) {
            // JSON Renderer; set content-type header
            $headers = $response->getHeaders();
            $headers->addHeaderLine('content-type', 'application/json');
            $response->setContent($result);
            return
        }

        if ($renderer === $this->feedRenderer) {
            // Feed Renderer; set content-type header, and export the feed if
            // necessary
            $feedType  = $this->feedRenderer->getFeedType();
            $headers   = $response->getHeaders();
            $mediatype = 'application/'
                       . (('rss' == $feedType) ? 'rss' : 'atom')
                       . '+xml';
            $headers->addHeaderLine('content-type', $mediatype);

            // If the $result is a feed, export it
            if ($result instanceof Feed) {
                $result = $result->export($feedType);
            }

            $response->setContent($result);
            return;
        }
    }
}
```

This strategy would be registered just as we demonstrated registering the
`JsonStrategy` earlier.  You would also need to define service manager
configuration to ensure the various renderers are injected when you retrieve the
strategy from the application's locator instance.


text:
package io.cloudslang.content.httpclient.services;

import io.cloudslang.content.httpclient.entities.*;
import io.cloudslang.content.httpclient.utils.HeaderObj;
import org.apache.commons.lang3.*;
import org.apache.hc.client5.http.classic.methods.*;

import static io.cloudslang.content.httpclient.utils.Constants.*;

public class HeaderBuilder {

    public static void headerBuiler(HttpUriRequestBase httpRequest, HttpClientInputs httpClientInputs) {

        if (!StringUtils.isEmpty(httpClientInputs.getHeaders())) {
            if (!httpClientInputs.getContentType().isEmpty()) {
                String[] headerList = httpClientInputs.getHeaders().split(COMMA);
                boolean counter = false;
                for (String eachHeader : headerList) {
                    if (eachHeader.toLowerCase().contains(CONTENT_TYPE.toLowerCase())) {
                        httpRequest.setHeader(new HeaderObj(CONTENT_TYPE, httpClientInputs.getContentType()));
                        counter = true;
                    } else {
                        String[] headerListSingle = eachHeader.split(COLON);
                        httpRequest.setHeader(new HeaderObj(headerListSingle[0].trim(), headerListSingle[1]));
                    }
                }
                if(!counter)
                    httpRequest.setHeader(new HeaderObj(CONTENT_TYPE, httpClientInputs.getContentType()));
            } else {
                String[] listheader = httpClientInputs.getHeaders().split(COMMA);
                for (String list : listheader) {
                    String[] headerListSingle = list.split(COLON);
                    httpRequest.setHeader(new HeaderObj(headerListSingle[0].trim(), headerListSingle[1]));
                }
            }
        } else if (!httpClientInputs.getContentType().isEmpty())
            httpRequest.setHeader(new HeaderObj(CONTENT_TYPE, httpClientInputs.getContentType()));
    }
}


text:
"""
dbseeder
----------------------------------

The main entry point for the package. Handles command line
operations for seeding/updating packages.
"""
import arcpy
import argparse
import os
from models import Field, Schema, TableInfo
from programs import Sdwis, Wqp, Dogm, Udwr, Ugs
from services import ConsolePrompt

class Seeder(object):
    #: the parent location of the gdb
    parent_folder = None
    #: the name of the gdb to seed
    gdb_name = None
    #: the combination of the parent_folder and the gdb_name
    location = None
    #: the number of records to query for sdwis
    count = None

    def __init__(self, parent_folder='./', gdb_name='WQP.gdb'):
        self.parent_folder = parent_folder
        self.gdb_name = gdb_name
        self.location = os.path.join(self.parent_folder, self.gdb_name)

    def _create_gdb(self):
        arcpy.CreateFileGDB_management(self.parent_folder,
                                       self.gdb_name,
                                       'CURRENT')

    def _create_feature_classes(self, types):
        """creates feature classes for the given types"""

        results_table = TableInfo(self.location, 'Results')
        station_points = TableInfo(self.location, 'Stations')
        schema = Schema()

        if 'Results' in types:
            arcpy.CreateTable_management(self.location,
                                         results_table.name)

            self._add_fields(results_table, schema.result)

        if 'Stations' in types:
            sr = arcpy.SpatialReference(26912)
            arcpy.CreateFeatureclass_management(self.location,
                                                station_points.name,
                                                'POINT',
                                                spatial_reference=sr)

            self._add_fields(station_points, schema.station)

    def _add_fields(self, table, schema):
        """adds fields to the table"""

        for schema_info in schema:
            field = Field(schema_info)
            arcpy.AddField_management(table.location,
                                      field.field_name,
                                      field.field_type,
                                      field_length=field.field_length,
                                      field_alias=field.field_alias)

    def create_relationship(self):
        origin = os.path.join(self.location, 'Stations')
        desitination = os.path.join(self.location, 'Results')
        key = 'StationId'

        arcpy.CreateRelationshipClass_management(origin,
                                                 desitination,
                                                 'Stations_Have_Results',
                                                 'COMPOSITE',
                                                 'Results',
                                                 'Stations',
                                                 'FORWARD',
                                                 'ONE_TO_MANY',
                                                 'NONE',
                                                 key,
                                                 key)

    def update(self):
        pass

    def field_lengths(self, types):
        if types[0].lower() == 'wqp':
            seed_data = 'C:\\Projects\\GitHub\\ugs-chemistry\\scripts\\dbseeder\\data'
            program = Wqp(self.location, arcpy.da.InsertCursor)

            return program.field_lengths(seed_data, types[1])

    def seed(self, folder, types):
        """
            #: folder - parent folder to seed data
            #: types - the type of data to seed [Stations, Results]
        """
        gdb_exists = os.path.exists(self.location)
        prompt = ConsolePrompt()

        if not gdb_exists:
            print 'creating gdb'
            self._create_gdb()
            print 'creating gdb: done'

            print 'creating feature classes'
            self._create_feature_classes(types)
            print 'creating feature classes: done'
        else:
            if not prompt.query_yes_no('gdb already exists. Seeed missing feature classes?'):
                if not prompt.query_yes_no('seed data? Could cause duplication'):
                    raise SystemExit('stopping')
                else:
                    self._seed(folder, types)
                    return
            else:
                print 'creating feature classes'
                self._create_feature_classes(types)
                print 'creating feature classes: done'

        self._seed(folder, types)

    def _seed(self, folder, types):
        wqp = Wqp(self.location, arcpy.da.InsertCursor)
        wqp.seed(folder, types)

        sdwis = Sdwis(self.location, arcpy.da.InsertCursor)
        sdwis.count = self.count
        sdwis.seed(types)

        dogm = Dogm(
            self.location, arcpy.da.SearchCursor, arcpy.da.InsertCursor)
        dogm.seed(folder, types)

        dwr = Udwr(
            self.location, arcpy.da.SearchCursor, arcpy.da.InsertCursor)
        dwr.seed(folder, types)

        ugs = Ugs(self.location, arcpy.da.SearchCursor, arcpy.da.InsertCursor)
        ugs.seed(folder, types)

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='seed a geodatabse.')

    parser.add_argument(
        '--update', action='store_true', help='update the gdb')
    parser.add_argument(
        '--seed', nargs='*', help='seed the gdb from a datasource on disk')
    parser.add_argument(
        '--length', nargs='*', help='get the max field sizes from files on disk. --length program featureclass')
    parser.add_argument(
        '--relate', action='store_true',
        help='creates the releationship class between stations and results')

    args = parser.parse_args()

    location = 'c:\\temp\\'
    gdb = 'master.gdb'
    seed_data = r'C:\Projects\GitHub\ugs-chemistry\scripts\dbseeder\data'

    try:
        if args.update:
            pass
        elif args.length:
            seeder = Seeder(location, gdb)
            maps = seeder.field_lengths(args.length)

            for key in maps.keys():
                print '{}'.format(maps[key])
        elif args.relate:
            seeder = Seeder(location, gdb)
            seeder.create_relationship()
        else:
            if args.seed is None:
                args.seed = ['Stations', 'Results']

            print 'seeding {} with {}'.format(gdb, args.seed)
            seeder = Seeder(location, gdb)
            seeder.seed(seed_data, args.seed)

        print 'finished'
    except:
        raise


text:
namespace mdt {

class RpcClient {
public:
    RpcClient() {
        ::sofa::pbrpc::RpcClientOptions options;
        options.max_pending_buffer_size = 128;
        _rpc_client = new sofa::pbrpc::RpcClient(options);
        //pthread_spinlock_init(&_server_map_lock, PTHREAD_PROCESS_SHARED);
    }
    ~RpcClient() {
        //delete _rpc_client;
        //pthread_spinlock_destory(&_server_map_lock);
    }

    template <class ServiceType>
    Status GetMethodList(const std::string& server_addr, ServiceType** service) {
        ::sofa::pbrpc::RpcChannel* channel = NULL;
        //pthread_spin_lock(&_server_map_lock);
        _server_map_lock.Lock();
        ServerMap::iterator it = _server_map.find(server_addr);
        if (it == _server_map.end()) {
            ::sofa::pbrpc::RpcChannelOptions options;
            channel = new ::sofa::pbrpc::RpcChannel(_rpc_client, server_addr, options);
            _server_map[server_addr] = channel;
        } else {
            channel = it->second;
        }
        //pthread_spin_unlock(&_server_map_lock);
        _server_map_lock.Unlock();
        *service = new ServiceType(channel);
        return Status::OK();
    }

    // default timeout 3000ms, rpc_timeout (in second)
    template <class ServiceType, class Request, class Response, class Callback>
    Status SyncCall(ServiceType* service, void(ServiceType::*func)(
                    ::google::protobuf::RpcController*,
                    const Request*, Response*, Callback*),
                    const Request* request, Response* response,
                    int32_t rpc_timeout = 10, int32_t retry_times = 3) {
        ::sofa::pbrpc::RpcController ctrl;
        ctrl.SetTimeout(rpc_timeout * 1000L);
        for (int i = 0; i < retry_times; i++) {
            (service->*func)(&ctrl, request, response, NULL);
            if (!ctrl.Failed()) {
                return Status::OK();
            }
            ctrl.Reset();
        }
        return Status::OK();
    }

    template <class ServiceType, class Request, class Response, class Callback>
    Status AsyncCall(ServiceType* service, void(ServiceType::*func)(
                     ::google::protobuf::RpcController*,
                     const Request*, Response*, Callback*),
                     const Request* request, Response* response,
                     boost::function<void (const Request*, Response*, bool, int)> callback,
                     int32_t rpc_timeout = 600, int32_t retry_times = 3) {
        ::sofa::pbrpc::RpcController* ctrl = new ::sofa::pbrpc::RpcController();
        ctrl->SetTimeout(rpc_timeout * 1000L);
        ::google::protobuf::Closure* done =
            ::sofa::pbrpc::NewClosure(&RpcClient::template RpcCallback<Request, Response, Callback>,
                                      ctrl, request, response, callback);
        (service->*func)(ctrl, request, response, done);
        return Status::OK();
    }

    template <class Request, class Response, class Callback>
    static void RpcCallback(::sofa::pbrpc::RpcController* controller,
                            const Request* request, Response* response,
                            boost::function<void (const Request*, Response*, bool, int)> callback) {
        bool failed = controller->Failed();
        int error = controller->ErrorCode();
        delete controller;
        callback(request, response, failed, error);
    }

private:
    ::sofa::pbrpc::RpcClient* _rpc_client;
    typedef std::map<std::string, ::sofa::pbrpc::RpcChannel*> ServerMap;
    ///pthread_spinlock_t _server_map_lock;
    Mutex _server_map_lock;
    ServerMap _server_map;
};

}
#endif


text:
- Fix powershell streams leaking to standard error breaking Windows 10, issue #18

# 0.2.1
- Fixed issue 16 creating zip file on Windows

# 0.2.0
- Redesigned temp zip file creation system
- Fixed lots of small edge case issues especially with directory uploads
- Simplified file manager upload method API to take only a single source file or directory
- Expanded acceptable username and hostnames for rwinrmcp

# 0.1.0
- Initial alpha quality release


text:
package com.clockwise.tworcy.model.game;

import java.security.AccessControlException;
import java.util.List;

import org.springframework.stereotype.Service;

import com.clockwise.tworcy.exception.ParameterTooLongException;
import com.clockwise.tworcy.model.account.Account;
import com.clockwise.tworcy.model.game.Game;
import com.clockwise.tworcy.model.game.GameDAOHibernate;

public @Service interface GameService {
	/**
	 * Adds the game by this account.
	 * @param game created by user. Only title and content is required.
	 * @param account which created the game.
	 * @throws AccessControlException if account has no permission to add game.
	 * @throws ParameterTooLongException if title or description is too long
	 * @return game with set it's table id and authorID
	 */
	public Game addGame(Game game, Account account) throws AccessControlException, ParameterTooLongException;
	public Game createGame(String title, String description, Account account) throws AccessControlException, ParameterTooLongException;

	/**
	 * Updates game by this account.
	 * @param game data to update.
	 * @param account which updated the game.
	 * @throws AccessControlException if account has no permission to update game.
	 * @throws ParameterTooLongException if title or description is too long
	 * @return updated game
	 */
	public Game updateGame(Game game, Account account) throws AccessControlException, ParameterTooLongException;

	/**
	 * Removes the game by this account.
	 * @param game which are going to be removed.
	 * @param account which removes the game.
	 * @throws AccessControlException if account has no permission to remove game.
	 * @throws ParameterTooLongException if title or description is too long
	 */
	public void removeBy(Game game, Account account) throws AccessControlException, ParameterTooLongException;

	/**
	 * Catches the count of records from database. It is fast if cached version of repository will be used.
	 * @see GameDAOHibernate
	 */
	public Integer getGameCount();

	/**
	 * Catches game by it's id.
	 * @param gameId
	 * @return null if no game was found
	 */
	public Game getSpecificByID(Integer gameId);

	/**
	 * Catches game created by the given account.
	 * @param account uses id of the user.
	 * @param count of entries for the catch
	 * @param offset from when should the counting start
	 * @return null if no game were found.
	 */
	public List<Game> getUserGames(Account account, Integer count, Integer offset);

	/**
	 * Catches all games.
	 * @param count of entries for the catch
	 * @param offset from when should the counting start
	 * @return null if no game were found.
	 */
	public List<Game> getRecentGames(Integer count, Integer offset);

	/**
	 * Checks if specified account can edit current game.
	 * @param account
	 * @param id
	 * @throws ParameterTooLongException if game received contains too long parameters
	 * @throws NullPointerException if game requested does not exist
	 * @return false if can't
	 */
	public boolean canEdit(Account account, Integer id) throws NullPointerException, ParameterTooLongException;

	public String getAuthorName(Integer gameId);
	public String getAuthorName(Game game);
}


text:
#ifndef __IP_SET_BITMAP_IP_GEN_H
#define __IP_SET_BITMAP_IP_GEN_H

#define mtype_do_test		IPSET_TOKEN(MTYPE, _do_test)
#define mtype_gc_test		IPSET_TOKEN(MTYPE, _gc_test)
#define mtype_is_filled		IPSET_TOKEN(MTYPE, _is_filled)
#define mtype_do_add		IPSET_TOKEN(MTYPE, _do_add)
#define mtype_ext_cleanup	IPSET_TOKEN(MTYPE, _ext_cleanup)
#define mtype_do_del		IPSET_TOKEN(MTYPE, _do_del)
#define mtype_do_list		IPSET_TOKEN(MTYPE, _do_list)
#define mtype_do_head		IPSET_TOKEN(MTYPE, _do_head)
#define mtype_adt_elem		IPSET_TOKEN(MTYPE, _adt_elem)
#define mtype_add_timeout	IPSET_TOKEN(MTYPE, _add_timeout)
#define mtype_gc_init		IPSET_TOKEN(MTYPE, _gc_init)
#define mtype_kadt		IPSET_TOKEN(MTYPE, _kadt)
#define mtype_uadt		IPSET_TOKEN(MTYPE, _uadt)
#define mtype_destroy		IPSET_TOKEN(MTYPE, _destroy)
#define mtype_flush		IPSET_TOKEN(MTYPE, _flush)
#define mtype_head		IPSET_TOKEN(MTYPE, _head)
#define mtype_same_set		IPSET_TOKEN(MTYPE, _same_set)
#define mtype_elem		IPSET_TOKEN(MTYPE, _elem)
#define mtype_test		IPSET_TOKEN(MTYPE, _test)
#define mtype_add		IPSET_TOKEN(MTYPE, _add)
#define mtype_del		IPSET_TOKEN(MTYPE, _del)
#define mtype_list		IPSET_TOKEN(MTYPE, _list)
#define mtype_gc		IPSET_TOKEN(MTYPE, _gc)
#define mtype			MTYPE

#define get_ext(set, map, id)	((map)->extensions + (set)->dsize * (id))

static void
mtype_gc_init(struct ip_set *set, void (*gc)(unsigned long ul_set))
{
	struct mtype *map = set->data;

	init_timer(&map->gc);
	map->gc.data = (unsigned long) set;
	map->gc.function = gc;
	map->gc.expires = jiffies + IPSET_GC_PERIOD(set->timeout) * HZ;
	add_timer(&map->gc);
}

static void
mtype_ext_cleanup(struct ip_set *set)
{
	struct mtype *map = set->data;
	u32 id;

	for (id = 0; id < map->elements; id++)
		if (test_bit(id, map->members))
			ip_set_ext_destroy(set, get_ext(set, map, id));
}

static void
mtype_destroy(struct ip_set *set)
{
	struct mtype *map = set->data;

	if (SET_WITH_TIMEOUT(set))
		del_timer_sync(&map->gc);

	ip_set_free(map->members);
	if (set->dsize) {
		if (set->extensions & IPSET_EXT_DESTROY)
			mtype_ext_cleanup(set);
		ip_set_free(map->extensions);
	}
	kfree(map);

	set->data = NULL;
}

static void
mtype_flush(struct ip_set *set)
{
	struct mtype *map = set->data;

	if (set->extensions & IPSET_EXT_DESTROY)
		mtype_ext_cleanup(set);
	memset(map->members, 0, map->memsize);
}

static int
mtype_head(struct ip_set *set, struct sk_buff *skb)
{
	const struct mtype *map = set->data;
	struct nlattr *nested;

	nested = ipset_nest_start(skb, IPSET_ATTR_DATA);
	if (!nested)
		goto nla_put_failure;
	if (mtype_do_head(skb, map) ||
	    nla_put_net32(skb, IPSET_ATTR_REFERENCES, htonl(set->ref - 1)) ||
	    nla_put_net32(skb, IPSET_ATTR_MEMSIZE,
			  htonl(sizeof(*map) +
				map->memsize +
				set->dsize * map->elements)))
		goto nla_put_failure;
	if (unlikely(ip_set_put_flags(skb, set)))
		goto nla_put_failure;
	ipset_nest_end(skb, nested);

	return 0;
nla_put_failure:
	return -EMSGSIZE;
}

static int
mtype_test(struct ip_set *set, void *value, const struct ip_set_ext *ext,
	   struct ip_set_ext *mext, u32 flags)
{
	struct mtype *map = set->data;
	const struct mtype_adt_elem *e = value;
	void *x = get_ext(set, map, e->id);
	int ret = mtype_do_test(e, map, set->dsize);

	if (ret <= 0)
		return ret;
	if (SET_WITH_TIMEOUT(set) &&
	    ip_set_timeout_expired(ext_timeout(x, set)))
		return 0;
	if (SET_WITH_COUNTER(set))
		ip_set_update_counter(ext_counter(x, set), ext, mext, flags);
	return 1;
}

static int
mtype_add(struct ip_set *set, void *value, const struct ip_set_ext *ext,
	  struct ip_set_ext *mext, u32 flags)
{
	struct mtype *map = set->data;
	const struct mtype_adt_elem *e = value;
	void *x = get_ext(set, map, e->id);
	int ret = mtype_do_add(e, map, flags, set->dsize);

	if (ret == IPSET_ADD_FAILED) {
		if (SET_WITH_TIMEOUT(set) &&
		    ip_set_timeout_expired(ext_timeout(x, set)))
			ret = 0;
		else if (!(flags & IPSET_FLAG_EXIST))
			return -IPSET_ERR_EXIST;
		/* Element is re-added, cleanup extensions */
		ip_set_ext_destroy(set, x);
	}

	if (SET_WITH_TIMEOUT(set))
#ifdef IP_SET_BITMAP_STORED_TIMEOUT
		mtype_add_timeout(ext_timeout(x, set), e, ext, set, map, ret);
#else
		ip_set_timeout_set(ext_timeout(x, set), ext->timeout);
#endif

	if (SET_WITH_COUNTER(set))
		ip_set_init_counter(ext_counter(x, set), ext);
	if (SET_WITH_COMMENT(set))
		ip_set_init_comment(ext_comment(x, set), ext);
	return 0;
}

static int
mtype_del(struct ip_set *set, void *value, const struct ip_set_ext *ext,
	  struct ip_set_ext *mext, u32 flags)
{
	struct mtype *map = set->data;
	const struct mtype_adt_elem *e = value;
	void *x = get_ext(set, map, e->id);

	if (mtype_do_del(e, map))
		return -IPSET_ERR_EXIST;

	ip_set_ext_destroy(set, x);
	if (SET_WITH_TIMEOUT(set) &&
	    ip_set_timeout_expired(ext_timeout(x, set)))
		return -IPSET_ERR_EXIST;

	return 0;
}

#ifndef IP_SET_BITMAP_STORED_TIMEOUT
static inline bool
mtype_is_filled(const struct mtype_elem *x)
{
	return true;
}
#endif

static int
mtype_list(const struct ip_set *set,
	   struct sk_buff *skb, struct netlink_callback *cb)
{
	struct mtype *map = set->data;
	struct nlattr *adt, *nested;
	void *x;
	u32 id, first = cb->args[IPSET_CB_ARG0];

	adt = ipset_nest_start(skb, IPSET_ATTR_ADT);
	if (!adt)
		return -EMSGSIZE;
	for (; cb->args[IPSET_CB_ARG0] < map->elements;
	     cb->args[IPSET_CB_ARG0]++) {
		id = cb->args[IPSET_CB_ARG0];
		x = get_ext(set, map, id);
		if (!test_bit(id, map->members) ||
		    (SET_WITH_TIMEOUT(set) &&
#ifdef IP_SET_BITMAP_STORED_TIMEOUT
		     mtype_is_filled((const struct mtype_elem *) x) &&
#endif
		     ip_set_timeout_expired(ext_timeout(x, set))))
			continue;
		nested = ipset_nest_start(skb, IPSET_ATTR_DATA);
		if (!nested) {
			if (id == first) {
				nla_nest_cancel(skb, adt);
				return -EMSGSIZE;
			} else
				goto nla_put_failure;
		}
		if (mtype_do_list(skb, map, id, set->dsize))
			goto nla_put_failure;
		if (ip_set_put_extensions(skb, set, x,
		    mtype_is_filled((const struct mtype_elem *) x)))
			goto nla_put_failure;
		ipset_nest_end(skb, nested);
	}
	ipset_nest_end(skb, adt);

	/* Set listing finished */
	cb->args[IPSET_CB_ARG0] = 0;

	return 0;

nla_put_failure:
	nla_nest_cancel(skb, nested);
	if (unlikely(id == first)) {
		cb->args[IPSET_CB_ARG0] = 0;
		return -EMSGSIZE;
	}
	ipset_nest_end(skb, adt);
	return 0;
}

static void
mtype_gc(unsigned long ul_set)
{
	struct ip_set *set = (struct ip_set *) ul_set;
	struct mtype *map = set->data;
	void *x;
	u32 id;

	/* We run parallel with other readers (test element)
	 * but adding/deleting new entries is locked out */
	read_lock_bh(&set->lock);
	for (id = 0; id < map->elements; id++)
		if (mtype_gc_test(id, map, set->dsize)) {
			x = get_ext(set, map, id);
			if (ip_set_timeout_expired(ext_timeout(x, set))) {
				clear_bit(id, map->members);
				ip_set_ext_destroy(set, x);
			}
		}
	read_unlock_bh(&set->lock);

	map->gc.expires = jiffies + IPSET_GC_PERIOD(set->timeout) * HZ;
	add_timer(&map->gc);
}

static const struct ip_set_type_variant mtype = {
	.kadt	= mtype_kadt,
	.uadt	= mtype_uadt,
	.adt	= {
		[IPSET_ADD] = mtype_add,
		[IPSET_DEL] = mtype_del,
		[IPSET_TEST] = mtype_test,
	},
	.destroy = mtype_destroy,
	.flush	= mtype_flush,
	.head	= mtype_head,
	.list	= mtype_list,
	.same_set = mtype_same_set,
};

#endif /* __IP_SET_BITMAP_IP_GEN_H */


text:
package org.drools.core.command.runtime.rule;

import java.io.ByteArrayInputStream;
import java.io.StringWriter;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.xml.bind.JAXBContext;

import static org.hamcrest.core.Is.*;
import static org.hamcrest.core.IsInstanceOf.*;
import static org.junit.Assert.*;
import org.drools.core.common.DisconnectedFactHandle;
import org.drools.core.xml.jaxb.util.JaxbListWrapper;
import org.junit.Test;

public class CommandSerializationTest {

    private Class<?>[] annotatedJaxbClasses = { JaxbListWrapper.class };

    @Test
    public void updateCommandTest() throws Exception {
        DisconnectedFactHandle discFactHandle = new DisconnectedFactHandle(2, 3, 4, 5l, "entry-point-id", "str-obj", true);

        DisconnectedFactHandle copyDiscFactHandle = roundTrip(discFactHandle);
        verifyDisconnectedFactHandle(discFactHandle, copyDiscFactHandle);

        UpdateCommand cmd = new UpdateCommand(discFactHandle, "new-str-object");
        UpdateCommand copyCmd = roundTrip(cmd);

        verifyDisconnectedFactHandle(discFactHandle, copyCmd.getHandle());
        assertEquals("entry point", cmd.getEntryPoint(), copyCmd.getEntryPoint());
        assertEquals("object", cmd.getObject(), copyCmd.getObject());
    }

    @Test
    public void insertObjectCommandTest() throws Exception {
        InsertObjectCommand cmd = new InsertObjectCommand("obj", "out-id");
        cmd.setReturnObject(false);
        cmd.setEntryPoint("entry-point");

        InsertObjectCommand copyCmd = roundTrip(cmd);

        assertEquals( "object", cmd.getObject(), copyCmd.getObject());
        assertEquals( "out id", cmd.getOutIdentifier(), copyCmd.getOutIdentifier() );
        assertEquals( "return obj", cmd.isReturnObject(), copyCmd.isReturnObject() );
        assertEquals( "entry point", cmd.getEntryPoint(), copyCmd.getEntryPoint() );
        assertEquals( "disconnected", cmd.isDisconnected(), copyCmd.isDisconnected() );
    }

    @Test
    public void insertObjectCommandListTest() throws Exception {
        List<String> objectList = new ArrayList<String>();
        objectList.add("obj");
        InsertObjectCommand cmd = new InsertObjectCommand(objectList, "out-id");

        InsertObjectCommand copyCmd = roundTrip(cmd);

        assertNotNull(copyCmd);
        assertThat(copyCmd.getObject(), is(instanceOf(List.class)));
        assertEquals( "object", cmd.getObject(), copyCmd.getObject());
    }

    @Test
    public void insertObjectCommandEmptyListTest() throws Exception {
        List<String> objectList = new ArrayList<String>();
        objectList.add("one-element");
        InsertObjectCommand cmd = new InsertObjectCommand(objectList, "out-id");

        // test list with 1 element
        InsertObjectCommand copyCmd = roundTrip(cmd);

        assertNotNull(copyCmd);
        assertThat(copyCmd.getObject(), is(instanceOf(List.class)));
        assertEquals( "object", cmd.getObject(), copyCmd.getObject());

        // test empty list
        objectList.clear();
        copyCmd = roundTrip(cmd);

        assertNotNull(copyCmd);
        assertThat(copyCmd.getObject(), is(instanceOf(List.class)));
        assertEquals( "object", cmd.getObject(), copyCmd.getObject());

    }

    private void verifyDisconnectedFactHandle( DisconnectedFactHandle orig, DisconnectedFactHandle copy ) {
        assertNotNull("copy disconnected fact handle is null", copy);
        assertEquals("id", orig.getId(), copy.getId());
        assertEquals("identity hash code", orig.getIdentityHashCode(), copy.getIdentityHashCode());
        assertEquals("object hash code", orig.getObjectHashCode(), copy.getObjectHashCode());
        assertEquals("recency", orig.getRecency(), copy.getRecency());
        assertEquals("entry point id", orig.getEntryPointId(), copy.getEntryPointId());
        assertEquals("object", orig.getObject(), copy.getObject());
        assertEquals("trait type", orig.getTraitType(), copy.getTraitType());
    }

    private <T> T roundTrip( Object obj ) throws Exception {
        Class[] classes = { obj.getClass() };
        JAXBContext ctx = getJaxbContext(classes);
        String xmlOut = marshall(ctx, obj);
        return unmarshall(ctx, xmlOut);
    }

    private <T> T unmarshall( JAXBContext ctx, String xmlIn ) throws Exception {
        ByteArrayInputStream xmlStrInputStream = new ByteArrayInputStream(xmlIn.getBytes(Charset.forName("UTF-8")));
        Object out = ctx.createUnmarshaller().unmarshal(xmlStrInputStream);
        return (T) out;
    }

    private String marshall( JAXBContext ctx, Object obj ) throws Exception {
        StringWriter writer = new StringWriter();
        ctx.createMarshaller().marshal(obj, writer);
        return writer.getBuffer().toString();
    }

    private JAXBContext getJaxbContext( Class<?>... classes ) throws Exception {
        List<Class<?>> jaxbClassList = new ArrayList<Class<?>>();
        jaxbClassList.addAll(Arrays.asList(classes));
        jaxbClassList.addAll(Arrays.asList(annotatedJaxbClasses));
        Class<?>[] jaxbClasses = jaxbClassList.toArray(new Class[jaxbClassList.size()]);
        return JAXBContext.newInstance(jaxbClasses);
    }
}


text:
package net.ontopia.topicmaps.rest.exceptions;

import org.restlet.data.Status;

public class OntopiaRestException extends RuntimeException {
	private static final long serialVersionUID = 1L;

	private Status status;
	private int ontopiaCode = -1;

	public OntopiaRestException(OntopiaRestErrors error, Object... parameters) {
		this(error, null, parameters);
	}
	public OntopiaRestException(OntopiaRestErrors error, Throwable cause, Object... parameters) {
		super(error.getMessage(parameters), cause);
		status = new Status(error.getStatus(), this, getMessage());
		ontopiaCode = error.getCode();
	}

	public OntopiaRestException(Status status) {
		super(status.getDescription());
		this.status = status;
	}

	public OntopiaRestException(Status status, String description) {
		super(description);
		this.status = new Status(status, this, description);
	}

	public OntopiaRestException(Status status, String description, Throwable cause) {
		super(description, cause);
		this.status = new Status(status, this, description);
	}

	public OntopiaRestException(Status status, Throwable cause) {
		super(cause);
		this.status = new Status(status, this);
	}

	public Status getStatus() {
		return status;
	}

	public int getOntopiaCode() {
		return ontopiaCode;
	}
}


text:
<html>
  <head>
    <title>Dodger</title>
    <!-- Phaser 2.4.4 Amador -->
    <script type="text/javascript" src="../node_modules/phaser/dist/phaser.min.js"></script>
    <script type="text/javascript" src="../plugins/PrimitiveShapes.js"></script>

    <script type="text/javascript" src="states/GameState.js"></script>
    <script type="text/javascript" src="states/GameOverState.js"></script>

    <script type="text/javascript" src="game.js"></script>
    <meta charset="utf-8" />
  </head>

  <body>

  </body>
</html>


text:
compiler_path=/usr/lib/gcc-mozilla
if [ -x "${compiler_path}/bin/gcc" ]; then
  export PATH="${compiler_path}/bin:$PATH"
  export LD_LIBRARY_PATH="${compiler_path}/lib:${LD_LIBRARY_PATH:-}"
  : ${CC:="${compiler_path}/bin/gcc"}
  : ${CXX:="${compiler_path}/bin/g++"}
  export CC CXX
fi

export PATH=$HOME/bin:/usr/local/bin:$PATH

# precise_i386, for instance.
CHROOT_NAME="$(lsb_release -cs)_i386"

PKG_EXTENSION=deb


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.8"/>
<title>AADC: Class Members</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

AADC

Main Page

Namespaces

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Class List

Class Index

Class Hierarchy

Class Members

All

Functions

Variables

a

b

c

d

g

i

l

m

n

o

p

r

s

t

u

w

x

y

z

~

 All Classes Namespaces Files Functions Variables Enumerations

Here is a list of all documented class members with links to the class documentation for each member:

- o -

OnAppendText()
: DisplayWidget

OnDriverState()
: DisplayWidget

OnKeyEvent()
: CarControlFilter

OnNotAus()
: cJuryTransmitter

OnPinEvent()
: CarControlFilter
, cDriverFilter

OnSendState()
: cDriverFilter

OnStart()
: cJuryTransmitter

OnStop()
: cJuryTransmitter

operator()()
: roadsignDetection::RoiPredicatePic

Generated on Tue Sep 16 2014 14:13:26 for AADC by

     1.8.8


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package erp.mtrn.data;

import java.sql.CallableStatement;

import erp.data.SProcConstants;
import erp.lib.SLibConstants;
import erp.lib.SLibUtilities;

/**
 *
 * @author Alfonso Flores
 */
public class SProcGetDpsQuantitySupplied extends erp.lib.data.SDataProcedure implements java.io.Serializable {

    public SProcGetDpsQuantitySupplied() {
        super(SProcConstants.TRN_GET_DPS_QTY_SUP);
    }

    @Override
    public int call(java.sql.Connection connection) {
        int nParam = 1;
        CallableStatement callableStatement = null;

        mnLastDbActionResult = SLibConstants.UNDEFINED;

        try {
            callableStatement = connection.prepareCall("{ CALL trn_get_good_f_qty_delivery(?, ?, ?, ?, ?, ?) }");
            callableStatement.setInt(nParam, (java.lang.Integer) mvParamsIn.get(nParam - 1)); nParam++;
            callableStatement.setInt(nParam, (java.lang.Integer) mvParamsIn.get(nParam - 1)); nParam++;
            callableStatement.setInt(nParam, (java.lang.Integer) mvParamsIn.get(nParam - 1)); nParam++;
            callableStatement.setInt(nParam, (java.lang.Integer) mvParamsIn.get(nParam - 1)); nParam++;
            callableStatement.setInt(nParam, (java.lang.Integer) mvParamsIn.get(nParam - 1)); nParam++;
            callableStatement.registerOutParameter(nParam, java.sql.Types.DECIMAL);
            callableStatement.execute();

            mvParamsOut.clear();
            mvParamsOut.add(callableStatement.getDouble(nParam));
            mnLastDbActionResult = SLibConstants.DB_PROCEDURE_OK;
        }
        catch (java.sql.SQLException e) {
            mnLastDbActionResult = SLibConstants.DB_PROCEDURE_ERROR;
            SLibUtilities.printOutException(this, e);
        }
        catch (java.lang.Exception e) {
            mnLastDbActionResult = SLibConstants.DB_PROCEDURE_ERROR;
            SLibUtilities.printOutException(this, e);
        }

        return mnLastDbActionResult;
    }
}


text:
package com.snowplowanalytics.sauna
package observers

// java
import java.nio.file._

// scala
import scala.collection.mutable
import scala.concurrent.duration._

// akka
import akka.actor._

// sauna
import Observer.{ LocalFilePublished, DeleteLocalFile }

/**
 * Local observer responsible for working with local system:
 * + signalling when new file is created on local filesystem
 * + maintaining list of known files
 * + deleting files
 *
 * @param root directory to track
 */
class LocalObserver(root: Path) extends Actor with Observer {
  import LocalObserver._

  import context.dispatcher

  /**
   * Sizes of each created file to track when copying is finishers
   */
  private val sizes = new mutable.HashMap[Path, Size]()

  /**
   * Run `FilesystemMonitor` in separate thread
   * It will message this actor about created files (but they can be on-write
   * at that moment)
   */
  // It's better to throw exceptions in monitor rather than stop gracefully
  // then LocalObserver will be restarted rather than hang
  private val monitor = new FilesystemMonitor(root, onCreated)
  private val watcherThread = new Thread(monitor)
  watcherThread.setDaemon(true)
  watcherThread.start()

  /**
   * Schedule check of sizes every 2 seconds
   * If after this period, file size hasn't been changed - its ready to be processed
   */
  private val tick = context.system.scheduler.schedule(1000.millis, 2000.millis, self, Tick)

  /**
   * Callback supposed to be called in `FilesystemMonitor` thread
   * when new file appears
   * Create message and send it to itself
   *
   * @param path local filesystem path to the file
   */
  def onCreated(path: Path): Unit = {
    self ! FileCreated(path)
  }

  /**
   * Update `sizes` hashmap with current size of file and return result
   * If size remains same - file write is completed, otherwise put new size
   *
   * @param file local filesystem path to a file
   * @param oldSize size currently written in `sizes`
   */
  def updateFile(file: Path, oldSize: Long): UpdateResult = {
    val newSize = Files.size(file)

    if (oldSize == newSize) {
      sizes.remove(file)
      Ready
    } else if (oldSize > newSize) {
      Error(s"Old size [$oldSize] is bigger than new [$newSize]", file)
    } else {
      sizes.put(file, newSize)
      Updated
    }
  }

  def receive = {
    case Tick =>
      sizes.foreach { case (path, size) =>
        updateFile(path, size) match {
          case Ready =>
            notify(s"Detected new local file [${path.toString}]")
            context.parent ! LocalFilePublished(path, self)
          case Updated => ()
          case Error(_, _) => ()
        }
      }

    case FileCreated(path) =>
      val newSize = Files.size(path)
      sizes.put(path, newSize)

    case deleteFile: DeleteLocalFile =>
      deleteFile.run()
  }

  /**
   * Clean-up resources
   */
  override def postStop(): Unit = {
    tick.cancel()
    watcherThread.interrupt()
  }
}

object LocalObserver {

  type Size = Long

  object Tick

  /**
   * File just appeared on filesystem.
   * This is private because its signalling from monitor thread only about
   * appearance of file, it can be writing at this moment `ObserverBatchEvent`
   * event must be used to signal responder
   */
  private[observers] case class FileCreated(path: Path)

  sealed trait UpdateResult extends Product with Serializable
  case object Updated extends UpdateResult
  case object Ready extends UpdateResult
  case class Error(message: String, path: Path) extends UpdateResult

  def props(path: Path): Props =
    Props(new LocalObserver(path))

  def props(path: String): Props =
    props(Paths.get(path))
}


text:
ROOT = File.expand_path(File.join(File.basename(__FILE__), '..'))

$: << File.join(ROOT, 'lib')

require 'minitest/unit'
require 'minitest/autorun'
require 'mocha'

require 'timeout' # assert_doesnt_time_out

module EnvHelpers
  def silence_warnings
    old = $VERBOSE
    $VERBOSE = nil
    yield
  ensure
    $VERBOSE = old
  end
end

class BaseTestCase < MiniTest::Unit::TestCase
  include EnvHelpers

  def assert_doesnt_time_out(n, reason = "", &blk)

    Timeout::timeout(n, &blk)
  rescue TimeoutError => err
    r_full = [reason, "(timed out after #{n}s)", "\n" + err.backtrace.join("\n")].join(" ")
    raise MiniTest::Assertion.new(r_full)
  end
end

class QMPClientTestCase < BaseTestCase

end


text:
import subprocess
import os
import os.path
import time
import traceback
import sys
import glob
import logging
import setup_util

from benchmark.utils import gather_tests

class Installer:

  ############################################################
  # install_software
  ############################################################
  def install_software(self):
    linux_install_root = self.fwroot + "/toolset/setup/linux"
    imode = self.benchmarker.install

    script_vars = {
      'TFB_DBHOST': self.benchmarker.database_host
    }
    l=[]
    for k,v in script_vars.iteritems():
      l.append("export %s=%s" % (k,v))
    script_vars_str = "\n".join(l) + "\n\n"

    if imode == 'all' or imode == 'database':
      print("\nINSTALL: Installing database software\n")
      self.__run_command("cd .. && " + self.benchmarker.database_sftp_string(batch_file="../config/database_sftp_batch"), True)
      with open (linux_install_root + "/database.sh", "r") as myfile:
        print("\nINSTALL: %s" % self.benchmarker.database_ssh_string)
        p = subprocess.Popen(self.benchmarker.database_ssh_string.split(" ") +
                             ["bash"], stdin=subprocess.PIPE)
        remote_script = myfile.read()
        p.communicate(script_vars_str + remote_script)
        returncode = p.returncode
        if returncode != 0:
          self.__install_error("status code %s running subprocess '%s'." % (returncode, self.benchmarker.database_ssh_string))
      print("\nINSTALL: Finished installing database software\n")

    if imode == 'all' or imode == 'client':
      print("\nINSTALL: Installing client software\n")
      with open (linux_install_root + "/client.sh", "r") as myfile:
        remote_script=myfile.read()
        print("\nINSTALL: %s" % self.benchmarker.client_ssh_string)
        p = subprocess.Popen(self.benchmarker.client_ssh_string.split(" ") + ["bash"], stdin=subprocess.PIPE)
        p.communicate(remote_script)
        returncode = p.returncode
        if returncode != 0:
          self.__install_error("status code %s running subprocess '%s'." % (returncode, self.benchmarker.client_ssh_string))
      print("\nINSTALL: Finished installing client software\n")
  ############################################################
  # End install_software
  ############################################################

  ############################################################
  # __install_error
  ############################################################
  def __install_error(self, message):
    print("\nINSTALL ERROR: %s\n" % message)
    if self.benchmarker.install_error_action == 'abort':
      sys.exit("Installation aborted.")
  ############################################################
  # End __install_error
  ############################################################

  ############################################################
  # __run_command
  ############################################################
  def __run_command(self, command, send_yes=False, cwd=None):
    if cwd is None:
        cwd = self.install_dir

    if send_yes:
      command = "yes yes | " + command

    rel_cwd = setup_util.path_relative_to_root(cwd)
    print("INSTALL: %s (cwd=$FWROOT/%s)" % (command, rel_cwd))

    try:
      subprocess.check_call(command, shell=True, cwd=cwd, executable='/bin/bash')
    except:
      exceptionType, exceptionValue, exceptionTraceBack = sys.exc_info()
      error_message = "".join(traceback.format_exception_only(exceptionType, exceptionValue))
      self.__install_error(error_message)
  ############################################################
  # End __run_command
  ############################################################

  ############################################################
  # __init__(benchmarker)
  ############################################################
  def __init__(self, benchmarker, install_strategy):
    self.benchmarker = benchmarker
    self.install_dir = "installs"
    self.fwroot = benchmarker.fwroot
    self.strategy = install_strategy

    # setup logging
    logging.basicConfig(stream=sys.stderr, level=logging.INFO)

    try:
      os.mkdir(self.install_dir)
    except OSError:
      pass
  ############################################################
  # End __init__
  ############################################################

# vim: sw=2


text:
package pbt4j;

import org.junit.*;
import org.junit.runner.RunWith;
import pbt4j.annotations.*;
import pbt4j.dto.*;
import pbt4j.score.*;

import java.util.*;
import java.util.function.*;
import java.util.stream.Stream;

import static org.junit.Assert.*;

/**
 * @author Linas on 2016.03.05.
 */
@RunWith(PropertyBasedTesting.class)
@JsEval("var Foo = Java.type('pbt4j.dto.Foo'); var Bean = Java.type('pbt4j.dto.Bean'); var SimpleDto = Java.type('pbt4j.dto.SimpleDto');")
public class PropertyBasedTestingTest {

    @Test
    public void shouldProvideTwoArguments(
           @JsonData({"1", "2"}) long numbers,
           @JsonData({"'foo'", "'bar'"}) String strings) {
        System.out.println("arg1: " + numbers);
        System.out.println("arg2: " + strings);
        //first run prints:
        // arg1: 1
        // arg2: foo
        //second run prints:
        // arg1: 2
        // arg2: bar
    }

    @Test
    public void shouldProvideListsOfArguments(
            @JsData({"['foo', 'bar']", "['second', 'third']"}) List<String> arg,
            @JsData({"[1, 2]", "[3, 4]"}) List<Integer> numbers) {

        assertEquals(2, arg.size());
        assertEquals(2, numbers.size());

        System.out.println(arg);
        System.out.println(numbers);
        //first run prints:
        // [foo, bar]
        // [1, 2]
        //second run prints:
        // [second, third]
        // [3, 4]
    }

    @Test
    public void shouldRunTestMethod100Times(String text) throws Exception {
        assertNotNull(text);
    }

    @Test
    @Repeat(times = 10)
    public void shouldProvideRandomValuesAndCallMethod10Times(int number) throws Exception {
        System.out.println(number);
        //Prints 10 random numbers
    }

    @Test
    public void shouldProvideMap( //this works only from JDK 8u60+
            @JsonData({"{foo: 'bar', second: 'bar2'}"}) Map<String, String> map
            ) throws Exception {
        assertEquals(HashMap.class, map.getClass());
        assertEquals("bar", map.get("foo"));
        assertEquals("bar2", map.get("second"));
        assertEquals(2, map.size());
    }

    @Test
    public void withoutParameters() throws Exception {
        assertTrue(true);
        //if test method does not contain parameters, just use junit default runner
    }

    @Test
    @Repeat(times = 1)
    public void shouldProvideCustomClass(Foo foo) throws Exception {
        assertNotNull(foo);
    }

    @Test
    @Repeat(times = 1)
    //@Named("should Provide Java bean")
    public void shouldProvideJavaBean(Bean bean) throws Exception {
        assertNotNull(bean);
        assertEquals("test", bean.finalValue);
        assertEquals("some data", Bean.STATIC_FIELD);
    }

    @Test
    public void shouldProvideCustomClassUsingJs(
            @JsData({"new Foo('Foo', 28, [new Bean()], null)"}) Foo foo) throws Exception {
        assertEquals("Foo", foo.name);
        assertEquals(28, foo.age);
        assertEquals(Foo.class, foo.getClass());
        assertEquals(1, foo.beans.size());
    }

    @Test
    public void shouldProvideSimpleDto(
            @JsData({"new SimpleDto('test', 100, ['Alice', 'Bob'])", "new SimpleDto('test2', 100, ['Alice', 'Bob'])"})
            SimpleDto simpleDto
    ) throws Exception {
        assertTrue(simpleDto.name.startsWith("test"));
        assertEquals(100, simpleDto.total);
        assertEquals("Alice", simpleDto.neighbours.get(0));
        assertEquals("Bob", simpleDto.neighbours.get(1));
        assertEquals(2, simpleDto.neighbours.size());
    }

    @SuppressWarnings("OptionalUsedAsFieldOrParameterType")
    @Test
    public void shouldProvideOptional(Optional<String> s) throws Exception {
        assertEquals(Optional.class, s.getClass());
    }

    @Test
    public void shouldProvideRandomByteArrays(byte[] bytes) throws Exception {
        System.out.println(Arrays.toString(bytes));
    }

    @Test
    public void shouldProvideEnums(Result result) throws Exception {
        assertTrue(result == Result.SUCCESS || result == Result.FAILURE);
    }

    @Test
    public void shouldProvideSupplier(Supplier<Integer> supplier) throws Exception {
        System.out.println(supplier.get());
    }

    @Test
    public void shouldProvideFunction(Function<Integer, Integer> function) throws Exception {
        System.out.println(function.apply(new Random().nextInt()));
    }

    @Test
    public void shouldProvideStream(Stream<Byte> stringStream) throws Exception {
        assertTrue(stringStream.count() >= 0);
    }

    @Test
    public void shouldAssertException() throws Exception {
        Check.assertException(RuntimeException.class, () -> {
            System.out.println("starting");
            throw new RuntimeException("error");
        });

    }

    @Test
    public void shouldProvideImplementationOfAnInterface(Score score) throws Exception {
        final Class<? extends Score> actual = score.getClass();
        System.out.println(actual);
        assertTrue(
                actual.equals(Advantage.class) ||
                actual.equals(Deuce.class) ||
                actual.equals(Forty.class) ||
                actual.equals(Game.class) ||
                actual.equals(Points.class)
            );
    }
}