text:
<link rel="import" href="../../polymer/polymer.html">
<link rel="import" href="../../neon-animation/neon-animatable-behavior.html">
<script>
  var GIVe = (function (give) {
    'use strict'

    give.GenemoCardContentBehavior = {

      properties: {

        collapseObject: {
          type: Object,
          value: null
        },

        icon: {
          type: String,
          value: '',
          readOnly: true
        },

        iconAlt: {
          type: String,
          value: '',
          readOnly: true
        },

        headerText: {
          type: String,
          value: '',
          readOnly: true
        },

        contentReady: {
          type: Boolean,
          value: false,
          readOnly: true
        },

        domReady: {
          type: Boolean,
          value: false,
          readOnly: true
        }

      },

      isReady: function () {
        return this.contentReady    // default behavior is that whenever it's loaded, the contents are ready.
      },

      setReady: function (readiness) {
        // set this.ready as ready and fire 'content-ready' event
        this._setContentReady(readiness)
        this.fire('content-ready', {flag: this.contentReady}, {cancelable: true})
      },

      isDOMReady: function () {
        return this.domReady    // default behavior is that whenever it's loaded, the contents are ready.
      },

      setDOMReady: function (readiness) {
        // set this.domReady as ready and fire 'content-dom-ready' event
        this._setDomReady(readiness)
        this.fire('content-dom-ready', {flag: this.domReady}, {cancelable: true})
      },

      checkReadiness: function () {
        if (this.domReady) {
          this.fire('content-dom-ready', {flag: this.domReady}, {cancelable: true})
          if (this.contentReady) {
            this.fire('content-ready', {flag: this.contentReady}, {cancelable: true})
          }
        }
      },

      getExpandedHeader: function () {
        var res = document.createElement('div')
        var coreIcon = this.getIcon()
        coreIcon.classList.add('smallInline')

        var textSpan = document.createElement('span')
        textSpan.textContent = this.headerText

        res.classList.add('headerText')
        res.appendChild(coreIcon)
        res.appendChild(textSpan)

        if (this.otherElem) {
          res.appendChild(this.otherElem)
        }

        return res
      },

      updateCurrentInfo: function (props) {
        if (Object.keys(props).length > 0) {
          this.collapseObject = props
        } else {
          this.collapseObject = null
        }
      },

      getCollapse: function () {
        if (this.collapseObject) {
          // prepare for shrinking and return the shrunk element
          var result = document.createElement('div')
          // add shrunk icon, ref, input file and display file
          // icon and ref in one line
          var resHeader = document.createElement('div')
          var resIcon = this.getIcon()
          resIcon.classList.add('smallInline')

          var resHeaderText = document.createElement('span')
          resHeaderText.textContent = this.headerText

          resHeader.classList.add('headerText')
          resHeader.classList.add('clearFix')
          resHeader.appendChild(resIcon)
          resHeader.appendChild(resHeaderText)
          result.appendChild(resHeader)

          var resContent = document.createElement('div')
          resContent.classList.add('collapseContent')
          for (var key in this.collapseObject) {
            if (this.collapseObject.hasOwnProperty(key)) {
              resContent.appendChild(this.createResElement(key, this.collapseObject[key]))
            }
          }
          result.appendChild(resContent)
          return result
        }
        return null
      },

      getIcon: function () {
        var resIcon = document.createElement('iron-icon')
        resIcon.setAttribute('icon', this.icon)
        resIcon.setAttribute('alt', this.iconAlt)
        return resIcon
      },

      createResElement: function (anno, text, beforeNode, afterNode) {
        var res = document.createElement('div')
        res.classList.add('clearFix')
        res.classList.add('fullWidth')
        res.classList.add('collapseDb')

        if (beforeNode) {
          res.appendChild(beforeNode)
        }

        var resAnno = document.createElement('span')
        resAnno.classList.add('anno')
        resAnno.classList.add('leftFloat')
        resAnno.textContent = anno + ': '
        var resContent = document.createElement('span')
        resContent.textContent = text

        res.appendChild(resAnno)
        res.appendChild(resContent)

        if (afterNode) {
          res.appendChild(afterNode)
        }

        return res
      },

      attached: function () {
        this.checkReadiness()
      }

    }

    return give
  })(GIVe || {})
</script>


text:
/*
 * Spinnaker API
 *
 * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
 *
 * API version: 1.0.0
 * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git)
 */

package swagger

import (
	"context"
	"io/ioutil"
	"net/http"
	"net/url"
	"strings"
	"fmt"
	"github.com/antihax/optional"
)

// Linger please
var (
	_ context.Context
)

type ArtifactControllerApiService service

/*
ArtifactControllerApiService Retrieve the list of artifact accounts configured in Clouddriver.
 * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
 * @param optional nil or *ArtifactControllerApiAllUsingGETOpts - Optional Parameters:
     * @param "XRateLimitApp" (optional.String) -  X-RateLimit-App

@return []interface{}
*/

type ArtifactControllerApiAllUsingGETOpts struct {
	XRateLimitApp optional.String
}

func (a *ArtifactControllerApiService) AllUsingGET(ctx context.Context, localVarOptionals *ArtifactControllerApiAllUsingGETOpts) ([]interface{}, *http.Response, error) {
	var (
		localVarHttpMethod = strings.ToUpper("Get")
		localVarPostBody   interface{}
		localVarFileName   string
		localVarFileBytes  []byte
		localVarReturnValue []interface{}
	)

	// create path and map variables
	localVarPath := a.client.cfg.BasePath + "/artifacts/credentials"

	localVarHeaderParams := make(map[string]string)
	localVarQueryParams := url.Values{}
	localVarFormParams := url.Values{}

	// to determine the Content-Type header
	localVarHttpContentTypes := []string{}

	// set Content-Type header
	localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)
	if localVarHttpContentType != "" {
		localVarHeaderParams["Content-Type"] = localVarHttpContentType
	}

	// to determine the Accept header
	localVarHttpHeaderAccepts := []string{"*/*"}

	// set Accept header
	localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)
	if localVarHttpHeaderAccept != "" {
		localVarHeaderParams["Accept"] = localVarHttpHeaderAccept
	}
	if localVarOptionals != nil && localVarOptionals.XRateLimitApp.IsSet() {
		localVarHeaderParams["X-RateLimit-App"] = parameterToString(localVarOptionals.XRateLimitApp.Value(), "")
	}
	r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)
	if err != nil {
		return localVarReturnValue, nil, err
	}

	localVarHttpResponse, err := a.client.callAPI(r)
	if err != nil || localVarHttpResponse == nil {
		return localVarReturnValue, localVarHttpResponse, err
	}

	localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body)
	localVarHttpResponse.Body.Close()
	if err != nil {
		return localVarReturnValue, localVarHttpResponse, err
	}

	if localVarHttpResponse.StatusCode < 300 {
		// If we succeed, return the data, otherwise pass on to decode error.
		err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type"));
		if err == nil {
			return localVarReturnValue, localVarHttpResponse, err
		}
	}

	if localVarHttpResponse.StatusCode >= 300 {
		newErr := GenericSwaggerError{
			body: localVarBody,
			error: localVarHttpResponse.Status,
		}

		if localVarHttpResponse.StatusCode == 200 {
			var v []interface{}
			err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type"));
				if err != nil {
					newErr.error = err.Error()
					return localVarReturnValue, localVarHttpResponse, newErr
				}
				newErr.model = v
				return localVarReturnValue, localVarHttpResponse, newErr
		}

		return localVarReturnValue, localVarHttpResponse, newErr
	}

	return localVarReturnValue, localVarHttpResponse, nil
}

/*
ArtifactControllerApiService Retrieve the list of artifact versions by account and artifact names
 * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
 * @param accountName accountName
 * @param artifactName artifactName
 * @param type_ type
 * @param optional nil or *ArtifactControllerApiArtifactVersionsUsingGETOpts - Optional Parameters:
     * @param "XRateLimitApp" (optional.String) -  X-RateLimit-App

@return []string
*/

type ArtifactControllerApiArtifactVersionsUsingGETOpts struct {
	XRateLimitApp optional.String
}

func (a *ArtifactControllerApiService) ArtifactVersionsUsingGET(ctx context.Context, accountName string, artifactName string, type_ string, localVarOptionals *ArtifactControllerApiArtifactVersionsUsingGETOpts) ([]string, *http.Response, error) {
	var (
		localVarHttpMethod = strings.ToUpper("Get")
		localVarPostBody   interface{}
		localVarFileName   string
		localVarFileBytes  []byte
		localVarReturnValue []string
	)

	// create path and map variables
	localVarPath := a.client.cfg.BasePath + "/artifacts/account/{accountName}/versions"
	localVarPath = strings.Replace(localVarPath, "{"+"accountName"+"}", fmt.Sprintf("%v", accountName), -1)

	localVarHeaderParams := make(map[string]string)
	localVarQueryParams := url.Values{}
	localVarFormParams := url.Values{}

	localVarQueryParams.Add("artifactName", parameterToString(artifactName, ""))
	localVarQueryParams.Add("type", parameterToString(type_, ""))
	// to determine the Content-Type header
	localVarHttpContentTypes := []string{}

	// set Content-Type header
	localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)
	if localVarHttpContentType != "" {
		localVarHeaderParams["Content-Type"] = localVarHttpContentType
	}

	// to determine the Accept header
	localVarHttpHeaderAccepts := []string{"*/*"}

	// set Accept header
	localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)
	if localVarHttpHeaderAccept != "" {
		localVarHeaderParams["Accept"] = localVarHttpHeaderAccept
	}
	if localVarOptionals != nil && localVarOptionals.XRateLimitApp.IsSet() {
		localVarHeaderParams["X-RateLimit-App"] = parameterToString(localVarOptionals.XRateLimitApp.Value(), "")
	}
	r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)
	if err != nil {
		return localVarReturnValue, nil, err
	}

	localVarHttpResponse, err := a.client.callAPI(r)
	if err != nil || localVarHttpResponse == nil {
		return localVarReturnValue, localVarHttpResponse, err
	}

	localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body)
	localVarHttpResponse.Body.Close()
	if err != nil {
		return localVarReturnValue, localVarHttpResponse, err
	}

	if localVarHttpResponse.StatusCode < 300 {
		// If we succeed, return the data, otherwise pass on to decode error.
		err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type"));
		if err == nil {
			return localVarReturnValue, localVarHttpResponse, err
		}
	}

	if localVarHttpResponse.StatusCode >= 300 {
		newErr := GenericSwaggerError{
			body: localVarBody,
			error: localVarHttpResponse.Status,
		}

		if localVarHttpResponse.StatusCode == 200 {
			var v []string
			err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type"));
				if err != nil {
					newErr.error = err.Error()
					return localVarReturnValue, localVarHttpResponse, newErr
				}
				newErr.model = v
				return localVarReturnValue, localVarHttpResponse, newErr
		}

		return localVarReturnValue, localVarHttpResponse, newErr
	}

	return localVarReturnValue, localVarHttpResponse, nil
}

