text:
[![StyleCI](https://styleci.io/repos/70251410/shield?branch=master)](https://styleci.io/repos/70251410)
[![SensioLabsInsight](https://insight.sensiolabs.com/projects/2113fe3d-8256-4009-8d0c-8a84f21a7b59/mini.png)](https://insight.sensiolabs.com/projects/2113fe3d-8256-4009-8d0c-8a84f21a7b59)

GmailBundle allows you to manage a Google Apps domain's inboxes (you can pick which). In order to do this,
you must authorize a [service account with domain wide delegation](https://console.developers.google.com/iam-admin/serviceaccounts/serviceaccounts-zero)

## Installation

```bash
    $ composer require fourlabs/gmail-bundle
```

## Configuration

```yaml
// app/config/config.yml
fl_gmail:
    admin_user_email: tech@slv.global
    json_key_location: /var/www/symfony/app/config/service_account_private_key.json
    gmail_message_class: \AppBundle\Entity\GmailMessage
    gmail_label_class: \AppBundle\Entity\GmailLabel
    gmail_history_class: \AppBundle\Entity\GmailHistory
    gmail_ids_class: \AppBundle\Entity\GmailIds

swiftmailer:
    default_mailer: general_mailer
    mailers:
        general_mailer:
            transport: "%mailer_transport%"
            host:      "%mailer_host%"
            username:  "%mailer_user%"
            password:  "%mailer_password%"
            spool:     { type: memory }
        fl_gmail_api_mailer:
            transport: fl_gmail.swift_transport
```

#### Syncing Gmail Ids (i.e. Which emails need to be synced?)
`FL\GmailBundle\Services\SyncGmailIds`
- Takes a `$userId` parameter.
- Gets a list of all the Gmail Ids, or the subset of Gmail Ids according to a history Id.  [What is a history Id?](https://developers.google.com/gmail/api/guides/sync)
- Dispatches `FL\GmailBundle\Event\GmailSyncIdsEvent` with a list of all the new / updated ids. (Updated Gmail Ids = change of label)
- It is your responsibility to save the Gmail Ids coming from this event.
- Dispatches `FL\GmailBundle\Event\GmailSyncHistoryEvent`, such that next time, you can perform a Partial Sync. [What is a Partial Sync?](https://developers.google.com/gmail/api/guides/sync)
- It is your responsibility to save the History Id coming from this event.

#### Syncing Messages using Gmail Ids (i.e. I know which emails need to be synced, let's fetch them.)
`FL\GmailBundle\Services\SyncMessages`
- This service, takes a list of gmail ids and resolves all the new/updated messages for you.
- I.e. use the ids you are fetching from `FL\GmailBundle\Services\SyncGmailIds`
- Dispatches `FL\GmailBundle\Event\GmailSyncMessagesEvent`.
- It is your responsibility to save the Gmail Messages coming from this event.
- It is your responsibility to remove the newly synced Gmail Ids, you had previously saved with `FL\GmailBundle\Services\SyncGmailIds`.

#### All this responsibility? :cry: :sob:

Why are there so many `It is your responsibility` statements? Because this bundle is storage agnostic. But don't fret! There
is a [GmailDoctrineBundle](https://github.com/fourlabsldn/GmailDoctrineBundle) that implements all of this in Doctrine for you.

### How do I dive into this bundle?

- Start by looking into the `Model` classes.
- To understand the services, have a look at `Resources/config/services.yml`.

### What else is going on?

- You can send swiftmailer emails through `FL\GmailBundle\Swift\GmailApiTransport`. Simply make sure the from is in your domain.
- `FL\GmailBundle\Form\Type\InboxType` contains a choice type, with all the inboxes in the authenticated domain.

## License

GmailBundle is licensed under the MIT license.


text:
#include "qplatformscreen_qpa.h"
#include <QtGui/qapplication.h>
#include <QtGui/private/qapplication_p.h>
#include <QtGui/qdesktopwidget.h>
#include <QtGui/qplatformintegration_qpa.h>
#include <QtGui/qwidget.h>
#include <QtGui/private/qwidget_p.h>

/*!
    Return the given top level widget for a given position.

    Default implementation retrieves a list of all top level widgets and finds the first widget
    which contains point \a pos
*/
QWidget *QPlatformScreen::topLevelAt(const QPoint & pos) const
{
    QWidgetList list = QApplication::topLevelWidgets();
    for (int i = list.size()-1; i >= 0; --i) {
        QWidget *w = list[i];
        //### mask is ignored
        if (w != QApplication::desktop() && w->isVisible() && w->geometry().contains(pos))
            return w;
    }

    return 0;
}

/*!
    Reimplement this function in subclass to return the physical size of the
    screen. This function is used by QFont to convert point sizes to pixel
    sizes.

    The default implementation takes the pixel size of the screen, considers a
    resolution of 100 dots per inch, and returns the calculated physical size.
    A device with a screen that has different resolutions will need to be
    supported by a suitable reimplementation of this function.
*/
QSize QPlatformScreen::physicalSize() const
{
    static const int dpi = 100;
    int width = geometry().width() / dpi * qreal(25.4) ;
    int height = geometry().height() / dpi * qreal(25.4) ;
    return QSize(width,height);
}

Q_GUI_EXPORT extern QWidgetPrivate *qt_widget_private(QWidget *widget);
QPlatformScreen * QPlatformScreen::platformScreenForWidget(const QWidget *widget)
{
    QWidget *window = widget->window();
    QWidgetPrivate *windowPrivate = qt_widget_private(window);
    QTLWExtra * topData = windowPrivate->topData();
    QPlatformIntegration *integration =
            QApplicationPrivate::platformIntegration();
    return integration->screens()[topData->screenIndex];
}

/*!
    \class QPlatformScreen
    \since 4.8
    \internal
    \preliminary
    \ingroup qpa

    \brief The QPlatformScreen class provides an abstraction for visual displays.

    Many window systems has support for retrieving information on the attached displays. To be able
    to query the display QPA uses QPlatformScreen. Qt its self is most dependent on the
    physicalSize() function, since this is the function it uses to calculate the dpi to use when
    converting point sizes to pixels sizes. However, this is unfortunate on some systems, as the
    native system fakes its dpi size.

    QPlatformScreen is also used by the public api QDesktopWidget for information about the desktop.
 */

/*! \fn QRect QPlatformScreen::geometry() const = 0
    Reimplement in subclass to return the pixel geometry of the screen
*/

/*! \fn QRect QPlatformScreen::availableGeometry() const
    Reimplement in subclass to return the pixel geometry of the available space
    This normally is the desktop screen minus the task manager, global menubar etc.
*/

/*! \fn int QPlatformScreen::depth() const = 0
    Reimplement in subclass to return current depth of the screen
*/

/*! \fn QImage::Format QPlatformScreen::format() const = 0
    Reimplement in subclass to return the image format which corresponds to the screen format
*/

redpajama_set_name: RedPajamaGithub


text:
@interface MCFileWriterUtil : NSObject<RCTBridgeModule>

@end


text:
import React from 'react';
import SvgIcon from 'paraviewweb/src/React/Widgets/SvgIconWidget';

import style from 'LightVizStyle/ListDatasets.mcss';

import { listDatasets } from '../../client';
import ThumbnailList from './ThumbnailList';
import lightVizIcon from '../../../svg/LightViz.svg';

import { loadConfiguration } from '../../config';

export default class ListDatasets extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      datasets: [],
    };

    this.refresh = this.refresh.bind(this);
  }

  componentDidMount() {
    this.refresh();
    loadConfiguration();
  }

  refresh() {
    listDatasets((datasets) =>
      this.setState({
        datasets,
      })
    );
  }

  render() {
    return (

          <SvgIcon icon={lightVizIcon} width="25px" height="25px" />

          <ThumbnailList list={this.state.datasets} />

    );
  }
}


text:
title:  "Notes on Module 3"
date:  2016-08-26 11:37:00
category: [python]
tags: [python]
---

Today I went through Module 3. This time the lab exercises were easy, but I had a hard time understanding parallel coordinates.

In particular, looking at this:

```python
data = load_iris()
df = pd.DataFrame(data.data, columns=data.feature_names)

df['target_names'] = [data.target_names[i] for i in data.target]

# Parallel Coordinates Start Here:
plt.figure()
parallel_coordinates(df, 'target_names')
```

Only made me confused. What the heck was going on? Didn't understand... I knew this `df['target_names']` was iterating through something, but I had no clue why or what that was. I had no idea why the second input for `parallel_coordinates` was `'target_names'`, so I didn't know how to make a parallel coordinate thing for the lab exercies.

Searched the [official documentation](http://pandas.pydata.org/pandas-docs/stable/visualization.html#parallel-coordinates) for any clues on why this is done. Apparently they were also using the iris dataset for the example, except now it was:

```python
In [89]: from pandas.tools.plotting import parallel_coordinates

In [90]: data = pd.read_csv('data/iris.data')

In [91]: plt.figure()
Out[91]: <matplotlib.figure.Figure at 0x11fb7fa50>

In [92]: parallel_coordinates(data, 'Name')
Out[92]: <matplotlib.axes._subplots.AxesSubplot at 0x121372590>
```

Well, well...this was...only even more confusing. What the heck was `'Name'` this time?!

Consulted DDG (which of course led me to SO). Found a [somewhat clearer explanation](https://stackoverflow.com/questions/38103738/plotting-parallel-coordinates-in-pandas-python/38104166), which said you should put in the 'class', but still felt somewhat confused. `'Name'`?!

And finally, somehow stumbled upon someone posting the actual csv used [here](https://raw.githubusercontent.com/pydata/pandas/master/pandas/tests/data/iris.csv). Now it made more sense! The class column name, of course!

It also dawned on me I was plotting the wrong thing (the dataframe which I didn't drop features off), no wonder the whole plot was out of whack with scaling issues.

Anyhow. I feel like I understand parallel coordinates a bit more now. After loading the actual iris datasest from `sklearn`, I finally saw why the heck was the edX example so complex. They had to build a dataframe from the whole thing since it wasn't as neat as the csv example above.

Other source I found pretty helpful: [https://eagereyes.org/techniques/parallel-coordinates](https://eagereyes.org/techniques/parallel-coordinates)

In particular, this line was a nice emphasis on what not to do:

>The number of cylinders can only be a whole number, and there aren't more than eight here, so all the lines have to pass through a small number of points. Data like this, and also categorical data, are usually not well suited for parallel coordinates. As long as there is only one or two, it's not a problem, but when the data is largely or completely categorical, parallel coordinates do not show any useful information anymore

(apparently it was written by a senior research scientist at Tableau, nice content marketing there ha!)

#### Additional Notes

`fig.add_subplot(111)` also confused me. Why `111`? Naturally I looked at the official docs, and lo and behold there was also something like `fig.add_subplot(212)`. (╯‵□′)╯︵┻━┻

Really thought they should explain more in the course's notes, or at least link things to the official docs to make searching easier. Anyhow, DDG/SO to the rescue again.

Glad to find I'm [not the only one](https://stackoverflow.com/questions/3584805/in-matplotlib-what-does-the-argument-mean-in-fig-add-subplot111) confused. Very helpful, along with the link in the 3rd answer. The first answer I sort of got and sort of didn't, I mixed it up with the 2nd answer's image which was what initially threw me off (kept wondering why the graphs were the same size, lol). But yeah I also experimented a bit on my iPython console so 'twas all good.

Additionally, [MatPlotLib's docs](http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.scatter) also helped. When I initially saw `c='r'` and `marker='.'` I did not know what those were for. Of course, it's pretty obvious now, but yeah. Glad I got that cleared up.

#### TODO:
Also find time to do [Numpy practice questions](http://www.labri.fr/perso/nrougier/teaching/numpy.100/), because the really popular Python for DataScience Udemy course I bought was not helpful. In fact, it was super boring and was also a pain to go through...felt like a frickin' chore and made me question whether I could really learn the stuff.

The problem was, of course, it was all talk and no useful exercise to work on. Pretty much forgot everything about numpy by now, but can probably better learn it through doing exercises.

Speaking of which, I should get on doing CodeChef problems too, because I haven't touched basic Python after I finished the Codecademy course, and I can barely remember how to do basic things.

Alas, so many things (including MBA classes and the clubs that will be starting soon). So little time. Just hope I can keep this learning momentum going.


text:
import uuid

from keystoneclient.contrib.ec2 import utils as ec2_utils
from six.moves import http_client

from keystone.common import utils
from keystone.contrib.ec2 import controllers
from keystone import exception
from keystone.tests import unit
from keystone.tests.unit import default_fixtures
from keystone.tests.unit.ksfixtures import database
from keystone.tests.unit import rest

CRED_TYPE_EC2 = controllers.CRED_TYPE_EC2

class V2CredentialEc2TestCase(rest.RestfulTestCase):
    def setUp(self):
        super(V2CredentialEc2TestCase, self).setUp()
        self.user_id = self.user_foo['id']
        self.project_id = self.tenant_bar['id']

    def _get_token_id(self, r):
        return r.result['access']['token']['id']

    def _get_ec2_cred(self):
        uri = self._get_ec2_cred_uri()
        r = self.public_request(method='POST', token=self.get_scoped_token(),
                                path=uri, body={'tenant_id': self.project_id})
        return r.result['credential']

    def _get_ec2_cred_uri(self):
        return '/v2.0/users/%s/credentials/OS-EC2' % self.user_id

    def test_ec2_cannot_get_non_ec2_credential(self):
        access_key = uuid.uuid4().hex
        cred_id = utils.hash_access_key(access_key)
        non_ec2_cred = unit.new_credential_ref(
            user_id=self.user_id,
            project_id=self.project_id)
        non_ec2_cred['id'] = cred_id
        self.credential_api.create_credential(cred_id, non_ec2_cred)

        # if access_key is not found, ec2 controller raises Unauthorized
        # exception
        path = '/'.join([self._get_ec2_cred_uri(), access_key])
        self.public_request(method='GET', token=self.get_scoped_token(),
                            path=path,
                            expected_status=http_client.UNAUTHORIZED)

    def assertValidErrorResponse(self, r):
        # FIXME(wwwjfy): it's copied from test_v3.py. The logic of this method
        # in test_v2.py and test_v3.py (both are inherited from rest.py) has no
        # difference, so they should be refactored into one place. Also, the
        # function signatures in both files don't match the one in the parent
        # class in rest.py.
        resp = r.result
        self.assertIsNotNone(resp.get('error'))
        self.assertIsNotNone(resp['error'].get('code'))
        self.assertIsNotNone(resp['error'].get('title'))
        self.assertIsNotNone(resp['error'].get('message'))
        self.assertEqual(int(resp['error']['code']), r.status_code)

    def test_ec2_list_credentials(self):
        self._get_ec2_cred()
        uri = self._get_ec2_cred_uri()
        r = self.public_request(method='GET', token=self.get_scoped_token(),
                                path=uri)
        cred_list = r.result['credentials']
        self.assertEqual(1, len(cred_list))

        # non-EC2 credentials won't be fetched
        non_ec2_cred = unit.new_credential_ref(
            user_id=self.user_id,
            project_id=self.project_id)
        non_ec2_cred['type'] = uuid.uuid4().hex
        self.credential_api.create_credential(non_ec2_cred['id'],
                                              non_ec2_cred)
        r = self.public_request(method='GET', token=self.get_scoped_token(),
                                path=uri)
        cred_list_2 = r.result['credentials']
        # still one element because non-EC2 credentials are not returned.
        self.assertEqual(1, len(cred_list_2))
        self.assertEqual(cred_list[0], cred_list_2[0])

class V2CredentialEc2Controller(unit.TestCase):
    def setUp(self):
        super(V2CredentialEc2Controller, self).setUp()
        self.useFixture(database.Database())
        self.load_backends()
        self.load_fixtures(default_fixtures)
        self.user_id = self.user_foo['id']
        self.project_id = self.tenant_bar['id']
        self.controller = controllers.Ec2Controller()
        self.blob, tmp_ref = unit.new_ec2_credential(
            user_id=self.user_id,
            project_id=self.project_id)

        self.creds_ref = (controllers.Ec2Controller
                          ._convert_v3_to_ec2_credential(tmp_ref))

    def test_signature_validate_no_host_port(self):
        """Test signature validation with the access/secret provided."""
        access = self.blob['access']
        secret = self.blob['secret']
        signer = ec2_utils.Ec2Signer(secret)
        params = {'SignatureMethod': 'HmacSHA256',
                  'SignatureVersion': '2',
                  'AWSAccessKeyId': access}
        request = {'host': 'foo',
                   'verb': 'GET',
                   'path': '/bar',
                   'params': params}
        signature = signer.generate(request)

        sig_ref = {'access': access,
                   'signature': signature,
                   'host': 'foo',
                   'verb': 'GET',
                   'path': '/bar',
                   'params': params}

        # Now validate the signature based on the dummy request
        self.assertTrue(self.controller.check_signature(self.creds_ref,
                                                        sig_ref))

    def test_signature_validate_with_host_port(self):
        """Test signature validation when host is bound with port.

        Host is bound with a port, generally, the port here is not the
        standard port for the protocol, like '80' for HTTP and port 443
        for HTTPS, the port is not omitted by the client library.
        """
        access = self.blob['access']
        secret = self.blob['secret']
        signer = ec2_utils.Ec2Signer(secret)
        params = {'SignatureMethod': 'HmacSHA256',
                  'SignatureVersion': '2',
                  'AWSAccessKeyId': access}
        request = {'host': 'foo:8181',
                   'verb': 'GET',
                   'path': '/bar',
                   'params': params}
        signature = signer.generate(request)

        sig_ref = {'access': access,
                   'signature': signature,
                   'host': 'foo:8181',
                   'verb': 'GET',
                   'path': '/bar',
                   'params': params}

        # Now validate the signature based on the dummy request
        self.assertTrue(self.controller.check_signature(self.creds_ref,
                                                        sig_ref))

    def test_signature_validate_with_missed_host_port(self):
        """Test signature validation when host is bound with well-known port.

        Host is bound with a port, but the port is well-know port like '80'
        for HTTP and port 443 for HTTPS, sometimes, client library omit
        the port but then make the request with the port.
        see (How to create the string to sign): 'http://docs.aws.amazon.com/
        general/latest/gr/signature-version-2.html'.

        Since "credentials['host']" is not set by client library but is
        taken from "req.host", so caused the differences.
        """
        access = self.blob['access']
        secret = self.blob['secret']
        signer = ec2_utils.Ec2Signer(secret)
        params = {'SignatureMethod': 'HmacSHA256',
                  'SignatureVersion': '2',
                  'AWSAccessKeyId': access}
        # Omit the port to generate the signature.
        cnt_req = {'host': 'foo',
                   'verb': 'GET',
                   'path': '/bar',
                   'params': params}
        signature = signer.generate(cnt_req)

        sig_ref = {'access': access,
                   'signature': signature,
                   'host': 'foo:8080',
                   'verb': 'GET',
                   'path': '/bar',
                   'params': params}

        # Now validate the signature based on the dummy request
        # Check the signature again after omitting the port.
        self.assertTrue(self.controller.check_signature(self.creds_ref,
                                                        sig_ref))

    def test_signature_validate_no_signature(self):
        """Signature is not presented in signature reference data."""
        access = self.blob['access']
        params = {'SignatureMethod': 'HmacSHA256',
                  'SignatureVersion': '2',
                  'AWSAccessKeyId': access}

        sig_ref = {'access': access,
                   'signature': None,
                   'host': 'foo:8080',
                   'verb': 'GET',
                   'path': '/bar',
                   'params': params}

        # Now validate the signature based on the dummy request
        self.assertRaises(exception.Unauthorized,
                          self.controller.check_signature,
                          self.creds_ref, sig_ref)

    def test_signature_validate_invalid_signature(self):
        """Signature is not signed on the correct data."""
        access = self.blob['access']
        secret = self.blob['secret']
        signer = ec2_utils.Ec2Signer(secret)
        params = {'SignatureMethod': 'HmacSHA256',
                  'SignatureVersion': '2',
                  'AWSAccessKeyId': access}
        request = {'host': 'bar',
                   'verb': 'GET',
                   'path': '/bar',
                   'params': params}
        signature = signer.generate(request)

        sig_ref = {'access': access,
                   'signature': signature,
                   'host': 'foo:8080',
                   'verb': 'GET',
                   'path': '/bar',
                   'params': params}

        # Now validate the signature based on the dummy request
        self.assertRaises(exception.Unauthorized,
                          self.controller.check_signature,
                          self.creds_ref, sig_ref)

    def test_check_non_admin_user(self):
        """Checking if user is admin causes uncaught error.

        When checking if a user is an admin, keystone.exception.Unauthorized
        is raised but not caught if the user is not an admin.
        """
        # make a non-admin user
        context = {'is_admin': False, 'token_id': uuid.uuid4().hex}

        # check if user is admin
        # no exceptions should be raised
        self.controller._is_admin(context)


text:
layout: post
title: Inverse Transform Sampling Via Generative Adversarial Networks
author: "Sunil Srinivasa"
---
<script src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML" type="text/javascript"></script>
<style>
.center-image
{
    margin: 0 auto;
    display: block;
}
</style>

## Using deep neural networks to sample arbitrary probability distributions

**What is Inverse Transform Sampling?**

[Inverse transform sampling](https://en.wikipedia.org/wiki/Inverse_transform_sampling){:target="_blank"} (ITS) is a generic technique used for generating independent sample numbers at random given any underlying probability distribution. It is akin to other random number generation techniques such as [rejection sampling](https://en.wikipedia.org/wiki/Rejection_sampling){:target="_blank"}, [Ziggurat algorithm](https://en.wikipedia.org/wiki/Ziggurat_algorithm){:target="_blank"} and [Box-Muller transform](https://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform){:target="_blank"}. It operates as follows:
suppose we wish to generate samples from a continuous probability distribution with cumulative density function (CDF) $$F_X(x)$$. ITS takes a uniform sample of a random variable $$U$$ that is disributed between $$[0,1]$$, interprets it as a probability, and generates sample $$x$$ for which $$F_X(x) = u$$, i.e., $$x = F^{-1}_X(u)$$.

As an illustration, consider the case when we wish to generate samples from an exponential distribution, i.e., $$F_X(x)=(1-e^{-\lambda x})$$ for $$x\geq 0$$ and $$0$$ otherwise. Using ITS, we obtain $$F_X(x) = u$$, or equivalently, $$x=-\frac{1}{\lambda}\ln(1-u)$$.

The mapping between $$u$$ and $$x$$ is depicted when we run this simple python script.
```
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

from pylab import rcParams
rcParams.update({'font.size': 14})

l = 1 # lambda
u_range = np.arange(0,1,0.001)
x = [-1/l*np.log(1-u) for u in u_range]

plt.plot(u_range,x,linewidth=3)
plt.grid()
plt.xlabel('u');plt.ylabel('x')
plt.title('Exponential distribution with mean $1$')

# Sample value of u
u = 0.75
plt.plot([u,u],[0,-1/l*np.log(1-u)],'r--',linewidth=2)
plt.plot([0,u],[-1/l*np.log(1-u),-1/l*np.log(1-u)],'r--',linewidth=2)
plt.plot(u,-1/l*np.log(1-u),'rs')
```

![png]({{site.baseurl}}/assets/images/2017-04-07-GANs/ITS.png){: .center-image}

In the above depiction, each of the randomly generated numbers from a uniform distribution $$U[0,1]$$ is mapped to a sample $$x$$ that follows an exponential distribution with unit mean. For instance, when $$\lambda=1$$, $$u=0.75$$ is mapped to $$x\approx1.38$$ (marked by the red dashed lines).

Conceptually, the ITS method makes sense since the CDF of any random variable lies between $$0$$ and $$1$$, and samples $$x$$ are generated according to their contribution towards the CDF. This approach also extends to discrete distributions, if we simply generate the largest sample $$x$$ from the domain of the distribution such that $$F_X(x)\leq u$$.

The above method will, however, not work in several cases such as:
- Unknown distribution (when the distribution of the random variable is not known in tractable form)
- Diverging or analytically intractable CDF, e.g. [Hyperbolic distribution](https://en.wikipedia.org/wiki/Hyperbolic_distribution){:target="_blank"}
- Non-invertible or analytically intractable CDF, e.g., [Gaussian distribution](https://en.wikipedia.org/wiki/Normal_distribution){:target="_blank"}, [Cauchy distribution](https://en.wikipedia.org/wiki/Cauchy_distribution){:target="_blank"}
- Mixture of densities, e.g., [Mixture Distribution](https://en.wikipedia.org/wiki/Mixture_distribution){:target="_blank"}
- Functions or transformations of random variables, e.g. for generating square of a Gaussian distribution
- Multi-dimensional random variables, e.g., [Multivariate Gaussian distribution](https://en.wikipedia.org/wiki/Multivariate_normal_distribution){:target="_blank"}

Moreover, in order to obtain a large number of samples, one needs to perform the CDF inversion multiple times, which is expensive. One possible way to reduce the number of inversions to only a few while obtaining a large number of samples is the application of the so-called the [*Stochastic Collocation Monte Carlo* (SCMC) sampler](https://papers.ssrn.com/sol3/papers.cfm?abstract_id=2529691){:target="_blank"}. However, SCMS methods are computationally expensive as they use the squared Bessel process.

> An immediate follow-up question becomes "Are there other methods using which we can generate independent random numbers with a lower computation overhead? Say hello to GANs.

**What are GANs?**

Generative Adversarial Networks (GANs) are examples of generative models in the machine learning literature. They are used in the context of unsupervised or semi-supervised learning. Using a few training data samples, GANs learn to represent an estimate of the distribution. For a detailed introduction to GANs, please refer to the seminal paper by Goodfellow et al. [[1]](https://arxiv.org/abs/1406.2661){:target="_blank"} or the same author's excellent summary on GANs at NIPS 2016 [[2]](https://arxiv.org/abs/1701.00160){:target="_blank"}.

GANs essentially comprise two deep neural networks, the **Discriminator** and the **Generator**. The discriminator function $$D$$ takes in an input sample $$x$$ and determines the probability $$D(x)$$, of $$x$$ having been drawn from the original data distribution. The generator function $$G$$ takes in a noisy sample $$z$$, and generates a sample $$G(z)$$, that is intended to fool the discriminator into believing that the sample is indeed from the original data distribution. While the generator attempts to generate samples that are probabilistically close to the training data, the discriminator attempts to deem the generated samples as fake, i.e., not having been drawn from the true distribution. A conceptual illustration of a GAN generating a MNIST digit sample is provided below (Picture credit [[3]](https://www.slideshare.net/ckmarkohchang/generative-adversarial-networks){:target="_blank"}).

![GANs concept]({{site.baseurl}}/assets/images/2017-04-07-GANs/GAN_concept.png){: .center-image}

***The objective function***

Together, the discriminator and the generator compete against each other in a *zero-sum game* (wherein one player's gain is the other's loss). Given a set of training data samples $$x$$ and noise samples $$z$$, the gain (loss) function for the discriminator (generator) respectively, is given by

$$
\begin{aligned}
  J(D,G)=\mathbb{E}_{x\sim data}\log_e D(x) + \mathbb{E}_{z\sim noise}\log_e \left(1-D(G(z))\right).
\end{aligned}
$$

Given parameters $$\theta_D$$ and $$\theta_G$$ for the discriminator and generator respectively, GANs play the minimax game:

$$
\begin{aligned}
  \min_{\theta_G}\max_{\theta_D}J(\theta_D,\theta_G).
\end{aligned}
$$

One immediate benefit from using GANs over ITS is that GANs can generate data with only some data samples and without knowing anything about the underlying distribution. Thus, they work well even with unweildy, functions of random variables or multidimensional distributions. At the same time, however, training GANs requires finding the *Nash equilibrium* (we will define this shortly) of a game, which maybe more time-consuming than inverting a CDF.

The framework for GANs (picture courtesy [[2]](https://arxiv.org/abs/1701.00160){:target="_blank"}) is depicted below. The discriminator $$D$$ has to maximize $$J(D,G)$$ with respect to parameters $$\theta_D$$. Since the logarithm is a monotonic function, $$D$$ tries to make $$D(x)$$ close to $$1$$ and $$D(G(z))$$ close to $$0$$. On the other hand, the generator $$G$$ has to minimize $$J(D,G)$$ with respect to parameters $$\theta_G$$; so $$G$$ attempts to make $$D(G(z))$$ close to $$1$$. In other words, in this mini-max game, the discriminator wants to deem the generated samples as fake, while the generator wants to fool the discriminator into believing that the generated samples are real. In the example below involving human faces, the human face on the left is a real image, while the discriminator is led into believing that the image on the right is real as well.

![Adversarial Networks Framework.]({{site.baseurl}}/assets/images/2017-04-07-GANs/GAN_model.png){: .center-image}

By competing or co-operating against each other, the system attains a *Nash equilibrium* corresponding to the generator sample distribution converging to the data distribution. The Nash equilibrium is defined as the solution concept of a game between two players wherein each player has chosen a strategy and neither player can benefit by changing strategies while the other players keep theirs unchanged.

Let us do some math now concerning the Nash equilibrium. Recall the loss function for GAN is given by

$$
\begin{aligned}
 J(D,G) = \mathbb{E}_{x\sim data}\log_e D(x) + \mathbb{E}_{z\sim noise}\log_e \left(1-D(G(z))\right).
\end{aligned}
$$

When $$G$$ is fixed (which happens when a Nash equilibrium is attained; and then we call $$G$$'s output as the *model*), we obtain

$$
\begin{aligned}
 J(D) = \mathbb{E}_{x\sim data}\log_e D(x) + \mathbb{E}_{x\sim model}\log_e \left(1-D(x)\right).
\end{aligned}
$$

Assuming that both $$p_{model}$$ and $$p_{data}$$ have the same sample space or basis, we can write

$$
\begin{aligned}
 J(D) = \int_x\left[p_{data}(x)\log_e D(x) + p_{model}(x)\log_e \left(1-D(x)\right)\right] \text{dx}.
\end{aligned}
$$

This is maximized when $$\frac{\partial J}{\partial D} = 0$$, i.e.,
$$
\begin{aligned}
  \frac{p_{data}(x)}{D(x)} = \frac{p_{model}(x)}{1-D(x)}.
\end{aligned}
$$
In other words, for fixed $$G$$, the optimal discriminator is given by

$$
\begin{aligned}
  D(x) = \frac{p_{data}(x)}{p_{data}(x)+p_{model}(x)}.
\end{aligned}
$$

At convergence, $$G$$ fixates to the model and  $$p_{data}(x)\sim p_{model}(x)$$. When this happens, the discriminator's output is always equal to $$\frac{1}{2}$$, i.e., $$D(x)=\frac{1}{2}\forall x$$; with this, $$J(D,G)$$ reaches a global minima of $$-\log_e(4)\approx -1.386$$. This number is useful while checking if the training for a GAN has converged.

***Training***

In the following, we use GANs to generate samples for certain toy distributions. For this (rather simple) use case, both the discriminator and generator networks were taken to be multi layer perceptrons (MLPs). A general architecture of the GAN network based on MLPs looks like the figure below (image credit [[4]](http://people.ee.duke.edu/~lcarin/Yunchen9.30.2016.pdf){:target="_blank"}.

![Adversarial Network.]({{site.baseurl}}/assets/images/2017-04-07-GANs/GAN_network.PNG){: .center-image}

There are a couple of tips and tricks we need to keep in mind while designing GANs:

- It is very important to balance the discriminator and generator; and usually, the discriminator ``wins''. In other words, it is important to ensure that the discriminator is bigger and deeper than the generator, as otherwise it will not have sufficient capacity to learn to be able to distinguish accurately between generated and real samples. For our experiments, we used a generator with a MLP two hidden layers with $$32$$ nodes each, and the ReLu non-linearity between the layers, while the discriminator was a three-layered MLP with $$32$$ nodes each, and the ReLu non-linearity between layers. The last layer of the discriminator is taken to be a sigmoid, since the output can then be directly interpreted as a probability.

- It is sometimes beneficial to train $$D$$ for a longer duration than $$G$$.The original GAN algorithm from [[1]](https://arxiv.org/abs/1406.2661){:target="_blank"} is pasted below. Notice that the algorithm interleaves $$k$$ steps of discriminator training for every generator training step. $$k$$ is a hyper-parameter; for our basic experiments here, we used $$k=1$$ like in the original paper.

![GAN algorithm]({{site.baseurl}}/assets/images/2017-04-07-GANs/algorithm.PNG){: .center-image}

***Preliminary Results***

##### Noise distribution
For all our simulations, we take the noise distribution $$p_z(Z)$$ to be a Gaussian with zero mean and unit standard variance, i.e., $$z\sim\mathcal{N}(0,1)$$. The noise histogram is shown below.

![noise]({{site.baseurl}}/assets/images/2017-04-07-GANs/noise.PNG){: .center-image}

##### Case 1: Generating a Normal distribution with a different mean and variance
First, we attempt to generate samples for another Gaussian distribution with a mean of $$5$$ and a variance of $$2$$. We train the GAN for $$5000$$ iterations each for $$D$$ and $$G$$ (or a total of $$10000$$ steps); however, the loss is seen to converge to its expected stationary value of $$\approx -1.38$$ around $$1000$$ steps itself.

![1d Gaussian]({{site.baseurl}}/assets/images/2017-04-07-GANs/1dGaussian.PNG){: .center-image}

##### Case 2: Generating a bi-modal Normal distribution
Second, we attempt to generate samples for a bi-modal Gaussian distribution. The bi-modal distribution is obtained as a linear combination of two Gaussian distributions, $$\mathcal{N}(-3,2)$$ and $$\mathcal{N}(3,1)$$.

![1d Gaussian]({{site.baseurl}}/assets/images/2017-04-07-GANs/1dBimodalGaussian.PNG){: .center-image}

We see that the generated samples' histogram matches the true data distribution reasonably well. We did not tweak the network parameters here further to potentially improve performance.

***Code***

This [Jupyter notebook]({{site.baseurl}}/assets/codes/2017-04-07-Understanding GAN.ipynb){:target="_blank"} using TensorFlow helped generate all the results shown here.

***Closing Notes***

In this blog, we have provided an introduction to how Generative Adversarial Networks can overcome some of the shortcomings of Inverse Transform Sampling methods. We have also illustrated via a couple of fundamental examples that GANs can emulate Gaussian distribution mixtures very effectively with basic neural network architectures. The ideas presented here can be extended (without much deliberation) to generate multi-dimensional distributions that represent more tangible data such as images. GANs of late are able to generate high compleling high-resolution examples using convolutional neural networks from diverse image classes. The GAN we introduced in this blog is the barebones or vanilla GAN. This model has been improved upon by several variants of GAN such as Deep Convolutional GANs, Conditional GANs, Autoencoding GANs and Infomation Maximizing GANs [[4]](http://people.ee.duke.edu/~lcarin/Yunchen9.30.2016.pdf){:target="_blank"}

***References***

[1] I. Goodfellow et. al, [Generative Adversarial Networks](https://arxiv.org/abs/1406.2661){:target="_blank"}

[2] I. Goodfellow, [NIPS 2016 Tutorial: Generative Adversarial Networks](https://arxiv.org/abs/1701.00160){:target="_blank"}

[3] M. Chang, [GAN slides](https://www.slideshare.net/ckmarkohchang/generative-adversarial-networks){:target="_blank"}

[4] Y. Pu, [GAN and its variants](http://people.ee.duke.edu/~lcarin/Yunchen9.30.2016.pdf){:target="_blank"}


text:
set -o errexit
set -o nounset
set -o pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
export PATH=${ROOT}/contrib/hack:${PATH}

# Clean up old containers if still around
docker rm -f etcd-svc-cat apiserver || true


text:
using System.Collections.Generic;
using MathNet.Numerics.LinearAlgebra;
using NUnit.Framework;

namespace MathNet.Numerics.UnitTests.LinearAlgebraTests.Complex
{
#if NOSYSNUMERICS
    using Complex = Numerics.Complex;
#else
    using Complex = System.Numerics.Complex;
#endif

    /// <summary>
    /// Base class for matrix tests.
    /// </summary>
    public abstract class MatrixLoader
    {
        /// <summary>
        /// Gets or sets test matrices values to use.
        /// </summary>
        protected Dictionary<string, Complex[,]> TestData2D { get; set; }

        /// <summary>
        /// Gets or sets test matrices instances to use.
        /// </summary>
        protected Dictionary<string, Matrix<Complex>> TestMatrices { get; set; }

        /// <summary>
        /// Creates a matrix for the given number of rows and columns.
        /// </summary>
        /// <param name="rows">The number of rows.</param>
        /// <param name="columns">The number of columns.</param>
        /// <returns>A matrix with the given dimensions.</returns>
        protected abstract Matrix<Complex> CreateMatrix(int rows, int columns);

        /// <summary>
        /// Creates a matrix from a 2D array.
        /// </summary>
        /// <param name="data">The 2D array to create this matrix from.</param>
        /// <returns>A matrix with the given values.</returns>
        protected abstract Matrix<Complex> CreateMatrix(Complex[,] data);

        /// <summary>
        /// Setup test matrices.
        /// </summary>
        [SetUp]
        public virtual void SetupMatrices()
        {
            TestData2D = new Dictionary<string, Complex[,]>
            {
                { "Singular3x3", new[,] { { new Complex(1.0, 1), new Complex(1.0, 1), new Complex(2.0, 1) }, { new Complex(1.0, 1), new Complex(1.0, 1), new Complex(2.0, 1) }, { new Complex(1.0, 1), new Complex(1.0, 1), new Complex(2.0, 1) } } },
                { "Square3x3", new[,] { { new Complex(-1.1, 1), new Complex(-2.2, 1), new Complex(-3.3, 1) }, { Complex.Zero, new Complex(1.1, 1), new Complex(2.2, 1) }, { new Complex(-4.4, 1), new Complex(5.5, 1), new Complex(6.6, 1) } } },
                { "Square4x4", new[,] { { new Complex(-1.1, 1), new Complex(-2.2, 1), new Complex(-3.3, 1), new Complex(-4.4, 1) }, { Complex.Zero, new Complex(1.1, 1), new Complex(2.2, 1), new Complex(3.3, 1) }, { new Complex(1.0, 1), new Complex(2.1, 1), new Complex(6.2, 1), new Complex(4.3, 1) }, { new Complex(-4.4, 1), new Complex(5.5, 1), new Complex(6.6, 1), new Complex(-7.7, 1) } } },
                { "Singular4x4", new[,] { { new Complex(-1.1, 1), new Complex(-2.2, 1), new Complex(-3.3, 1), new Complex(-4.4, 1) }, { new Complex(-1.1, 1), new Complex(-2.2, 1), new Complex(-3.3, 1), new Complex(-4.4, 1) }, { new Complex(-1.1, 1), new Complex(-2.2, 1), new Complex(-3.3, 1), new Complex(-4.4, 1) }, { new Complex(-1.1, 1), new Complex(-2.2, 1), new Complex(-3.3, 1), new Complex(-4.4, 1) } } },
                { "Tall3x2", new[,] { { new Complex(-1.1, 1), new Complex(-2.2, 1) }, { Complex.Zero, new Complex(1.1, 1) }, { new Complex(-4.4, 1), new Complex(5.5, 1) } } },
                { "Wide2x3", new[,] { { new Complex(-1.1, 1), new Complex(-2.2, 1), new Complex(-3.3, 1) }, { Complex.Zero, new Complex(1.1, 1), new Complex(2.2, 1) } } },
                { "Symmetric3x3", new[,] { { Complex.One, 2.0, 3.0 }, { 2.0, 2.0, 0.0 }, { 3.0, 0.0, 3.0 } } }
            };

            TestMatrices = new Dictionary<string, Matrix<Complex>>();
            foreach (var name in TestData2D.Keys)
            {
                TestMatrices.Add(name, CreateMatrix(TestData2D[name]));
            }
        }
    }
}


text:
'use strict';

module.exports = function (id, name, filename, parent) {
    this.id = id;
    this.name = name;
    this.filename = filename;
    this.parent = parent;
};


text:
Add this line to your application's Gemfile:

    gem 'youcandoit'

And then execute:

    $ bundle

Or install it yourself:

    $ gem install youcandoit


text:
/**
 * Specification of the @em equality_comparable concept.
 */

#ifndef NSTL_CONCEPT_EQUALITY_COMPARABLE_H
#define NSTL_CONCEPT_EQUALITY_COMPARABLE_H

#include <nstl/concept/base.h>
#include <nstl/internal/type.h>

/**
 * A type is equality comparable if it has both the equality and inequality
 * operators.
 */
#define NSTL_CONCEPT_EQUALITY_COMPARABLE(T)                                    \
NSTL_CONCEPT(                                                                  \
    NSTL_CONCEPT_REQUIREMENT(                                                  \
        NSTL_ISSET(T, eq), "missing equality operator"                         \
    )                                                                          \
    NSTL_CONCEPT_REQUIREMENT(                                                  \
        NSTL_ISSET(T, neq), "missing inequality operator"                      \
    )                                                                          \
)                                                                              \
/**/

#endif /* !NSTL_CONCEPT_EQUALITY_COMPARABLE_H */


text:
package com.assesortron.walkthroughnavigator;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.Space;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;
import android.widget.ViewSwitcher;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by otf on 6/13/15.
 */
public class Navigator extends Fragment implements DisplayFragment.ParentListener {

    public static final int NUM_PREVIEW_FRAGS = 3;

    public static final int UP = 1;
    public static final int DOWN = 2;
    public static final int LEFT = 3;
    public static final int RIGHT = 4;

    private TextView numFields;
    private List<DisplayObject> objs;
    private DisplayFragment.ParentListener parentListener;
    private DisplayFragment<DisplayObject> previewFragment;
    private DisplayFragment<DisplayObject> displayFragment;
    private List<DisplayFragment<DisplayObject>> previewFragments = new ArrayList<>();
    private ViewFlipper previewFragmentSpace;
    private Spinner axisOne, axisTwo, axisThree;
    private RadioButton completeFilter, toDoFilter;
    private Button allFilter;
    private ViewSwitcher viewSwitcher;
    private AxisMatrix axisMatrix;

    private int axis1Pos, axis2Pos, axis3Pos;

    private GestureDetector touchListener;

    private Comparator<DisplayObject> axisOneComparator = new Comparator<DisplayObject>() {
        @Override
        public int compare(DisplayObject lhs, DisplayObject rhs) {
            return lhs.getAxis1Value().compareTo(rhs.getAxis1Value());
        }
    };
    private Comparator<DisplayObject> axisTwoComparator = new Comparator<DisplayObject>() {
        @Override
        public int compare(DisplayObject lhs, DisplayObject rhs) {
            return lhs.getAxis2Value().compareTo(rhs.getAxis2Value());
        }
    };
    private Comparator<DisplayObject> axisThreeComparator = new Comparator<DisplayObject>() {
        @Override
        public int compare(DisplayObject lhs, DisplayObject rhs) {
            return lhs.getAxis3Value().compareTo(rhs.getAxis3Value());
        }
    };

    public Navigator () {
        Log.i("Navigator", "constructor");
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i("Navigator", "OnCreate");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        Log.i("Navigator", "OnCreateView");
        return inflater.inflate(R.layout.fragment_navigator, container, false);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        Log.i("Navigator", "OnAttach");
        try {
            //TODO
            //call back for parent activity to get the current values of all of the matrix objects
        }
        catch (ClassCastException ex) {
            throw new ClassCastException(activity.toString() + " must" +
                    "implement ParentListener");
        }
    }

    @Override
    public void onActivityCreated(Bundle savedInstances) {
        super.onActivityCreated(savedInstances);
        Log.i("Navigator", "OnActivityCreated");
        if (getView() != null) {
            setVariables();
            setListeners();
            if (axisMatrix != null && !axisMatrix.getFirst().isEmpty()) {
                setFields();
            }
        }
    }

    public void setPreviewFragments() throws IllegalAccessException, java.lang.InstantiationException {
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        if (previewFragments == null || previewFragments.isEmpty()) {
            for (int i = 0; i < NUM_PREVIEW_FRAGS; i++) {
                DisplayFragment<DisplayObject> df = previewFragment.newInstance();
                if(!axisMatrix.isEmpty()) {
                    df.setObjects(axisMatrix.getFirst(), this);
                }
                ft.add(df, previewTag(i));
            }
            ft.commit();
//            for (int i = 0; i < NUM_PREVIEW_FRAGS; i++) {
//                previewFragments.add((DisplayFragment<DisplayObject>) getFragmentManager().findFragmentByTag(previewTag(i)));
//            }
        }
    }

    private String previewTag(int i) {
        return "preview" + i;
    }

//        if (getView() != null && getView().findViewById(R.id.navigator_preview_fragment) != null) {
//            getFragmentManager().beginTransaction().add(R.id.navigator_preview_fragment, previewFragments.get(0));
//        }
//
//    }

//    public void setDisplayFragments() throws IllegalAccessException, java.lang.InstantiationException {
//        FragmentTransaction ft = getFragmentManager().beginTransaction();
//        if (displayFragments == null || displayFragments.isEmpty()) {
//            for (int i = 0; i < NUM_DISPLAY_FRAGS; i++) {
//                DisplayFragment<DisplayObject> df = (displayFragment.newInstance());
//                df.setObjects(axisMatrix.getFirst(), this);
//                ft.add(df, "display" +i);
//            }
//            ft.commit();
//            for (int i = 0; i < NUM_DISPLAY_FRAGS; i++) {{
//                displayFragments.add((DisplayFragment<DisplayObject>)getFragmentManager().findFragmentByTag("display" + i));
//            }}
//        }
//
//
//        if (getView() != null && getView().findViewById(R.id.navigator_work_fragment) != null) {
//            getFragmentManager().beginTransaction().add(R.id.navigator_work_fragment, displayFragments.get(0));
//        }
//    }

    public void setUp(List<DisplayObject> obj,
                      DisplayFragment<DisplayObject> displayFragment) {
        this.previewFragment = new PreviewFragment();
        this.displayFragment = displayFragment;
        objs = obj;
        axisMatrix = new AxisMatrix(obj);
        Log.i("Navigator", "SetUp");

        if(getView() != null) {
            setVariables();
            setListeners();
            setFields();
        }
    }

    private void setVariables() {
        Log.i("Navigator", "setVariables");
        previewFragmentSpace = (ViewFlipper) getView().findViewById(R.id.navigator_preview_fragment);
        numFields = (TextView) getView().findViewById(R.id.navigator_num_items);
        //workingFragmentSpace = (ViewFlipper) getView().findViewById(R.id.navigator_work_fragment);

        axisOne = (Spinner) getView().findViewById(R.id.navigator_axis_one);
        axisTwo = (Spinner) getView().findViewById(R.id.navigator_axis_two);
        axisThree = (Spinner) getView().findViewById(R.id.navigator_axis_three);

        allFilter = (Button) getView().findViewById(R.id.navigator_all);
        completeFilter = (RadioButton) getView().findViewById(R.id.navigator_complete);
        toDoFilter = (RadioButton) getView().findViewById(R.id.navigator_todo);

        viewSwitcher = (ViewSwitcher)getView().findViewById(R.id.navigator_view_switcher);
    }

    private void setFields() {
        Log.i("Navigator", "setFields");

        numFields.setText(axisMatrix.getSize() + "");

        ArrayAdapter<Comparable> a1 = new ArrayAdapter(getActivity(),
                android.R.layout.simple_spinner_dropdown_item, axisMatrix.getAxisOne());
        ArrayAdapter<Comparable> a2 = new ArrayAdapter<>(getActivity(),
                android.R.layout.simple_spinner_dropdown_item, axisMatrix.getAxisTwo());
        ArrayAdapter<Comparable> a3 = new ArrayAdapter<>(getActivity(),
                android.R.layout.simple_spinner_dropdown_item, axisMatrix.getAxisThree());

        a1.insert(objs.get(0).axis1Name(), 0);
        a2.insert(objs.get(0).axis2Name(), 0);
        a3.insert(objs.get(0).axis3Name(), 0);

        AdapterView.OnItemSelectedListener a1Lis = axisOne.getOnItemSelectedListener();
        AdapterView.OnItemSelectedListener a2Lis = axisTwo.getOnItemSelectedListener();
        AdapterView.OnItemSelectedListener a3List = axisThree.getOnItemSelectedListener();

        axisOne.setOnItemSelectedListener(null);
        axisTwo.setOnItemSelectedListener(null);
        axisThree.setOnItemSelectedListener(null);

        axisOne.setAdapter(a1);
        axisTwo.setAdapter(a2);
        axisThree.setAdapter(a3);

        axisOne.setOnItemSelectedListener(a1Lis);
        axisTwo.setOnItemSelectedListener(a2Lis);
        axisThree.setOnItemSelectedListener(a3List);

//        previewFragment.setObjects(axisMatrix.getFirst(), this);
//        FragmentTransaction ft = getFragmentManager().beginTransaction();
//        ft.add(previewFragment, "first");
//        ft.commit();

        try {
            if (previewFragments == null || previewFragments.isEmpty()) {
                setPreviewFragments();
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (java.lang.InstantiationException e) {
            e.printStackTrace();
        }

    }

    private void setListeners() {
        allFilter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                completeFilter.setSelected(false);
                toDoFilter.setSelected(false);
                filter(objs);
                setSelections();
            }
        });
        completeFilter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                allFilter.setSelected(false);
                toDoFilter.setSelected(false);
                List<DisplayObject> completeObjs = new ArrayList<DisplayObject>();
                for (DisplayObject d : objs) {
                    if (d.isComplete()) {
                        completeObjs.add(d);
                    }
                }
                Log.i("Complete", "filtered " + completeObjs.size() + " out of " +objs.size());
                filter(completeObjs);
                setSelections();
            }
        });
        toDoFilter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                allFilter.setSelected(false);
                completeFilter.setSelected(false);
                List<DisplayObject> incompleteObjs = new ArrayList<DisplayObject>();
                for (DisplayObject d : objs) {
                    if (!d.isComplete()) {
                        incompleteObjs.add(d);
                    }
                }
                Log.i("To Do", "filtered " + incompleteObjs.size() + " out of " +objs.size());
                filter(incompleteObjs);
                setSelections();
            }
        });

        axisOne.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position !=  axis1Pos) {
                    Log.i("AxisOne fired", "Position- " + position + " Stored -" + axis1Pos);
                    axis1Pos = position;
                    filter(objs);
                    if (position > 0) {
                        axis1Pos = 1;
                    } else {
                        axis1Pos = 0;
                    }
                    setSelections();
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {}
        });
        axisTwo.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position != axis2Pos) {
                    Log.i("AxisTwo fired", "Position- " + position + " Stored -" + axis2Pos);
                    axis2Pos = position;
                    filter(objs);
                    if (position > 0) {
                        axis2Pos = 1;
                    } else {
                        axis2Pos = 0;
                    }
                    setSelections();
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {}
        });
        axisThree.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position != axis3Pos) {
                    Log.i("AxisThree fired", "Position- " + position + " Stored -" + axis3Pos);
                    axis3Pos = position;
                    filter(objs);
                    if (position > 0) {
                        axis3Pos = 1;
                    } else {
                        axis3Pos = 0;
                    }
                    setSelections();
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                Log.i("Nothing SEECTED","");
            }
        });

        // Gesture Detector used to detect left and right swipes on the Preview Fragment. this
        //translates into the viewpager showing the next element (up,down,left,right)
        GestureDetector.OnGestureListener gestureListener = new GestureDetector.SimpleOnGestureListener() {
            @Override
            public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
                Log.i("OnFlingEvent", "");
                switch (getDirection(velocityX, velocityY)) {
                    case UP:
                        displayNextFirstAxis();
                        break;
                    case DOWN:
                        displayPreviousFirstAxis();
                        break;
                    case LEFT:
                        displayNextSecondAxis();
                        break;
                    case RIGHT:
                        displayPreviousSecondAxis();
                        break;
                    default:
                        Toast.makeText(getActivity(), "fling not handled NAVIGATOR", Toast.LENGTH_SHORT).show();
                }
                return true;
            }

            @Override
            public boolean onDown(MotionEvent e) {
                return true;
            }

            @Override
            public void onLongPress(MotionEvent e) {
                Toast.makeText(getActivity(), "Long Press (gesture detector)", Toast.LENGTH_SHORT).show();
            }
        };

        final GestureDetector gd = new GestureDetector(getActivity(), gestureListener);

        previewFragmentSpace.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                Log.i("touch", "ON TOUCH EVENT");
                return gd.onTouchEvent(event);
            }
        });
    }

    /**
     * need to call this after the filter is applied and the spinners are updated. this could have
     * been part of the setFields() method, but in order to abstract filter, it had to be seperate because,
     * filter needs to check that spinner selection matches the marked one (axis(123)Pos), BUT after
     * the spinners are updated, the spinner whoes listenere triggered the filter will now only contain
     * 1 element, as the others are inherently filtered out. so, after the filter and set fields, the
     * axis(123)Pos is set to 1, not the originially selecte position, this is a translation from old
     * state to new state. now the spinners must be set to the proper selection so the spinner doesnt
     * trigger, as if the 0th element had been selected. F'in spinners..their listeners really suck
     */
    private void setSelections() {
        axisOne.setSelection(axis1Pos);
        axisTwo.setSelection(axis2Pos);
        axisThree.setSelection(axis3Pos);
    }

    private void filter(List<DisplayObject> objects) {
        Log.i("Filtering", objects.size() + " objects");
        int a1Pos = axisOne.getSelectedItemPosition();
        int a2Pos = axisTwo.getSelectedItemPosition();
        int a3Pos = axisThree.getSelectedItemPosition();
        Log.i("A1 Filter", "selected- " + a1Pos + " stored selected- " + axis1Pos);
        Log.i("A2 Filter", "selected- " + a2Pos + " stored selected- " + axis2Pos);
        Log.i("A3 Filter", "selected- " + a3Pos + " stored selected- " + axis3Pos);

        String selection1 = null;
        String selection2 = null;
        String selection3 = null;

        List<DisplayObject> filtered = new ArrayList<>(objects);
        Set<DisplayObject> toRemove = new LinkedHashSet<>();

        //WHY DOES IT KEEP ON REPEATING AND REPEATING AFTER I SELECT FROM SPINNER ??????????

        if (a1Pos > 0) {
            selection1 = axisOne.getSelectedItem().toString();
        }
        if (a2Pos > 0) {
            selection2 = axisTwo.getSelectedItem().toString();
        }
        if (a3Pos > 0) {
            selection3 = axisThree.getSelectedItem().toString();
        }
        for (DisplayObject d : objects) {
            if (selection1 != null && !d.getAxis1Value().toString().equals(selection1.toString())) {
                toRemove.add(d);
            }
            if (selection2 != null && !d.getAxis2Value().toString().equals(selection2.toString())) {
                toRemove.add(d);
            }
            if (selection3 != null && !d.getAxis3Value().toString().equals(selection3.toString())) {
                toRemove.add(d);
            }
        }
        for (DisplayObject d : toRemove) {
            filtered.remove(d);
        }
        if (filtered.isEmpty()) {
            Toast.makeText(getActivity(), "There no fields to display", Toast.LENGTH_SHORT).show();
        } else {
            axisMatrix = new AxisMatrix(filtered);
            setFields();
        }
    }

//    private List<DisplayObject> orderBy (Comparator<DisplayObject> comparator) {
//        List<DisplayObject> li = new ArrayList<>(objList);
//        Collections.sort(li, comparator);
//        return li;
//    }

    private int viewIndex = 0;

//    private void displayCurrentData() {
//        List<DisplayObject> data = axisMatrix.getCurrentData();
//        DisplayFragment<DisplayObject> df = (DisplayFragment<DisplayObject>)getFragmentManager().findFragmentByTag(previewTag(viewIndex++ % 3));
//        df.setObjects(data, this);
//    }

    private void displayNextFirstAxis() {
        if (axisMatrix.getFirstAxisCount() > 1) {
            List<DisplayObject> data = axisMatrix.getNextFirstAxis();
            previewFragmentSpace.setInAnimation(AnimationUtils.loadAnimation(getActivity(), R.anim.abc_slide_in_bottom));
            previewFragmentSpace.setOutAnimation(AnimationUtils.loadAnimation(getActivity(), R.anim.abc_slide_out_top));
            DisplayFragment<DisplayObject> df = (DisplayFragment<DisplayObject>) getFragmentManager().findFragmentByTag(previewTag(viewIndex++ % 3));
            df.setObjects(data, this);
        }
//        previewFragmentSpace.setOutAnimation(getActivity(),android.R.anim.fade_out);
        //Toast.makeText(getActivity(),"display next floor",Toast.LENGTH_SHORT).show();
    }

    private void displayPreviousFirstAxis() {
        if (axisMatrix.getFirstAxisCount() > 1) {
            List<DisplayObject> data = axisMatrix.getPreviousFirstAxis();
            previewFragmentSpace.setInAnimation(AnimationUtils.loadAnimation(getActivity(), R.anim.abc_slide_in_top));
            previewFragmentSpace.setOutAnimation(AnimationUtils.loadAnimation(getActivity(), R.anim.abc_slide_out_bottom));
            DisplayFragment<DisplayObject> df = (DisplayFragment<DisplayObject>) getFragmentManager().findFragmentByTag(previewTag(viewIndex++ % 3));
            df.setObjects(data, this);
        }
//        previewFragments.get(viewIndex++%3).setObjects(data, this);
  //      previewFragmentSpace.animate();
        //Toast.makeText(getActivity(),"display previous floor",Toast.LENGTH_SHORT).show();
    }

    private void displayNextSecondAxis() {
        if (axisMatrix.getSecondAxisCount() > 1) {
            List<DisplayObject> data = axisMatrix.getNextSecondAxis();
            previewFragmentSpace.setInAnimation(AnimationUtils.loadAnimation(getActivity(), R.anim.right_in));
            previewFragmentSpace.setOutAnimation(AnimationUtils.loadAnimation(getActivity(), R.anim.left_out));
            DisplayFragment<DisplayObject> df = (DisplayFragment<DisplayObject>) getFragmentManager().findFragmentByTag(previewTag(viewIndex++ % 3));
            df.setObjects(data, this);
        }
        //Toast.makeText(getActivity(),"display next area",Toast.LENGTH_SHORT).show();
    }

    private void displayPreviousSecondAxis() {
        if (axisMatrix.getSecondAxisCount() > 1) {
            List<DisplayObject> data = axisMatrix.getPreviousSecondAxis();
            previewFragmentSpace.setInAnimation(AnimationUtils.loadAnimation(getActivity(), R.anim.left_in));
            previewFragmentSpace.setOutAnimation(AnimationUtils.loadAnimation(getActivity(), R.anim.right_out));
            DisplayFragment<DisplayObject> df = (DisplayFragment<DisplayObject>) getFragmentManager().findFragmentByTag(previewTag(viewIndex++ % 3));
            df.setObjects(data, this);
        }
        //Toast.makeText(getActivity(),"display previous area",Toast.LENGTH_SHORT).show();
    }

    private int getDirection(float velocityX, float velocityY) {
        if (velocityX > 0) {
            if (Math.abs(velocityX) > Math.abs(velocityY)) {
                return RIGHT;
            } else {
                if (velocityY < 0) {
                    return UP;
                } else {
                    return DOWN;
                }
            }
        } else {
            if (Math.abs(velocityX) > Math.abs(velocityY)) {
                return LEFT;
            } else {
                if (velocityY < 0) {
                    return UP;
                } else {
                    return DOWN;
                }
            }
        }
    }

    @Override
    public void viewCreated(View view) {
        if (previewFragmentSpace.getChildCount() == 0) {
            previewFragmentSpace.addView(view);
        } else {
            Log.i("View added","");
            previewFragmentSpace.addView(view, 1);
            previewFragmentSpace.showNext();
            previewFragmentSpace.removeViewAt(0);
        }
    }

    @Override
    public void display(DisplayObject obj) {
        FragmentTransaction ft = getFragmentManager().beginTransaction();

        Toast.makeText(getActivity(), obj.displayMessage(), Toast.LENGTH_SHORT).show();
    }

    @Override
    public void updateObject(DisplayObject obj) {
        objs.remove(obj);
        objs.add(obj);
        viewSwitcher.showNext();
    }

    @Override
    public List<DisplayObject> getObjects() {
        return objs;
    }

    public class AxisMatrix {
        private List<List<List<DisplayObject>>> axisMatrix;
        private List<DisplayObject> axisObjects;
        private int size;

        private List<Comparable> axis1;
        private List<Comparable> axis2;
        private List<Comparable> axis3;

        private int axisOneIndex = 0;
        private int axisTwoIndex = 0;

        private boolean isEmpty;

        public AxisMatrix (List<DisplayObject> objs) {
            axisObjects = objs;
            size = objs.size();
            isEmpty = objs.isEmpty();
            Log.i("Axis Matrix constructor", objs.size() + " items");
            getAxisSets(objs);
            buildAxisMatrix(objs);
        }

        private void buildAxisMatrix(List<DisplayObject> objs) {
            axisMatrix = new ArrayList<>();
            for (int i = 0; i < axis1.size(); i++) {
                axisMatrix.add(new ArrayList<List<DisplayObject>>());
                for (int j = 0; j < axis2.size(); j++) {
                    axisMatrix.get(i).add(new ArrayList<DisplayObject>());
                }
            }
            for (DisplayObject obj : objs) {
                axisMatrix.get(axis1.indexOf(obj.getAxis1Value())).get(axis2.indexOf(obj.getAxis2Value())).add(obj);
            }
            for (int i = 0; i < axis1.size(); i++) {
                for (int j = 0; j < axis2.size(); j++) {
                    Collections.sort(axisMatrix.get(i).get(j), axisThreeComparator);
                }
            }
        }

        private void getAxisSets(List<DisplayObject> objList) {
            Set<Comparable> axis1Values = new LinkedHashSet<>();
            Set<Comparable> axis2Values = new LinkedHashSet<>();
            Set<Comparable> axis3Values = new LinkedHashSet<>();

            for (DisplayObject obj : objList) {
                axis1Values.add(obj.getAxis1Value());
                axis2Values.add(obj.getAxis2Value());
                axis3Values.add(obj.getAxis3Value());
            }

            axis1 = new ArrayList<>(axis1Values);
            axis2 = new ArrayList<>(axis2Values);
            axis3 = new ArrayList<>(axis3Values);

            Collections.sort(axis1);
            Collections.sort(axis2);
            Collections.sort(axis3);
        }

        public List<DisplayObject> getAxisObjects() {
            return axisObjects;
        }

        public boolean isEmpty() {
            return isEmpty;
        }

        public int getSize() {
            return size;
        }

        /***
         * returns the size of the first axis
         * @return the size of the first axis
         */
        public int getFirstAxisCount() {
            return axisMatrix.size();
        }

        /**
         * returns the size of the second axis for the CURRENT first axis
         * @return the size of the second axis
         */
        public int getSecondAxisCount() {
            return axisMatrix.get(axisOneIndex).size();
        }

        public List<DisplayObject> getFirst() {
            return axisMatrix.get(0).get(0);
        }

        public List<DisplayObject>getNextFirstAxis() {
            if (axisOneIndex >= axisMatrix.size() - 1) {
                axisOneIndex = 0;
            } else {
                axisOneIndex++;
            }
            return get(axisOneIndex, axisTwoIndex);
        }

        public List<DisplayObject> getPreviousFirstAxis() {
            if (axisOneIndex <= 0) {
                axisOneIndex = (axisMatrix.size() - 1);
            } else {
                axisOneIndex--;
            }
            return get(axisOneIndex, axisTwoIndex);
        }

        public List<DisplayObject> getNextSecondAxis() {
            if (axisTwoIndex >= axisMatrix.get(axisOneIndex).size() - 1) {
                axisTwoIndex = 0;
            } else {
                axisTwoIndex++;
            }
            return get(axisOneIndex, axisTwoIndex);
        }

        public List<DisplayObject> getPreviousSecondAxis() {
            if (axisTwoIndex <= 0) {
                axisTwoIndex = axisMatrix.get(axisOneIndex).size() - 1;
            } else {
                axisTwoIndex--;
            }
            return get(axisOneIndex, axisTwoIndex);
        }

        private List<DisplayObject> get(int axis1Loc, int axis2Loc) {
            return axisMatrix.get(axis1Loc).get(axis2Loc);
        }

        public List<Comparable> getAxisOne() {
            return axis1;
        }
        public List<Comparable> getAxisTwo() {
            return axis2;
        }
        public List<Comparable> getAxisThree() {
            return axis3;
        }
    }

    public interface DisplayObject {

        public String axis1Name();
        public String axis2Name();
        public String axis3Name();

        public Comparable getAxis1Value();
        public Comparable getAxis2Value();
        public Comparable getAxis3Value();

        public boolean isComplete();

        public String displayMessage();

    }

}


text:
using NUnit.Framework;
using SupaCharge.Core.Config;

namespace SupaCharge.UnitTests.Core.Config {
  [TestFixture]
  internal class ConfigWrapperTest {
    [Test]
    public void TestContainsTrue() {
      Assert.That(mWrapper.Contains("name"), Is.True);
      Assert.That(mWrapper.Contains("num"), Is.True);
    }

    [Test]
    public void TestContainsFalse() {
      Assert.That(mWrapper.Contains("nom-nom"), Is.False);
    }

    [Test]
    public void TestGetString() {
      Assert.That(mWrapper.Get<string>("name"), Is.EqualTo("joe"));
    }

    [Test]
    public void TestGetInt() {
      Assert.That(mWrapper.Get<int>("num"), Is.EqualTo(123));
    }

    [Test]
    public void TestGetWithDefaultValueReturnsDefaultIfKeyNotFoundString() {
      Assert.That(mWrapper.Get("nam", "harold"), Is.EqualTo("harold"));
    }

    [Test]
    public void TestGetWithDefaultValueReturnsDefaultIfKeyNotFoundInt() {
      Assert.That(mWrapper.Get("nom-nom", 321), Is.EqualTo(321));
    }

    [Test]
    public void TestGetWithDefaultValueReturnsValueIfKeyFound() {
      Assert.That(mWrapper.Get("name", "bo-bop"), Is.EqualTo("joe"));
    }

    private readonly AppConfig mWrapper = new AppConfig();
  }
}


text:
package pl.coderion.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import pl.coderion.export.DefaultReportService;
import pl.coderion.export.ReportResponseDto;
import pl.coderion.model.YouTrackStatementModel;
import pl.coderion.rest.YouTrackService;
import pl.coderion.softfaktor.service.youtrack.dto.PlannedReleaseDateModel;

import java.io.IOException;

/**
 * Created by coderion on 15.05.17.
 */
@RestController
@Component("youtrackController")
public class YouTrackServiceRestController {

    @Autowired
    DefaultReportService defaultReportService;

    @Autowired
    YouTrackService youTrackService;

    @RequestMapping(value = "/api/getYouTrackReport", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public ReportResponseDto getYouTrackReport(@RequestBody YouTrackStatementModel youTrackStatementModel) throws IOException {
        youTrackService.login();
        ReportResponseDto responseDto = new ReportResponseDto();
        responseDto.setContent(defaultReportService.youTrackReport(youTrackStatementModel));
        return responseDto;
    }

    @RequestMapping(value = "/api/getPlannedReleaseDateReport", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public ReportResponseDto getPlannedReleaseDateReport(@RequestBody PlannedReleaseDateModel plannedReleaseDateModel) throws IOException {
        youTrackService.login();
        ReportResponseDto responseDto = new ReportResponseDto();
        responseDto.setContent(defaultReportService.youTrackPlannedReleaseDateReport(plannedReleaseDateModel));
        return responseDto;
    }
}


text:
define({
  "_widgetLabel": "Powiązane diagramy tabelowe",
  "searchHeaderText": "Wyszukaj adres lub zlokalizuj na mapie",
  "addressInfowindowTitle": "Wyszukiwana lokalizacja",
  "mouseOverTooltip": "Kliknij, aby zobaczyć diagram(y)",
  "errMsgNoResultsFound": "Nie znaleziono wyników",
  "errMsgNoFeaturesFound": "Nie znaleziono żadnych obiektów",
  "noChatsConfigured": "Żadne wstępnie skonfigurowane wykresy nie są dostępne",
  "locationButtonAriaLabel": "Wybierz lokalizację na mapie"
});


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Trapezoids
{
    public class Program
    {
        public static void Main()
        {
            double sideA = double.Parse(Console.ReadLine());
            double sideB = double.Parse(Console.ReadLine());
            double height = double.Parse(Console.ReadLine());

            double area = ((sideA + sideB) * height) / 2;

            Console.WriteLine("{0:F7}", area);
        }
    }
}


text:
package net.ontopia.presto.jaxrs.constraints;

import net.ontopia.presto.spi.PrestoField;
import net.ontopia.presto.spi.PrestoSchemaProvider;
import net.ontopia.presto.spi.utils.PrestoContext;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;

public abstract class DefaultConstraintException extends ConstraintException {

    protected final PrestoSchemaProvider schemaProvider;
    protected PrestoContext context;
    protected PrestoField field;

    protected DefaultConstraintException(PrestoSchemaProvider schemaProvider) {
        this.schemaProvider = schemaProvider;
    }

    protected DefaultConstraintException(PrestoContext context, PrestoField field) {
        this.schemaProvider = field.getSchemaProvider();
        this.context = context;
        this.field = field;
    }

    protected PrestoSchemaProvider getSchemaProvider() {
        return schemaProvider;
    }

    protected PrestoContext getContext() {
        return context;
    }

    protected PrestoField getField() {
        return field;
    }

    protected abstract String[] getMessageKeys();

    @Override
    public String getType() {
        return getMessageValue("type", "ALERT");
    }

    @Override
    public String getTitle() {
        return getMessageValue("title", "Constraint error");
    }

    @Override
    public String getMessage() {
        return getMessageValue("message", "Value is invalid.");
    }

    protected String getMessageValue(String property, String defaultValue) {
        for (String messageKey : getMessageKeys()) {
            for (ObjectNode extra : getExtraNodes()) {
                if (extra != null) {
                    ObjectNode messageNode = getMessageNodeFromExtraNode(messageKey, extra);
                    if (messageNode != null) {
                        String messageValue = messageNode.path(property).textValue();
                        if (messageValue != null) {
                            return messageValue;
                        }
                    }
                }
            }
        }
        return defaultValue;
    }

    protected ObjectNode[] getExtraNodes() {
        return new ObjectNode[] {
                field == null ? null : (ObjectNode)field.getExtra(),
                context == null ? null : (ObjectNode)context.getView().getExtra(),
                context == null ? null : (ObjectNode)context.getType().getExtra(),
                (ObjectNode)schemaProvider.getExtra()
        };
    }

    private ObjectNode getMessageNodeFromExtraNode(String messageKey, ObjectNode extra) {
        JsonNode resourcesNode = extra.path("error-messages");
        if (resourcesNode.isObject()) {
            JsonNode messageNode = resourcesNode.path(messageKey);
            if (messageNode.isObject()) {
                return (ObjectNode)messageNode;
            }
        }
        return null;
    }

}


text:
run_recipe File.dirname(__FILE__) + "/_common_accounts.rb"

use_manual_close

create_account :usd_gateway
create_account :scott
create_account :andrew

close_ledger

require_trust_auth :usd_gateway
set_flags :usd_gateway, [:auth_revocable_flag]

close_ledger

trust :scott,  :usd_gateway, "USD"              ; close_ledger
change_trust :andrew, :usd_gateway, "USD", 4000 ; close_ledger
allow_trust :usd_gateway, :scott, "USD"         ; close_ledger
allow_trust :usd_gateway, :andrew, "USD"        ; close_ledger
revoke_trust :usd_gateway, :andrew, "USD"       ; close_ledger


text:
module Azure::KeyVault::V7_0_preview
  module Models
    #
    # The backup secret result, containing the backup blob.
    #
    class BackupSecretResult

      include MsRestAzure

      # @return The backup blob containing the backed up secret.
      attr_accessor :value

      #
      # Mapper for BackupSecretResult class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'BackupSecretResult',
          type: {
            name: 'Composite',
            class_name: 'BackupSecretResult',
            model_properties: {
              value: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'value',
                type: {
                  name: 'Base64Url'
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
module.exports = diff

function diff(o,o2,report,fragment){
  fragment = fragment||[]
  if(!report) throw new TypeError("missing report! must be an array.")

  if(Array.isArray(o)) {

    // check length
    if(!Array.isArray(o2)){
      report.push({path:fragment,reason:'the other side is not an array',code:'ANARRAY'})
    } else {

      if(o.length != o2.length){
        if(o.length < o2.length){
          report.push({path:fragment,reason:'array has fewer items.',values:{a:o.length,b:o2.length},code:'ALESS'})
        } else {
          report.push({path:fragment,reason:'array has more items.',values:{a:o.length,b:o2.length},code:'AMORE'})
        }
      }

      //? if i have a length error every item could be off by one
      //? i check that each item is anywhere in the array then if the array is sorted
      //? check each item

      // assumed sort will generate a bunch of errors on length mismatch
      for(var i=0; i < o.length;++i){
        diff(o[i],o2[i],report,fkey(fragment,i))
      }
    }
  } else if(!o) {
    if(o !== o2) {
      report.push({path:fragment,reason:'falsey value is not equal ',values:{a:o,b:o2},code:'VFALSEY'})
    }
  } else if(typeof o === 'object') {

    if(!o2) {
      // missing object for o2 value
      // i do not include the a side object because that would bloat logs.
      report.push({path:fragment,reason:'object missing on other side.',values:{a:o},code:'ONEW'})

    } else {

      var keys = Object.keys(o);
      var keys2 = Object.keys(o2)

      if(keys.length < keys2.length) {
        report.push({path:fragment,reason:'object has more items. ',values:{a:keys.length,b:keys2.length},code:'OMORE'})
      } else if(keys.length < keys.length) {
        report.push({path:fragment,reason:'object has fewer items.',values:{a:keys.length,b:keys2.length},code:'OLESS'})
      }

      // key length check

      for(var i=0;i<keys.length;++i){
        diff(o[keys[i]],o2[keys[i]],report,fkey(fragment,keys[i]))
      }
    }

  } else {
    // plain value
    if(o != o2) {
      report.push({path:fragment,reason:'values are not equal',value:{a:o,b:o2},code:'VNEQUAL'})
    }
  }
}

function fkey(f,v){
  var n = f.slice.apply(f)
  n.push(v)
  return n
}


text:
package org.runningdinner.core;

import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;

import org.runningdinner.core.util.CoreUtil;

public final class IdentifierUtil {

	private IdentifierUtil() {
		// NOP
	}

	/**
	 * Gathers all IDs of the passed entities and returns them as a set
	 *
	 * @param entities
	 * @return
	 */
	public static <T extends Identifiable> Set<UUID> getIds(final Collection<T> entities) {
		if (CoreUtil.isEmpty(entities)) {
			return Collections.emptySet();
		}

		Set<UUID> result = new HashSet<>(entities.size());
		for (T entity : entities) {
			result.add(entity.getId());
		}
		return result;
	}

	public static <T extends Identifiable> Optional<T> filterListForId(final Collection<T> entities, final UUID entityId) {

		return entities
						.stream()
						.filter(e -> Objects.equals(entityId, e.getId()))
						.findFirst();
	}

	public static <T extends Identifiable> T filterListForIdMandatory(final Collection<T> entityList, UUID entityId) {

    return filterListForId(entityList, entityId)
            .orElseThrow(() -> new IllegalStateException("Expected " + entityList + " to contain requested " + entityId));
  }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<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>

    <artifactId>driver-couchbase</artifactId>
    <name>Simulator Driver Couchbase</name>

    <parent>
        <groupId>com.hazelcast.simulator</groupId>
        <artifactId>simulator-root</artifactId>
        <version>2.0-SNAPSHOT</version>
        <relativePath>../../pom.xml</relativePath>
    </parent>

    <prerequisites>
        <maven>${maven.version}</maven>
    </prerequisites>

    <properties>
        <main.basedir>${project.parent.basedir}</main.basedir>
        <couchbase-javaclient.version>2.4.3</couchbase-javaclient.version>
        <javassist.version>3.12.1.GA</javassist.version>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>${maven-dependency-plugin.version}</version>
                <executions>
                    <execution>
                        <id>copy-dependencies</id>
                        <phase>package</phase>
                        <goals>
                            <goal>copy-dependencies</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${project.build.directory}/</outputDirectory>
                            <overWriteReleases>false</overWriteReleases>
                            <overWriteSnapshots>false</overWriteSnapshots>
                            <overWriteIfNewer>true</overWriteIfNewer>
                            <excludeTransitive>false</excludeTransitive>
                            <excludeScope>provided</excludeScope>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <dependency>
            <groupId>com.hazelcast.simulator</groupId>
            <artifactId>simulator</artifactId>
            <version>${project.version}</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>com.couchbase.client</groupId>
            <artifactId>java-client</artifactId>
            <version>${couchbase-javaclient.version}</version>
        </dependency>
    </dependencies>
</project>


text:
SPEC_BEGIN(UADDBScanRequestSpec)

describe(@"UADDBScanRequest", ^
{
	it(@"should import a JSON string.", ^
	{
	    NSString *json = @"";
	    NSError *parseError = nil;
	    NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:[json dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:&parseError];
	    [[parseError should] beNil];
	    [[jsonDictionary should] beNonNil];

	    NSError *serialisationError = nil;
	    UADDBScanRequest *scanRequest = [MTLJSONAdapter modelOfClass:[UADDBScanRequest class] fromJSONDictionary:jsonDictionary error:&serialisationError];
	    [[serialisationError should] beNil];
	    [[scanRequest should] beNonNil];

	    // additional verification
	});

});

SPEC_END


text:
package derpatiel.manafluidics.block.furnaceHeater;

import derpatiel.manafluidics.capability.heat.CapabilityHeat;
import derpatiel.manafluidics.capability.heat.HeatProvider;
import net.minecraft.block.state.IBlockState;
import net.minecraft.inventory.SlotFurnaceFuel;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.FurnaceRecipes;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.play.server.SPacketUpdateTileEntity;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.tileentity.TileEntityFurnace;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.ITickable;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.fluids.capability.CapabilityFluidHandler;
import net.minecraftforge.fml.common.registry.GameRegistry;
import net.minecraftforge.items.CapabilityItemHandler;
import net.minecraftforge.items.ItemStackHandler;

public class FurnaceHeaterTileEntity extends TileEntity implements ITickable {

    public static final int SIZE = 1;

    //100 ticks/smelt in a furnace
    //100 HU/t from burning in this inventory
    //therefore, 10000 HU/smelt
    private final HeatProvider heatProvider = new HeatProvider(100);
    private final ItemStackHandler itemHandler = new ItemStackHandler(1);

    private int ticksLeft=0;
    private int itemProvidedTicks=0;

    @Override
    public void update() {
        boolean wasGenerating = ticksLeft>0;
        if(ticksLeft>0) {
            ticksLeft--;
            heatProvider.generateHeat();
        }else{//ticks==0
            int fuelValue = TileEntityFurnace.getItemBurnTime(itemHandler.getStackInSlot(0));
            if(fuelValue>0){
                ItemStack burningStack = itemHandler.getStackInSlot(0);
                burningStack.stackSize--;
                if(burningStack.stackSize == 0) {
                    burningStack = burningStack.getItem().getContainerItem(burningStack);
                }
                itemHandler.setStackInSlot(0,burningStack);
                ticksLeft=fuelValue;
                itemProvidedTicks=fuelValue;
                markDirty();
            }
        }
        boolean isGenerating = ticksLeft>0;
        if(isGenerating!=wasGenerating){
            worldObj.setBlockState(getPos(),worldObj.getBlockState(getPos()).withProperty(FurnaceHeater.GENERATING,isGenerating),3);
            markDirty();
        }
    }

    public boolean isGenerating(){
        return ticksLeft>0;
    }

    public float getBurnFraction(){
        if (ticksLeft==0 || itemProvidedTicks==0) {
            return 0f;
        }else{
            return ((float)ticksLeft)/((float)itemProvidedTicks);
        }
    }

    public void readFromNBT(NBTTagCompound compound)
    {
        super.readFromNBT(compound);
        ticksLeft = compound.getInteger("ticksLeft");
        itemProvidedTicks=compound.getInteger("providedTicks");
        itemHandler.deserializeNBT(compound.getCompoundTag("inventory"));
    }

    public NBTTagCompound writeToNBT(NBTTagCompound compound)
    {
        super.writeToNBT(compound);
        compound.setInteger("ticksLeft",ticksLeft);
        compound.setInteger("providedTicks",itemProvidedTicks);
        compound.setTag("inventory",itemHandler.serializeNBT());
        return compound;
    }

    @Override
    public NBTTagCompound getUpdateTag() {
        return writeToNBT(new NBTTagCompound());
    }

    @Override
    public SPacketUpdateTileEntity getUpdatePacket() {
        return new SPacketUpdateTileEntity(getPos(), 0, getUpdateTag());
    }

    @Override
    public void onDataPacket(NetworkManager net, SPacketUpdateTileEntity pkt) {
        readFromNBT(pkt.getNbtCompound());
        final IBlockState state = getWorld().getBlockState(getPos());
        getWorld().notifyBlockUpdate(getPos(), state, state, 3);
    }

    @Override
    public boolean shouldRefresh(World world, BlockPos pos, IBlockState oldState, IBlockState newSate) {
        return oldState.getBlock() != newSate.getBlock();
    }

    @Override
    public boolean hasCapability(Capability<?> capability, EnumFacing facing)
    {
        if(capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY || capability == CapabilityHeat.HEAT) {
            return true;
        }
        return super.hasCapability(capability,facing);
    }

    @SuppressWarnings("unchecked")
    @Override
    public <T> T getCapability(Capability<T> capability, EnumFacing facing)
    {
        if (capability == CapabilityHeat.HEAT) {
            return (T) heatProvider;
        }else if(capability==CapabilityItemHandler.ITEM_HANDLER_CAPABILITY){
            return (T) itemHandler;
        }
        return super.getCapability(capability, facing);
    }
}


text:
{{title}}

    <svg id='{{id}}' style="height: 500px; width: 100%;" ></svg>

Period	{{growthStats.title}}

Today	{{growthStats.today | growthNumber}}

Yesterday	{{growthStats.yesterday | growthNumber}}

Last 7 Days	{{growthStats.last7Days | growthNumber }}

All Time	{{growthStats.total | growthNumber}}

Grow MTD	{{growthStats.thisMonth|growthNumber:'%'}}

Growth Last Month	{{growthStats.lastMonth|growthNumber:'%' }}

Growth Last 3 Month	{{growthStats.last3Months|growthNumber:'%'}}

Growth Last 12 Month	{{ growthStats.last12Months|growthNumber:'%'}}

Loading....

{{errorMessage}}


text:
@interface GADURequest : NSObject

/// Returns an initialized GADURequest object.
- (id)init;

/// Words or phrase describing the current activity of the user.
@property(nonatomic, strong) NSMutableArray *keywords;

/// String that identifies the ad request's origin.
@property(nonatomic, strong) NSString *requestAgent;

/// GADMediationExtras to be sent up in the ad request.
@property(nonatomic, strong) NSMutableArray<id<GADAdNetworkExtras>> *mediationExtras;

/// Extra parameters to be sent up in the ad request.
@property(nonatomic, strong) NSMutableDictionary *extras;

/// Convenience method for adding a single keyword.
- (void)addKeyword:(NSString *)keyword;

/// Convenience method for setting an extra parameters.
- (void)setExtraWithKey:(NSString *)key value:(NSString *)value;

/// Constructs a GADRequest with the defined targeting values.
- (GADRequest *)request;

@end


text:
Cli
=============
This is simple set of classes for support php-cli script options

Advantages
-------
1. Lightweight - only two classes for work with command options
2. Events helps to up your code flexibility
3. Self-autoloading. You need to include only one file
4. Independed namespace helps to use Cli on different projects and frameworks

Posibilities
-------
You can set short or long option name, while call php-cli script. The same lines may be equal

    php script.php -a               # short name of option apply
    php script.php --apply

You can use boolean or string option values

    php script.php --apply          # option 'apply' has boolean value
    php script.php --change=all -a  # option 'change' has string value 'all', and option 'aplly' has boolean value true
    php script.php --change=all     # option 'aplly' has boolean value false. It's not set

If you use string values, that containing spaces, quote its

    php script.php --change="all the world"

You can create required options or not

    php script.php -s Test          # option 'script' is required

...if you call 'script.php' without 's' option, you will see

    php script.php
    PHP Fatal error:  Uncaught exception 'Cli\RequiredOptionException' in /root/CommandPosix.php:79

On each option you can add callback (see Usage Example). Callback function can use first parameter as an option name, second as value

    $Command->appendParameter($Option, function($name, $value) {
        echo 'option \'' . $name . '\' value is \'' . $value . '\'' . "\n";
    });

you will see

    php script.php --script=noscript
    option 'script' value is 'noscript'

Usage example
-------
    // Firstly include base class
    include('../source/Cli.php');

    use \Cli\CommandPosix,
        \Cli\Option;

    // Just create command line option instances
    $OptionHelp = new Option('help', 'h', 'show help screen option');

    // Create command instance
    $Command = new CommandPosix();

    // Append created option for help to command
    $Command->appendHelpParameter('show help screen option');

    // Append one required option. And...
    $Command->appendParameter(new Option('option', 'o', 'some option', Option::TYPE_BOOLEAN, true));

    // ...just parse the command
    $Command->parse();

If you will need the exception when required options value will not set, try:

    $Command->parse(true);

You will see something like this:

    alxmsl:~/cli/tests$ php usage.php
    PHP Fatal error:  Uncaught exception 'Cli\RequiredOptionException' with message 'option' in /home/alxmsl/cli/source/CommandPosix.php:92
    Stack trace:
    #0 /home/alxmsl/cli/tests/usage.php(27): Cli\CommandPosix->parse(true)
    #1 {main}
      thrown in /home/alxmsl/sources/cli/CommandPosix.php on line 92

License
-------

Copyright 2015 Alexey Maslov <alexey.y.maslov@gmail.com>

Licensed 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.


text:
typedef bool (*oom_handler_t)(void *data);
void libugeneric_set_oom_handler(oom_handler_t handler, void *ctx);

void *umalloc(size_t size);
void *ucalloc(size_t nmemb, size_t size);
void *urealloc(void *ptr, size_t size);
void *umemdup(const void *src, size_t n);
void ufree(void *ptr);

static inline void *uzalloc(size_t size) {return ucalloc(size, 1);}

#define BUFFER_INITIAL_CAPACITY 16

// Handy abstraction for simple memory buffer operations, was not intended to
// be fully opaque so all the fields are public.
typedef struct {
    void *data;
    size_t data_size;
    size_t capacity;
} ubuffer_t;

// Just for simplifying passing pointer together with size of the data it
// points to.
typedef struct {
    void *data;
    size_t size;
} umemchunk_t;

void ubuffer_reserve_capacity(ubuffer_t *buf, size_t new_capacity);
void ubuffer_append_data(ubuffer_t *buf, const void *data, size_t size);
void ubuffer_append_memchunk(ubuffer_t *buf, const umemchunk_t *chunk);
void ubuffer_append_buffer(ubuffer_t *buf, const ubuffer_t *data);
void ubuffer_append_byte(ubuffer_t *buf, char byte);
void ubuffer_append_string(ubuffer_t *buf, const char *str);
void ubuffer_null_terminate(ubuffer_t *buf);

static inline void ubuffer_reset(ubuffer_t *buf)   {buf->data_size = 0;}
static inline void ubuffer_destroy(ubuffer_t *buf) {ufree(buf->data);}

char *umemchunk_as_str(umemchunk_t m);
void umemchunk_serialize(umemchunk_t m, ubuffer_t *buf);
int umemchunk_fprint(umemchunk_t m, FILE *out);
static inline int umemchunk_print(umemchunk_t m) {return umemchunk_fprint(m, stdout);}

#endif