text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using CassiniDev;
using NUnit.Framework;

namespace Salient.JsonClient.Tests
{
    /// <summary>
    /// </summary>
    [TestFixture,Ignore("hudson is choking on serving the website, not sure why but local runs prove that the exception pollution is not an issue in JsonClient so can ignore for now.")]
    public class ExceptionHandlingFixture : CassiniDevServer
    {
        [TestFixtureSetUp]
        public void Setup()
        {
            StartServer(new ContentLocator(@"src\JsonClient.Tests.Web").LocateContent());
        }

        #region expected behavior

        [Test,Description("this test is not really a test. I am using it to dispose the client to interactively check that the background threads are disposed. no reason to get more complicated yet as we may just merge the types")]
        public void EnsureCacheAndThrottleAreDisposed()
        {
            var client = new JsonClient.Client(new Uri("http://apiurl.foo.bar"));
            client.Dispose();

        }
        [Test, ExpectedExceptionAttribute(typeof(WebException), ExpectedMessage = "The remote server returned an error: (400) Bad Request."), Category("expected behavior")]
        public void SanityCheckServerIsRunningAndWillServeException()
        {
            var client = new WebClient();
            client.DownloadString(NormalizeUrl("ErrorEcho.aspx?code=400&message={%22foo%22}"));
        }

        [Test, Category("expected behavior")]
        public void AsyncExceptionReturnsResponseText()
        {
            var client = new Client(new Uri(RootUrl));
            var gate = new AutoResetEvent(false);
            string expected = "{\"Foo\": \"bar\"}"; ;
            string actual = null;

            client.BeginRequest<TestDTO>(ar =>
                                             {
                                                 try
                                                 {
                                                     client.EndRequest(ar);
                                                     Assert.Fail("expected exception");
                                                 }
                                                 catch (ApiException ex)
                                                 {
                                                     Assert.IsTrue(ex.Message.StartsWith("The remote server returned an error: (400) Bad Request."));

                                                     actual = ex.ResponseText;

                                                 }
                                                 finally
                                                 {
                                                     gate.Set();
                                                 }

                                             }, null, "ErrorEcho.aspx?code=400&message=" + HttpUtility.UrlEncode(expected), "GET");

            gate.WaitOne();

            Assert.AreEqual(expected, actual);

        }

        [Test, Category("expected behavior")]
        public void AsyncExceptionSurroundedByAsyncRequestsReturnsResponseText()
        {
            var client = new Client(new Uri(RootUrl));
            var gate = new AutoResetEvent(false);
            string expected = "{\"Foo\": \"bar\"}"; ;
            string actual = null;

            client.BeginRequest<TestDTO>(ar =>
            {
                try
                {
                    var dto = client.EndRequest(ar);
                    Assert.IsNotNull(dto);
                }
                finally
                {
                    gate.Set();
                }

            }, null, "ErrorEcho.aspx?code=200&message=" + HttpUtility.UrlEncode(expected), "GET");

            gate.WaitOne();

            client.BeginRequest<TestDTO>(ar =>
            {
                try
                {
                    client.EndRequest(ar);
                    Assert.Fail("expected exception");
                }
                catch (ApiException ex)
                {

                    Assert.IsTrue(ex.Message.StartsWith("The remote server returned an error: (400) Bad Request."));

                    actual = ex.ResponseText;

                }
                finally
                {
                    gate.Set();
                }

            }, null, "ErrorEcho.aspx?code=400&message=" + HttpUtility.UrlEncode(expected), "GET");

            gate.WaitOne();

            Assert.AreEqual(expected, actual);

            client.BeginRequest<TestDTO>(ar =>
            {
                try
                {
                    var dto = client.EndRequest(ar);
                    Assert.IsNotNull(dto);
                }
                finally
                {
                    gate.Set();
                }

            }, null, "ErrorEcho.aspx?code=200&message=" + HttpUtility.UrlEncode(expected), "GET");

            gate.WaitOne();

        }

        [Test, Category("expected behavior")]
        public void ConsucutiveAsyncExceptionReturnsResponseText()
        {
            var client = new Client(new Uri(RootUrl));
            var gate = new AutoResetEvent(false);
            string expected = "{\"Foo\": \"bar\"}"; ;
            string actual = null;
            client.BeginRequest<TestDTO>(ar =>
            {
                try
                {
                    client.EndRequest(ar);
                    Assert.Fail("expected exception");
                }
                catch (ApiException ex)
                {

                    Assert.IsTrue(ex.Message.StartsWith("The remote server returned an error: (400) Bad Request."));

                    actual = ex.ResponseText;

                }
                finally
                {
                    gate.Set();
                }

            }, null, "ErrorEcho.aspx?code=400&message=" + HttpUtility.UrlEncode(expected), "GET");

            gate.WaitOne();

            Assert.AreEqual(expected, actual);

            client.BeginRequest<TestDTO>(ar =>
            {
                try
                {
                    client.EndRequest(ar);
                    Assert.Fail("expected exception");
                }
                catch (ApiException ex)
                {

                    Assert.IsTrue(ex.Message.StartsWith("The remote server returned an error: (400) Bad Request."));

                    actual = ex.ResponseText;

                }
                finally
                {
                    gate.Set();
                }

            }, null, "ErrorEcho.aspx?code=400&message=" + HttpUtility.UrlEncode(expected), "GET");

            gate.WaitOne();

            Assert.AreEqual(expected, actual);

            client.BeginRequest<TestDTO>(ar =>
            {
                try
                {
                    client.EndRequest(ar);
                    Assert.Fail("expected exception");
                }
                catch (ApiException ex)
                {

                    Assert.IsTrue(ex.Message.StartsWith("The remote server returned an error: (400) Bad Request."));

                    actual = ex.ResponseText;

                }
                finally
                {
                    gate.Set();
                }

            }, null, "ErrorEcho.aspx?code=400&message=" + HttpUtility.UrlEncode(expected), "GET");

            gate.WaitOne();

            Assert.AreEqual(expected, actual);

        }

        [Test, Category("expected behavior")]
        public void SycnExceptionReturnsResponseText()
        {
            var client = new Client(new Uri(RootUrl));
            string expected = "{\"Foo\": \"bar\"}"; ;
            string actual = null;

            try
            {
                client.Request<TestDTO>("ErrorEcho.aspx?code=400&message=" + HttpUtility.UrlEncode(expected), "GET");
            }
            catch (ApiException ex)
            {

                Assert.IsTrue(ex.Message.StartsWith("The remote server returned an error: (400) Bad Request."));

                actual = ex.ResponseText;

            }
            Assert.AreEqual(expected, actual);
        }

        [Test, Category("expected behavior")]
        public void MultipleSycnExceptionReturnsResponseText()
        {
            var client = new Client(new Uri(RootUrl));
            string expected = "{\"Foo\": \"bar\"}"; ;
            string actual = null;

            try
            {
                client.Request<TestDTO>("ErrorEcho.aspx?code=400&message=" + HttpUtility.UrlEncode(expected), "GET");
            }
            catch (ApiException ex)
            {

                Assert.IsTrue(ex.Message.StartsWith("The remote server returned an error: (400) Bad Request."));

                actual = ex.ResponseText;

            }
            Assert.AreEqual(expected, actual);

            expected = "{\"Foo\": \"bar\"}"; ;
            try
            {
                client.Request<TestDTO>("ErrorEcho.aspx?code=400&message=" + HttpUtility.UrlEncode(expected), "GET");
            }
            catch (ApiException ex)
            {

                Assert.IsTrue(ex.Message.StartsWith("The remote server returned an error: (400) Bad Request."));

                actual = ex.ResponseText;

            }
            Assert.AreEqual(expected, actual);
        }

        [Test, Category("expected behavior")]
        public void SyncThenAsyncExceptionReturnsResponseText()
        {
            var client = new Client(new Uri(RootUrl));
            string expected = "{\"Foo\": \"bar\"}"; ;
            string actual = null;

            try
            {
                client.Request<TestDTO>("ErrorEcho.aspx?code=400&message=" + HttpUtility.UrlEncode(expected), "GET");
            }
            catch (ApiException ex)
            {

                Assert.IsTrue(ex.Message.StartsWith("The remote server returned an error: (400) Bad Request."));

                actual = ex.ResponseText;

            }
            Assert.AreEqual(expected, actual);

            expected = "{\"Foo\": \"bar\"}"; ;
            var gate = new AutoResetEvent(false);

            client.BeginRequest<TestDTO>(ar =>
            {
                try
                {
                    client.EndRequest(ar);
                    Assert.Fail("expected exception");
                }
                catch (ApiException ex)
                {

                    Assert.IsTrue(ex.Message.StartsWith("The remote server returned an error: (400) Bad Request."));

                    actual = ex.ResponseText;

                }
                finally
                {
                    gate.Set();
                }

            }, null, "ErrorEcho.aspx?code=400&message=" + HttpUtility.UrlEncode(expected), "GET");

            gate.WaitOne();

            Assert.AreEqual(expected, actual);

        }

        #endregion

        [Test,Category("Bug case")]
        public void SyncThenAsyncExceptionThenSyncRequestReturnsResponseText ()
        {
            var client = new Client(new Uri(RootUrl));
            string expected = "{\"Foo\": \"bar\"}";
            string actual = null;

            try
            {
                client.Request<TestDTO>("ErrorEcho.aspx?code=400&message=" + HttpUtility.UrlEncode(expected), "GET");
            }
            catch (ApiException ex)
            {

                Assert.IsTrue(ex.Message.StartsWith("The remote server returned an error: (400) Bad Request."));

                actual = ex.ResponseText;

            }
            Assert.AreEqual(expected, actual);

            expected = "{\"Foo\": \"bar\"}";
            var gate = new AutoResetEvent(false);

            client.BeginRequest<TestDTO>(ar =>
            {
                try
                {
                    client.EndRequest(ar);
                    Assert.Fail("expected exception");
                }
                catch (ApiException ex)
                {

                    Assert.IsTrue(ex.Message.StartsWith("The remote server returned an error: (400) Bad Request."));

                    actual = ex.ResponseText;

                }
                finally
                {
                    gate.Set();
                }

            }, null, "ErrorEcho.aspx?code=400&message=" + HttpUtility.UrlEncode(expected), "GET");

            gate.WaitOne();

            Assert.AreEqual(expected, actual);

            var tdto = client.Request<TestDTO>("ErrorEcho.aspx?code=200&message=" + HttpUtility.UrlEncode(expected), "GET");

        }

        [Test,Category("Bug case")]
        public void SyncExceptionSurroundedBySyncRequestsReturnsResponseText()
        {
            var client = new Client(new Uri(RootUrl));
            string expected = "{\"Foo\": \"bar\"}"; ;
            string actual = null;

            var tdto = client.Request<TestDTO>("ErrorEcho.aspx?code=200&message=" + HttpUtility.UrlEncode(expected), "GET");
            Assert.IsNotNull(tdto);

            try
            {
                client.Request<TestDTO>("ErrorEcho.aspx?code=400&message=" + HttpUtility.UrlEncode(expected), "GET");
            }
            catch (ApiException ex)
            {

                Assert.IsTrue(ex.Message.StartsWith("The remote server returned an error: (400) Bad Request."));

                actual = ex.ResponseText;

            }
            Assert.AreEqual(expected, actual);

            tdto = client.Request<TestDTO>("ErrorEcho.aspx?code=200&message=" + HttpUtility.UrlEncode(expected), "GET");
            Assert.IsNotNull(tdto);

        }
    }