/*
ArtifactControllerApiService Retrieve the specified artifact version for an artifact provider and package name
 * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
 * @param packageName packageName
 * @param provider provider
 * @param version version

@return interface{}
*/
func (a *ArtifactControllerApiService) GetArtifactUsingGET(ctx context.Context, packageName string, provider string, version string) (interface{}, *http.Response, error) {
	var (
		localVarHttpMethod = strings.ToUpper("Get")
		localVarPostBody   interface{}
		localVarFileName   string
		localVarFileBytes  []byte
		localVarReturnValue interface{}
	)

	// create path and map variables
	localVarPath := a.client.cfg.BasePath + "/artifacts/{provider}/{packageName}/{version}"
	localVarPath = strings.Replace(localVarPath, "{"+"packageName"+"}", fmt.Sprintf("%v", packageName), -1)
	localVarPath = strings.Replace(localVarPath, "{"+"provider"+"}", fmt.Sprintf("%v", provider), -1)
	localVarPath = strings.Replace(localVarPath, "{"+"version"+"}", fmt.Sprintf("%v", version), -1)

	localVarHeaderParams := make(map[string]string)
	localVarQueryParams := url.Values{}
	localVarFormParams := url.Values{}

	// to determine the Content-Type header
	localVarHttpContentTypes := []string{}

	// set Content-Type header
	localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)
	if localVarHttpContentType != "" {
		localVarHeaderParams["Content-Type"] = localVarHttpContentType
	}

	// to determine the Accept header
	localVarHttpHeaderAccepts := []string{"*/*"}

	// set Accept header
	localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)
	if localVarHttpHeaderAccept != "" {
		localVarHeaderParams["Accept"] = localVarHttpHeaderAccept
	}
	r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)
	if err != nil {
		return localVarReturnValue, nil, err
	}

	localVarHttpResponse, err := a.client.callAPI(r)
	if err != nil || localVarHttpResponse == nil {
		return localVarReturnValue, localVarHttpResponse, err
	}

	localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body)
	localVarHttpResponse.Body.Close()
	if err != nil {
		return localVarReturnValue, localVarHttpResponse, err
	}

	if localVarHttpResponse.StatusCode < 300 {
		// If we succeed, return the data, otherwise pass on to decode error.
		err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type"));
		if err == nil {
			return localVarReturnValue, localVarHttpResponse, err
		}
	}

	if localVarHttpResponse.StatusCode >= 300 {
		newErr := GenericSwaggerError{
			body: localVarBody,
			error: localVarHttpResponse.Status,
		}

		if localVarHttpResponse.StatusCode == 200 {
			var v interface{}
			err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type"));
				if err != nil {
					newErr.error = err.Error()
					return localVarReturnValue, localVarHttpResponse, newErr
				}
				newErr.model = v
				return localVarReturnValue, localVarHttpResponse, newErr
		}

		return localVarReturnValue, localVarHttpResponse, newErr
	}

	return localVarReturnValue, localVarHttpResponse, nil
}

redpajama_set_name: RedPajamaGithub


text:
require 'truss/router/node'
require 'truss/router/routes/patch'

describe Truss::Router::Routes::Patch do
    subject { described_class.new("/home", String) }
    its(:request_method)    { should eq(:patch) }
    its(:endpoint)          { should eq(String) }
    its(:path)              { should eq("/home") }
end


text: export { WarningSquare24 as default } from "../../";


text:
var couch = require('./couch.js');

var db = couch.init('testdb');

function next(callback) {
 return function(response) {
   if (response.error) {
     console.log('Error: ' + response.reason || response.error);
   }
   else callback(response);
  }
}

function start() {
  console.log('Creating db');
  db.createDb(next(insert));
}

function insert(response) {
  console.log('Saving doc');
  db.saveDoc({'name': 'Test document'}, next(retrieve));
}

function retrieve(response) {
  console.log('Retrieving doc ' + response.id);
  db.getDoc(response.id, next(remove));
}

function remove(doc) {
  console.log('Got doc with name: ' + doc.name);
  console.log('Removing doc ' + doc._id);
  db.deleteDoc(doc, next(stop));
}

function stop(response) {
  console.log('Deleting the db');
  db.deleteDb();
}

start();


text:
package com.google.template.soy.coredirectives;

import static com.google.common.truth.Truth.assertThat;

import com.google.common.collect.ImmutableList;
import com.google.template.soy.data.SanitizedContent;
import com.google.template.soy.data.UnsafeSanitizedContentOrdainer;
import com.google.template.soy.jssrc.restricted.JsExpr;
import com.google.template.soy.pysrc.restricted.PyExpr;
import com.google.template.soy.testing.AbstractSoyPrintDirectiveTestCase;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/**
 * Unit tests for EscapeHtmlDirective.
 *
 */
@RunWith(JUnit4.class)
public class EscapeHtmlDirectiveTest extends AbstractSoyPrintDirectiveTestCase {

  @Test
  public void testApplyForTofu() {
    EscapeHtmlDirective escapeHtmlDirective = new EscapeHtmlDirective();

    assertTofuOutput("", "", escapeHtmlDirective);
    assertTofuOutput("a&b > c", "a&b > c", escapeHtmlDirective);
    assertTofuOutput(
        "<script>alert('boo');</script>",
        "<script>alert('boo');</script>",
        escapeHtmlDirective);
    SanitizedContent fooTagHtml =
        UnsafeSanitizedContentOrdainer.ordainAsSafe("<foo>", SanitizedContent.ContentKind.HTML);
    assertTofuOutput(
        fooTagHtml,
        // Sanitized HTML is not escaped.
        fooTagHtml,
        escapeHtmlDirective);
    assertTofuOutput(
        "<foo>",
        // But JS_STR_CHARS are.
        UnsafeSanitizedContentOrdainer.ordainAsSafe("<foo>", SanitizedContent.ContentKind.JS),
        escapeHtmlDirective);
    assertTofuOutput(
        "<foo>",
        // But CSS is.
        UnsafeSanitizedContentOrdainer.ordainAsSafe("<foo>", SanitizedContent.ContentKind.CSS),
        escapeHtmlDirective);
  }

  @Test
  public void testApplyForJsSrc() {
    EscapeHtmlDirective escapeHtmlDirective = new EscapeHtmlDirective();
    JsExpr dataRef = new JsExpr("opt_data.myKey", Integer.MAX_VALUE);
    assertThat(escapeHtmlDirective.applyForJsSrc(dataRef, ImmutableList.of()).getText())
        .isEqualTo("soy.$$escapeHtml(opt_data.myKey)");
  }

  @Test
  public void testApplyForPySrc() {
    EscapeHtmlDirective escapeHtmlDirective = new EscapeHtmlDirective();
    PyExpr data = new PyExpr("'data'", Integer.MAX_VALUE);
    assertThat(escapeHtmlDirective.applyForPySrc(data, ImmutableList.of()).getText())
        .isEqualTo("sanitize.escape_html('data')");
  }
}


text:
identifier: MIR:00000370
name: PSCDB
description: The PSCDB (Protein Structural Change DataBase) collects information on the relationship between protein structural change upon ligand binding. Each entry page provides detailed information about this structural motion.
prefix: pscdb
pattern: ^\d+$
prefixed: 0
local_id: 051
synonyms:
 - Protein Structural Change DataBase
resources:
 - identifier: MIR:00100469
   accessurl: http://idp1.force.cs.is.nagoya-u.ac.jp/pscdb/${lid}.html
   keyword: 89A-90A
   description: PSCDB at Nagoya University
   homepage: http://idp1.force.cs.is.nagoya-u.ac.jp/pscdb/index.html
   institution: Graduate School of Information Science, Nagoya University, Furo-cho, Chikusa-ku
   location: Japan
   official: false
---


text:
package com.qinyadan.monitor.network.client;

public interface ClientReconnectEventListener {

    void reconnectPerformed(MonitorClient client);

}


text:
title: Making changes to rules_nodejs
layout: default
toc: true
---

# Making changes to rules_nodejs

One advantage of open-source software is that you can make your own changes that suit your needs.

The packages published to npm and GitHub differ from the sources in this repo. The packages have only runtime bazel dependencies, but the sources depend on development dependencies. For example, the `@bazel_skylib` library is a development-time transitive dependency, while an npm package would have that dependency statically linked in.

> This differs from much of the Bazel ecosystem, where you are expected to build the whole transitive toolchain from sources.

If you have a small change, it's easiest to just patch the distributed artifacts rather than build from source. However if you're doing active development in rules_nodejs or have a policy of not depending on release artifacts, it's possible to depend directly on sources. This is not yet documented; file an issue on our repo if you think you need this.

## Patching the npm packages

The pattern we use most commonly is to use [patch-package]. To store your local changes to the npm packages follow the steps:

1. `npm i -D patch-package`
1. Edit the target package in your `node_modules`
1. Run `npx patch-package <npm package>`. This will store the patch in the `patches/` directory in the root of the workspace
1. Add `"postinstall": "patch-package"` to the `package.json` in your repo to apply the patches when building dependencies (aka at `npm install`)

[patch-package]: https://www.npmjs.com/package/patch-package

## Patching the built-in release

rules_nodejs has a distribution format which is a tgz published to GitHub, and this can make it tricky to make casual changes without forking the project and building your own release artifacts.

