text:
**Date:** 2019-10-03

1. [High-level migration plan](#high-level-migration-plan)
1. [New cluster architecture](#new-cluster-architecture)
1. [Elasticsearch 6 compatibility](#elasticsearch-6-compatibility)
1. [Connecting to multiple Elasticsearch clusters](#connecting-to-multiple-elasticsearch-clusters)
1. [Synchronising the state](#synchronising-the-state)
1. [Data sync for production -> staging -> integration](#data-sync-for-production---staging---integration)
1. [A/B testing Elasticsearch 6](#ab-testing-elasticsearch-6)
1. [Decomissioning Elasticsearch 5](#decomissioning-elasticsearch-5)

This work was done over 2019/20 Q1 and Q2.  Most of the changes were
made in this repository.  There were also significant changes in
[govuk-aws][], [govuk-aws-data][], and [govuk-puppet][].

[govuk-aws]: https://github.com/alphagov/govuk-aws
[govuk-aws-data]: https://github.com/alphagov/govuk-aws-data
[govuk-puppet]: https://github.com/alphagov/govuk-puppet

## High-level migration plan

Based on our experiences [migrating to Elasticsearch 5][] we decided
that this time we wanted to isolate the complexity of having two
Elasticsearch clusters to search-api:

1. Make search-api work with both Elasticsearch 5 and Elasticsearch 6.
2. Give search-api support for multiple Elasticsearch clusters:
   - Index changes into all clusters.
   - Add a URL parameter to select the cluster to use for a query.
3. Perform a one-time import of data from Elasticsearch 5 to
   Elasticsearch 6, and synchronise any updates missed while this
   import was running.
4. Confirm that the Elasticsearch 5 and Elasticsearch 6 clusters are
   consistent.
5. Set up an A/B test for finder-frontend (etc) to select which
   Elasticsearch cluster to use.
6. Gradually phase from 100% Elasticsearch 5 to 100% Elasticsearch 6.
7. Retire Elasticsearch 5.

The approach we took last time of having both rummager and search-api
running in parallel, necessitated by one being in Carrenza and one in
AWS, led to a lot of changes to govuk-puppet, and didn't really give
us anything reusable.  By adding multi-cluster support to search-api
directly, we do get something reusable.

[migrating to Elasticsearch 5]: https://github.com/alphagov/search-api/blob/master/docs/arch/adr-008-elasticsearch5-upgrade.md

## New cluster architecture

Based on our experience of running Elasticsearch 5 for a quarter, we
at first opted for:

- Three dedicated master nodes, of type `c4.large.elasticsearch`.
- Six data nodes, of type `r4.large.elasticsearch`.

We found the data nodes were not powerful enough, and switched to
`r4.xlarge.elasticsearch`.  After talking to an AWS Solutions
Architect, we changed again to `r5.xlarge.elasticsearch`.  Due to
wider GOV.UK scaling concerns caused by political activity, we
increased the data nodes to `r5.2xlarge.elasticsearch`.

We also shrunk the cluster in staging (to below production size), as
it does not need to cope with the indexing load.  The final cluster
sizes are:

| Environment | Master                       | Data                          |
| ----------- | ---------------------------- | ----------------------------- |
| Production  | 3x `c4.large.elasticsearch`  | 6x `r5.2xlarge.elasticsearch` |
| Staging     | 3x `c4.large.elasticsearch`  | 3x `r5.2xlarge.elasticsearch` |
| Integration | 3x `t2.medium.elasticsearch` | 3x `r5.large.elasticsearch`   |

The cluster is configured in the [app-elasticsearch6][] Terraform
project.

[app-elasticsearch6]: https://github.com/alphagov/govuk-aws/tree/master/terraform/projects/app-elasticsearch6

## Elasticsearch 6 compatibility

We used deprecation messages from Elasticsearch 5 and error messages
from Elasticsearch 6 to figure out what needed to change.  There were
some changes needed to the indices and some to the queries.

Index changes were:

- Switching from `string` fields to `text` and `keyword` fields ([PR #1553](https://github.com/alphagov/search-api/pull/1553)).
- Removing the use of the `_all` field and `include_in_all` ([PR #1557](https://github.com/alphagov/search-api/pull/1557)).

Query changes were:

- Using `like` instead of `docs` in the `more_like_this` query ([PR #1561](https://github.com/alphagov/search-api/pull/1561)).
- Replacing `match: { type: phrase }` with `match_phrase` queries ([PR #1564](https://github.com/alphagov/search-api/pull/1564)).
- Replacing `indices` query with a `should` query ([PR #1568](https://github.com/alphagov/search-api/pull/1568)).

The `indices`/`should` change introduced an inefficiency where query
generation now needs to ask Elasticsearch for the real name of an
alias.  We added a new `build_query` metric to keep track of this.
[Elasticsearch issue #23306][], opened in February 2017, is about a
solution to this problem.

We also changed the text similarity metric from [classic similarity][]
to the new [BM25 similarity][].

[Elasticsearch issue #23306]: https://github.com/elastic/elasticsearch/issues/23306
[classic similarity]: https://www.elastic.co/guide/en/elasticsearch/reference/6.0/index-modules-similarity.html#classic-similarity
[BM25 similarity]: https://www.elastic.co/guide/en/elasticsearch/reference/6.0/index-modules-similarity.html#bm25

## Connecting to multiple Elasticsearch clusters

The `elasticsearch.yml` file contains a list of clusters.  These
clusters can specify their own schema configuration file, which means
we can try out different index-level settings in a new cluster (for
example, changing the text similarity metric only for Elasticsearch
6).

In the code, the multi-cluster support is implemented in the
`SearchConfig` and `Index::Client` classes.  Cluster selection is
implemented in the `SearchParameterParser` class.

This involved some significant refactoring ([PR #1569][] and [PR
#1604][]).

The main architectural decisions made here were:

- To index writes to all clusters, ensuring cluster consistency.
- To perform queries against the default cluster unless a URL
  parameter is given, so we can A/B test clusters.
- To have one `SearchConfig` singleton per cluster.

This change did result in details of clusters leaking throughout
search-api, which is unfortunate, but that can be addressed in future
refactoring work (for example, passing around `SearchConfig` instances
rather than asking for cluster singletons).

[PR #1569]: https://github.com/alphagov/search-api/pull/1569
[PR #1604]: https://github.com/alphagov/search-api/pull/1604

## Synchronising the state

We planned to either take a snapshot from Elasticsearch 5 and restore
it to Elasticsearch 6, or to use the same approach as the last upgrade
(a script to copy the data across), but these turned out to be
unnecessary.

We had search-api running with both clusters for a couple of weeks
before we started to think about synchronising the data, and by that
time everything had been republished (either directly or as a result
of dependency resolution) and so the `govuk`, `government`, and
`detailed` indices were consistent with Elasticsearch 5.

The `page-traffic` index was also handled in the multi-cluster work,
with traffic data being saved to all clusters.

The only index which needed some manual work was `metasearch`, which
holds best bets.  Attempting to republish these from [search-admin][]
kept failing due to transient network issues, and getting all of the
best bets seemed impossible.  So for the `metasearch` index we used
this script:

```python
from elasticsearch5 import Elasticsearch as Elasticsearch5, TransportError as TransportError5
from elasticsearch6 import Elasticsearch as Elasticsearch6, TransportError as TransportError6
from elasticsearch6.helpers import bulk
from datetime import datetime
import os

INDEX = 'metasearch'
GENERIC_DOC_TYPE = 'generic-document'

ES5_HOST_PORT = os.getenv('ES5_ORIGIN_HOST', 'http://elasticsearch5:80')
ES6_TARGET_PORT = os.getenv('ES6_TARGET_HOST', 'http://elasticsearch6:80')

es_client5 = Elasticsearch5([ES5_HOST_PORT])
es_client6 = Elasticsearch6([ES6_TARGET_PORT])

def _prepare_docs_for_bulk_insert(docs):
    for doc in docs:
        yield {
            "_id": doc['_id'],
            "_source": doc['_source'],
        }

def bulk_index_documents_to_es6(documents):
    try:
        bulk(
            es_client6,
            _prepare_docs_for_bulk_insert(documents),
            index=INDEX,
            doc_type=GENERIC_DOC_TYPE,
            chunk_size=100
        )
    except TransportError6 as e:
        print("Failed to index documents: %s", str(e))

def fetch_documents(from_=0, page_size=100, scroll_id=None):
    try:
        if scroll_id is None:
            results = es_client5.search(INDEX, GENERIC_DOC_TYPE, from_=from_, size=page_size, scroll='2m')
            scroll_id = results['_scroll_id']
        else:
            results = es_client5.scroll(scroll_id=scroll_id, scroll='2m')
        docs = results['hits']['hits']
        return (scroll_id, docs)
    except TransportError5 as e:
        print("Failed to fetch documents: %s", str(e))
        return str(e), e.status_code

if __name__ == '__main__':
    start = datetime.now()

    dcount = es_client5.count(index=INDEX, doc_type=GENERIC_DOC_TYPE)['count']

    print('Preparing to index {} document(s) from ES5'.format(dcount))

    offset = 0
    page_size = 250
    scroll_id = None
    while offset <= dcount:
        scroll_id, docs = fetch_documents(from_=offset, page_size=page_size, scroll_id=scroll_id)

        print('Indexing documents {} to {} into ES6'.format(offset, offset+page_size))
        bulk_index_documents_to_es6(docs)

        offset += page_size

    print('Finished in {} seconds'.format(datetime.now() - start))
```

[search-admin]: https://github.com/alphagov/search-admin

## Data sync for production -> staging -> integration

This was done in the same way [as for Elasticsearch 5][].

The data sync script needed to be modified to allow for a different
host to be used (`http://elasticsearch6` vs `http://elasticsearch5`)
but otherwise this was just a matter of writing some more
configuration.

[as for Elasticsearch 5]: https://github.com/alphagov/search-api/blob/master/docs/arch/adr-008-elasticsearch5-upgrade.md

## A/B testing Elasticsearch 6

The A/B test was set up like so:

1. Configuration in govuk-cdn-config.
2. Logic in finder-frontend to pass one of two URL parameters to
   search-api, based on the CDN-level A/B test.
3. Logic in search-api to choose a cluster based on the parameter from
   finder-frontend.

The general A/B test process [is covered in the dev docs][].

For the A/B test we monitored click-through rate, proportion of search
refinements, and proportion of search exits.  The test revealed a
significant degradation in our metrics compared with Elasticsearch 5,
and we were unable to proceed with the switch without doing work to
improve the search results.

The two main changes in Elasticsearch 6 which impacted search result
quality were:

- Switching from classic similarity to [BM25 similarity][].  This
  issue arose with Elasticsearch 5, but we decided to go ahead with
  the new similarity when moving to Elasticsearch 6.

- The removal of query coordination factors, affecting the scoring of
  multi-clause `should` and `must` queries.  This meant that even if
  we switched back to classic similarity, we wouldn't get the same
  results we had with Elasticsearch 5.

With query coordination factors, multi-clause `should` and `must`
queries are scored as:

```
sum(clause scores) * num(matching clauses) / num(clauses)
```

So if a query has 7 clauses and 2 of them match, the overall score is
multipled by 2/7.  The effect of this is to make documents which match
multiple clauses tend to rank higher than documents which match fewer
clauses, even if those fewer clauses are matched really well.  The
assumption is that the number of matching clauses is an important
predictor of relevance.

Without query coordination factors, the query is scored as:

```
sum(clause scores)
```

Figuring out how to improve the search query was not a
straightforward, or particularly systematic, process.

Our Elasticsearch 5 query is:

```ruby
{
  bool: {
    should: [
      match_phrase("title", query),
      match_phrase("acronym", query),
      match_phrase("description", query),
      match_phrase("indexable_content", query),
      match_all_terms(%w(title acronym description indexable_content), query),
      match_any_terms(%w(title acronym description indexable_content), query),
      minimum_should_match("all_searchable_text", query)
    ],
  }
}
```

And the Elasticsearch 6 query we settled on is:

```ruby
should_coord_query([
  match_all_terms(%w(title), query, MATCH_ALL_TITLE_BOOST),
  match_all_terms(%w(acronym), query, MATCH_ALL_ACRONYM_BOOST),
  match_all_terms(%w(description), query, MATCH_ALL_DESCRIPTION_BOOST),
  match_all_terms(%w(indexable_content), query, MATCH_ALL_INDEXABLE_CONTENT_BOOST),
  match_all_terms(%w(title acronym description indexable_content), query, MATCH_ALL_MULTI_BOOST),
  match_any_terms(%w(title acronym description indexable_content), query, MATCH_ANY_MULTI_BOOST),
  minimum_should_match("all_searchable_text", query, MATCH_MINIMUM_BOOST)
])
```

Here `should_coord_query` is [a reimplementation of the query
coordination factor-based scoring][], using a [function_score][]
query.  We also changed the `match_phrase` clauses in the
Elasticsearch 5 query to `match_all_terms` clauses, and adjusted the
field boosting factors.

We then ran the A/B test again, and found that the Elasticsearch 6
with the new query had a clickthrough rate within 3 percentage points
of Elasticsearch 5 with the old query, and decided that this was good
enough to go ahead with the switch.

[is covered in the dev docs]: https://docs.publishing.service.gov.uk/manual/run-ab-test.html
[a reimplementation of the query coordination factor-based scoring]: https://github.com/alphagov/search-api/blob/df38c7ecc2af5e2c21d12096d10aca79ce900310/lib/search/query_helpers.rb#L62-L84
[function_score]: https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-function-score-query.html

## Decomissioning Elasticsearch 5

The steps we followed to switch to Elasticsearch 6 permanently and to
decomission Elasticsearch 5 were:

1. Switch search-api to the B variant of the A/B test and disable the A cluster so no more indexing is done ([PR #1713](https://github.com/alphagov/search-api/pull/1713)).
2. Disable the A/B test in govuk-cdn-config ([PR #203](https://github.com/alphagov/govuk-cdn-config/pull/203)) and finder-frontend ([PR #1611](https://github.com/alphagov/finder-frontend/pull/1611)).
3. Remove Elasticsearch 5 configuration from govuk-puppet ([PR #9643](https://github.com/alphagov/govuk-puppet/pull/9643)).
4. Remove Elasticsearch 5 from govuk-aws ([PR #1123](https://github.com/alphagov/govuk-aws/pull/1123)).

We didn't want to be permanently using the "B" configuration, which
required some care to change:

1. Set the `ELASTICSEARCH_URI` environment variable to the same value as the `ELASTICSEARCH_B_URI` environment variable in govuk-puppet ([PR #9648](https://github.com/alphagov/govuk-puppet/pull/9648)).
2. Swap out the "B" cluster configuration for the "A" cluster configuration ([PR #1718](https://github.com/alphagov/search-api/pull/1718)).
3. Unset the `ELASTICSEARCH_B_URI` environment variable in govuk-puppet ([PR #9649](https://github.com/alphagov/govuk-puppet/pull/9649)).

This approach avoided the need to coordinate simultaneous deploys of
search-api and govuk-puppet.


text:
<?php

namespace avadim\MathExecutor\Token;

use avadim\MathExecutor\Generic\AbstractToken;

/**
 * Class TokenVariable
 *
 * @package avadim\MathExecutor
 */
class TokenVariable extends AbstractToken
{
    protected static $matching = self::MATCH_REGEX;

    /**
     * @param string $pattern
     *
     * @return array
     */
    public static function getMatching($pattern = null)
    {
        return [
            'pattern'  => '/' . preg_quote($pattern, '/') . '[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/',
            'matching' => static::$matching,
            'callback' => static::$callback,
        ];
    }

}

redpajama_set_name: RedPajamaGithub


text:
libp2p can leverage the encrypted communications from the transports it uses (i.e WebRTC). To ensure that every connection is encrypted, independently of how it was set up, libp2p also supports a set of modules that encrypt every communication established.

We call this usage a _connection upgrade_ where given a connection between peer A to peer B, a protocol handshake can be performed that gives that connection new properties.

A byproduct of having these encrypted communications modules is that we can authenticate the peers we are dialing to. You might have noticed that every time we dial to a peer in libp2p space, we always use its PeerId at the end (e.g /ip4/127.0.0.1/tcp/89765/ipfs/QmWCbVw1XZ8hiYBwwshPce2yaTDYTqTaP7GCHGpry3ykWb), this PeerId is generated by hashing the Public Key of the peer. With this, we can create a crypto challenge when dialing to another peer and prove that peer is the owner of a PrivateKey that matches the Public Key we know.

# 1. Set up encrypted communications with SECIO

We will build this example on top of example for [Protocol and Stream Multiplexing](../protocol-and-stream-multiplexing). You will need the module `libp2p-secio` to complete it, go ahead and `npm install libp2p-secio`.

SECIO is the crypto channel developed for IPFS, it is a TLS 1.3 like crypto channel that established an encrypted communication channel between two peers.

To add it to your libp2p bundle, all you have to do is:

```JavaScript
const SECIO = require('libp2p-secio')

class MyBundle extends libp2p {
  constructor (peerInfo) {
    const defaults = {
      modules: {
        transport: [ TCP ],
        streamMuxer: [ SPDY ],
        // Attach secio as the crypto channel to use
        connEncryption: [ SECIO ]
      }
    }

    super(defaultsDeep(_options, defaults))
  }
}
```

And that's it, from now on, all your libp2p communications are encrypted. Try running the example [1.js](./1.js) to see it working.

If you want to want to learn more about how SECIO works, you can read the [great write up done by Dominic Tarr](https://github.com/auditdrivencrypto/secure-channel/blob/master/prior-art.md#ipfss-secure-channel).

Important note: SECIO hasn't been audited and so, we do not recommend to trust its security. We intent to move to TLS 1.3 once the specification is finalized and an implementation exists that we can use.


text:
AudioBeamFrameReader Events
===========================

Events
======

<colgroup>
<col width="30%" />
<col width="60%" />
</colgroup>

Name
Description

FrameArrived
Event that fires whenever a frame is captured.

PropertyChanged
Occurs when a property of the AudioBeamFrameReader class changes.

See also
========

#### Reference

[AudioBeamFrameReader Class](../AudioBeamFrameReader_Class.md)
 [WindowsPreview.Kinect Namespace](../../Kinect.md)


text:
package com.jetlag.jcreator.pictures;

import android.net.Uri;
import android.os.Parcel;
import android.os.Parcelable;
import android.provider.MediaStore;

/**
 * Created by vince on 17/04/16.
 */
public class DevicePicture implements Picture, Parcelable {

  private String storeId;
  private double latitude;
  private double longitude;
  private String description;
  private boolean picked;
  private State uploadState = State.LOCAL;

  public DevicePicture() {}

  public String getStoreId() {
    return storeId;
  }

  public void setStoreId(String storeId) {
    this.storeId = storeId;
  }

  public double getLatitude() {
    return latitude;
  }

  public void setLatitude(double latitude) {
    this.latitude = latitude;
  }

  public double getLongitude() {
    return longitude;
  }

  public void setLongitude(double longitude) {
    this.longitude = longitude;
  }

  public String getDescription() {
    return description;
  }

  public void setDescription(String description) {
    this.description = description;
  }

  public Uri getUri() {
    return Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, storeId);
  }

  public void setPicked(boolean picked) {
    this.picked = picked;
  }

  public boolean isPicked() {
    return picked;
  }

  @Override
  public State getState() {
    return uploadState;
  }

  /*
   * Parcelable
   */

  @Override
  public int describeContents() {
    return 0;
  }

  public static final Parcelable.Creator<DevicePicture> CREATOR
          = new Parcelable.Creator<DevicePicture>() {
    public DevicePicture createFromParcel(Parcel in) {
      return new DevicePicture(in);
    }

    public DevicePicture[] newArray(int size) {
      return new DevicePicture[size];
    }
  };

  private DevicePicture(Parcel in) {
    storeId = in.readString();
    latitude = in.readDouble();
    longitude = in.readDouble();
    description = in.readString();
    picked = in.readInt() > 0;
    uploadState = State.valueOf(in.readString());
  }

  @Override
  public void writeToParcel(Parcel parcel, int flags) {
    parcel.writeString(storeId);
    parcel.writeDouble(latitude);
    parcel.writeDouble(longitude);
    parcel.writeString(description);
    parcel.writeInt(picked ? 1 : 0);
    parcel.writeString(uploadState.name());
  }

}


text:
package esapi

import (
	"context"
	"net/http"
	"strconv"
	"strings"
)

func newGetFunc(t Transport) Get {
	return func(index string, id string, o ...func(*GetRequest)) (*Response, error) {
		var r = GetRequest{Index: index, DocumentID: id}
		for _, f := range o {
			f(&r)
		}
		return r.Do(r.ctx, t)
	}
}

// ----- API Definition -------------------------------------------------------

// Get returns a document.
//
// See full documentation at https://www.elastic.co/guide/en/elasticsearch/reference/master/docs-get.html.
//
type Get func(index string, id string, o ...func(*GetRequest)) (*Response, error)

// GetRequest configures the Get API request.
//
type GetRequest struct {
	Index        string
	DocumentType string
	DocumentID   string

	Preference     string
	Realtime       *bool
	Refresh        *bool
	Routing        string
	Source         []string
	SourceExcludes []string
	SourceIncludes []string
	StoredFields   []string
	Version        *int
	VersionType    string

	Pretty     bool
	Human      bool
	ErrorTrace bool
	FilterPath []string

	Header http.Header

	ctx context.Context
}

// Do executes the request and returns response or error.
//
func (r GetRequest) Do(ctx context.Context, transport Transport) (*Response, error) {
	var (
		method string
		path   strings.Builder
		params map[string]string
	)

	method = "GET"

	if r.DocumentType == "" {
		r.DocumentType = "_doc"
	}

	path.Grow(1 + len(r.Index) + 1 + len(r.DocumentType) + 1 + len(r.DocumentID))
	path.WriteString("/")
	path.WriteString(r.Index)
	if r.DocumentType != "" {
		path.WriteString("/")
		path.WriteString(r.DocumentType)
	}
	path.WriteString("/")
	path.WriteString(r.DocumentID)

	params = make(map[string]string)

	if r.Preference != "" {
		params["preference"] = r.Preference
	}

	if r.Realtime != nil {
		params["realtime"] = strconv.FormatBool(*r.Realtime)
	}

	if r.Refresh != nil {
		params["refresh"] = strconv.FormatBool(*r.Refresh)
	}

	if r.Routing != "" {
		params["routing"] = r.Routing
	}

	if len(r.Source) > 0 {
		params["_source"] = strings.Join(r.Source, ",")
	}

	if len(r.SourceExcludes) > 0 {
		params["_source_excludes"] = strings.Join(r.SourceExcludes, ",")
	}

	if len(r.SourceIncludes) > 0 {
		params["_source_includes"] = strings.Join(r.SourceIncludes, ",")
	}

	if len(r.StoredFields) > 0 {
		params["stored_fields"] = strings.Join(r.StoredFields, ",")
	}

	if r.Version != nil {
		params["version"] = strconv.FormatInt(int64(*r.Version), 10)
	}

	if r.VersionType != "" {
		params["version_type"] = r.VersionType
	}

	if r.Pretty {
		params["pretty"] = "true"
	}

	if r.Human {
		params["human"] = "true"
	}

	if r.ErrorTrace {
		params["error_trace"] = "true"
	}

	if len(r.FilterPath) > 0 {
		params["filter_path"] = strings.Join(r.FilterPath, ",")
	}

	req, err := newRequest(method, path.String(), nil)
	if err != nil {
		return nil, err
	}

	if len(params) > 0 {
		q := req.URL.Query()
		for k, v := range params {
			q.Set(k, v)
		}
		req.URL.RawQuery = q.Encode()
	}

	if len(r.Header) > 0 {
		if len(req.Header) == 0 {
			req.Header = r.Header
		} else {
			for k, vv := range r.Header {
				for _, v := range vv {
					req.Header.Add(k, v)
				}
			}
		}
	}

	if ctx != nil {
		req = req.WithContext(ctx)
	}

	res, err := transport.Perform(req)
	if err != nil {
		return nil, err
	}

	response := Response{
		StatusCode: res.StatusCode,
		Body:       res.Body,
		Header:     res.Header,
	}

	return &response, nil
}

// WithContext sets the request context.
//
func (f Get) WithContext(v context.Context) func(*GetRequest) {
	return func(r *GetRequest) {
		r.ctx = v
	}
}

// WithDocumentType - the type of the document (use `_all` to fetch the first document matching the ID across all types).
//
func (f Get) WithDocumentType(v string) func(*GetRequest) {
	return func(r *GetRequest) {
		r.DocumentType = v
	}
}

// WithPreference - specify the node or shard the operation should be performed on (default: random).
//
func (f Get) WithPreference(v string) func(*GetRequest) {
	return func(r *GetRequest) {
		r.Preference = v
	}
}

// WithRealtime - specify whether to perform the operation in realtime or search mode.
//
func (f Get) WithRealtime(v bool) func(*GetRequest) {
	return func(r *GetRequest) {
		r.Realtime = &v
	}
}

// WithRefresh - refresh the shard containing the document before performing the operation.
//
func (f Get) WithRefresh(v bool) func(*GetRequest) {
	return func(r *GetRequest) {
		r.Refresh = &v
	}
}

// WithRouting - specific routing value.
//
func (f Get) WithRouting(v string) func(*GetRequest) {
	return func(r *GetRequest) {
		r.Routing = v
	}
}

// WithSource - true or false to return the _source field or not, or a list of fields to return.
//
func (f Get) WithSource(v ...string) func(*GetRequest) {
	return func(r *GetRequest) {
		r.Source = v
	}
}

// WithSourceExcludes - a list of fields to exclude from the returned _source field.
//
func (f Get) WithSourceExcludes(v ...string) func(*GetRequest) {
	return func(r *GetRequest) {
		r.SourceExcludes = v
	}
}

// WithSourceIncludes - a list of fields to extract and return from the _source field.
//
func (f Get) WithSourceIncludes(v ...string) func(*GetRequest) {
	return func(r *GetRequest) {
		r.SourceIncludes = v
	}
}

// WithStoredFields - a list of stored fields to return in the response.
//
func (f Get) WithStoredFields(v ...string) func(*GetRequest) {
	return func(r *GetRequest) {
		r.StoredFields = v
	}
}

// WithVersion - explicit version number for concurrency control.
//
func (f Get) WithVersion(v int) func(*GetRequest) {
	return func(r *GetRequest) {
		r.Version = &v
	}
}

// WithVersionType - specific version type.
//
func (f Get) WithVersionType(v string) func(*GetRequest) {
	return func(r *GetRequest) {
		r.VersionType = v
	}
}

// WithPretty makes the response body pretty-printed.
//
func (f Get) WithPretty() func(*GetRequest) {
	return func(r *GetRequest) {
		r.Pretty = true
	}
}

// WithHuman makes statistical values human-readable.
//
func (f Get) WithHuman() func(*GetRequest) {
	return func(r *GetRequest) {
		r.Human = true
	}
}

// WithErrorTrace includes the stack trace for errors in the response body.
//
func (f Get) WithErrorTrace() func(*GetRequest) {
	return func(r *GetRequest) {
		r.ErrorTrace = true
	}
}

// WithFilterPath filters the properties of the response body.
//
func (f Get) WithFilterPath(v ...string) func(*GetRequest) {
	return func(r *GetRequest) {
		r.FilterPath = v
	}
}

// WithHeader adds the headers to the HTTP request.
//
func (f Get) WithHeader(h map[string]string) func(*GetRequest) {
	return func(r *GetRequest) {
		if r.Header == nil {
			r.Header = make(http.Header)
		}
		for k, v := range h {
			r.Header.Add(k, v)
		}
	}
}

// WithOpaqueID adds the X-Opaque-Id header to the HTTP request.
//
func (f Get) WithOpaqueID(s string) func(*GetRequest) {
	return func(r *GetRequest) {
		if r.Header == nil {
			r.Header = make(http.Header)
		}
		r.Header.Set("X-Opaque-Id", s)
	}
}


text:
def sort_by_bgp_neighbor(hashelem)
  key, value = hashelem
  # Newer way to use peer-group
  is_peer_group = value.include?('peer_group') && value['peer_group'].is_a?(TrueClass)
  # Older, but should not break those user configurations.
  is_peer_group |= value.include?('peer_type') && value['peer_type'] == 'peer-group'
  # 0 comes before 1.
  [is_peer_group ? 0 : 1, key, value]
end


text:
@interface XcodeCommonPlugin : NSObject

+ (instancetype)sharedPlugin;

@property (nonatomic, strong, readonly) NSBundle* bundle;
@end


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.trino.connector.system;

import io.trino.metadata.TablePropertyManager;
import io.trino.transaction.TransactionManager;

import javax.inject.Inject;

public class TablePropertiesSystemTable
        extends AbstractPropertiesSystemTable
{
    @Inject
    public TablePropertiesSystemTable(TransactionManager transactionManager, TablePropertyManager tablePropertyManager)
    {
        super("table_properties", transactionManager, tablePropertyManager::getAllProperties);
    }
}


text:
Advanced language features, that require either explicitly imported feature flag
or explicit compiler option to be enabled (SIP-18).

    Postfix operator notation:

    val s = 123 toString

    Reflective call:

    def foo(v: {def bar()}) = v.bar()

    Dynamic member selection:

    class Foo extends Dynamic

    Implicit conversion:

    implicit def toInt(s: String) = s.toInt

    Higher-kinded type:

    class Bar[M[A]]

    Existential type:

    def foo(v: Seq[T] forSome { type T })

    Macro definition:

    def assert(s: String) = macro Asserts.assertImpl

Scala compiler may also emit these warnings when "-feature" option is provided.

See: Project Settings / Compiler / Scala Compiler / Features

Since: Scala 2.10


text:
			<ng-form class="form-horizontal" name="newCourseForm" role="form">

					Title

						<input type="text" class="form-control" ng-model="course.title" maxlength="50" required placeholder="Title">

					Price

						<input type="number" min="0" class="form-control" ng-model="course.price" placeholder="price">

					Image

						<input type="text" class="form-control" ng-model="course.pic" placeholder="image url">

					Date

						<input type="text" class="form-control" ng-model="course.date" placeholder="enter date in dd/mm/yyyy" ng-pattern="/\d\d/\d\d/\d\d\d\d/">

					Description

						<textarea rows="6" class="form-control" ng-model="course.description" placeholder="Description"></textarea>

Review

					<my-preview preview-content="description">
					</my-preview>

						<button class="btn btn-success pull-right" ng-disabled="newCourseForm.$invalid" ng-click="addCourse(course, newCourseForm)">Create</button>

			</ng-form>


text:
package org.apache.hadoop.fs.s3a;

import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.GetObjectRequest;
import com.amazonaws.services.s3.model.S3Object;
import com.amazonaws.services.s3.model.S3ObjectInputStream;
import org.apache.hadoop.fs.FSExceptionMessages;
import org.apache.hadoop.fs.FSInputStream;
import org.apache.hadoop.fs.FileSystem;

import org.slf4j.Logger;

import java.io.EOFException;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.net.SocketException;

public class S3AInputStream extends FSInputStream {
  private long pos;
  private boolean closed;
  private S3ObjectInputStream wrappedStream;
  private S3Object wrappedObject;
  private FileSystem.Statistics stats;
  private AmazonS3Client client;
  private String bucket;
  private String key;
  private long contentLength;
  public static final Logger LOG = S3AFileSystem.LOG;

  public S3AInputStream(String bucket, String key, long contentLength, AmazonS3Client client,
                        FileSystem.Statistics stats) {
    this.bucket = bucket;
    this.key = key;
    this.contentLength = contentLength;
    this.client = client;
    this.stats = stats;
    this.pos = 0;
    this.closed = false;
    this.wrappedObject = null;
    this.wrappedStream = null;
  }

  private void openIfNeeded() throws IOException {
    if (wrappedObject == null) {
      reopen(0);
    }
  }

  private synchronized void reopen(long pos) throws IOException {

    if (wrappedStream != null) {
      if (LOG.isDebugEnabled()) {
        LOG.debug("Aborting old stream to open at pos " + pos);
      }
      wrappedStream.abort();
    }

    if (pos < 0) {
      throw new EOFException(FSExceptionMessages.NEGATIVE_SEEK
          +" " + pos);
    }

    if (contentLength > 0 && pos > contentLength-1) {
      throw new EOFException(
          FSExceptionMessages.CANNOT_SEEK_PAST_EOF
          + " " + pos);
    }

    LOG.debug("Actually opening file " + key + " at pos " + pos);

    GetObjectRequest request = new GetObjectRequest(bucket, key);
    request.setRange(pos, contentLength-1);

    wrappedObject = client.getObject(request);
    wrappedStream = wrappedObject.getObjectContent();

    if (wrappedStream == null) {
      throw new IOException("Null IO stream");
    }

    this.pos = pos;
  }

  @Override
  public synchronized long getPos() throws IOException {
    return pos;
  }

  @Override
  public synchronized void seek(long pos) throws IOException {
    checkNotClosed();

    if (this.pos == pos) {
      return;
    }

    LOG.debug(
        "Reopening " + this.key + " to seek to new offset " + (pos - this.pos));
    reopen(pos);
  }

  @Override
  public boolean seekToNewSource(long targetPos) throws IOException {
    return false;
  }

  @Override
  public synchronized int read() throws IOException {
    checkNotClosed();

    openIfNeeded();

    int byteRead;
    try {
      byteRead = wrappedStream.read();
    } catch (SocketTimeoutException e) {
      LOG.info("Got timeout while trying to read from stream, trying to recover " + e);
      reopen(pos);
      byteRead = wrappedStream.read();
    } catch (SocketException e) {
      LOG.info("Got socket exception while trying to read from stream, trying to recover " + e);
      reopen(pos);
      byteRead = wrappedStream.read();
    }

    if (byteRead >= 0) {
      pos++;
    }

    if (stats != null && byteRead >= 0) {
      stats.incrementBytesRead(1);
    }
    return byteRead;
  }

  @Override
  public synchronized int read(byte[] buf, int off, int len) throws IOException {
    checkNotClosed();

    openIfNeeded();

    int byteRead;
    try {
      byteRead = wrappedStream.read(buf, off, len);
    } catch (SocketTimeoutException e) {
      LOG.info("Got timeout while trying to read from stream, trying to recover " + e);
      reopen(pos);
      byteRead = wrappedStream.read(buf, off, len);
    } catch (SocketException e) {
      LOG.info("Got socket exception while trying to read from stream, trying to recover " + e);
      reopen(pos);
      byteRead = wrappedStream.read(buf, off, len);
    }

    if (byteRead > 0) {
      pos += byteRead;
    }

    if (stats != null && byteRead > 0) {
      stats.incrementBytesRead(byteRead);
    }

    return byteRead;
  }

  private void checkNotClosed() throws IOException {
    if (closed) {
      throw new IOException(FSExceptionMessages.STREAM_IS_CLOSED);
    }
  }

  @Override
  public synchronized void close() throws IOException {
    super.close();
    closed = true;
    if (wrappedObject != null) {
      wrappedObject.close();
    }
  }

  @Override
  public synchronized int available() throws IOException {
    checkNotClosed();

    long remaining = this.contentLength - this.pos;
    if (remaining > Integer.MAX_VALUE) {
      return Integer.MAX_VALUE;
    }
    return (int)remaining;
  }

  @Override
  public boolean markSupported() {
    return false;
  }
}


text:
from rest_framework import serializers

from .models import Book

class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book
        # fileds = ('title')
        fields = '__all__'


text:
using System;
using Moroco;
using SolrNet.Impl;

namespace SolrNet.Tests.Mocks {
    public class MSolrMoreLikeThisHandlerQueryResultsParser<T> : ISolrMoreLikeThisHandlerQueryResultsParser<T> {
        public MFunc<string, SolrMoreLikeThisHandlerResults<T>> parse;

        public SolrMoreLikeThisHandlerResults<T> Parse(string r) {
            return parse.Invoke(r);
        }
    }
}


text:
package com.facebook.buck.rules.coercer;

import com.facebook.buck.core.cell.nameresolver.CellNameResolver;
import com.facebook.buck.core.path.ForwardRelativePath;
import com.facebook.buck.io.filesystem.ProjectFilesystem;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.reflect.TypeToken;
import com.google.common.util.concurrent.UncheckedExecutionException;
import java.nio.file.Path;

/** Coerce to {@link java.nio.file.Path}. */
public class PathTypeCoercer extends LeafUnconfiguredOnlyCoercer<Path> {

  private final LoadingCache<Path, LoadingCache<String, Path>> pathCache =
      CacheBuilder.newBuilder()
          .build(
              CacheLoader.from(
                  pathRelativeToProjectRoot -> {
                    return CacheBuilder.newBuilder()
                        .weakValues()
                        .build(
                            CacheLoader.from(
                                path -> pathRelativeToProjectRoot.resolve(path).normalize()));
                  }));

  @Override
  public TypeToken<Path> getUnconfiguredType() {
    return TypeToken.of(Path.class);
  }

  @Override
  public Path coerceToUnconfigured(
      CellNameResolver cellRoots,
      ProjectFilesystem filesystem,
      ForwardRelativePath pathRelativeToProjectRoot,
      Object object)
      throws CoerceFailedException {
    if (object instanceof String) {
      String pathString = (String) object;
      if (pathString.isEmpty()) {
        throw new CoerceFailedException("invalid path");
      }
      try {
        Path fsPath = pathRelativeToProjectRoot.toPath(filesystem.getFileSystem());
        Path resultPath = pathCache.getUnchecked(fsPath).getUnchecked(pathString);
        if (resultPath.isAbsolute()) {
          throw CoerceFailedException.simple(
              object, getOutputType(), "Path cannot contain an absolute path");
        }
        if (resultPath.startsWith("..")) {
          throw CoerceFailedException.simple(
              object, getOutputType(), "Path cannot point to above repository root");
        }
        return resultPath;
      } catch (UncheckedExecutionException e) {
        throw new CoerceFailedException(
            String.format("Could not convert '%s' to a Path", pathString), e.getCause());
      }
    } else {
      throw CoerceFailedException.simple(object, getOutputType());
    }
  }

  public enum PathExistenceVerificationMode {
    VERIFY,
    DO_NOT_VERIFY,
  }
}


text:
using System;

namespace Jasily.Frameworks.Cli.Attributes
{
    [AttributeUsage(AttributeTargets.Constructor)]
    public sealed class CommandConstructorAttribute : BaseCommandAttribute
    {
    }
}


text:
from streamsx.spl import spl

#------------------------------------------------------------------
# Test passing in SPL types functions
#------------------------------------------------------------------

# Defines the SPL namespace for any functions in this module
# Multiple modules can map to the same namespace
def spl_namespace():
    return "com.ibm.streamsx.topology.pytest.pyprimitives"

@spl.primitive_operator()
class NoPorts(object):
    def __init__(self, mn, iv):
        self.mn = mn
        self.iv = iv

    def __enter__(self):
        import streamsx.ec as ec
        self.cm = ec.CustomMetric(self, 'NP_' + self.mn)
        self.cm.value = self.iv

    def __exit__(self, exc_type, exc_value, traceback):
        pass

@spl.primitive_operator()
class SingleInputPort(object):
    def __init__(self):
        pass

    def __enter__(self):
        import streamsx.ec as ec
        self.cm = ec.CustomMetric(self, 'SIP_METRIC')

    def __exit__(self, exc_type, exc_value, traceback):
        pass

    @spl.input_port()
    def my_only_port(self, *t):
        self.cm.value = t[0] + 17

@spl.primitive_operator()
class MultiInputPort(object):
    def __init__(self):
        pass

    def __enter__(self):
        import streamsx.ec as ec
        self.cm0 = ec.CustomMetric(self, 'MIP_METRIC_0')
        self.cm1 = ec.CustomMetric(self, 'MIP_METRIC_1')
        self.cm2 = ec.CustomMetric(self, 'MIP_METRIC_2')

    def __exit__(self, exc_type, exc_value, traceback):
        pass

    @spl.input_port()
    def port0(self, *t):
        self.cm0.value = t[0] + 17

    @spl.input_port()
    def port1(self, **t):
        self.cm1.value = t['v'] + 34

    @spl.input_port()
    def port2(self, *t):
        self.cm2.value = t[0] + 51

@spl.primitive_operator(output_ports=['A'])
class SingleOutputPort(spl.PrimitiveOperator):
    def __init__(self):
        pass

    @spl.input_port()
    def port0(self, *t):
        self.submit('A', t)

@spl.primitive_operator(output_ports=[1,2,3])
class MultiOutputPorts(spl.PrimitiveOperator):
    def __init__(self):
        pass

    @spl.input_port()
    def port0(self, *t):
        self.submit(1, t)
        self.submit(2, (t[0] + 921,))
        self.submit(3, (t[0] - 407,))

@spl.primitive_operator(output_ports=['A', 'B'])
class DictOutputPorts(spl.PrimitiveOperator):
    def __init__(self):
        pass

    @spl.input_port()
    def port0(self, **tuple_):
        self.submit('A', tuple_)
        self.submit('B', [{'d':tuple_['d'] + 7, 'e':tuple_['f'] + 77, 'f':tuple_['e'] + 777}, tuple_],)

@spl.primitive_operator(output_ports=['A'])
class InputByPosition(spl.PrimitiveOperator):
    def __init__(self):
        pass

    @spl.input_port(style='position')
    def port0(self, a, b):
        self.submit('A', (a,b+89,-92))

import threading
@spl.primitive_operator(output_ports=['A'])
class OutputOnly(spl.PrimitiveOperator):
    def __init__(self, count):
        self.count = count

    def all_ports_ready(self):
        self.submitter = threading.Thread(target=self.submit_some)
        self.submitter.start()
        return self.submitter.join

    def submit_some(self):
        for i in range(self.count):
            self.submit('A', (i+501,))


text: extern inline linux_error_t linux_rename(char const* oldname, char const* newname);


text:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign#Polyfill

function isFunction(obj) {
  return typeof obj === 'function'
}

var EVENTS = {
  MOUSE_ENTER: 'mouseenter',
  MOUSE_LEAVE: 'mouseleave',
  MOUSE_DOWN: 'mousedown',
  MOUSE_UP: 'mouseup',
  FOCUS: 'focus',
  BLUR: 'blur',
  CLICK: 'click',
  INPUT: 'input',
  KEY_DOWN: 'keydown',
  KEY_UP: 'keyup',
  KEY_PRESS: 'keypress',
  RESIZE: 'resize',
  SCROLL: 'scroll',
  TOUCH_START: 'touchstart',
  TOUCH_END: 'touchend',
};

function on(element, event, handler) {
  /* istanbul ignore next */
  element.addEventListener(event, handler);
}

function off(element, event, handler) {
  /* istanbul ignore next */
  element.removeEventListener(event, handler);
}

var HANDLER = '_uiv_scroll_handler';
var events = [EVENTS.RESIZE, EVENTS.SCROLL];

var bind = function (el, binding) {
  var callback = binding.value;
  if (!isFunction(callback)) {
    return
  }
  unbind(el);
  el[HANDLER] = callback;
  events.forEach(function (event) {
    on(window, event, el[HANDLER]);
  });
};

var unbind = function (el) {
  events.forEach(function (event) {
    off(window, event, el[HANDLER]);
  });
  delete el[HANDLER];
};

var update = function (el, binding) {
  if (binding.value !== binding.oldValue) {
    bind(el, binding);
  }
};

var scroll = { bind: bind, unbind: unbind, update: update };

//

var script = {
  directives: {
    scroll: scroll,
  },
  props: {
    offset: {
      type: Number,
      default: 0,
    },
  },
  data: function data() {
    return {
      affixed: false,
    }
  },
  computed: {
    classes: function classes() {
      return {
        affix: this.affixed,
      }
    },
    styles: function styles() {
      return {
        top: this.affixed ? this.offset + 'px' : null,
      }
    },
  },
  methods: {
    // from https://github.com/ant-design/ant-design/blob/master/components/affix/index.jsx#L20
    onScroll: function onScroll() {
      var this$1$1 = this;

      // if is hidden don't calculate anything
      if (
        !(
          this.$el.offsetWidth ||
          this.$el.offsetHeight ||
          this.$el.getClientRects().length
        )
      ) {
        return
      }
      // get window scroll and element position to detect if have to be normal or affixed
      var scroll = {};
      var element = {};
      var rect = this.$el.getBoundingClientRect();
      var body = document.body;
      var types = ['Top', 'Left'];
      types.forEach(function (type) {
        var t = type.toLowerCase();
        scroll[t] = window['page' + (type === 'Top' ? 'Y' : 'X') + 'Offset'];
        element[t] =
          scroll[t] +
          rect[t] -
          (this$1$1.$el['client' + type] || body['client' + type] || 0);
      });
      var fix = scroll.top > element.top - this.offset;
      if (this.affixed !== fix) {
        this.affixed = fix;
        this.$emit(this.affixed ? 'affix' : 'unfix');
        this.$nextTick(function () {
          this$1$1.$emit(this$1$1.affixed ? 'affixed' : 'unfixed');
        });
      }
    },
  },
};

function normalizeComponent(template, style, script, scopeId, isFunctionalTemplate, moduleIdentifier /* server only */, shadowMode, createInjector, createInjectorSSR, createInjectorShadow) {
    if (typeof shadowMode !== 'boolean') {
        createInjectorSSR = createInjector;
        createInjector = shadowMode;
        shadowMode = false;
    }
    // Vue.extend constructor export interop.
    var options = typeof script === 'function' ? script.options : script;
    // render functions
    if (template && template.render) {
        options.render = template.render;
        options.staticRenderFns = template.staticRenderFns;
        options._compiled = true;
        // functional template
        if (isFunctionalTemplate) {
            options.functional = true;
        }
    }
    // scopedId
    if (scopeId) {
        options._scopeId = scopeId;
    }
    var hook;
    if (moduleIdentifier) {
        // server build
        hook = function (context) {
            // 2.3 injection
            context =
                context || // cached call
                    (this.$vnode && this.$vnode.ssrContext) || // stateful
                    (this.parent && this.parent.$vnode && this.parent.$vnode.ssrContext); // functional
            // 2.2 with runInNewContext: true
            if (!context && typeof __VUE_SSR_CONTEXT__ !== 'undefined') {
                context = __VUE_SSR_CONTEXT__;
            }
            // inject component styles
            if (style) {
                style.call(this, createInjectorSSR(context));
            }
            // register component module identifier for async chunk inference
            if (context && context._registeredComponents) {
                context._registeredComponents.add(moduleIdentifier);
            }
        };
        // used by ssr in case component is cached and beforeCreate
        // never gets called
        options._ssrRegister = hook;
    }
    else if (style) {
        hook = shadowMode
            ? function (context) {
                style.call(this, createInjectorShadow(context, this.$root.$options.shadowRoot));
            }
            : function (context) {
                style.call(this, createInjector(context));
            };
    }
    if (hook) {
        if (options.functional) {
            // register for functional component in vue file
            var originalRender = options.render;
            options.render = function renderWithStyleInjection(h, context) {
                hook.call(context);
                return originalRender(h, context);
            };
        }
        else {
            // inject component registration as beforeCreate hook
            var existing = options.beforeCreate;
            options.beforeCreate = existing ? [].concat(existing, hook) : [hook];
        }
    }
    return script;
}

/* script */
var __vue_script__ = script;

/* template */
var __vue_render__ = function () {
  var _vm = this;
  var _h = _vm.$createElement;
  var _c = _vm._self._c || _h;
  return _c("div", { staticClass: "hidden-print" }, [
    _c(
      "div",
      {
        directives: [
          {
            name: "scroll",
            rawName: "v-scroll",
            value: _vm.onScroll,
            expression: "onScroll",
          } ],
        class: _vm.classes,
        style: _vm.styles,
      },
      [_vm._t("default")],
      2
    ) ])
};
var __vue_staticRenderFns__ = [];
__vue_render__._withStripped = true;

  /* style */
  var __vue_inject_styles__ = undefined;
  /* scoped */
  var __vue_scope_id__ = undefined;
  /* module identifier */
  var __vue_module_identifier__ = undefined;
  /* functional template */
  var __vue_is_functional_template__ = false;
  /* style inject */

  /* style inject SSR */

  /* style inject shadow dom */

  var __vue_component__ = /*#__PURE__*/normalizeComponent(
    { render: __vue_render__, staticRenderFns: __vue_staticRenderFns__ },
    __vue_inject_styles__,
    __vue_script__,
    __vue_scope_id__,
    __vue_is_functional_template__,
    __vue_module_identifier__,
    false,
    undefined,
    undefined,
    undefined
  );

export { __vue_component__ as default };
//# sourceMappingURL=Affix.js.map


text:
/*++

Module Name:

  PlatformIsa.c

Abstract:

  Platform related Isa definition.

--*/

#include "DebugSupportBBTestMain.h"

EFI_INSTRUCTION_SET_ARCHITECTURE PlatformIsa = IsaIa32;


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
All Classes (SMPPSim)
</TITLE>

<META NAME="date" CONTENT="2008-06-06">

<LINK REL ="stylesheet" TYPE="text/css" HREF="stylesheet.css" TITLE="Style">

All Classes

BindReceiver

BindReceiverException

BindReceiverResp

BindTransceiver

BindTransceiverException

BindTransceiverResp

BindTransmitter

BindTransmitterException

BindTransmitterResp

CallbackServerConnector

CancelSM

CancelSmFailedException

CancelSMResp

DataSM

DataSMResp

DeliverSM

DeliverSmFailedException

DeliverSMResp

DeliveryReceipt

Demarshaller

DestAddress

DestAddressDL

DestAddressSME

DeterministicLifeCycleManager

EnquireLink

EnquireLinkFailedException

EnquireLinkResp

GenericNak

GenericNakResp

HttpHandler

InboundQueue

InboundQueueFullException

InternalException

InvalidHexStringlException

LifeCycleManager

LogFormatter

LoggingUtilities

Marshaller

MessageQueue

MessageState

MessageStateNotFoundException

MoMessagePool

MoService

Outbind

OutbindTest

OutboundQueue

OutboundQueueFullException

Pdu

PduConstants

PduUtilities

QuerySM

QuerySmFailedException

QuerySMResp

ReceiverLogger

ReplaceSM

ReplaceSmFailedException

ReplaceSMResp

Request

Response

Session

SMPPSim

SmppsimBindTests

SmppsimCancelSmTests

SmppsimDeliverSmTests

SmppsimEnquireLinkTests

SmppsimQuerySmTests

SmppsimReplaceSmTests

SmppsimSubmitMultiTests

SmppsimSubmitSmTests

SmppsimTests

SmppTime

Smsc

StandardConnectionHandler

StandardProtocolHandler

SubmitMulti

SubmitMultiFailedException

SubmitMultiResp

SubmitSM

SubmitSmFailedException

SubmitSMResp

TestProtocolHandler1

Tlv

TlvEmpty

Unbind

UnbindResp

UnsuccessSME

Utilities


text:
[jvm]
Content
open override fun [type](type.md)(value: [Type](https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Type.html)): [S](index.md)
More info

See T.type


text:
class testApp : public ofBaseApp{

public:
    void setup();
    void update();
    void draw();

    void keyPressed  (int key);
    void keyReleased(int key);
    void mouseMoved(int x, int y );
    void mouseDragged(int x, int y, int button);
    void mousePressed(int x, int y, int button);
    void mouseReleased(int x, int y, int button);
    void windowResized(int w, int h);
    void dragEvent(ofDragInfo dragInfo);
    void gotMessage(ofMessage msg);

    ofVideoGrabber vidGrabber;
    SmartLayerManager smartLayerManager;

    // Pointer to shape returned by layer manger when doing shape selected
    SmartShape * selectedShape;
    // Indicates a shape has been selected (as apposed to just highlighted)
    bool selected;

    // For cycling through layers
    int layerOffset;

};


text:
package com.intellij.openapi.command.impl;

import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.CommandEvent;
import com.intellij.openapi.command.CommandListener;
import com.intellij.openapi.command.CommandProcessorEx;
import com.intellij.openapi.command.UndoConfirmationPolicy;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.EmptyRunnable;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.List;
import java.util.Stack;

public class CoreCommandProcessor extends CommandProcessorEx {
  private static class CommandDescriptor {
    public final Runnable myCommand;
    public final Project myProject;
    public String myName;
    public Object myGroupId;
    public final Document myDocument;
    public final UndoConfirmationPolicy myUndoConfirmationPolicy;

    public CommandDescriptor(Runnable command,
                             Project project,
                             String name,
                             Object groupId,
                             UndoConfirmationPolicy undoConfirmationPolicy,
                             Document document) {
      myCommand = command;
      myProject = project;
      myName = name;
      myGroupId = groupId;
      myUndoConfirmationPolicy = undoConfirmationPolicy;
      myDocument = document;
    }

    @Override
    public String toString() {
      return "'" + myName + "', group: '" + myGroupId + "'";
    }
  }

  protected CommandDescriptor myCurrentCommand = null;
  private final Stack<CommandDescriptor> myInterruptedCommands = new Stack<CommandDescriptor>();

//  private HashMap myStatisticsMap = new HashMap(); // command name --> count

  //  private HashMap myStatisticsMap = new HashMap(); // command name --> count

  private final List<CommandListener> myListeners = ContainerUtil.createLockFreeCopyOnWriteList();

  private int myUndoTransparentCount = 0;

  @Override
  public void executeCommand(@NotNull Runnable runnable, String name, Object groupId) {
    executeCommand(null, runnable, name, groupId);
  }

  @Override
  public void executeCommand(Project project, @NotNull Runnable runnable, String name, Object groupId) {
    executeCommand(project, runnable, name, groupId, UndoConfirmationPolicy.DEFAULT);
  }

  @Override
  public void executeCommand(Project project, @NotNull Runnable runnable, String name, Object groupId, Document document) {
    executeCommand(project, runnable, name, groupId, UndoConfirmationPolicy.DEFAULT, document);
  }

  @Override
  public void executeCommand(Project project,
                             @NotNull final Runnable command,
                             final String name,
                             final Object groupId,
                             @NotNull UndoConfirmationPolicy confirmationPolicy) {
    executeCommand(project, command, name, groupId, confirmationPolicy, null);
  }

  @Override
  public void executeCommand(Project project,
                             @NotNull final Runnable command,
                             final String name,
                             final Object groupId,
                             @NotNull UndoConfirmationPolicy confirmationPolicy,
                             Document document) {
    ApplicationManager.getApplication().assertIsDispatchThread();
    if (project != null && project.isDisposed()) return;

    if (CommandLog.LOG.isDebugEnabled()) {
      CommandLog.LOG.debug("executeCommand: " + command + ", name = " + name + ", groupId = " + groupId);
    }

    if (myCurrentCommand != null) {
      command.run();
      return;
    }
    Throwable throwable = null;
    try {
      myCurrentCommand = new CommandDescriptor(command, project, name, groupId, confirmationPolicy, document);
      fireCommandStarted();
      command.run();
    }
    catch (Throwable th) {
      throwable = th;
    }
    finally {
      finishCommand(project, myCurrentCommand, throwable);
    }
  }

  @Override
  @Nullable
  public Object startCommand(final Project project,
                             @Nls final String name,
                             final Object groupId,
                             final UndoConfirmationPolicy undoConfirmationPolicy) {
    ApplicationManager.getApplication().assertIsDispatchThread();
    if (project != null && project.isDisposed()) return null;

    if (CommandLog.LOG.isDebugEnabled()) {
      CommandLog.LOG.debug("startCommand: name = " + name + ", groupId = " + groupId);
    }

    if (myCurrentCommand != null) {
      return null;
    }

    Document document = groupId instanceof Ref && ((Ref)groupId).get() instanceof Document ? (Document)((Ref)groupId).get() : null;
    myCurrentCommand = new CommandDescriptor(EmptyRunnable.INSTANCE, project, name, groupId, undoConfirmationPolicy, document);
    fireCommandStarted();
    return myCurrentCommand;
  }

  @Override
  public void finishCommand(final Project project, final Object command, final Throwable throwable) {
    ApplicationManager.getApplication().assertIsDispatchThread();
    CommandLog.LOG.assertTrue(myCurrentCommand != null, "no current command in progress");
    fireCommandFinished();
  }

  protected void fireCommandFinished() {
    ApplicationManager.getApplication().assertIsDispatchThread();
    CommandDescriptor currentCommand = myCurrentCommand;
    CommandEvent event = new CommandEvent(this, currentCommand.myCommand,
                                          currentCommand.myName,
                                          currentCommand.myGroupId,
                                          currentCommand.myProject,
                                          currentCommand.myUndoConfirmationPolicy,
                                          currentCommand.myDocument);
    try {
      for (CommandListener listener : myListeners) {
        try {
          listener.beforeCommandFinished(event);
        }
        catch (Throwable e) {
          CommandLog.LOG.error(e);
        }
      }
    }
    finally {
      myCurrentCommand = null;
      for (CommandListener listener : myListeners) {
        try {
          listener.commandFinished(event);
        }
        catch (Throwable e) {
          CommandLog.LOG.error(e);
        }
      }
    }
  }

  @Override
  public void enterModal() {
    ApplicationManager.getApplication().assertIsDispatchThread();
    CommandDescriptor currentCommand = myCurrentCommand;
    myInterruptedCommands.push(currentCommand);
    if (currentCommand != null) {
      fireCommandFinished();
    }
  }

  @Override
  public void leaveModal() {
    ApplicationManager.getApplication().assertIsDispatchThread();
    CommandLog.LOG.assertTrue(myCurrentCommand == null, "Command must not run: " + String.valueOf(myCurrentCommand));

    myCurrentCommand = myInterruptedCommands.pop();
    if (myCurrentCommand != null) {
      fireCommandStarted();
    }
  }

  @Override
  public void setCurrentCommandName(String name) {
    ApplicationManager.getApplication().assertIsDispatchThread();
    CommandDescriptor currentCommand = myCurrentCommand;
    CommandLog.LOG.assertTrue(currentCommand != null);
    currentCommand.myName = name;
  }

  @Override
  public void setCurrentCommandGroupId(Object groupId) {
    ApplicationManager.getApplication().assertIsDispatchThread();
    CommandDescriptor currentCommand = myCurrentCommand;
    CommandLog.LOG.assertTrue(currentCommand != null);
    currentCommand.myGroupId = groupId;
  }

  @Override
  @Nullable
  public Runnable getCurrentCommand() {
    CommandDescriptor currentCommand = myCurrentCommand;
    return currentCommand != null ? currentCommand.myCommand : null;
  }

  @Override
  @Nullable
  public String getCurrentCommandName() {
    CommandDescriptor currentCommand = myCurrentCommand;
    if (currentCommand != null) return currentCommand.myName;
    if (!myInterruptedCommands.isEmpty()) {
      final CommandDescriptor command = myInterruptedCommands.peek();
      return command != null ? command.myName : null;
    }
    return null;
  }

  @Override
  @Nullable
  public Object getCurrentCommandGroupId() {
    CommandDescriptor currentCommand = myCurrentCommand;
    if (currentCommand != null) return currentCommand.myGroupId;
    if (!myInterruptedCommands.isEmpty()) {
      final CommandDescriptor command = myInterruptedCommands.peek();
      return command != null ? command.myGroupId : null;
    }
    return null;
  }

  @Override
  @Nullable
  public Project getCurrentCommandProject() {
    CommandDescriptor currentCommand = myCurrentCommand;
    return currentCommand != null ? currentCommand.myProject : null;
  }

  @Override
  public void addCommandListener(@NotNull CommandListener listener) {
    myListeners.add(listener);
  }

  @Override
  public void addCommandListener(@NotNull final CommandListener listener, @NotNull Disposable parentDisposable) {
    addCommandListener(listener);
    Disposer.register(parentDisposable, new Disposable() {
      @Override
      public void dispose() {
        removeCommandListener(listener);
      }
    });
  }

  @Override
  public void removeCommandListener(@NotNull CommandListener listener) {
    myListeners.remove(listener);
  }

  @Override
  public void runUndoTransparentAction(@NotNull Runnable action) {
    if (myUndoTransparentCount++ == 0) fireUndoTransparentStarted();
    try {
      action.run();
    }
    finally {
      if (--myUndoTransparentCount == 0) fireUndoTransparentFinished();
    }
  }

  @Override
  public boolean isUndoTransparentActionInProgress() {
    return myUndoTransparentCount > 0;
  }

  @Override
  public void markCurrentCommandAsGlobal(Project project) {
  }

  @Override
  public void addAffectedDocuments(Project project, @NotNull Document... docs) {
  }

  @Override
  public void addAffectedFiles(Project project, @NotNull VirtualFile... files) {
  }

  private void fireCommandStarted() {
    ApplicationManager.getApplication().assertIsDispatchThread();
    CommandDescriptor currentCommand = myCurrentCommand;
    CommandEvent event = new CommandEvent(this,
                                          currentCommand.myCommand,
                                          currentCommand.myName,
                                          currentCommand.myGroupId,
                                          currentCommand.myProject,
                                          currentCommand.myUndoConfirmationPolicy,
                                          currentCommand.myDocument);
    for (CommandListener listener : myListeners) {
      try {
        listener.commandStarted(event);
      }
      catch (Throwable e) {
        CommandLog.LOG.error(e);
      }
    }
  }

  private void fireUndoTransparentStarted() {
    for (CommandListener listener : myListeners) {
      try {
        listener.undoTransparentActionStarted();
      }
      catch (Throwable e) {
        CommandLog.LOG.error(e);
      }
    }
  }

  private void fireUndoTransparentFinished() {
    for (CommandListener listener : myListeners) {
      try {
        listener.undoTransparentActionFinished();
      }
      catch (Throwable e) {
        CommandLog.LOG.error(e);
      }
    }
  }
}


text:
namespace IxMilia.Iges.Entities
{
    public class IgesCubicTriangle : IgesFiniteElement
    {
        public override IgesElementEdgeOrder EdgeOrder { get { return IgesElementEdgeOrder.Cubic; } }

        public IgesPoint P1 { get; set; }
        public IgesPoint P1P2Control1 { get; set; }
        public IgesPoint P1P2Control2 { get; set; }
        public IgesPoint P2 { get; set; }
        public IgesPoint P2P3Control1 { get; set; }
        public IgesPoint P2P3Control2 { get; set; }
        public IgesPoint P3 { get; set; }
        public IgesPoint P3P1Control1 { get; set; }
        public IgesPoint P3P1Control2 { get; set; }

        public IgesCubicTriangle(
            IgesPoint p1,
            IgesPoint p1P2Control1,
            IgesPoint p1P2Control2,
            IgesPoint p2,
            IgesPoint p2P3Control1,
            IgesPoint p2P3Control2,
            IgesPoint p3,
            IgesPoint p3P1Control1,
            IgesPoint p3P1Control2)
            : base(IgesTopologyType.CubicTriangle)
        {
            P1 = p1;
            P1P2Control1 = p1P2Control1;
            P1P2Control2 = p1P2Control2;
            P2 = p2;
            P2P3Control1 = p2P3Control1;
            P2P3Control2 = p2P3Control2;
            P3 = p3;
            P3P1Control1 = p3P1Control1;
            P3P1Control2 = p3P1Control2;
        }

        protected override void AddNodes()
        {
            InternalNodes.Add(new IgesNode(P1));
            InternalNodes.Add(new IgesNode(P1P2Control1));
            InternalNodes.Add(new IgesNode(P1P2Control2));
            InternalNodes.Add(new IgesNode(P2));
            InternalNodes.Add(new IgesNode(P2P3Control1));
            InternalNodes.Add(new IgesNode(P2P3Control2));
            InternalNodes.Add(new IgesNode(P3));
            InternalNodes.Add(new IgesNode(P3P1Control1));
            InternalNodes.Add(new IgesNode(P3P1Control2));
        }

        internal static IgesCubicTriangle FromDummy(IgesFiniteElementDummy dummy)
        {
            return new IgesCubicTriangle(
                GetNodeOffset(dummy, 0),
                GetNodeOffset(dummy, 1),
                GetNodeOffset(dummy, 2),
                GetNodeOffset(dummy, 3),
                GetNodeOffset(dummy, 4),
                GetNodeOffset(dummy, 5),
                GetNodeOffset(dummy, 6),
                GetNodeOffset(dummy, 7),
                GetNodeOffset(dummy, 8));
        }
    }
}


text:
layout: post
title:  "Assignment Five Reflection"
date:   2016-11-16 19:45:31 +0530
categories: jekyll update
---

This assignment created a script that stored the answers to our previous assignment in a database.
The database created has the names, hometowns, number of siblings, age, and favorite movies of all the respondants along with the time stamp and random string.
The first step was the set a variable for the username and to make the passwork blank. We did this with `password=''` because mysql requires a username and password.
Our script initializes mysql then creates a database called malily and then fills the database with the contents of a mysql file called *malilydab.sql*.
We then opened the database abd inserted the contents of *tblFinal*, the responses to our intial questions, into the database.
The database then dumped into *malilydab.sql*. This circular dumping ensures that the previous responses will all be there no matter who runs the script. We also edited the script to show
the responder the database with their responses in it as well as all the previous responses.

I learned a lot during this assignment because Malvika had experience using mysql before while I had none.
She did a very good job of explaining what we need to do and how to do it. We worked well together to fix issues we had.
One issue was simply with syntax problems. We researched a while before we realized that mysqldump need to be a seperate command from the rest.
We also had a problem where the script would not work unless mysql was initialized in the terminal.
We fixed this by using the command `mysql-ctl start` at the beginning of our script. I am excited to learn more about the possible applications of this database.
It's very cool to know how to create one but since I have no experience with mysql I don't really know what the possibilities are in analyzing it now.

Here is our [respository](https://github.com/ldinkins/malily5.git).


text:
    <meta charset="utf-8">
    <title>接口代理,数据mock</title>
    <link rel="stylesheet" href="./target/build.css">


text:
.icon-email { background-image: url('png/email.png'); background-repeat: no-repeat; }

.icon-social-facebook { background-image: url('png/social-facebook.png'); background-repeat: no-repeat; }

.icon-social-instagram { background-image: url('png/social-instagram.png'); background-repeat: no-repeat; }

.icon-social-pinterest { background-image: url('png/social-pinterest.png'); background-repeat: no-repeat; }

.icon-social-twitter { background-image: url('png/social-twitter.png'); background-repeat: no-repeat; }

.icon-social-youtube { background-image: url('png/social-youtube.png'); background-repeat: no-repeat; }


text:
package org.intellij.lang.xpath.context;

import javax.annotation.Nonnull;

import com.intellij.codeInsight.intention.IntentionAction;
import com.intellij.psi.PsiElement;

import org.intellij.lang.xpath.psi.XPathVariable;
import org.intellij.lang.xpath.psi.XPathVariableReference;

/*
* Created by IntelliJ IDEA.
* User: sweinreuter
* Date: 08.01.2008
*/
public abstract class SimpleVariableContext implements VariableContext<String> {

    public XPathVariable resolve(XPathVariableReference reference) {
        return null;
    }

    public boolean canResolve() {
        return false;
    }

    @Nonnull
    public IntentionAction[] getUnresolvedVariableFixes(XPathVariableReference reference) {
        return IntentionAction.EMPTY_ARRAY;
    }

    public boolean isReferenceTo(PsiElement element, XPathVariableReference reference) {
        return false;
    }
}


text:
using System.Runtime.CompilerServices;

namespace NCaseFramework.Test.Util
{
    public class LineUtil
    {
        public static string GetLine(int offset, [CallerLineNumber] int callerLineNumber = -1)
        {
            return "line " + (offset + callerLineNumber);
        }
    }
}


text:
package org.semver;

import org.testng.annotations.Test;

import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;

import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotSame;

public class VersionTest {

    @Test
    public void testVersionSerializable() throws Exception {
        try(ObjectOutputStream out = new ObjectOutputStream(new ByteArrayOutputStream())){
            out.writeObject(new Version.Builder().preRelease("alpha").buildMetadata("12").build());
        }
    }

    @Test
    public void testInitialVersionString() throws Exception {
        assertEquals(new Version.Builder().build().toString(), "0.1.0", "Found wrong initial version.");
    }

    @Test
    public void testImmutabilityMajor() throws Exception {
        Version v1 = new Version.Builder().build();
        Version v2 = v1.major(1);
        assertEquals(v2.toString(), "1.1.0", "Found wrong version after setting major version.");
        assertNotSame(v1, v2, "After setting major version the version instance is the same.");
    }

    @Test
    public void testImmutabilityMinor() throws Exception {
        Version v1 = new Version.Builder().build();
        Version v2 = v1.minor(2);
        assertEquals(v2.toString(), "0.2.0", "Found wrong version after setting minor version.");
        assertNotSame(v1, v2, "After setting minor version the version instance is the same.");
    }

    @Test
    public void testImmutabilityPatch() throws Exception {
        Version v1 = new Version.Builder().build();
        Version v2 = v1.patch(1);
        assertEquals(v2.toString(), "0.1.1", "Found wrong version after setting patch version.");
        assertNotSame(v1, v2, "After setting patch version the version instance is the same.");
    }

    @Test
    public void testNextMajorVersion() throws Exception {
        Version v1 = new Version.Builder().build().major(1).patch(1).nextMajor();
        assertEquals(v1.toString(), "2.0.0", "Found wrong version increasing major version.");
    }

    @Test
    public void testNextMinorVersion() throws Exception {
        Version v1 = new Version.Builder().build().major(1).patch(1).nextMinor();
        assertEquals(v1.toString(), "1.2.0", "Found wrong version increasing minor version.");
    }

    @Test
    public void testNextPatchVersion() throws Exception {
        Version v1 = new Version.Builder().build().major(1).patch(1).nextPatch();
        assertEquals(v1.toString(), "1.1.2", "Found wrong version increasing patch version.");
    }

}


text:
(function(context, OBJECT, NUMBER, LENGTH, toString, undefined, oldClass, jsface) {
  /**
   * Return a map itself or null. A map is a set of { key: value }
   * @param obj object to be checked
   * @return obj itself as a map or false
   */
  function mapOrNil(obj) { return (obj && typeof obj === OBJECT && !(typeof obj.length === NUMBER && !(obj.propertyIsEnumerable(LENGTH))) && obj) || null; }

  /**
   * Return an array itself or null
   * @param obj object to be checked
   * @return obj itself as an array or null
   */
  function arrayOrNil(obj) { return (obj && typeof obj === OBJECT && typeof obj.length === NUMBER && !(obj.propertyIsEnumerable(LENGTH)) && obj) || null; }

  /**
   * Return a function itself or null
   * @param obj object to be checked
   * @return obj itself as a function or null
   */
  function functionOrNil(obj) { return (obj && typeof obj === "function" && obj) || null; }

  /**
   * Return a string itself or null
   * @param obj object to be checked
   * @return obj itself as a string or null
   */
  function stringOrNil(obj) { return (toString.apply(obj) === "[object String]" && obj) || null; }

  /**
   * Return a class itself or null
   * @param obj object to be checked
   * @return obj itself as a class or false
   */
  function classOrNil(obj) { return (functionOrNil(obj) && (obj.prototype && obj === obj.prototype.constructor) && obj) || null; }

  /**
   * Util for extend() to copy a map of { key:value } to an object
   * @param key key
   * @param value value
   * @param ignoredKeys ignored keys
   * @param object object
   * @param iClass true if object is a class
   * @param oPrototype object prototype
   */
  function copier(key, value, ignoredKeys, object, iClass, oPrototype) {
    if ( !ignoredKeys || !ignoredKeys.hasOwnProperty(key)) {
      object[key] = value;
      if (iClass) { oPrototype[key] = value; }                       // class? copy to prototype as well
    }
  }

  /**
   * Extend object from subject, ignore properties in ignoredKeys
   * @param object the child
   * @param subject the parent
   * @param ignoredKeys (optional) keys should not be copied to child
   */
  function extend(object, subject, ignoredKeys) {
    if (arrayOrNil(subject)) {
      for (var len = subject.length; --len >= 0;) { extend(object, subject[len], ignoredKeys); }
    } else {
      ignoredKeys = ignoredKeys || { constructor: 1, $super: 1, prototype: 1, $superp: 1 };

      var iClass     = classOrNil(object),
          isSubClass = classOrNil(subject),
          oPrototype = object.prototype, supez, key, proto;

      // copy static properties and prototype.* to object
      if (mapOrNil(subject)) {
        for (key in subject) {
          copier(key, subject[key], ignoredKeys, object, iClass, oPrototype);
        }
      }

      if (isSubClass) {
        proto = subject.prototype;
        for (key in proto) {
          copier(key, proto[key], ignoredKeys, object, iClass, oPrototype);
        }
      }

      // prototype properties
      if (iClass && isSubClass) { extend(oPrototype, subject.prototype, ignoredKeys); }
    }
  }

  /**
   * Create a class.
   * @param parent parent class(es)
   * @param api class api
   * @return class
   */
  function Class(parent, api) {
    if ( !api) {
      parent = (api = parent, 0);                                     // !api means there's no parent
    }

    var clazz, constructor, singleton, statics, key, bindTo, len, i = 0, p,
        ignoredKeys = { constructor: 1, $singleton: 1, $statics: 1, prototype: 1, $super: 1, $superp: 1, main: 1, toString: 0 },
        plugins     = Class.plugins;

    api         = (typeof api === "function" ? api() : api) || {};             // execute api if it's a function
    constructor = api.hasOwnProperty("constructor") ? api.constructor : 0;     // hasOwnProperty is a must, constructor is special
    singleton   = api.$singleton;
    statics     = api.$statics;

    // add plugins' keys into ignoredKeys
    for (key in plugins) { ignoredKeys[key] = 1; }

    // construct constructor
    clazz  = singleton ? {} : (constructor ? constructor : function(){});

    // determine bindTo: where api should be bound
    bindTo = singleton ? clazz : clazz.prototype;

    // make sure parent is always an array
    parent = !parent || arrayOrNil(parent) ? parent : [ parent ];

    // do inherit
    len = parent && parent.length;
    while (i < len) {
      p = parent[i++];
      for (key in p) {
        if ( !ignoredKeys[key]) {
          bindTo[key] = p[key];
          if ( !singleton) { clazz[key] = p[key]; }
        }
      }
      for (key in p.prototype) { if ( !ignoredKeys[key]) { bindTo[key] = p.prototype[key]; } }
    }

    // copy properties from api to bindTo
    for (key in api) {
      if ( !ignoredKeys[key]) {
        bindTo[key] = api[key];
      }
    }

    // copy static properties from statics to both clazz and bindTo
    for (key in statics) { clazz[key] = bindTo[key] = statics[key]; }

    // if class is not a singleton, add $super and $superp
    if ( !singleton) {
      p = parent && parent[0] || parent;
      clazz.$super  = p;
      clazz.$superp = p && p.prototype ? p.prototype : p;
      bindTo.$class = clazz;
    }

    for (key in plugins) { plugins[key](clazz, parent, api); }                 // pass control to plugins
    if (functionOrNil(api.main)) { api.main.call(clazz, clazz); }              // execute main()
    return clazz;
  }

  /* Class plugins repository */
  Class.plugins = {};

  /* Initialization */
  jsface = {
    Class        : Class,
    extend       : extend,
    mapOrNil     : mapOrNil,
    arrayOrNil   : arrayOrNil,
    functionOrNil: functionOrNil,
    stringOrNil  : stringOrNil,
    classOrNil   : classOrNil
  };

  if (typeof module !== "undefined" && module.exports) {                       // NodeJS/CommonJS
    module.exports = jsface;
  } else {
    oldClass          = context.Class;                                         // save current Class namespace
    context.Class     = Class;                                                 // bind Class and jsface to global scope
    context.jsface    = jsface;
    jsface.noConflict = function() { context.Class = oldClass; };              // no conflict
  }
})(this, "object", "number", "length", Object.prototype.toString);
/*
 * JSFace Object Oriented Programming Library - Ready plugin
 * https://github.com/tnhu/jsface
 *
 * Copyright (c) 2009-2012 Tan Nhu
 * Licensed under MIT license (https://github.com/tnhu/jsface/blob/master/LICENSE.txt)
 */
(function(context) {
  var jsface        = context.jsface || require("./jsface"),
      Class         = jsface.Class,
      functionOrNil = jsface.functionOrNil,
      readyFns      = [],
      readyCount    = 0;

  Class.plugins.$ready = function invoke(clazz, parent, api, loop) {
    var r       = api.$ready,
        len     = parent ? parent.length : 0,
        count   = len,
        _super  = len && parent[0].$super,
        pa, i, entry;

    // find and invoke $ready from parent(s)
    while (len--) {
      for (i = 0; i < readyCount; i++) {
        entry = readyFns[i];
        pa    = parent[len];

        if (pa === entry[0]) {
          entry[1].call(pa, clazz, parent, api);
          count--;
        }

        if ( !count) { break; }
      }
    }

    // call $ready from grandparent(s), if any
    if (_super) {
      invoke(clazz, [ _super ], api, true);
    }

    // in an environment where there are a lot of class creating/removing (rarely)
    // this implementation might cause a leak (saving pointers to clazz and $ready)
    if ( !loop && functionOrNil(r)) {
      r.call(clazz, clazz, parent, api);  // invoke ready from current class
      readyFns.push([ clazz,  r ]);
      readyCount++;
    }
  };
})(this);

/*
 * JSFace Object Oriented Programming Library - Plug and Play pointcut plugin
 * https://github.com/tnhu/jsface
 *
 * Copyright (c) 2009-2012 Tan Nhu
 * Licensed under MIT license (https://github.com/tnhu/jsface/blob/master/LICENSE.txt).
 */
(function(context) {
  var jsface        = context.jsface || require("./jsface"),
      Class         = jsface.Class,
      classOrNil    = jsface.classOrNil,
      functionOrNil = jsface.functionOrNil,
      extend        = jsface.extend,
      mapOrNil      = jsface.mapOrNil,
      WRAPPER       = "___wrapper___",
      BEFORE        = "___before_fns___",
      AFTER         = "___after_fns___",
      ORIGIN        = "___origin_fn___",
      ADVISOR       = "___advisors___",
      INVALID       = "Invalid ",
      NON_FUNC      = "Non-function property named ",
      noop          = function(){};

  /**
   * Wrap a function with before & after.
   */
  function wrap(fn, before, after, advisor) {
    var ignoredKeys = { prototype: 1 };

    function wrapper() {
      var _before = wrapper[BEFORE],
          bLen    = _before.length,
          _after  = wrapper[AFTER],
          aLen    = _after.length,
          _fn     = wrapper[ORIGIN],
          ret, r;

      // Invoke before, if it returns { $skip: true } then skip fn() and after() and returns $data
      while (bLen--) {
        r = _before[bLen].apply(this, arguments);
        if (mapOrNil(r) && r.$skip === true) {
          return r.$data;
        }
      }

      // Invoke fn, save return value
      ret = _fn.apply(this, arguments);

      while (aLen--) {
        r = _after[aLen].apply(this, arguments);
        if (mapOrNil(r) && r.$skip === true) {
          return ret;
        }
      }
      return ret;
    }

    // wrapper exists? reuse it
    if (fn[WRAPPER] === fn) {
      fn[BEFORE].push(before);
      fn[AFTER].push(after);
      fn[ADVISOR].push(advisor);
      return fn;
    }

    // create a reusable wrapper structure
    extend(wrapper, fn, 0, true);
    if (classOrNil(fn)) {
      wrapper.prototype = fn.prototype;

      // this destroys the origin of wrapper[ORIGIN], in theory, prototype.constructor should point
      // to the class constructor itself, but it's no harm to not let that happen
      // wrapper.prototype.constructor = wrapper;
    }

    wrapper[BEFORE]  = [ before ];
    wrapper[AFTER]   = [ after ];
    wrapper[ORIGIN]  = fn;
    wrapper[ADVISOR] = [ advisor ];
    wrapper[WRAPPER] = wrapper;
    wrapper.$super   = fn.$super;
    wrapper.$superp  = fn.$superp;
    return wrapper;
  }

  /**
   * Restore a function to its origin state.
   * @return function's origin state
   */
  function restore(fn, advisor) {
    var origin, index, len;

    if (fn && fn === fn[WRAPPER]) {
      if ( !advisor) {
        origin = fn[ORIGIN];
        delete fn[ORIGIN];
        delete fn[ADVISOR];
        delete fn[BEFORE];
        delete fn[AFTER];
        delete fn[WRAPPER];
      } else {
        index = len = fn[ADVISOR].length;
        while (index--) {
          if (fn[ADVISOR][index] === advisor) { break; }
        }
        if (index >= 0) {
          if (len === 1) { return restore(fn); }
          fn[ADVISOR].splice(index, 1);
          fn[BEFORE].splice(index, 1);
          fn[AFTER].splice(index, 1);
        }
      }
    }
    return origin;
  }

  /**
   * Do unpointcut: Remove pointcuts from subject.
   * Execute from public pointcut api:
   *  - poincut(subject, "remove");
   *  - poincut(subject, "remove constructor foo bar");
   *  - poincut(subject, "remove", advisor);
   */
  function unpointcut(clazz, opts, advisor, iClass, iInstance, bindTo) {
    var constructor, re, keys, fn, c;

    function doRestore(collection, advisor) {
      var c, key, iConstructor, iStatic, fn;

      for (c in collection) {
        key          = c/1 == c ? collection[c] : c;
        iConstructor = (key === "constructor");
        iStatic      = iClass && bindTo[key] === clazz[key];
        fn           = restore(iConstructor && iClass && clazz || bindTo[key], advisor);

        constructor = constructor || (iConstructor && fn);
        if (fn && !iConstructor) {
          bindTo[key] = fn;
          if (iStatic) {
            clazz[key] = fn;
          }
        }
      }
    }

    if (opts === "remove") {
      if ( !advisor) {                                                         // type 1: "remove"
        constructor = iClass && (clazz === clazz[WRAPPER]) && clazz[ORIGIN];
        for (var name in bindTo) {
          var fn      = bindTo[name],
              iStatic = iClass && bindTo[name] === clazz[name];

          bindTo[name] = restore(fn) || bindTo[name];

          // restore static method
          if (iStatic) {
            clazz[name] = bindTo[name];
          }
        }
      } else {                                                                 // type 2: "remove", advisor
        doRestore(advisor, advisor);
      }
    } else if ((re = /^remove /.exec(opts)) !== null) {                        // type 3: "remove contructor foo"
      keys = opts.replace(re, "").split(" ");
      doRestore(keys);
    } else {
      throw INVALID + "params";
    }
    return constructor || clazz;
  }

  /**
   * Apply pointcut to a subject.
   */
  jsface.pointcut = function pointcut(clazz, opts) {
    var iClass    = functionOrNil(clazz),
        iInstance = mapOrNil(clazz),
        iRemove   = (/^remove ?/.exec(opts) !== null),
        advisor   = iRemove && arguments[2],
        bindTo, method, pointcuts;

    if ( !(iClass || iInstance) || !(mapOrNil(opts) || iRemove)) {
      throw INVALID + "params";
    }
    bindTo = iClass ? clazz.prototype : clazz;

    if (iRemove) {
      return unpointcut(clazz, opts, advisor, iClass, iInstance, bindTo);
    };

    for (method in opts) {
      pointcuts = opts[method];
      pointcuts = functionOrNil(pointcuts) ? { before: pointcuts } : pointcuts;   // sugar syntax

      var before = mapOrNil(pointcuts) && !pointcuts.before ? noop : pointcuts.before,
          after  = mapOrNil(pointcuts) && !pointcuts.after ? noop : pointcuts.after,
          isStatic;

      // check if before & after are valid
      if ( !functionOrNil(before)) {
        throw INVALID + method + ":before";
      }
      if ( !functionOrNil(after)) {
        throw INVALID + method + ":after";
      }

      if (iInstance) {
        if (functionOrNil(bindTo[method])) {
          bindTo[method] = wrap(bindTo[method], before, after, opts);
        } else {
          throw NON_FUNC + method;
        }
      } else {
        if (method === "constructor") {
          clazz = wrap(clazz, before, after, opts);
        } else {
          if (functionOrNil(bindTo[method])) {
            isStatic = iClass && bindTo[method] === clazz[method];
            bindTo[method] = wrap(bindTo[method], before, after, opts);
            if (isStatic) { clazz[method] = bindTo[method]; }
          } else {
            throw NON_FUNC + method;
          }
        }
      }
    }
    return clazz;
  };

  if (typeof module !== "undefined" && module.exports) {
    module.exports = jsface.pointcut;
  }
})(this);


text:
package shop.main.controller;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import shop.main.data.entity.Product;
import shop.main.data.entity.Review;
import shop.main.data.entity.WishList;
import shop.main.data.service.ProductService;
import shop.main.data.service.ReviewService;
import shop.main.data.service.UserService;
import shop.main.data.service.WishListService;

@Controller
public class AjaxFrontController extends FrontController implements ResourceLoaderAware {
	private ResourceLoader resourceLoader;

	@Autowired
	ServletContext context;

	public void setResourceLoader(ResourceLoader resourceLoader) {
		this.resourceLoader = resourceLoader;
	}

	public Resource getResource(String location) {
		return resourceLoader.getResource(location);
	}

	@Autowired
	private ProductService productService;

	@Autowired
	private ReviewService reviewService;

	@Autowired
	protected UserService userService;

	@Autowired
	protected WishListService wishListService;

	@RequestMapping(value = "/createReview", method = RequestMethod.POST/*
																		 * ,
																		 * consumes
																		 * =
																		 * {"application/json;charset=utf-8"}
																		 */)
	public @ResponseBody String createReview(Review review) {
		System.out.println("*");
		System.out.println("request is " + review.toString());
		System.out.println("*");
		String errorMessage = "";
		if (review.getUserName() == null || review.getUserName().equals("")) {
			errorMessage += "User name is required! ";
		}
		if (review.getUserEmail() == null || review.getUserEmail().equals("")
				|| review.getUserEmail().indexOf("@") < 0) {
			errorMessage += "Valid email is required!";
		}
		if (errorMessage.equals("")) {
			reviewService.save(review);
			productService.updateRating(review.getProduct().getId());
			return "SUCCESS";
		} else {
			return errorMessage;
		}
	}

	@RequestMapping(value = "/chooseFilter", method = RequestMethod.POST)
	public String chooseFilter(@RequestParam(value = "myArray[]") String[] filters, Integer pageSize, Integer current,
			Model model) {
		List<Long> filterList = null;
		List<Long> categoryList = null;
		if (!filters[0].isEmpty()) {
			filterList = Arrays.asList(filters[0].split(",")).stream().map(Long::valueOf).collect(Collectors.toList());
		}
		if (!filters[1].isEmpty()) {
			categoryList = Arrays.asList(filters[1].split(",")).stream().map(Long::valueOf)
					.collect(Collectors.toList());
		}

		loadFilterProductTableData(filterList, categoryList, current, pageSize, model);

		return "products";
	}

	@RequestMapping(value = "/addtowishlist", method = RequestMethod.POST)
	public @ResponseBody String addToWishList(@RequestParam String sku, HttpServletRequest request, Model model) {

		org.springframework.security.core.userdetails.User authorizeduser = (org.springframework.security.core.userdetails.User) SecurityContextHolder
				.getContext().getAuthentication().getPrincipal();
		if (authorizeduser != null) {
			String username = authorizeduser.getUsername();
			shop.main.data.entity.User savedUser = userService.findByUsername(username);
			if (savedUser != null) {
				if (wishListService.isInWishlist(sku, username)) {
					return "Product is already in your wishlist!";
				} else {
					Product product = productService.findProductBySKU(sku);
					wishListService.save(new WishList(product, savedUser));
				}
			}
		}

		return "Product added to your wishlist!";
	}

}