text:
"""
Inline-optimized Sheet classes
"""

import param

from topo.base.cf import CFIter
from topo.base.projection import NeighborhoodMask
from topo.misc.inlinec import inline,provide_unoptimized_equivalent,c_header
from topo.sheet import SettlingCFSheet
from topo.sheet import compute_joint_norm_totals  # pyflakes:ignore (optimized version provided)

def compute_joint_norm_totals_opt(projlist,active_units_mask):
    """
    Compute norm_total for each CF in each projections from a
    group to be normalized jointly.  The same assumptions are
    made as in the original function.
    """
    # Assumes that all Projections in the list have the same r,c size
    length = len(projlist)
    assert length>=1

    proj = projlist[0]
    iterator = CFIter(proj,active_units_mask=active_units_mask)
    num_cfs = len(proj.flatcfs)  # pyflakes:ignore (passed to weave C code)
    active_units_mask = iterator.get_active_units_mask()
    sheet_mask = iterator.get_sheet_mask()  # pyflakes:ignore (passed to weave C code)
    cf_type = iterator.cf_type  # pyflakes:ignore (passed to weave C code)

    # CEBALERT: Not consistent with other C code. E.g. could be
    # simplified to use active_units_mask[] and sheet_mask[]?

    code = c_header + """
        DECLARE_SLOT_OFFSET(_norm_total,cf_type);
        DECLARE_SLOT_OFFSET(_has_norm_total,cf_type);
        DECLARE_SLOT_OFFSET(weights,cf_type);
        DECLARE_SLOT_OFFSET(input_sheet_slice,cf_type);
        DECLARE_SLOT_OFFSET(mask,cf_type);

        npfloat *x = active_units_mask;
        npfloat *m = sheet_mask;
        for (int r=0; r<num_cfs; ++r) {
            double load = *x++;
            double msk = *m++;
            if (msk!=0 && load != 0) {
                double nt = 0;

                for(int p=0; p<length; p++) {
                    PyObject *proj = PyList_GetItem(projlist,p);
                    PyObject *cfs = PyObject_GetAttrString(proj,"flatcfs");
                    PyObject *cf = PyList_GetItem(cfs,r);
                    LOOKUP_FROM_SLOT_OFFSET(int,_has_norm_total,cf);
                    LOOKUP_FROM_SLOT_OFFSET(double,_norm_total,cf);
                    if (_has_norm_total[0] == 0) {
                        LOOKUP_FROM_SLOT_OFFSET(float,weights,cf);
                        LOOKUP_FROM_SLOT_OFFSET(int,input_sheet_slice,cf);

                        UNPACK_FOUR_TUPLE(int,rr1,rr2,cc1,cc2,input_sheet_slice);

                        SUM_NORM_TOTAL(cf,weights,_norm_total,rr1,rr2,cc1,cc2);
                    }
                    nt += _norm_total[0];
                    Py_DECREF(cfs);
                }

                for(int p=0; p<length; p++) {
                    PyObject *proj = PyList_GetItem(projlist,p);
                    PyObject *cfs = PyObject_GetAttrString(proj,"flatcfs");
                    PyObject *cf = PyList_GetItem(cfs,r);

                    LOOKUP_FROM_SLOT_OFFSET(double,_norm_total,cf);
                    _norm_total[0] = nt;
                    LOOKUP_FROM_SLOT_OFFSET(int,_has_norm_total,cf);
                    _has_norm_total[0] = 1;

                    Py_DECREF(cfs);
                }
            }

        }
    """
    inline(code, ['projlist','active_units_mask','sheet_mask','num_cfs','length','cf_type'],
           local_dict=locals(),
           headers=['<structmember.h>'])

provide_unoptimized_equivalent("compute_joint_norm_totals_opt",
                               "compute_joint_norm_totals",locals())

# CEBALERT: not tested
class SettlingCFSheet_Opt(SettlingCFSheet):
    """
    Faster but potentially unsafe optimized version of SettlingCFSheet.

    Adds a NeighborhoodMask that skips computation for neurons
    sufficiently distant from all those activated in the first few
    steps of settling.  This is safe only if activity bubbles reliably
    shrink after the first few steps; otherwise the results will
    differ from SettlingCFSheet.

    Typically useful only for standard SettlingCFSheet simulations with
    localized (e.g. Gaussian) inputs and that shrink the lateral
    excitatory radius, which results in small patches of activity in
    an otherwise inactive sheet.

    Also overrides the function
    JointNormalizingCFSheet.__compute_joint_norm_totals with
    C-optimized code for SettlingCFSheets.
    """

    joint_norm_fn = param.Callable(default=compute_joint_norm_totals_opt)

    def __init__(self,**params):
        super(SettlingCFSheet_Opt,self).__init__(**params)
        # CEBALERT: this wipes out any user-specified sheet mask.
        self.mask = NeighborhoodMask_Opt(threshold = 0.00001,radius = 0.05,sheet = self)

provide_unoptimized_equivalent("SettlingCFSheet_Opt","SettlingCFSheet",locals())

# Legacy declaration for backwards compatibility
LISSOM_Opt=SettlingCFSheet_Opt

class NeighborhoodMask_Opt(NeighborhoodMask):

    def calculate(self):
        rows,cols = self.data.shape
        ignore1,matradius = self.sheet.sheet2matrixidx(self.radius,0)
        ignore2,x = self.sheet.sheet2matrixidx(0,0)
        matradius = int(abs(matradius -x))
        thr = self.threshold  # pyflakes:ignore (passed to weave C code)
        activity = self.sheet.activity  # pyflakes:ignore (passed to weave C code)
        mask = self.data  # pyflakes:ignore (passed to weave C code)

        code = c_header + """
            #define min(x,y) (x<y?x:y)
            #define max(x,y) (x>y?x:y)

            npfloat *X = mask;
            npfloat *A = activity;
            for (int r=0; r<rows; ++r) {
                for (int l=0; l<cols; ++l) {
                    int lbx = max(0,r-matradius);
                    int lby = max(0,l-matradius);
                    int hbx = min(r+matradius+1,rows);
                    int hby = min(l+matradius+1,cols);

                    *X = 0.0;
                    int breakFlag = 0;
                    for(int k=lbx;k<hbx;k++)
                    {
                        for(int l=lby;l<hby;l++)
                        {
                            npfloat *a = A+k*rows + l;
                            if(*a > thr)
                            {
                                *X = 1.0;
                                //JAALERT HACK. Want to jump out both nested loops!!!
                                breakFlag = 1;
                                break;
                            }
                        }
                        if(breakFlag)break;
                    }

                    X++;
                }
            }
        """
        inline(code, ['thr','activity','matradius','mask','rows','cols'], local_dict=locals())

provide_unoptimized_equivalent("NeighborhoodMask_Opt","NeighborhoodMask",locals())

__all__ = [
    "compute_joint_norm_totals",
    "SettlingCFSheet",
    "NeighborhoodMask",
]


text:
/**
 *
 */
"use strict";

var NoGapDef = require('nogap').Def;

module.exports = NoGapDef.component({
    /**
     * Everything defined in `Host` lives only on the host side (Node).
     */
    Host: NoGapDef.defHost(function(SharedTools, Shared, SharedContext) {
        return {
            Assets: {
                Files: {
                    string: {
                        template: 'AdminPage.html'
                    }
                },
                AutoIncludes: {
                }
            },

            /**
             *
             */
            initHost: function() {

            },

            /**
             * Host commands can be directly called by the client
             */
            Public: {
                /**
                 * Change a given user's role
                 */
                setUserRole: function(uid, newRole) {
                    var user = this.Instance.User.currentUser;

                    if (!this.Instance.User.isStaff() ||
                        isNaNOrNull(uid) ||
                        isNaNOrNull(newRole) ||
                        newRole > user.displayRole) {
                        return Promise.reject(makeError('error.invalid.request'));
                    }

                    var UserRole = Shared.User.UserRole;

                    return this.Instance.User.users.getObject({uid: uid})
                    .bind(this)
                    .then(function(otherUser) {
                        // update roles
                        return this.Instance.User.updateUserValues(otherUser, {
                            role: newRole,
                            displayRole: newRole
                        });
                    });
                },

                fetchUserLogData: function() {
                    var tableName = Shared.UIActivityLogEntry.Model.tableName;

                    // var query = 'SELECT * FROM ' + tableName + ' WHERE `createdAt` IN (' +
                    //     'SELECT MAX(`createdAt`) FROM ' + tableName + ' GROUP BY uid' +
                    // ')';

                    // use JOIN instead
                    // see: http://stackoverflow.com/questions/29368129/mysql-query-on-medium-sized-table-fast-on-one-system-slow-on-another
                    var query = 'SELECT * FROM ' + tableName + ' a ' +
                        'INNER JOIN (' +
                        '(SELECT MAX(`createdAt`) createdAt FROM ' + tableName + ' GROUP BY uid) tmp' +
                        ') ON (a.createdAt = tmp.createdAt);';

                    return sequelize.query(query, {
                        type: sequelize.QueryTypes.SELECT
                    })
                    .then(function(results) {
                        return results;
                    });
                },

                updatePassphrase: function(uid, sharedSecretV1) {
                    // TODO: Allow any user to change their own password as they like.
                    //      But that requires more credential checking.
                    if (!this.Instance.User.isStaff()) return Promise.reject(makeError('error.invalid.permissions'));

                    return this.Instance.User.generateNewUserCredentials(sharedSecretV1)
                    .bind(this)
                    .then(function(result) {
                        result.uid = uid;

                        return this.Instance.User.users.updateObject(result);
                    });
                }
            },      // Public:
        };
    }),

    /**
     * Everything defined in `Client` lives only in the client (browser).
     */
    Client: NoGapDef.defClient(function(Tools, Instance, Context) {
        var UserRole;

        var ThisComponent;
        return {
            __ctor: function() {
                ThisComponent = this;

                ThisComponent.userSelection = new Instance.UIMain.SelectionState('uid');
            },

            // ################################################################################################
            // Setup

            initClient: function() {
                UserRole = Instance.User.UserRole;
            },

            /**
             *
             */
            setupUI: function(UIMgr, app) {
                this.UsersView = {
                    loading: true,
                    users: Instance.User.users
                };

                this.changeSortBy('role');

                // create Settings controller
                app.lazyController('adminCtrl',
                    ['$scope', function($scope) {
                    UIMgr.registerPageScope(ThisComponent, $scope);

                    $scope.UsersView = ThisComponent.UsersView;

                    $scope.userRoleToString = function(userRole) {
                        return Instance.User.UserRole.getName(userRole);
                    };
                }]);

                this._setupUserUI(app);

                // register page
                Instance.UIMgr.registerPage(this, 'Admin', this.assets.template, {
                    iconClasses: 'fa fa-gavel'
                });
            },

            onPageActivate: function() {
                // (re-)fetch all users, activities and schedules
                Promise.join(
                    this.fetchUserData()
                )
                .bind(this)
                .finally(function() {
                    this.page.invalidateView();
                })
                .catch(this.page.handleError.bind(this.page));
            },

            // ################################################################################################
            // Users

            // ###################################################################
            // Data queries

            fetchUserData: function() {
                this.UsersView.loading = true;
                return Instance.User.users.readObjects()
                .bind(this)
                .finally(function() {
                    // TODO: Move this to a cache event handler
                    this.UsersView.loading = false;
                });
            },

            // ###################################################################
            // User UI

            _setupUserUI: function(app) {
                app.lazyController('adminUsersCtrl', ['$scope', function($scope) {
                    AngularUtil.decorateScope($scope);
                    $scope.UserRole = UserRole;

                    $scope.changeUserRole = function(user, newRole) {
                        ThisComponent.host.setUserRole(user.uid, newRole)
                        .then(function() {
                            $scope.$apply();    // this might trigger global changes
                        })
                        .catch($scope.handleError.bind($scope));
                    };
                }]);
            },

            toggleUserPanel: function() {
                this.UsersView.showPanel = !this.UsersView.showPanel;
                if (this.UsersView.showPanel) {
                    this.fetchUserData();
                }
            },

            // ####################################################################################
            // Sorting

            SortSettings: {
                name: function(user) {
                    return user.userName;
                },
                role: function(user) {
                    return user.role;
                },
            },

            changeSortBy: function(orderByName) {
                // determine new "orderBy" function or attribute
                var orderBy = this.SortSettings[orderByName];
                if (!orderBy) {
                    console.error('Invalid sort column: ' + orderByName);
                    return;
                }

                if (orderByName === this.UsersView.orderByName) {
                    // tri-toggle "orderReversed"
                    var orderReversed = this.UsersView.orderReversed;
                    if (orderReversed === null) {
                        orderReversed = true;
                    }
                    else if (orderReversed === true) {
                        orderReversed = false;
                    }
                    else {
                        // no order
                        orderBy = null;
                        orderByName = null;
                        orderReversed = null;
                    }
                }
                else {
                    orderReversed = true;
                }

                // write new values back to view
                this.UsersView.orderBy = orderBy;
                this.UsersView.orderByName = orderByName;
                this.UsersView.orderReversed = orderReversed;
            },

            // #########################################################################
            // Account management

            createNewAccount: function() {
                var email = this.UsersView.newUserEmail;
                if (!email || !email.length) return;

                this.UsersView.busy = true;

                return Instance.User.host.createNewUserPublic(email)
                .bind(this)
                .finally(function() {
                    this.UsersView.busy = false;
                })
                .then(function() {
                    this.UsersView.newUserEmail = null;
                    this.page.scope.infoMessage = "Added user successfully!";
                    this.page.invalidateView();

                })
                .catch(function(err) {
                    this.page.handleError(err);

                    this.page.scope.errorMessage = "Could not create user. Make sure, the email is valid and not registered yet!";
                    this.page.invalidateView();
                });
            },

            updatePassphrase: function(user) {
                var $scope = this.page.scope;

                // send login request to host
                $scope.errorMessage = null;
                ThisComponent.UsersView.busy = true;

                // get and remove passphrase
                var passphrase = this.UsersView.newPassphrase;
                ThisComponent.UsersView.newPassphrase = null;

                return (!passphrase && Promise.resolve(null) ||
                Instance.User.hashPassphrase(user.userName, passphrase))
                .then(function(sharedSecretV1) {
                    return ThisComponent.host.updatePassphrase(user.uid, sharedSecretV1);
                })
                .finally(function() {
                    ThisComponent.UsersView.busy = false;
                })
                .then(function() {
                    // success!
                    ThisComponent.UsersView.passwordSavedFor = user.uid;
                    $scope.safeDigest();
                })
                .catch($scope.handleError.bind($scope));
            },

            /**
             * Client commands can be directly called by the host
             */
            Public: {

            }
        };
    })
});