Bazel has a handy patching mechanism that lets you easily apply a local patch to the release artifact for built-in rules: [the `patches` attribute to `http_archive`](https://docs.bazel.build/versions/master/repo/http.html#attributes).

First, make your changes in a clone of the rules_nodejs repo. Export a patch file simply using `git diff`:

```sh
git diff > my.patch
```

Then copy the patch file somewhere in your repo and point to it from your `WORKSPACE` file:

```python
http_archive(
    name = "build_bazel_rules_nodejs",
    patch_args = ["-p1"],
    patches = ["//path/to/my.patch"],
    sha256 = "6d4edbf28ff6720aedf5f97f9b9a7679401bf7fca9d14a0fff80f644a99992b4",
    urls = ["https://github.com/bazelbuild/rules_nodejs/releases/download/0.32.2/rules_nodejs-0.32.2.tar.gz"],
)
```


text:
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "third_party/blink/renderer/core/frame/dom_window.h"

#include <algorithm>
#include <memory>

#include "base/metrics/histogram_macros.h"
#include "services/network/public/mojom/web_sandbox_flags.mojom-blink.h"
#include "third_party/blink/public/common/action_after_pagehide.h"
#include "third_party/blink/renderer/bindings/core/v8/serialization/post_message_helper.h"
#include "third_party/blink/renderer/bindings/core/v8/source_location.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_window.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_window_post_message_options.h"
#include "third_party/blink/renderer/bindings/core/v8/window_proxy_manager.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/events/message_event.h"
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/core/execution_context/security_context.h"
#include "third_party/blink/renderer/core/frame/coop_access_violation_report_body.h"
#include "third_party/blink/renderer/core/frame/csp/content_security_policy.h"
#include "third_party/blink/renderer/core/frame/frame.h"
#include "third_party/blink/renderer/core/frame/frame_client.h"
#include "third_party/blink/renderer/core/frame/frame_console.h"
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
#include "third_party/blink/renderer/core/frame/location.h"
#include "third_party/blink/renderer/core/frame/report.h"
#include "third_party/blink/renderer/core/frame/reporting_context.h"
#include "third_party/blink/renderer/core/frame/settings.h"
#include "third_party/blink/renderer/core/frame/user_activation.h"
#include "third_party/blink/renderer/core/input/input_device_capabilities.h"
#include "third_party/blink/renderer/core/inspector/console_message.h"
#include "third_party/blink/renderer/core/page/chrome_client.h"
#include "third_party/blink/renderer/core/page/focus_controller.h"
#include "third_party/blink/renderer/core/page/page.h"
#include "third_party/blink/renderer/core/probe/core_probes.h"
#include "third_party/blink/renderer/platform/heap/garbage_collected.h"
#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/weborigin/kurl.h"
#include "third_party/blink/renderer/platform/weborigin/security_origin.h"

namespace blink {

DOMWindow::DOMWindow(Frame& frame)
    : frame_(frame),
      window_proxy_manager_(frame.GetWindowProxyManager()),
      window_is_closing_(false) {}

DOMWindow::~DOMWindow() {
  // The frame must be disconnected before finalization.
  DCHECK(!frame_);
}

v8::MaybeLocal<v8::Value> DOMWindow::Wrap(ScriptState* script_state) {
  // TODO(yukishiino): Get understanding of why it's possible to initialize
  // the context after the frame is detached.  And then, remove the following
  // lines.  See also https://crbug.com/712638 .
  Frame* frame = GetFrame();
  if (!frame)
    return v8::Null(script_state->GetIsolate());

  // TODO(yukishiino): Make this function always return the non-empty handle
  // even if the frame is detached because the global proxy must always exist
  // per spec.
  return frame->GetWindowProxy(script_state->World())
      ->GlobalProxyIfNotDetached();
}

v8::Local<v8::Object> DOMWindow::AssociateWithWrapper(
    v8::Isolate*,
    const WrapperTypeInfo*,
    v8::Local<v8::Object> wrapper) {
  NOTREACHED();
  return v8::Local<v8::Object>();
}

const AtomicString& DOMWindow::InterfaceName() const {
  return event_target_names::kWindow;
}

const DOMWindow* DOMWindow::ToDOMWindow() const {
  return this;
}

bool DOMWindow::IsWindowOrWorkerGlobalScope() const {
  return true;
}

Location* DOMWindow::location() const {
  if (!location_)
    location_ = MakeGarbageCollected<Location>(const_cast<DOMWindow*>(this));
  return location_.Get();
}

bool DOMWindow::closed() const {
  return window_is_closing_ || !GetFrame() || !GetFrame()->GetPage();
}

unsigned DOMWindow::length() const {
  return GetFrame() ? GetFrame()->Tree().ScopedChildCount() : 0;
}

DOMWindow* DOMWindow::self() const {
  if (!GetFrame())
    return nullptr;

  return GetFrame()->DomWindow();
}

DOMWindow* DOMWindow::opener() const {
  // FIXME: Use FrameTree to get opener as well, to simplify logic here.
  if (!GetFrame() || !GetFrame()->Client())
    return nullptr;

  Frame* opener = GetFrame()->Opener();
  return opener ? opener->DomWindow() : nullptr;
}

DOMWindow* DOMWindow::parent() const {
  if (!GetFrame())
    return nullptr;

  Frame* parent = GetFrame()->Tree().Parent(FrameTreeBoundary::kFenced);
  return parent ? parent->DomWindow() : GetFrame()->DomWindow();
}

DOMWindow* DOMWindow::top() const {
  if (!GetFrame())
    return nullptr;

  return GetFrame()->Tree().Top(FrameTreeBoundary::kFenced).DomWindow();
}

void DOMWindow::postMessage(v8::Isolate* isolate,
                            const ScriptValue& message,
                            const String& target_origin,
                            HeapVector<ScriptValue>& transfer,
                            ExceptionState& exception_state) {
  WindowPostMessageOptions* options = WindowPostMessageOptions::Create();
  options->setTargetOrigin(target_origin);
  if (!transfer.IsEmpty())
    options->setTransfer(transfer);
  postMessage(isolate, message, options, exception_state);
}

void DOMWindow::postMessage(v8::Isolate* isolate,
                            const ScriptValue& message,
                            const WindowPostMessageOptions* options,
                            ExceptionState& exception_state) {
  LocalDOMWindow* incumbent_window = IncumbentDOMWindow(isolate);
  UseCounter::Count(incumbent_window->document(),
                    WebFeature::kWindowPostMessage);

  Transferables transferables;
  scoped_refptr<SerializedScriptValue> serialized_message =
      PostMessageHelper::SerializeMessageByMove(isolate, message, options,
                                                transferables, exception_state);
  if (exception_state.HadException())
    return;
  DCHECK(serialized_message);
  DoPostMessage(std::move(serialized_message), transferables.message_ports,
                options, incumbent_window, exception_state);
}

DOMWindow* DOMWindow::AnonymousIndexedGetter(uint32_t index) {
  ReportCoopAccess("indexed");

  if (!GetFrame())
    return nullptr;

  Frame* child = GetFrame()->Tree().ScopedChild(index);
  return child ? child->DomWindow() : nullptr;
}

bool DOMWindow::IsCurrentlyDisplayedInFrame() const {
  if (GetFrame())
    SECURITY_CHECK(GetFrame()->DomWindow() == this);
  return GetFrame() && GetFrame()->GetPage();
}

// FIXME: Once we're throwing exceptions for cross-origin access violations, we
// will always sanitize the target frame details, so we can safely combine
// 'crossDomainAccessErrorMessage' with this method after considering exactly
// which details may be exposed to JavaScript.
//
// http://crbug.com/17325
String DOMWindow::SanitizedCrossDomainAccessErrorMessage(
    const LocalDOMWindow* accessing_window,
    CrossDocumentAccessPolicy cross_document_access) const {
  if (!accessing_window || !GetFrame())
    return String();

  const KURL& accessing_window_url = accessing_window->Url();
  if (accessing_window_url.IsNull())
    return String();

  const SecurityOrigin* active_origin = accessing_window->GetSecurityOrigin();
  String message;
  if (cross_document_access == CrossDocumentAccessPolicy::kDisallowed) {
    message = "Blocked a restricted frame with origin \"" +
              active_origin->ToString() + "\" from accessing another frame.";
  } else {
    message = "Blocked a frame with origin \"" + active_origin->ToString() +
              "\" from accessing a cross-origin frame.";
  }

  // FIXME: Evaluate which details from 'crossDomainAccessErrorMessage' may
  // safely be reported to JavaScript.

  return message;
}

String DOMWindow::CrossDomainAccessErrorMessage(
    const LocalDOMWindow* accessing_window,
    CrossDocumentAccessPolicy cross_document_access) const {
  if (!accessing_window || !GetFrame())
    return String();

  const KURL& accessing_window_url = accessing_window->Url();
  if (accessing_window_url.IsNull())
    return String();

  const SecurityOrigin* active_origin = accessing_window->GetSecurityOrigin();
  const SecurityOrigin* target_origin =
      GetFrame()->GetSecurityContext()->GetSecurityOrigin();
  auto* local_dom_window = DynamicTo<LocalDOMWindow>(this);
  // It's possible for a remote frame to be same origin with respect to a
  // local frame, but it must still be treated as a disallowed cross-domain
  // access. See https://crbug.com/601629.
  DCHECK(GetFrame()->IsRemoteFrame() ||
         !active_origin->CanAccess(target_origin) ||
         (local_dom_window &&
          accessing_window->GetAgent() != local_dom_window->GetAgent()));

  String message = "Blocked a frame with origin \"" +
                   active_origin->ToString() +
                   "\" from accessing a frame with origin \"" +
                   target_origin->ToString() + "\". ";

  // Sandbox errors: Use the origin of the frames' location, rather than their
  // actual origin (since we know that at least one will be "null").
  KURL active_url = accessing_window->Url();
  // TODO(alexmos): RemoteFrames do not have a document, and their URLs
  // aren't replicated.  For now, construct the URL using the replicated
  // origin for RemoteFrames. If the target frame is remote and sandboxed,
  // there isn't anything else to show other than "null" for its origin.
  KURL target_url = local_dom_window
                        ? local_dom_window->Url()
                        : KURL(NullURL(), target_origin->ToString());
  using SandboxFlags = network::mojom::blink::WebSandboxFlags;
  if (GetFrame()->GetSecurityContext()->IsSandboxed(SandboxFlags::kOrigin) ||
      accessing_window->IsSandboxed(SandboxFlags::kOrigin)) {
    message = "Blocked a frame at \"" +
              SecurityOrigin::Create(active_url)->ToString() +
              "\" from accessing a frame at \"" +
              SecurityOrigin::Create(target_url)->ToString() + "\". ";

    if (GetFrame()->GetSecurityContext()->IsSandboxed(SandboxFlags::kOrigin) &&
        accessing_window->IsSandboxed(SandboxFlags::kOrigin)) {
      return "Sandbox access violation: " + message +
             " Both frames are sandboxed and lack the \"allow-same-origin\" "
             "flag.";
    }

    if (GetFrame()->GetSecurityContext()->IsSandboxed(SandboxFlags::kOrigin)) {
      return "Sandbox access violation: " + message +
             " The frame being accessed is sandboxed and lacks the "
             "\"allow-same-origin\" flag.";
    }

    return "Sandbox access violation: " + message +
           " The frame requesting access is sandboxed and lacks the "
           "\"allow-same-origin\" flag.";
  }

  // Protocol errors: Use the URL's protocol rather than the origin's protocol
  // so that we get a useful message for non-heirarchal URLs like 'data:'.
  if (target_origin->Protocol() != active_origin->Protocol())
    return message + " The frame requesting access has a protocol of \"" +
           active_url.Protocol() +
           "\", the frame being accessed has a protocol of \"" +
           target_url.Protocol() + "\". Protocols must match.";

  // 'document.domain' errors.
  if (target_origin->DomainWasSetInDOM() && active_origin->DomainWasSetInDOM())
    return message +
           "The frame requesting access set \"document.domain\" to \"" +
           active_origin->Domain() +
           "\", the frame being accessed set it to \"" +
           target_origin->Domain() +
           "\". Both must set \"document.domain\" to the same value to allow "
           "access.";
  if (active_origin->DomainWasSetInDOM())
    return message +
           "The frame requesting access set \"document.domain\" to \"" +
           active_origin->Domain() +
           "\", but the frame being accessed did not. Both must set "
           "\"document.domain\" to the same value to allow access.";
  if (target_origin->DomainWasSetInDOM())
    return message + "The frame being accessed set \"document.domain\" to \"" +
           target_origin->Domain() +
           "\", but the frame requesting access did not. Both must set "
           "\"document.domain\" to the same value to allow access.";
  if (cross_document_access == CrossDocumentAccessPolicy::kDisallowed)
    return message + "The document-access policy denied access.";

  // Default.
  return message + "Protocols, domains, and ports must match.";
}

void DOMWindow::close(v8::Isolate* isolate) {
  LocalDOMWindow* incumbent_window = IncumbentDOMWindow(isolate);
  Close(incumbent_window);
}

void DOMWindow::Close(LocalDOMWindow* incumbent_window) {
  DCHECK(incumbent_window);

  if (!GetFrame() || !GetFrame()->IsMainFrame())
    return;

  Page* page = GetFrame()->GetPage();
  if (!page)
    return;

  if (page->InsidePortal())
    return;

  Document* active_document = incumbent_window->document();
  if (!(active_document && active_document->GetFrame() &&
        active_document->GetFrame()->CanNavigate(*GetFrame()))) {
    return;
  }

  Settings* settings = GetFrame()->GetSettings();
  bool allow_scripts_to_close_windows =
      settings && settings->GetAllowScriptsToCloseWindows();

  if (!page->OpenedByDOM() && GetFrame()->Client()->BackForwardLength() > 1 &&
      !allow_scripts_to_close_windows) {
    active_document->domWindow()->GetFrameConsole()->AddMessage(
        MakeGarbageCollected<ConsoleMessage>(
            mojom::ConsoleMessageSource::kJavaScript,
            mojom::ConsoleMessageLevel::kWarning,
            "Scripts may close only the windows that were opened by them."));
    return;
  }

  if (!GetFrame()->ShouldClose())
    return;

  ExecutionContext* execution_context = nullptr;
  if (auto* local_dom_window = DynamicTo<LocalDOMWindow>(this)) {
    execution_context = local_dom_window->GetExecutionContext();
  }
  probe::BreakableLocation(execution_context, "DOMWindow.close");

  page->CloseSoon();

  // So as to make window.closed return the expected result
  // after window.close(), separately record the to-be-closed
  // state of this window. Scripts may access window.closed
  // before the deferred close operation has gone ahead.
  window_is_closing_ = true;
}

void DOMWindow::focus(v8::Isolate* isolate) {
  Frame* frame = GetFrame();
  if (!frame)
    return;

  Page* page = frame->GetPage();
  if (!page)
    return;

  // HTML standard doesn't require to check the incumbent realm, but Blink
  // historically checks it for some reasons, maybe the same reason as |close|.
  // (|close| checks whether the incumbent realm is eligible to close the window
  // in order to prevent a (cross origin) window from abusing |close| to close
  // pages randomly or with a malicious intent.)
  // https://html.spec.whatwg.org/C/#dom-window-focus
  // https://html.spec.whatwg.org/C/#focusing-steps
  LocalDOMWindow* incumbent_window = IncumbentDOMWindow(isolate);

  // TODO(mustaq): Use of |allow_focus| and consuming the activation here seems
  // suspicious (https://crbug.com/959815).
  bool allow_focus = incumbent_window->IsWindowInteractionAllowed();
  if (allow_focus) {
    incumbent_window->ConsumeWindowInteraction();
  } else {
    DCHECK(IsMainThread());
    allow_focus = opener() && opener() != this && incumbent_window == opener();
  }

  // If we're a top level window, bring the window to the front.
  if (frame->IsMainFrame() && allow_focus) {
    frame->FocusPage(incumbent_window->GetFrame());
  } else if (auto* local_frame = DynamicTo<LocalFrame>(frame)) {
    // We are depending on user activation twice since IsFocusAllowed() will
    // check for activation. This should be addressed in
    // https://crbug.com/959815.
    if (local_frame->GetDocument() &&
        !local_frame->GetDocument()->IsFocusAllowed()) {
      return;
    }
  }

  page->GetFocusController().FocusDocumentView(GetFrame(),
                                               true /* notifyEmbedder */);
}

InputDeviceCapabilitiesConstants* DOMWindow::GetInputDeviceCapabilities() {
  if (!input_capabilities_) {
    input_capabilities_ =
        MakeGarbageCollected<InputDeviceCapabilitiesConstants>();
  }
  return input_capabilities_;
}

void DOMWindow::PostMessageForTesting(
    scoped_refptr<SerializedScriptValue> message,
    const MessagePortArray& ports,
    const String& target_origin,
    LocalDOMWindow* source,
    ExceptionState& exception_state) {
  WindowPostMessageOptions* options = WindowPostMessageOptions::Create();
  options->setTargetOrigin(target_origin);
  DoPostMessage(std::move(message), ports, options, source, exception_state);
}

void DOMWindow::InstallCoopAccessMonitor(
    LocalFrame* accessing_frame,
    network::mojom::blink::CrossOriginOpenerPolicyReporterParamsPtr
        coop_reporter_params) {
  CoopAccessMonitor monitor;

  DCHECK(accessing_frame->IsMainFrame());
  monitor.report_type = coop_reporter_params->report_type;
  monitor.accessing_main_frame = accessing_frame->GetLocalFrameToken();
  monitor.endpoint_defined = coop_reporter_params->endpoint_defined;
  monitor.reported_window_url =
      std::move(coop_reporter_params->reported_window_url);

  monitor.reporter.Bind(std::move(coop_reporter_params->reporter));
  // CoopAccessMonitor are cleared when their reporter are gone. This avoids
  // accumulation. However it would have been interesting continuing reporting
  // accesses past this point, at least for the ReportingObserver and Devtool.
  // TODO(arthursonzogni): Consider observing |accessing_main_frame| deletion
  // instead.
  monitor.reporter.set_disconnect_handler(
      WTF::Bind(&DOMWindow::DisconnectCoopAccessMonitor,
                WrapWeakPersistent(this), monitor.accessing_main_frame));

  // As long as RenderDocument isn't shipped, it can exist a CoopAccessMonitor
  // for the same |accessing_main_frame|, because it might now host a different
  // Document. Same is true for |this| DOMWindow, it might refer to a window
  // hosting a different document.
  // The new documents will still be part of a different virtual browsing
  // context group, however the new COOPAccessMonitor might now contain updated
  // URLs.
  //
  // There are up to 2 CoopAccessMonitor for the same access, because it can be
  // reported to the accessing and the accessed window at the same time.
  for (CoopAccessMonitor& old : coop_access_monitor_) {
    if (old.accessing_main_frame == monitor.accessing_main_frame &&
        network::IsAccessFromCoopPage(old.report_type) ==
            network::IsAccessFromCoopPage(monitor.report_type)) {
      old = std::move(monitor);
      return;
    }
  }
  coop_access_monitor_.push_back(std::move(monitor));
  // Any attempts to access |this| window from |accessing_main_frame| will now
  // trigger reports (network, ReportingObserver, Devtool).
}

// Check if the accessing context would be able to access this window if COOP
// was enforced. If this isn't a report is sent.
void DOMWindow::ReportCoopAccess(const char* property_name) {
  if (coop_access_monitor_.IsEmpty())  // Fast early return. Very likely true.
    return;

  v8::Isolate* isolate = window_proxy_manager_->GetIsolate();
  LocalDOMWindow* accessing_window = IncumbentDOMWindow(isolate);
  LocalFrame* accessing_frame = accessing_window->GetFrame();

  // A frame might be destroyed, but its context can still be able to execute
  // some code. Those accesses are ignored. See https://crbug.com/1108256.
  if (!accessing_frame)
    return;

  // Iframes are allowed to trigger reports, only when they are same-origin with
  // their top-level document.
  if (accessing_frame->IsCrossOriginToMainFrame())
    return;

  // See https://crbug.com/1183571
  // We assumed accessing_frame->IsCrossOriginToMainFrame() implies
  // accessing_frame->Tree().Top() to be a LocalFrame. This might not be the
  // case after all, some crashes are reported. This block speculatively returns
  // early to avoid crashing.
  // TODO(https://crbug.com/1183571): Check if crashes are still happening and
  // remove this block.
  if (!accessing_frame->Tree().Top().IsLocalFrame()) {
    NOTREACHED();
    return;
  }

  LocalFrame& accessing_main_frame =
      To<LocalFrame>(accessing_frame->Tree().Top());
  const LocalFrameToken accessing_main_frame_token =
      accessing_main_frame.GetLocalFrameToken();

  auto* it = coop_access_monitor_.begin();
  while (it != coop_access_monitor_.end()) {
    if (it->accessing_main_frame != accessing_main_frame_token) {
      ++it;
      continue;
    }

    // TODO(arthursonzogni): Send the blocked-window-url.

    auto location = SourceLocation::Capture(
        ExecutionContext::From(isolate->GetCurrentContext()));
    // TODO(arthursonzogni): Once implemented, use the SourceLocation typemap
    // https://chromium-review.googlesource.com/c/chromium/src/+/2041657
    auto source_location = network::mojom::blink::SourceLocation::New(
        location->Url() ? location->Url() : "", location->LineNumber(),
        location->ColumnNumber());

    // TODO(https://crbug.com/1124251): Notify Devtool about the access attempt.

    // If the reporting document hasn't specified any network report
    // endpoint(s), then it is likely not interested in receiving
    // ReportingObserver's reports.
    //
    // TODO(arthursonzogni): Reconsider this decision later, developers might be
    // interested.
    if (it->endpoint_defined) {
      it->reporter->QueueAccessReport(it->report_type, property_name,
                                      std::move(source_location),
                                      std::move(it->reported_window_url));
      // Send a coop-access-violation report.
      if (network::IsAccessFromCoopPage(it->report_type)) {
        ReportingContext::From(accessing_main_frame.DomWindow())
            ->QueueReport(MakeGarbageCollected<Report>(
                ReportType::kCoopAccessViolation,
                accessing_main_frame.GetDocument()->Url().GetString(),
                MakeGarbageCollected<CoopAccessViolationReportBody>(
                    std::move(location), it->report_type, String(property_name),
                    it->reported_window_url)));
      }
    }

    // CoopAccessMonitor are used once and destroyed. This avoids sending
    // multiple reports for the same access.
    it = coop_access_monitor_.erase(it);
  }
}

void DOMWindow::DoPostMessage(scoped_refptr<SerializedScriptValue> message,
                              const MessagePortArray& ports,
                              const WindowPostMessageOptions* options,
                              LocalDOMWindow* source,
                              ExceptionState& exception_state) {
  TRACE_EVENT0("blink", "DOMWindow::DoPostMessage");
  auto* source_frame = source->GetFrame();
  bool unload_event_in_progress =
      source_frame && source_frame->GetDocument() &&
      source_frame->GetDocument()->UnloadEventInProgress();
  if (!unload_event_in_progress && source_frame && source_frame->GetPage() &&
      source_frame->GetPage()->DispatchedPagehideAndStillHidden()) {
    // The postMessage call is done after the pagehide event got dispatched
    // and the page is still hidden, which is not normally possible (this
    // might happen if we're doing a same-site cross-RenderFrame navigation
    // where we dispatch pagehide during the new RenderFrame's commit but
    // won't unload/freeze the page after the new RenderFrame finished
    // committing). We should track this case to measure how often this is
    // happening, except for when the unload event is currently in progress,
    // which means the page is not actually stored in the back-forward cache and
    // this behavior is ok.
    UMA_HISTOGRAM_ENUMERATION("BackForwardCache.SameSite.ActionAfterPagehide2",
                              ActionAfterPagehide::kSentPostMessage);
  }
  if (!IsCurrentlyDisplayedInFrame())
    return;

  // Compute the target origin.  We need to do this synchronously in order
  // to generate the SyntaxError exception correctly.
  scoped_refptr<const SecurityOrigin> target =
      PostMessageHelper::GetTargetOrigin(options, *source, exception_state);
  if (exception_state.HadException())
    return;
  if (!target) {
    UseCounter::Count(source, WebFeature::kUnspecifiedTargetOriginPostMessage);
  }

  auto channels = MessagePort::DisentanglePorts(GetExecutionContext(), ports,
                                                exception_state);
  if (exception_state.HadException())
    return;

  const SecurityOrigin* target_security_origin =
      GetFrame()->GetSecurityContext()->GetSecurityOrigin();
  const SecurityOrigin* source_security_origin = source->GetSecurityOrigin();
  bool is_source_secure = source_security_origin->IsPotentiallyTrustworthy();
  bool is_target_secure = target_security_origin->IsPotentiallyTrustworthy();
  if (is_target_secure) {
    if (is_source_secure) {
      UseCounter::Count(source, WebFeature::kPostMessageFromSecureToSecure);
    } else {
      UseCounter::Count(source, WebFeature::kPostMessageFromInsecureToSecure);
      if (!GetFrame()
               ->Tree()
               .Top()
               .GetSecurityContext()
               ->GetSecurityOrigin()
               ->IsPotentiallyTrustworthy()) {
        UseCounter::Count(source,
                          WebFeature::kPostMessageFromInsecureToSecureToplevel);
      }
    }
  } else {
    if (is_source_secure) {
      UseCounter::Count(source, WebFeature::kPostMessageFromSecureToInsecure);
    } else {
      UseCounter::Count(source, WebFeature::kPostMessageFromInsecureToInsecure);
    }
  }

  if (source->GetFrame() &&
      source->GetFrame()->Tree().Top() != GetFrame()->Tree().Top()) {
    if ((!target_security_origin->RegistrableDomain() &&
         target_security_origin->Host() == source_security_origin->Host()) ||
        (target_security_origin->RegistrableDomain() &&
         target_security_origin->RegistrableDomain() ==
             source_security_origin->RegistrableDomain())) {
      if (target_security_origin->Protocol() ==
          source_security_origin->Protocol()) {
        UseCounter::Count(source, WebFeature::kSchemefulSameSitePostMessage);
      } else {
        UseCounter::Count(source, WebFeature::kSchemelesslySameSitePostMessage);
        if (is_source_secure && !is_target_secure) {
          UseCounter::Count(
              source,
              WebFeature::kSchemelesslySameSitePostMessageSecureToInsecure);
        } else if (!is_source_secure && is_target_secure) {
          UseCounter::Count(
              source,
              WebFeature::kSchemelesslySameSitePostMessageInsecureToSecure);
        }
      }
    } else {
      UseCounter::Count(source, WebFeature::kCrossSitePostMessage);
    }
  }
  auto* local_dom_window = DynamicTo<LocalDOMWindow>(this);
  KURL target_url = local_dom_window
                        ? local_dom_window->Url()
                        : KURL(NullURL(), target_security_origin->ToString());
  if (!source->GetContentSecurityPolicy()->AllowConnectToSource(
          target_url, target_url, RedirectStatus::kNoRedirect,
          ReportingDisposition::kSuppressReporting)) {
    UseCounter::Count(
        source, WebFeature::kPostMessageOutgoingWouldBeBlockedByConnectSrc);
  }
  UserActivation* user_activation = nullptr;
  if (options->includeUserActivation())
    user_activation = UserActivation::CreateSnapshot(source);

  // TODO(mustaq): This is an ad-hoc mechanism to support delegating a single
  // capability.  We need to add a structure to support passing other
  // capabilities.  An explainer for the general delegation API is here:
  // https://github.com/mustaqahmed/capability-delegation
  bool delegate_payment_request = false;
  if (LocalFrame::HasTransientUserActivation(source_frame) &&
      options->hasDelegate()) {
    Vector<String> capability_list;
    options->delegate().Split(' ', capability_list);
    delegate_payment_request = capability_list.Contains("paymentrequest");
  }

  PostedMessage* posted_message = MakeGarbageCollected<PostedMessage>();
  posted_message->source_origin = source->GetSecurityOrigin();
  posted_message->target_origin = std::move(target);
  posted_message->data = std::move(message);
  posted_message->channels = std::move(channels);
  posted_message->source = source;
  posted_message->user_activation = user_activation;
  posted_message->delegate_payment_request = delegate_payment_request;
  SchedulePostMessage(posted_message);
}

void DOMWindow::PostedMessage::Trace(Visitor* visitor) const {
  visitor->Trace(source);
  visitor->Trace(user_activation);
}

BlinkTransferableMessage
DOMWindow::PostedMessage::ToBlinkTransferableMessage() && {
  BlinkTransferableMessage result;

  // Message data and cluster ID (optional).
  result.message = std::move(data);
  if (result.message->IsLockedToAgentCluster())
    result.locked_agent_cluster_id = source->GetAgentClusterID();

  // Ports
  result.ports = std::move(channels);

  // User activation
  if (user_activation) {
    result.user_activation = mojom::blink::UserActivationSnapshot::New(
        user_activation->hasBeenActive(), user_activation->isActive());
  }

  // Capability delegation
  result.delegate_payment_request = delegate_payment_request;

  return result;
}

void DOMWindow::Trace(Visitor* visitor) const {
  visitor->Trace(frame_);
  visitor->Trace(window_proxy_manager_);
  visitor->Trace(input_capabilities_);
  visitor->Trace(location_);
  EventTargetWithInlineData::Trace(visitor);
}

void DOMWindow::DisconnectCoopAccessMonitor(
    const LocalFrameToken& accessing_main_frame) {
  auto* it = coop_access_monitor_.begin();
  while (it != coop_access_monitor_.end()) {
    if (it->accessing_main_frame == accessing_main_frame) {
      it = coop_access_monitor_.erase(it);
    } else {
      ++it;
    }
  }
}

}  // namespace blink


text:
@interface PodsDummy_Pods_EnsemblesTesting : NSObject
@end
@implementation PodsDummy_Pods_EnsemblesTesting
@end


text:
default['mongodb']['mongod']['port'] = 27017
default['mongodb']['mongod']['bind_ip'] = '' # Leave blank to bind to all local and public IPs - in any case, make sure you list "127.0.0.1"!

# Replica set node settings
default['mongodb']['mongod']['replica_set'] = 'my_set'

default['mongodb']['mongod']['arbiter_only'] = false
default['mongodb']['mongod']['build_indexes'] = true
default['mongodb']['mongod']['hidden'] = false
default['mongodb']['mongod']['priority'] = 1.0
default['mongodb']['mongod']['tags'] = {}
default['mongodb']['mongod']['slave_delay'] = 0
default['mongodb']['mongod']['votes'] = 1

# Use the value of this property when setting the address for a given replica set node
default['mongodb']['node_address_attribute'] = 'fqdn' # leave blank to use 'bind_ip' - can't both be blank!


text:
class DualVNH5019MotorShield
{
  public:
    // CONSTRUCTORS
    DualVNH5019MotorShield(); // Default pin selection.
    DualVNH5019MotorShield(unsigned char INA1, unsigned char INB1, unsigned char EN1DIAG1, unsigned char CS1,
                           unsigned char INA2, unsigned char INB2, unsigned char EN2DIAG2, unsigned char CS2); // User-defined pin selection.

    // PUBLIC METHODS
    void init(); // Initialize TIMER 1 (or timer 3 for mega) set the PWM to 20kHZ.
    void setM1Speed(int speed); // Set speed for M1.
    void setM2Speed(int speed); // Set speed for M2.
    int getM1Speed(); // Get speed from M1
    int getM2Speed(); // Get speed from M2
    void setSpeeds(int m1Speed, int m2Speed); // Set speed for both M1 and M2.
    void setM1Brake(int brake); // Brake M1.
    void setM2Brake(int brake); // Brake M2.
    void setBrakes(int m1Brake, int m2Brake); // Brake both M1 and M2.
    unsigned int getM1CurrentMilliamps(); // Get current reading for M1.
    unsigned int getM2CurrentMilliamps(); // Get current reading for M2.
    unsigned char getM1Fault(); // Get fault reading from M1.
    unsigned char getM2Fault(); // Get fault reading from M2.

  private:
    unsigned char _INA1;
    unsigned char _INB1;
  #if defined(__AVR_ATmega168__)|| defined(__AVR_ATmega328P__)
    static const unsigned char _PWM1 = 9;
    static const unsigned char _PWM2 = 10;
  #endif
  #if defined(__AVR_ATmega128__) || defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
    static const unsigned char _PWM1 = 11;
    static const unsigned char _PWM2 = 12;
  #endif
    unsigned char _EN1DIAG1;
    unsigned char _CS1;
    unsigned char _INA2;
    unsigned char _INB2;
    unsigned char _EN2DIAG2;
    unsigned char _CS2;
    int _M1SPEED, _M2SPEED;

};

#endif


text:
// @@author A0130195M

package jfdi.logic.commands;

import jfdi.logic.events.AliasDoneEvent;
import jfdi.logic.events.AliasFailedEvent;
import jfdi.logic.interfaces.Command;
import jfdi.storage.apis.AliasAttributes;
import jfdi.storage.exceptions.DuplicateAliasException;
import jfdi.storage.exceptions.InvalidAliasException;
import jfdi.storage.exceptions.InvalidAliasParametersException;

/**
 * @author Liu Xinan
 */
public class AliasCommand extends Command {

    private String command;
    private String alias;
    private boolean isValid;

    private AliasCommand(Builder builder) {
        this.command = builder.command;
        this.alias = builder.alias;
        this.isValid = builder.isValid;
    }

    public String getCommand() {
        return command;
    }

    public String getAlias() {
        return alias;
    }

    public boolean isValid() {
        return isValid;
    }

    public static class Builder {

        String command;
        String alias;
        boolean isValid;

        public Builder setCommand(String command) {
            this.command = command;
            return this;
        }

        public Builder setAlias(String alias) {
            this.alias = alias;
            return this;
        }

        public Builder setIsValid(boolean isValid) {
            this.isValid = isValid;
            return this;
        }

        public AliasCommand build() {
            return new AliasCommand(this);
        }

    }

    @Override
    public void execute() {
        AliasAttributes newAlias = new AliasAttributes(alias, command);
        try {
            newAlias.save();
            parser.setAliases(aliasDb.getAll());

            pushToUndoStack();
            eventBus.post(new AliasDoneEvent(command, alias));
            logger.info("Aliased " + command + " to " + alias);
        } catch (InvalidAliasParametersException e) {
            eventBus.post(new AliasFailedEvent(command, alias, AliasFailedEvent.Error.INVALID_PARAMETERS));
            logger.warning("Alias not saved: Invalid alias");
        } catch (DuplicateAliasException e) {
            eventBus.post(new AliasFailedEvent(command, alias, AliasFailedEvent.Error.DUPLICATED_ALIAS));
            logger.warning("Alias not saved: Duplicate alias");
        }
    }

    @Override
    public void undo() {
        try {
            aliasDb.destroy(alias);
            parser.setAliases(aliasDb.getAll());

            logger.info("Undo add alias: Deleting alias:" + alias);
        } catch (InvalidAliasException e) {
            // Should not happen
            assert false;
        }
    }

}


text:
<?php
namespace Payum\Klarna\Checkout\Tests\Action;

use Payum\Core\PaymentInterface;
use Payum\Core\Request\NotifyRequest;
use Payum\Klarna\Checkout\Action\NotifyAction;
use Payum\Klarna\Checkout\Constants;

class NotifyActionTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @test
     */
    public function shouldBeSubClassOfPaymentAwareAction()
    {
        $rc = new \ReflectionClass('Payum\Klarna\Checkout\Action\NotifyAction');

        $this->assertTrue($rc->isSubclassOf('Payum\Core\Action\PaymentAwareAction'));
    }

    /**
     * @test
     */
    public function couldBeConstructedWithoutAnyArguments()
    {
        new NotifyAction;
    }

    /**
     * @test
     */
    public function shouldSupportNotifyRequestWithArrayAsModel()
    {
        $action = new NotifyAction();

        $this->assertTrue($action->supports(new NotifyRequest(array(), array())));
    }

    /**
     * @test
     */
    public function shouldNotSupportAnythingNotNotifyRequest()
    {
        $action = new NotifyAction;

        $this->assertFalse($action->supports(new \stdClass()));
    }

    /**
     * @test
     */
    public function shouldNotSupportNotifyRequestWithNotArrayAccessModel()
    {
        $action = new NotifyAction;

        $this->assertFalse($action->supports(new NotifyRequest(array(), new \stdClass)));
    }

    /**
     * @test
     *
     * @expectedException \Payum\Core\Exception\RequestNotSupportedException
     */
    public function throwIfNotSupportedRequestGivenAsArgumentOnExecute()
    {
        $action = new NotifyAction;

        $action->execute(new \stdClass());
    }

    /**
     * @test
     */
    public function shouldUpdateOrderWithStatusCreatedIfCurrentStatusCheckoutCompleteOnExecute()
    {
        $paymentMock = $this->createPaymentMock();
        $paymentMock
            ->expects($this->at(0))
            ->method('execute')
            ->with($this->isInstanceOf('Payum\Core\Request\SyncRequest'))
        ;
        $paymentMock
            ->expects($this->at(1))
            ->method('execute')
            ->with($this->isInstanceOf('Payum\Klarna\Checkout\Request\Api\UpdateOrderRequest'))
        ;
        $paymentMock
            ->expects($this->at(2))
            ->method('execute')
            ->with($this->isInstanceOf('Payum\Core\Request\SyncRequest'))
        ;

        $action = new NotifyAction;
        $action->setPayment($paymentMock);

        $action->execute(new NotifyRequest(array(), array(
            'status' => Constants::STATUS_CHECKOUT_COMPLETE,
            'location' => 'aLocation',
        )));
    }

    /**
     * @test
     */
    public function shouldNotUpdateOrderWithStatusCreatedIfCurrentStatusCheckoutInCompleteOnExecute()
    {
        $paymentMock = $this->createPaymentMock();
        $paymentMock
            ->expects($this->at(0))
            ->method('execute')
            ->with($this->isInstanceOf('Payum\Core\Request\SyncRequest'))
        ;

        $action = new NotifyAction;
        $action->setPayment($paymentMock);

        $action->execute(new NotifyRequest(array(), array(
            'status' => Constants::STATUS_CHECKOUT_INCOMPLETE,
            'location' => 'aLocation',
        )));
    }

    /**
     * @test
     */
    public function shouldNotUpdateOrderWithStatusCreatedIfCurrentStatusCreatedOnExecute()
    {
        $paymentMock = $this->createPaymentMock();
        $paymentMock
            ->expects($this->at(0))
            ->method('execute')
            ->with($this->isInstanceOf('Payum\Core\Request\SyncRequest'))
        ;

        $action = new NotifyAction;
        $action->setPayment($paymentMock);

        $action->execute(new NotifyRequest(array(), array(
            'status' => Constants::STATUS_CREATED,
            'location' => 'aLocation',
        )));
    }

    /**
     * @return \PHPUnit_Framework_MockObject_MockObject|PaymentInterface
     */
    protected function createPaymentMock()
    {
        return $this->getMock('Payum\Core\PaymentInterface');
    }

    /**
     * @return \PHPUnit_Framework_MockObject_MockObject|\Klarna_Checkout_Order
     */
    protected function createOrderMock()
    {
        return $this->getMock('Klarna_Checkout_Order', array(), array(), '', false);
    }
}