    public class TestDTO
    {
        public string Foo { get; set; }
    }
}


text:
<?php

namespace MavenAlgolia\Admin\Controllers;
use \MavenAlgolia\Core;
use \MavenAlgolia\Core\Registry;

class Indexer  {

	private static $instance;

	/**
	 *
	 */
	public function __construct ( ) {

		if( Registry::instance()->isEnabled() ){
			// Delete the post in the index when it was deleted in the site
			add_action( 'deleted_post', array( &$this, 'postDeleted' ) );
			// Delete the post in the index when it was unpublished
			add_action( 'transition_post_status', array( &$this, 'postUnpublished' ), 10, 3 );
			// Update the post in the index when it was updated
			// JUST WHEN IT IS publish
			add_action( 'save_post', array( &$this, 'postUpdated' ), 11, 3 );

			// Update the term in the index when the counter was updated in WP
			add_action( "edited_term_taxonomy", array( &$this, 'termTaxonomyUpdated' ), 10, 2 );
			// Insert the term in the index when it was created
			add_action( "created_term", array( &$this, 'termCreated' ), 10, 3 );
			// Delete the term in the index when it was deleted in the site
			add_action( 'delete_term', array( &$this, 'termDeleted' ), 10, 4 );
		}
	}

	/**
	 *
	 * @return \MavenAlgolia\Core\Registry
	 */
	static function instance() {
		if ( ! isset( self::$instance ) ) {
			self::$instance = new self( );
		}
		return self::$instance;
	}

	/**
	 * Remove the post from the index when it was unpublished in WP
	 * Called from transition_post_status action
	 * @param string $new_status
	 * @param string $old_status
	 * @param \WP_Post $post
	 */
	public function postUnpublished( $new_status, $old_status, $post ) {
		$postTypesToIndex = Core\FieldsHelper::getPostTypesToIndex();
		if ( isset( $postTypesToIndex[$post->post_type] ) && $old_status == 'publish' && $new_status != 'publish' && !empty( $post->ID ) ) {
			// Post is unpublished so remove from index
			try {
				// Init the index
				$indexer = new Core\Indexer( Registry::instance()->getAppId(), Registry::instance()->getApiKey() );
				// TODO: remember to add the index by post type when we have it implemented
				$indexer->deleteObject( Registry::instance()->getDefaultIndex(), $post->ID );
			} catch ( Exception $exc ) {

			}
		}
	}

	/**
	 * Update post in the index when it was unpdated in WP
	 * Called from save_post action
	 * @param integer $postID
	 * @param \WP_Post $post
	 */
	public function postUpdated( $postID, $post ) {
		// If this is just a revision, don't send the email.
		if ( wp_is_post_revision( $postID ) ){ return; }
//		if ( count( $_POST ) <= 0 && count( $_GET ) <= 0 ) { return $postID; }
		if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) { return $postID; }
//		if ( !current_user_can('edit_post', $postID) ) { return $postID; }
		if ( $post->post_status !== 'publish' ) { return $postID; }