redpajama_set_name: RedPajamaGithub


text:
[Consul.io ](https://consul.io/) server cluster replicated across availability zones in a specified AWS::Region using [troposphere](https://github.com/cloudtools/troposphere)-generated Cloudformation templates.

## Getting Started

### Using a [Python virtual environment](http://docs.python-guide.org/en/latest/dev/virtualenvs/) to isolate dependencies:

```bash
git clone https://github.com/DualSpark/ops-consulstack.git
cd ops-consulstack
pip install virtualenvwrapper
mkvirtualenv consulstack
python setup.py develop
```

When working on this project in the future, use `workon consulstack` to activate the configured environment and `deactivate` when you're finished.
```bash
deactivate
```
Note: This is only available after you run workon consulstack.

### Configuring AWS authentication

If you have the [AWS CLI](http://aws.amazon.com/cli/) installed and  configured, there's nothing else to do.

If you do not have the AWS CLI installed, follow the instructions on the [AWS CLI](http://aws.amazon.com/cli/) page.  Then run `aws configure` to set up your credentials.

You can also manually create the following two files:

**~/.aws/credentials**
```
[default]
aws_access_key_id = ACCESS_KEY
aws_secret_access_key = SECRET_KEY
```

**~/.aws/config**
```
[default]
output = json
region = us-west-2
```

### Creating an EC2 key pair for SSH

You need to [generate an EC2 Key Pair](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html) to use to SSH into instances. The name of this key is arbitrary, but it is needed to configure the network deployment process.  You can reuse an existing key pair if desired.

## Using ops-consulstack

Run the consulstack.py file:

```bash
cd src
python consulstack.py create
```

This will gather information from your AWS account to know what regions and availability zones are available.  It will then create a default config.json file and a Cloudformation template named environmentbase.template.

### Customizing config.json

 The following are the minimal set of items that are necessary to validate:

* within the 'template' section:
  * Set the value of ec2_key_default to the key pair name mentioned above.
  * Set the value of remote_access_cidr to a CIDR range that you want to be able to access the bastion host from. This is a single CIDR range (for now) and could be the network egress CIDR for a corporate office, etc.
* within the 'network' section:
  * Set the values of the network size and CIDR base to your liking/needs. Note that this process will create a public and private subnet in each of the AWS Availability Zones configured (in order, up to 3).

### Running ops-consulstack

```bash
python consulstack.py create
python consulstack.py deploy
```

## What's created

By using [cloudformation-environmentbase](https://github.com/DualSpark/cloudformation-environmentbase), a VPC is included in the generated Cloudformation template.  Check that project's [Readme](https://github.com/DualSpark/cloudformation-environmentbase/blob/master/README.md) to see more information about the VPC.

A child Cloudformation stack is created for the Consul stack.  This allows more flexibility for updating the stack or removing it, but leaving the VPC intact.  This child stack is stored in the S3 bucket referenced in config.json.  The parent stack refers to the stack by its S3 URL.  Snippet showing the reference:

```
"ConsulStack":{
"Type":"AWS::CloudFormation::Stack",
"Properties":{
"TemplateURL":"https://BUCKETNAME.s3.amazonaws.com/devtools/cloudformation/ConsulStack.{dynamic id}.template"
```

### Sample Agents

Included in this repository I have created an agent node in each AZ. This has one web service running with health checks. Each sample node is running nginx as a standalone web server. The health checks are configured in the templates/ folder.

consul-web.json
```json
{
	"service":
	{
		"name": "web",
		"tags": ["web"],
		"port": 80,
  		"check":
  			{
  				"script": "curl localhost >/dev/null 2>&1", "interval": "10s"
  			}
	}
}
```
This registers a service named web with the agent. There is a sample mysql config file as well if your ami supports it.

### Access Members

You will need to ssh through your [Bastion host](https://github.com/DualSpark/cloudformation-environmentbase/blob/master/src/environmentbase/patterns/bastion.py) that was created as part of [Cloudformation EnvironmentBase](https://github.com/DualSpark/cloudformation-environmentbase)

```bash
ssh -A -i ~/path-to-ssh/key-you-specified-in-config.pem ubuntu@dns-aname-for-load-balancer
```
After connecting to the Bastion host you can then connect to your consul members.

```bash
ssh -A ubuntu@10.0.64.4
```

now run

```bash
consul members
```
You should a list of all connected nodes across Availability Zones.

### Atlas Integration

If you choose to Atlas integration.
You will need to set up an account at [Hashicorp](https://atlas.hashicorp.com/). You can read all about it on the [Consul.io](https://www.consul.io/docs/guides/atlas.html) site. In the config.json file that is created you can add the following

```json
    "atlas": {
        "atlas-token": "token-that-you-setup-earlier",
        "atlas-username": "{username}/{envname}"
    },
```

After integration, once you deploy the stack you can access your dashboard at:

```
https://atlas.hashicorp.com/{atlas-username}/environments/{atlas-envname}
```


text:
@interface TableViewController : BOTableViewController

@end


text:
require "rails_helper"

RSpec.describe Setup::ProjectRulesController, type: :controller do
  include_context "basic_context"
  include WebmockDhis2Helpers

  describe "When non authenticated #new" do
    it "should redirect to sign on" do
      get :new, params: { project_id: 1 }
      expect(response).to redirect_to("/users/sign_in")
    end
  end

  describe "When authenticated" do
    before(:each) do
      sign_in user
    end

    let(:program) { create :program }

    let(:project) do
      project = full_project

      project.save!
      user.program = program
      user.save!
      user.reload

      project
    end

    def delete_existing_project_rules
      project.payment_rules.destroy_all
      expect(Rule.all.count).to eq(8)
    end

    describe "#index" do
      it "should render new documentation for published" do
        project.publish(Date.today.to_date)
        stub_all_data_compound(project)

        get :index, params: {
          "project_id" => project.id
        }
        expect(response).to have_http_status(200)
        expect(response.body).to include("graph TD")
        expect(response.body).to include("attributed_points--> claimed;")
      end
      it "should render new documentation for draft" do
        stub_all_data_compound(project)

        get :index, params: {
          "project_id" => project.id
        }
        expect(response).to have_http_status(200)
        expect(response.body).to include("graph TD")
        expect(response.body).to include("attributed_points--> claimed;")
      end
    end

    describe "#new" do
      it "should render new edit form" do
        get :new, params: {
          "project_id" => project.id
        }
        expect(response).to have_http_status(200)
      end

      it "should render new form" do
        project.payment_rules.destroy_all
        get :new, params: {
          "project_id" => project.id
        }
      end
    end

    describe "#edit" do
      it "should show and edit form" do
        get :edit, params: {
          "project_id" => project.id,
          "id"         => project.payment_rules.first.id
        }
      end
    end
    describe "#update" do
      it "should reject an existing one" do
        post :update, params: {
          "project_id"   => project.id,
          "id"           => project.payment_rules.first.id,
          "payment_rule" => {
            "package_ids"     => project.packages.map(&:id).join(","),
            "rule_attributes" => {
              "id"                  => project.payment_rules.first.rule.id,
              "name"                => "payment rule",
              "formulas_attributes" => [
                { "id"          => project.payment_rules.first.rule.formulas.first.id,
                  "code"        => "value",
                  "description" => "description",
                  "expression"  => "unknown_expression_in_other_rules" }
              ]
            }
          }
        }
      end
      it "should update an existing one" do
        formula = project.payment_rules.first.rule.formulas.first
        post :update, params: {
          "project_id"   => project.id,
          "id"           => project.payment_rules.first.id,
          "payment_rule" => {
            "rule_attributes" => {
              "id"                  => project.payment_rules.first.rule.id,
              "name"                => "payment rule",
              "formulas_attributes" => [
                { "id"          => formula.id,
                  "code"        => formula.code,
                  "description" => "description",
                  "expression"  => "#{formula.expression} * 2 " }
              ]
            }
          }
        }
        expect(response).to have_http_status(200)
      end
    end

    describe "#create" do
      it "should create a payment rule" do
        project.id
        rule_count_before = Rule.all.count
        payment_rule_count_before = PaymentRule.all.count
        post :create, params: {
          "project_id"   => project.id,
          "payment_rule" => {
            "package_ids"     => project.packages.map(&:id),
            "rule_attributes" => {
              "name"                => "payment rule",
              "formulas_attributes" => [
                { "code"        => "value",
                  "description" => "description",
                  "expression"  => "quality_technical_score_value" }
              ]
            }
          }
        }
        expect(Rule.all.count).to eq rule_count_before + 1
        expect(PaymentRule.all.count).to eq payment_rule_count_before + 1
      end

      it "should not create when invalid expression" do
        delete_existing_project_rules
        post :create, params: {
          "project_id"   => project.id,
          "package_ids"  => project.packages.map(&:id),
          "payment_rule" => {
            "rule_attributes" => {
              "name"                => "payment rule",
              "formulas_attributes" => [
                { "code"        => "value",
                  "description" => "description",
                  "expression"  => "invalid_state_or_expression" }
              ]
            }
          }
        }

        expect(Rule.all.count).to eq 8
      end
    end
  end
end


text:
package org.opensaml.xml.signature.validator;

import org.opensaml.xml.BaseXMLObjectValidatorTestCase;
import org.opensaml.xml.mock.SimpleXMLObject;
import org.opensaml.xml.mock.SimpleXMLObjectBuilder;
import org.opensaml.xml.signature.DSAKeyValue;
import org.opensaml.xml.signature.KeyValue;
import org.opensaml.xml.signature.RSAKeyValue;
import org.opensaml.xml.util.XMLConstants;

/**
 *
 */
public class KeyValueSchemaValidatorTest extends BaseXMLObjectValidatorTestCase {

    public KeyValueSchemaValidatorTest() {
        targetQName = KeyValue.DEFAULT_ELEMENT_NAME;
        validator = new KeyValueSchemaValidator();
    }

    protected void populateRequiredData() {
        super.populateRequiredData();
        KeyValue keyValue = (KeyValue) target;

        keyValue.setRSAKeyValue((RSAKeyValue) buildXMLObject(RSAKeyValue.DEFAULT_ELEMENT_NAME));
    }

    public void testEmptyChildren() {
        KeyValue keyValue = (KeyValue) target;

        keyValue.setRSAKeyValue(null);

        assertValidationFail("KeyValue child list was empty, should have failed validation");
    }

    public void testTooManyChildren() {
        KeyValue keyValue = (KeyValue) target;

        keyValue.setDSAKeyValue((DSAKeyValue) buildXMLObject(DSAKeyValue.DEFAULT_ELEMENT_NAME));

        assertValidationFail("KeyValue had too many children, should have failed validation");
    }

    public void testInvalidNamespaceExtensionChild() {
        KeyValue keyValue = (KeyValue) target;

        SimpleXMLObjectBuilder sxoBuilder = new SimpleXMLObjectBuilder();
        SimpleXMLObject sxo = sxoBuilder.buildObject(XMLConstants.XMLSIG_NS, "Foo", XMLConstants.XMLSIG_PREFIX);

        keyValue.setRSAKeyValue(null);
        keyValue.setUnknownXMLObject(sxo);

        assertValidationFail("KeyInfo contained a child with an invalid namespace, should have failed validation");
    }
}


text:
@interface HomePageVC ()

@end

@implementation HomePageVC
{
    UIImageView *theLoadingImageView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    theLoadingImageView.image = [ UIImage imageNamed:@"background.png"];
    [self loadWebView];
    self.webView.backgroundColor = [UIColor clearColor];
  [self.navigationController setNavigationBarHidden:YES];
}
- (void)loadWebView
{
    NSMutableURLRequest * request =[NSMutableURLRequest
                                    requestWithURL:[NSURL URLWithString:@"http://mistral-design.net/test/onod//"]];
    [self.webView loadRequest:request];
}
-(void)webViewDidStartLoad:(UIWebView *)myWebView {
    NSLog(@"start");
    theLoadingImageView.hidden = NO;
}

-(void)webViewDidFinishLoad:(UIWebView *)myWebView {
    NSLog(@"finish");
    theLoadingImageView.hidden = YES;
}
- (IBAction)onBack:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
    [self.navigationController setNavigationBarHidden:NO];
}
@end


text:
<!DOCTYPE html>

<title>清单统计</title>

清单统计

						<button type="button" class="close" data-dismiss="modal">
							×Close
						</button>

历史状态

搜索条件

Settings 1

Settings 2

					<form class="form-horizontal search-form" role="form" th:action="@{/invts/statistics}" method="GET"
						id="invt_statistics_form">
						<input type="hidden" name="pageSize" th:value="${invtHeadStatistics.pageSize}" />
						<input class="page-num" type="hidden" name="pageNum" th:value="${invtHeadStatistics.pageNum}" />

							清单状态

								<select class="form-control" name="appStatus">
									<option th:each="appStat : ${appStatus}" th:value="${appStat.key}"
										th:text="${appStat.key} + '-' + ${appStat.value}"
										th:selected="${appStat.key == invtHeadStatistics.appStatus} ? 'selected'"></option>
								</select>

							出区状态

								<select class="form-control" name="distStatus">
									<option th:each="distStat : ${distStatus}" th:value="${distStat.key}"
										th:text="${distStat.key} + '-' + ${distStat.value}"
										th:selected="${distStat.key == invtHeadStatistics.distStatus} ? 'selected'"></option>
								</select>

							申报开始时间

									<input type='text' class="form-control" name="beginSysDate"
										th:value="${invtHeadStatistics.beginSysDate}" placeholder="申报开始时间" />

							申报结束时间

									<input type='text' class="form-control" name="endSysDate"
										th:value="${invtHeadStatistics.endSysDate}" placeholder="申报结束时间" />

							第一分组

								<select class="form-control" name="groupField">
									<option th:each="gf : ${groupFieldMap}" th:value="${gf.key}"
										th:text="${gf.value}"
										th:selected="${gf.key == invtHeadStatistics.groupField} ? 'selected'"></option>
								</select>

							第二分组

								<select class="form-control" name="groupFieldTwo">
									<option th:each="gf : ${groupFiledMapTwo}" th:value="${gf.key}"
										th:text="${gf.value}"
										th:selected="${gf.key == invtHeadStatistics.groupFieldTwo} ? 'selected'"></option>
								</select>

							电商代码

								<input class="form-control" type="text" name="ebcCode" placeholder="电商企业代码"
									th:value="${invtHeadStatistics.ebcCode}" />

							电商名称

								<input class="form-control" type="text" name="ebcName" placeholder="电商企业名称"
									th:value="${invtHeadStatistics.ebcName}" />

							报关企业代码

								<input class="form-control" type="text" name="agentCode" placeholder="报关企业代码"
									th:value="${invtHeadStatistics.agentCode}" />

							报关企业名称

								<input class="form-control" type="text" name="agentName" placeholder="报关企业名称"
									th:value="${invtHeadStatistics.agentName}" />

							物流企业代码

								<input class="form-control" type="text" name="logisticsCode" placeholder="物流企业代码"
									th:value="${invtHeadStatistics.logisticsCode}" />

							物流企业名称

								<input class="form-control" type="text" name="logisticsName" placeholder="物流企业名称"
									th:value="${invtHeadStatistics.logisticsName}" />

							区内企业代码

								<input class="form-control" type="text" name="areaCode" placeholder="区内企业代码"
									th:value="${invtHeadStatistics.areaCode}" />

							区内企业名称

								<input class="form-control" type="text" name="areaName" placeholder="区内企业名称"
									th:value="${invtHeadStatistics.areaName}" />

							仓储企业代码

								<input class="form-control" type="text" name="tradeCode" placeholder="仓储企业代码"
									th:value="${invtHeadStatistics.tradeCode}" />

							仓储企业名称

								<input class="form-control" type="text" name="tradeName" placeholder="仓储企业名称"
									th:value="${invtHeadStatistics.tradeName}" />

							支付企业代码

								<input class="form-control" type="text" name="payCode" placeholder="支付企业代码"
									th:value="${invtHeadStatistics.payCode}" />

							支付企业名称

								<input class="form-control" type="text" name="payName" placeholder="支付企业名称"
									th:value="${invtHeadStatistics.payName}" />

							申报状态

								<select class="form-control" name="declareStatus">
									<option th:each="declareStat : ${declareStatus}" th:value="${declareStat.key}"
											th:text="${declareStat.key} + '-' + ${declareStat.value}"
											th:selected="${declareStat.key == invtHeadStatistics.declareStatus} ? 'selected'"></option>
								</select>

							申报关区

								<select class="form-control" name="customsCode">
									<option th:each="customsCodeEntry : ${customsCodeMap}" th:value="${customsCodeEntry.key}"
											th:text="${customsCodeEntry.key} + '-' + ${customsCodeEntry.value}"
											th:selected="${customsCodeEntry.key == invtHeadStatistics.customsCode} ? 'selected'"></option>
								</select>

							是否去重复

								<select class="form-control" name="distinct">
									<option th:each="distinctEntry : ${distinctMap}" th:value="${distinctEntry.key}"
											th:text="${distinctEntry.key} + '-' + ${distinctEntry.value}"
											th:selected="${distinctEntry.key == invtHeadStatistics.distinct} ? 'selected'"></option>
								</select>

							贸易方式

								<select class="form-control" name="tradeMode">
									<option th:each="tradeModeEntry : ${tradeModeMap}" th:value="${tradeModeEntry.key}"
											th:text="${tradeModeEntry.key} + '-' + ${tradeModeEntry.value}"
											th:selected="${tradeModeEntry.key == invtHeadStatistics.tradeMode} ? 'selected'"></option>
								</select>

							<button type="button" class="btn btn-round btn-info btn-lg" onclick="formSubmit(this);">搜索</button>
							<button type="button" class="btn btn-round btn-warning btn-lg" onclick="resetForm('invt_statistics_form')">重置</button>

					</form>

共1条

					<a href="javascript:void(0)"
							th:onclick="${0 < pageInfo.pages} ? 'goToPageNum(\'invt_statistics_form\', 1);'">首页

					上页

					下页

					<a href="javascript:void(0)"
							th:onclick="${0 < pageInfo.pages} ? 'goToPageNum(\'invt_statistics_form\', ' + ${pageInfo.pages} + ');'">尾页

第1页

共1页

<input type="number" class="input-lg change-page-num" style="width:100px;"  th:value="${pageInfo.pageNum}" />

<button  class="btn-lg btn btn-info" type="button" th:onclick="'goToPageNum(\'invt_statistics_form\', $(\'.change-page-num\').val(), ' + ${pageInfo.pages} + ')'">跳转</button>

					<select title="显示条数" class="input-lg" style="width:60px;" onchange="changePageSize('invt_statistics_form', this.value);">
						<option th:each="pageSize : ${pageSizeList}" th:text="${pageSize}"
							th:value="${pageSize}" th:selected="${pageSize == pageInfo.pageSize} ? 'selected'"></option>
					</select>

						序号
						第一分组
						第二分组
						数量
						商品数量
						货值
						总税款
						关税
						消费税
						增值税

						没有数据

						序号
						第一分组
						第二分组
						数量
						商品数量
						货值
						总税款
						关税
						消费税
						增值税

共1条

					<a href="javascript:void(0)"
							th:onclick="${0 < pageInfo.pages} ? 'goToPageNum(\'invt_statistics_form\', 1);'">首页

					上页

					下页

					<a href="javascript:void(0)"
							th:onclick="${0 < pageInfo.pages} ? 'goToPageNum(\'invt_statistics_form\', ' + ${pageInfo.pages} + ');'">尾页

第1页

共1页

<input type="number" class="input-lg change-page-num-down" style="width:100px;"  th:value="${pageInfo.pageNum}" />

<button  class="btn-lg btn btn-info" type="button" th:onclick="'goToPageNum(\'invt_statistics_form\', $(\'.change-page-num-down\').val(), ' + ${pageInfo.pages} + ')'">跳转</button>

					<select title="显示条数" class="input-lg" style="width:60px;" onchange="changePageSize('invt_statistics_form', this.value);">
						<option th:each="pageSize : ${pageSizeList}" th:text="${pageSize}"
							th:value="${pageSize}" th:selected="${pageSize == pageInfo.pageSize} ? 'selected'"></option>
					</select>


text:
<?php

namespace Drupal\search\Tests;

/**
 * Indexes content and tests the advanced search form.
 *
 * @group search
 */
class SearchAdvancedSearchFormTest extends SearchTestBase {

  /**
   * A node to use for testing.
   *
   * @var \Drupal\node\NodeInterface
   */
  protected $node;

  protected function setUp() {
    parent::setUp();
    // Create and log in user.
    $test_user = $this->drupalCreateUser(['access content', 'search content', 'use advanced search', 'administer nodes']);
    $this->drupalLogin($test_user);

    // Create initial node.
    $this->node = $this->drupalCreateNode();

    // First update the index. This does the initial processing.
    $this->container->get('plugin.manager.search')->createInstance('node_search')->updateIndex();

    // Then, run the shutdown function. Testing is a unique case where indexing
    // and searching has to happen in the same request, so running the shutdown
    // function manually is needed to finish the indexing process.
    search_update_totals();
  }

  /**
   * Tests advanced search by node type.
   */
  public function testNodeType() {
    // Verify some properties of the node that was created.
    $this->assertTrue($this->node->getType() == 'page', 'Node type is Basic page.');
    $dummy_title = 'Lorem ipsum';
    $this->assertNotEqual($dummy_title, $this->node->label(), "Dummy title doesn't equal node title.");

    // Search for the dummy title with a GET query.
    $this->drupalGet('search/node', ['query' => ['keys' => $dummy_title]]);
    $this->assertNoText($this->node->label(), 'Basic page node is not found with dummy title.');

    // Search for the title of the node with a GET query.
    $this->drupalGet('search/node', ['query' => ['keys' => $this->node->label()]]);
    $this->assertText($this->node->label(), 'Basic page node is found with GET query.');

    // Search for the title of the node with a POST query.
    $edit = ['or' => $this->node->label()];
    $this->drupalPostForm('search/node', $edit, t('Advanced search'));
    $this->assertText($this->node->label(), 'Basic page node is found with POST query.');

    // Search by node type.
    $this->drupalPostForm('search/node', array_merge($edit, ['type[page]' => 'page']), t('Advanced search'));
    $this->assertText($this->node->label(), 'Basic page node is found with POST query and type:page.');

    $this->drupalPostForm('search/node', array_merge($edit, ['type[article]' => 'article']), t('Advanced search'));
    $this->assertText('search yielded no results', 'Article node is not found with POST query and type:article.');
  }

  /**
   * Tests that after submitting the advanced search form, the form is refilled.
   */
  public function testFormRefill() {
    $edit = [
      'keys' => 'cat',
      'or' => 'dog gerbil',
      'phrase' => 'pets are nice',
      'negative' => 'fish snake',
      'type[page]' => 'page',
    ];
    $this->drupalPostForm('search/node', $edit, t('Advanced search'));

    // Test that the encoded query appears in the page title. Only test the
    // part not including the quote, because assertText() cannot seem to find
    // the quote marks successfully.
    $this->assertText('Search for cat dog OR gerbil -fish -snake');

    // Verify that all of the form fields are filled out.
    foreach ($edit as $key => $value) {
      if ($key != 'type[page]') {
        $elements = $this->xpath('//input[@name=:name]', [':name' => $key]);
        $this->assertTrue(isset($elements[0]) && $elements[0]['value'] == $value, "Field $key is set to $value");
      }
      else {
        $elements = $this->xpath('//input[@name=:name]', [':name' => $key]);
        $this->assertTrue(isset($elements[0]) && !empty($elements[0]['checked']), "Field $key is checked");
      }
    }

    // Now test by submitting the or/not part of the query in the main
    // search box, and verify that the advanced form is not filled out.
    // (It shouldn't be filled out unless you submit values in those fields.)
    $edit2 = ['keys' => 'cat dog OR gerbil -fish -snake'];
    $this->drupalPostForm('search/node', $edit2, t('Advanced search'));
    $this->assertText('Search for cat dog OR gerbil -fish -snake');
    foreach ($edit as $key => $value) {
      if ($key != 'type[page]') {
        $elements = $this->xpath('//input[@name=:name]', [':name' => $key]);
        $this->assertFalse(isset($elements[0]) && $elements[0]['value'] == $value, "Field $key is not set to $value");
      }
    }
  }

}


text:
'''
This Python script is part of the easytags plug-in for the Vim text editor. The
Python Interface to Vim is used to load this script which accelerates dynamic
syntax highlighting by reimplementing tag file reading and :syntax command
generation in Python with a focus on doing the least amount of work.

Author: Peter Odding <peter@peterodding.com>
Last Change: March 8, 2014
URL: http://peterodding.com/code/vim/easytags
'''

# TODO Cache the contents of tags files to further improve performance?

import re
import vim
import sys

def easytags_ping():
    print 'it works!'

def easytags_gensyncmd(tagsfiles, filetype, tagkinds, syntaxgroup, prefix, suffix, filters, ignoresyntax):
    # Get arguments from Vim.
    if filters:
        tagkinds = filters['kind']
    # Shallow parse tags files for matching identifiers.
    pattern = '^([^\t]+)\t[^\t]+\t[^\t]+\t' + tagkinds + '\tlanguage:' + re.escape(filetype)
    compiled_pattern = re.compile(pattern, re.IGNORECASE)
    matches = {}
    for fname in tagsfiles:
        handle = open(fname)
        for line in handle:
            m = compiled_pattern.match(line)
            if m and ('match' not in filters or re.search(filters['match'], line)) \
                    and ('nomatch' not in filters or not re.search(filters['nomatch'], line)):
                matches[m.group(1)] = True
        handle.close()
    # Generate Vim :syntax command to highlight identifiers.
    patterns, commands = [], []
    counter, limit = 0, 1024 * 20
    to_escape = re.compile(r'[.*^$/\\~\[\]]')
    for ident in matches.keys():
        escaped = to_escape.sub(r'\\\g<0>', ident)
        patterns.append(escaped)
        counter += len(escaped)
        if counter > limit:
            commands.append(_easytags_makecmd(syntaxgroup, prefix, suffix, patterns, ignoresyntax))
            patterns = []
            counter = 0
    if patterns:
        commands.append(_easytags_makecmd(syntaxgroup, prefix, suffix, patterns, ignoresyntax))
    return ' | '.join(commands)

def _easytags_makecmd(syntaxgroup, prefix, suffix, patterns, ignoresyntax):
    template = r'syntax match %s /%s\%%(%s\)%s/ containedin=ALLBUT,%s'
    return template % (syntaxgroup, prefix, r'\|'.join(patterns), suffix, ignoresyntax)


text:
package selfsigned

import (
	"context"
	"crypto"
	"crypto/x509"
	"errors"
	"fmt"

	corev1 "k8s.io/api/core/v1"
	k8sErrors "k8s.io/apimachinery/pkg/api/errors"
	corelisters "k8s.io/client-go/listers/core/v1"
	"k8s.io/client-go/tools/record"

	apiutil "github.com/jetstack/cert-manager/pkg/api/util"
	cmapi "github.com/jetstack/cert-manager/pkg/apis/certmanager/v1"
	controllerpkg "github.com/jetstack/cert-manager/pkg/controller"
	"github.com/jetstack/cert-manager/pkg/controller/certificaterequests"
	crutil "github.com/jetstack/cert-manager/pkg/controller/certificaterequests/util"
	"github.com/jetstack/cert-manager/pkg/issuer"
	logf "github.com/jetstack/cert-manager/pkg/logs"
	cmerrors "github.com/jetstack/cert-manager/pkg/util/errors"
	"github.com/jetstack/cert-manager/pkg/util/kube"
	"github.com/jetstack/cert-manager/pkg/util/pki"
)

const (
	CRControllerName = "certificaterequests-issuer-selfsigned"
	emptyDNMessage   = "Certificate will be issued with an empty Issuer DN, which contravenes RFC 5280 and could break some strict clients"
)

type signingFn func(*x509.Certificate, *x509.Certificate, crypto.PublicKey, interface{}) ([]byte, *x509.Certificate, error)

type SelfSigned struct {
	issuerOptions controllerpkg.IssuerOptions
	secretsLister corelisters.SecretLister

	reporter *crutil.Reporter
	recorder record.EventRecorder

	// Used for testing to get reproducible resulting certificates
	signingFn signingFn
}

func init() {
	// create certificate request controller for selfsigned issuer
	controllerpkg.Register(CRControllerName, func(ctx *controllerpkg.Context) (controllerpkg.Interface, error) {
		return controllerpkg.NewBuilder(ctx, CRControllerName).
			For(certificaterequests.New(apiutil.IssuerSelfSigned, NewSelfSigned(ctx))).
			Complete()
	})
}

func NewSelfSigned(ctx *controllerpkg.Context) *SelfSigned {
	return &SelfSigned{
		issuerOptions: ctx.IssuerOptions,
		secretsLister: ctx.KubeSharedInformerFactory.Core().V1().Secrets().Lister(),
		reporter:      crutil.NewReporter(ctx.Clock, ctx.Recorder),
		recorder:      ctx.Recorder,
		signingFn:     pki.SignCertificate,
	}
}

func (s *SelfSigned) Sign(ctx context.Context, cr *cmapi.CertificateRequest, issuerObj cmapi.GenericIssuer) (*issuer.IssueResponse, error) {
	log := logf.FromContext(ctx, "sign")

	resourceNamespace := s.issuerOptions.ResourceNamespace(issuerObj)

	secretName, ok := cr.ObjectMeta.Annotations[cmapi.CertificateRequestPrivateKeyAnnotationKey]
	if !ok || secretName == "" {
		message := fmt.Sprintf("Annotation %q missing or reference empty",
			cmapi.CertificateRequestPrivateKeyAnnotationKey)
		err := errors.New("secret name missing")

		s.reporter.Failed(cr, err, "MissingAnnotation", message)
		log.Error(err, message)

		return nil, nil
	}

	privatekey, err := kube.SecretTLSKey(ctx, s.secretsLister, cr.Namespace, secretName)
	if k8sErrors.IsNotFound(err) {
		message := fmt.Sprintf("Referenced secret %s/%s not found", cr.Namespace, secretName)

		s.reporter.Pending(cr, err, "MissingSecret", message)
		log.Error(err, message)

		return nil, nil
	}

	if cmerrors.IsInvalidData(err) {
		message := fmt.Sprintf("Failed to get key %q referenced in annotation %q",
			secretName, cmapi.CertificateRequestPrivateKeyAnnotationKey)

		s.reporter.Pending(cr, err, "ErrorParsingKey", message)
		log.Error(err, message)

		return nil, nil
	}

	if err != nil {
		// We are probably in a network error here so we should backoff and retry
		message := fmt.Sprintf("Failed to get certificate key pair from secret %s/%s", resourceNamespace, secretName)
		s.reporter.Pending(cr, err, "ErrorGettingSecret", message)
		log.Error(err, message)
		return nil, err
	}

	template, err := pki.GenerateTemplateFromCertificateRequest(cr)
	if err != nil {
		message := "Error generating certificate template"
		s.reporter.Failed(cr, err, "ErrorGenerating", message)
		log.Error(err, message)
		return nil, nil
	}

	template.CRLDistributionPoints = issuerObj.GetSpec().SelfSigned.CRLDistributionPoints

	if template.Subject.String() == "" {
		// RFC 5280 (https://tools.ietf.org/html/rfc5280#section-4.1.2.4) says that:
		// "The issuer field MUST contain a non-empty distinguished name (DN)."
		// Since we're creating a self-signed cert, the issuer will match whatever is
		// in the template's subject DN.
		log.V(logf.DebugLevel).Info("issued cert will have an empty issuer DN, which contravenes RFC 5280. emitting warning event")
		s.recorder.Event(cr, corev1.EventTypeWarning, "BadConfig", emptyDNMessage)
	}

	// extract the public component of the key
	publickey, err := pki.PublicKeyForPrivateKey(privatekey)
	if err != nil {
		message := "Failed to get public key from private key"
		s.reporter.Failed(cr, err, "ErrorPublicKey", message)
		log.Error(err, message)
		return nil, nil
	}

	ok, err = pki.PublicKeysEqual(publickey, template.PublicKey)
	if err != nil || !ok {

		if err == nil {
			err = errors.New("CSR not signed by referenced private key")
		}

		message := "Error generating certificate template"
		s.reporter.Failed(cr, err, "ErrorKeyMatch", message)
		log.Error(err, message)

		return nil, nil
	}

	// sign and encode the certificate
	certPem, _, err := s.signingFn(template, template, publickey, privatekey)
	if err != nil {
		message := "Error signing certificate"
		s.reporter.Failed(cr, err, "ErrorSigning", message)
		log.Error(err, message)
		return nil, nil
	}

	log.V(logf.DebugLevel).Info("self signed certificate issued")

	// We set the CA to the returned certificate here since this is self signed.
	return &issuer.IssueResponse{
		Certificate: certPem,
		CA:          certPem,
	}, nil
}


text:
#include "greentop/enum/IncludeItem.h"

#include <stdexcept>

#include "greentop/Enum.h"

namespace greentop {

const std::string IncludeItem::ALL = "ALL";
const std::string IncludeItem::DEPOSITS_WITHDRAWALS = "DEPOSITS_WITHDRAWALS";
const std::string IncludeItem::EXCHANGE = "EXCHANGE";
const std::string IncludeItem::POKER_ROOM = "POKER_ROOM";

IncludeItem::IncludeItem() {
    valid = false;
};

IncludeItem::IncludeItem(const std::string& v) {

    if (v != ALL &&
        v != DEPOSITS_WITHDRAWALS &&
        v != EXCHANGE &&
        v != POKER_ROOM) {
        throw std::invalid_argument("Invalid IncludeItem: " + v);
    }

    value = v;
    valid = true;
}

bool IncludeItem::operator<(const IncludeItem& other) const {
    return value < other.value;
}

bool IncludeItem::operator==(const IncludeItem& other) const {
    return value == other.value;
}

}


text:
OilCharLiteral :: OilCharLiteral ( const SourceRef & Ref, char32_t Value ):
	Value ( Value ),
	Ref ( Ref )
{
}

OilCharLiteral :: ~OilCharLiteral ()
{
}

char32_t OilCharLiteral :: GetValue () const
{

	return Value;

}

bool OilCharLiteral :: IsConstant () const
{

	return true;

}

IOilPrimary :: PrimaryType OilCharLiteral :: GetPrimaryType () const
{

	return kPrimaryType_CharLiteral;

}

const SourceRef & OilCharLiteral :: GetSourceRef () const
{

	return Ref;

}


text:
`ExceptionNotifier::HatoNotifier` is a custom notifier for [Exception Notification](http://smartinez87.github.io/exception_notification/). It sends exception notification via [Hato](https://github.com/kentaro/hato).

## Usage

As other exception notifiers, add settings at the environments:

  * `host` is the host of Hato server
  * `port` is the port of the server (optional, default is `9699`)
  * `api_key` is to set the API key if the server requires it (optional)
  * `template` is to set templates for tag and message to be sent to Hato

### Example

```ruby
Whatever::Application.config.middleware.use ExceptionNotification::Rack,
  hato: {
    host:     'localhost',
    port:     9699,
    api_key:  'YOUR API KEY',
    template: {
        tag:     ->(exception, options) { "exception.#{exception.class}" },
        message: ->(exception, options) { "Exception: #{exception.class}: #{exception.message}" },
    },
  }
```

## Installation

Add this line to your application's Gemfile:

    gem 'exception_notification-hato_notifier'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install exception_notification-hato_notifier

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request


text:
This repository contains a collection of ready-to-deploy serverless data feeds and demo applications that utilize the [Flex.io API](https://www.flex.io) for moving, processing and integrating data in the cloud.

## Introduction

Please fork and utilize these examples at will; we hope you find them useful.  All code is available under the [MIT License](http://opensource.org/licenses/MIT); any other content is available under the [Creative Commons Attribution 4.0 International License](http://creativecommons.org/licenses/by/4.0/).

If you have question or would like more information, please feel free to email the Flex.io developer support team at [support@flex.io](mailto:support@flex.io?subject=Flex.io%20Examples%20Repo) or use the chat button at the bottom of the [Flex.io website](https://www.flex.io).

## Examples

Each example contains a `README.md` with an explanation of what it does and how it works. Each example also includes at least one `pipe.js` file that can be used to install the pipe in your Flex.io account:

```
node pipe.js
```

**Have an example?** Submit a PR or [open an issue](https://github.com/flexiodata/examples/issues).

### Demo App Examples

| Example | Demo App | Source |
|:--------|:---------|:------:|
| **Chicago Crime Map**
 Read a table from local storage in Flex.io, filter its rows by year and output the result in JSON. | [Chicago Crime Map](https://flexiodata.github.io/examples/demo-chicago-crime-map/) | [Source](https://github.com/flexiodata/examples/tree/master/demo-chicago-crime-map) |
| **Contact Refinement**
 Request a CSV from GitHub, convert it to a table, select a subset of columns, transform the result to uppercase and output the result in JSON. | [Contact Refinement](https://flexiodata.github.io/examples/demo-contact-refinement/) | [Source](https://github.com/flexiodata/examples/tree/master/demo-contact-refinement) |
| **Saastr Podcast Search**
 Request a CSV from GitHub, convert it to a table, select a subset of columns, filter it based on a search string from an HTML input and output the result in JSON. | [Saastr Podcast Search](https://flexiodata.github.io/examples/demo-saastr-podcast-search/) | [Source](https://github.com/flexiodata/examples/tree/master/demo-saastr-podcast-search) |
| **Webpage Thumbnail Generator**
 Load the HTML contents of the webpage, reduce it in size to a thumbnail and output it as a PNG image. | [Webpage Thumbnail Generator](https://flexiodata.github.io/examples/demo-webpage-thumbnail-generator/) | [Source](https://github.com/flexiodata/examples/tree/master/demo-webpage-thumbnail-generator) |
| **Webpage Word Cloud Generator**
 Parse the HTML contents of the webpage and return a wordcloud of the words on that page. | [Webpage Word Cloud Generator](https://flexiodata.github.io/examples/demo-webpage-word-cloud-generator/) | [Source](https://github.com/flexiodata/examples/tree/master/demo-webpage-word-cloud-generator) |
| **Upload to Amazon S3**
 Upload to Amazon S3. | [Upload to Amazon S3](https://flexiodata.github.io/examples/demo-upload-to-amazon-s3/) | [Source](https://github.com/flexiodata/examples/tree/master/demo-upload-to-amazon-s3) |

### Transfer Examples

| Example | Source |
|:--------|--------|
| **Copy Files Between Cloud Storage**
 Copy files between cloud storage providers such as AWS S3 and Dropbox. Filter the file transfer based on file name, file size and modified date. | [Source](https://github.com/flexiodata/examples/tree/master/transfer-copy-files-between-cloud-storage) |
| **Bulk Load CSV Files into Elasticsearch**
 Copy CSV files cloud storage providers into Elasticsearch. Load from an API, like Twilio or a database, like Postgres. | [Source](https://github.com/flexiodata/examples/tree/master/transfer-csv-to-elasticsearch) |

### Community Examples

| Example | Location | Source |
|:--------|:---------|:------:|

## Contributing

Do you have an example you'd like to share? We are happy to accept more examples from the community.

### Adding a community example

We love hearing about projects happening in the community. Feel free to add your serverless project to our growing list.

1. Fork this repo.

2. Add `example`, `location`, and optionally a link to the `source` to the [Community Examples](#Community-Examples) section above. Always add your examples to the end of the list. To be fair, the order is first-come-first-serve.

3. Open a new pull request with your example.


text:
"""
Common distribution functions for plasmas, such as the Maxwellian or
Kappa distributions. Functionality is intended to include generation,
fitting and calculation.
"""
__all__ = [
    "Maxwellian_1D",
    "Maxwellian_velocity_2D",
    "Maxwellian_velocity_3D",
    "Maxwellian_speed_1D",
    "Maxwellian_speed_2D",
    "Maxwellian_speed_3D",
    "kappa_velocity_1D",
    "kappa_velocity_3D",
]

import astropy.units as u
import numpy as np

from scipy.special import gamma

from plasmapy.formulary.speeds import kappa_thermal_speed, thermal_speed
from plasmapy.particles import particle_input, ParticleLike
from plasmapy.utils._units_definitions import (
    SPEED_DISTRIBUTION_UNITS_1D,
    SPEED_DISTRIBUTION_UNITS_2D,
    SPEED_DISTRIBUTION_UNITS_3D,
    SPEED_UNITS,
)

def _v_drift_conversion(v_drift):
    # Helper method to assign equivalent value in SPEED_UNITS and/or remove units
    if isinstance(v_drift, u.Quantity):
        v_drift = v_drift.to_value(SPEED_UNITS)
    return v_drift

@particle_input
def Maxwellian_1D(
    v, T, particle: ParticleLike = "e", v_drift=0, vTh=np.nan, units="units"
):
    r"""
    Probability distribution function of velocity for a Maxwellian
    distribution in 1D.

    Returns the probability density function at the velocity ``v`` in m/s
    to find a particle ``particle`` in a plasma of temperature ``T``
    following the Maxwellian distribution function.

    Parameters
    ----------
    v : `~astropy.units.Quantity`
        The velocity in units convertible to m/s.

    T : `~astropy.units.Quantity`
        The temperature in kelvin.

    particle : `str`, optional
        Representation of the particle species(e.g., ``'p'`` for protons,
        ``'D+'`` for deuterium, or ``'He-4 +1'`` for singly ionized
        helium-4), which defaults to electrons.

    v_drift : `~astropy.units.Quantity`, optional
        The drift velocity in units convertible to m/s.

    vTh : `~astropy.units.Quantity`, optional
        Thermal velocity (most probable velocity) in m/s. This is used for
        optimization purposes to avoid re-calculating ``vTh``, for example
        when integrating over velocity-space.

    units : `str`, optional
        Selects whether to run function with units and unit checks (when
        equal to "units") or to run as unitless (when equal to "unitless").
        The unitless version is substantially faster for intensive
        computations.

    Returns
    -------
    f : `~astropy.units.Quantity`
        Probability density in units of velocity\ :sup:`-1`\ , normalized so that
        :math:`\int_{-∞}^{+∞} f(v) dv = 1`.

    Raises
    ------
    `TypeError`
        The parameter arguments are not Quantities and
        cannot be converted into Quantities.

    `~astropy.units.UnitConversionError`
        If the parameters are not in appropriate units.

    `ValueError`
        If the temperature is negative, or the particle mass or charge state
        cannot be found.

    Notes
    -----
    In one dimension, the Maxwellian distribution function for a particle of
    mass m, velocity v, a drift velocity V and with temperature T is:

    .. math::

        f = \sqrt{\frac{m}{2 \pi k_B T}} e^{-\frac{m}{2 k_B T} (v-V)^2}
        \equiv \frac{1}{\sqrt{\pi v_{Th}^2}} e^{-(v - v_{drift})^2 / v_{Th}^2}

    where :math:`v_{Th} = \sqrt{2 k_B T / m}` is the thermal speed

    Examples
    --------
    >>> from astropy import units as u
    >>> v=1*u.m/u.s
    >>> Maxwellian_1D(v=v, T=30000 * u.K, particle='e', v_drift=0 * u.m / u.s)
    <Quantity 5.9163...e-07 s / m>
    """

    if units == "units":
        # unit checks and conversions
        # checking velocity units
        v = v.to_value(SPEED_UNITS)
        # Catching case where drift velocities have default values,
        v_drift = _v_drift_conversion(v_drift)
        # convert temperature to kelvin
        T = T.to_value(u.K, equivalencies=u.temperature_energy())
        if not np.isnan(vTh):
            # check units of thermal velocity
            vTh = vTh.to_value(SPEED_UNITS)

    if np.isnan(vTh):
        # get thermal speed
        vTh = thermal_speed(
            T << u.K, particle=particle, method="most_probable"
        ).to_value(SPEED_UNITS)

    # Get thermal velocity squared
    vThSq = vTh**2
    # Get square of relative particle velocity
    vSq = (v - v_drift) ** 2
    # calculating distribution function
    coeff = (vThSq * np.pi) ** (-1 / 2)
    expTerm = np.exp(-vSq / vThSq)
    distFunc = coeff * expTerm
    if units == "units":
        return distFunc << SPEED_DISTRIBUTION_UNITS_1D
    elif units == "unitless":
        return distFunc

@particle_input
def Maxwellian_velocity_2D(
    vx,
    vy,
    T,
    particle: ParticleLike = "e",
    vx_drift=0,
    vy_drift=0,
    vTh=np.nan,
    units="units",
):
    r"""
    Probability distribution function of velocity for a Maxwellian
    distribution in 2D.

    Return the probability density function for finding a particle with
    velocity components ``vx`` and ``vy`` in m/s in an equilibrium plasma of
    temperature ``T`` which follows the 2D Maxwellian distribution function.
    This function assumes Cartesian coordinates.

    Parameters
    ----------
    vx : `~astropy.units.Quantity`
        The velocity in x-direction units convertible to m/s.

    vy : `~astropy.units.Quantity`
        The velocity in y-direction units convertible to m/s.

    T : `~astropy.units.Quantity`
        The temperature, preferably in kelvin.

    particle : `str`, optional
        Representation of the particle species [e.g., ``'p'`` for protons,
        ``'D+'`` for deuterium, or ``'He-4 +1'`` for :math:`He_4^{+1}`
        (singly ionized helium-4)], which defaults to electrons.

    vx_drift : `~astropy.units.Quantity`, optional
        The drift velocity in x-direction in units convertible to m/s.

    vy_drift : `~astropy.units.Quantity`, optional
        The drift velocity in y-direction in units convertible to m/s.

    vTh : `~astropy.units.Quantity`, optional
        Thermal velocity (most probable) in m/s. This is used for
        optimization purposes to avoid re-calculating ``vTh``, for example
        when integrating over velocity-space.

    units : `str`, optional
        Selects whether to run function with units and unit checks (when
        equal to "units") or to run as unitless (when equal to "unitless").
        The unitless version is substantially faster for intensive
        computations.

    Returns
    -------
    f : `~astropy.units.Quantity`
        Probability density in Velocity\ :sup:`-1`\ , normalized so that
        :math:`\iiint_{0}^∞ f(\vec{v}) d\vec{v} = 1`.

    Raises
    ------
    TypeError
        A parameter argument is not a `~astropy.units.Quantity` and
        cannot be converted into a `~astropy.units.Quantity`.

    ~astropy.units.UnitConversionError
        If the parameters is not in appropriate units.

    ValueError
        If the temperature is negative, or the particle mass or charge state
        cannot be found.

    Notes
    -----
    In 2D, the Maxwellian velocity distribution function describing
    the distribution of particles with speed :math:`v` in a plasma with
    temperature :math:`T` is given by:

    .. math::

        f = (\pi v_{Th}^2)^{-1} \exp \left [-(\vec{v} -
        \vec{V}_{drift})^2 / v_{Th}^2 \right ]

    where :math:`v_{Th} = \sqrt{2 k_B T / m}` is the thermal speed.

    See Also
    --------
    Maxwellian_1D

    Examples
    --------
    >>> from astropy import units as u
    >>> v=1 * u.m / u.s
    >>> Maxwellian_velocity_2D(vx=v,
    ... vy=v,
    ... T=30000*u.K,
    ... particle='e',
    ... vx_drift=0 * u.m / u.s,
    ... vy_drift=0 * u.m / u.s)
    <Quantity 3.5002...e-13 s2 / m2>

    """
    if units == "units":
        # unit checks and conversions
        # checking velocity units
        vx = vx.to_value(SPEED_UNITS)
        vy = vy.to_value(SPEED_UNITS)
        # catching case where drift velocities have default values, they
        # need to be assigned units
        vx_drift = _v_drift_conversion(vx_drift)
        vy_drift = _v_drift_conversion(vy_drift)

        # convert temperature to kelvin
        T = T.to_value(u.K, equivalencies=u.temperature_energy())
        if not np.isnan(vTh):
            # check units of thermal velocity
            vTh = vTh.to_value(SPEED_UNITS)

    if np.isnan(vTh):
        # get thermal speed
        vTh = thermal_speed(
            T << u.K, particle=particle, method="most_probable"
        ).to_value(SPEED_UNITS)

    # accounting for thermal velocity in 2D
    vThSq = vTh**2
    # Get square of relative particle velocity
    vSq = (vx - vx_drift) ** 2 + (vy - vy_drift) ** 2
    # calculating distribution function
    coeff = (vThSq * np.pi) ** (-1)
    expTerm = np.exp(-vSq / vThSq)
    distFunc = coeff * expTerm
    if units == "units":
        return distFunc << SPEED_DISTRIBUTION_UNITS_2D
    elif units == "unitless":
        return distFunc

@particle_input
def Maxwellian_velocity_3D(
    vx,
    vy,
    vz,
    T,
    particle: ParticleLike = "e",
    vx_drift=0,
    vy_drift=0,
    vz_drift=0,
    vTh=np.nan,
    units="units",
):
    r"""
    Probability distribution function of velocity for a Maxwellian
    distribution in 3D.

    Return the probability density function for finding a particle with
    velocity components ``vx``, ``vy``, and ``vz`` in m/s in an equilibrium
    plasma of temperature ``T`` which follows the 3D Maxwellian distribution
    function. This function assumes Cartesian coordinates.

    Parameters
    ----------
    vx : `~astropy.units.Quantity`
        The velocity in x-direction in units convertible to m/s.

    vy : `~astropy.units.Quantity`
        The velocity in y-direction units convertible to m/s.

    vz : `~astropy.units.Quantity`
        The velocity in z-direction units convertible to m/s.

    T : `~astropy.units.Quantity`
        The temperature, preferably in kelvin.

    particle : `str`, optional
        Representation of the particle species (e.g., ``'p'`` for protons,
        ``'D+'`` for deuterium, or ``'He-4 +1'`` for
        singly ionized helium-4), which defaults to electrons.

    vx_drift : `~astropy.units.Quantity`, optional
        The drift velocity in x-direction units convertible to m/s.

    vy_drift : `~astropy.units.Quantity`, optional
        The drift velocity in y-direction units convertible to m/s.

    vz_drift : `~astropy.units.Quantity`, optional
        The drift velocity in z-direction units convertible to m/s.

    vTh : `~astropy.units.Quantity`, optional
        Thermal velocity (most probable) in m/s. This is used for
        optimization purposes to avoid re-calculating ``vTh``, for example
        when integrating over velocity-space.

    units : `str`, optional
        Selects whether to run function with units and unit checks (when
        equal to "units") or to run as unitless (when equal to "unitless").
        The unitless version is substantially faster for intensive
        computations.

    Returns
    -------
    f : `~astropy.units.Quantity`
        Probability density in Velocity^-1, normalized so that
        :math:`\iiint_{0}^∞ f(\vec{v}) d\vec{v} = 1`.

    Raises
    ------
    `TypeError`
        A parameter argument is not a `~astropy.units.Quantity` and
        cannot be converted into a `~astropy.units.Quantity`.

    `~astropy.units.UnitConversionError`
        If the parameters is not in appropriate units.

    `ValueError`
        If the temperature is negative, or the particle mass or charge state
        cannot be found.

    Notes
    -----
    In 3D, the Maxwellian speed distribution function describing
    the distribution of particles with speed :math:`v` in a plasma with
    temperature :math:`T` is given by:

    .. math::

        f = (\pi v_{Th}^2)^{-3/2} \exp \left [-(\vec{v} -
        \vec{V}_{drift})^2 / v_{Th}^2 \right ]

    where :math:`v_{Th} = \sqrt{2 k_B T / m}` is the thermal speed.

    See Also
    --------
    Maxwellian_1D

    Examples
    --------
    >>> from astropy import units as u
    >>> v=1 * u.m / u.s
    >>> Maxwellian_velocity_3D(vx=v,
    ... vy=v,
    ... vz=v,
    ... T=30000 * u.K,
    ... particle='e',
    ... vx_drift=0 * u.m / u.s,
    ... vy_drift=0 * u.m / u.s,
    ... vz_drift=0 * u.m / u.s)
    <Quantity 2.0708...e-19 s3 / m3>

    """
    if units == "units":
        # unit checks and conversions
        # checking velocity units
        vx = vx.to_value(SPEED_UNITS)
        vy = vy.to_value(SPEED_UNITS)
        vz = vz.to_value(SPEED_UNITS)
        # catching case where drift velocities have default values, they
        # need to be assigned units
        vx_drift = _v_drift_conversion(vx_drift)
        vy_drift = _v_drift_conversion(vy_drift)
        vz_drift = _v_drift_conversion(vz_drift)
        # convert temperature to kelvin
        T = T.to_value(u.K, equivalencies=u.temperature_energy())
        if not np.isnan(vTh):
            # check units of thermal velocity
            vTh = vTh.to_value(SPEED_UNITS)

    if np.isnan(vTh):
        # get thermal velocity and thermal velocity squared
        vTh = thermal_speed(
            T << u.K, particle=particle, method="most_probable"
        ).to_value(SPEED_UNITS)

    # accounting for thermal velocity in 3D
    vThSq = vTh**2
    # Get square of relative particle velocity
    vSq = (vx - vx_drift) ** 2 + (vy - vy_drift) ** 2 + (vz - vz_drift) ** 2
    # calculating distribution function
    coeff = (vThSq * np.pi) ** (-3 / 2)
    expTerm = np.exp(-vSq / vThSq)
    distFunc = coeff * expTerm
    if units == "units":
        return distFunc << SPEED_DISTRIBUTION_UNITS_3D
    elif units == "unitless":
        return distFunc

@particle_input
def Maxwellian_speed_1D(
    v, T, particle: ParticleLike = "e", v_drift=0, vTh=np.nan, units="units"
):
    r"""
    Probability distribution function of speed for a Maxwellian distribution
    in 1D.

    Return the probability density function for finding a particle with
    speed ``v`` in m/s in an equilibrium plasma of temperature ``T`` which
    follows the Maxwellian distribution function.

    Parameters
    ----------
    v : `~astropy.units.Quantity`
        The speed in units convertible to m/s.

    T : `~astropy.units.Quantity`
        The temperature, preferably in kelvin.

    particle : `str`, optional
        Representation of the particle species [e.g., ``'p'`` for protons, ``'D+'``
        for deuterium, or ``'He-4 +1'`` for :math:`He_4^{+1}`
        (singly ionized helium-4)], which defaults to electrons.

    v_drift : `~astropy.units.Quantity`
        The drift speed in units convertible to m/s.

    vTh : `~astropy.units.Quantity`, optional
        Thermal velocity (most probable) in m/s. This is used for
        optimization purposes to avoid re-calculating ``vTh``, for example
        when integrating over velocity-space.

    units : `str`, optional
        Selects whether to run function with units and unit checks (when
        equal to "units") or to run as unitless (when equal to "unitless").
        The unitless version is substantially faster for intensive
        computations.

    Returns
    -------
    f : `~astropy.units.Quantity`
        Probability density in speed\ :sup:`-1`\ , normalized so that
        :math:`\int_{0}^∞ f(v) dv = 1`.

    Raises
    ------
    `TypeError`
        The parameter arguments are not Quantities and
        cannot be converted into Quantities.

    `~astropy.units.UnitConversionError`
        If the parameters is not in appropriate units.

    `ValueError`
        If the temperature is negative, or the particle mass or charge state
        cannot be found.

    Notes
    -----
    In one dimension, the Maxwellian speed distribution function describing
    the distribution of particles with speed :math:`v` in a plasma with
    temperature :math:`T` is given by:

    .. math::

       f(v) = 2 \frac{1}{(π v_{Th}^2)^{1/2}} \exp(-(v - V_{drift})^2 / v_{Th}^2 )

    where :math:`v_{Th} = \sqrt{2 k_B T / m}` is the thermal speed.

    Examples
    --------
    >>> from astropy import units as u
    >>> v=1 * u.m / u.s
    >>> Maxwellian_speed_1D(v=v, T=30000 * u.K, particle='e', v_drift=0 * u.m / u.s)
    <Quantity 1.1832...e-06 s / m>

    """
    if units == "units":
        # unit checks and conversions
        # checking velocity units
        v = v.to_value(SPEED_UNITS)
        # Catching case where drift velocities have default values, they
        # need to be assigned units
        v_drift = _v_drift_conversion(v_drift)
        # convert temperature to kelvin
        T = T.to_value(u.K, equivalencies=u.temperature_energy())
        if not np.isnan(vTh):
            # check units of thermal velocity
            vTh = vTh.to_value(SPEED_UNITS)

    if np.isnan(vTh):
        # get thermal velocity and thermal velocity squared
        vTh = thermal_speed(
            T << u.K, particle=particle, method="most_probable"
        ).to_value(SPEED_UNITS)

    # Get thermal velocity squared
    vThSq = vTh**2
    # Get square of relative particle velocity
    vSq = (v - v_drift) ** 2
    # calculating distribution function
    coeff = 2 * (vThSq * np.pi) ** (-1 / 2)
    expTerm = np.exp(-vSq / vThSq)
    distFunc = coeff * expTerm
    if units == "units":
        return distFunc << SPEED_DISTRIBUTION_UNITS_1D
    elif units == "unitless":
        return distFunc

@particle_input
def Maxwellian_speed_2D(
    v, T, particle: ParticleLike = "e", v_drift=0, vTh=np.nan, units="units"
):
    r"""
    Probability distribution function of speed for a Maxwellian distribution
    in 2D.

    Return the probability density function of finding a particle with speed components
    ``vx`` and ``vy`` in m/s in an equilibrium plasma of temperature
    ``T`` which follows the 2D Maxwellian distribution function. This
    function assumes Cartesian coordinates.

    Parameters
    ----------
    v: `~astropy.units.Quantity`
        The speed in units convertible to m/s.

    T: `~astropy.units.Quantity`
        The temperature, preferably in kelvin.

    particle: `str`, optional
        Representation of the particle species(e.g., ``'p'`` for protons, ``'D+'``
        for deuterium, or ``'He-4 +1'`` for singly ionized helium-4),
        which defaults to electrons.

    v_drift: `~astropy.units.Quantity`
        The drift speed in units convertible to m/s.

    vTh: `~astropy.units.Quantity`, optional
        Thermal velocity (most probable) in m/s. This is used for
        optimization purposes to avoid re-calculating ``vTh``, for example
        when integrating over velocity-space.

    units: `str`, optional
        Selects whether to run function with units and unit checks (when
        equal to "units") or to run as unitless (when equal to "unitless").
        The unitless version is substantially faster for intensive
        computations.

    Returns
    -------
    f : `~astropy.units.Quantity`
        Probability density in \ :sup:`-1`\ , normalized so that:
        :math:`\iiint_{0}^∞ f(\vec{v}) d\vec{v} = 1`.

    Raises
    ------
    `TypeError`
        A parameter argument is not a `~astropy.units.Quantity` and
        cannot be converted into a `~astropy.units.Quantity`.

    `~astropy.units.UnitConversionError`
        If the parameters is not in appropriate units.

    `ValueError`
        If the temperature is negative, or the particle mass or charge state
        cannot be found.

    Notes
    -----
    In 2D, the Maxwellian speed distribution function describing
    the distribution of particles with speed :math:`v` in a plasma with
    temperature :math:`T` is given by:

    .. math::

       f = 2 π v (π v_{Th}^2)^{-1} \exp(-v^2 / v_{Th}^2)

    where :math:`v_{Th} = \sqrt{2 k_B T / m}` is the thermal speed.

    See Also
    --------
    Maxwellian_speed_1D

    Examples
    --------
    >>> from astropy import units as u
    >>> v=1 * u.m / u.s
    >>> Maxwellian_speed_2D(v=v, T=30000 * u.K, particle='e', v_drift=0 * u.m / u.s)
    <Quantity 2.199...e-12 s / m>

    """
    if v_drift != 0:
        raise NotImplementedError("Non-zero drift speed is work in progress.")
    if units == "units":
        # unit checks and conversions
        # checking velocity units
        v = v.to_value(SPEED_UNITS)
        # Catching case where drift velocity has default value, and
        # needs to be assigned units
        v_drift = _v_drift_conversion(v_drift)
        # convert temperature to kelvin
        T = T.to_value(u.K, equivalencies=u.temperature_energy())
        if not np.isnan(vTh):
            # check units of thermal velocity
            vTh = vTh.to_value(SPEED_UNITS)

    if np.isnan(vTh):
        # get thermal velocity and thermal velocity squared
        vTh = thermal_speed(
            T << u.K, particle=particle, method="most_probable"
        ).to_value(SPEED_UNITS)

    # getting square of thermal speed
    vThSq = vTh**2
    # get square of relative particle speed
    vSq = (v - v_drift) ** 2
    # calculating distribution function
    coeff1 = (np.pi * vThSq) ** (-1)
    coeff2 = 2 * np.pi * (v - v_drift)
    expTerm = np.exp(-vSq / vThSq)
    distFunc = coeff1 * coeff2 * expTerm
    if units == "units":
        return distFunc << SPEED_DISTRIBUTION_UNITS_1D
    elif units == "unitless":
        return distFunc

@particle_input
def Maxwellian_speed_3D(
    v, T, particle: ParticleLike = "e", v_drift=0, vTh=np.nan, units="units"
):
    r"""
    Probability distribution function of speed for a Maxwellian
    distribution in 3D.

    Return the probability density function for finding a particle with
    speed components ``vx``, ``vy``, and ``vz`` in m/s in an equilibrium
    plasma of temperature ``T`` which follows the 3D Maxwellian
    distribution function. This function assumes Cartesian coordinates.

    Parameters
    ----------
    v : `~astropy.units.Quantity`
        The speed in units convertible to m/s.

    T : `~astropy.units.Quantity`
        The temperature, preferably in kelvin.

    particle : `str`, optional
        Representation of the particle species(e.g., ``'p'`` for protons, ``'D+'``
        for deuterium, or ``'He-4 +1'`` for :math:`He_4^{+1}`
        (singly ionized helium-4)), which defaults to electrons.

    v_drift : `~astropy.units.Quantity`
        The drift speed in units convertible to m/s.

    vTh : `~astropy.units.Quantity`, optional
        Thermal velocity (most probable) in m/s. This is used for
        optimization purposes to avoid re-calculating vTh, for example
        when integrating over velocity-space.

    units : `str`, optional
        Selects whether to run function with units and unit checks (when
        equal to "units") or to run as unitless (when equal to "unitless").
        The unitless version is substantially faster for intensive
        computations.

    Returns
    -------
    f : `~astropy.units.Quantity`
        Probability density in speed\ :sup:`-1`\ , normalized so that:
        :math:`\iiint_0^∞ f(\vec{v}) d\vec{v} = 1`.

    Raises
    ------
    `TypeError`
        A parameter argument is not a `~astropy.units.Quantity` and
        cannot be converted into a `~astropy.units.Quantity`.

    `~astropy.units.UnitConversionError`
        If the parameters is not in appropriate units.

    `ValueError`
        If the temperature is negative, or the particle mass or charge state
        cannot be found.

    Notes
    -----
    In 3D, the Maxwellian speed distribution function describing
    the distribution of particles with speed :math:`v` in a plasma with
    temperature :math:`T` is given by:

    .. math::

       f = 4 π v^{2} (π v_{Th}^2)^{-3/2} \exp(-v^{2} / v_{Th}^2)

    where :math:`v_{Th} = \sqrt{2 k_B T / m}` is the thermal speed.

    See Also
    --------
    Maxwellian_speed_1D

    Examples
    --------
    >>> from astropy import units as u
    >>> v=1 * u.m / u.s
    >>> Maxwellian_speed_3D(v=v, T=30000*u.K, particle='e', v_drift=0 * u.m / u.s)
    <Quantity 2.60235...e-18 s / m>

    """
    if v_drift != 0:
        raise NotImplementedError("Non-zero drift speed is work in progress.")
    if units == "units":
        # unit checks and conversions
        # checking velocity units
        v = v.to_value(SPEED_UNITS)
        # Catching case where drift velocity has default value, and
        # needs to be assigned units
        v_drift = _v_drift_conversion(v_drift)
        # convert temperature to kelvin
        T = T.to_value(u.K, equivalencies=u.temperature_energy())
        if not np.isnan(vTh):
            # check units of thermal velocity
            vTh = vTh.to_value(SPEED_UNITS)

    if np.isnan(vTh):
        # get thermal velocity and thermal velocity squared
        vTh = thermal_speed(
            T << u.K, particle=particle, method="most_probable"
        ).to_value(SPEED_UNITS)

    # getting square of thermal speed
    vThSq = vTh**2
    # get square of relative particle speed
    vSq = (v - v_drift) ** 2
    # calculating distribution function
    coeff1 = (np.pi * vThSq) ** (-3 / 2)
    coeff2 = 4 * np.pi * vSq
    expTerm = np.exp(-vSq / vThSq)
    distFunc = coeff1 * coeff2 * expTerm
    if units == "units":
        return distFunc << SPEED_DISTRIBUTION_UNITS_1D
    elif units == "unitless":
        return distFunc

@particle_input
def kappa_velocity_1D(
    v, T, kappa, particle: ParticleLike = "e", v_drift=0, vTh=np.nan, units="units"
):
    r"""
    Return the probability density at the velocity ``v`` in m/s
    to find a particle ``particle`` in a plasma of temperature ``T``
    following the Kappa distribution function in 1D. The slope of the
    tail of the Kappa distribution function is set by 'kappa', which
    must be greater than :math:`1/2`.

    Parameters
    ----------
    v : `~astropy.units.Quantity`
        The velocity in units convertible to m/s.

    T : `~astropy.units.Quantity`
        The temperature in kelvin.

    kappa : `~astropy.units.Quantity`
        The kappa parameter is a dimensionless number which sets the slope
        of the energy spectrum of suprathermal particles forming the tail
        of the Kappa velocity distribution function. Kappa must be greater
        than :math:`3/2`.

    particle : `str`, optional
        Representation of the particle species(e.g., ``'p`` for protons, ``'D+'``
        for deuterium, or ``'He-4 +1'`` for :math:`He_4^{+1}`
        (singly ionized helium-4)), which defaults to electrons.

    v_drift : `~astropy.units.Quantity`, optional
        The drift velocity in units convertible to m/s.

    vTh : `~astropy.units.Quantity`, optional
        Thermal velocity (most probable) in m/s. This is used for
        optimization purposes to avoid re-calculating ``vTh``, for example
        when integrating over velocity-space.

    units : `str`, optional
        Selects whether to run function with units and unit checks (when
        equal to ``"units"``) or to run as unitless (when equal to
        ``"unitless"``). The unitless version is substantially faster for
        intensive computations.

    Returns
    -------
    f : `~astropy.units.Quantity`
        Probability density in velocity\ :sup:`-1`\ , normalized so that
        :math:`\int_{-∞}^{+∞} f(v) dv = 1`.

    Raises
    ------
    `TypeError`
        A parameter argument is not a `~astropy.units.Quantity` and
        cannot be converted into a `~astropy.units.Quantity`.

    `~astropy.units.UnitConversionError`
        If the parameters is not in appropriate units.

    `ValueError`
        If the temperature is negative, or the particle mass or charge state
        cannot be found.

    Notes
    -----
    In one dimension, the Kappa velocity distribution function describing
    the distribution of particles with speed :math:`v` in a plasma with
    temperature :math:`T` and suprathermal parameter :math:`κ` is
    given by:

    .. math::

       f = A_κ \left(1 + \frac{(\vec{v} -
       \vec{V_{drift}})^2}{κ v_{Th},κ^2}\right)^{-κ}

    where :math:`v_{Th},κ` is the kappa thermal speed
    and :math:`A_κ = \frac{1}{\sqrt{π} κ^{3/2} v_{Th},κ^2
    \frac{Γ(κ + 1)}{Γ(κ - 1/2)}}`
    is the normalization constant.

    As :math:`κ → ∞`, the kappa distribution function converges to the
    Maxwellian distribution function.

    Examples
    --------
    >>> from astropy import units as u
    >>> v=1 * u.m / u.s
    >>> kappa_velocity_1D(v=v, T=30000*u.K, kappa=4, particle='e', v_drift=0 * u.m / u.s)
    <Quantity 6.75549...e-07 s / m>

    See Also
    --------
    kappa_velocity_3D
    ~plasmapy.formulary.speeds.kappa_thermal_speed
    """
    # must have kappa > 3/2 for distribution function to be valid
    if kappa <= 3 / 2:
        raise ValueError(f"Must have κ > 3/2, instead of {kappa}.")
    if units == "units":
        # unit checks and conversions
        # checking velocity units
        v = v.to_value(SPEED_UNITS)
        # catching case where drift velocities have default values
        v_drift = _v_drift_conversion(v_drift)

        # convert temperature to kelvin
        T = T.to_value(u.K, equivalencies=u.temperature_energy())
        if not np.isnan(vTh):
            # check units of thermal velocity
            vTh = vTh.to_value(SPEED_UNITS)

    if np.isnan(vTh):
        # get thermal velocity and thermal velocity squared
        vTh = kappa_thermal_speed(T << u.K, kappa, particle=particle).to_value(
            SPEED_UNITS
        )

    # Get thermal velocity squared and accounting for 1D instead of 3D
    vThSq = vTh**2
    # Get square of relative particle velocity
    vSq = (v - v_drift) ** 2
    # calculating distribution function
    expTerm = (1 + vSq / (kappa * vThSq)) ** (-kappa)
    coeff1 = 1 / (np.sqrt(np.pi) * kappa ** (3 / 2) * vTh)
    coeff2 = gamma(kappa + 1) / (gamma(kappa - 1 / 2))
    distFunc = coeff1 * coeff2 * expTerm
    if units == "units":
        return distFunc << SPEED_DISTRIBUTION_UNITS_1D
    elif units == "unitless":
        return distFunc

@particle_input
def kappa_velocity_3D(
    vx,
    vy,
    vz,
    T,
    kappa,
    particle: ParticleLike = "e",
    vx_drift=0,
    vy_drift=0,
    vz_drift=0,
    vTh=np.nan,
    units="units",
):
    r"""
    Return the probability density function for finding a particle with
    velocity components ``v_x``, ``v_y``, and ``v_z``in m/s in a suprathermal
    plasma of temperature ``T`` and parameter ``kappa`` which follows the
    3D Kappa distribution function. This function assumes Cartesian
    coordinates.

    Parameters
    ----------
    vx : `~astropy.units.Quantity`
        The velocity in x-direction units convertible to m/s.

    vy : `~astropy.units.Quantity`
        The velocity in y-direction units convertible to m/s.

    vz : `~astropy.units.Quantity`
        The velocity in z-direction units convertible to m/s.

    T : `~astropy.units.Quantity`
        The temperature, preferably in kelvin.

    kappa : `~astropy.units.Quantity`
        The kappa parameter is a dimensionless number which sets the slope
        of the energy spectrum of suprathermal particles forming the tail
        of the Kappa velocity distribution function. ``kappa`` must be greater
        than :math:`3/2`.

    particle : `str`, optional
        Representation of the particle species(e.g., 'p' for protons, 'D+'
        for deuterium, or 'He-4 +1' for :math:`He_4^{+1}` : singly ionized
        helium-4)), which defaults to electrons.

    vx_drift : `~astropy.units.Quantity`, optional
        The drift velocity in x-direction units convertible to m/s.

    vy_drift : `~astropy.units.Quantity`, optional
        The drift velocity in y-direction units convertible to m/s.

    vz_drift : `~astropy.units.Quantity`, optional
        The drift velocity in z-direction units convertible to m/s.

    vTh : `~astropy.units.Quantity`, optional
        Thermal velocity (most probable) in m/s. This is used for
        optimization purposes to avoid re-calculating ``vTh``, for example
        when integrating over velocity-space.

    units : `str`, optional
        Selects whether to run function with units and unit checks (when
        equal to "units") or to run as unitless (when equal to "unitless").
        The unitless version is substantially faster for intensive
        computations.

    Returns
    -------
    f : `~astropy.units.Quantity`
        Probability density in units of inverse velocity, normalized so that:
        :math:`\iiint_{0}^∞ f(\vec{v}) d\vec{v} = 1`

    Raises
    ------
    `TypeError`
        If any of the parameters is not a `~astropy.units.Quantity` and
        cannot be converted into one.

    `~astropy.units.UnitConversionError`
        If the parameters is not in appropriate units.

    `ValueError`
        If the temperature is negative, or the particle mass or charge state
        cannot be found.

    Notes
    -----
    In three dimensions, the Kappa velocity distribution function describing
    the distribution of particles with speed :math:`v` in a plasma with
    temperature :math:`T` and suprathermal parameter :math:`κ` is given by:

    .. math::

       f = A_κ \left(1 + \frac{(\vec{v} -
       \vec{V_{drift}})^2}{κ v_{Th},κ^2}\right)^{-(κ + 1)}

    where :math:`v_{Th},κ` is the kappa thermal speed
    and :math:`A_κ = \frac{1}{2 π (κ v_{Th},κ^2)^{3/2}}
    \frac{Γ(κ + 1)}{Γ(κ - 1/2) Γ(3/2)}` is the
    normalization constant.

    As :math:`κ → ∞`, the kappa distribution function converges to the
    Maxwellian distribution function.

    See Also
    --------
    kappa_velocity_1D
    ~plasmapy.formulary.speeds.kappa_thermal_speed

    Examples
    --------
    >>> from astropy import units as u
    >>> v=1 * u.m / u.s
    >>> kappa_velocity_3D(vx=v,
    ... vy=v,
    ... vz=v,
    ... T=30000 * u.K,
    ... kappa=4,
    ... particle='e',
    ... vx_drift=0 * u.m / u.s,
    ... vy_drift=0 * u.m / u.s,
    ... vz_drift=0 * u.m / u.s)
    <Quantity 3.7833...e-19 s3 / m3>
    """
    # must have kappa > 3/2 for distribution function to be valid
    if kappa <= 3 / 2:
        raise ValueError(f"Must have kappa > 3/2, instead of {kappa}.")
    if units == "units":
        # unit checks and conversions
        # checking velocity units
        vx = vx.to_value(SPEED_UNITS)
        vy = vy.to_value(SPEED_UNITS)
        vz = vz.to_value(SPEED_UNITS)
        # Catching case where drift velocities have default values
        vx_drift = _v_drift_conversion(vx_drift)
        vy_drift = _v_drift_conversion(vy_drift)
        vz_drift = _v_drift_conversion(vz_drift)
        # convert temperature to kelvin
        T = T.to_value(u.K, equivalencies=u.temperature_energy())
        if not np.isnan(vTh):
            # check units of thermal velocity
            vTh = vTh.to_value(SPEED_UNITS)

    if np.isnan(vTh):
        # get thermal velocity and thermal velocity squared
        vTh = kappa_thermal_speed(T << u.K, kappa, particle=particle).to_value(
            SPEED_UNITS
        )

    # getting square of thermal velocity
    vThSq = vTh**2
    # Get square of relative particle velocity
    vSq = (vx - vx_drift) ** 2 + (vy - vy_drift) ** 2 + (vz - vz_drift) ** 2
    # calculating distribution function
    expTerm = (1 + vSq / (kappa * vThSq)) ** (-(kappa + 1))
    coeff1 = 1 / (2 * np.pi * (kappa * vThSq) ** (3 / 2))
    coeff2 = gamma(kappa + 1) / (gamma(kappa - 1 / 2) * gamma(3 / 2))
    distFunc = coeff1 * coeff2 * expTerm
    if units == "units":
        return distFunc << SPEED_DISTRIBUTION_UNITS_3D
    elif units == "unitless":
        return distFunc


text:
/**
 * The examples provided by Facebook are for non-commercial testing and
 * evaluation purposes only.
 *
 * Facebook reserves all rights not expressly granted.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL
 * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
 * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

package com.facebook.react.uiapp;

import android.app.Application;

import com.facebook.react.ReactApplication;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;

import java.util.Arrays;
import java.util.List;

import javax.annotation.Nullable;

public class UIExplorerApplication extends Application implements ReactApplication {
  private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
    @Override
    public String getJSMainModuleName() {
      return "Examples/UIExplorer/UIExplorerApp.android";
    }

    @Override
    public @Nullable String getBundleAssetName() {
      return "UIExplorerApp.android.bundle";
    }

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

    @Override
    public List<ReactPackage> getPackages() {
      return Arrays.<ReactPackage>asList(
        new MainReactPackage()
      );
    }
  };

  @Override
  public ReactNativeHost getReactNativeHost() {
    return mReactNativeHost;
  }
};