text:
package com.salesfront.commons.shared.model.v20150831;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import java.io.Serializable;

/**
 * Created by ahtremblay on 2016-02-18.
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(propOrder={"label", "countryCode", "number", "extension"})
public class Phone implements Serializable {
    private static final long serialVersionUID = -155882664206623193L;

    private String label;
    private Country countryCode;
    private Long number;
    private Long extension;

    public String getLabel() {
        return label;
    }

    public void setLabel(String label) {
        this.label = label;
    }

    public Country getCountryCode() {
        return countryCode;
    }

    public void setCountryCode(Country countryCode) {
        this.countryCode = countryCode;
    }

    public Long getNumber() {
        return number;
    }

    public void setNumber(Long number) {
        this.number = number;
    }

    public Long getExtension() {
        return extension;
    }

    public void setExtension(Long extension) {
        this.extension = extension;
    }

    public boolean isValid(){
        if (countryCode==null)
            return false;
        if (number==null)
            return false;

        return true;
    }

    public String stringValue(){
        String n = "";
        if (countryCode!=null)
            n+="("+countryCode.name()+")";
        if (number!=null)
            n+=number;
        if (extension!=null)
            n+=";"+extension;
        return n;
    }

    public String storeValue(){
        String n = "";
        if (number!=null)
            n+=number;
        if (extension!=null)
            n+=";"+extension;
        return n;
    }

    public enum Format{
        INTERNATIONAL,
        NATIONAL,
        E164,
        RFC3966
    }

}


text:
/**
args = {
  torrent: {
    name: Torrent name
    directory: Torrent dir
    files: [torrent files]
    kind: constants.kind.single or constants.kind.multi
  }
  constants: see constants file
}
*/
module.exports = require('./rename.js')('cartoons')


