text:
layout: "intro"
page_title: "Resource Dependencies"
sidebar_current: "gettingstarted-deps"
description: |-
  In this page, we're going to introduce resource dependencies, where we'll not only see a configuration with multiple resources for the first time, but also scenarios where resource parameters use information from other resources.
---

# Resource Dependencies

In this page, we're going to introduce resource dependencies,
where we'll not only see a configuration with multiple resources
for the first time, but also scenarios where resource parameters
use information from other resources.

Up to this point, our example has only contained a single resource.
Real infrastructure has a diverse set of resources and resource
types. Terraform configurations can contain multiple resources,
multiple resource types, and these types can even span multiple
providers.

On this page, we'll show a basic example of multiple resources
and how to reference the attributes of other resources to configure
subsequent resources.

## Assigning an Elastic IP

We'll improve our configuration by assigning an elastic IP to
the EC2 instance we're managing. Modify your `example.tf` and
add the following:

```
resource "aws_eip" "ip" {
	instance = "${aws_instance.example.id}"
}
```

This should look familiar from the earlier example of adding
an EC2 instance resource, except this time we're building
an "aws\_eip" resource type. This resource type allocates
and associates an
[elastic IP](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html)
to an EC2 instance.

The only parameter for
[aws\_eip](/docs/providers/aws/r/eip.html) is "instance" which
is the EC2 instance to assign the IP to. For this value, we
use an interpolation to use an attribute from the EC2 instance
we managed earlier.

The syntax for this interpolation should be straightforward:
it requests the "id" attribute from the "aws\_instance.example"
resource.

## Plan and Execute

Run `terraform plan` to view the execution plan. The output
will look something like the following:

```
$ terraform plan
...

+ aws_eip.ip
    instance:   "" => "${aws_instance.example.id}"
    private_ip: "" => "<computed>"
    public_ip:  "" => "<computed>"

+ aws_instance.example
    ami:               "" => "ami-b8b061d0"
    availability_zone: "" => "<computed>"
    instance_type:     "" => "t1.micro"
    key_name:          "" => "<computed>"
    private_dns:       "" => "<computed>"
    private_ip:        "" => "<computed>"
    public_dns:        "" => "<computed>"
    public_ip:         "" => "<computed>"
    security_groups:   "" => "<computed>"
    subnet_id:         "" => "<computed>"
```

Terraform will create two resources: the instance and the elastic
IP. In the "instance" value for the "aws\_eip", you can see the
raw interpolation is still present. This is because this variable
won't be known until the "aws\_instance" is created. It will be
replaced at apply-time.

Next, run `terraform apply`. The output will look similar to the
following:

```
aws_instance.example: Creating...
  ami:           "" => "ami-b8b061d0"
  instance_type: "" => "t1.micro"
aws_eip.ip: Creating...
  instance: "" => "i-0e737b25"

Apply complete! Resources: 2 added, 0 changed, 0 destroyed.
```

It is clearer to see from actually running Terraform, but
Terraform creates the EC2 instance before the elastic IP
address. Due to the interpolation earlier where the elastic
IP requires the ID of the EC2 instance, Terraform is able
to infer a dependency, and knows to create the instance
first.

## Implicit and Explicit Dependencies

Most dependencies in Terraform are implicit: Terraform is able
to infer dependencies based on usage of attributes of other
resources.

Using this information, Terraform builds a graph of resources.
This tells Terraform not only in what order to create resources,
but also what resources can be created in parallel. In our example,
since the IP address depended on the EC2 instance, they could
not be created in parallel.

Implicit dependencies work well and are usually all you ever need.
However, you can also specify explicit dependencies with the
`depends_on` parameter which is available on any resource. For example,
we could modify the "aws\_eip" resource to the following, which
effectively does the same thing and is redundant:

```
resource "aws_eip" "ip" {
	instance = "${aws_instance.example.id}"
	depends_on = ["aws_instance.example"]
}
```

