text:
// MIT License:
//
// Copyright (c) 2010-2012, Joe Walnes
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

/**
 * This behaves like a WebSocket in every way, except if it fails to connect,
 * or it gets disconnected, it will repeatedly poll until it successfully connects
 * again.
 *
 * It is API compatible, so when you have:
 *   ws = new WebSocket('ws://....');
 * you can replace with:
 *   ws = new ReconnectingWebSocket('ws://....');
 *
 * The event stream will typically look like:
 *  onconnecting
 *  onopen
 *  onmessage
 *  onmessage
 *  onclose // lost connection
 *  onconnecting
 *  onopen  // sometime later...
 *  onmessage
 *  onmessage
 *  etc...
 *
 * It is API compatible with the standard WebSocket API, apart from the following members:
 *
 * - `bufferedAmount`
 * - `extensions`
 * - `binaryType`
 *
 * Latest version: https://github.com/joewalnes/reconnecting-websocket/
 * - Joe Walnes
 *
 * Syntax
 * ======
 * var socket = new ReconnectingWebSocket(url, protocols, options);
 *
 * Parameters
 * ==========
 * url - The url you are connecting to.
 * protocols - Optional string or array of protocols.
 * options - See below
 *
 * Options
 * =======
 * Options can either be passed upon instantiation or set after instantiation:
 *
 * var socket = new ReconnectingWebSocket(url, null, { debug: true, reconnectInterval: 4000 });
 *
 * or
 *
 * var socket = new ReconnectingWebSocket(url);
 * socket.debug = true;
 * socket.reconnectInterval = 4000;
 *
 * debug
 * - Whether this instance should log debug messages. Accepts true or false. Default: false.
 *
 * automaticOpen
 * - Whether or not the websocket should attempt to connect immediately upon instantiation. The socket can be manually opened or closed at any time using ws.open() and ws.close().
 *
 * reconnectInterval
 * - The number of milliseconds to delay before attempting to reconnect. Accepts integer. Default: 1000.
 *
 * maxReconnectInterval
 * - The maximum number of milliseconds to delay a reconnection attempt. Accepts integer. Default: 30000.
 *
 * reconnectDecay
 * - The rate of increase of the reconnect delay. Allows reconnect attempts to back off when problems persist. Accepts integer or float. Default: 1.5.
 *
 * timeoutInterval
 * - The maximum time in milliseconds to wait for a connection to succeed before closing and retrying. Accepts integer. Default: 2000.
 *
 */
(function (global, factory) {
    if (typeof define === 'function' && define.amd) {
        define([], factory);
    } else if (typeof module !== 'undefined' && module.exports){
        module.exports = factory();
    } else {
        global.ReconnectingWebSocket = factory();
    }
})(this, function () {

    if (!('WebSocket' in window)) {
        return;
    }

    function ReconnectingWebSocket(url, protocols, options) {

        // Default settings
        var settings = {

            /** Whether this instance should log debug messages. */
            debug: false,

            /** Whether or not the websocket should attempt to connect immediately upon instantiation. */
            automaticOpen: true,

            /** The number of milliseconds to delay before attempting to reconnect. */
            reconnectInterval: 1000,
            /** The maximum number of milliseconds to delay a reconnection attempt. */
            maxReconnectInterval: 30000,
            /** The rate of increase of the reconnect delay. Allows reconnect attempts to back off when problems persist. */
            reconnectDecay: 1.5,

            /** The maximum time in milliseconds to wait for a connection to succeed before closing and retrying. */
            timeoutInterval: 2000,

            /** The maximum number of reconnection attempts to make. Unlimited if null. */
            maxReconnectAttempts: null,

            /** The binary type, possible values 'blob' or 'arraybuffer', default 'blob'. */
            binaryType: 'blob'
        }
        if (!options) { options = {}; }

        // Overwrite and define settings with options if they exist.
        for (var key in settings) {
            if (typeof options[key] !== 'undefined') {
                this[key] = options[key];
            } else {
                this[key] = settings[key];
            }
        }

        // These should be treated as read-only properties

        /** The URL as resolved by the constructor. This is always an absolute URL. Read only. */
        this.url = url;

        /** The number of attempted reconnects since starting, or the last successful connection. Read only. */
        this.reconnectAttempts = 0;

        /**
         * The current state of the connection.
         * Can be one of: WebSocket.CONNECTING, WebSocket.OPEN, WebSocket.CLOSING, WebSocket.CLOSED
         * Read only.
         */
        this.readyState = WebSocket.CONNECTING;

        /**
         * A string indicating the name of the sub-protocol the server selected; this will be one of
         * the strings specified in the protocols parameter when creating the WebSocket object.
         * Read only.
         */
        this.protocol = null;

        // Private state variables

        var self = this;
        var ws;
        var forcedClose = false;
        var timedOut = false;
        var eventTarget = document.createElement('div');

        // Wire up "on*" properties as event handlers

        eventTarget.addEventListener('open',       function(event) { self.onopen(event); });
        eventTarget.addEventListener('close',      function(event) { self.onclose(event); });
        eventTarget.addEventListener('connecting', function(event) { self.onconnecting(event); });
        eventTarget.addEventListener('message',    function(event) { self.onmessage(event); });
        eventTarget.addEventListener('error',      function(event) { self.onerror(event); });

        // Expose the API required by EventTarget

        this.addEventListener = eventTarget.addEventListener.bind(eventTarget);
        this.removeEventListener = eventTarget.removeEventListener.bind(eventTarget);
        this.dispatchEvent = eventTarget.dispatchEvent.bind(eventTarget);

        /**
         * This function generates an event that is compatible with standard
         * compliant browsers and IE9 - IE11
         *
         * This will prevent the error:
         * Object doesn't support this action
         *
         * http://stackoverflow.com/questions/19345392/why-arent-my-parameters-getting-passed-through-to-a-dispatched-event/19345563#19345563
         * @param s String The name that the event should use
         * @param args Object an optional object that the event will use
         */
        function generateEvent(s, args) {
        	var evt = document.createEvent("CustomEvent");
        	evt.initCustomEvent(s, false, false, args);
        	return evt;
        };

        this.open = function (reconnectAttempt) {
            ws = new WebSocket(self.url, protocols || []);
            ws.binaryType = this.binaryType;

            if (reconnectAttempt) {
                if (this.maxReconnectAttempts && this.reconnectAttempts > this.maxReconnectAttempts) {
                    return;
                }
            } else {
                eventTarget.dispatchEvent(generateEvent('connecting'));
                this.reconnectAttempts = 0;
            }

            if (self.debug || ReconnectingWebSocket.debugAll) {
                console.debug('ReconnectingWebSocket', 'attempt-connect', self.url);
            }

            var localWs = ws;
            var timeout = setTimeout(function() {
                if (self.debug || ReconnectingWebSocket.debugAll) {
                    console.debug('ReconnectingWebSocket', 'connection-timeout', self.url);
                }
                timedOut = true;
                localWs.close();
                timedOut = false;
            }, self.timeoutInterval);

            ws.onopen = function(event) {
                clearTimeout(timeout);
                if (self.debug || ReconnectingWebSocket.debugAll) {
                    console.debug('ReconnectingWebSocket', 'onopen', self.url);
                }
                self.protocol = ws.protocol;
                self.readyState = WebSocket.OPEN;
                self.reconnectAttempts = 0;
                var e = generateEvent('open');
                e.isReconnect = reconnectAttempt;
                reconnectAttempt = false;
                eventTarget.dispatchEvent(e);
            };

            ws.onclose = function(event) {
                clearTimeout(timeout);
                ws = null;
                if (forcedClose) {
                    self.readyState = WebSocket.CLOSED;
                    eventTarget.dispatchEvent(generateEvent('close'));
                } else {
                    self.readyState = WebSocket.CONNECTING;
                    var e = generateEvent('connecting');
                    e.code = event.code;
                    e.reason = event.reason;
                    e.wasClean = event.wasClean;
                    eventTarget.dispatchEvent(e);
                    if (!reconnectAttempt && !timedOut) {
                        if (self.debug || ReconnectingWebSocket.debugAll) {
                            console.debug('ReconnectingWebSocket', 'onclose', self.url);
                        }
                        eventTarget.dispatchEvent(generateEvent('close'));
                    }

                    var timeout = self.reconnectInterval * Math.pow(self.reconnectDecay, self.reconnectAttempts);
                    setTimeout(function() {
                        self.reconnectAttempts++;
                        self.open(true);
                    }, timeout > self.maxReconnectInterval ? self.maxReconnectInterval : timeout);
                }
            };
            ws.onmessage = function(event) {
                if (self.debug || ReconnectingWebSocket.debugAll) {
                    console.debug('ReconnectingWebSocket', 'onmessage', self.url, event.data);
                }
                var e = generateEvent('message');
                e.data = event.data;
                eventTarget.dispatchEvent(e);
            };
            ws.onerror = function(event) {
                if (self.debug || ReconnectingWebSocket.debugAll) {
                    console.debug('ReconnectingWebSocket', 'onerror', self.url, event);
                }
                eventTarget.dispatchEvent(generateEvent('error'));
            };
        }

        // Whether or not to create a websocket upon instantiation
        if (this.automaticOpen == true) {
            this.open(false);
        }

        /**
         * Transmits data to the server over the WebSocket connection.
         *
         * @param data a text string, ArrayBuffer or Blob to send to the server.
         */
        this.send = function(data) {
            if (ws) {
                if (self.debug || ReconnectingWebSocket.debugAll) {
                    console.debug('ReconnectingWebSocket', 'send', self.url, data);
                }
                return ws.send(data);
            } else {
                throw 'INVALID_STATE_ERR : Pausing to reconnect websocket';
            }
        };

        /**
         * Closes the WebSocket connection or connection attempt, if any.
         * If the connection is already CLOSED, this method does nothing.
         */
        this.close = function(code, reason) {
            // Default CLOSE_NORMAL code
            if (typeof code == 'undefined') {
                code = 1000;
            }
            forcedClose = true;
            if (ws) {
                ws.close(code, reason);
            }
        };

        /**
         * Additional public API method to refresh the connection if still open (close, re-open).
         * For example, if the app suspects bad data / missed heart beats, it can try to refresh.
         */
        this.refresh = function() {
            if (ws) {
                ws.close();
            }
        };
    }

    /**
     * An event listener to be called when the WebSocket connection's readyState changes to OPEN;
     * this indicates that the connection is ready to send and receive data.
     */
    ReconnectingWebSocket.prototype.onopen = function(event) {};
    /** An event listener to be called when the WebSocket connection's readyState changes to CLOSED. */
    ReconnectingWebSocket.prototype.onclose = function(event) {};
    /** An event listener to be called when a connection begins being attempted. */
    ReconnectingWebSocket.prototype.onconnecting = function(event) {};
    /** An event listener to be called when a message is received from the server. */
    ReconnectingWebSocket.prototype.onmessage = function(event) {};
    /** An event listener to be called when an error occurs. */
    ReconnectingWebSocket.prototype.onerror = function(event) {};

    /**
     * Whether all instances of ReconnectingWebSocket should log debug messages.
     * Setting this to true is the equivalent of setting all instances of ReconnectingWebSocket.debug to true.
     */
    ReconnectingWebSocket.debugAll = false;

    ReconnectingWebSocket.CONNECTING = WebSocket.CONNECTING;
    ReconnectingWebSocket.OPEN = WebSocket.OPEN;
    ReconnectingWebSocket.CLOSING = WebSocket.CLOSING;
    ReconnectingWebSocket.CLOSED = WebSocket.CLOSED;

    return ReconnectingWebSocket;
});