text:
import React, {PropTypes} from "react";
import {RenderCamera} from "../systems";
import Entity from "../Entity";
import EntityLoaded from "../EntityLoaded";

class TargetCamera extends React.Component {
    static propTypes = {
        position: PropTypes.arrayOf(PropTypes.number).isRequired,
        target: PropTypes.arrayOf(PropTypes.number)
    }

    static contextTypes = {
        appState: PropTypes.object,
        actions: PropTypes.object
    }

    render() {
        return (
            <Entity>
                <RenderCamera
                    type="target"
                    {...this.props}
                />
                <EntityLoaded>
                    {this.props.children}
                </EntityLoaded>
            </Entity>
        );
    }
}

export default TargetCamera;


text:
"""
Created on Mon Apr  2 21:52:14 2018

@author: spencer
"""

# functools_partial.py
import functools

def myfunc(a, b=2):
    "Docstring for myfunc()."
    print('  called myfunc with:', (a, b))

def show_details(name, f, is_partial=False):
    "Show details of a callable object."
    print('{}:'.format(name))
    print('  object:', f)
    if not is_partial:
        print('  __name__:', f.__name__)
    if is_partial:
        print('  func:', f.func)
        print('  args:', f.args)
        print('  keywords:', f.keywords)
    return

show_details('myfunc', myfunc)
myfunc('a', 3)
print()