		$postTypesToIndex = Core\FieldsHelper::getPostTypesObject();
		if ( !isset( $postTypesToIndex[$post->post_type] ) ) { return $postID; }
		try {
			// Init the index
			$indexer = new Core\Indexer( Registry::instance()->getAppId(), Registry::instance()->getApiKey() );
			$objectToIndex = $indexer->postToAlgoliaObject( $post, $postTypesToIndex[$post->post_type] );
			if( $objectToIndex ){
				// TODO: remember to add the index by post type when we have it implemented
				$indexer->indexObject( Registry::instance()->getDefaultIndex(), $objectToIndex );
				do_action( 'mvnAlgObjectIndexedOnPostUpdate', $post, $objectToIndex );
			}
		} catch ( \Exception $exc ) {

		}
	}

	/**
	 * Remove the post from the index when it was deleted in WP
	 * Called from deleted_post action
	 * @param int $postId
	 */
	public function postDeleted( $postId ) {
		if ( !empty( $postId ) ) {
			try {
				// Post is unpublished so remove from index
				$indexer = new Core\Indexer( Registry::instance()->getAppId(), Registry::instance()->getApiKey() );
				// TODO: remember to add the index by post type when we have it implemented
				$indexer->deleteObject( Registry::instance()->getDefaultIndex(), $postId );
			} catch ( Exception $exc ) {

			}
		}
	}

	/**
	 * Update term in the index when it was unpdated in WP
	 * Called from edited_term and created_term actions
	 * @param integer $ttId
	 * @param object $taxonomy
	 */
	public function termTaxonomyUpdated( $ttId, $taxonomy ) {
		if( empty( $taxonomy->name ) ){ return $ttId; }

		$taxonomyToIndex = Core\FieldsHelper::getTaxonomyObjectByType( $taxonomy->name );

		if ( empty( $taxonomyToIndex ) || ! $taxonomyToIndex->getIndexName() ) { return $ttId; }

		// Get the object before deletion so we can pass to actions below
		$termUpdated = get_term_by( 'term_taxonomy_id', $ttId, $taxonomy->name );
		if( !is_wp_error( $termUpdated ) && $termUpdated ){
			try {
				// Init the index
				$indexer = new Core\Indexer( Registry::instance()->getAppId(), Registry::instance()->getApiKey() );
				// Convert the term in a algolia object
				$objectToIndex = $indexer->termToAlgoliaObject( $termUpdated, $taxonomyToIndex );
				if( $objectToIndex ){
					$indexer->indexObject( $taxonomyToIndex->getIndexName(), $objectToIndex );
				}
			} catch ( Exception $exc ) {

			}
		}
	}

	/**
	 * Update term in the index when it was unpdated in WP
	 * Called from edited_term and created_term actions
	 * @param integer $termId
	 * @param integer $ttId
	 * @param string $taxonomy
	 */
	public function termCreated( $termId, $ttId, $taxonomy ) {
		$taxonomyToIndex = Core\FieldsHelper::getTaxonomyObjectByType( $taxonomy );
		if ( empty( $taxonomyToIndex ) || ! $taxonomyToIndex->getIndexName() ) { return $termId; }

		// Get the object before deletion so we can pass to actions below
		$termUpdated = get_term( $termId, $taxonomy );
		if( !is_wp_error( $termUpdated ) && $termUpdated ){
			try {
				// Init the index
				$indexer = new Core\Indexer( Registry::instance()->getAppId(), Registry::instance()->getApiKey() );
				// Convert the term in a algolia object
				$objectToIndex = $indexer->termToAlgoliaObject( $termUpdated, $taxonomyToIndex );
				if( $objectToIndex ){
					$indexer->indexObject( $taxonomyToIndex->getIndexName(), $objectToIndex );
				}
			} catch ( Exception $exc ) {

			}
		}
	}

	/**
	 * Remove the term from the index when it was deleted in WP
	 * Called from delete_term action
	 * @param integer $termId
	 * @param integer $ttId
	 * @param string $taxonomy
	 * @param object $deleted_term
	 */
	public function termDeleted( $termId, $ttId, $taxonomy, $deleted_term ) {
		$taxonomyToIndex = Core\FieldsHelper::getTaxonomyObjectByType( $taxonomy );
		if ( empty( $ttId ) || empty( $taxonomyToIndex ) || ! $taxonomyToIndex->getIndexName() ) { return $termId; }
		try {
				// Term was removed so remove it from index
			$indexer = new Core\Indexer( Registry::instance()->getAppId(), Registry::instance()->getApiKey() );
			$indexer->deleteObject( $taxonomyToIndex->getIndexName(), $ttId );
		} catch ( Exception $exc ) {

		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
==========================================
NEP 13 — A Mechanism for Overriding Ufuncs
==========================================

.. currentmodule:: numpy

:Author: Blake Griffith
:Contact: blake.g@utexas.edu
:Date: 2013-07-10

:Author: Pauli Virtanen

:Author: Nathaniel Smith

:Author: Marten van Kerkwijk

:Author: Stephan Hoyer
:Date: 2017-03-31

:Status: Final

Executive summary
=================

NumPy's universal functions (ufuncs) currently have some limited
functionality for operating on user defined subclasses of
:class:`ndarray` using ``__array_prepare__`` and ``__array_wrap__``
[1]_, and there is little to no support for arbitrary
objects. e.g. SciPy's sparse matrices [2]_ [3]_.

Here we propose adding a mechanism to override ufuncs based on the ufunc
checking each of it's arguments for a ``__array_ufunc__`` method.
On discovery of ``__array_ufunc__`` the ufunc will hand off the
operation to the method.

This covers some of the same ground as Travis Oliphant's proposal to
retro-fit NumPy with multi-methods [4]_, which would solve the same
problem. The mechanism here follows more closely the way Python enables
classes to override ``__mul__`` and other binary operations. It also
specifically addresses how binary operators and ufuncs should interact.
(Note that in earlier iterations, the override was called
``__numpy_ufunc__``. An implementation was made, but had not quite the
right behaviour, hence the change in name.)

The ``__array_ufunc__`` as described below requires that any
corresponding Python binary operations (``__mul__`` et al.) should be
implemented in a specific way and be compatible with Numpy's ndarray
semantics. Objects that do not satisfy this cannot override any Numpy
ufuncs.  We do not specify a future-compatible path by which this
requirement can be relaxed --- any changes here require corresponding
changes in 3rd party code.

.. [1] http://docs.python.org/doc/numpy/user/basics.subclassing.html
.. [2] https://github.com/scipy/scipy/issues/2123
.. [3] https://github.com/scipy/scipy/issues/1569
.. [4] https://technicaldiscovery.blogspot.com/2013/07/thoughts-after-scipy-2013-and-specific.html

Motivation
==========

The current machinery for dispatching Ufuncs is generally agreed to be
insufficient. There have been lengthy discussions and other proposed
solutions [5]_, [6]_.

Using ufuncs with subclasses of :class:`ndarray` is limited to
``__array_prepare__`` and ``__array_wrap__`` to prepare the output arguments,
but these don't allow you to for example change the shape or the data of
the arguments. Trying to ufunc things that don't subclass
:class:`ndarray` is even more difficult, as the input arguments tend to
be cast to object arrays, which ends up producing surprising results.

Take this example of ufuncs interoperability with sparse matrices.::

    In [1]: import numpy as np
    import scipy.sparse as sp

    a = np.random.randint(5, size=(3,3))
    b = np.random.randint(5, size=(3,3))

    asp = sp.csr_matrix(a)
    bsp = sp.csr_matrix(b)

    In [2]: a, b
    Out[2]:(array([[0, 4, 4],
                   [1, 3, 2],
                   [1, 3, 1]]),
            array([[0, 1, 0],
                   [0, 0, 1],
                   [4, 0, 1]]))

    In [3]: np.multiply(a, b) # The right answer
    Out[3]: array([[0, 4, 0],
                   [0, 0, 2],
                   [4, 0, 1]])

    In [4]: np.multiply(asp, bsp).todense() # calls __mul__ which does matrix multi
    Out[4]: matrix([[16,  0,  8],
                    [ 8,  1,  5],
                    [ 4,  1,  4]], dtype=int64)

    In [5]: np.multiply(a, bsp) # Returns NotImplemented to user, bad!
    Out[5]: NotImplemted

Returning :obj:`NotImplemented` to user should not happen. Moreover::

    In [6]: np.multiply(asp, b)
    Out[6]: array([[ <3x3 sparse matrix of type '<class 'numpy.int64'>'
                    with 8 stored elements in Compressed Sparse Row format>,
                        <3x3 sparse matrix of type '<class 'numpy.int64'>'
                    with 8 stored elements in Compressed Sparse Row format>,
                        <3x3 sparse matrix of type '<class 'numpy.int64'>'
                    with 8 stored elements in Compressed Sparse Row format>],
                       [ <3x3 sparse matrix of type '<class 'numpy.int64'>'
                    with 8 stored elements in Compressed Sparse Row format>,
                        <3x3 sparse matrix of type '<class 'numpy.int64'>'
                    with 8 stored elements in Compressed Sparse Row format>,
                        <3x3 sparse matrix of type '<class 'numpy.int64'>'
                    with 8 stored elements in Compressed Sparse Row format>],
                       [ <3x3 sparse matrix of type '<class 'numpy.int64'>'
                    with 8 stored elements in Compressed Sparse Row format>,
                        <3x3 sparse matrix of type '<class 'numpy.int64'>'
                    with 8 stored elements in Compressed Sparse Row format>,
                        <3x3 sparse matrix of type '<class 'numpy.int64'>'
                    with 8 stored elements in Compressed Sparse Row format>]], dtype=object)

Here, it appears that the sparse matrix was converted to an object array
scalar, which was then multiplied with all elements of the ``b`` array.
However, this behavior is more confusing than useful, and having a
:exc:`TypeError` would be preferable.

This proposal will *not* resolve the issue with scipy.sparse matrices,
which have multiplication semantics incompatible with numpy arrays.
However, the aim is to enable writing other custom array types that have
strictly ndarray compatible semantics.

.. [5] https://mail.python.org/pipermail/numpy-discussion/2011-June/056945.html

.. [6] https://github.com/numpy/numpy/issues/5844

Proposed interface
==================

The standard array class :class:`ndarray` gains an ``__array_ufunc__``
method and objects can override Ufuncs by overriding this method (if
they are :class:`ndarray` subclasses) or defining their own. The method
signature is::

    def __array_ufunc__(self, ufunc, method, *inputs, **kwargs)

Here:

- *ufunc* is the ufunc object that was called.
- *method* is a string indicating how the Ufunc was called, either
  ``"__call__"`` to indicate it was called directly, or one of its
  methods: ``"reduce"``, ``"accumulate"``,  ``"reduceat"``, ``"outer"``,
  or ``"at"``.
- *inputs* is a tuple of the input arguments to the ``ufunc``
- *kwargs* contains any optional or keyword arguments passed to the
  function. This includes any ``out`` arguments, which are always
  contained in a tuple.

Hence, the arguments are normalized: only the required input arguments
(``inputs``) are passed on as positional arguments, all the others are
passed on as a dict of keyword arguments (``kwargs``). In particular, if
there are output arguments, positional are otherwise, that are not
:obj:`None`, they are passed on as a tuple in the ``out`` keyword
argument (even for the ``reduce``, ``accumulate``, and ``reduceat`` methods
where in all current cases only a single output makes sense).

The function dispatch proceeds as follows:

- If one of the input or output arguments implements
  ``__array_ufunc__``, it is executed instead of the ufunc.

- If more than one of the arguments implements ``__array_ufunc__``,
  they are tried in the following order: subclasses before superclasses,
  inputs before outputs, otherwise left to right.

- The first ``__array_ufunc__`` method returning something else than
  :obj:`NotImplemented` determines the return value of the Ufunc.

- If all ``__array_ufunc__`` methods of the input arguments return
  :obj:`NotImplemented`, a :exc:`TypeError` is raised.

- If a ``__array_ufunc__`` method raises an error, the error is
  propagated immediately.

- If none of the input arguments had an ``__array_ufunc__`` method, the
  execution falls back on the default ufunc behaviour.

In the above, there is one proviso: if a class has an
``__array_ufunc__`` attribute but it is identical to
``ndarray.__array_ufunc__``, the attribute is ignored.  This happens for
instances of `ndarray` and for `ndarray` subclasses that did not
override their inherited ``__array_ufunc__`` implementation.

Type casting hierarchy
----------------------

The Python operator override mechanism gives much freedom in how to
write the override methods, and it requires some discipline in order to
achieve predictable results. Here, we discuss an approach for
understanding some of the implications, which can provide input in the
design.

It is useful to maintain a clear idea of what types can be "upcast" to
others, possibly indirectly (e.g. indirect A->B->C is implemented but
direct A->C not). If the implementations of ``__array_ufunc__`` follow a
coherent type casting hierarchy, it can be used to understand results of
operations.

Type casting can be expressed as a `graph <https://en.wikipedia.org/wiki/Graph_theory>`__
defined as follows:

    For each ``__array_ufunc__`` method, draw directed edges from each
    possible input type to each possible output type.

    That is, in each case where ``y = x.__array_ufunc__(a, b, c, ...)``
    does something else than returning ``NotImplemented`` or raising an error,
    draw edges ``type(a) -> type(y)``, ``type(b) -> type(y)``, ...

If the resulting graph is *acyclic*, it defines a coherent type casting
hierarchy (unambiguous partial ordering between types).  In this case,
operations involving multiple types generally predictably produce result
of the "highest" type, or raise a :exc:`TypeError`.  See examples at the
end of this section.

If the graph has cycles, the ``__array_ufunc__`` type casting is not
well-defined, and things such as ``type(multiply(a, b)) !=
type(multiply(b, a))`` or ``type(add(a, add(b, c))) != type(add(add(a,
b), c))`` are not excluded (and then probably always possible).

If the type casting hierarchy is well defined, for each class A, all
other classes that define ``__array_ufunc__`` belong to exactly one of
three groups:

- *Above A*: the types that A can be (indirectly) upcast to in ufuncs.

- *Below A*: the types that can be (indirectly) upcast to A in ufuncs.

- *Incompatible*: neither above nor below A; types for which no
  (indirect) upcasting is possible.

Note that the legacy behaviour of numpy ufuncs is to try to convert
unknown objects to :class:`ndarray` via :func:`np.asarray`.  This is
equivalent to placing :class:`ndarray` above these objects in the graph.
Since we above defined :class:`ndarray` to return `NotImplemented` for
classes with custom ``__array_ufunc__``, this puts :class:`ndarray`
below such classes in the type hierarchy, allowing the operations to be
overridden.

In view of the above, binary ufuncs describing transitive operations
should aim to define a well-defined casting hierarchy.  This is likely
also a sensible approach to all ufuncs --- exceptions to this should
consider carefully if any surprising behavior results.

.. admonition:: Example

   Type casting hierarchy.

   .. image:: _static/nep0013_image1.png

   The ``__array_ufunc__`` of type A can handle ndarrays returning C,
   B can handle ndarray and D returning B, and C can handle A and B returning C,
   but not ndarrays or D.  The
   result is a directed acyclic graph, and defines a type casting
   hierarchy, with relations ``C > A``, ``C > ndarray``, ``C > B > ndarray``,
   ``C > B > D``. The type A is incompatible with B, D, ndarray,
   and D is incompatible with A and ndarray.  Ufunc
   expressions involving these classes should produce results of the
   highest type involved or raise a :exc:`TypeError`.

.. admonition:: Example

   One-cycle in the ``__array_ufunc__`` graph.

   .. image:: _static/nep0013_image2.png

   In this case, the ``__array_ufunc__`` relations have a cycle of length 1,
   and a type casting hierarchy does not exist. Binary operations are not
   commutative: ``type(a + b) is A`` but ``type(b + a) is B``.

.. admonition:: Example

   Longer cycle in the ``__array_ufunc__`` graph.

   .. image:: _static/nep0013_image3.png

   In this case, the ``__array_ufunc__`` relations have a longer cycle, and a
   type casting hierarchy does not exist. Binary operations are still
   commutative, but type transitivity is lost: ``type(a + (b + c)) is A`` but
   ``type((a + b) + c) is C``.

Subclass hierarchies
--------------------

Generally, it is desirable to mirror the class hierarchy in the ufunc
type casting hierarchy. The recommendation is that an
``__array_ufunc__`` implementation of a class should generally return
`NotImplemented` unless the inputs are instances of the same class or
superclasses.  This guarantees that in the type casting hierarchy,
superclasses are below, subclasses above, and other classes are
incompatible.  Exceptions to this need to check they respect the
implicit type casting hierarchy.

.. note::

   Note that type casting hierarchy and class hierarchy are here defined
   to go the "opposite" directions.  It would in principle also be
   consistent to have ``__array_ufunc__`` handle also instances of
   subclasses. In this case, the "subclasses first" dispatch rule would
   ensure a relatively similar outcome. However, the behavior is then less
   explicitly specified.

Subclasses can be easily constructed if methods consistently use
:func:`super` to pass through the class hierarchy [7]_.  To support
this, :class:`ndarray` has its own ``__array_ufunc__`` method,
equivalent to::

    def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
        # Cannot handle items that have __array_ufunc__ (other than our own).
        outputs = kwargs.get('out', ())
        for item in inputs + outputs:
            if (hasattr(item, '__array_ufunc__') and
                    type(item).__array_ufunc__ is not ndarray.__array_ufunc__):
                return NotImplemented

        # If we didn't have to support legacy behaviour (__array_prepare__,
        # __array_wrap__, etc.), we might here convert python floats,
        # lists, etc, to arrays with
        # items = [np.asarray(item) for item in inputs]
        # and then start the right iterator for the given method.
        # However, we do have to support legacy, so call back into the ufunc.
        # Its arguments are now guaranteed not to have __array_ufunc__
        # overrides, and it will do the coercion to array for us.
        return getattr(ufunc, method)(*items, **kwargs)

Note that, as a special case, the ufunc dispatch mechanism does not call
this `ndarray.__array_ufunc__` method, even for `ndarray` subclasses
if they have not overridden the default `ndarray` implementation. As a
consequence, calling `ndarray.__array_ufunc__` will not result to a
nested ufunc dispatch cycle.

The use of :func:`super` should be particularly useful for subclasses of
:class:`ndarray` that only add an attribute like a unit.  In their
`__array_ufunc__` implementation, such classes can do possible
adjustment of the arguments relevant to their own class, and pass on to
the superclass implementation using :func:`super` until the ufunc is
actually done, and then do possible adjustments of the outputs.

In general, custom implementations of `__array_ufunc__` should avoid
nested dispatch cycles, where one not just calls the ufunc via
``getattr(ufunc, method)(*items, **kwargs)``, but catches possible
exceptions, etc.  As always, there may be exceptions. For instance, for a
class like :class:`MaskedArray`, which only cares that whatever
it contains is an :class:`ndarray` subclass, a reimplementation with
``__array_ufunc__`` may well be more easily done by directly applying
the ufunc to its data, and then adjusting the mask.  Indeed, one can
think of this as part of the class determining whether it can handle the
other argument (i.e., where in the type hierarchy it sits). In this
case, one should return :obj:`NotImplemented` if the trial fails.  So,
the implementation would be something like::

    def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
        # for simplicity, outputs are ignored here.
        unmasked_items = tuple((item.data if isinstance(item, MaskedArray)
                                else item) for item in inputs)
        try:
            unmasked_result = getattr(ufunc, method)(*unmasked_items, **kwargs)
        except TypeError:
            return NotImplemented
        # for simplicity, ignore that unmasked_result could be a tuple
        # or a scalar.
        if not isinstance(unmasked_result, np.ndarray):
            return NotImplemented
        # now combine masks and view as MaskedArray instance
        ...

As a specific example, consider a quantity and a masked array class
which both override ``__array_ufunc__``, with specific instances ``q``
and ``ma``, where the latter contains a regular array. Executing
``np.multiply(q, ma)``, the ufunc will first dispatch to
``q.__array_ufunc__``, which returns :obj:`NotImplemented` (since the
quantity class turns itself into an array and calls :func:`super`, which
passes on to ``ndarray.__array_ufunc__``, which sees the override on
``ma``). Next, ``ma.__array_ufunc__`` gets a chance. It does not know
quantity, and if it were to just return :obj:`NotImplemented` as well,
an :exc:`TypeError` would result. But in our sample implementation, it
uses ``getattr(ufunc, method)`` to, effectively, evaluate
``np.multiply(q, ma.data)``. This again will pass to
``q.__array_ufunc__``, but this time, since ``ma.data`` is a regular
array, it will return a result that is also a quantity. Since this is a
subclass of :class:`ndarray`, ``ma.__array_ufunc__`` can turn this into
a masked array and thus return a result (obviously, if it was not a
array subclass, it could still return :obj:`NotImplemented`).

Note that in the context of the type hierarchy discussed above this is a
somewhat tricky example, since :class:`MaskedArray` has a strange
position: it is above all subclasses of :class:`ndarray`, in that it can
cast them to its own type, but it does not itself know how to interact
with them in ufuncs.

.. [7] https://rhettinger.wordpress.com/2011/05/26/super-considered-super/

.. _neps.ufunc-overrides.turning-ufuncs-off:

Turning Ufuncs off
------------------

For some classes, Ufuncs make no sense, and, like for some other special
methods such as ``__hash__`` and ``__iter__`` [8]_, one can indicate
Ufuncs are not available by setting ``__array_ufunc__`` to :obj:`None`.
If a Ufunc is called on any operand that sets ``__array_ufunc__ = None``,
it will unconditionally raise :exc:`TypeError`.

In the type casting hierarchy, this makes it explicit that the type is
incompatible relative to :class:`ndarray`.

.. [8] https://docs.python.org/3/reference/datamodel.html#specialnames

Behavior in combination with Python's binary operations
-------------------------------------------------------

The Python operator override mechanism in :class:`ndarray` is coupled to
the ``__array_ufunc__`` mechanism. For the special methods calls such as
``ndarray.__mul__(self, other)`` that Python calls for implementing
binary operations such as ``*`` and ``+``, NumPy's :class:`ndarray`
implements the following behavior:

- If ``other.__array_ufunc__ is None``, :class:`ndarray`
  returns :obj:`NotImplemented`. Control reverts to Python, which in turn
  will try calling a corresponding reflexive method on ``other`` (e.g.,
  ``other.__rmul__``), if present.
- If the ``__array_ufunc__`` attribute is absent on ``other`` and
  ``other.__array_priority__ > self.__array_priority__``, :class:`ndarray`
  also returns :obj:`NotImplemented` (and the logic proceeds as in the
  previous case). This ensures backwards compatibility with old versions
  of NumPy.
- Otherwise, :class:`ndarray` unilaterally calls the corresponding Ufunc.
  Ufuncs never return ``NotImplemented``, so **reflexive methods such
  as** ``other.__rmul__`` **cannot be used to override arithmetic with
  NumPy arrays if** ``__array_ufunc__`` **is set** to any value other than
  ``None``. Instead, their behavior needs to be changed by implementing
  ``__array_ufunc__`` in a fashion consistent with the corresponding Ufunc,
  e.g., ``np.multiply``. See :ref:`neps.ufunc-overrides.list-of-operators`
  for a list of affected operators and their corresponding ufuncs.

A class wishing to modify the interaction with :class:`ndarray` in
binary operations therefore has two options:

1. Implement ``__array_ufunc__`` and follow Numpy semantics for Python
   binary operations (see below).

2. Set ``__array_ufunc__ = None``, and implement Python binary
   operations freely.  In this case, ufuncs called on this argument will
   raise :exc:`TypeError` (see
   :ref:`neps.ufunc-overrides.turning-ufuncs-off`).

Recommendations for implementing binary operations
--------------------------------------------------

For most numerical classes, the easiest way to override binary
operations is thus to define ``__array_ufunc__`` and override the
corresponding Ufunc. The class can then, like :class:`ndarray` itself,
define the binary operators in terms of Ufuncs. Here, one has to take
some care to ensure that one allows for other classes to indicate they
are not compatible, i.e., implementations should be something like::

    def _disables_array_ufunc(obj):
        try:
            return obj.__array_ufunc__ is None
        except AttributeError:
            return False

    class ArrayLike(object):
        ...
        def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
            ...
            return result

        # Option 1: call ufunc directly
        def __mul__(self, other):
            if _disables_array_ufunc(other):
                return NotImplemented
            return np.multiply(self, other)

        def __rmul__(self, other):
            if _disables_array_ufunc(other):
                return NotImplemented
            return np.multiply(other, self)

        def __imul__(self, other):
            return np.multiply(self, other, out=(self,))

        # Option 2: call into one's own __array_ufunc__
        def __mul__(self, other):
            return self.__array_ufunc__(np.multiply, '__call__', self, other)

        def __rmul__(self, other):
            return self.__array_ufunc__(np.multiply, '__call__', other, self)

        def __imul__(self, other):
            result = self.__array_ufunc__(np.multiply, '__call__', self, other,
                                          out=(self,))
            if result is NotImplemented:
                raise TypeError(...)

To see why some care is necessary, consider another class ``other`` that
does not know how to deal with arrays and ufuncs, and thus has set
``__array_ufunc__`` to :obj:`None`, but does know how to do
multiplication::

    class MyObject(object):
        __array_ufunc__ = None
        def __init__(self, value):
            self.value = value
        def __repr__(self):
            return "MyObject({!r})".format(self.value)
        def __mul__(self, other):
            return MyObject(1234)
        def __rmul__(self, other):
            return MyObject(4321)

For either option above, we get the expected result::

    mine = MyObject(0)
    arr = ArrayLike([0])

    mine * arr    # -> MyObject(1234)
    mine *= arr   # -> MyObject(1234)
    arr * mine    # -> MyObject(4321)
    arr *= mine   # -> TypeError

Here, in the first and second example, ``mine.__mul__(arr)`` gets called
and the result arrives immediately.  In the third example, first
``arr.__mul__(mine)`` is called. In option (1), the check on
``mine.__array_ufunc__ is None`` will succeed and thus
:obj:`NotImplemented` is returned, which causes ``mine.__rmul__(arg)``
to be executed.  In option (2), it is presumably inside
``arr.__array_ufunc__`` that it becomes clear that the other argument
cannot be dealt with, and again :obj:`NotImplemented` is returned,
causing control to pass to ``mine.__rmul__``.

For the fourth example, with the in-place operators, we have here
followed :class:`ndarray` and ensure we never return
:obj:`NotImplemented`, but rather raise a :exc:`TypeError`. In
option (1) this happens indirectly: we pass to ``np.multiply``, which
in turn immediately raises :exc:`TypeError`, because one of its operands
(``out[0]``) disables Ufuncs.  In option (2), we pass directly to
``arr.__array_ufunc__``, which will return :obj:`NotImplemented`, which
we catch.

.. note :: the reason for not allowing in-place operations to return
   :obj:`NotImplemented` is that these cannot generically be replaced by
   a simple reverse operation: most array operations assume the contents
   of the instance are changed in-place, and do not expect a new
   instance.  Also, what would ``ndarr[:] *= mine`` imply?  Assuming it
   means ``ndarr[:] = ndarr[:] * mine``, as python does by default if
   the ``ndarr.__imul__`` were to return :obj:`NotImplemented`, is
   likely to be wrong.

Now consider what would happen if we had not added checks. For option
(1), the relevant case is if we had not checked whether
``__array_func__`` was set to :obj:`None`.  In the third example,
``arr.__mul__(mine)`` is called, and without the check, this would go to
``np.multiply(arr, mine)``. This tries ``arr.__array_ufunc__``, which
returns :obj:`NotImplemented` and sees that ``mine.__array_ufunc__ is
None``, so a :exc:`TypeError` is raised.

For option (2), the relevant example is the fourth, with ``arr *=
mine``: if we had let the :obj:`NotImplemented` pass, python would have
replaced this with ``arr = mine.__rmul__(arr)``, which is not wanted.

Because the semantics of Ufunc overrides and Python's binary operations
are nearly identical, in most cases options (1) and (2) will
yield the same result with the same implementation of ``__array_ufunc__``.
One exception is the order in which implementations are tried when the
second argument is a subclass of the first argument, due to a Python
bug [9]_ expected to be fixed in Python 3.7.

In general, we recommend adopting option (1), which is the option most
similar to that used by :class:`ndarray` itself. Note that option (1)
is viral, in the sense that any other class that wishes to support binary
operations with your class now must also follow these rules for supporting
binary arithmetic with :class:`ndarray` (i.e., they must either implement
``__array_ufunc__`` or set it to :obj:`None`). We believe this is a good
thing, because it ensures the consistency of ufuncs and arithmetic on all
objects that support them.

To make implementing such array-like classes easier, the mixin class
:class:`~numpy.lib.mixins.NDArrayOperatorsMixin` provides option (1) style
overrides for all binary operators with corresponding Ufuncs. Classes
that wish to implement ``__array_ufunc__`` for compatible versions
of NumPy but that also need to support binary arithmetic with NumPy arrays
on older versions should ensure that ``__array_ufunc__`` can also be used
to implement all binary operations they support.

Finally, we note that we had extensive discussion about whether it might
make more sense to ask classes like ``MyObject`` to implement a full
``__array_ufunc__`` [6]_. In the end, allowing classes to opt out was
preferred, and the above reasoning led us to agree on a similar
implementation for :class:`ndarray` itself. The opt-out mechanism requires
disabling Ufuncs so a class cannot define a Ufuncs to return a different
result than the corresponding binary operations (i.e., if
``np.add(x, y)`` is defined, it should match ``x + y``). Our goal was to
simplify the dispatch logic for binary operations with NumPy arrays
as much as possible, by making it possible to use Python's dispatch rules
or NumPy's dispatch rules, but not some mixture of both at the same time.

.. [9] https://bugs.python.org/issue30140

.. _neps.ufunc-overrides.list-of-operators:

List of operators and NumPy Ufuncs
----------------------------------

Here is a full list of Python binary operators and the corresponding NumPy
Ufuncs used by :class:`ndarray` and
:class:`~numpy.lib.mixins.NDArrayOperatorsMixin`:

====== ============ =========================================
Symbol Operator     NumPy Ufunc(s)
====== ============ =========================================
``<``  ``lt``       :func:`less`
``<=`` ``le``       :func:`less_equal`
``==`` ``eq``       :func:`equal`
``!=`` ``ne``       :func:`not_equal`
``>``  ``gt``       :func:`greater`
``>=`` ``ge``       :func:`greater_equal`
``+``  ``add``      :func:`add`
``-``  ``sub``      :func:`subtract`
``*``  ``mul``      :func:`multiply`
``/``  ``truediv``  :func:`true_divide`
       (Python 3)
``/``  ``div``      :func:`divide`
       (Python 2)
``//`` ``floordiv`` :func:`floor_divide`
``%``  ``mod``      :func:`remainder`
NA     ``divmod``   :func:`divmod`
``**`` ``pow``      :func:`power` [10]_
``<<`` ``lshift``   :func:`left_shift`
``>>`` ``rshift``   :func:`right_shift`
``&``  ``and_``     :func:`bitwise_and`
``^``  ``xor_``     :func:`bitwise_xor`
``|``  ``or_``      :func:`bitwise_or`
``@``  ``matmul``   Not yet implemented as a ufunc [11]_
====== ============ =========================================

And here is the list of unary operators:

====== ============ =========================================
Symbol Operator     NumPy Ufunc(s)
====== ============ =========================================
``-``  ``neg``      :func:`negative`
``+``  ``pos``      :func:`positive` [12]_
NA     ``abs``      :func:`absolute`
``~``  ``invert``   :func:`invert`
====== ============ =========================================

.. [10] class :`ndarray` takes short cuts for ``__pow__`` for the
        cases where the power equals ``1`` (:func:`positive`),
        ``-1`` (:func:`reciprocal`), ``2`` (:func:`square`), ``0`` (an
        otherwise private ``_ones_like`` ufunc), and ``0.5``
        (:func:`sqrt`), and the array is float or complex (or integer
        for square).
.. [11] Because NumPy's :func:`matmul` is not a ufunc, it is
        `currently not possible <https://github.com/numpy/numpy/issues/9028>`_
        to override ``numpy_array @ other`` with ``other`` taking precedence
        if ``other`` implements ``__array_func__``.
.. [12] :class:`ndarray` currently does a copy instead of using this ufunc.

Future extensions to other functions
------------------------------------

Some numpy functions could be implemented as (generalized) Ufunc, in
which case it would be possible for them to be overridden by the
``__array_ufunc__`` method.  A prime candidate is :func:`~numpy.matmul`,
which currently is not a Ufunc, but could be relatively easily be
rewritten as a (set of) generalized Ufuncs. The same may happen with
functions such as :func:`~numpy.median`, :func:`~numpy.min`, and
:func:`~numpy.argsort`.

.. Local Variables:
.. mode: rst
.. coding: utf-8
.. fill-column: 72
.. End:


text:
class ZMQ::Socket::Pair

# == ZMQ::Socket::Pair
#
# A socket of type ZMQ::Socket::Pair can only be connected to a single peer at any one time. No message routing or filtering
# is performed on messages sent over a ZMQ::Socket::Pair socket.
#
# When a ZMQ::Socket::Pair socket enters an exceptional state due to having reached the high water mark for the connected
# peer, or if no peer is connected, then any ZMQ::Socket#send operations on the socket shall block until the peer becomes
# available for sending; messages are not discarded.
#
# === Summary of ZMQ::Socket::Pair characteristics
#
# [Compatible peer sockets] ZMQ::Socket::Pair
# [Direction] Bidirectional
# [Send/receive pattern] Unrestricted
# [Incoming routing strategy] N/A
# [Outgoing routing strategy] N/A
# [ZMQ::Socket#hwm option action] Block

  TYPE_STR = "PAIR"
  REXP_INPROC = /inproc:\/\//

  def bind(endpoint)
    raise(ZMQ::Error, "PAIR sockets can only listen using the inproc:// transport") unless endpoint =~ REXP_INPROC
    super
  end

  def connect(endpoint)
    raise(ZMQ::Error, "PAIR sockets can only connect using the inproc:// transport") unless endpoint =~ REXP_INPROC
    super
  end

  def type
    ZMQ::PAIR
  end
end


text:
echo ""
echo "Teamviewer for Raspberry Pi 2 & 3"
echo ""
echo "You can always download the latest script here:"
echo "wget htt://bit.ly/teamviewerrpi"
echo ""

wget http://download.teamviewer.com/download/linux/version_11x/teamviewer-host_armhf.deb
sudo dpkg -i teamviewer-host_armhf.deb
sudo apt-get -f install

echo ""
echo "If you want TeamViewer to star with the system use the following command:"
echo "sudo teamviewer daemon enable"
echo "sudo teamviewer passwd YOURPASSWORD"
echo ""


text:
import _extends from 'babel-runtime/helpers/extends';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
// TODO: Remove this pragma once we upgrade eslint-config-airbnb.
/* eslint-disable react/no-multi-comp */

import classNames from 'classnames';
import React, { PropTypes } from 'react';
import elementType from 'react-prop-types/lib/elementType';
import uncontrollable from 'uncontrollable';

import Grid from './Grid';
import NavbarBrand from './NavbarBrand';
import NavbarCollapse from './NavbarCollapse';
import NavbarHeader from './NavbarHeader';
import NavbarToggle from './NavbarToggle';
import { bsClass as setBsClass, bsStyles, getClassSet, prefix, splitBsPropsAndOmit } from './utils/bootstrapUtils';
import { Style } from './utils/StyleConfig';
import createChainedFunction from './utils/createChainedFunction';

var propTypes = {
  /**
   * Create a fixed navbar along the top of the screen, that scrolls with the
   * page
   */
  fixedTop: React.PropTypes.bool,
  /**
   * Create a fixed navbar along the bottom of the screen, that scrolls with
   * the page
   */
  fixedBottom: React.PropTypes.bool,
  /**
   * Create a full-width navbar that scrolls away with the page
   */
  staticTop: React.PropTypes.bool,
  /**
   * An alternative dark visual style for the Navbar
   */
  inverse: React.PropTypes.bool,
  /**
   * Allow the Navbar to fluidly adjust to the page or container width, instead
   * of at the predefined screen breakpoints
   */
  fluid: React.PropTypes.bool,

  /**
   * Set a custom element for this component.
   */
  componentClass: elementType,
  /**
   * A callback fired when the `<Navbar>` body collapses or expands. Fired when
   * a `<Navbar.Toggle>` is clicked and called with the new `navExpanded`
   * boolean value.
   *
   * @controllable navExpanded
   */
  onToggle: React.PropTypes.func,
  /**
   * A callback fired when a descendant of a child `<Nav>` is selected. Should
   * be used to execute complex closing or other miscellaneous actions desired
   * after selecting a descendant of `<Nav>`. Does nothing if no `<Nav>` or `<Nav>`
   * descendants exist. The callback is called with an eventKey, which is a
   * prop from the selected `<Nav>` descendant, and an event.
   *
   * ```js
   * function (
   * 	Any eventKey,
   * 	SyntheticEvent event?
   * )
   * ```
   *
   * For basic closing behavior after all `<Nav>` descendant onSelect events in
   * mobile viewports, try using collapseOnSelect.
   *
   * Note: If you are manually closing the navbar using this `OnSelect` prop,
   * ensure that you are setting `expanded` to false and not *toggling* between
   * true and false.
   */
  onSelect: React.PropTypes.func,
  /**
   * Sets `expanded` to `false` after the onSelect event of a descendant of a
   * child `<Nav>`. Does nothing if no `<Nav>` or `<Nav>` descendants exist.
   *
   * The onSelect callback should be used instead for more complex operations
   * that need to be executed after the `select` event of `<Nav>` descendants.
   */
  collapseOnSelect: React.PropTypes.bool,
  /**
   * Explicitly set the visiblity of the navbar body
   *
   * @controllable onToggle
   */
  expanded: React.PropTypes.bool,

  role: React.PropTypes.string
};

var defaultProps = {
  componentClass: 'nav',
  fixedTop: false,
  fixedBottom: false,
  staticTop: false,
  inverse: false,
  fluid: false,
  collapseOnSelect: false
};

var childContextTypes = {
  $bs_navbar: PropTypes.shape({
    bsClass: PropTypes.string,
    expanded: PropTypes.bool,
    onToggle: PropTypes.func.isRequired,
    onSelect: PropTypes.func
  })
};

var Navbar = function (_React$Component) {
  _inherits(Navbar, _React$Component);

  function Navbar(props, context) {
    _classCallCheck(this, Navbar);

    var _this = _possibleConstructorReturn(this, _React$Component.call(this, props, context));

    _this.handleToggle = _this.handleToggle.bind(_this);
    _this.handleCollapse = _this.handleCollapse.bind(_this);
    return _this;
  }

  Navbar.prototype.getChildContext = function getChildContext() {
    var _props = this.props,
        bsClass = _props.bsClass,
        expanded = _props.expanded,
        onSelect = _props.onSelect,
        collapseOnSelect = _props.collapseOnSelect;

    return {
      $bs_navbar: {
        bsClass: bsClass,
        expanded: expanded,
        onToggle: this.handleToggle,
        onSelect: createChainedFunction(onSelect, collapseOnSelect ? this.handleCollapse : null)
      }
    };
  };

  Navbar.prototype.handleCollapse = function handleCollapse() {
    var _props2 = this.props,
        onToggle = _props2.onToggle,
        expanded = _props2.expanded;

    if (expanded) {
      onToggle(false);
    }
  };

  Navbar.prototype.handleToggle = function handleToggle() {
    var _props3 = this.props,
        onToggle = _props3.onToggle,
        expanded = _props3.expanded;

    onToggle(!expanded);
  };

  Navbar.prototype.render = function render() {
    var _extends2;

    var _props4 = this.props,
        Component = _props4.componentClass,
        fixedTop = _props4.fixedTop,
        fixedBottom = _props4.fixedBottom,
        staticTop = _props4.staticTop,
        inverse = _props4.inverse,
        fluid = _props4.fluid,
        className = _props4.className,
        children = _props4.children,
        props = _objectWithoutProperties(_props4, ['componentClass', 'fixedTop', 'fixedBottom', 'staticTop', 'inverse', 'fluid', 'className', 'children']);

    var _splitBsPropsAndOmit = splitBsPropsAndOmit(props, ['expanded', 'onToggle', 'onSelect', 'collapseOnSelect']),
        bsProps = _splitBsPropsAndOmit[0],
        elementProps = _splitBsPropsAndOmit[1];

    // will result in some false positives but that seems better
    // than false negatives. strict `undefined` check allows explicit
    // "nulling" of the role if the user really doesn't want one

    if (elementProps.role === undefined && Component !== 'nav') {
      elementProps.role = 'navigation';
    }

    if (inverse) {
      bsProps.bsStyle = Style.INVERSE;
    }

    var classes = _extends({}, getClassSet(bsProps), (_extends2 = {}, _extends2[prefix(bsProps, 'fixed-top')] = fixedTop, _extends2[prefix(bsProps, 'fixed-bottom')] = fixedBottom, _extends2[prefix(bsProps, 'static-top')] = staticTop, _extends2));

    return React.createElement(
      Component,
      _extends({}, elementProps, {
        className: classNames(className, classes)
      }),
      React.createElement(
        Grid,
        { fluid: fluid },
        children
      )
    );
  };

  return Navbar;
}(React.Component);

Navbar.propTypes = propTypes;
Navbar.defaultProps = defaultProps;
Navbar.childContextTypes = childContextTypes;

setBsClass('navbar', Navbar);

var UncontrollableNavbar = uncontrollable(Navbar, { expanded: 'onToggle' });

function createSimpleWrapper(tag, suffix, displayName) {
  var Wrapper = function Wrapper(_ref, _ref2) {
    var Component = _ref.componentClass,
        className = _ref.className,
        pullRight = _ref.pullRight,
        pullLeft = _ref.pullLeft,
        props = _objectWithoutProperties(_ref, ['componentClass', 'className', 'pullRight', 'pullLeft']);

    var _ref2$$bs_navbar = _ref2.$bs_navbar,
        navbarProps = _ref2$$bs_navbar === undefined ? { bsClass: 'navbar' } : _ref2$$bs_navbar;
    return React.createElement(Component, _extends({}, props, {
      className: classNames(className, prefix(navbarProps, suffix), pullRight && prefix(navbarProps, 'right'), pullLeft && prefix(navbarProps, 'left'))
    }));
  };

  Wrapper.displayName = displayName;

  Wrapper.propTypes = {
    componentClass: elementType,
    pullRight: React.PropTypes.bool,
    pullLeft: React.PropTypes.bool
  };

  Wrapper.defaultProps = {
    componentClass: tag,
    pullRight: false,
    pullLeft: false
  };

  Wrapper.contextTypes = {
    $bs_navbar: PropTypes.shape({
      bsClass: PropTypes.string
    })
  };

  return Wrapper;
}

UncontrollableNavbar.Brand = NavbarBrand;
UncontrollableNavbar.Header = NavbarHeader;
UncontrollableNavbar.Toggle = NavbarToggle;
UncontrollableNavbar.Collapse = NavbarCollapse;

UncontrollableNavbar.Form = createSimpleWrapper('div', 'form', 'NavbarForm');
UncontrollableNavbar.Text = createSimpleWrapper('p', 'text', 'NavbarText');
UncontrollableNavbar.Link = createSimpleWrapper('a', 'link', 'NavbarLink');

// Set bsStyles here so they can be overridden.
export default bsStyles([Style.DEFAULT, Style.INVERSE], Style.DEFAULT, UncontrollableNavbar);


text:
class CreateOrdenDelDia < ActiveRecord::Migration
  def change
    create_table :orden_del_dia do |t|
      t.integer :nro
      t.date :fecha
      t.text :observacion
      #== el orden del dia tiene una sesion
      t.belongs_to :sesion, index: true

      t.timestamps null: false
    end
  end
end


text:
#pragma once

#include "Common.hpp"
#include "Segmentation.hpp"

namespace opencc {
/**
 * Conversion interface
 * @ingroup opencc_cpp_api
 */
class OPENCC_EXPORT Conversion {
public:
  Conversion(DictPtr _dict) : dict(_dict) {}

  // Convert single phrase
  std::string Convert(const std::string& phrase) const;

  // Convert single phrase
  std::string Convert(const char* phrase) const;

  // Convert segmented text
  SegmentsPtr Convert(const SegmentsPtr& input) const;

  const DictPtr GetDict() const { return dict; }

private:
  const DictPtr dict;
};
} // namespace opencc


text:
package com.intellij.util.xml;

import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.SearchScope;
import com.intellij.psi.scope.PsiScopeProcessor;
import com.intellij.util.IncorrectOperationException;
import com.intellij.lang.Language;
import com.intellij.lang.ASTNode;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.NonNls;

import javax.swing.*;

public class DomReferenceInjectorTest extends DomHardCoreTestCase {
  public void testBasic() throws Exception {
    MyElement element = createElement("<value>abc${prop}def</value>", MyElement.class);
    assertEquals("abc${prop}def", element.getValue().getStringValue());
    assertEquals("abc${prop}def", element.getValue().getValue());
  }

  public void testWithInjector() throws Exception {
    MyElement element = createElement("<value>abc${prop}def</value>", MyElement.class);

    registerInjectorFor(element, null);

    assertEquals("abcFOOdef", element.getValue().getStringValue());
    assertEquals("abcFOOdef", element.getValue().getValue());
  }

  public void testCorrectlyCalculateOffsetWithInjector() throws Exception {
    MyElement element = createElement("<value>   abc${prop}def   </value>", MyElement.class);

    registerInjectorFor(element, null);

    assertEquals("abcFOOdef", element.getValue().getStringValue());
    assertEquals("abcFOOdef", element.getValue().getValue());
  }

  public void testWithInjectorAndConverter() throws Exception {
    MyElement element = createElement("<converted-value>abc${prop}def</converted-value>", MyElement.class);

    registerInjectorFor(element, null);

    assertEquals("abcFOOdef", element.getConvertedValue().getStringValue());
    assertEquals("abcBARdef", element.getConvertedValue().getValue());
  }

  public void testReference() throws Exception {
    String text = "<value>abc${prop}def</value>";
    MyElement element = createElement(text, MyElement.class);

    MyPsiElement targetElement = new MyPsiElement();
    registerInjectorFor(element, targetElement);

    assertEquals("abcFOOdef", element.getValue().getStringValue());
    assertEquals("abcFOOdef", element.getValue().getValue());

    assertReference(element.getValue(), targetElement, text.indexOf("${prop}") + 1);
  }

  public void testAttribute() throws Exception {
    String text = "";
    MyElement element = createElement(text, MyElement.class);

    MyPsiElement targetElement = new MyPsiElement();
    registerInjectorFor(element, targetElement);

    assertEquals("abcFOOdef", element.getAttr().getStringValue());
    assertEquals("abcFOOdef", element.getAttr().getValue());

    assertReference(element.getAttr(), targetElement, text.indexOf("${prop}") + 1);
  }

  private void registerInjectorFor(DomElement element, PsiElement targetElement) {
    DomUtil.getFileElement(element).getFileDescription().registerReferenceInjector(new MyInjector(targetElement));
  }

  public interface MyElement extends DomElement {
    GenericDomValue<String> getValue();

    @Convert(MyConverter.class)
    GenericDomValue<String> getConvertedValue();

    GenericAttributeValue<String> getAttr();
  }

  public static class MyConverter extends Converter<String> {
    @Override
    public String fromString(@Nullable @NonNls String s, ConvertContext context) {
      return s == null ? null : s.replaceAll("FOO", "BAR");
    }

    @Override
    public String toString(@Nullable String s, ConvertContext context) {
      return s;
    }
  }

  public static class MyPsiElement implements PsiElement {
    @Override
    @NotNull
    public Project getProject() throws PsiInvalidElementAccessException {
      throw new UnsupportedOperationException();
    }

    @Override
    @NotNull
    public Language getLanguage() {
      throw new UnsupportedOperationException();
    }

    @Override
    public PsiManager getManager() {
      throw new UnsupportedOperationException();
    }

    @Override
    @NotNull
    public PsiElement[] getChildren() {
      throw new UnsupportedOperationException();
    }

    @Override
    public PsiElement getParent() {
      throw new UnsupportedOperationException();
    }

    @Override
    public PsiElement getFirstChild() {
      throw new UnsupportedOperationException();
    }

    @Override
    public PsiElement getLastChild() {
      throw new UnsupportedOperationException();
    }

    @Override
    public PsiElement getNextSibling() {
      throw new UnsupportedOperationException();
    }

    @Override
    public PsiElement getPrevSibling() {
      throw new UnsupportedOperationException();
    }

    @Override
    public PsiFile getContainingFile() throws PsiInvalidElementAccessException {
      throw new UnsupportedOperationException();
    }

    @Override
    public TextRange getTextRange() {
      throw new UnsupportedOperationException();
    }

    @Override
    public int getStartOffsetInParent() {
      throw new UnsupportedOperationException();
    }

    @Override
    public int getTextLength() {
      throw new UnsupportedOperationException();
    }

    @Override
    public PsiElement findElementAt(int offset) {
      throw new UnsupportedOperationException();
    }

    @Override
    public PsiReference findReferenceAt(int offset) {
      throw new UnsupportedOperationException();
    }

    @Override
    public int getTextOffset() {
      throw new UnsupportedOperationException();
    }

    @Override
    public String getText() {
      throw new UnsupportedOperationException();
    }

    @Override
    @NotNull
    public char[] textToCharArray() {
      throw new UnsupportedOperationException();
    }

    @Override
    public PsiElement getNavigationElement() {
      throw new UnsupportedOperationException();
    }

    @Override
    public PsiElement getOriginalElement() {
      throw new UnsupportedOperationException();
    }

    @Override
    public boolean textMatches(@NotNull @NonNls CharSequence text) {
      throw new UnsupportedOperationException();
    }

    @Override
    public boolean textMatches(@NotNull PsiElement element) {
      throw new UnsupportedOperationException();
    }

    @Override
    public boolean textContains(char c) {
      throw new UnsupportedOperationException();
    }

    @Override
    public void accept(@NotNull PsiElementVisitor visitor) {
      throw new UnsupportedOperationException();
    }

    @Override
    public void acceptChildren(@NotNull PsiElementVisitor visitor) {
      throw new UnsupportedOperationException();
    }

    @Override
    public PsiElement copy() {
      throw new UnsupportedOperationException();
    }

    @Override
    public PsiElement add(@NotNull PsiElement element) throws IncorrectOperationException {
      throw new UnsupportedOperationException();
    }

    @Override
    public PsiElement addBefore(@NotNull PsiElement element, PsiElement anchor) throws IncorrectOperationException {
      throw new UnsupportedOperationException();
    }

    @Override
    public PsiElement addAfter(@NotNull PsiElement element, PsiElement anchor) throws IncorrectOperationException {
      throw new UnsupportedOperationException();
    }

    @Override
    public void checkAdd(@NotNull PsiElement element) throws IncorrectOperationException {
      throw new UnsupportedOperationException();
    }

    @Override
    public PsiElement addRange(PsiElement first, PsiElement last) throws IncorrectOperationException {
      throw new UnsupportedOperationException();
    }

    @Override
    public PsiElement addRangeBefore(@NotNull PsiElement first, @NotNull PsiElement last, PsiElement anchor)
      throws IncorrectOperationException {
      throw new UnsupportedOperationException();
    }

    @Override
    public PsiElement addRangeAfter(PsiElement first, PsiElement last, PsiElement anchor) throws IncorrectOperationException {
      throw new UnsupportedOperationException();
    }

    @Override
    public void delete() throws IncorrectOperationException {
      throw new UnsupportedOperationException();
    }

    @Override
    public void checkDelete() throws IncorrectOperationException {
      throw new UnsupportedOperationException();
    }

    @Override
    public void deleteChildRange(PsiElement first, PsiElement last) throws IncorrectOperationException {
      throw new UnsupportedOperationException();
    }

    @Override
    public PsiElement replace(@NotNull PsiElement newElement) throws IncorrectOperationException {
      throw new UnsupportedOperationException();
    }

    @Override
    public boolean isValid() {
      throw new UnsupportedOperationException();
    }

    @Override
    public boolean isWritable() {
      throw new UnsupportedOperationException();
    }

    @Override
    public PsiReference getReference() {
      throw new UnsupportedOperationException();
    }

    @Override
    @NotNull
    public PsiReference[] getReferences() {
      throw new UnsupportedOperationException();
    }

    @Override
    public <T> T getCopyableUserData(Key<T> key) {
      throw new UnsupportedOperationException();
    }

    @Override
    public <T> void putCopyableUserData(Key<T> key, T value) {
      throw new UnsupportedOperationException();
    }

    @Override
    public boolean processDeclarations(@NotNull PsiScopeProcessor processor,
                                       @NotNull ResolveState state,
                                       @Nullable PsiElement lastParent,
                                       @NotNull PsiElement place) {
      throw new UnsupportedOperationException();
    }

    @Override
    public PsiElement getContext() {
      throw new UnsupportedOperationException();
    }

    @Override
    public boolean isPhysical() {
      throw new UnsupportedOperationException();
    }

    @Override
    @NotNull
    public GlobalSearchScope getResolveScope() {
      throw new UnsupportedOperationException();
    }

    @Override
    @NotNull
    public SearchScope getUseScope() {
      throw new UnsupportedOperationException();
    }

    @Override
    public ASTNode getNode() {
      throw new UnsupportedOperationException();
    }

    @Override
    public boolean isEquivalentTo(PsiElement another) {
      throw new UnsupportedOperationException();
    }

    @Override
    public <T> T getUserData(@NotNull Key<T> key) {
      throw new UnsupportedOperationException();
    }

    @Override
    public <T> void putUserData(@NotNull Key<T> key, @Nullable T value) {
      throw new UnsupportedOperationException();
    }

    @Override
    public Icon getIcon(int flags) {
      throw new UnsupportedOperationException();
    }
  }

  private static class MyInjector implements DomReferenceInjector {
    private final PsiElement myMyTargetElement;

    public MyInjector(PsiElement myTargetElement) {
      myMyTargetElement = myTargetElement;
    }

    @Override
    public String resolveString(@Nullable String unresolvedText, @NotNull ConvertContext context) {
      return unresolvedText == null ? null : unresolvedText.replaceAll("\\$\\{prop\\}", "FOO");
    }

    @Override
    @NotNull
    public PsiReference[] inject(@Nullable String unresolvedText, @NotNull final PsiElement element, @NotNull ConvertContext context) {
      final String prop = "${prop}";
      int index = unresolvedText == null ? -1 : unresolvedText.indexOf(prop);
      if (index == -1) return PsiReference.EMPTY_ARRAY;

      TextRange textRange = ElementManipulators.getValueTextRange(element);
      final TextRange refRange = TextRange.from(textRange.getStartOffset() + index, prop.length());

      return new PsiReference[] {
        new PsiReference() {
          @Override
          public PsiElement getElement() {
            return element;
          }

          @Override
          public TextRange getRangeInElement() {
            return refRange;
          }

          @Override
          public PsiElement resolve() {
            return myMyTargetElement;
          }

          @Override
          @NotNull
          public String getCanonicalText() {
            return prop;
          }

          @Override
          public PsiElement handleElementRename(String newElementName) throws IncorrectOperationException {
            return null;
          }

          @Override
          public PsiElement bindToElement(@NotNull PsiElement element) throws IncorrectOperationException {
            return null;
          }

          @Override
          public boolean isReferenceTo(PsiElement element) {
            return false;
          }

          @Override
          @NotNull
          public Object[] getVariants() {
            return EMPTY_ARRAY;
          }

          @Override
          public boolean isSoft() {
            return true;
          }
        }
      };
    }
  }
}


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.github.amccurry</groupId>
	<artifactId>yrun</artifactId>
	<version>0.1.0-SNAPSHOT</version>
	<packaging>jar</packaging>
	<name>Yarn Runner</name>
	<description>Yarn runner will distribute generic programs for execution in Yarn.</description>

	<dependencies>
        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-client</artifactId>
            <version>2.6.0</version>
        </dependency>
	</dependencies>

	<repositories>
		<repository>
			<id>libdir</id>
			<url>file://${basedir}/../lib</url>
		</repository>
	</repositories>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-surefire-plugin</artifactId>
				<configuration>
					<argLine>-XX:+UseConcMarkSweepGC -Xmx1g -Xms1g</argLine>
					<forkCount>2</forkCount>
					<forkMode>always</forkMode>
					<reuseForks>false</reuseForks>
					<systemPropertyVariables>
						<blur.tmp.dir>${project.build.directory}/target/tmp</blur.tmp.dir>
					</systemPropertyVariables>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<source>1.6</source>
					<target>1.6</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>


text:
"""
Collection of physical constants and conversion factors.

Most constants are in SI units, so you can do
print '10 mile per minute is', 10*mile/minute, 'm/s or', 10*mile/(minute*knot), 'knots'

The list is not meant to be comprehensive, but just a convenient list for everyday use.
"""

"""
BasSw 2006
physical constants: imported from CODATA
unit conversion: see e.g. NIST special publication 811
Use at own risk: double-check values before calculating your Mars orbit-insertion burn.
Some constants exist in a few variants, which are marked with suffixes.
The ones without any suffix should be the most common one.
"""

import math as _math
from codata import value as _cd
import numpy as np

#mathematical constants
pi = _math.pi
golden = golden_ratio = (1 + _math.sqrt(5)) / 2

#SI prefixes
yotta = 1e24
zetta = 1e21
exa = 1e18
peta = 1e15
tera = 1e12
giga = 1e9
mega = 1e6
kilo = 1e3
hecto = 1e2
deka = 1e1
deci = 1e-1
centi = 1e-2
milli = 1e-3
micro = 1e-6
nano = 1e-9
pico = 1e-12
femto = 1e-15
atto = 1e-18
zepto = 1e-21

#binary prefixes
kibi = 2**10
mebi = 2**20
gibi = 2**30
tebi = 2**40
pebi = 2**50
exbi = 2**60
zebi = 2**70
yobi = 2**80

#physical constants
c = speed_of_light = _cd('speed of light in vacuum')
mu_0 = 4e-7*pi
epsilon_0 = 1 / (mu_0*c*c)
h = Planck = _cd('Planck constant')
hbar = h / (2 * pi)
G = gravitational_constant = _cd('Newtonian constant of gravitation')
g = _cd('standard acceleration of gravity')
e = elementary_charge = _cd('elementary charge')
R = gas_constant = _cd('molar gas constant')
alpha = fine_structure = _cd('fine-structure constant')
N_A = Avogadro = _cd('Avogadro constant')
k = Bolzmann = _cd('Boltzmann constant')
sigma = Stefan_Bolzmann = _cd('Stefan-Boltzmann constant')
Wien = _cd('Wien wavelength displacement law constant')
Rydberg = _cd('Rydberg constant')

#weight in kg
gram = 1e-3
metric_ton = 1e3
grain = 64.79891e-6
lb = pound = 7000 * grain #avoirdupois
oz = ounce = pound / 16
stone = 14 * pound
long_ton = 2240 * pound
short_ton = 2000 * pound

troy_ounce = 480 * grain #only for metals / gems
troy_pound = 12 * troy_ounce
carat = 200e-6

m_e = electron_mass = _cd('electron mass')
m_p = proton_mass = _cd('proton mass')
m_n = neutron_mass = _cd('neutron mass')
m_u = u = atomic_mass = _cd('atomic mass constant')

#angle in rad
degree = pi / 180
arcmin = arcminute = degree / 60
arcsec = arcsecond = arcmin / 60

#time in second
minute = 60.0
hour = 60 * minute
day = 24 * hour
week = 7 * day
year = 365 * day
Julian_year = 365.25 * day

#length in meter
inch = 0.0254
foot = 12 * inch
yard = 3 * foot
mile = 1760 * yard
mil = inch / 1000
pt = point = inch / 72 #typography
survey_foot = 1200.0 / 3937
survey_mile = 5280 * survey_foot
nautical_mile = 1852.0
fermi = 1e-15
angstrom = 1e-10
micron = 1e-6
au = astronomical_unit = 149597870691.0
light_year = Julian_year * c
parsec = au / arcsec

#pressure in pascal
atm = atmosphere = _cd('standard atmosphere')
bar = 1e5
torr = mmHg = atm / 760
psi = pound * g / (inch * inch)

#area in meter**2
hectare = 1e4
acre = 43560 * foot**2

#volume in meter**3
litre = liter = 1e-3
gallon = gallon_US = 231 * inch**3 #US
#pint = gallon_US / 8
fluid_ounce = fluid_ounce_US = gallon_US / 128
bbl = barrel = 42 * gallon_US #for oil

gallon_imp = 4.54609e-3 #uk
fluid_ounce_imp = gallon_imp / 160

#speed in meter per second
kmh = 1e3 / hour
mph = mile / hour
mach = speed_of_sound = 340.5 #approx value at 15 degrees in 1 atm. is this a common value?
knot = nautical_mile / hour

#temperature in kelvin
zero_Celsius = 273.15
degree_Fahrenheit = 1/1.8 #only for differences

#energy in joule
eV = electron_volt = elementary_charge # * 1 Volt
calorie = calorie_th = 4.184
calorie_IT = 4.1868
erg = 1e-7
Btu_th = pound * degree_Fahrenheit * calorie_th / gram
Btu = Btu_IT = pound * degree_Fahrenheit * calorie_IT / gram
ton_TNT = 1e9 * calorie_th
#Wh = watt_hour

#power in watt
hp = horsepower = 550 * foot * pound * g

#force in newton
dyn = dyne = 1e-5
lbf = pound_force = pound * g
kgf = kilogram_force = g # * 1 kg

#functions for conversions that are not linear

def C2K(C):
    """
    Convert Celsius to Kelvin

    Parameters
    ----------
    C : array_like
        Celsius temperature(s) to be converted.

    Returns
    -------
    K : float or array of floats
        Equivalent Kelvin temperature(s).

    Notes
    -----
    Computes ``K = C + zero_Celsius`` where `zero_Celsius` = 273.15, i.e.,
    (the absolute value of) temperature "absolute zero" as measured in Celsius.

    Examples
    --------
    >>> from scipy.constants.constants import C2K
    >>> C2K(np.array([-40, 40.0]))
    array([ 233.15,  313.15])

    """
    return np.asanyarray(C) + zero_Celsius

def K2C(K):
    """
    Convert Kelvin to Celsius

    Parameters
    ----------
    K : array_like
        Kelvin temperature(s) to be converted.

    Returns
    -------
    C : float or array of floats
        Equivalent Celsius temperature(s).

    Notes
    -----
    Computes ``C = K - zero_Celsius`` where `zero_Celsius` = 273.15, i.e.,
    (the absolute value of) temperature "absolute zero" as measured in Celsius.

    Examples
    --------
    >>> from scipy.constants.constants import K2C
    >>> K2C(np.array([233.15, 313.15]))
    array([-40.,  40.])

    """
    return np.asanyarray(K) - zero_Celsius

def F2C(F):
    """
    Convert Fahrenheit to Celsius

    Parameters
    ----------
    F : array_like
        Fahrenheit temperature(s) to be converted.

    Returns
    -------
    C : float or array of floats
        Equivalent Celsius temperature(s).

    Notes
    -----
    Computes ``C = (F - 32) / 1.8``.

    Examples
    --------
    >>> from scipy.constants.constants import F2C
    >>> F2C(np.array([-40, 40.0]))
    array([-40.        ,   4.44444444])

    """
    return (np.asanyarray(F) - 32) / 1.8

def C2F(C):
    """
    Convert Celsius to Fahrenheit

    Parameters
    ----------
    C : array_like
        Celsius temperature(s) to be converted.

    Returns
    -------
    F : float or array of floats
        Equivalent Fahrenheit temperature(s).

    Notes
    -----
    Computes ``F = 1.8 * C + 32``.

    Examples
    --------
    >>> from scipy.constants.constants import C2F
    >>> C2F(np.array([-40, 40.0]))
    array([ -40.,  104.])

    """
    return 1.8 * np.asanyarray(C) + 32

def F2K(F):
    """
    Convert Fahrenheit to Kelvin

    Parameters
    ----------
    F : array_like
        Fahrenheit temperature(s) to be converted.

    Returns
    -------
    K : float or array of floats
        Equivalent Kelvin temperature(s).

    Notes
    -----
    Computes ``K = (F - 32)/1.8 + zero_Celsius`` where `zero_Celsius` =
    273.15, i.e., (the absolute value of) temperature "absolute zero" as
    measured in Celsius.

    Examples
    --------
    >>> from scipy.constants.constants import F2K
    >>> F2K(np.array([-40, 104]))
    array([ 233.15,  313.15])

    """
    return C2K(F2C(np.asanyarray(F)))

def K2F(K):
    """
    Convert Kelvin to Fahrenheit

    Parameters
    ----------
    K : array_like
        Kelvin temperature(s) to be converted.

    Returns
    -------
    F : float or array of floats
        Equivalent Fahrenheit temperature(s).

    Notes
    -----
    Computes ``F = 1.8 * (K - zero_Celsius) + 32`` where `zero_Celsius` =
    273.15, i.e., (the absolute value of) temperature "absolute zero" as
    measured in Celsius.

    Examples
    --------
    >>> from scipy.constants.constants import K2F
    >>> K2F(np.array([233.15,  313.15]))
    array([ -40.,  104.])

    """
    return C2F(K2C(np.asanyarray(K)))

#optics

def lambda2nu(lambda_):
    """
    Convert wavelength to optical frequency

    Parameters
    ----------
    lambda : array_like
        Wavelength(s) to be converted.

    Returns
    -------
    nu : float or array of floats
        Equivalent optical frequency.

    Notes
    -----
    Computes ``nu = c / lambda`` where c = 299792458.0, i.e., the
    (vacuum) speed of light in meters/second.

    Examples
    --------
    >>> from scipy.constants.constants import lambda2nu
    >>> lambda2nu(np.array((1, speed_of_light)))
    array([  2.99792458e+08,   1.00000000e+00])

    """
    return np.asanyarray(c) / lambda_

def nu2lambda(nu):
    """
    Convert optical frequency to wavelength.

    Parameters
    ----------
    nu : array_like
        Optical frequency to be converted.

    Returns
    -------
    lambda : float or array of floats
        Equivalent wavelength(s).

    Notes
    -----
    Computes ``lambda = c / nu`` where c = 299792458.0, i.e., the
    (vacuum) speed of light in meters/second.

    Examples
    --------
    >>> from scipy.constants.constants import nu2lambda
    >>> nu2lambda(np.array((1, speed_of_light)))
    array([  2.99792458e+08,   1.00000000e+00])

    """
    return c / np.asanyarray(nu)


text:
MccWhileStatement::MccWhileStatement(MccExpression *condition, MccStatement *stmt)
	: MccConditionStatement(condition),
	  m_statement(stmt)
{
}

MccWhileStatement::~MccWhileStatement(void)
{
	if (this->m_statement != nullptr) {
		delete this->m_statement;
	}
}

int MccWhileStatement::generate_code() const
{
	MccRobot &robot = theMccRobot();
	string &code_buffer = robot.get_code_buffer();
	string while_start_label = "while_";
	while_start_label += robot.generate_branch_label();
	string break_label = while_start_label + "_end";

	// Backup for later recovery.
	string continue_label_bak = robot.get_current_continue_label();
	string break_label_bak = robot.get_current_break_label();

	// Set up new label.
	robot.set_current_break_label(break_label);
	robot.set_current_continue_label(while_start_label);

#ifdef DEBUG_MODE
	code_buffer += "MccWhileStatement generation.\n";
#endif
	code_buffer +=
		while_start_label + ":\n";
	robot
		.add_code(while_start_label + ":");

	// While condition.
	this->m_condition->generate_code();
	code_buffer +=
		"beq $v0, $zero, " + break_label + "\n"
		"srlv $v1, $zero, $zero\n";
	robot
		.add_code("beq $v0, $zero, " + break_label)
		.add_code("srlv $v1, $zero, $zero");

	// While body.
	this->m_statement->generate_code();

	// Jump back to the beginning of the while.
	code_buffer +=
		"j " + while_start_label + "\n"
		"srlv $v1, $zero, $zero\n";
	robot
		.add_code("j " + while_start_label)
		.add_code("srlv $v1, $zero, $zero");

	// While end.
	code_buffer +=
		break_label + ":\n";
	robot
		.add_code(break_label + ":");

	// Recovery.
	robot.set_current_break_label(break_label_bak);
	robot.set_current_continue_label(continue_label_bak);

	return 0;
}

void MccWhileStatement::semantic_detect()
{
	theMccRobot().get_current_checker()->detect(this);
}


text:
import { Model } from '@shiftcoders/dynamo-easy'

@Model({ tableName: 'my-model-table-name' })
export class MyModel {

}


text:
/**
 *
 */
package gov.nih.nci.calims2.business.administration.customerservice.service;

import gov.nih.nci.calims2.business.util.validation.DefaultValidator;
import gov.nih.nci.calims2.domain.administration.customerservice.Service;

/**
 * @author connollym@moxieinformatics.com
 *
 */
public class ServiceValidator extends DefaultValidator<Service> {

//Nothing to do for now

}


text:
<?php

namespace SystemBundle\DataFixtures\ORM;

use Doctrine\Common\DataFixtures\FixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use SystemBundle\Entity\Admin;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

class LoadAdminData implements FixtureInterface, ContainerAwareInterface
{
    /** @var  ContainerInterface */
    public $container;

    public function setContainer(ContainerInterface $container = null)
    {
        $this->container = $container;
    }

    public function load(ObjectManager $manager)
    {
        $admin = new Admin();

        $encoder = $this->container->get('security.password_encoder');
        $encoded = $encoder->encodePassword($admin, '123456');

        $admin
            ->setEmail('admin@gmail.com')
            ->setPassword($encoded);

        $manager->persist($admin);
        $manager->flush();
    }
}


text:
using Xunit;
using HtmlHelper.Bootstrap;
using static HtmlHelper.Bootstrap.FluentApi;

namespace HtmlHelper.Tests
{
    public class ButtonsTests
    {
       [Fact]
        public void SuccessButtonTest()
        {
            // arrange
            var button = Button(ButtonType.Success, "Success!");

            // act
            var html = button.Render();

            // assert
            Assert.Equal("<button type='button' class='btn btn-success'>Success!</button>", html);
        }

        [Fact]
        public void LargeDangerButtonTest()
        {
            // arrange
            var button = Button(ButtonType.Danger, ButtonSize.Large, "Danger!");

            // act
            var html = button.Render();

            // assert
            Assert.Equal("<button type='button' class='btn btn-danger btn-lg'>Danger!</button>", html);
        }

        [Fact]
        public void OutlineButtonTest()
        {
            // arrange
            var button = OutlineButton(ButtonType.Primary, "Click me!");

            // act
            var html = button.Render();

            // assert
            Assert.Equal("<button type='button' class='btn btn-outline-primary'>Click me!</button>", html);
        }

        [Fact]
        public void SmallOutlineButtonTest()
        {
            // arrange
            var button = OutlineButton(ButtonType.Info, ButtonSize.Small, "Click for more info!");

            // act
            var html = button.Render();

            // assert
            Assert.Equal("<button type='button' class='btn btn-outline-info btn-sm'>Click for more info!</button>", html);
        }

        [Fact]
        public void BlockButtonTest()
        {
            // arrange
            var button = BlockButton(ButtonType.Default, "Block Level Button");

            // act
            var html = button.Render();

            // assert
            Assert.Equal("<button type='button' class='btn btn-default btn-block'>Block Level Button</button>", html);
        }

        [Fact]
        public void ButtonGroupTest()
        {
            // arrange
            var group = ButtonGroup(
                Button(ButtonType.Default, "Button 1"),
                Button(ButtonType.Default, "Button 2"),
                Button(ButtonType.Default, "Button 3"));

            // act
            var html = group.Render();

            // assert
            Assert.Equal(
                "
" +
                    "<button type='button' class='btn btn-default'>Button 1</button>" +
                    "<button type='button' class='btn btn-default'>Button 2</button>" +
                    "<button type='button' class='btn btn-default'>Button 3</button>" +
                "
",
                html);
        }

        [Fact]
        public void ButtonToolbarTest()
        {
            // arrange
            var toolbar = ButtonToolbar(
                ButtonGroup(
                    Button(ButtonType.Default, "1"),
                    Button(ButtonType.Default, "2"),
                    Button(ButtonType.Default, "3")
                ),
                ButtonGroup(
                    Button(ButtonType.Default, "4"),
                    Button(ButtonType.Default, "5")
                ),
                ButtonGroup(
                    Button(ButtonType.Default, "6")
                )
            );

            // act
            var html = toolbar.Render();

            // assert
            Assert.Equal(
                "
" +
                    "
" +
                        "<button type='button' class='btn btn-default'>1</button>" +
                        "<button type='button' class='btn btn-default'>2</button>" +
                        "<button type='button' class='btn btn-default'>3</button>" +
                    "
" +
                    "
" +
                        "<button type='button' class='btn btn-default'>4</button>" +
                        "<button type='button' class='btn btn-default'>5</button>" +
                    "
" +
                    "
" +
                        "<button type='button' class='btn btn-default'>6</button>" +
                    "
" +
                "
",
                html);
        }

        [Fact]
        public void ButtonToolbarWithInputGroup()
        {
            // arrange
            var toolbar = ButtonToolbar(
                ButtonGroup(
                    Button(ButtonType.Default, "1"),
                    Button(ButtonType.Default, "2"),
                    Button(ButtonType.Default, "3")
                ),
                InputGroup(
                    InputGroupAddOn("@"),
                    FormControl(InputType.Text)
                )
            );

            // act
            var html = toolbar.Render();

            // assert
            Assert.Equal(
                "
" +
                    "
" +
                        "<button type='button' class='btn btn-default'>1</button>" +
                        "<button type='button' class='btn btn-default'>2</button>" +
                        "<button type='button' class='btn btn-default'>3</button>" +
                    "
" +
                    "
" +
                        "@" +
                        "<input type='text' class='form-control'/>" +
                    "
" +
                "
",
                html);
        }
    }
}


text:
Login to Voyager

        <form class="form-signin" role="form">

{{error}}

                        <button class="btn btn-lg btn-default" style="width:100%; padding: 10px 16px; font-size: 18px; margin-bottom: 10px;" ng-click="goExternal(method)">Sign in with {{method.displayName}}</button>

OR

            <fieldset>
                <input type="text" class="form-control focus_field" name="username" placeholder="Your username" ng-model="$parent.user" ng-keypress="handleEnter($event)" required autofocus />
                Your username
            </fieldset>
            <fieldset>
                <input type="password" class="form-control focus_field" name="password" placeholder="Your password" ng-model="$parent.pass"  ng-keypress="handleEnter($event)" required>
                What are you looking for?
            </fieldset>
            Forgot your password?
            <input style="margin-top: 10px" type="checkbox" ng-model="$parent.keepLoggedIn" id="keepLoggedInCheck">
            Keep me logged in
        </form>

            <button class="btn btn-primary" ng-click="ok()">Login</button>
            Cancel


text: qmake -tp vc dirview.pro