redpajama_set_name: RedPajamaGithub


text:
title: Coworking Session
text: "Come with a problem and get feedback on what tools, packages and strategies you can use to solve it! Beginners welcome and bring your friends!"
location: MP408
link: https://github.com/UofTCoders/Events/issues/41
date: 2016-04-07
startTime: '18:10'
endTime: '19:30'
---


text:
This example shows how to connect and execute HIVE SQL against BigInsights cluster using JAVA. It connects via [JDBC](https://en.wikipedia.org/wiki/Java_Database_Connectivity) via Hive Server to send request and process result sets.

Apache HIVE is data warehouse software to facilitate reading, writing, and managing large datasets residing in HDFS using SQL. Structure can be projected onto data already in HDFS (e.g. external tables).

See also:

- [Apache Hive](https://hive.apache.org)

## Developer experience

Developers will gain the most from these examples if they are:

- Comfortable using Windows, OS X or *nix command prompts
- Familiar with Database concepts and SQL language
- Able to read code written in a high level language such as [Java](https://en.wikipedia.org/wiki/Java_\(programming_language\))
- Familiar with the [Gradle](https://gradle.org/) build tool

## Example Requirements

Your have met the [pre-requisites](../../README.md#pre-requisites) and have followed the [setup instructions](../../README.md#setup-instructions) in the top level [README](../../README.md)

Specificaly, ensure you have run from top level repo directory the following tasks:

- `./gradlew DownloadCertificate` - to get SSL certificate

## Run the example

There is one simple example in this folder written in the [Java Language](https://en.wikipedia.org/wiki/Java_\(programming_language\)):

- [Example.java](./src/main/java/Example.java) - this example connects to Hive via JDBC, Creates and Drops a table

To run the example [Example.java](./src/main/java/Example.java), in a command prompt window:

   - change into the directory containing this example and run gradle to execute the example
      - `./gradlew Example` (OS X / *nix)
      - `gradlew.bat Example` (Windows)
   - some output from running the command on my machine is shown below

```bash
$ cd examples/HiveJava
$ ./gradlew Example
Defining custom 'clean' task when using the standard Gradle lifecycle plugins has been deprecated and is scheduled to be removed in Gradle 3.0
:compileJava
:compileGroovy UP-TO-DATE
:processResources
:classes
:Example
SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/Users/pierreregazzoni/.gradle/caches/modules-2/files-2.1/org.apache.logging.log4j/log4j-slf4j-impl/2.4.1/1153bec315f388b2635c25cf97105ae9dce61b58/log4j-slf4j-impl-2.4.1.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/Users/pierreregazzoni/.gradle/caches/modules-2/files-2.1/ch.qos.logback/logback-classic/1.0.9/258c3d8f956e7c8723f13fdea6b81e3d74201f68/logback-classic-1.0.9.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/Users/pierreregazzoni/.gradle/caches/modules-2/files-2.1/org.slf4j/slf4j-log4j12/1.7.5/6edffc576ce104ec769d954618764f39f0f0f10d/slf4j-log4j12-1.7.5.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
SLF4J: Actual binding is of type [org.apache.logging.slf4j.Log4jLoggerFactory]
ERROR StatusLogger No log4j2 configuration file found. Using default configuration: logging only errors to the console.

>> Create Table

>> Drop Table

>> Connectivity test was successful.

BUILD SUCCESSFUL

Total time: 8.006 secs
```

The output above shows:

- remove and Create keystore as defined in [build.gradle](./build.gradle)
- the steps performed by gradle (command names are prefixed by ':' such as :compileGroovy)
- execute java code to Create and Drop table in HIVE

## Decomposition Instructions

The examples uses a gradle build file [build.gradle](./build.gradle) when you run `./gradlew` or `gradle.bat`.  The build.gradle for this example does the following:

- Identify HIVE server2 to connect to
- Create key store with the SSL certificate. This is used as part of the JDBC connection
- compile and execute the java code

All code is well commented and it is suggested that you browse the build.gradle and *.java code to understand in more detail how they work.


text:
package com.smassive.comicviewr.domain.executor;

import java.util.concurrent.Executor;

/**
 * Executor implementation can be based on different frameworks or techniques of asynchronous execution, but every implementation
 * will execute the {@link com.smassive.comicviewr.domain.interactor.UseCase} out of the UI thread.
 */
public interface ThreadExecutor extends Executor {
}


text:
<?php

namespace React\Socket;

use React\EventLoop\LoopInterface;
use React\Promise\Deferred;
use RuntimeException;
use UnexpectedValueException;

/**
 * This class is considered internal and its API should not be relied upon
 * outside of Socket.
 *
 * @internal
 */
class StreamEncryption
{
    private $loop;
    private $method;
    private $server;

    public function __construct(LoopInterface $loop, $server = true)
    {
        $this->loop = $loop;
        $this->server = $server;

        // support TLSv1.0+ by default and exclude legacy SSLv2/SSLv3.
        // As of PHP 7.2+ the main crypto method constant includes all TLS versions.
        // As of PHP 5.6+ the crypto method is a bitmask, so we explicitly include all TLS versions.
        // For legacy PHP < 5.6 the crypto method is a single value only and this constant includes all TLS versions.
        // @link https://3v4l.org/9PSST
        if ($server) {
            $this->method = \STREAM_CRYPTO_METHOD_TLS_SERVER;

            if (\PHP_VERSION_ID < 70200 && \PHP_VERSION_ID >= 50600) {
                $this->method |= \STREAM_CRYPTO_METHOD_TLSv1_0_SERVER | \STREAM_CRYPTO_METHOD_TLSv1_1_SERVER | \STREAM_CRYPTO_METHOD_TLSv1_2_SERVER; // @codeCoverageIgnore
            }
        } else {
            $this->method = \STREAM_CRYPTO_METHOD_TLS_CLIENT;

            if (\PHP_VERSION_ID < 70200 && \PHP_VERSION_ID >= 50600) {
                $this->method |= \STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT | \STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT | \STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT; // @codeCoverageIgnore
            }
        }
    }

    public function enable(Connection $stream)
    {
        return $this->toggle($stream, true);
    }

    public function toggle(Connection $stream, $toggle)
    {
        // pause actual stream instance to continue operation on raw stream socket
        $stream->pause();

        // TODO: add write() event to make sure we're not sending any excessive data

        // cancelling this leaves this stream in an inconsistent state…
        $deferred = new Deferred(function () {
            throw new \RuntimeException();
        });

        // get actual stream socket from stream instance
        $socket = $stream->stream;

        // get crypto method from context options or use global setting from constructor
        $method = $this->method;
        $context = \stream_context_get_options($socket);
        if (isset($context['ssl']['crypto_method'])) {
            $method = $context['ssl']['crypto_method'];
        }

        $that = $this;
        $toggleCrypto = function () use ($socket, $deferred, $toggle, $method, $that) {
            $that->toggleCrypto($socket, $deferred, $toggle, $method);
        };

        $this->loop->addReadStream($socket, $toggleCrypto);

        if (!$this->server) {
            $toggleCrypto();
        }

        $loop = $this->loop;

        return $deferred->promise()->then(function () use ($stream, $socket, $loop, $toggle) {
            $loop->removeReadStream($socket);

            $stream->encryptionEnabled = $toggle;
            $stream->resume();

            return $stream;
        }, function($error) use ($stream, $socket, $loop) {
            $loop->removeReadStream($socket);
            $stream->resume();
            throw $error;
        });
    }

    public function toggleCrypto($socket, Deferred $deferred, $toggle, $method)
    {
        $error = null;
        \set_error_handler(function ($_, $errstr) use (&$error) {
            $error = \str_replace(array("\r", "\n"), ' ', $errstr);

            // remove useless function name from error message
            if (($pos = \strpos($error, "): ")) !== false) {
                $error = \substr($error, $pos + 3);
            }
        });

        $result = \stream_socket_enable_crypto($socket, $toggle, $method);

        \restore_error_handler();

        if (true === $result) {
            $deferred->resolve();
        } else if (false === $result) {
            // overwrite callback arguments for PHP7+ only, so they do not show
            // up in the Exception trace and do not cause a possible cyclic reference.
            $d = $deferred;
            $deferred = null;

            if (\feof($socket) || $error === null) {
                // EOF or failed without error => connection closed during handshake
                $d->reject(new \UnexpectedValueException(
                    'Connection lost during TLS handshake (ECONNRESET)',
                    \defined('SOCKET_ECONNRESET') ? \SOCKET_ECONNRESET : 104
                ));
            } else {
                // handshake failed with error message
                $d->reject(new \UnexpectedValueException(
                    $error
                ));
            }
        } else {
            // need more data, will retry
        }
    }
}


text:
package main

import (
	"fmt"
	"github.com/abextm/go-sdl2/sdl"
	"os"
)

var winTitle string = "Go-SDL2 TestWaitEvent"
var winWidth, winHeight int = 800, 600

func main() {
	var window *sdl.Window
	var renderer *sdl.Renderer
	var event sdl.Event
	var running bool

	window = sdl.CreateWindow(winTitle, sdl.WINDOWPOS_UNDEFINED, sdl.WINDOWPOS_UNDEFINED,
		winWidth, winHeight, sdl.WINDOW_SHOWN)
	if window == nil {
		fmt.Fprintf(os.Stderr, "Failed to create window: %s\n", sdl.GetError())
		os.Exit(1)
	}

	renderer = sdl.CreateRenderer(window, -1, sdl.RENDERER_ACCELERATED)
	if renderer == nil {
		fmt.Fprintf(os.Stderr, "Failed to create renderer: %s\n", sdl.GetError())
		os.Exit(2)
	}

	running = true
	for running {
		event = sdl.WaitEventTimeout(1000) // wait here until an event is in the event queue
		if event == nil {
			fmt.Println("WaitEventTimeout timed out")
			continue
		}

		switch t := event.(type) {
		case *sdl.QuitEvent:
			running = false
		case *sdl.MouseMotionEvent:
			fmt.Printf("[%d ms] MouseMotion\ttype:%d\tid:%d\tx:%d\ty:%d\txrel:%d\tyrel:%d\n",
				t.Timestamp, t.Type, t.Which, t.X, t.Y, t.XRel, t.YRel)
		case *sdl.MouseButtonEvent:
			fmt.Printf("[%d ms] MouseButton\ttype:%d\tid:%d\tx:%d\ty:%d\tbutton:%d\tstate:%d\n",
				t.Timestamp, t.Type, t.Which, t.X, t.Y, t.Button, t.State)
		case *sdl.MouseWheelEvent:
			fmt.Printf("[%d ms] MouseWheel\ttype:%d\tid:%d\tx:%d\ty:%d\n",
				t.Timestamp, t.Type, t.Which, t.X, t.Y)
		case *sdl.KeyUpEvent:
			fmt.Printf("[%d ms] Keyboard\ttype:%d\tsym:%c\tmodifiers:%d\tstate:%d\trepeat:%d\n",
				t.Timestamp, t.Type, t.Keysym.Sym, t.Keysym.Mod, t.State, t.Repeat)
		}
	}

	renderer.Destroy()
	window.Destroy()
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Rhino.Mocks;
using Services.Enums;
using Services.Interfaces.Repository;
using Services.Objects;
using Services.Service;

namespace Services.Tests.Service
{
    [TestClass]
    public class ServiceOfInspectionTests
    {
        private IInspectionRepository repo;
        private ServiceOfInspection service;

        [TestInitialize]
        public void Inicializacao()
        {
            var mock = new MockRepository();
            repo = mock.Stub<IInspectionRepository>();
            using (mock.Record())
            {
                var inscpectBad = InspectionGood(1);
                inscpectBad.UsuarioId = 15000;
                var goodList = new List<Inspection> { InspectionGood(2), InspectionGood(4) };

                //Save OK
                repo.Expect(r => r.Add(Arg<Inspection>.Matches(x => x.Id == 0))).Repeat.Any().Return(InspectionGood(2));

                //Save Invalid
                repo.Expect(r => r.Find(Arg<int>.Is.Equal(1))).Return(null).Repeat.Any();

                // Remove Invalid
                repo.Expect(r => r.Find(Arg<int>.Is.Equal(-2))).Repeat.Any().Return(InspectionGood(-2));
                repo.Expect(r => r.Remove(Arg<int>.Is.Equal(-2))).Return(false).Repeat.Any();

                // Remove Invalid2
                repo.Expect(r => r.Find(Arg<int>.Is.Equal(4))).Return(InspectionGood(4)).Repeat.Any();

                // Remove OK
                repo.Expect(r => r.Find(Arg<int>.Is.Equal(3))).Return(InspectionGood(3)).Repeat.Any();
                repo.Expect(r => r.Remove(Arg<int>.Is.Equal(3))).Return(true).Repeat.Any();

                // GetAllByUser & GetLast OK
                repo.Expect(r => r.GetAllByUser(Arg<User>.Matches(x=> x.Id == 1))).Return(goodList).Repeat.Any();

                // GetAllByUser & GetLast Invalid
                repo.Expect(r => r.GetAllByUser(Arg<User>.Matches(x => x.Id == 2))).Return(new List<Inspection>()).Repeat.Any();

                // GetAllByDates OK
                repo.Expect(r => r.GetAllByDates(Arg<User>.Matches(x => x.Id == 1), Arg<DateTime>.Is.Equal(DateTime.Today), Arg<DateTime>.Is.Equal(DateTime.Today))).Return(goodList).Repeat.Any();

                // GetAllByDates Invalid
                repo.Expect(r => r.GetAllByDates(Arg<User>.Matches(x => x.Id == 2), Arg<DateTime>.Is.Equal(DateTime.Today), Arg<DateTime>.Is.Equal(DateTime.Today))).Return(new List<Inspection>()).Repeat.Any();
            }

            //Set Mock on Service.
            service = new ServiceOfInspection(repo);
        }

        [TestMethod, TestCategory("ServiceOfInspection")]
        public void Save_should_be_Ok()
        {
            var inspect = InspectionGood(0);
            var result = service.Save(inspect);
            result.Should().Be(inspect.Id);
        }

        [TestMethod, TestCategory("ServiceOfInspection")]
        public void Save_should_be_Invalid()
        {
            var inspect = InspectionGood(0);
            try
            {
                service.Save(inspect);
            }
            catch (InvalidOperationException e)
            {
                e.Message.Should().Be("UsuarioId:O usuário deve ser responsável pela fiscalização.");
            }
        }

        [TestMethod, TestCategory("ServiceOfInspection")]
        public void Remove_should_be_Ok()
        {
            var inspect = InspectionGood(3);
            service.Remove(inspect);
        }

        [TestMethod, TestCategory("ServiceOfInspection")]
        public void Remove_should_be_Invalid()
        {
            var inspect = InspectionGood(-2);
            try
            {
                service.Remove(inspect);
            }
            catch (InvalidOperationException e)
            {
                e.Message.Should().Be("Error during the removal.");
            }
        }

        [TestMethod, TestCategory("ServiceOfInspection")]
        public void Remove_should_be_Invalid2()
        {
            var inspect = InspectionGood(4);
            inspect.UsuarioId = -1;
            try
            {
                service.Remove(inspect);
            }
            catch (InvalidOperationException e)
            {
                e.Message.Should().Be("UsuarioId:O usuário deve ser responsável pela fiscalização.\r\nUsuarioId:O usuário deve ser informado.");
            }
        }

        [TestMethod, TestCategory("ServiceOfInspection")]
        public void GetLast_should_be_Ok()
        {
            var results = service.GetLast(1).ToList();
            results.Should().NotBeNullOrEmpty();
            results.Count.Should().Be(2);
        }

        [TestMethod, TestCategory("ServiceOfInspection")]
        public void GetLast_should_be_Invalid()
        {
            var results = service.GetLast(2).ToList();
            results.Should().BeEmpty();
        }

        [TestMethod, TestCategory("ServiceOfInspection")]
        public void GetAfterDate_should_be_Ok()
        {
            var results = service.GetAfterDate(1, DateTime.Today).ToList();
            results.Should().NotBeNullOrEmpty();
            results.Count.Should().Be(2);
        }

        [TestMethod, TestCategory("ServiceOfInspection")]
        public void GetAfterDate_should_be_Invalid()
        {
            var results = service.GetAfterDate(2, DateTime.Today).ToList();
            results.Should().BeEmpty();
        }

        [TestMethod, TestCategory("ServiceOfInspection")]
        public void GetAll_should_be_Ok()
        {
            var results = service.GetAll(1).ToList();
            results.Should().NotBeNullOrEmpty();
            results.Count.Should().Be(2);
        }

        [TestMethod, TestCategory("ServiceOfInspection")]
        public void GetAll_should_be_Invalid()
        {
            var results = service.GetAll(2).ToList();
            results.Should().BeEmpty();
        }

        private Inspection InspectionGood(int id)
        {
            return new Inspection
            {
                Create = DateTime.Today,
                Id = id,
                Latitude = 10.02f,
                Longitude = -10.02f,
                UsuarioId = 1,
                Precisao = 1,
                Local = "Right here, right now",
                Observacao = "Fat lazy boy...",
                TipoLancamento = EnumTipoLancamento.Manual
            };
        }
    }
}


text:
package com.magic.acme.assist.jpa.xtt.entity;
// Generated 2017-6-22 10:27:00 by Hibernate Tools 5.2.0.CR1

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

/**
 * HandshakeNoCargo generated by hbm2java
 */
@Entity
@Table(name = "handshake_no_cargo", schema = "public")
public class HandshakeNoCargo implements java.io.Serializable {

    private long id;
    private String handshakeId;
    private String comment;
    private Integer orderLineIndex;
    private Integer pickedQuantity;

    private Handshake handshake;

    public HandshakeNoCargo() {
    }

    @Id
    @Column(name = "id", unique = true, nullable = false)
    public long getId() {
        return this.id;
    }

    public void setId(long id) {
        this.id = id;
    }

    @Column(name = "handshake_id", insertable = false, updatable = false)
    public String getHandshakeId() {
        return this.handshakeId;
    }

    public void setHandshakeId(String handshakeId) {
        this.handshakeId = handshakeId;
    }

    @Column(name = "comment", nullable = false)
    public String getComment() {
        return this.comment;
    }

    public void setComment(String comment) {
        this.comment = comment;
    }

    @Column(name = "order_line_index")
    public Integer getOrderLineIndex() {
        return this.orderLineIndex;
    }

    public void setOrderLineIndex(Integer orderLineIndex) {
        this.orderLineIndex = orderLineIndex;
    }

    @Column(name = "picked_quantity")
    public Integer getPickedQuantity() {
        return this.pickedQuantity;
    }

    public void setPickedQuantity(Integer pickedQuantity) {
        this.pickedQuantity = pickedQuantity;
    }

    @ManyToOne(optional = false, fetch = FetchType.LAZY)
    @JoinColumn(name = "handshake_id", nullable = false)
    public Handshake getHandshake() {
        return handshake;
    }

    public void setHandshake(Handshake handshake) {
        this.handshake = handshake;
    }
}


text:
from __future__ import absolute_import

import types
from collections import defaultdict
from contextlib import contextmanager

from rpython.tool.ansi_print import AnsiLogger
from rpython.tool.pairtype import pair
from rpython.tool.error import (format_blocked_annotation_error,
                             gather_error, source_lines)
from rpython.flowspace.model import Variable, Constant, checkgraph
from rpython.translator import simplify, transform
from rpython.annotator import model as annmodel, signature
from rpython.annotator.model import (
    typeof, s_ImpossibleValue, SomeInstance, intersection, difference)
from rpython.annotator.bookkeeper import Bookkeeper
from rpython.rtyper.normalizecalls import perform_normalizations

log = AnsiLogger("annrpython")

class RPythonAnnotator(object):
    """Block annotator for RPython.
    See description in doc/translation.txt."""

    def __init__(self, translator=None, policy=None, bookkeeper=None,
            keepgoing=False):
        import rpython.rtyper.extfuncregistry # has side effects

        if translator is None:
            # interface for tests
            from rpython.translator.translator import TranslationContext
            translator = TranslationContext()
            translator.annotator = self
        self.translator = translator
        self.pendingblocks = {}  # map {block: graph-containing-it}
        self.annotated = {}      # set of blocks already seen
        self.added_blocks = None # see processblock() below
        self.links_followed = {} # set of links that have ever been followed
        self.notify = {}        # {block: {positions-to-reflow-from-when-done}}
        self.fixed_graphs = {}  # set of graphs not to annotate again
        self.blocked_blocks = {} # set of {blocked_block: (graph, index)}
        # --- the following information is recorded for debugging ---
        self.blocked_graphs = {} # set of graphs that have blocked blocks
        # --- end of debugging information ---
        self.frozen = False
        if policy is None:
            from rpython.annotator.policy import AnnotatorPolicy
            self.policy = AnnotatorPolicy()
        else:
            self.policy = policy
        if bookkeeper is None:
            bookkeeper = Bookkeeper(self)
        self.bookkeeper = bookkeeper
        self.keepgoing = keepgoing
        self.failed_blocks = set()
        self.errors = []

    def __getstate__(self):
        attrs = """translator pendingblocks annotated links_followed
        notify bookkeeper frozen policy added_blocks""".split()
        ret = self.__dict__.copy()
        for key, value in ret.items():
            if key not in attrs:
                assert type(value) is dict, (
                    "%r is not dict. please update %s.__getstate__" %
                    (key, self.__class__.__name__))
                ret[key] = {}
        return ret

    #___ convenience high-level interface __________________

    def build_types(self, function, input_arg_types, complete_now=True,
                    main_entry_point=False):
        """Recursively build annotations about the specific entry point."""
        assert isinstance(function, types.FunctionType), "fix that!"

        from rpython.annotator.policy import AnnotatorPolicy
        policy = AnnotatorPolicy()
        # make input arguments and set their type
        args_s = [self.typeannotation(t) for t in input_arg_types]

        # XXX hack
        annmodel.TLS.check_str_without_nul = (
            self.translator.config.translation.check_str_without_nul)

        with self.using_policy(policy):
            flowgraph, inputs_s = self.get_call_parameters(function, args_s)

        if main_entry_point:
            self.translator.entry_point_graph = flowgraph
        return self.build_graph_types(flowgraph, inputs_s, complete_now=complete_now)

    def get_call_parameters(self, function, args_s):
        with self.bookkeeper.at_position(None):
            desc = self.bookkeeper.getdesc(function)
            return desc.get_call_parameters(args_s)

    def annotate_helper(self, function, args_s, policy=None):
        if policy is None:
            from rpython.annotator.policy import AnnotatorPolicy
            policy = AnnotatorPolicy()
            # XXX hack
            annmodel.TLS.check_str_without_nul = (
                self.translator.config.translation.check_str_without_nul)
        with self.using_policy(policy):
            graph, inputcells = self.get_call_parameters(function, args_s)
            self.build_graph_types(graph, inputcells, complete_now=False)
            self.complete_helpers()
        return graph

    def complete_helpers(self):
        saved = self.added_blocks
        self.added_blocks = {}
        try:
            self.complete()
            # invoke annotation simplifications for the new blocks
            self.simplify(block_subset=self.added_blocks)
        finally:
            self.added_blocks = saved

    @contextmanager
    def using_policy(self, policy):
        """A context manager that temporarily replaces the annotator policy"""
        old_policy = self.policy
        self.policy = policy
        yield
        self.policy = old_policy

    def build_graph_types(self, flowgraph, inputcells, complete_now=True):
        checkgraph(flowgraph)

        nbarg = len(flowgraph.getargs())
        assert len(inputcells) == nbarg # wrong number of args

        # register the entry point
        self.addpendinggraph(flowgraph, inputcells)
        # recursively proceed until no more pending block is left
        if complete_now:
            self.complete()
        return self.annotation(flowgraph.getreturnvar())

    def gettype(self, variable):
        """Return the known type of a control flow graph variable,
        defaulting to 'object'."""
        if isinstance(variable, Constant):
            return type(variable.value)
        elif isinstance(variable, Variable):
            s_variable = variable.annotation
            if s_variable:
                return s_variable.knowntype
            else:
                return object
        else:
            raise TypeError("Variable or Constant instance expected, "
                              "got %r" % (variable,))

    def getuserclassdefinitions(self):
        """Return a list of ClassDefs."""
        return self.bookkeeper.classdefs

    #___ medium-level interface ____________________________

    def addpendinggraph(self, flowgraph, inputcells):
        self.addpendingblock(flowgraph, flowgraph.startblock, inputcells)

    def addpendingblock(self, graph, block, cells):
        """Register an entry point into block with the given input cells."""
        if graph in self.fixed_graphs:
            # special case for annotating/rtyping in several phases: calling
            # a graph that has already been rtyped.  Safety-check the new
            # annotations that are passed in, and don't annotate the old
            # graph -- it's already low-level operations!
            for a, s_newarg in zip(block.inputargs, cells):
                s_oldarg = a.annotation
                # XXX: Should use s_oldarg.contains(s_newarg) but that breaks
                # PyPy translation
                if annmodel.unionof(s_oldarg, s_newarg) != s_oldarg:
                    raise annmodel.AnnotatorError(
                        "Late-stage annotation is not allowed to modify the "
                        "existing annotation for variable %s: %s" %
                            (a, s_oldarg))

        else:
            assert not self.frozen
            if block not in self.annotated:
                self.bindinputargs(graph, block, cells)
            else:
                self.mergeinputargs(graph, block, cells)
            if not self.annotated[block]:
                self.pendingblocks[block] = graph

    def complete_pending_blocks(self):
        while self.pendingblocks:
            block, graph = self.pendingblocks.popitem()
            self.processblock(graph, block)

    def complete(self):
        """Process pending blocks until none is left."""
        while True:
            self.complete_pending_blocks()
            self.policy.no_more_blocks_to_annotate(self)
            if not self.pendingblocks:
                break   # finished
        # make sure that the return variables of all graphs is annotated
        if self.added_blocks is not None:
            newgraphs = [self.annotated[block] for block in self.added_blocks]
            newgraphs = dict.fromkeys(newgraphs)
            got_blocked_blocks = False in newgraphs
        else:
            newgraphs = self.translator.graphs  #all of them
            got_blocked_blocks = False in self.annotated.values()
        if self.failed_blocks:
            text = ('Annotation failed, %s errors were recorded:' %
                    len(self.errors))
            text += '\n-----'.join(str(e) for e in self.errors)
            raise annmodel.AnnotatorError(text)

        if got_blocked_blocks:
            for graph in self.blocked_graphs.values():
                self.blocked_graphs[graph] = True

            blocked_blocks = [block for block, done in self.annotated.items()
                                    if done is False]
            assert len(blocked_blocks) == len(self.blocked_blocks)

            text = format_blocked_annotation_error(self, self.blocked_blocks)
            #raise SystemExit()
            raise annmodel.AnnotatorError(text)
        for graph in newgraphs:
            v = graph.getreturnvar()
            if v.annotation is None:
                self.setbinding(v, s_ImpossibleValue)
            v = graph.exceptblock.inputargs[1]
            if v.annotation is not None and v.annotation.can_be_none():
                raise annmodel.AnnotatorError(
                    "%r is found by annotation to possibly raise None, "
                    "but the None was not suppressed by the flow space" %
                        (graph,))

    def validate(self):
        """Check that the annotation results are valid"""
        self.bookkeeper.check_no_flags_on_instances()

    def annotation(self, arg):
        "Gives the SomeValue corresponding to the given Variable or Constant."
        if isinstance(arg, Variable):
            return arg.annotation
        elif isinstance(arg, Constant):
            return self.bookkeeper.immutablevalue(arg.value)
        else:
            raise TypeError('Variable or Constant expected, got %r' % (arg,))

    def binding(self, arg):
        "Gives the SomeValue corresponding to the given Variable or Constant."
        s_arg = self.annotation(arg)
        if s_arg is None:
            raise KeyError
        return s_arg

    def typeannotation(self, t):
        return signature.annotation(t, self.bookkeeper)

    def setbinding(self, arg, s_value):
        s_old = arg.annotation
        if s_old is not None:
            if not s_value.contains(s_old):
                log.WARNING("%s does not contain %s" % (s_value, s_old))
                log.WARNING("%s" % annmodel.union(s_value, s_old))
                assert False
        arg.annotation = s_value

    def warning(self, msg, pos=None):
        if pos is None:
            try:
                pos = self.bookkeeper.position_key
            except AttributeError:
                pos = '?'
        if pos != '?':
            pos = self.whereami(pos)

        log.WARNING("%s/ %s" % (pos, msg))

    #___ interface for annotator.bookkeeper _______

    def recursivecall(self, graph, whence, inputcells):
        if isinstance(whence, tuple):
            parent_graph, parent_block, parent_index = whence
            tag = parent_block, parent_index
            self.translator.update_call_graph(parent_graph, graph, tag)
        # self.notify[graph.returnblock] is a dictionary of call
        # points to this func which triggers a reflow whenever the
        # return block of this graph has been analysed.
        callpositions = self.notify.setdefault(graph.returnblock, {})
        if whence is not None:
            if callable(whence):
                def callback():
                    whence(self, graph)
            else:
                callback = whence
            callpositions[callback] = True

        # generalize the function's input arguments
        self.addpendingblock(graph, graph.startblock, inputcells)

        # get the (current) return value
        v = graph.getreturnvar()
        try:
            return self.binding(v)
        except KeyError:
            # the function didn't reach any return statement so far.
            # (some functions actually never do, they always raise exceptions)
            return s_ImpossibleValue

    def reflowfromposition(self, position_key):
        graph, block, index = position_key
        self.reflowpendingblock(graph, block)

    def call_sites(self):
        newblocks = self.added_blocks
        if newblocks is None:
            newblocks = self.annotated  # all of them
        for block in newblocks:
            for op in block.operations:
                if op.opname in ('simple_call', 'call_args'):
                    yield op

                # some blocks are partially annotated
                if op.result.annotation is None:
                    break   # ignore the unannotated part

    #___ simplification (should be moved elsewhere?) _______

    def simplify(self, block_subset=None, extra_passes=None):
        # Generic simplifications
        transform.transform_graph(self, block_subset=block_subset,
                                  extra_passes=extra_passes)
        if block_subset is None:
            graphs = self.translator.graphs
        else:
            graphs = {}
            for block in block_subset:
                graph = self.annotated.get(block)
                if graph:
                    graphs[graph] = True
        for graph in graphs:
            simplify.eliminate_empty_blocks(graph)
        self.bookkeeper.compute_at_fixpoint()
        if block_subset is None:
            perform_normalizations(self)

    #___ flowing annotations in blocks _____________________

    def processblock(self, graph, block):
        # Important: this is not called recursively.
        # self.flowin() can only issue calls to self.addpendingblock().
        # The analysis of a block can be in three states:
        #  * block not in self.annotated:
        #      never seen the block.
        #  * self.annotated[block] == False:
        #      the input variables of the block have bindings but we
        #      still have to consider all the operations in the block.
        #  * self.annotated[block] == graph-containing-block:
        #      analysis done (at least until we find we must generalize the
        #      input variables).

        #print '* processblock', block, cells
        self.annotated[block] = graph
        if block in self.failed_blocks:
            return
        if block in self.blocked_blocks:
            del self.blocked_blocks[block]
        try:
            self.flowin(graph, block)
        except BlockedInference as e:
            self.annotated[block] = False   # failed, hopefully temporarily
            self.blocked_blocks[block] = (graph, e.opindex)
        except Exception as e:
            # hack for debug tools only
            if not hasattr(e, '__annotator_block'):
                setattr(e, '__annotator_block', block)
            raise

        # The dict 'added_blocks' is used by rpython.annlowlevel to
        # detect which are the new blocks that annotating an additional
        # small helper creates.
        if self.added_blocks is not None:
            self.added_blocks[block] = True

    def reflowpendingblock(self, graph, block):
        assert not self.frozen
        assert graph not in self.fixed_graphs
        self.pendingblocks[block] = graph
        assert block in self.annotated
        self.annotated[block] = False  # must re-flow
        self.blocked_blocks[block] = (graph, None)

    def bindinputargs(self, graph, block, inputcells):
        # Create the initial bindings for the input args of a block.
        assert len(block.inputargs) == len(inputcells)
        for a, cell in zip(block.inputargs, inputcells):
            self.setbinding(a, cell)
        self.annotated[block] = False  # must flowin.
        self.blocked_blocks[block] = (graph, None)

    def mergeinputargs(self, graph, block, inputcells):
        # Merge the new 'cells' with each of the block's existing input
        # variables.
        oldcells = [self.binding(a) for a in block.inputargs]
        try:
            unions = [annmodel.unionof(c1,c2) for c1, c2 in zip(oldcells,inputcells)]
        except annmodel.UnionError as e:
            # Add source code to the UnionError
            e.source = '\n'.join(source_lines(graph, block, None, long=True))
            if self.keepgoing:
                self.errors.append(e)
                self.failed_blocks.add(block)
                return
            raise
        # if the merged cells changed, we must redo the analysis
        if unions != oldcells:
            self.bindinputargs(graph, block, unions)

    def apply_renaming(self, s_out, renaming):
        if hasattr(s_out, 'is_type_of'):
            renamed_is_type_of = []
            for v in s_out.is_type_of:
                renamed_is_type_of += renaming[v]
            assert s_out.knowntype is type
            newcell = typeof(renamed_is_type_of)
            if s_out.is_constant():
                newcell.const = s_out.const
            s_out = newcell

        if hasattr(s_out, 'knowntypedata'):
            renamed_knowntypedata = {}
            for value, constraints in s_out.knowntypedata.items():
                renamed_knowntypedata[value] = {}
                for v, s in constraints.items():
                    new_vs = renaming.get(v, [])
                    for new_v in new_vs:
                        renamed_knowntypedata[value][new_v] = s
            assert isinstance(s_out, annmodel.SomeBool)
            newcell = annmodel.SomeBool()
            if s_out.is_constant():
                newcell.const = s_out.const
            s_out = newcell
            s_out.set_knowntypedata(renamed_knowntypedata)
        return s_out

    def whereami(self, position_key):
        graph, block, i = position_key
        blk = ""
        if block:
            at = block.at()
            if at:
                blk = " block"+at
        opid=""
        if i is not None:
            opid = " op=%d" % i
        return repr(graph) + blk + opid

    def flowin(self, graph, block):
        try:
            i = 0
            while i < len(block.operations):
                op = block.operations[i]
                with self.bookkeeper.at_position((graph, block, i)):
                    new_ops = op.transform(self)
                    if new_ops is not None:
                        block.operations[i:i+1] = new_ops
                        if not new_ops:
                            continue
                        new_ops[-1].result = op.result
                        op = new_ops[0]
                    self.consider_op(op)
                i += 1

        except BlockedInference as e:
            if e.op is block.raising_op:
                # this is the case where the last operation of the block will
                # always raise an exception which is immediately caught by
                # an exception handler.  We then only follow the exceptional
                # branches.
                exits = [link for link in block.exits
                              if link.exitcase is not None]

            elif e.op.opname in ('simple_call', 'call_args', 'next'):
                # XXX warning, keep the name of the call operations in sync
                # with the flow object space.  These are the operations for
                # which it is fine to always raise an exception.  We then
                # swallow the BlockedInference and that's it.
                # About 'next': see test_annotate_iter_empty_container().
                return

            else:
                # other cases are problematic (but will hopefully be solved
                # later by reflowing).  Throw the BlockedInference up to
                # processblock().
                e.opindex = i
                raise

        except annmodel.HarmlesslyBlocked:
            return

        except annmodel.AnnotatorError as e: # note that UnionError is a subclass
            e.source = gather_error(self, graph, block, i)
            if self.keepgoing:
                self.errors.append(e)
                self.failed_blocks.add(block)
                return
            raise

        else:
            # dead code removal: don't follow all exits if the exitswitch
            # is known
            exits = block.exits
            if isinstance(block.exitswitch, Variable):
                s_exitswitch = self.binding(block.exitswitch)
                if s_exitswitch.is_constant():
                    exits = [link for link in exits
                                  if link.exitcase == s_exitswitch.const]

        if block.canraise:
            op = block.raising_op
            s_exception = self.get_exception(op)
            for link in exits:
                case = link.exitcase
                if case is None:
                    self.follow_link(graph, link, {})
                    continue
                if s_exception == s_ImpossibleValue:
                    break
                s_case = SomeInstance(self.bookkeeper.getuniqueclassdef(case))
                s_matching_exc = intersection(s_exception, s_case)
                if s_matching_exc != s_ImpossibleValue:
                    self.follow_raise_link(graph, link, s_matching_exc)
                s_exception = difference(s_exception, s_case)
        else:
            if isinstance(block.exitswitch, Variable):
                knowntypedata = getattr(
                    block.exitswitch.annotation, "knowntypedata", {})
            else:
                knowntypedata = {}
            for link in exits:
                constraints = knowntypedata.get(link.exitcase, {})
                self.follow_link(graph, link, constraints)

        if block in self.notify:
            # reflow from certain positions when this block is done
            for callback in self.notify[block]:
                if isinstance(callback, tuple):
                    self.reflowfromposition(callback) # callback is a position
                else:
                    callback()

    def follow_link(self, graph, link, constraints):
        assert not (isinstance(link.exitcase, (types.ClassType, type)) and
                issubclass(link.exitcase, BaseException))

        ignore_link = False
        inputs_s = []
        renaming = defaultdict(list)
        for v_out, v_input in zip(link.args, link.target.inputargs):
            renaming[v_out].append(v_input)

        for v_out in link.args:
            s_out = self.annotation(v_out)
            if v_out in constraints:
                s_constraint = constraints[v_out]
                s_out = pair(s_out, s_constraint).improve()
                # ignore links that try to pass impossible values
                if s_out == s_ImpossibleValue:
                    ignore_link = True
            s_out = self.apply_renaming(s_out, renaming)
            inputs_s.append(s_out)
        if ignore_link:
            return

        self.links_followed[link] = True
        self.addpendingblock(graph, link.target, inputs_s)

    def follow_raise_link(self, graph, link, s_last_exc_value):
        v_last_exc_type = link.last_exception
        v_last_exc_value = link.last_exc_value

        assert (isinstance(link.exitcase, (types.ClassType, type)) and
                issubclass(link.exitcase, BaseException))

        assert v_last_exc_type and v_last_exc_value

        if isinstance(v_last_exc_value, Variable):
            self.setbinding(v_last_exc_value, s_last_exc_value)

        if isinstance(v_last_exc_type, Variable):
            self.setbinding(v_last_exc_type, typeof([v_last_exc_value]))

        inputs_s = []
        renaming = defaultdict(list)
        for v_out, v_input in zip(link.args, link.target.inputargs):
            renaming[v_out].append(v_input)

        for v_out, v_input in zip(link.args, link.target.inputargs):
            if v_out == v_last_exc_type:
                s_out = typeof(renaming[v_last_exc_value])
                if isinstance(v_last_exc_type, Constant):
                    s_out.const = v_last_exc_type.value
                elif v_last_exc_type.annotation.is_constant():
                    s_out.const = v_last_exc_type.annotation.const
                inputs_s.append(s_out)
            else:
                s_out = self.annotation(v_out)
                s_out = self.apply_renaming(s_out, renaming)
                inputs_s.append(s_out)

        self.links_followed[link] = True
        self.addpendingblock(graph, link.target, inputs_s)

    #___ creating the annotations based on operations ______

    def consider_op(self, op):
        # let's be careful about avoiding propagated SomeImpossibleValues
        # to enter an op; the latter can result in violations of the
        # more general results invariant: e.g. if SomeImpossibleValue enters is_
        #  is_(SomeImpossibleValue, None) -> SomeBool
        #  is_(SomeInstance(not None), None) -> SomeBool(const=False) ...
        # boom -- in the assert of setbinding()
        for arg in op.args:
            if isinstance(self.annotation(arg), annmodel.SomeImpossibleValue):
                raise BlockedInference(self, op, -1)
        resultcell = op.consider(self)
        if resultcell is None:
            resultcell = s_ImpossibleValue
        elif resultcell == s_ImpossibleValue:
            raise BlockedInference(self, op, -1) # the operation cannot succeed
        assert isinstance(resultcell, annmodel.SomeObject)
        assert isinstance(op.result, Variable)
        self.setbinding(op.result, resultcell)  # bind resultcell to op.result

    def get_exception(self, operation):
        """
        Return the annotation for all exceptions that `operation` may raise.
        """
        can_only_throw = operation.get_can_only_throw(self)
        if can_only_throw is None:
            return SomeInstance(self.bookkeeper.getuniqueclassdef(Exception))
        else:
            return self.bookkeeper.new_exception(can_only_throw)

class BlockedInference(Exception):
    """This exception signals the type inference engine that the situation
    is currently blocked, and that it should try to progress elsewhere."""

    def __init__(self, annotator, op, opindex):
        self.annotator = annotator
        try:
            self.break_at = annotator.bookkeeper.position_key
        except AttributeError:
            self.break_at = None
        self.op = op
        self.opindex = opindex

    def __repr__(self):
        if not self.break_at:
            break_at = "?"
        else:
            break_at = self.annotator.whereami(self.break_at)
        return "<BlockedInference break_at %s [%s]>" %(break_at, self.op)

    __str__ = __repr__


text:
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
 * Copyright (c) 2005 INRIA
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation;
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * Author: Mathieu Lacage <mathieu.lacage.inria.fr>
 */

#include "system-wall-clock-ms.h"

#include <ctime>

namespace ns3 {

class SystemWallClockMsPrivate {
public:
  void Start (void);
  int64_t End (void);
  int64_t GetElapsedReal (void) const;
  int64_t GetElapsedUser (void) const;
  int64_t GetElapsedSystem (void) const;

private:
  clock_t m_startTime;
  int64_t m_elapsedReal;
  int64_t m_elapsedUser;
  int64_t m_elapsedSystem;
};

void
SystemWallClockMsPrivate::Start (void)
{
  NS_LOG_FUNCTION (this);
  m_startTime = std::clock ();
}

int64_t
SystemWallClockMsPrivate::End (void)
{
  //
  // We need to return the number of milliseconds that have elapsed in some
  // reasonably portable way.  The underlying function that we will use returns
  // a number of elapsed ticks.  We can look up the number of ticks per second
  // from the system configuration.
  //
  // Conceptually, we need to find the number of elapsed clock ticks and then
  // multiply the result by the milliseconds per clock tick (or just as easily
  // divide by clock ticks per millisecond).  Integer dividing by clock ticks
  // per millisecond is bad since this number is fractional on most machines
  // and would result in divide by zero errors due to integer rounding.
  //
  // Multiplying by milliseconds per clock tick works up to a clock resolution
  // of 1000 ticks per second.  If we go  past this point, we begin to get zero
  // elapsed times when millisecondsPerTick becomes fractional and another
  // rounding error appears.
  //
  // So rounding errors using integers can bite you from two direction.  Since
  // all of our targets have math coprocessors, why not just use doubles
  // internally?  Works fine, lasts a long time.
  //
  // If millisecondsPerTick becomes fractional, and an elapsed time greater than
  // a milliscond is measured, the function will work as expected.  If an elapsed
  // time is measured that turns out to be less than a millisecond, we'll just
  // return zero which would, I think, also will be expected.
  //
  NS_LOG_FUNCTION (this);
  static int64_t ticksPerSecond = CLOCKS_PER_SEC;
  static double millisecondsPerTick = 1000. / ticksPerSecond;

  clock_t endTime = std::clock ();

  double tmp;

  tmp = static_cast<double> (endTime - m_startTime) * millisecondsPerTick;
  m_elapsedReal = static_cast<int64_t> (tmp);

  //
  // Nothing like this in MinGW, for example.
  //
  m_elapsedUser = 0;
  m_elapsedSystem = 0;

  return m_elapsedReal;
}

int64_t
SystemWallClockMsPrivate::GetElapsedReal (void) const
{
  NS_LOG_FUNCTION (this);
  return m_elapsedReal;
}

int64_t
SystemWallClockMsPrivate::GetElapsedUser (void) const
{
  NS_LOG_FUNCTION (this);
  return m_elapsedUser;
}

int64_t
SystemWallClockMsPrivate::GetElapsedSystem (void) const
{
  NS_LOG_FUNCTION (this);
  return m_elapsedSystem;
}

SystemWallClockMs::SystemWallClockMs ()
  : m_priv (new SystemWallClockMsPrivate ())
{
  NS_LOG_FUNCTION (this);
}

SystemWallClockMs::~SystemWallClockMs ()
{
  NS_LOG_FUNCTION (this);
  delete m_priv;
  m_priv = 0;
}

void
SystemWallClockMs::Start (void)
{
  NS_LOG_FUNCTION (this);
  m_priv->Start ();
}

int64_t
SystemWallClockMs::End (void)
{
  NS_LOG_FUNCTION (this);
  return m_priv->End ();
}

int64_t
SystemWallClockMs::GetElapsedReal (void) const
{
  NS_LOG_FUNCTION (this);
  return m_priv->GetElapsedReal ();
}

int64_t
SystemWallClockMs::GetElapsedUser (void) const
{
  NS_LOG_FUNCTION (this);
  return m_priv->GetElapsedUser ();
}

int64_t
SystemWallClockMs::GetElapsedSystem (void) const
{
  NS_LOG_FUNCTION (this);
  return m_priv->GetElapsedSystem ();
}

} // namespace ns3


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2017.11.30 at 08:24:17 PM JST
//

package uk.org.siri.siri;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;

/**
 * Type for error.
 *
 *
Java class for OtherErrorStructure complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="OtherErrorStructure">
 *   <complexContent>
 *     <extension base="{http://www.siri.org.uk/siri}ErrorCodeStructure">
 *     </extension>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "OtherErrorStructure")
public class OtherErrorStructure
    extends ErrorCodeStructure
{

}


text:
require 'spec_helper'

describe Puppet::Type.type(:dsc_xspsearchcontentsource) do

  let :dsc_xspsearchcontentsource do
    Puppet::Type.type(:dsc_xspsearchcontentsource).new(
      :name     => 'foo',
      :dsc_name => 'foo',
      :dsc_serviceappname => 'foo',
    )
  end

  it 'should allow all properties to be specified' do
    expect { Puppet::Type.type(:dsc_xspsearchcontentsource).new(
      :name     => 'foo',
      :dsc_name => 'foo',
      :dsc_serviceappname => 'foo',
      :dsc_contentsourcetype => 'SharePoint',
      :dsc_addresses => ["foo", "bar", "spec"],
      :dsc_crawlsetting => 'CrawlEverything',
      :dsc_continuouscrawl => true,
      :dsc_incrementalschedule => {"ScheduleType"=>"None", "CrawlScheduleDaysOfMonth"=>32, "CrawlScheduleDaysOfWeek"=>"Everyday", "CrawlScheduleMonthsOfYear"=>"AllMonths", "StartHour"=>32, "StartMinute"=>32, "CrawlScheduleRepeatDuration"=>32, "CrawlScheduleRepeatInterval"=>32, "CrawlScheduleRunEveryInterval"=>32},
      :dsc_fullschedule => {"ScheduleType"=>"None", "CrawlScheduleDaysOfMonth"=>32, "CrawlScheduleDaysOfWeek"=>"Everyday", "CrawlScheduleMonthsOfYear"=>"AllMonths", "StartHour"=>32, "StartMinute"=>32, "CrawlScheduleRepeatDuration"=>32, "CrawlScheduleRepeatInterval"=>32, "CrawlScheduleRunEveryInterval"=>32},
      :dsc_priority => 'Normal',
      :dsc_limitpagedepth => 32,
      :dsc_limitserverhops => 32,
      :dsc_ensure => 'Present',
      :dsc_force => true,
      :dsc_installaccount => {"user"=>"user", "password"=>"password"},
    )}.to_not raise_error
  end

  it "should stringify normally" do
    expect(dsc_xspsearchcontentsource.to_s).to eq("Dsc_xspsearchcontentsource[foo]")
  end

  it 'should default to ensure => present' do
    expect(dsc_xspsearchcontentsource[:ensure]).to eq :present
  end

  it 'should require that dsc_name is specified' do
    #dsc_xspsearchcontentsource[:dsc_name]
    expect { Puppet::Type.type(:dsc_xspsearchcontentsource).new(
      :name     => 'foo',
      :dsc_serviceappname => 'foo',
    )}.to raise_error(Puppet::Error, /dsc_name is a required attribute/)
  end

  it 'should not accept array for dsc_name' do
    expect{dsc_xspsearchcontentsource[:dsc_name] = ["foo", "bar", "spec"]}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept boolean for dsc_name' do
    expect{dsc_xspsearchcontentsource[:dsc_name] = true}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept int for dsc_name' do
    expect{dsc_xspsearchcontentsource[:dsc_name] = -16}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept uint for dsc_name' do
    expect{dsc_xspsearchcontentsource[:dsc_name] = 16}.to raise_error(Puppet::ResourceError)
  end

  it 'should require that dsc_serviceappname is specified' do
    #dsc_xspsearchcontentsource[:dsc_serviceappname]
    expect { Puppet::Type.type(:dsc_xspsearchcontentsource).new(
      :name     => 'foo',
      :dsc_name => 'foo',
    )}.to raise_error(Puppet::Error, /dsc_serviceappname is a required attribute/)
  end

  it 'should not accept array for dsc_serviceappname' do
    expect{dsc_xspsearchcontentsource[:dsc_serviceappname] = ["foo", "bar", "spec"]}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept boolean for dsc_serviceappname' do
    expect{dsc_xspsearchcontentsource[:dsc_serviceappname] = true}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept int for dsc_serviceappname' do
    expect{dsc_xspsearchcontentsource[:dsc_serviceappname] = -16}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept uint for dsc_serviceappname' do
    expect{dsc_xspsearchcontentsource[:dsc_serviceappname] = 16}.to raise_error(Puppet::ResourceError)
  end

  it 'should accept dsc_contentsourcetype predefined value SharePoint' do
    dsc_xspsearchcontentsource[:dsc_contentsourcetype] = 'SharePoint'
    expect(dsc_xspsearchcontentsource[:dsc_contentsourcetype]).to eq('SharePoint')
  end

  it 'should accept dsc_contentsourcetype predefined value sharepoint' do
    dsc_xspsearchcontentsource[:dsc_contentsourcetype] = 'sharepoint'
    expect(dsc_xspsearchcontentsource[:dsc_contentsourcetype]).to eq('sharepoint')
  end

  it 'should accept dsc_contentsourcetype predefined value Website' do
    dsc_xspsearchcontentsource[:dsc_contentsourcetype] = 'Website'
    expect(dsc_xspsearchcontentsource[:dsc_contentsourcetype]).to eq('Website')
  end

  it 'should accept dsc_contentsourcetype predefined value website' do
    dsc_xspsearchcontentsource[:dsc_contentsourcetype] = 'website'
    expect(dsc_xspsearchcontentsource[:dsc_contentsourcetype]).to eq('website')
  end

  it 'should accept dsc_contentsourcetype predefined value FileShare' do
    dsc_xspsearchcontentsource[:dsc_contentsourcetype] = 'FileShare'
    expect(dsc_xspsearchcontentsource[:dsc_contentsourcetype]).to eq('FileShare')
  end

  it 'should accept dsc_contentsourcetype predefined value fileshare' do
    dsc_xspsearchcontentsource[:dsc_contentsourcetype] = 'fileshare'
    expect(dsc_xspsearchcontentsource[:dsc_contentsourcetype]).to eq('fileshare')
  end

  it 'should not accept values not equal to predefined values' do
    expect{dsc_xspsearchcontentsource[:dsc_contentsourcetype] = 'invalid value'}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept array for dsc_contentsourcetype' do
    expect{dsc_xspsearchcontentsource[:dsc_contentsourcetype] = ["foo", "bar", "spec"]}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept boolean for dsc_contentsourcetype' do
    expect{dsc_xspsearchcontentsource[:dsc_contentsourcetype] = true}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept int for dsc_contentsourcetype' do
    expect{dsc_xspsearchcontentsource[:dsc_contentsourcetype] = -16}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept uint for dsc_contentsourcetype' do
    expect{dsc_xspsearchcontentsource[:dsc_contentsourcetype] = 16}.to raise_error(Puppet::ResourceError)
  end

  it 'should accept array for dsc_addresses' do
    dsc_xspsearchcontentsource[:dsc_addresses] = ["foo", "bar", "spec"]
    expect(dsc_xspsearchcontentsource[:dsc_addresses]).to eq(["foo", "bar", "spec"])
  end

  it 'should not accept boolean for dsc_addresses' do
    expect{dsc_xspsearchcontentsource[:dsc_addresses] = true}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept int for dsc_addresses' do
    expect{dsc_xspsearchcontentsource[:dsc_addresses] = -16}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept uint for dsc_addresses' do
    expect{dsc_xspsearchcontentsource[:dsc_addresses] = 16}.to raise_error(Puppet::ResourceError)
  end

  it 'should accept dsc_crawlsetting predefined value CrawlEverything' do
    dsc_xspsearchcontentsource[:dsc_crawlsetting] = 'CrawlEverything'
    expect(dsc_xspsearchcontentsource[:dsc_crawlsetting]).to eq('CrawlEverything')
  end

  it 'should accept dsc_crawlsetting predefined value crawleverything' do
    dsc_xspsearchcontentsource[:dsc_crawlsetting] = 'crawleverything'
    expect(dsc_xspsearchcontentsource[:dsc_crawlsetting]).to eq('crawleverything')
  end

  it 'should accept dsc_crawlsetting predefined value CrawlFirstOnly' do
    dsc_xspsearchcontentsource[:dsc_crawlsetting] = 'CrawlFirstOnly'
    expect(dsc_xspsearchcontentsource[:dsc_crawlsetting]).to eq('CrawlFirstOnly')
  end

  it 'should accept dsc_crawlsetting predefined value crawlfirstonly' do
    dsc_xspsearchcontentsource[:dsc_crawlsetting] = 'crawlfirstonly'
    expect(dsc_xspsearchcontentsource[:dsc_crawlsetting]).to eq('crawlfirstonly')
  end

  it 'should accept dsc_crawlsetting predefined value Custom' do
    dsc_xspsearchcontentsource[:dsc_crawlsetting] = 'Custom'
    expect(dsc_xspsearchcontentsource[:dsc_crawlsetting]).to eq('Custom')
  end

  it 'should accept dsc_crawlsetting predefined value custom' do
    dsc_xspsearchcontentsource[:dsc_crawlsetting] = 'custom'
    expect(dsc_xspsearchcontentsource[:dsc_crawlsetting]).to eq('custom')
  end

  it 'should not accept values not equal to predefined values' do
    expect{dsc_xspsearchcontentsource[:dsc_crawlsetting] = 'invalid value'}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept array for dsc_crawlsetting' do
    expect{dsc_xspsearchcontentsource[:dsc_crawlsetting] = ["foo", "bar", "spec"]}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept boolean for dsc_crawlsetting' do
    expect{dsc_xspsearchcontentsource[:dsc_crawlsetting] = true}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept int for dsc_crawlsetting' do
    expect{dsc_xspsearchcontentsource[:dsc_crawlsetting] = -16}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept uint for dsc_crawlsetting' do
    expect{dsc_xspsearchcontentsource[:dsc_crawlsetting] = 16}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept array for dsc_continuouscrawl' do
    expect{dsc_xspsearchcontentsource[:dsc_continuouscrawl] = ["foo", "bar", "spec"]}.to raise_error(Puppet::ResourceError)
  end

  it 'should accept boolean for dsc_continuouscrawl' do
    dsc_xspsearchcontentsource[:dsc_continuouscrawl] = true
    expect(dsc_xspsearchcontentsource[:dsc_continuouscrawl]).to eq(true)
  end

  it "should accept boolean-like value 'true' and munge this value to boolean for dsc_continuouscrawl" do
    dsc_xspsearchcontentsource[:dsc_continuouscrawl] = 'true'
    expect(dsc_xspsearchcontentsource[:dsc_continuouscrawl]).to eq(true)
  end

  it "should accept boolean-like value 'false' and munge this value to boolean for dsc_continuouscrawl" do
    dsc_xspsearchcontentsource[:dsc_continuouscrawl] = 'false'
    expect(dsc_xspsearchcontentsource[:dsc_continuouscrawl]).to eq(false)
  end

  it "should accept boolean-like value 'True' and munge this value to boolean for dsc_continuouscrawl" do
    dsc_xspsearchcontentsource[:dsc_continuouscrawl] = 'True'
    expect(dsc_xspsearchcontentsource[:dsc_continuouscrawl]).to eq(true)
  end

  it "should accept boolean-like value 'False' and munge this value to boolean for dsc_continuouscrawl" do
    dsc_xspsearchcontentsource[:dsc_continuouscrawl] = 'False'
    expect(dsc_xspsearchcontentsource[:dsc_continuouscrawl]).to eq(false)
  end

  it "should accept boolean-like value :true and munge this value to boolean for dsc_continuouscrawl" do
    dsc_xspsearchcontentsource[:dsc_continuouscrawl] = :true
    expect(dsc_xspsearchcontentsource[:dsc_continuouscrawl]).to eq(true)
  end

  it "should accept boolean-like value :false and munge this value to boolean for dsc_continuouscrawl" do
    dsc_xspsearchcontentsource[:dsc_continuouscrawl] = :false
    expect(dsc_xspsearchcontentsource[:dsc_continuouscrawl]).to eq(false)
  end

  it 'should not accept int for dsc_continuouscrawl' do
    expect{dsc_xspsearchcontentsource[:dsc_continuouscrawl] = -16}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept uint for dsc_continuouscrawl' do
    expect{dsc_xspsearchcontentsource[:dsc_continuouscrawl] = 16}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept array for dsc_incrementalschedule' do
    expect{dsc_xspsearchcontentsource[:dsc_incrementalschedule] = ["foo", "bar", "spec"]}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept boolean for dsc_incrementalschedule' do
    expect{dsc_xspsearchcontentsource[:dsc_incrementalschedule] = true}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept int for dsc_incrementalschedule' do
    expect{dsc_xspsearchcontentsource[:dsc_incrementalschedule] = -16}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept uint for dsc_incrementalschedule' do
    expect{dsc_xspsearchcontentsource[:dsc_incrementalschedule] = 16}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept array for dsc_fullschedule' do
    expect{dsc_xspsearchcontentsource[:dsc_fullschedule] = ["foo", "bar", "spec"]}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept boolean for dsc_fullschedule' do
    expect{dsc_xspsearchcontentsource[:dsc_fullschedule] = true}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept int for dsc_fullschedule' do
    expect{dsc_xspsearchcontentsource[:dsc_fullschedule] = -16}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept uint for dsc_fullschedule' do
    expect{dsc_xspsearchcontentsource[:dsc_fullschedule] = 16}.to raise_error(Puppet::ResourceError)
  end

  it 'should accept dsc_priority predefined value Normal' do
    dsc_xspsearchcontentsource[:dsc_priority] = 'Normal'
    expect(dsc_xspsearchcontentsource[:dsc_priority]).to eq('Normal')
  end

  it 'should accept dsc_priority predefined value normal' do
    dsc_xspsearchcontentsource[:dsc_priority] = 'normal'
    expect(dsc_xspsearchcontentsource[:dsc_priority]).to eq('normal')
  end

  it 'should accept dsc_priority predefined value High' do
    dsc_xspsearchcontentsource[:dsc_priority] = 'High'
    expect(dsc_xspsearchcontentsource[:dsc_priority]).to eq('High')
  end

  it 'should accept dsc_priority predefined value high' do
    dsc_xspsearchcontentsource[:dsc_priority] = 'high'
    expect(dsc_xspsearchcontentsource[:dsc_priority]).to eq('high')
  end

  it 'should not accept values not equal to predefined values' do
    expect{dsc_xspsearchcontentsource[:dsc_priority] = 'invalid value'}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept array for dsc_priority' do
    expect{dsc_xspsearchcontentsource[:dsc_priority] = ["foo", "bar", "spec"]}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept boolean for dsc_priority' do
    expect{dsc_xspsearchcontentsource[:dsc_priority] = true}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept int for dsc_priority' do
    expect{dsc_xspsearchcontentsource[:dsc_priority] = -16}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept uint for dsc_priority' do
    expect{dsc_xspsearchcontentsource[:dsc_priority] = 16}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept array for dsc_limitpagedepth' do
    expect{dsc_xspsearchcontentsource[:dsc_limitpagedepth] = ["foo", "bar", "spec"]}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept boolean for dsc_limitpagedepth' do
    expect{dsc_xspsearchcontentsource[:dsc_limitpagedepth] = true}.to raise_error(Puppet::ResourceError)
  end

  it 'should accept uint for dsc_limitpagedepth' do
    dsc_xspsearchcontentsource[:dsc_limitpagedepth] = 32
    expect(dsc_xspsearchcontentsource[:dsc_limitpagedepth]).to eq(32)
  end

  it 'should not accept signed (negative) value for dsc_limitpagedepth' do
    value = -32
    expect(value).to be < 0
    expect{dsc_xspsearchcontentsource[:dsc_limitpagedepth] = value}.to raise_error(Puppet::ResourceError)
  end

  it 'should accept string-like uint for dsc_limitpagedepth' do
    dsc_xspsearchcontentsource[:dsc_limitpagedepth] = '16'
    expect(dsc_xspsearchcontentsource[:dsc_limitpagedepth]).to eq(16)
  end

  it 'should accept string-like uint for dsc_limitpagedepth' do
    dsc_xspsearchcontentsource[:dsc_limitpagedepth] = '32'
    expect(dsc_xspsearchcontentsource[:dsc_limitpagedepth]).to eq(32)
  end

  it 'should accept string-like uint for dsc_limitpagedepth' do
    dsc_xspsearchcontentsource[:dsc_limitpagedepth] = '64'
    expect(dsc_xspsearchcontentsource[:dsc_limitpagedepth]).to eq(64)
  end

  it 'should not accept array for dsc_limitserverhops' do
    expect{dsc_xspsearchcontentsource[:dsc_limitserverhops] = ["foo", "bar", "spec"]}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept boolean for dsc_limitserverhops' do
    expect{dsc_xspsearchcontentsource[:dsc_limitserverhops] = true}.to raise_error(Puppet::ResourceError)
  end

  it 'should accept uint for dsc_limitserverhops' do
    dsc_xspsearchcontentsource[:dsc_limitserverhops] = 32
    expect(dsc_xspsearchcontentsource[:dsc_limitserverhops]).to eq(32)
  end

  it 'should not accept signed (negative) value for dsc_limitserverhops' do
    value = -32
    expect(value).to be < 0
    expect{dsc_xspsearchcontentsource[:dsc_limitserverhops] = value}.to raise_error(Puppet::ResourceError)
  end

  it 'should accept string-like uint for dsc_limitserverhops' do
    dsc_xspsearchcontentsource[:dsc_limitserverhops] = '16'
    expect(dsc_xspsearchcontentsource[:dsc_limitserverhops]).to eq(16)
  end

  it 'should accept string-like uint for dsc_limitserverhops' do
    dsc_xspsearchcontentsource[:dsc_limitserverhops] = '32'
    expect(dsc_xspsearchcontentsource[:dsc_limitserverhops]).to eq(32)
  end

  it 'should accept string-like uint for dsc_limitserverhops' do
    dsc_xspsearchcontentsource[:dsc_limitserverhops] = '64'
    expect(dsc_xspsearchcontentsource[:dsc_limitserverhops]).to eq(64)
  end

  it 'should accept dsc_ensure predefined value Present' do
    dsc_xspsearchcontentsource[:dsc_ensure] = 'Present'
    expect(dsc_xspsearchcontentsource[:dsc_ensure]).to eq('Present')
  end

  it 'should accept dsc_ensure predefined value present' do
    dsc_xspsearchcontentsource[:dsc_ensure] = 'present'
    expect(dsc_xspsearchcontentsource[:dsc_ensure]).to eq('present')
  end

  it 'should accept dsc_ensure predefined value present and update ensure with this value (ensure end value should be a symbol)' do
    dsc_xspsearchcontentsource[:dsc_ensure] = 'present'
    expect(dsc_xspsearchcontentsource[:ensure]).to eq(dsc_xspsearchcontentsource[:dsc_ensure].downcase.to_sym)
  end

  it 'should accept dsc_ensure predefined value Absent' do
    dsc_xspsearchcontentsource[:dsc_ensure] = 'Absent'
    expect(dsc_xspsearchcontentsource[:dsc_ensure]).to eq('Absent')
  end

  it 'should accept dsc_ensure predefined value absent' do
    dsc_xspsearchcontentsource[:dsc_ensure] = 'absent'
    expect(dsc_xspsearchcontentsource[:dsc_ensure]).to eq('absent')
  end

  it 'should accept dsc_ensure predefined value absent and update ensure with this value (ensure end value should be a symbol)' do
    dsc_xspsearchcontentsource[:dsc_ensure] = 'absent'
    expect(dsc_xspsearchcontentsource[:ensure]).to eq(dsc_xspsearchcontentsource[:dsc_ensure].downcase.to_sym)
  end

  it 'should not accept values not equal to predefined values' do
    expect{dsc_xspsearchcontentsource[:dsc_ensure] = 'invalid value'}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept array for dsc_ensure' do
    expect{dsc_xspsearchcontentsource[:dsc_ensure] = ["foo", "bar", "spec"]}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept boolean for dsc_ensure' do
    expect{dsc_xspsearchcontentsource[:dsc_ensure] = true}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept int for dsc_ensure' do
    expect{dsc_xspsearchcontentsource[:dsc_ensure] = -16}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept uint for dsc_ensure' do
    expect{dsc_xspsearchcontentsource[:dsc_ensure] = 16}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept array for dsc_force' do
    expect{dsc_xspsearchcontentsource[:dsc_force] = ["foo", "bar", "spec"]}.to raise_error(Puppet::ResourceError)
  end

  it 'should accept boolean for dsc_force' do
    dsc_xspsearchcontentsource[:dsc_force] = true
    expect(dsc_xspsearchcontentsource[:dsc_force]).to eq(true)
  end

  it "should accept boolean-like value 'true' and munge this value to boolean for dsc_force" do
    dsc_xspsearchcontentsource[:dsc_force] = 'true'
    expect(dsc_xspsearchcontentsource[:dsc_force]).to eq(true)
  end

  it "should accept boolean-like value 'false' and munge this value to boolean for dsc_force" do
    dsc_xspsearchcontentsource[:dsc_force] = 'false'
    expect(dsc_xspsearchcontentsource[:dsc_force]).to eq(false)
  end

  it "should accept boolean-like value 'True' and munge this value to boolean for dsc_force" do
    dsc_xspsearchcontentsource[:dsc_force] = 'True'
    expect(dsc_xspsearchcontentsource[:dsc_force]).to eq(true)
  end

  it "should accept boolean-like value 'False' and munge this value to boolean for dsc_force" do
    dsc_xspsearchcontentsource[:dsc_force] = 'False'
    expect(dsc_xspsearchcontentsource[:dsc_force]).to eq(false)
  end

  it "should accept boolean-like value :true and munge this value to boolean for dsc_force" do
    dsc_xspsearchcontentsource[:dsc_force] = :true
    expect(dsc_xspsearchcontentsource[:dsc_force]).to eq(true)
  end

  it "should accept boolean-like value :false and munge this value to boolean for dsc_force" do
    dsc_xspsearchcontentsource[:dsc_force] = :false
    expect(dsc_xspsearchcontentsource[:dsc_force]).to eq(false)
  end

  it 'should not accept int for dsc_force' do
    expect{dsc_xspsearchcontentsource[:dsc_force] = -16}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept uint for dsc_force' do
    expect{dsc_xspsearchcontentsource[:dsc_force] = 16}.to raise_error(Puppet::ResourceError)
  end

  it "should not accept empty password for dsc_installaccount" do
    expect{dsc_xspsearchcontentsource[:dsc_installaccount] = {"user"=>"user", "password"=>""}}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept array for dsc_installaccount' do
    expect{dsc_xspsearchcontentsource[:dsc_installaccount] = ["foo", "bar", "spec"]}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept boolean for dsc_installaccount' do
    expect{dsc_xspsearchcontentsource[:dsc_installaccount] = true}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept int for dsc_installaccount' do
    expect{dsc_xspsearchcontentsource[:dsc_installaccount] = -16}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept uint for dsc_installaccount' do
    expect{dsc_xspsearchcontentsource[:dsc_installaccount] = 16}.to raise_error(Puppet::ResourceError)
  end

  # Configuration PROVIDER TESTS

  describe "powershell provider tests" do

    it "should successfully instanciate the provider" do
      described_class.provider(:powershell).new(dsc_xspsearchcontentsource)
    end

    before(:each) do
      @provider = described_class.provider(:powershell).new(dsc_xspsearchcontentsource)
    end

    describe "when dscmeta_module_name existing/is defined " do

      it "should compute powershell dsc test script with Invoke-DscResource" do
        expect(@provider.ps_script_content('test')).to match(/Invoke-DscResource/)
      end

      it "should compute powershell dsc test script with method Test" do
        expect(@provider.ps_script_content('test')).to match(/Method\s+=\s*'test'/)
      end

      it "should compute powershell dsc set script with Invoke-DscResource" do
        expect(@provider.ps_script_content('set')).to match(/Invoke-DscResource/)
      end

      it "should compute powershell dsc test script with method Set" do
        expect(@provider.ps_script_content('set')).to match(/Method\s+=\s*'set'/)
      end

    end

    describe "when dsc_ensure is 'present'" do

      before(:each) do
        dsc_xspsearchcontentsource.original_parameters[:dsc_ensure] = 'present'
        dsc_xspsearchcontentsource[:dsc_ensure] = 'present'
        @provider = described_class.provider(:powershell).new(dsc_xspsearchcontentsource)
      end

      it "should update :ensure to :present" do
        expect(dsc_xspsearchcontentsource[:ensure]).to eq(:present)
      end

      it "should compute powershell dsc test script in which ensure value is 'present'" do
        expect(@provider.ps_script_content('test')).to match(/ensure = 'present'/)
      end

      it "should compute powershell dsc set script in which ensure value is 'present'" do
        expect(@provider.ps_script_content('set')).to match(/ensure = 'present'/)
      end

    end

    describe "when dsc_ensure is 'absent'" do

      before(:each) do
        dsc_xspsearchcontentsource.original_parameters[:dsc_ensure] = 'absent'
        dsc_xspsearchcontentsource[:dsc_ensure] = 'absent'
        @provider = described_class.provider(:powershell).new(dsc_xspsearchcontentsource)
      end

      it "should update :ensure to :absent" do
        expect(dsc_xspsearchcontentsource[:ensure]).to eq(:absent)
      end

      it "should compute powershell dsc test script in which ensure value is 'present'" do
        expect(@provider.ps_script_content('test')).to match(/ensure = 'present'/)
      end

      it "should compute powershell dsc set script in which ensure value is 'absent'" do
        expect(@provider.ps_script_content('set')).to match(/ensure = 'absent'/)
      end

    end

    describe "when dsc_resource has credentials" do

      it "should convert credential hash to a pscredential object" do
        expect(@provider.ps_script_content('test')).to match(/| new-pscredential'/)
      end

    end

  end
end


text:
from typing import (TYPE_CHECKING,
                    Any,
                    Union)

from twisted.internet.defer import Deferred

from couchbase.result import CounterResult, MutationResult

if TYPE_CHECKING:
    from couchbase.options import (AppendOptions,
                                   DecrementOptions,
                                   IncrementOptions,
                                   PrependOptions)

class BinaryCollection:

    def __init__(self, collection):
        self._collection = collection

    def increment(
        self,
        key,  # type: str
        *opts,  # type: IncrementOptions
        **kwargs,  # type: Any
    ) -> Deferred[CounterResult]:
        return self._collection._increment(key, *opts, **kwargs)

    def decrement(
        self,
        key,  # type: str
        *opts,  # type: DecrementOptions
        **kwargs,  # type: Any
    ) -> Deferred[CounterResult]:
        return self._collection._decrement(key, *opts, **kwargs)

    def append(
        self,
        key,  # type: str
        value,  # type: Union[str,bytes,bytearray]
        *opts,  # type: AppendOptions
        **kwargs,  # type: Any
    ) -> Deferred[MutationResult]:
        return self._collection._append(key, value, *opts, **kwargs)

    def prepend(
        self,
        key,  # type: str
        value,  # type: Union[str,bytes,bytearray]
        *opts,  # type: PrependOptions
        **kwargs,  # type: Any
    ) -> Deferred[MutationResult]:
        return self._collection._prepend(key, value, *opts, **kwargs)


text:
//  (C) Copyright John Maddock 2000.
//  Use, modification and distribution are subject to the Boost Software License,
//  Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt).
//
//  See http://www.boost.org/libs/type_traits for most recent version including documentation.

#ifndef BOOST_TT_ALIGNMENT_OF_HPP_INCLUDED
#define BOOST_TT_ALIGNMENT_OF_HPP_INCLUDED

#include <boost/config.hpp>
#include <cstddef>

#include <boost/type_traits/intrinsics.hpp>
// should be the last #include
#include <boost/type_traits/detail/size_t_trait_def.hpp>

#ifdef BOOST_MSVC
#   pragma warning(push)
#   pragma warning(disable: 4121 4512) // alignment is sensitive to packing
#endif
#if defined(__BORLANDC__) && (__BORLANDC__ < 0x600)
#pragma option push -Vx- -Ve-
#endif

namespace boost {

template <typename T> struct alignment_of;

// get the alignment of some arbitrary type:
namespace detail {

#ifdef BOOST_MSVC
#pragma warning(push)
#pragma warning(disable:4324) // structure was padded due to __declspec(align())
#endif
template <typename T>
struct alignment_of_hack
{
    char c;
    T t;
    alignment_of_hack();
};
#ifdef BOOST_MSVC
#pragma warning(pop)
#endif

template <unsigned A, unsigned S>
struct alignment_logic
{
    BOOST_STATIC_CONSTANT(std::size_t, value = A < S ? A : S);
};

template< typename T >
struct alignment_of_impl
{
#if defined(BOOST_MSVC) && (BOOST_MSVC >= 1400)
	//
	// With MSVC both the native __alignof operator
	// and our own logic gets things wrong from time to time :-(
	// Using a combination of the two seems to make the most of a bad job:
	//
    BOOST_STATIC_CONSTANT(std::size_t, value =
        (::boost::detail::alignment_logic<
            sizeof(::boost::detail::alignment_of_hack<T>) - sizeof(T),
            __alignof(T)
        >::value));
#elif !defined(BOOST_ALIGNMENT_OF)
    BOOST_STATIC_CONSTANT(std::size_t, value =
        (::boost::detail::alignment_logic<
            sizeof(::boost::detail::alignment_of_hack<T>) - sizeof(T),
            sizeof(T)
        >::value));
#else
   //
   // We put this here, rather than in the definition of
   // alignment_of below, because MSVC's __alignof doesn't
   // always work in that context for some unexplained reason.
   // (See type_with_alignment tests for test cases).
   //
   BOOST_STATIC_CONSTANT(std::size_t, value = BOOST_ALIGNMENT_OF(T));
#endif
};

} // namespace detail

BOOST_TT_AUX_SIZE_T_TRAIT_DEF1(alignment_of,T,::boost::detail::alignment_of_impl<T>::value)

// references have to be treated specially, assume
// that a reference is just a special pointer:
#ifndef BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION
template <typename T>
struct alignment_of<T&>
    : alignment_of<T*>
{
};
#endif
#ifdef __BORLANDC__
// long double gives an incorrect value of 10 (!)
// unless we do this...
struct long_double_wrapper{ long double ld; };
template<> struct alignment_of<long double>
   : public alignment_of<long_double_wrapper>{};
#endif

// void has to be treated specially:
BOOST_TT_AUX_SIZE_T_TRAIT_SPEC1(alignment_of,void,0)
#ifndef BOOST_NO_CV_VOID_SPECIALIZATIONS
BOOST_TT_AUX_SIZE_T_TRAIT_SPEC1(alignment_of,void const,0)
BOOST_TT_AUX_SIZE_T_TRAIT_SPEC1(alignment_of,void volatile,0)
BOOST_TT_AUX_SIZE_T_TRAIT_SPEC1(alignment_of,void const volatile,0)
#endif

} // namespace boost

#if defined(__BORLANDC__) && (__BORLANDC__ < 0x600)
#pragma option pop
#endif
#ifdef BOOST_MSVC
#   pragma warning(pop)
#endif

#include <boost/type_traits/detail/size_t_trait_undef.hpp>

#endif // BOOST_TT_ALIGNMENT_OF_HPP_INCLUDED