# Set a different default value for 'b', but require
# the caller to provide 'a'.
p1 = functools.partial(myfunc, b=4)
show_details('partial with named default', p1, True)
p1('passing a')
p1('override b', b=5)
print()

# Set default values for both 'a' and 'b'.
p2 = functools.partial(myfunc, 'default a', b=99)
show_details('partial with defaults', p2, True)
p2()
p2(b='override b')
print()

print('Insufficient arguments:')
p1()


text:
package cgeo.geocaching.utils.formulas;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

import org.junit.Test;
import static org.assertj.core.api.Java6Assertions.assertThat;

public class VariableListTest {

    private VariableList createTestInstance() {
        return new VariableList();
    }

    private VariableList createInstanceWithStandardFill() {
        final VariableList cv = createTestInstance();
        cv.addVariable("a", "1", 5);
        cv.addVariable("b", "a", 5);
        cv.addVariable("c", "b", 5);
        assertVariableList(cv, "a", "f:1", "b", "f:a", "c", "f:b");
        return cv;
    }

    @Test
    public void simpleAdd() {
        final VariableList cv = createTestInstance();
        assertVariableList(cv);
        cv.addVariable("a", "2", 0);
        assertVariableList(cv, "a", "f:2");
        cv.addVariable("b", "3", 0);
        assertVariableList(cv, "b", "f:3", "a", "f:2");
        cv.addVariable("c", "3", 5);
        assertVariableList(cv, "b", "f:3", "a", "f:2", "c", "f:3");
    }

    @Test
    public void simpleRemove() {
        final VariableList cv = createInstanceWithStandardFill();
        assertVariableList(cv, "a", "f:1", "b", "f:a", "c", "f:b");

        cv.removeVariable("d"); //nonexisting
        assertVariableList(cv, "a", "f:1", "b", "f:a", "c", "f:b");

        cv.removeVariable("a");
        assertVariableList(cv, "b", "f:a", "c", "f:b");
    }

    @Test
    public void simpleChange() {
        final VariableList cv = createInstanceWithStandardFill();
        assertVariableList(cv, "a", "f:1", "b", "f:a", "c", "f:b");

        cv.changeVariable("d", "5"); //nonexisting
        assertVariableList(cv, "a", "f:1", "b", "f:a", "c", "f:b");

        cv.changeVariable("b", "5"); //nonexisting
        assertVariableList(cv, "a", "f:1", "b", "f:5", "c", "f:b");
    }

    @Test
    public void addExisting() {
        final VariableList cv = createInstanceWithStandardFill();
        assertVariableList(cv, "a", "f:1", "b", "f:a", "c", "f:b");

        cv.addVariable("b", "5", 0); //add BEFORE old var
        assertVariableList(cv, "b", "f:5", "a", "f:1", "c", "f:b");

        cv.addVariable("b", "6", 5); ///add AFTER old var
        assertVariableList(cv, "a", "f:1", "c", "f:b", "b", "f:6");
    }

    @Test
    public void addUnknown() {
        final VariableList cv = createInstanceWithStandardFill();
        assertVariableList(cv, "a", "f:1", "b", "f:a", "c", "f:b");

        final String name = cv.addVariable(null, "5", 1); //add BEFORE old var
        assertThat(name).isEqualTo("_1");
        assertVariableList(cv, "a", "f:1", "_1", "f:5", "b", "f:a", "c", "f:b");
    }

    @Test
    public void sort() {
        final VariableList cv = createInstanceWithStandardFill();
        assertVariableList(cv, "a", "f:1", "b", "f:a", "c", "f:b");

        cv.sortVariables((s1, s2) -> -s1.compareTo(s2)); //sort backwards
        assertVariableList(cv, "c", "f:b", "b", "f:a", "a", "f:1");
    }

    @Test
    public void nextChar() {
        final VariableList cv = createTestInstance();
        assertThat(cv.getLowestMissingChar()).isEqualTo('A');
        cv.addVariable("A", "");
        assertThat(cv.getLowestMissingChar()).isEqualTo('B');
        cv.addVariable("B", "");
        assertThat(cv.getLowestMissingChar()).isEqualTo('C');
        cv.removeVariable("A");
        cv.addVariable("A", "");
    }

    @Test
    public void tidyUp() {
        final VariableList cv = createTestInstance();
        cv.addVariable("B", "C");
        cv.addVariable("A", "B");
        cv.addVariable("E", "F");
        cv.addVariable("D", "");
        cv.addVariable("F", "G");

        cv.tidyUp(Arrays.asList("A", "K"));

        //D is removed (empty and no uses), C, G and K are added with empty formulas, list is sorted
        assertVariableList(cv,
                "A", "f:B", "B", "f:C", "C", "f:", "E", "f:F", "F", "f:G", "G", "f:", "K", "f:");

    }