If you're ever unsure about the dependency chain that Terraform
is creating, you can use the [`terraform graph` command](/docs/commands/graph.html) to view
the graph. This command outputs a dot-formatted graph which can be
viewed with
[Graphviz](http://www.graphviz.org/).

## Non-Dependent Resources

We can now augment the configuration with another EC2 instance.
Because this doesn't rely on any other resource, it can be
created in parallel to everything else.

```
resource "aws_instance" "another" {
	ami = "ami-b8b061d0"
	instance_type = "t1.micro"
}
```

You can view the graph with `terraform graph` to see that
nothing depends on this and that it will likely be created
in parallel.

Before moving on, remove this resource from your configuration
and `terraform apply` again to destroy it. We won't use the
second instance anymore in the getting started guide.

## Next

In this page you were introduced to both multiple resources
as well as basic resource dependencies and resource attribute
interpolation.

Moving on, [we'll use provisioners](/intro/getting-started/provision.html)
to do some basic bootstrapping of our launched instance.


text:
"use strict";

function getLoginStatus(callbackId, force) {
    // Try will catch errors when SDK has not been init
    try {
        FB.getLoginStatus(function (response) {
            window.external.notify(JSON.stringify({
                exec: 'success',
                callbackId: callbackId,
                response: response
            }));
        }, force);
    } catch (error) {
        window.external.notify(JSON.stringify({
            exec: 'error',
            callbackId: callbackId,
            response: error
        }));
    }
}

function showDialog(options, callbackId) {
    options = JSON.parse(options);

    if (!options.name) {
        options.name = "";
    }
    if (!options.message) {
        options.message = "";
    }
    if (!options.caption) {
        options.caption = "";
    }
    if (!options.description) {
        options.description = "";
    }
    if (!options.link) {
        options.link = "";
    }
    if (!options.picture) {
        options.picture = "";
    }

    // Try will catch errors when SDK has not been init
    try {
        FB.ui({
            method: options.method,
            message: options.message,
            name: options.name,
            caption: options.caption,
            description: (
                options.description
            ),
            link: options.link,
            // JS SDK expects href and not link
            href: options.link,
            picture: options.picture
        },
        function (response) {
            if (response && (response.request || !response.error_code)) {
                window.external.notify(JSON.stringify({
                    exec: 'success',
                    callbackId: callbackId,
                    type: "showDialog",
                    response: response
                }));
            } else {
                window.external.notify(JSON.stringify({
                    exec: 'fail',
                    callbackId: callbackId,
                    type: "showDialog",
                    response: response
                }));
            }
        });
    } catch (error) {
        window.external.notify(JSON.stringify({
            exec: 'error',
            callbackId: callbackId,
            type: "showDialog",
            response: error
        }));
    }
}

function getAccessToken(callbackId) {
    var response = FB.getAccessToken();
    if (!response) {
        window.external.notify(JSON.stringify({
            exec: 'error',
            callbackId: callbackId,
            response: "NO_TOKEN"
        }));
    } else {
        window.external.notify(JSON.stringify({
            exec: 'success',
            callbackId: callbackId,
            response: response
        }));
    }
}

function logEvent(eventName, params, valueToSum, callbackId) {
    // AppEvents are not avaliable in JS.
    window.external.notify(JSON.stringify({
        exec: 'success',
        callbackId: callbackId
    }));
}

function logPurchase(value, currency, callbackId) {
    // AppEvents are not avaliable in JS.
    window.external.notify(JSON.stringify({
        exec: 'success',
        callbackId: callbackId
    }));
}

function logout(callbackId) {
    // Try will catch errors when SDK has not been init
    try {
        FB.logout( function (response) {
            window.external.notify(JSON.stringify({
                exec: 'success',
                callbackId: callbackId,
                response: response
            }));
        });
    } catch (error) {
        window.external.notify(JSON.stringify({
            exec: 'error',
            callbackId: callbackId,
            response: error
        }));
    }
}

function api(graphPath, permissions, callbackId) {
    // JS API does not take additional permissions

    // Try will catch errors when SDK has not been init
    try {
        FB.api(graphPath, function (response) {
            if (response.error) {
                window.external.notify(JSON.stringify({
                    exec: 'fail',
                    callbackId: callbackId,
                    response: response
                }));
            } else {
                window.external.notify(JSON.stringify({
                    exec: 'success',
                    callbackId: callbackId,
                    response: response
                }));
            }
        });
    } catch (error) {
        window.external.notify(JSON.stringify({
            exec: 'error',
            callbackId: callbackId,
            response: error
        }));
    }
}

// Browser wrapper API ONLY
function browserInit(appId, version) {
    if (!version) {
        version = "v2.0";
    }
    FB.init({
        appId      : appId,
        cookie     : true,
        xfbml      : true,
        version    : version
    })
}

redpajama_set_name: RedPajamaGithub


text:
package org.observe.assoc.impl;

import java.util.concurrent.locks.ReentrantReadWriteLock;

import org.observe.ObservableValue;
import org.observe.collect.CollectionSession;
import org.observe.collect.ObservableCollection;
import org.qommons.Transactable;

import com.google.common.reflect.TypeToken;

/**
 * Creates a collection, given the internals. This interface allows creation of observable structures that use observable collections in
 * their internals with specific implementations of those collections. For example, instead of needing separate classes to implement a hash
 * map and a sorted map, the user can use {@link ObservableMapImpl} and supply the {@link org.observe.collect.impl.ObservableHashSet} or
 * {@link org.observe.collect.impl.ObservableTreeSet} constructor to the {@link ObservableMapImpl} constructor.
 *
 * @param <T> The type of elements for the collection
 * @param <C> The sub-type of collection to create
 */
public interface CollectionCreator<T, C extends ObservableCollection<T>> {
	/**
	 * Creates the collection
	 *
	 * @param type The type of elements for the collection
	 * @param lock The lock for the collection to use
	 * @param session The session for the collection to use (see {@link ObservableCollection#getSession()})
	 * @param sessionController The controller for the session. May be null, in which case the transactional methods in this collection will
	 *            not actually create transactions.
	 * @return The new collection
	 */
	C create(TypeToken<T> type, ReentrantReadWriteLock lock, ObservableValue<CollectionSession> session, Transactable sessionController);
}


text:
<?xml version="1.0" encoding="utf-8"?>
<selector
  xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="@color/background_holo_light" android:state_accelerated="false" />
    <item android:color="@color/transparent" />
</selector>


text:
layout: default
title: Select2 4.0.0 Released
slug: announcements-4.0
---

Announcing Select2 4.0.0

Select2 4.0.0

          The 4.0 release of Select2 is the result of three years of working on the
          code base and watching where it needs to go. At the core, it is a full
          rewrite that addresses many of the extensibility and usability problems
          that could not be addressed in previous versions.

          This release contains many breaking changes, but easy-upgrade paths have
          been created as well as helper modules that will allow for backwards
          compatibility to be maintained with past versions of Select2. Upgrading
          will require you to read the release notes carefully, but the
          migration path should be relatively straightforward. You can view a list
          of the most common changes that you will need to make
          in the release notes.

          Below is an in-depth review of what is new in Select2, as well as some of
          the major changes that have been made.

New features

          The notable features of this new release include:

            A more flexible plugin framework that allows you to override Select2 to
            behave exactly how you want it to.

            Consistency with standard <select> elements for all
            data adapters, removing the need for hidden <input>
            elements.

            A new build system that uses AMD to keep everything organized.

            Less specific selectors allowing for Select2 to be styled to fit the
            rest of your application.

Plugin system

          Select2 now provides interfaces that allow for it to be easily extended,
          allowing for anyone to create a plugin that changes the way Select2 works.
          This is the result of Select2 being broken into four distinct sections,
          each of which can be extended and used together to create your unique
          Select2.

          The adapters implement a consistent interface that is documented in the
          options section for adapters, allowing
          you to customize Select2 to do exactly what you are looking for. Select2
          is designed such that you can mix and match plugins, with most of the core
          options being built as decorators that wrap the standard adapters.

AMD-based build system

          Select2 now uses an
          AMD-based build system,
          allowing for builds that only require the parts of Select2 that you need.
          While a custom build system has not yet been created, Select2 is open
          source and will gladly accept a pull request for one.

          Select2 includes the minimal almond
          AMD loader, but a custom select2.amd.js build is available
          if you already use an AMD loader. The code base (available in the
          src directory) also uses AMD, allowing you to include Select2
          in your own build system and generate your own builds alongside your
          existing infrastructure.

          The AMD methods used by Select2 are available as
          jQuery.fn.select2.amd.define()/require(), allowing you to use the
          included almond loader. These methods are primarily used by the
          translations, but they are the recommended way to access custom modules
          that Select2 provides.

Migrating from Select2 3.5

          There are a few breaking changes that migrators should be aware of when
          they are coming from older versions of Select2.

          If you use the full build of Select2 (select2.full.js), you
          will be automatically notified of the major breaking changes, and
          compatibility modules will be used in some cases to ensure that your code
          still behaves how you were expecting.

No more hidden input tags

          In past versions of Select2, an <input type="hidden" />
          tag was recommended if you wanted to do anything advanced with Select2,
          such as work with remote data sources or allow users to add their own
          tags. This had the unfortunate side-effect of servers not receiving the
          data from Select2 as an array, like a standard <select>
          element does, but instead sending a string containing the comma-separated
          strings. The code base ended up being littered with special cases for the
          hidden input, and libraries using Select2 had to work around the
          differences it caused.

          In Select2 4.0, the <select> element supports all core
          options, and support for the old
          <input type="hidden" /> has been deprecated. This means
          that if you previously declared an AJAX field with some pre-selected
          options that looked like…

<input type="hidden" name="select-boxes" value="1,2,4,6" />

          It will need to be recreated as a <select> element with
          some <option> tags that have value
          attributes that match the old value.

<select name="select-boxes" multiple="multiple">
  <option value="1" selected="selected">Select2</option>
  <option value="2" selected="selected">Chosen</option>
  <option value="4" selected="selected">selectize.js</option>
  <option value="6" selected="selected">typeahead.js</option>
</select>

          The options that you create should have selected="selected"
          set so Select2 and the browser knows that they should be selected. The
          value attribute of the option should also be set to the value
          that will be returned from the server for the result, so Select2 can
          highlight it as selected in the dropdown. The text within the option
          should also reflect the value that should be displayed by default for the
          option.

Advanced matching of searches

          In past versions of Select2, when matching search terms to individual
          options, which limited the control that you had when displaying results,
          especially in cases where there was nested data. The matcher
          function was only given the individual option, even if it was a nested
          options, without any context.

          With the new matcher function, only the root-level options are matched and
          matchers are expected to limit the results of any children options that
          they contain. This allows developers to customize how options within
          groups can be displayed, and modify how the results are returned.

          A function has been created that allows old-style matcher functions to be
          converted to the new style. You can retrieve the function from the
          select2/compat/matcher module, which should just wrap the old
          matcher function.

          So if your old code used a matcher that only displayed options if they
          started with the term that was entered, it would look something like…

function matchStart (term, text) {
  if (text.toUpperCase().indexOf(term.toUpperCase()) == 0) {
    return true;
  }

  return false;
}

$("select").select2({
  matcher: matchStart
})

          Then in Select2 4.0, you would need to wrap the matchStart
          method (or the name of the matcher you created) with a
          oldMatcher method that we have created.

function matchStart (term, text) {
  if (text.toUpperCase().indexOf(term.toUpperCase()) == 0) {
    return true;
  }

  return false;
}

$.fn.select2.amd.require(['select2/compat/matcher'], function (oldMatcher) {
  $("select").select2({
    matcher: oldMatcher(matchStart)
  })
});

          This will work for any matchers that only took in the search term and the
          text of the option as parameters. If your matcher relied on the third
          parameter containing the jQuery element representing the original
          <option> tag, then you may need to slightly change
          your matcher to expect the full JavaScript data object being passed in
          instead. You can still retrieve the jQuery element from the data object
          using the data.element property.

More flexible placeholders

          In the most recent versions of Select2, placeholders could only be
          applied to the first (typically the default) option in a
          <select> if it was blank. The
          placeholderOption option was added to Select2 to allow users
          using the select tag to select a different option, typically
          an automatically generated option with a different value.

          The placeholder option can now take an object as well as just
          a string. This replaces the need for the old
          placeholderOption, as now the id of the object
          can be set to the value attribute of the
          <option> tag.

          For a select that looks like the following, where the first option (with a
          value of -1) is the placeholder option…

<select>
  <option value="-1" selected="selected">Select an option</option>
  <option value="1">Something else</option>
</select>

          You would have previously had to get the placeholder option through the
          placeholderOption, but now you can do it through the
          placeholder option by setting an id.

$("select").select2({
  placeholder: {
    id: "-1",
    placeholder: "Select an option"
  }
})

          And Select2 will automatically display the placeholder when the value of
          the select is -1, which it will be by default. This does not
          break the old functionality of Select2 where the placeholder option was
          blank by default.

Display reflects the actual order of the values

          In past versions of Select2, choices were displayed in the order that
          they were selected. In cases where Select2 was used on a
          <select> element, the order that the server received
          the selections did not always match the order that the choices were
          displayed, resulting in confusion in situations where the order is
          important.

          Select2 will now order selected choices in the same order that will be
          sent to the server.

Changed method and option names

          When designing the future option set for Select2 4.0, special care was
          taken to ensure that the most commonly used options were brought over.
          For the most part, the commonly used options of Select2 can still be
          referenced under their previous names, but there were some changes which
          have been noted.

          Removed the requirement of initSelection

          In the past, whenever you wanted to use a custom data adapter, such as
          AJAX or tagging, you needed to help Select2 out in determining the initial
          values that were selected. This was typically done through the
          initSelection option, which took the underlying data of the
          input and converted it into data objects that Select2 could use.

          This is now handled by
          the data adapter in the
          current method, which allows Select2 to convert the currently
          selected values into data objects that can be displayed. The default
          implementation converts the text and value of option elements
          into data objects, and is probably suitable for most cases. An example of
          the old initSelection option is included below, which
          converts the value of the selected options into a data object with both
          the id and text matching the selected value.

initSelection : function (element, callback) {
  var data = [];
  $(element.val()).each(function () {
    data.push({id: this, text: this});
  });
  callback(data);
}

          When using the new current method of the custom data adapter,
          this method is called any time Select2 needs a list of
          the currently selected options. This is different from the old
          initSelection in that it was only called once, so it could
          suffer from being relatively slow to process the data (such as from a
          remote data source).

$.fn.select2.amd.require([
  'select2/data/array',
  'select2/utils'
], function (ArrayData, Utils) {
  function CustomData ($element, options) {
    CustomData.__super__.constructor.call(this, $element, options);
  }

  Utils.Extend(CustomData, ArrayData);

  CustomData.prototype.current = function (callback) {
    var data = [];
    var currentVal = this.$element.val();

    if (!this.$element.prop('multiple')) {
      currentVal = [currentVal];
    }

    for (var v = 0; v < currentVal.length; v++) {
      data.push({
        id: currentVal[v],
        text: currentVal[v]
      });
    }

    callback(data);
  };

  $("#select").select2({
    dataAdapter: CustomData
  });
}

          The new current method of the data adapter works in a similar
          way to the old initSelection method, with three notable
          differences. The first, and most important, is that it is called
          whenever the current selections are needed to ensure that Select2
          is always displaying the most accurate and up to date data. No matter
          what type of element Select2 is attached to, whether it supports a
          single or multiple selections, the data passed to the callback
          must be an array, even if it contains one selection.
          The last is that there is only one parameter, the callback to be
          executed with the latest data, and the current element that Select2 is
          attached to is available on the class itself as
          this.$element.

          If you only need to load in the initial options once, and otherwise will
          be letting Select2 handle the state of the selections, you don't need to
          use a custom data adapter. You can just create the
          <option> tags on your own, and Select2 will pick up
          the changes.

var $element = $('select').select2(); // the select element you are working with

var $request = $.ajax({
  url: '/my/remote/source' // wherever your data is actually coming from
});

$request.then(function (data) {
  // This assumes that the data comes back as an array of data objects
  // The idea is that you are using the same callback as the old `initSelection`

  for (var d = 0; d < data.length; d++) {
    var item = data[d];

    // Create the DOM option that is pre-selected by default
    var option = new Option(item.text, item.id, true, true);

    // Append it to the select
    $element.append(option);
  }

  // Update the selected options that are displayed
  $element.trigger('change');
});

          Custom data adapters instead of query

          In the past, any time
          you wanted to hook Select2 up to a different data source you would be
          required to implement custom query and
          initSelection methods. This allowed Select2 to determine the
          initial selection and the list of results to display, and it would handle
          everything else internally, which was fine more most people.

          The custom query and initSelection methods have
          been replaced by
          custom data adapters that handle
          how Select2 stores and retrieves the data that will be displayed to the
          user. An example of the old query option is provided below,
          which is
          the same as the old example,
          and it generates results that contain the search term repeated a certain
          number of times.

query: function (query) {
  var data = {results: []}, i, j, s;
  for (i = 1; i < 5; i++) {
    s = "";
    for (j = 0; j < i; j++) {s = s + query.term;}
    data.results.push({id: query.term + i, text: s});
  }
  query.callback(data);
}

          This has been replaced by custom data adapters which define a similarly
          named query method. The comparable data adapter is provided
          below as an example.

$.fn.select2.amd.require([
  'select2/data/array',
  'select2/utils'
], function (ArrayData, Utils) {
  function CustomData ($element, options) {
    CustomData.__super__.constructor.call(this, $element, options);
  }

  Utils.Extend(CustomData, ArrayData);

  CustomData.prototype.query = function (params, callback) {
    var data = {
      results: []
    };

    for (var i = 1; i < 5; i++) {
      var s = "";

      for (var j = 0; j < i; j++) {
        s = s + params.term;
      }

      data.results.push({
        id: params.term + i,
        text: s
      });
    }

    callback(data);
  };

  $("#select").select2({
    dataAdapter: CustomData
  });
}

          The new query method of the data adapter is very similar to
          the old query option that was passed into Select2 when
          initializing it. The old query argument is mostly the same as
          the new params that are passed in to query on, and the
          callback that should be used to return the results is now passed in as the
          second parameter.

Renamed templating options

          Select2 previously provided multiple options for formatting the results
          list and selected options, commonly referred to as "formatters", using the
          formatSelection and formatResult options. As the
          "formatters" were also used for things such as localization,
          which has also changed, they have been
          renamed to templateSelection and templateResult
          and their signatures have changed as well.

          You should refer to the updated
          documentation on templates when
          migrating from previous versions of Select2.

          The id and text properties are strictly enforced

          When working with array and AJAX data in the past, Select2 allowed a
          custom id function or attribute to be set in various places,
          ranging from the initialization of Select2 to when the remote data was
          being returned. This allowed Select2 to better integrate with existing
          data sources that did not necessarily use the id attribute to
          indicate the unique identifier for an object.

          Select2 no longer supports a custom id or text
          to be used, but provides integration points for converting incorrect data
          to the expected format.

          When working with array data

          Select2 previously supported defining array data as an object that matched
          the signature of an AJAX response. A text property could be
          specified that would map the given property to the text
          property on the individual objects. You can now do this when initializing
          Select2 by using the following jQuery code to map the old
          text and id properties to the new ones.

var data = $.map([
  {
    pk: 1,
    word: 'one'
  },
  {
    pk: 2,
    word: 'two'
  }
], function (obj) {
  obj.id = obj.id || obj.pk;
  obj.text = obj.text || obj.word;

  return obj;
});

          This will result in an array of data objects that have the id
          properties that match the existing pk properties and
          text properties that match the existing word
          properties.

          When working with remote data

          The same code that was given above can be used in the
          processResults method of an AJAX call to map properties there
          as well.

Renamed translation options

          In previous versions of Select2, the default messages provided to users
          could be localized to fit the language of the website that it was being
          used on. Select2 only comes with the English language by default, but
          provides
          community-contributed translations for
          many common languages. Many of the formatters have been moved to the
          language option and the signatures of the formatters have
          been changed to handle future additions.

          Declaring options using data-* attributes

          In the past, Select2 has only supported declaring a subset of options
          using data-* attributes. Select2 now supports declaring all
          options using the attributes, using
          the format specified in the documentation.

          You could previously declare the URL that was used for AJAX requests using
          the data-ajax-url attribute. While Select2 still allows for
          this, the new attribute that should be used is the
          data-ajax--url attribute. Support for the old attribute will
          be removed in Select2 4.1.

          Although it was not documented, a list of possible tags could also be
          provided using the data-select2-tags attribute and passing in
          a JSON-formatted array of objects for tags. As the method for specifying
          tags has changed in 4.0, you should now provide the array of objects using
          the data-data attribute, which maps to
          the array data option. You should also
          enable tags by setting data-tags="true" on the object, to
          maintain the ability for users to create their own options as well.

          If you previously declared the list of tags as…

<select data-select2-tags='[{"id": "1", "text": "One"}, {"id": "2", "text": "Two"}]'></select>

          …then you should now declare it as…

<select data-data='[{"id": "1", "text": "One"}, {"id": "2", "text": "Two"}]' data-tags="true"></select>

Deprecated and removed methods

          As Select2 now uses a <select> element for all data
          sources, a few methods that were available by calling
          .select2() are no longer required.

.select2("val")

          The "val" method has been deprecated and will be removed in
          Select2 4.1. The deprecated method no longer includes the
          triggerChange parameter.

          You should directly call .val on the underlying
          <select> element instead. If you needed the second
          parameter (triggerChange), you should also call
          .trigger("change") on the element.

$("select").val("1").trigger("change"); // instead of $("select").select2("val", "1");

.select2("enable")

          Select2 will respect the disabled property of the underlying
          select element. In order to enable or disable Select2, you should call
          .prop('disabled', true/false) on the
          <select> element. Support for the old methods will be
          completely removed in Select2 4.1.

$("select").prop("disabled", true); // instead of $("select").enable(false);

      {% include nav/announcements-4.0.html %}


text:
package de.jtem.riemann.schottky;

import java.io.Serializable;

import de.jtem.mfc.field.Complex;
import de.jtem.mfc.group.Moebius;

/**
 * @version 0.5
 * @author schmies
 *
 */
public class SchottkyData
    implements Serializable {

  private static final long serialVersionUID = 1L;

  protected SchottkyGroupElement [] generator;

  protected SchottkyGroupElement [] generatorInv;

  /**
   ** Number of generators of schottky group.
   **/
  final int numGenerators;

  /**
   * Radius of ismetric circles.
   */
  double[] radius;

  /**
   * Centers of isometric cirlces.
   */
  Complex[][] center;

  /**
   * Fixpoints of loxodromic generators.
   */
  Complex[][] fixpoint;

  /**
   * Field.Complex factor of loxodromic generators.
   */
  Complex[] mu;

  double[] uniformizationData;

  public SchottkyData() {
    this(2);
    System.out.println("Does this even ever happen?");
  }

  public SchottkyData(int numOfGenerators) {
    this(getDefaultUniformizationData(numOfGenerators));
    // numOfGenerators = genus
    System.out.println("JEREMY1=" + numOfGenerators);
    double[] JData;
    JData = getDefaultUniformizationData(numOfGenerators);
    System.out.println("Jdata = "+JData);
    System.out.println("Jdata[0] = "+JData[0]);
    System.out.println("Jdata[1] = "+JData[1]);
    System.out.println("Jdata[2] = "+JData[2]);
    System.out.println("Jdata[3] = "+JData[3]);
    System.out.println("Jdata[4] = "+JData[4]);
    System.out.println("Jdata[5] = "+JData[5]);
    System.out.println("JEREMY2, getDefaultUniformizationData = " + getDefaultUniformizationData(numOfGenerators));
  }

  public SchottkyData(double[] uniformizationData) {

    if (uniformizationData.length % 6 != 0) {
      throw new IllegalArgumentException(
          " uniformizatinoData has wrong length ");
    }

    System.out.println("OKAY HERE"+uniformizationData.length);
    numGenerators = uniformizationData.length / 6;
    System.out.println("numGenerators = "+ numGenerators);

    init();

    System.arraycopy(uniformizationData, 0,
                     this.uniformizationData, 0, uniformizationData.length);

    updateFixPointsAndMusFromDataArray();
    updateGeneratorsFromFixPointsAndMus();
    updateCircles();
  }

  private void init() {

    generator = new SchottkyGroupElement[numGenerators];
    generatorInv = new SchottkyGroupElement[numGenerators];

    for ( char i = 0; i < numGenerators; i++) {
      generator[i] = new SchottkyGroupElement();
      generatorInv[i] = new SchottkyGroupElement();

      generator[i].left = generator[i].right = i;
      generator[i].leftIsInvert = generator[i].rightIsInvert = 0;
      generator[i].wordLength = 1;

      generatorInv[i].left = generatorInv[i].right = i;
      generatorInv[i].leftIsInvert = generatorInv[i].rightIsInvert = 1;
      generatorInv[i].wordLength = 1;
    }

    radius = new double[numGenerators];
    uniformizationData = new double[numGenerators * 6];

    center = new Complex[numGenerators][2];
    fixpoint = new Complex[numGenerators][2];

    mu = new Complex[numGenerators];

    for (int i = 0; i < numGenerators; i++) {

      center[i][0] = new Complex();
      center[i][1] = new Complex();

      fixpoint[i][0] = new Complex();
      fixpoint[i][1] = new Complex();

      mu[i] = new Complex();
    }
  }

  public double[] getUniformizationData() {
    return (double[]) uniformizationData.clone();
  }

  public Moebius getGenerator(int anIndex) {
    return new Moebius(generator[anIndex]);
  }

  public double[] getRadius() {
    return radius;
  }

  public double getRadius(int anIndex) {
    return radius[anIndex];
  }

  public Complex[][] getCenters() {
    return center;
  }

  public Complex getCenterOfCircle(int anIndex, boolean isPrime) {
    return center[anIndex][isPrime ? 1 : 0];
  }

  public Complex getCenterOfCircle(int anIndex) {
    return center[anIndex][0];
  }

  public void getCenterOfCircle(int anIndex, boolean isPrime, Complex center ) {
  	center.assign( this.center[anIndex][isPrime ? 1 : 0] );
  }

  public void getCenterOfCircle(int anIndex, Complex center ) {
  	center.assign( this.center[anIndex][0] );
  }

  final IllegalArgumentException generatorsIntersect =
      new IllegalArgumentException("Generators intersect");

  static double[] getDefaultUniformizationData(int genus) {

    double[] data = new double[6 * genus];

    double muRe = 0.01;

    for (int i = 0, j = 0; i < genus; i++, muRe /= 5) {

      data[j++] = i + 1;
      data[j++] = 0;
      data[j++] = -i - 1;
      data[j++] = 0;
      data[j++] = muRe;
      data[j++] = 0;
    }

    return data;
  }

  public int getNumGenerators() {
    return numGenerators;
  }

  public Complex getA(int anIndex) {
    return new Complex(fixpoint[anIndex][0]);
  }

  public void setA(int anIndex, Complex aComplex) {
    fixpoint[anIndex][0].assign(aComplex);
    updateFromFixPointsAndMus();
  }

  public Complex getB(int anIndex) {
    return new Complex(fixpoint[anIndex][1]);
  }

  public void setB(int anIndex, Complex aComplex) {
    fixpoint[anIndex][1].assign(aComplex);
    updateFromFixPointsAndMus();
  }

  public void getMu(int anIndex, Complex mu) {
    mu.assign(this.mu[anIndex]);
  }

  public Complex getMu(int anIndex) {
    return new Complex(mu[anIndex]);
  }

  public void setMu(int anIndex, Complex aComplex) {
    mu[anIndex].assign(aComplex);
    updateFromFixPointsAndMus(); ;
    System.out.println("Uniformization Data[0] - = "+uniformizationData[0]);
    System.out.println("Uniformization Data[1] - = "+uniformizationData[1]);
    System.out.println("Uniformization Data[2] - = "+uniformizationData[2]);
    System.out.println("Uniformization Data[3] - = "+uniformizationData[3]);
    System.out.println("Uniformization Data[4] - = "+uniformizationData[4]);
    System.out.println("Uniformization Data[5] - = "+uniformizationData[5]);
  }

  public double[] getDoubleArrayValue() {
    double[] data = new double[6 * numGenerators];

    getUniformizationData(data, 0);

    return data;
  }

  public int getDoubleArrayValueLength() {
    return 6 * numGenerators;
  }

  public void getValue(double[] data) {
    getUniformizationData(data, 0);
  }

  public void getUniformizationData(double[] data, int offset) {
    System.arraycopy(uniformizationData, 0, data, offset,
                     uniformizationData.length);
  }

  public void setUniformizationData(double[] data) {
    setDoubleArrayParameter(data, 0);
  }

  final private boolean equalToUniformizationData( double[] data, int offset ) {
	for( int i=0, j=offset; i<uniformizationData.length; i++, j++ )
		  if( uniformizationData[i]!=data[j])
		  	return false;
  		return true;
  }

  public void setDoubleArrayParameter(double[] data, int offset) {

  	if( equalToUniformizationData( data, offset ) )
  		return;

    System.arraycopy(data, offset, uniformizationData, 0,
                     uniformizationData.length);

    updateFixPointsAndMusFromDataArray();
    updateGeneratorsFromFixPointsAndMus();
    update();
  }

  public void set(
      Complex[] A,
      Complex[] B,
      Complex[] Mu) {

    if (A.length != numGenerators
        || B.length != numGenerators
        || Mu.length != numGenerators) {
      throw new IllegalArgumentException("array(s) have wrong length");
    }

    for (int i = 0; i < numGenerators; i++) {
      fixpoint[i][0].assign(A[i]);
      fixpoint[i][1].assign(B[i]);
      mu[i].assign(Mu[i]);
    }

    updateFromFixPointsAndMus();
  }

  /**
   * @deprecated
   * @param data
   */
  public void set(double[] data) {
    setUniformizationData(data);
  }

  public void set(Moebius[] generator) {

    if (generator.length != numGenerators) {
      throw new IllegalArgumentException("array(s) have wrong length");
    }

    for (int i = 0; i < numGenerators; i++) {
      this.generator[i].assign(generator[i]);
      generatorInv[i].assignInvert(this.generator[i]);
    }

    updateFixPointsAndMusFromGenerators();
    updateDataArrayFromFixPointsAndMus();
    update();
  }

  void updateGeneratorsFromFixPointsAndMus() {

    for (int i = 0; i < numGenerators; i++) {
      generator[i].assign(fixpoint[i][0], fixpoint[i][1], mu[i]);
      generatorInv[i].assignInvert(generator[i]);
      generatorInv[i].parent = generator[i].parent;
    }
  }

  void updateFromFixPointsAndMus() {
    updateDataArrayFromFixPointsAndMus();
    updateGeneratorsFromFixPointsAndMus();
    update();
  }

  void updateDataArrayFromFixPointsAndMus() {

    for (int i = 0, j = 0; i < numGenerators; i++) {
      uniformizationData[j++] = fixpoint[i][0].re;
      uniformizationData[j++] = fixpoint[i][0].im;
      uniformizationData[j++] = fixpoint[i][1].re;
      uniformizationData[j++] = fixpoint[i][1].im;
      uniformizationData[j++] = mu[i].re;
      uniformizationData[j++] = mu[i].im;
    }
  }

  void updateFixPointsAndMusFromDataArray() {

    for (int i = 0, j = 0; i < numGenerators; i++) {

      fixpoint[i][0].assign(uniformizationData[j++], uniformizationData[j++]);
      fixpoint[i][1].assign(uniformizationData[j++], uniformizationData[j++]);

      mu[i].assign(uniformizationData[j++], uniformizationData[j++]);
    }
  }

  private Complex[] eigenvalues = new Complex[2];

  void updateFixPointsAndMusFromGenerators() {

    for (int i = 0; i < numGenerators; i++) {
      generator[i].getEigenValues(eigenvalues);
      mu[i].assignSqr(eigenvalues[0]);
      generator[i].getFixPoints(fixpoint[i]);
    }
  }

  void updateCircles() {
    for (int i = 0; i < numGenerators; i++) {
      radius[i] = generator[i].getCircles(center[i]);
    }
  }

  /**
    * Querries if this generates a classical Schottky group.
    * @return true iff this generates a classical Schottky group.
    */
   public boolean isClassical() {

     for( int i=0, N=0; i<2; i++ ) {
       for( int n=0; n<numGenerators; n++, N++ ) {

         final Complex c1 = center[n][i];
         final double r1 = radius[n];

         for( int j=0, M=0; j<2; j++ ) {
           for (int m = 0; m < numGenerators && M<N; m++, M++) {

             final Complex c2 = center[m][j];
             final double r2 = radius[m];

             if( c1.distSqr( c2 ) < (r1+r2)*(r1+r2) )
               return false;
           }
         }
       }
     }

     return true;
   }

  void update() {
    updateCircles();
  }

  /**
   * Checks whether a point p is inside the
   * fundamental domain F.
   * The boundary of F, i.e. the isometric circles
   * are considered to be part of F,
   * @see #isInFundamentalDomain(Complex, double)
   */
  public boolean isInFundamentalDomain(Complex p ) {
	  return isInFundamentalDomain( p, -1e-12 );
  }
  /**
   * Checks whether a point p is inside the
   * fundamental domain F.
   * With relTol you provide a signed relative tolerance, which means
   * that the creteria scale the radii by a factor of (1-relTol).
   * Thus a positive tolerance will enlarge the fundamental domain by the
   * given relative tolerance.
   */
  public boolean isInFundamentalDomain(Complex p, double relTol) {

    for (int i = 0; i < numGenerators; i++) {

      final double thresh = radius[i] * radius[i] * ( 1 - 2*relTol ) ;

      for (int j = 0; j < 2; j++) {

        if (center[i][j].distSqr(p) < thresh )
          return false;
      }
    }

    return true;
  }

  /** Returns distance of P to boundary of fundamental domain F.
   * Thus the result is only zero if P lays in one
   * of the 2N isomorphics circles which forms the boundary of F. */
  public double distToBoundaryOfFundamentalDomain(Complex P) {

    double minDist = Double.MAX_VALUE;

    for (int j = 0; j < 2; j++) {
      for (int i = 0; i < numGenerators; i++) {

        double aDist = radius[i] - center[i][j].dist(P);

        if (aDist > 0) {
          return aDist;
        }

        if ( -aDist < minDist) {
          minDist = -aDist;
        }
      }
    }

    return minDist;
  }

}


text:
import browserify from 'browserify-string';

export default class Bundler {
  constructor({
    babelOptions = {
      presets: ['es2015', 'react'],
    }
  } = {}) {
    this.babelOptions = babelOptions;
  }

  bundle(jsString) {
    return new Promise((resolve, reject) =>
      browserify(jsString)
        .transform('babelify', this.babelOptions)
        .bundle((err, src) => {
          if (err) return reject(err);
          return resolve(src.toString());
        })
    );
  }
}


text:
package tutorial;

import com.stormpath.sdk.account.Account;
import com.stormpath.sdk.directory.CustomData;
import com.stormpath.sdk.lang.Strings;
import com.stormpath.sdk.servlet.account.AccountResolver;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping(value="/dashboard")
public class DashboardController {

    @RequestMapping(method=RequestMethod.GET)
    public String get() {
        return "dashboard";
    }

    @RequestMapping(method=RequestMethod.POST)
    public String onSubmit(HttpServletRequest req) {

        String birthday = req.getParameter("birthday");
        String color = req.getParameter("color");

        //get the currently-logged-in account:
        Account account = AccountResolver.INSTANCE.getAccount(req);

        if (account != null) {

            CustomData data = account.getCustomData();

            if (Strings.hasText(birthday)) {
                data.put("birthday", birthday);
            } else {
                data.remove("birthday");
            }

            if (Strings.hasText(color)) {
                data.put("color", color);
            } else {
                data.remove("color");
            }

            data.save();
        }

        return "dashboard";
    }

}


text:
package com.android.settings;

import android.text.Spannable;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.View;
import android.widget.TextView;
import android.widget.TextView.BufferType;

/**
 * Utility class to create clickable links inside {@link TextView TextViews}.
 */
public class LinkifyUtils {
    private static final String PLACE_HOLDER_LINK_BEGIN = "LINK_BEGIN";
    private static final String PLACE_HOLDER_LINK_END = "LINK_END";

    private LinkifyUtils() {
    }

    /** Interface that handles the click event of the link */
    public interface OnClickListener {
        void onClick();
    }

    /**
     * Applies the text into the {@link TextView} and part of it a clickable link.
     * The text surrounded with "LINK_BEGIN" and "LINK_END" will become a clickable link. Only
     * supports at most one link.
     * @return true if the link has been successfully applied, or false if the original text
     *         contains no link place holders.
     */
    public static boolean linkify(TextView textView, StringBuilder text,
            final OnClickListener listener) {
        // Remove place-holders from the string and record their positions
        final int beginIndex = text.indexOf(PLACE_HOLDER_LINK_BEGIN);
        if (beginIndex == -1) {
            textView.setText(text);
            return false;
        }
        text.delete(beginIndex, beginIndex + PLACE_HOLDER_LINK_BEGIN.length());
        final int endIndex = text.indexOf(PLACE_HOLDER_LINK_END);
        if (endIndex == -1) {
            textView.setText(text);
            return false;
        }
        text.delete(endIndex, endIndex + PLACE_HOLDER_LINK_END.length());

        textView.setText(text.toString(), BufferType.SPANNABLE);
        textView.setMovementMethod(LinkMovementMethod.getInstance());
        Spannable spannableContent = (Spannable) textView.getText();
        ClickableSpan spannableLink = new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                listener.onClick();
            }

            @Override
            public void updateDrawState(TextPaint ds) {
                super.updateDrawState(ds);
                ds.setUnderlineText(false);
            }
        };
        spannableContent.setSpan(spannableLink, beginIndex, endIndex,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        return true;
    }
}


text:
___

Define all your routes in one place...

```js
class App extends React.Component {
  render() {
    return (
      <Router>
        <Scene key="root">
          <Scene key="login" component={Login} title="Login"/>
          <Scene key="register" component={Register} title="Register"/>
          <Scene key="home" component={Home}/>
        </Scene>
      </Router>
    );
  }
}
```

...and navigate from scene to scene with a simple, powerful API

```js
// login.js

// navigate to 'home' as defined in your top-level router
Actions.home(PARAMS)

// go back (i.e. pop the current screen off the nav stack)
Actions.pop()

// refresh the current Scene with the specified props
Actions.refresh({param1: 'hello', param2: 'world'})
```

## Try the example app

![rnrf](https://user-images.githubusercontent.com/3681859/27937441-ef61d932-626b-11e7-885f-1db7dc74b32e.gif)

```bash
# Get the code
git clone git@github.com:aksonov/react-native-router-flux.git`
cd react-native-router-flux/Example

# Install dependencies
yarn

# Run it
react-native run-ios
```

## v4 Features
* Based on latest [React Navigation](https://reactnavigation.org) API
* Separate navigation logic from presentation. You may change now navigation state directly from your business logic code - stores/reducers/etc. navigationStore
* Built-in state machine (former Switch replacement) - each 'scene' has onEnter/onExit handlers.
MobX-powered, all used scenes are wrapped as 'observer' automatically. You may subscribe to navigationStore (former Actions), observe current navigation state, etc. If you are using Redux, skip this.
* Flexible nav bar customization, that is not allowed by react navigation right now:
https://github.com/react-community/react-navigation/issues/779
* Drawer support (react
* 'Lightbox' support (used by popups like Error alert within Example project)

## Breaking changes (compared to v3):
* No duration/panHandlers support - you have to implement custom navigator now instead and pass it as 'navigator' prop:
https://reactnavigation.org/docs/navigators/custom
* No support for partial hiding of tab bar for some tabs because of react navigation bug:
https://github.com/react-community/react-navigation/issues/1584
* No possibility to skip animation during reset/replace:
https://github.com/react-community/react-navigation/issues/1493
* `Switch` is removed - you may use onEnter/onExit handlers for more flexible logic.
* `getSceneStyle` is removed (no needed in v4).
* Custom reducer (`createReducer` prop for Router) - Redux actions now are passed from React Navigation ('Navigation/BACK', 'Navigation/NAVIGATE', etc.)
* Drawer is 'drawer' attribute Scene
* Modal is 'modal' attribute for Scene
* No flux 'focus' actions - use onEnter/onExit handlers instead.
* Possible other stuff.

## Migrating from v3
Coming soon


text:
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.psi.impl.light;

import com.intellij.lang.java.JavaLanguage;
import com.intellij.navigation.ItemPresentation;
import com.intellij.navigation.ItemPresentationProviders;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.AtomicNotNullLazyValue;
import com.intellij.openapi.util.NotNullLazyValue;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileVisitor;
import com.intellij.psi.*;
import com.intellij.psi.javadoc.PsiDocComment;
import com.intellij.psi.util.CachedValueProvider;
import com.intellij.psi.util.CachedValuesManager;
import com.intellij.psi.util.PsiUtil;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.List;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.intellij.util.ObjectUtils.notNull;

public class LightJavaModule extends LightElement implements PsiJavaModule {
  private final LightJavaModuleReferenceElement myRefElement;
  private final VirtualFile myJarRoot;
  private final NotNullLazyValue<List<PsiPackageAccessibilityStatement>> myExports = AtomicNotNullLazyValue.createValue(() -> findExports());

  private LightJavaModule(@NotNull PsiManager manager, @NotNull VirtualFile jarRoot) {
    super(manager, JavaLanguage.INSTANCE);
    myJarRoot = jarRoot;
    myRefElement = new LightJavaModuleReferenceElement(manager, moduleName(jarRoot));
  }

  @NotNull
  public VirtualFile getRootVirtualFile() {
    return myJarRoot;
  }

  @Nullable
  @Override
  public PsiDocComment getDocComment() {
    return null;
  }

  @NotNull
  @Override
  public Iterable<PsiRequiresStatement> getRequires() {
    return Collections.emptyList();
  }

  @NotNull
  @Override
  public Iterable<PsiPackageAccessibilityStatement> getExports() {
    return myExports.getValue();
  }

  private List<PsiPackageAccessibilityStatement> findExports() {
    List<PsiPackageAccessibilityStatement> exports = ContainerUtil.newArrayList();

    VfsUtilCore.visitChildrenRecursively(myJarRoot, new VirtualFileVisitor() {
      private final JavaDirectoryService service = JavaDirectoryService.getInstance();

      @Override
      public boolean visitFile(@NotNull VirtualFile file) {
        if (file.isDirectory() && !myJarRoot.equals(file)) {
          PsiDirectory directory = myManager.findDirectory(file);
          if (directory != null) {
            PsiPackage pkg = service.getPackage(directory);
            if (pkg != null) {
              String packageName = pkg.getQualifiedName();
              if (!packageName.isEmpty() && !PsiUtil.isPackageEmpty(new PsiDirectory[]{directory}, packageName)) {
                exports.add(new LightPackageAccessibilityStatement(myManager, packageName));
              }
            }
          }
        }
        return true;
      }
    });

    return exports;
  }

  @NotNull
  @Override
  public Iterable<PsiPackageAccessibilityStatement> getOpens() {
    return Collections.emptyList();
  }

  @NotNull
  @Override
  public Iterable<PsiUsesStatement> getUses() {
    return Collections.emptyList();
  }

  @NotNull
  @Override
  public Iterable<PsiProvidesStatement> getProvides() {
    return Collections.emptyList();
  }

  @NotNull
  @Override
  public PsiJavaModuleReferenceElement getNameIdentifier() {
    return myRefElement;
  }

  @NotNull
  @Override
  public String getName() {
    return myRefElement.getReferenceText();
  }

  @Override
  public PsiElement setName(@NotNull String name) throws IncorrectOperationException {
    throw new IncorrectOperationException("Cannot modify automatic module '" + getName() + "'");
  }

  @Override
  public PsiModifierList getModifierList() {
    return null;
  }

  @Override
  public boolean hasModifierProperty(@NotNull String name) {
    return false;
  }

  @Override
  public ItemPresentation getPresentation() {
    return ItemPresentationProviders.getItemPresentation(this);
  }

  @NotNull
  @Override
  public PsiElement getNavigationElement() {
    return notNull(myManager.findDirectory(myJarRoot), super.getNavigationElement());
  }

  @Override
  public boolean equals(Object obj) {
    return obj instanceof LightJavaModule && myJarRoot.equals(((LightJavaModule)obj).myJarRoot) && getManager() == ((LightJavaModule)obj).getManager();
  }

  @Override
  public int hashCode() {
    return getName().hashCode() * 31 + getManager().hashCode();
  }

  @Override
  public String toString() {
    return "PsiJavaModule:" + getName();
  }

  private static class LightJavaModuleReferenceElement extends LightElement implements PsiJavaModuleReferenceElement {
    private final String myText;

    private LightJavaModuleReferenceElement(@NotNull PsiManager manager, @NotNull String text) {
      super(manager, JavaLanguage.INSTANCE);
      myText = text;
    }

    @NotNull
    @Override
    public String getReferenceText() {
      return myText;
    }

    @Override
    public PsiJavaModuleReference getReference() {
      return null;
    }

    @Override
    public String toString() {
      return "PsiJavaModuleReference";
    }
  }

  private static class LightPackageAccessibilityStatement extends LightElement implements PsiPackageAccessibilityStatement {
    private final String myPackageName;

    private LightPackageAccessibilityStatement(@NotNull PsiManager manager, @NotNull String packageName) {
      super(manager, JavaLanguage.INSTANCE);
      myPackageName = packageName;
    }

    @NotNull
    @Override
    public Role getRole() {
      return Role.EXPORTS;
    }

    @Nullable
    @Override
    public PsiJavaCodeReferenceElement getPackageReference() {
      return null;
    }

    @Nullable
    @Override
    public String getPackageName() {
      return myPackageName;
    }

    @NotNull
    @Override
    public Iterable<PsiJavaModuleReferenceElement> getModuleReferences() {
      return Collections.emptyList();
    }

    @NotNull
    @Override
    public List<String> getModuleNames() {
      return Collections.emptyList();
    }

    @Override
    public String toString() {
      return "PsiPackageAccessibilityStatement";
    }
  }

  @NotNull
  public static LightJavaModule getModule(@NotNull PsiManager manager, @NotNull VirtualFile jarRoot) {
    PsiDirectory directory = manager.findDirectory(jarRoot);
    assert directory != null : jarRoot;
    return CachedValuesManager.getCachedValue(directory, () -> {
      LightJavaModule module = new LightJavaModule(manager, jarRoot);
      return CachedValueProvider.Result.create(module, directory);
    });
  }

  @NotNull
  public static String moduleName(@NotNull VirtualFile jarRoot) {
    VirtualFile manifest = jarRoot.findFileByRelativePath(JarFile.MANIFEST_NAME);
    if (manifest != null) {
      try (InputStream stream = manifest.getInputStream()) {
        String claimed = new Manifest(stream).getMainAttributes().getValue("Automatic-Module-Name");
        if (claimed != null) return claimed;
      }
      catch (IOException e) {
        Logger.getInstance(LightJavaModule.class).warn(e);
      }
    }

    return moduleName(jarRoot.getNameWithoutExtension());
  }

  /**
   *
Implements a name deriving for automatic modules as described in ModuleFinder.of(Path...) method documentation.

   *
   *
Please note that the result may not be a valid module name when the source contains a sequence which starts with a digit
   * (e.g. "org.7gnomes..."). One may validate the result with {@link PsiNameHelper#isValidModuleName}.

   *
   * @param name a .jar file name without extension
   * @see ModuleFinder.of(Path...)
   */
  @NotNull
  public static String moduleName(@NotNull String name) {
    // If the name matches the regular expression "-(\\d+(\\.|$))" then the module name will be derived from the sub-sequence
    // preceding the hyphen of the first occurrence.
    Matcher m = Patterns.VERSION.matcher(name);
    if (m.find()) {
      name = name.substring(0, m.start());
    }

    // All non-alphanumeric characters ([^A-Za-z0-9]) are replaced with a dot (".") ...
    name = Patterns.NON_NAME.matcher(name).replaceAll(".");
    // ... all repeating dots are replaced with one dot ...
    name = Patterns.DOT_SEQUENCE.matcher(name).replaceAll(".");
    // ... and all leading and trailing dots are removed.
    name = StringUtil.trimLeading(StringUtil.trimTrailing(name, '.'), '.');

    return name;
  }

  private static class Patterns {
    private static final Pattern VERSION = Pattern.compile("-(\\d+(\\.|$))");
    private static final Pattern NON_NAME = Pattern.compile("[^A-Za-z0-9]");
    private static final Pattern DOT_SEQUENCE = Pattern.compile("\\.{2,}");
  }
}


text:
FROM maven:3.3.3-jdk-8

ENV CHATALYTICSPARENTDIR /opt/chatalytics
ENV CHATALYTICSDIR ${CHATALYTICSPARENTDIR}/chatalytics
ENV CHATALYTICSUIDIR ${CHATALYTICSPARENTDIR}/chatalyticsui
ENV DATABASEDIR /mnt/

# Install all the necessary packages

RUN apt-get update
RUN apt-get install -y software-properties-common\
                       python-software-properties\
                       apt-transport-https

RUN apt-key adv --keyserver keyserver.ubuntu.com --recv 68576280
RUN apt-add-repository "deb https://deb.nodesource.com/node_5.x $(lsb_release -sc) main"
RUN apt-get update
RUN apt-get install -y nodejs

RUN mkdir -p ${CHATALYTICSDIR}
RUN mkdir -p ${DATABASEDIR}

# Copy the source code
COPY OpenChatAlytics ${CHATALYTICSDIR}/code
COPY OpenChatAlyticsUI ${CHATALYTICSUIDIR}

# Setup the platform first
WORKDIR ${CHATALYTICSDIR}/code
RUN mvn clean package -Dmaven.test.skip=true
# Copy all the necessary things
RUN cp web/target/chatalytics-web-0.3-with-dependencies.jar ${CHATALYTICSDIR}
RUN cp compute/target/chatalytics-compute-0.3-with-dependencies.jar ${CHATALYTICSDIR}
RUN cp -r config ${CHATALYTICSDIR}
WORKDIR ${CHATALYTICSDIR}
RUN rm -rf code

# Now setup the UI
WORKDIR ${CHATALYTICSUIDIR}
RUN rm -rf node_modules
RUN rm -rf client/dist
RUN npm install
RUN npm run dist
ARG NODE=production
ENV NODE_ENV ${NODE}
EXPOSE 3001

# Copy over the script and start it
WORKDIR ${CHATALYTICSPARENTDIR}
COPY OpenChatAlyticsStack/bin/start-web-compute-ui.sh .
CMD ./start-web-compute-ui.sh chatalytics-local.yaml


text:
'use strict'
const test = require('tape')

const {
  getHasManyDescriptors,
  getBelongsToDescriptors
} = require('./get-descriptors')

test('getBelongsToDescriptors()', (t) => {
  t.throws(
    () => getBelongsToDescriptors(undefined),
    /getBelongsToDescriptors: schemaObject is undefined/
  )

  const schemaObject = {
    group: {
      belongsTo: 'userGroup',
      fkField: 'GrpID'
    },
    rights: {
      belongsTo: 'rights'
      /* fkField: is the same, so we can skip it */
    }
  }

  const relations = getBelongsToDescriptors(schemaObject)
  t.equal(relations.length, 2)
  t.deepEqual(
    relations, [
      {
        relationModelName: 'userGroup',
        modelFieldName: 'group',
        fkField: 'GrpID',
        fkAs: 'userGroupId'
      },
      {
        relationModelName: 'rights',
        modelFieldName: 'rights',
        fkField: 'rights',
        fkAs: 'rightsId'
      }
    ],
    'returns collection of "belongsTo" descriptors'
  )
  t.end()
})

test('getHasManyDescriptors()', (t) => {
  t.throws(
    () => getHasManyDescriptors(undefined),
    /getHasManyDescriptors: schemaObject is undefined/
  )

  const schemaObject = {
    users: {
      hasMany: 'user',
      fkField: 'GrpID'
    },
    tables: {
      hasMany: 'restTable',
      fkField: 'UserGroupID'
    },
    group: {
      belongsTo: 'userGroup',
      fkField: 'GrpID'
    },
    rights: {
      belongsTo: 'rights'
      /* fkField: is the same, so we can skip it */
    }
  }

  const relations = getHasManyDescriptors(schemaObject)
  t.equal(relations.length, 2)
  t.deepEqual(
    relations, [
      {
        relationModelName: 'user',
        modelFieldName: 'users',
        fkField: 'GrpID'
      },
      {
        relationModelName: 'restTable',
        modelFieldName: 'tables',
        fkField: 'UserGroupID'
      }
    ],
    'returns collection of "hasMany" descriptors'
  )
  t.end()
})


text:
__author__ = 'Adam R. Smith'

from pyon.public import log
from pyon.service import service
from pyon.net import entity
from pyon.container import cc
from pyon.service.service import BaseService
from interface.services.iping_service import IPingService

from zope.interface import implements
import bottle
from bottle import request, response, route

container = None

class PingService(BaseService):
    implements(IPingService)

    def ping(self, pong='pong'):
        print 'in ping'
        return 'pong'

class BridgeService(BaseService):
    #implements(IBridgeService)

    def __init__(self, port=8080, debug=False):
        self.app = bottle.app()
        bottle.debug(debug)
        bottle.run(self.app, host='0.0.0.0', port=port)

    @route('/')
    def index():
        print 'index'
        ping_client = entity.RPCClientEntityFromInterface(IPingService)
        container.start_client('ooibridge', ping_client)
        pong = ping_client.ping()
        return 'Ping said: %s' % pong

if __name__ == '__main__':
    container = cc.Container()
    container.start() # :(
    print 'container started'

    #ping_client = entity.RPCClientEntityFromInterface(IPingService)
    #container.start_client('ooibridge', ping_client)
    #print 'client started'

    bridge_service = BridgeService(port=8080, debug=True)
    bridge_entity = entity.RPCEntityFromService(bridge_service)
    container.start_server('ooibridge', bridge_entity)
    print 'service started'

    container.serve_forever()


text:
package upenn.junto.test

import java.io._
import io.Source
import upenn.junto.app._
import upenn.junto.config._

class PrepInfo (val id: String,   val verb: String, val noun: String,
                val prep: String, val pobj: String, val label: String)

object PrepInfoFromLine {
  def apply (line: String) = {
    val Array(id, verb, noun, prep, pobj, label) = line split(" ")
    new PrepInfo(id, verb, noun, prep, pobj, label)
  }
}

object PrepAttachTest {

  def idNode (s: String)   = s+"_ID"
  def verbNode (s: String) = s+"_VERB"
  def nounNode (s: String) = s+"_NOUN"
  def prepNode (s: String) = s+"_PREP"
  def pobjNode (s: String) = s+"_POBJ"

  def createEdges (info: List[PrepInfo]): List[Edge] = {
    (for (item <- info) yield {
      List(EdgeCreator(idNode(item.id), verbNode(item.verb)),
           EdgeCreator(idNode(item.id), nounNode(item.noun)),
           EdgeCreator(idNode(item.id), prepNode(item.prep)),
           EdgeCreator(idNode(item.id), pobjNode(item.pobj)))
    }).toList.flatten
  }

  def createLabels (info: List[PrepInfo]): List[Label] =
    info map { item => LabelCreator(idNode(item.id), verbNode(item.label)) }

  def main (args: Array[String]) {
    val ppadir = args(0)

    // Define the file locations
    val trainFile = ppadir+"/training"
    val devFile = ppadir+"/devset"
    val testFile = ppadir+"/test"

    // Convert files to PrepInfo lists
    val trainInfo = (Source fromFile(trainFile) getLines).toList map (PrepInfoFromLine(_))
    val devInfo = (Source fromFile(devFile) getLines).toList map (PrepInfoFromLine(_))
    val testInfo = (Source fromFile(testFile) getLines).toList map (PrepInfoFromLine(_))

    // Create the edges and seeds
    val edges = createEdges(trainInfo) ::: createEdges(devInfo) ::: createEdges(testInfo)
    val seeds = createLabels(trainInfo)
    val gold = createLabels(devInfo)

    // Create the graph and run label propagation
    val graph = GraphBuilder(edges, seeds, gold)
    JuntoRunner(graph)
    //graph.SaveEstimatedScores("data/label_prop_output")

    // BELOW: This is the file-based paradigm

    // Write out the edges and seeds
    //val outputDir = new File("data")
    //outputDir.mkdirs()
    //EdgeFileWriter(edges, outputDir.getPath + "/input_graph")
    //LabelFileWriter(seeds, outputDir.getPath + "/seeds")
    //LabelFileWriter(gold, outputDir.getPath + "/gold_labels")

  }

}


text:
package com.team4153;

import com.team4153.commands.DriveWithJoystick;
import com.team4153.commands.GyroReset;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.buttons.Button;
import edu.wpi.first.wpilibj.buttons.DigitalIOButton;
import edu.wpi.first.wpilibj.buttons.JoystickButton;
import edu.wpi.first.wpilibj.command.Scheduler;

/**
 * This class is the glue that binds the controls on the physical operator
 * interface to the commands and command groups that allow control of the robot.
 */
public class OI {

    private static Joystick joystick;
    private static Button triggerButton;
    private static Button gyroReset;

    public OI(Scheduler scheduler) {
        joystick = new Joystick(RobotMap.JOYSTICK_PORT);
        triggerButton = new JoystickButton(joystick, RobotMap.JSBUTTON_TRIGGER);
        gyroReset=new JoystickButton(joystick,RobotMap.JSBUTTON_GYRO_RESET);
        gyroReset.whenPressed(new GyroReset());
//        triggerButton.whenPressed(new DriveWithJoystick());
//        (new DriveWithJoystick()).start();
        scheduler.add(new DriveWithJoystick());
    }
    //// CREATING BUTTONS
    // One type of button is a joystick button which is any button on a joystick.
    // You create one by telling it which joystick it's on and which button
    // number it is.
    // Joystick stick = new Joystick(port);
    // Button button = new JoystickButton(stick, buttonNumber);

    // Another type of button you can create is a DigitalIOButton, which is
    // a button or switch hooked up to the cypress module. These are useful if
    // you want to build a customized operator interface.
    // Button button = new DigitalIOButton(1);
    // There are a few additional built in buttons you can use. Additionally,
    // by subclassing Button you can create custom triggers and bind those to
    // commands the same as any other Button.
    //// TRIGGERING COMMANDS WITH BUTTONS
    // Once you have a button, it's trivial to bind it to a button in one of
    // three ways:
    // Start the command when the button is pressed and let it run the command
    // until it is finished as determined by it's isFinished method.
    // button.whenPressed(new ExampleCommand());
    // Run the command while the button is being held down and interrupt it once
    // the button is released.
    // button.whileHeld(new ExampleCommand());
    // Start the command when the button is released  and let it run the command
    // until it is finished as determined by it's isFinished method.
    // button.whenReleased(new ExampleCommand());
    public static Joystick getJoystick() {
        return joystick;
    }

    public static Button getTriggerButton() {
        return triggerButton;
    }

    public static Button getGyroResetButton() {
        return gyroReset;
    }
}


text:
package org.hotpoor.pyq.fragment;

import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class MyFragment3 extends Fragment {

	private TextView tv;

	// 启动Fragment——>屏幕锁屏——>屏幕解锁——>
	//切换到其他的Fragment——>回到桌面——>回到应用——>退出Fragment
	/**
	 * 每次创建都会绘制Fragment的View组件时回调该方法
	 */
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment2, container, false);
		TextView tv = (TextView) view.findViewById(R.id.text);
		tv.setText("第一个Fragment");
		Log.i("Main", "Fragment1---onCreateView()");
		return view;
	}

	/**
	 * 当Fragment被添加到Activity时候会回调这个方法,并且只调用一次
	 */
	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		Log.i("Main", "Fragment1---onAttach()");

	}

	/**
	 * 创建Fragment时会回调,只会调用一次
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.i("Main", "Fragment1---onCreate()");

	}

	/**
	 * 当Fragment所在的Activty启动完成后调用
	 */
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		Log.i("Main", "Fragment1---onActivityCreated()");

	}

	/**
	 * 启动Fragment
	 *
	 */
	@Override
	public void onStart() {
		super.onStart();
		Log.i("Main", "Fragment1---onStart()");

	}

	/**
	 * 恢复Fragment时会被回调,调用onStart()方法后面一定会调用onResume()方法
	 */
	@Override
	public void onResume() {
		super.onResume();
		Log.i("Main", "Fragment1---onResume()");

	}

	/**
	 * 暂停Fragment
	 */
	@Override
	public void onPause() {
		super.onPause();
		Log.i("Main", "Fragment1---onPause()");

	}

	/**
	 * 停止Fragment
	 */
	@Override
	public void onStop() {
		super.onStop();
		Log.i("Main", "Fragment1---onStop()");

	}

	/**
	 * 销毁Fragment所包含的View组件时
	 */
	@Override
	public void onDestroyView() {
		super.onDestroyView();
		Log.i("Main", "Fragment1---onDestroyView()");

	}

	/**
	 * 销毁Fragment时会被回调
	 */
	@Override
	public void onDestroy() {
		super.onDestroy();
		Log.i("Main", "Fragment1---onDestroy()");

	}

	/**
	 * Fragment从Activity中删除时会回调该方法,并且这个方法只会调用一次
	 */
	@Override
	public void onDetach() {
		super.onDetach();
		Log.i("Main", "Fragment1---onDetach()");
	}
}


text:
// Kernel name: EndIntraThread.asm
//
// Common module to end current intra thread
//
#ifndef SW_SCOREBOARD
// Check for write commit first if SW scoreboard is disabled
	mov	(1)	REG_WRITE_COMMIT_Y<1>:ud	REG_WRITE_COMMIT_Y<0;1,0>:ud		// Make sure Y write is committed
	mov	(1)	REG_WRITE_COMMIT_UV<1>:ud	REG_WRITE_COMMIT_UV<0;1,0>:ud		// Make sure U/V write is committed
#endif

	END_THREAD

    #include "Intra_funcLib.asm"

#ifndef COMBINED_KERNEL		// For standalone kernel only
.end_code

.end_kernel
#endif	// COMBINED_KERNEL

// End of EndIntraThread


text:
package org.ictact.webproceedings.service.impl;

import java.util.List;

import org.ictact.webproceedings.model.BaseEntity;
import org.ictact.webproceedings.service.BaseEntityCrudService;
import org.springframework.data.jpa.repository.JpaRepository;

public abstract class BaseEntityCrudServiceImpl<T extends BaseEntity, R extends JpaRepository<T, Long>>
		implements BaseEntityCrudService<T> {

	protected abstract R getRepository();

	@Override
	public void save(T entity) {
		getRepository().save(entity);

	}

	@Override
	public List<T> findAll() {
		return getRepository().findAll();
	}

	@Override
	public T findById(Long id) {
		return getRepository().findOne(id);
	}

	@Override
	public void delete(Long id) {
		getRepository().delete(id);
	}

}


text:
Article 1748
----
L'acquéreur qui veut user de la faculté réservée par le bail d'expulser le
locataire en cas de vente est, en outre, tenu de l'avertir au temps d'avance
usité dans le lieu pour les congés.


text:
ACCEPTED

#### According to
Integrated Taxonomic Information System

#### Published in
null

#### Original name
Panicum variifolium Swallen

### Remarks
null


text:
package model

import (
	"time"

	"gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
)

type TrafficSeriesSnapshot struct {
	Id         bson.ObjectId `bson:"_id,omitempty"`
	Created_at time.Time     `bson:"created_at"`
	Start      int           `bson:"start"`
	End        int           `bson:"end"`
	Frequency  int           `bson:"frequency"`
	Traffic    []*Traffic    `bson:"sites"`
}

func (h TrafficSeriesSnapshot) Save(session *mgo.Session) {
	collection := session.DB("").C("TrafficSeries")
	err := collection.Insert(h)

	debugger.Printf("Saving %v", h)

	if err != nil {
		debugger.Printf("Failed to insert Historical snapshot: %v", err)
		return
	}
	removeOldSnapshots(collection)
}

type Traffic struct {
	Source string `bson:"source"`
	Visits []int  `bson:"visits"`
}

type TrafficSeriesIn struct {
	Series *struct {
		People []int `json:"people"`
	} `json:"series"`
}

func (his *TrafficSeriesIn) Visits() []int {
	return his.Series.People
}


text:
package data;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

/**
 * Created by ouyangzx on 17/3/3.
 */

public class Utils {

    static final int THREAD_LEAK_CLEANING_MS = 1000;

    static void flushStackLocalLeaks(Looper looper) {
        Handler handler = new Handler(looper) {
            @Override public void handleMessage(Message msg) {
                sendMessageDelayed(obtainMessage(), THREAD_LEAK_CLEANING_MS);
            }
        };
        handler.sendMessageDelayed(handler.obtainMessage(), THREAD_LEAK_CLEANING_MS);
    }

    /**
     * Map转化为对应得参数字符串
     * @param pe
     * @return
     */
    /**
     * Map转化为对应得参数字符串
     * @param pe
     * @return
     */
    public static String getMapToParameters(Map pe){
        StringBuilder builder = new StringBuilder();
        for (Object key : pe.keySet()) {
            Object o = pe.get(key);

            if (null == o) {
                continue;
            }

            if (o instanceof List) {
                o = ((List) o).toArray();
            }
            try {
                if (o instanceof Object[]) {
                    Object[] os = (Object[]) o;
                    String valueStr = "";
                    for (int i = 0, len = os.length; i < len; i++) {
                        if (null == os[i]) {
                            continue;
                        }
                        String value = os[i].toString().trim();
                        valueStr += (i == len - 1) ?  value :  value + ",";
                    }
                    builder.append(key).append("=").append(URLEncoder.encode(valueStr, "utf-8")).append("&");

                    continue;
                }
                builder.append(key).append("=").append(URLEncoder.encode((String) pe.get(key), "utf-8")).append("&");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        if (builder.length() > 1) {
            builder.deleteCharAt(builder.length() - 1);
        }
        return builder.toString();
    }

}


text:
'use strict';

angular.module('newCodexApp')
  .controller('GameplaytargetCtrl', function ($scope, utilityFactions) {
    $scope.awesomeThings = [
      'HTML5 Boilerplate',
      'AngularJS',
      'Karma'
    ];

    $scope.add = function() {
      if (!$scope.action.targets) { $scope.action.targets = []; }

      utilityFactions.newObj({
        parent: $scope.action,
        arrayKey: 'targets',
        message: 'card.data.changed'
      });
    };

    $scope.delete = function (target) {
      utilityFactions.deleteObj({
          parent: $scope.action,
          arrayKey: 'targets',
          id: target.id,
          message: 'card.data.changed'
        });
    };

  });


text:
// RotorData.cs
// <copyright file="RotorData.cs"> This code is protected under the MIT License. </copyright>
namespace EnigmaUtilities.Data
{
    /// <summary>
    /// A class that holds data about rotors to be used.
    /// </summary>
    public class RotorData
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="RotorData" /> class.
        /// </summary>
        /// <param name="name"> The name of the rotor. </param>
        /// <param name="wiring"> The wiring of the rotor. </param>
        /// <param name="turningNotches"> The letters that will turn the next rotor. </param>
        public RotorData(string name, string wiring, string turningNotches)
        {
            this.Name = name;
            this.Wiring = wiring;
            this.TunringNotches = turningNotches;
        }

        /// <summary>
        /// Gets or sets the name of the component.
        /// </summary>
        public string Name { get; set; }

        /// <summary>
        /// Gets or sets the wiring to be used for this component.
        /// </summary>
        public string Wiring { get; set; }

        /// <summary>
        /// Gets or sets the letter that will turn the rotor.
        /// </summary>
        public string TunringNotches { get; set; }
    }
}


text:
<?php

namespace library\App;

/**
 * Form class.
 *
 * @author      Bogdan Ghervan <bogdan.ghervan@gmail.com>
 * @copyright   2014 Bogdan Ghervan
 * @link        http://github.com/cronkeep/cronkeep
 * @license     http://opensource.org/licenses/Apache-2.0 Apache License 2.0
 */
class Form extends \Zend\Form\Form
{
    /**
     * Retrieves validation error messages in a one-dimensional array format.
     *
     * @return array
     */
    public function getFormattedMessages()
    {
        $messages = $this->getMessages();
        $preparedMessages = array();

        // Prepend every element with the name of the form?
        $formName = $this->wrapElements() ? $this->getName() : '';

        // Prepare an one-dimensional array of error messages
        $this->_prepareMessages($messages, $preparedMessages, $formName);

        return $preparedMessages;
    }

    /**
     * Recursively iterates through the validation error messages in the format returned
     * by {@link Zend\Form\Form::getMessages()} and builds up a one-dimensional
     * representation in $output.
     *
     * @param array $messages Validation error messages
     * @param array $output Array where output is built
     * @param string $elementName Name to prepend (optional)
     * @param string $separator Separator for multiple messages on one element (optional)
     * @return Form
     */
    protected function _prepareMessages(array $messages, array &$output, $elementName = '',
        $separator = '. ')
    {
        if (is_string(current($messages))) {
            $output[$elementName] = implode($separator, $messages);
        } else {
            foreach ($messages as $currentName => $messageSet) {
                $currentName = $elementName ?
                    ($elementName . '[' . $currentName . ']') :
                    $currentName;

                $this->_prepareMessages($messageSet, $output, $currentName);
            }
        }

        return $this;
    }
}


text:
        <itemsourceimage-nolink [cssh]="collectedItem.itemSource.cssHorizontalOffset" [cssv]="collectedItem.itemSource.cssVerticalOffset"></itemsourceimage-nolink>

        <item-image-nolink [cssh]="collectedItem.item.cssHorizontalOffset" [cssv]="collectedItem.item.cssVerticalOffset"></item-image-nolink>

X


text:
module.exports.id = "challenges";

module.exports.up = function (done) {
  // use this.db for MongoDB communication, and this.log() for logging
    const challenges = this.db.collection('challenges');
    challenges.update(
        {"user" :{$exists: true}},
        {
            $set: {
                "user.fullName": 'Alex Torsk'
            },
            $unset: {
                "user.lastName": 1,
                "user.firstName": 1
            }
        },
        { multi: true }, done);
    done();
};

module.exports.down = function (done) {
  // use this.db for MongoDB communication, and this.log() for logging
  done();
};


text:
{{#shapes}}{{#selector.dimensions}}{{expression}}{{^last}},
{{/last}}{{/selector.dimensions}} {
	width: {{width.outer}}px;
	height: {{height.outer}}px;
}

{{/shapes}}


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class ClickToNextScene : MonoBehaviour {
    public string nextScene;

	// Update is called once per frame
	void Update () {
        if (Input.GetMouseButtonDown(0))
        {
            SceneManager.LoadScene(nextScene);
        }
	}
}


text:
    Background Image:  The Mustard Field Gone Wrong
    by goingslo is licensed under
    CC BY 2.0


text:
package com.anysoftkeyboard.ui;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import com.menny.android.anysoftkeyboard.R;

public class VoiceInputNotInstalledActivity extends Activity
        implements android.view.View.OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.voice_input_not_installed);
        findViewById(R.id.install_button).setOnClickListener(this);
        findViewById(R.id.no_button).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.install_button) {
            Intent search = new Intent(Intent.ACTION_VIEW);
            search.setData(Uri.parse("market://search?q=pname:com.google.android.voicesearch"));
            search.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            try {
                getApplicationContext().startActivity(search);
            } catch (Exception e) {
                Toast.makeText(
                                getApplicationContext(),
                                getText(R.string.voice_input_not_voice_pack_in_market),
                                Toast.LENGTH_LONG)
                        .show();
            }
        }

        finish();
    }
}


text:
using UnityEngine;
using UnityEngine.EventSystems;
using System.Collections;

public class UserInput : MonoBehaviour, IPointerClickHandler {

//	void Start(){}
//	void Update(){}

	// Mutually exclusive for now, priority is in the following order:
	// Left click for human,
	// Right for zombie,
	// Middle for corpse
	public void OnPointerClick(PointerEventData e)
	{
		if(e.button == PointerEventData.InputButton.Left)
		{
			FindObjectOfType<AgentDirector>().spawnAgent(Agent.AgentType.ZOMBIE, Camera.main.ScreenToWorldPoint(e.position));
		}
		else if(e.button == PointerEventData.InputButton.Right)
		{
			FindObjectOfType<AgentDirector>().spawnAgent(Agent.AgentType.HUMAN, Camera.main.ScreenToWorldPoint(e.position));
		}
		else if(e.button == PointerEventData.InputButton.Middle)
		{
			FindObjectOfType<AgentDirector>().spawnAgent(Agent.AgentType.CORPSE, Camera.main.ScreenToWorldPoint(e.position));
		}
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.ensipoly.match3">

    <application
        android:hardwareAccelerated="false"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".activities.MainActivity" android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".activities.GameActivity" android:screenOrientation="portrait" />
    </application>

</manifest>


text: Base API module for Lighp


text:
package com.github.amarcinkowski.metro.command;

public class CommandFactory {

    public final static int PACKAGE_NAME_INDEX=8;

    public Class<Command> getCommand(String name) throws ClassNotFoundException{
        String className = name.substring(0,1).toUpperCase() + name.substring(1) + "Command";
        String packageName = this.getClass().getPackage().toString().substring(PACKAGE_NAME_INDEX);
        return (Class<Command>) Class.forName(packageName + "." + className);
    }

}