    /**
     * expectedParams syntax: pure string = expected var, prefix with f: to assert formula
     */
    private void assertVariableList(final VariableList cv, final String... expectedParams) {
        final List<String> vars = new ArrayList<>();
        String currentVar = null;
        for (String p : expectedParams) {
            if (p.startsWith("f:")) {
                assertThat(Objects.requireNonNull(cv.getState(currentVar)).getFormulaString()).as("Formula for var '" + currentVar + "'").isEqualTo(p.substring(2));
            } else {
                currentVar = p;
                vars.add(p);
            }
        }
        assertThat(cv.asList()).containsExactlyElementsOf(vars);
        assertThat(cv.asSet()).containsExactlyInAnyOrderElementsOf(vars);
    }

}


text:
**Built with [JAX](https://jax.readthedocs.io) and
[Pint](https://pint.readthedocs.io)!**

This module provides and interface between [JAX](https://jax.readthedocs.io) and
[Pint](https://pint.readthedocs.io) to allow JAX to support operations with
units. The propagation of units happens at trace time, so jitted functions
should see no runtime cost. This library is experimental so expect some sharp
edges.

For example:

```python
>>> import jax
>>> import jax.numpy as jnp
>>> import jpu
>>>
>>> u = jpu.UnitRegistry()
>>>
>>> @jax.jit
... def add_two_lengths(a, b):
...     return a + b
...
>>> add_two_lengths(3 * u.m, jnp.array([4.5, 1.2, 3.9]) * u.cm)
<Quantity([3.045 3.012 3.039], 'meter')>

```

## Installation

To install, use `pip`:

```bash
python -m pip install jpu
```

The only dependencies are `jax` and `pint`, and these will also be installed, if
not already in your environment. Take a look at [the JAX docs for more
information about installing JAX on different
systems](https://github.com/google/jax#installation).

## Usage

Here is a slightly more complete example:

```python
>>> import jax
>>> import numpy as np
>>> from jpu import UnitRegistry, numpy as jnpu
>>>
>>> u = UnitRegistry()
>>>
>>> @jax.jit
... def projectile_motion(v_init, theta, time, g=u.standard_gravity):
...     """Compute the motion of a projectile with support for units"""
...     x = v_init * time * jnpu.cos(theta)
...     y = v_init * time * jnpu.sin(theta) - 0.5 * g * jnpu.square(time)
...     return x.to(u.m), y.to(u.m)
...
>>> x, y = projectile_motion(
...     5.0 * u.km / u.h, 60 * u.deg, np.linspace(0, 1, 50) * u.s
... )
>>> x[:3]
<Quantity([0.         0.01417234 0.02834467], 'meter')>

```

## Technical details & limitations

The most significant limitation of this library is the fact that users must use
`jpu.numpy` functions when interacting with "quantities" with units instead of
the `jax.numpy` interface. This is because JAX does not (yet?) provide a general
interface for dispatching of ufuncs on custom array classes. I have played
around with the undocumented `__jax_array__` interface, but it's not really
flexible enough, and it isn't currently compatible with Pytree objects.

So far, only a subset of the `numpy`/`jax.numpy` interface is implemented. Pull
requests adding broader support (including submodules) would be welcome!


text:
<app-header></app-header>

{{user.name}}

@{{user.username}}

{{user.description}}

		  					SEGUIR
		  					DEJAR DE SEGUIR

Últimas Publicaciones

							{{publication.title}}

{{publication.description}}

      	<app-media url="{{publication.media}}" media_type="{{publication.media_type}}"></app-media>

		<app-comments (writtenComment)="writtenComment($event)" [comments]="user.comments" location="{{user.username}}" location_type="profile"></app-comments>

<app-footer></app-footer>


text:
import React from 'react'
import { withRouter } from 'react-router'
import { graphql, compose } from 'react-apollo'
import { ProductlistQuery } from '../../../server/graphql/queries/product'
import ProductList from './component.web'
import { ScrollView } from '../../components/web/'

const ProductListWithData = (props) =>
    (
        <ScrollView>
            <ProductList {...props} />
        </ScrollView>
    )

const ProductlistQueryOptions = {
    options: ({ category: { id } }) => ({
        variables: {
            category: parseInt(id, 10)
        }
    }),
    props: ({ ownProps, data: { loading, error, products } }) => ({
        ...ownProps, loading, error, products
    })
}

export default compose(
    graphql(ProductlistQuery, ProductlistQueryOptions),
    withRouter
)(ProductListWithData)


text:
//
//  _SPLRemoteObjectConnection.h
//  SPLRemoteObject
//
//  The MIT License (MIT)
//  Copyright (c) 2013 Oliver Letterer, Sparrow-Labs
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
//

#import <Foundation/Foundation.h>

@class _SPLRemoteObjectConnection;

NS_ASSUME_NONNULL_BEGIN

@protocol _SPLRemoteObjectConnectionDelegate <NSObject>

- (void)remoteObjectConnectionConnectionAttemptFailed:(_SPLRemoteObjectConnection *)connection;
- (void)remoteObjectConnectionConnectionEnded:(_SPLRemoteObjectConnection *)connection;

- (void)remoteObjectConnection:(_SPLRemoteObjectConnection *)connection didReceiveDataPackage:(NSData *)dataPackage;

@end

/**
 @abstract  <#abstract comment#>
 */
@interface _SPLRemoteObjectConnection : NSObject

@property (nonatomic, nullable) NSInputStream *inputStream;
@property (nonatomic, nullable) NSOutputStream *outputStream;

@property (nonatomic, readonly) BOOL isClientConnection;

@property (nonatomic, weak) id<_SPLRemoteObjectConnectionDelegate> delegate;

@property (nonatomic, readonly) BOOL isConnected;

- (void)connect;
- (void)disconnect;

- (void)sendDataPackage:(NSData *)dataPackage;

@end

NS_ASSUME_NONNULL_END


text:
package com.microsoft.bingads.v10.bulk.entities;

import com.microsoft.bingads.v10.bulk.BulkServiceManager;
import com.microsoft.bingads.v10.campaignmanagement.Address;
import com.microsoft.bingads.v10.campaignmanagement.BusinessGeoCodeStatus;
import com.microsoft.bingads.v10.campaignmanagement.GeoPoint;
import com.microsoft.bingads.v10.campaignmanagement.LocationAdExtension;
import com.microsoft.bingads.v10.bulk.BulkOperation;
import com.microsoft.bingads.v10.bulk.BulkFileReader;
import com.microsoft.bingads.v10.bulk.BulkFileWriter;
import com.microsoft.bingads.v10.internal.bulk.StringExtensions;
import com.microsoft.bingads.v10.internal.bulk.StringTable;
import com.microsoft.bingads.v10.internal.bulk.BulkMapping;
import com.microsoft.bingads.v10.internal.bulk.MappingHelpers;
import com.microsoft.bingads.v10.internal.bulk.RowValues;
import com.microsoft.bingads.v10.internal.bulk.SimpleBulkMapping;
import com.microsoft.bingads.internal.functionalinterfaces.BiConsumer;
import com.microsoft.bingads.internal.functionalinterfaces.Consumer;
import com.microsoft.bingads.internal.functionalinterfaces.Function;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Represents an location ad extension. This class exposes
 * properties that can be read
 * and written as fields of the Location Ad Extension record in a bulk file.
 *
 *

 * For more information, see Location Ad Extension at
 * http://go.microsoft.com/fwlink/?LinkID=620235
 *

 *
 * @see BulkServiceManager
 * @see BulkOperation
 * @see BulkFileReader
 * @see BulkFileWriter
 */
public class BulkLocationAdExtension extends BulkAdExtension<LocationAdExtension> {

    /**
     * Gets the location ad extension.
     */
    public LocationAdExtension getLocationAdExtension() {
        return this.getAdExtension();
    }

    public void setLocationAdExtension(LocationAdExtension extension) {
        this.setAdExtension(extension);
    }

    private static final List<BulkMapping<BulkLocationAdExtension>> MAPPINGS;

    static {
        List<BulkMapping<BulkLocationAdExtension>> m = new ArrayList<BulkMapping<BulkLocationAdExtension>>();

        m.add(new SimpleBulkMapping<BulkLocationAdExtension, String>(StringTable.BusinessName,
                new Function<BulkLocationAdExtension, String>() {
                    @Override
                    public String apply(BulkLocationAdExtension c) {
                        return c.getLocationAdExtension().getCompanyName();
                    }
                },
                new BiConsumer<String, BulkLocationAdExtension>() {
                    @Override
                    public void accept(String v, BulkLocationAdExtension c) {
                        c.getLocationAdExtension().setCompanyName(v);
                    }
                }
        ));

        m.add(new SimpleBulkMapping<BulkLocationAdExtension, String>(StringTable.PhoneNumber,
                new Function<BulkLocationAdExtension, String>() {
                    @Override
                    public String apply(BulkLocationAdExtension c) {
                        return StringExtensions.toOptionalBulkString(c.getLocationAdExtension().getPhoneNumber());
                    }
                },
                new BiConsumer<String, BulkLocationAdExtension>() {
                    @Override
                    public void accept(String v, BulkLocationAdExtension c) {
                        c.getLocationAdExtension().setPhoneNumber(StringExtensions.getValueOrEmptyString(v));
                    }
                },
                true
        ));

        m.add(new SimpleBulkMapping<BulkLocationAdExtension, String>(StringTable.GeoCodeStatus,
                new Function<BulkLocationAdExtension, String>() {
                    @Override
                    public String apply(BulkLocationAdExtension c) {
                        return StringExtensions.toGeoCodeStatusBulkString(c.getLocationAdExtension().getGeoCodeStatus());
                    }
                },
                new BiConsumer<String, BulkLocationAdExtension>() {
                    @Override
                    public void accept(String v, BulkLocationAdExtension c) {
                        c.getLocationAdExtension().setGeoCodeStatus(StringExtensions.<BusinessGeoCodeStatus>parseOptional(v, new Function<String, BusinessGeoCodeStatus>() {
                            @Override
                            public BusinessGeoCodeStatus apply(String value) {
                                return BusinessGeoCodeStatus.fromValue(value);
                            }
                        }));
                    }
                }
        ));

        m.add(new SimpleBulkMapping<BulkLocationAdExtension, Long>(StringTable.IconMediaId,
                new Function<BulkLocationAdExtension, Long>() {
                    @Override
                    public Long apply(BulkLocationAdExtension c) {
                        return c.getLocationAdExtension().getIconMediaId();
                    }
                },
                new BiConsumer<String, BulkLocationAdExtension>() {
                    @Override
                    public void accept(String v, BulkLocationAdExtension c) {
                        c.getLocationAdExtension().setIconMediaId(StringExtensions.<Long>parseOptional(v, new Function<String, Long>() {
                            @Override
                            public Long apply(String value) {
                                return Long.parseLong(value);
                            }
                        }));
                    }
                }
        ));

        m.add(new SimpleBulkMapping<BulkLocationAdExtension, String>(StringTable.AddressLine1,
                new Function<BulkLocationAdExtension, String>() {
                    @Override
                    public String apply(BulkLocationAdExtension c) {
                        return getAddressPart(c, new Function<Address, String>() {
                            @Override
                            public String apply(Address x) {
                                return x.getStreetAddress();
                            }
                        });
                    }
                },
                new BiConsumer<String, BulkLocationAdExtension>() {
                    @Override
                    public void accept(final String v, BulkLocationAdExtension c) {
                        setAddressPart(c, new Consumer<Address>() {
                            @Override
                            public void accept(Address x) {
                                x.setStreetAddress(StringExtensions.getValueOrEmptyString(v));
                            }
                        });
                    }
                }
        ));

        m.add(new SimpleBulkMapping<BulkLocationAdExtension, String>(StringTable.AddressLine2,
                new Function<BulkLocationAdExtension, String>() {
                    @Override
                    public String apply(BulkLocationAdExtension c) {
                        return getAddressPart(c, new Function<Address, String>() {
                            @Override
                            public String apply(Address x) {
                                return StringExtensions.toOptionalBulkString(x.getStreetAddress2());
                            }
                        });
                    }
                },
                new BiConsumer<String, BulkLocationAdExtension>() {
                    @Override
                    public void accept(final String v, BulkLocationAdExtension c) {
                        setAddressPart(c, new Consumer<Address>() {
                            @Override
                            public void accept(Address x) {
                                x.setStreetAddress2(StringExtensions.getValueOrEmptyString(v));
                            }
                        });
                    }
                }
        ));

        m.add(new SimpleBulkMapping<BulkLocationAdExtension, String>(StringTable.City,
                new Function<BulkLocationAdExtension, String>() {
                    @Override
                    public String apply(BulkLocationAdExtension c) {
                        return getAddressPart(c, new Function<Address, String>() {
                            @Override
                            public String apply(Address x) {
                                return x.getCityName();
                            }
                        });
                    }
                },
                new BiConsumer<String, BulkLocationAdExtension>() {
                    @Override
                    public void accept(final String v, BulkLocationAdExtension c) {
                        setAddressPart(c, new Consumer<Address>() {
                            @Override
                            public void accept(Address x) {
                                x.setCityName(v);
                            }
                        });
                    }
                }
        ));

        m.add(new SimpleBulkMapping<BulkLocationAdExtension, String>(StringTable.ProvinceName,
                new Function<BulkLocationAdExtension, String>() {
                    @Override
                    public String apply(BulkLocationAdExtension c) {
                        return getAddressPart(c, new Function<Address, String>() {
                            @Override
                            public String apply(Address x) {
                                return x.getProvinceName();
                            }
                        });
                    }
                },
                new BiConsumer<String, BulkLocationAdExtension>() {
                    @Override
                    public void accept(final String v, BulkLocationAdExtension c) {
                        setAddressPart(c, new Consumer<Address>() {
                            @Override
                            public void accept(Address x) {
                                x.setProvinceName(v);
                            }
                        });
                    }
                }
        ));

        m.add(new SimpleBulkMapping<BulkLocationAdExtension, String>(StringTable.StateOrProvince,
                new Function<BulkLocationAdExtension, String>() {
                    @Override
                    public String apply(BulkLocationAdExtension c) {
                        return getAddressPart(c, new Function<Address, String>() {
                            @Override
                            public String apply(Address x) {
                                return x.getProvinceCode();
                            }
                        });
                    }
                },
                new BiConsumer<String, BulkLocationAdExtension>() {
                    @Override
                    public void accept(final String v, BulkLocationAdExtension c) {
                        setAddressPart(c, new Consumer<Address>() {
                            @Override
                            public void accept(Address x) {
                                x.setProvinceCode(v);
                            }
                        });
                    }
                }
        ));

        m.add(new SimpleBulkMapping<BulkLocationAdExtension, String>(StringTable.PostalCode,
                new Function<BulkLocationAdExtension, String>() {
                    @Override
                    public String apply(BulkLocationAdExtension c) {
                        return getAddressPart(c, new Function<Address, String>() {
                            @Override
                            public String apply(Address x) {
                                return x.getPostalCode();
                            }
                        });
                    }
                },
                new BiConsumer<String, BulkLocationAdExtension>() {
                    @Override
                    public void accept(final String v, BulkLocationAdExtension c) {
                        setAddressPart(c, new Consumer<Address>() {
                            @Override
                            public void accept(Address x) {
                                x.setPostalCode(v);
                            }
                        });
                    }
                }
        ));

        m.add(new SimpleBulkMapping<BulkLocationAdExtension, String>(StringTable.CountryCode,
                new Function<BulkLocationAdExtension, String>() {
                    @Override
                    public String apply(BulkLocationAdExtension c) {
                        return getAddressPart(c, new Function<Address, String>() {
                            @Override
                            public String apply(Address x) {
                                return x.getCountryCode();
                            }
                        });
                    }
                },
                new BiConsumer<String, BulkLocationAdExtension>() {
                    @Override
                    public void accept(final String v, BulkLocationAdExtension c) {
                        setAddressPart(c, new Consumer<Address>() {
                            @Override
                            public void accept(Address x) {
                                x.setCountryCode(v);
                            }
                        });
                    }
                }
        ));

        m.add(new SimpleBulkMapping<BulkLocationAdExtension, Double>(StringTable.Latitude,
                new Function<BulkLocationAdExtension, Double>() {
                    @Override
                    public Double apply(BulkLocationAdExtension c) {
                        return getGeoPointPart(c, new Function<GeoPoint, Double>() {
                            @Override
                            public Double apply(GeoPoint x) {
                                return (x.getLatitudeInMicroDegrees() / 1000000.0);
                            }
                        });
                    }
                },
                new BiConsumer<String, BulkLocationAdExtension>() {
                    @Override
                    public void accept(final String v, BulkLocationAdExtension c) {
                        setGeoPointPart(c, new BiConsumer<GeoPoint, String>() {
                            @Override
                            public void accept(GeoPoint x, final String longitude) {
                                x.setLatitudeInMicroDegrees(StringExtensions.parseLatLngInMicroDegrees(longitude));
                            }
                        }, v);
                    }
                }
        ));

        m.add(new SimpleBulkMapping<BulkLocationAdExtension, Double>(StringTable.Longitude,
                new Function<BulkLocationAdExtension, Double>() {
                    @Override
                    public Double apply(BulkLocationAdExtension c) {
                        return getGeoPointPart(c, new Function<GeoPoint, Double>() {
                            @Override
                            public Double apply(GeoPoint x) {
                                return (x.getLongitudeInMicroDegrees() / 1000000.0);
                            }
                        });
                    }
                },
                new BiConsumer<String, BulkLocationAdExtension>() {
                    @Override
                    public void accept(final String v, BulkLocationAdExtension c) {
                        setGeoPointPart(c, new BiConsumer<GeoPoint, String>() {
                            @Override
                            public void accept(GeoPoint x, final String longitude) {
                                x.setLongitudeInMicroDegrees(StringExtensions.parseLatLngInMicroDegrees(longitude));
                            }
                        }, v);
                    }
                }
        ));

        MAPPINGS = Collections.unmodifiableList(m);
    }

    private static String getAddressPart(BulkLocationAdExtension adExtension, Function<Address, String> getFunc) {
        return adExtension.getLocationAdExtension().getAddress() != null ? getFunc.apply(adExtension.getLocationAdExtension().getAddress()) : null;
    }

    private static void setAddressPart(BulkLocationAdExtension adExtension, Consumer<Address> setFunc) {
        if (adExtension.getLocationAdExtension().getAddress() == null) {
            adExtension.getLocationAdExtension().setAddress(new Address());
        }

        setFunc.accept(adExtension.getLocationAdExtension().getAddress());
    }

    private static Double getGeoPointPart(BulkLocationAdExtension adExtension, Function<GeoPoint, Double> getFunc) {
        return adExtension.getLocationAdExtension().getGeoPoint() != null ? getFunc.apply(adExtension.getLocationAdExtension().getGeoPoint()) : null;
    }

    private static void setGeoPointPart(BulkLocationAdExtension adExtension, BiConsumer<GeoPoint, String> setFunc, String value) {
        if (StringExtensions.isNullOrEmpty(value)) {
            return;
        }

        if (adExtension.getLocationAdExtension().getGeoPoint() == null) {
            adExtension.getLocationAdExtension().setGeoPoint(new GeoPoint());
        }

        setFunc.accept(adExtension.getLocationAdExtension().getGeoPoint(), value);
    }

    @Override
    public void processMappingsFromRowValues(RowValues values) {
        LocationAdExtension extension = new LocationAdExtension();

        extension.setType("LocationAdExtension");

        this.setLocationAdExtension(extension);

        if (!StringExtensions.isNullOrEmpty(values.get(StringTable.Latitude)) || !StringExtensions.isNullOrEmpty(values.get(StringTable.Longitude))) {
            this.getLocationAdExtension().setGeoPoint(new GeoPoint());
        }

        super.processMappingsFromRowValues(values);

        MappingHelpers.convertToEntity(values, MAPPINGS, this);
    }

    @Override
    public void processMappingsToRowValues(RowValues values, boolean excludeReadonlyData) {
        validatePropertyNotNull(this.getLocationAdExtension(), "LocationAdExtension");

        super.processMappingsToRowValues(values, excludeReadonlyData);

        MappingHelpers.convertToValues(this, values, MAPPINGS);
    }
}


text:
        {{#author.avatar}}

        {{/author.avatar}}

            {{#author.displayName}}
                {{ author.displayName }}
            {{/author.displayName}}
            {{^author.displayName}}
                {{ author.id }}
            {{/author.displayName}}

        {{{ body }}}

{{#featured}}

Featured

{{/featured}}

            Share

    {{#formattedCreatedAt}}

{{{formattedCreatedAt}}}

    {{/formattedCreatedAt}}


text:
#ifndef BOOST_MPL_END_HPP_INCLUDED
#define BOOST_MPL_END_HPP_INCLUDED

// Copyright Aleksey Gurtovoy 2004
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/mpl for documentation.

// $Id: end.hpp 49267 2008-10-11 06:19:02Z agurtovoy $
// $Date: 2008-10-10 23:19:02 -0700 (Fri, 10 Oct 2008) $
// $Revision: 49267 $

#include <boost/mpl/begin_end.hpp>

#endif // BOOST_MPL_END_HPP_INCLUDED


text:
package org.basex.query.func.db;

import org.basex.data.*;
import org.basex.index.resource.*;
import org.basex.io.*;
import org.basex.query.*;
import org.basex.query.up.*;
import org.basex.query.up.primitives.db.*;
import org.basex.query.up.primitives.node.*;
import org.basex.query.value.item.*;
import org.basex.query.value.seq.*;
import org.basex.util.*;
import org.basex.util.list.*;

/**
 * Function implementation.
 *
 * @author BaseX Team 2005-22, BSD License
 * @author Christian Gruen
 */
public final class DbDelete extends DbAccess {
  @Override
  public Item item(final QueryContext qc, final InputInfo ii) throws QueryException {
    final Data data = toData(qc);
    final String path = toDbPath(1, qc);

    // delete XML resources
    final IntList docs = data.resources.docs(path);
    final int ds = docs.size();
    final Updates updates = qc.updates();
    for(int d = 0; d < ds; d++) {
      updates.add(new DeleteNode(docs.get(d), data, info), qc);
    }
    // delete file resources
    for(final ResourceType type : Resources.BINARIES) {
      final IOFile bin = data.meta.file(path, type);
      if(bin != null) updates.add(new DBDelete(data, bin, info), qc);
    }
    return Empty.VALUE;
  }
}