text:
"use strict";
// Shared code for Shellsort: Shared between shellsortAV and shellsortCON

// Insertion sort using increments
function inssort(av, arr, start, incr, interpret) {
  var i, j;
  for (i = start + incr; i < arr.size(); i += incr) {
    for (j = i; j >= incr; j -= incr) {
      arr.unhighlight([j - incr, j]);
      arr.addClass([j - incr, j], "processing");
      av.umsg(interpret("av_code1"));
      av.step();
      if (arr.value(j) < arr.value(j - incr)) {
        arr.swap(j, j - incr); // swap the two indices
        av.umsg(interpret("av_code2"));
        av.step();
        if (j - incr > incr) {
          arr.removeClass(j, "processing");
          arr.highlight(j);
        } else {
          arr.removeClass([j - incr, j], "processing");
          arr.highlight([j - incr, j]);
        }
      }
      else {
        av.umsg(interpret("av_code3"));
        arr.highlight([j - incr, j]);
        arr.removeClass([j - incr, j], "processing");
        break; // Done pushing element, leave for loop
      }
    }
  }
}

// Partial Shellsort. Sweep with the given increment
function sweep(av, arr, incr, interpret) {
  var j = 0;
  var numElem = Math.ceil(arr.size() / incr);
  av.umsg(interpret("av_code4") + incr);
  av.step();
  var highlightFunction = function (index) { return index % incr === j; };
  for (j = 0; j < incr; j++) {         // Sort each sublist
    // Highlight the sublist
    arr.highlight(highlightFunction);
    if (j + (incr * (numElem - 1)) >= arr.size()) {
      numElem = numElem - 1;
    }
    if ((j + incr) === arr.size()) { // Only one element, don't process
      arr.unhighlight(highlightFunction);
      av.umsg(interpret("av_code5"));
      av.step();
      return;
    }
    av.umsg(interpret("av_code6") + numElem + interpret("av_code7"));
    av.step();
    inssort(av, arr, j, incr, interpret);
    arr.removeClass(true, "processing");
    arr.unhighlight(highlightFunction);
  }
}

// Display a slideshow for a sweep of "increment" steps on array "inArr"
function doSweep(av_name, inArr, increment) {
  // Load the config object with interpreter and code created by odsaUtils.js
  var config = ODSA.UTILS.loadConfig(
                 {"av_name": av_name, "json_path": "AV/Sorting/shellsortAV.json"});
  var interpret = config.interpreter;       // get the interpreter
  var av = new JSAV(av_name);
  // Create an array object under control of JSAV library
  var arr = av.ds.array(inArr, {indexed: true});
  av.displayInit();
  sweep(av, arr, increment, interpret); // first sweep with increment 8
  av.recorded();
}

// Show the differences between the original array and given array "a"
function showDifference(av_name, theArray, a) {
  // Load the config object with interpreter and code created by odsaUtils.js
  var config = ODSA.UTILS.loadConfig(
                 {"av_name": av_name, "json_path": "AV/Sorting/shellsortAV.json"});
  var interpret = config.interpreter;       // get the interpreter
  var av = new JSAV(av_name, {"animationMode": "none"});
  var origarr = av.ds.array(theArray, {indexed: true});
  var origlabel = av.label(interpret("av_diff1"), {before: origarr});
  var arr = av.ds.array(a, {indexed: true});
  var arrlabel = av.label(interpret("av_diff2"), {before: arr});
  arr.addClass(function (index)
                 { return arr.value(index) !== origarr.value(index); },
               "greentext");
}


text:
require 'test_helper'

class ListingCategoriesTest < ActionDispatch::IntegrationTest
  setup do
    Category.create!(name: 'Dirt Cheap')
    Category.create!(name: 'Da Bling')
  end

  test 'listing categories' do
    get '/categories'

    assert_equal 200, response.status
    assert_equal Mime::JSON, response.content_type

    assert_equal Category.count, json(response.body).size
  end
end

redpajama_set_name: RedPajamaGithub


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

<resources>
    <!--
    TODO: Before you release your application, you need a Google Maps API key.

    To do this, you can either add your release key credentials to your existing
    key, or create a new key.

    Note that this file specifies the API key for the release build target.
    If you have previously set up a key for the debug target with the debug signing certificate,
    you will also need to set up a key for your release certificate.

    Follow the directions here:

    https://developers.google.com/maps/documentation/android/signup

    Once you have your key (it starts with "AIza"), replace the "google_maps_key"
    string in this file.
    -->
    <string name="google_maps_key" templateMergeStrategy="preserve" translatable="false">
        YOUR_KEY_HERE
    </string>
</resources>


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

/* global require, module */

var EmberApp = require('ember-cli/lib/broccoli/ember-app');

var app = new EmberApp();

// Use `app.import` to add additional libraries to the generated
// output files.
//
// If you need to use different assets in different
// environments, specify an object as the first parameter. That
// object's keys should be the environment name and the values
// should be the asset to use in that environment.
//
// If the library that you are including contains AMD or ES6
// modules that you would like to import into your application
// please specify an object with the list of modules as keys
// along with the exports of each module as its value.

module.exports = app.toTree();


text:
# Starting from scratch

This is part of [The Brunch.io Guide](../../README.md).

If you've carefully read through the previous sections, well done you :clap:, I know it can be tempting to skip straight to the code/tutorial.  I'm sure you're glad you read these chapters, though. :grin:

## How about a shortcut?

If you'd like to **follow along easily**, I set up a public repository on GitHub that has every step of the way available:

  * [The GitHub repo](https://github.com/brunch/brunch-guide-demos)
  * If you don't use Git, grab an archive: [Zip](https://github.com/brunch/brunch-guide-demos/archive/master.zip) or [TGZ](https://github.com/brunch/brunch-guide-demos/archive/master.tar.gz).

## Just a couple files

Let's start with a first example, that'll stick with Brunch's conventions, but not start off a skeleton.  We'll go with simple JS (ES3/ES5), a SASS stylesheet and static HTML.

Our tree looks like this:

```text
.
├── app
│   ├── application.js
│   ├── assets
│   │   └── index.html
│   └── styles
│       └── main.scss
└── package.json
```

Here are the files we start with (you'll find these in `0-starter` in the repo):

`app/assets/index.html`:

```html
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Simple Brunch Demo</title>
  <link rel="stylesheet" href="app.css">
</head>
<body>
  <h1>
    Brunch
    <small>• A simple demo</small>
  </h1>
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>
  <script src="app.js"></script>
</body>
</html>
```

`app/styles/main.scss`:

```scss
$default-bg: white;
$default-text: black;

body {
  font-family: Georgia, serif;
  font-size: 16px;
  background: $default-bg;
  color: $default-text;
}

h1 {
  font-size: 2em;
  margin: 0.5em 0 1em;

  & > small {
    color: gray;
    font-size: 70%;
  }
}
```

`app/application.js`:

```js
'use strict';

const App = {
  init() {
    console.log('App initialized.');
  }
};

module.exports = App;
```

Finally, `package.json`:

```json
{
  "name": "simple-brunch",
  "version": "0.1.0",
  "private": true
}
```

## Installing a starting set of Brunch modules

Now we'll "install" Brunch and the minimum set of modules we need in this case, locally to the current app:

```
$ npm install --save-dev brunch javascript-brunch sass-brunch
…

$ npm ls -depth=0
simple-brunch@0.1.0 …
├── brunch@1.8.3
├── javascript-brunch@1.7.1
└── sass-brunch@1.8.10
```

Finally, we need a minimal **Brunch configuration**.  A Brunch configuration file is just a Node module that exports at least a `files` property that describes concatenations.  Here's our `brunch-config.js`:

```js
module.exports = {
  files: {
    javascripts: {joinTo: 'app.js'},
    stylesheets: {joinTo: 'app.css'}
  }
}
```

And yes, **that's it!** :grin:

## Our first build

OK, let's go for our first build.  From the app's root directory, where `brunch-config.js` is (at the same level as `app`) just do:

```
$ brunch build
25 Feb 17:07:20 - info: compiled 2 files into 2 files, copied index.html in 94ms
```

Note how long that one-shot build took: **94 milliseconds**.  And that' on a live-encrypted disk.

Here's what Brunch will have put in `public`:

```text
public/
├── app.css
├── app.css.map
├── app.js
├── app.js.map
└── index.html
```

The files from `assets/` are there alright (hence the `index.html`), and the concatenations too, along with their sourcemaps.  Let's have a look at `app.css`:

```css
/* line 4, stdin */
body {
  font-family: Georgia, serif;
  font-size: 16px;
  background: white;
  color: black; }

/* line 11, stdin */
h1 {
  font-size: 2em;
  margin: 0.5em 0 1em; }
  /* line 15, stdin */
  h1 > small {
    color: gray;
    font-size: 70%; }

/*# sourceMappingURL=app.css.map*/
```

Not too shabby.  What about `app.js`?  It starts with Brunch's "bootstrapper", less than a hundred lines of JS code that provide module management and `require(…)` logic, then we get our modules, neatly wrapped.  Here are lines 93 and below, check out the `require.register(…)` plumbing for module registration:

```js
require.register("application", function(exports, require, module) {
"use strict";

var App = {
  init: function init() {
    console.log("App initialized");
  }
};

module.exports = App;

});

//# sourceMappingURL=app.js.map
```

Because our JS is now modularized, nothing appears in the console when we load the page: we need to **require the module** that serves as our app's entry point.

By default, **modules are named from their path** inside the watched paths that are subject to module wrapping.  If you only have one such path, it won't prefix module names (this is our case, as just `app` is relevant).  If you have many such paths, their basename will prefix module names.  The file extension is not used, which lets you use whatever script syntax you'd like (e.g. CoffeeScript or TypeScript).

As we have an `app/application.js` file, the module name is just `"application"`, as you can see above.  So at the end of our `<body>`, inside `app/assets/index.html`, we just add the following at line 15:

```html
<script>require('application').init();</script>
```

Let's run the build again:

```sh
$ brunch b  # Shortcut for "brunch build"
```

And now, if we refresh this:

![Our module runs at page load](../images/brunch-simple-console.png)

Notice the path you get in the log: `application.js:5` instead of `app.js:98`: this is sourcemaps for you!  If you don't get this mapping, check that sourcemaps are enabled in your developer tool settings, and also open developer tools *before* refreshing the page, otherwise sourcemaps won't get loaded in time.  In doubt, once the console is visible, just refresh the page.

Sourcemaps work for CSS, too:

![Sourcemaps work for CSS as well](../images/brunch-simple-styles.png)

Notice the `main.scss:2` location for our `body` rule?  And if you click it (or one of its properties), you'll get the original source code, naturally.

## Globals; because, reasons.

Now let's say we want to use jQuery, or another library.  If we already have code that assumes jQuery is available as a global variable, we'll either need to migrate our code (which is a must-do in the long run), or leave jQuery as a non-wrapped codebase (which is acceptable as a transition hack).

Let's say our `application.js` needs to inject content at the end of the `<body>`:

```js
'use strict';

const App = {
  init() {
    $('body').append('App initialized.');
  }
};

module.exports = App;
```

We'll first stay with the global-variable approach, as a transition thing.  So we put our `jquery.js` in a new `vendor` folder, in the same place as `app`, and rebuild.  When we refresh, it works, and the message appears at the end of our page:

![Global jQuery kinda works](../images/brunch-simple-jquery.png)

The entire jQuery codebase is actually injected as-is between Brunch's "bootstrapper" code and our own wrapped modules.  Brunch will inject all the files in `vendor` there, in alphabetical order (unless we specify another order in our configuration).

## Getting modular again

Still, that gross global variable isn't so good, that's just sloppy, wouldn't you say?  Especially considering that jQuery has a sort of UMD loader in it, so it can detect CommonJS module wrapping and export itself properly.  So let's try to refactor our code instead.

Let's just move `jquery.js` from `vendor` to `app`, so it gets wrapped as a module with a simple name `"jquery"`.  Feel free to remove the now-empty `vendor` directory.

Next, let's adjust our `application.js` so it explicitly requires `jquery`, using the idiomatic `$` name for it locally (yes, locally: we're in a module, remember?).  See line 3 here:

```js
'use strict';

const $ = require('jquery');

const App = {
  init() {
    $('body').append('App initialized.');
  }
};

module.exports = App;
```

We rebuild, refresh, and it still works! :heart:

## Split targets

A common recommendation here is to **put your third-party libraries in a separate bundle**, because they'll change **far less often** than your own codebase: so by using two targets, one for third-party and one for your own code, you get two initial loads instead of one, but then only require refreshing your own, **vastly smaller** bundle later on.

Here's a sample Brunch configuration that achieves this split; because our third-party code is not currently grouped in a special directory, but just slapped casually at the root of our watched path for their module names to stay simple (we'll learn how to set that up in a more flexible way later), we'll list them explicitly, here through a regex.

This is our updated `brunch-config.js`:

```js
module.exports = {
  files: {
    javascripts: {
      joinTo: {
        'libraries.js': /^app\/jquery\.js/,
        'app.js': /^(?!app\/jquery\.js)/
      }
    },
    stylesheets: {joinTo: 'app.css'}
  }
}
```

As soon as you have multiple targets, your `joinTo` properties become objects mapping a target name (the property key) with a description of matching sources (the property value).  These descriptions are [anymatch sets](https://github.com/es128/anymatch#anymatch--), which can be specific names, globbings, regexes, predicate functions, or an array mixing any of these.  In short, it's super flexible.

For this to still work, you'll need to adjust the bottom of your `index.html` file in `assets` to properly load both target scripts:

```html
<script src="libraries.js"></script>
<script src="app.js"></script>
<script>require("application").init();</script>
```

----

In the next chapter, we'll learn how to rely on third-party module registries to be able to use versioned dependencies for our code.

« Previous: [Conventions and defaults](chapter03-conventions-and-defaults.md) • Next: [Using third-party module registries](chapter05-using-third-party-registries.md) »


text:
package spet.sbwo.control.action.batch;

import spet.sbwo.control.action.base.BaseDatabaseAction;
import spet.sbwo.control.action.base.IDatabaseAction;
import spet.sbwo.control.action.misc.GeocodeLocation;
import spet.sbwo.control.channel.location.LocationChannel;
import spet.sbwo.data.access.IDatabaseExecutor;
import spet.sbwo.data.table.Location;
import spet.sbwo.integration.api.geocode.IGeocodingApi;

import java.util.List;

public class GeocodeLocationBatch extends BaseDatabaseAction<Integer, Void> {
    private final GeocodeLocation geocodeLocation;

    public GeocodeLocationBatch(IGeocodingApi api) {
        super(LocationChannel.class);
        geocodeLocation = new GeocodeLocation(api);
    }

    public static IDatabaseAction<Void, Void> forInput(IGeocodingApi api, int count) {
        return (i, e) -> new GeocodeLocationBatch(api).run(count, e);
    }

    @Override
    protected Void doRun(Integer input, IDatabaseExecutor executor) {
        List<Location> locations = executor.queryListLimit("Location.getNotGeocoded", Location.class, input);
        for (Location location : locations) {
            geocodeLocation.run(location, executor);
        }
        return null;
    }

}


text:
package io.crate.operation.reference.sys.node;

import io.crate.metadata.sys.SysNodesTableInfo;
import io.crate.operation.reference.sys.SysNodeObjectReference;
import org.elasticsearch.monitor.os.OsStats;

public class NodeOsExpression extends SysNodeObjectReference {

    abstract class OsExpression extends SysNodeExpression<Object> {
    }

    public static final String UPTIME = "uptime";
    public static final String TIMESTAMP = "timestamp";
    private static final String PROBE_TIMESTAMP = "probe_timestamp";

    public NodeOsExpression(OsStats stats) {
        addChildImplementations(stats);
    }

    private void addChildImplementations(final OsStats os) {
        childImplementations.put(UPTIME, new OsExpression() {
            @Override
            public Long value() {
                return os.uptime().millis();
            }
        });
        childImplementations.put(TIMESTAMP, new OsExpression() {
            @Override
            public Long value() {
                return System.currentTimeMillis();
            }
        });
        childImplementations.put(PROBE_TIMESTAMP, new OsExpression() {
            @Override
            public Long value() {
                return os.timestamp();
            }
        });
        childImplementations.put(SysNodesTableInfo.SYS_COL_OS_CPU,
                new NodeOsCpuExpression(os));
    }

}


text:
package com.dci.intellij.dbn.connection.config.ui;

import com.dci.intellij.dbn.common.options.ui.CompositeConfigurationEditorForm;
import com.dci.intellij.dbn.common.ui.tab.TabbedPane;
import com.dci.intellij.dbn.common.ui.tab.TabbedPaneUtil;
import com.dci.intellij.dbn.connection.config.ConnectionDatabaseSettings;
import com.dci.intellij.dbn.connection.config.ConnectionDetailSettings;
import com.dci.intellij.dbn.connection.config.ConnectionFilterSettings;
import com.dci.intellij.dbn.connection.config.ConnectionSettings;
import com.intellij.ui.tabs.TabInfo;

import javax.swing.JComponent;
import javax.swing.JPanel;
import java.awt.BorderLayout;

public class ConnectionSettingsForm extends CompositeConfigurationEditorForm<ConnectionSettings> {
    private JPanel mainPanel;
    private TabbedPane configTabbedPane;

    public ConnectionSettingsForm(ConnectionSettings connectionSettings) {
        super(connectionSettings);
        ConnectionDatabaseSettings databaseSettings = connectionSettings.getDatabaseSettings();
        configTabbedPane = new TabbedPane(databaseSettings.getProject());
        mainPanel.add(configTabbedPane, BorderLayout.CENTER);

        TabInfo connectionTabInfo = new TabInfo(databaseSettings.createComponent());
        connectionTabInfo.setText("Connection");
        configTabbedPane.addTab(connectionTabInfo);

        ConnectionDetailSettings detailSettings = connectionSettings.getDetailSettings();
        TabInfo detailsTabInfo = new TabInfo(detailSettings.createComponent());
        detailsTabInfo.setText("Details");
        configTabbedPane.addTab(detailsTabInfo);

        ConnectionFilterSettings filterSettings = connectionSettings.getFilterSettings();
        TabInfo filtersTabInfo = new TabInfo(filterSettings.createComponent());
        filtersTabInfo.setText("Filters");
        configTabbedPane.addTab(filtersTabInfo);

        String connectionId = connectionSettings.getId();
        ConnectionDetailSettingsForm detailSettingsForm = detailSettings.getSettingsEditor();
        ConnectionFilterSettingsForm filterSettingsForm = filterSettings.getSettingsEditor();
        GenericDatabaseSettingsForm databaseSettingsForm = databaseSettings.getSettingsEditor();

        filterSettingsForm.setConnectionId(connectionId);
        databaseSettingsForm.setConnectionId(connectionId);
        detailSettingsForm.setConnectionId(connectionId);

        databaseSettingsForm.notifyPresentationChanges();
        detailSettingsForm.notifyPresentationChanges();
    }

    public void selectTab(String tabName) {
        TabbedPaneUtil.selectTab(configTabbedPane, tabName);
    }

    public String getSelectedTabName() {
        return TabbedPaneUtil.getSelectedTabName(configTabbedPane);
    }

    public JComponent getComponent() {
        return mainPanel;
    }

    @Override
    public void dispose() {
        super.dispose();
    }
}


text:
#include "web/tests/FrameTestHelpers.h"

#include "platform/testing/URLTestHelpers.h"
#include "platform/testing/UnitTestHelpers.h"
#include "public/platform/Platform.h"
#include "public/platform/WebData.h"
#include "public/platform/WebString.h"
#include "public/platform/WebThread.h"
#include "public/platform/WebURLRequest.h"
#include "public/platform/WebURLResponse.h"
#include "public/platform/WebUnitTestSupport.h"
#include "public/web/WebFrameWidget.h"
#include "public/web/WebRemoteFrame.h"
#include "public/web/WebSettings.h"
#include "public/web/WebTreeScopeType.h"
#include "public/web/WebViewClient.h"
#include "web/WebLocalFrameImpl.h"
#include "web/WebRemoteFrameImpl.h"
#include "wtf/Functional.h"
#include "wtf/StdLibExtras.h"
#include "wtf/text/StringBuilder.h"

namespace blink {
namespace FrameTestHelpers {

namespace {

// The frame test helpers coordinate frame loads in a carefully choreographed
// dance. Since the parser is threaded, simply spinning the run loop once is not
// enough to ensure completion of a load. Instead, the following pattern is
// used to ensure that tests see the final state:
// 1. Starts a load.
// 2. Enter the run loop.
// 3. Posted task triggers the load, and starts pumping pending resource
//    requests using runServeAsyncRequestsTask().
// 4. TestWebFrameClient watches for didStartLoading/didStopLoading calls,
//    keeping track of how many loads it thinks are in flight.
// 5. While runServeAsyncRequestsTask() observes TestWebFrameClient to still
//    have loads in progress, it posts itself back to the run loop.
// 6. When runServeAsyncRequestsTask() notices there are no more loads in
//    progress, it exits the run loop.
// 7. At this point, all parsing, resource loads, and layout should be finished.
TestWebFrameClient* testClientForFrame(WebFrame* frame)
{
    return static_cast<TestWebFrameClient*>(toWebLocalFrameImpl(frame)->client());
}

void runServeAsyncRequestsTask(TestWebFrameClient* client)
{
    Platform::current()->unitTestSupport()->serveAsynchronousMockedRequests();
    if (client->isLoading())
        Platform::current()->currentThread()->taskRunner()->postTask(BLINK_FROM_HERE, bind(&runServeAsyncRequestsTask, client));
    else
        testing::exitRunLoop();
}

void pumpPendingRequests(WebFrame* frame)
{
    Platform::current()->currentThread()->taskRunner()->postTask(BLINK_FROM_HERE, bind(&runServeAsyncRequestsTask, testClientForFrame(frame)));
    testing::enterRunLoop();
}

TestWebFrameClient* defaultWebFrameClient()
{
    DEFINE_STATIC_LOCAL(TestWebFrameClient, client, ());
    return &client;
}

TestWebViewClient* defaultWebViewClient()
{
    DEFINE_STATIC_LOCAL(TestWebViewClient,  client, ());
    return &client;
}

} // namespace

void loadFrame(WebFrame* frame, const std::string& url)
{
    WebURLRequest urlRequest;
    urlRequest.initialize();
    urlRequest.setURL(URLTestHelpers::toKURL(url));
    frame->loadRequest(urlRequest);
    pumpPendingRequests(frame);
}

void loadHTMLString(WebFrame* frame, const std::string& html, const WebURL& baseURL)
{
    frame->loadHTMLString(WebData(html.data(), html.size()), baseURL);
    pumpPendingRequests(frame);
}

void loadHistoryItem(WebFrame* frame, const WebHistoryItem& item, WebHistoryLoadType loadType, WebURLRequest::CachePolicy cachePolicy)
{
    frame->loadHistoryItem(item, loadType, cachePolicy);
    pumpPendingRequests(frame);
}

void reloadFrame(WebFrame* frame)
{
    frame->reload(false);
    pumpPendingRequests(frame);
}

void reloadFrameIgnoringCache(WebFrame* frame)
{
    frame->reload(true);
    pumpPendingRequests(frame);
}

void pumpPendingRequestsDoNotUse(WebFrame* frame)
{
    pumpPendingRequests(frame);
}

WebLocalFrame* createLocalChild(WebRemoteFrame* parent, const WebString& name, WebFrameClient* client, WebFrame* previousSibling, const WebFrameOwnerProperties& properties)
{
    if (!client)
        client = defaultWebFrameClient();

    // |uniqueName| is normally calculated in a somewhat complicated way by the
    // FrameTree class, but for test purposes the approximation below should be
    // close enough.
    static int uniqueNameCounter = 0;
    StringBuilder uniqueName;
    uniqueName.append(name);
    uniqueName.appendNumber(uniqueNameCounter++);

    return parent->createLocalChild(WebTreeScopeType::Document, name, uniqueName.toString(), WebSandboxFlags::None, client, previousSibling, properties);
}

WebViewHelper::WebViewHelper(SettingOverrider* settingOverrider)
    : m_webView(nullptr)
    , m_webViewWidget(nullptr)
    , m_settingOverrider(settingOverrider)
{
}

WebViewHelper::~WebViewHelper()
{
    reset();
}

WebViewImpl* WebViewHelper::initialize(bool enableJavascript, TestWebFrameClient* webFrameClient, TestWebViewClient* webViewClient, void (*updateSettingsFunc)(WebSettings*))
{
    reset();

    if (!webFrameClient)
        webFrameClient = defaultWebFrameClient();
    if (!webViewClient)
        webViewClient = defaultWebViewClient();
    m_webView = WebViewImpl::create(webViewClient);
    m_webView->settings()->setJavaScriptEnabled(enableJavascript);
    m_webView->settings()->setPluginsEnabled(true);
    // Enable (mocked) network loads of image URLs, as this simplifies
    // the completion of resource loads upon test shutdown & helps avoid
    // dormant loads trigger Resource leaks for image loads.
    //
    // Consequently, all external image resources must be mocked.
    m_webView->settings()->setLoadsImagesAutomatically(true);
    if (updateSettingsFunc)
        updateSettingsFunc(m_webView->settings());
    else
        m_webView->settings()->setDeviceSupportsMouse(false);
    if (m_settingOverrider)
        m_settingOverrider->overrideSettings(m_webView->settings());
    m_webView->setDeviceScaleFactor(webViewClient->screenInfo().deviceScaleFactor);
    m_webView->setDefaultPageScaleLimits(1, 4);
    WebLocalFrame* frame = WebLocalFrameImpl::create(WebTreeScopeType::Document, webFrameClient);
    m_webView->setMainFrame(frame);
    // TODO(dcheng): The main frame widget currently has a special case.
    // Eliminate this once WebView is no longer a WebWidget.
    m_webViewWidget = blink::WebFrameWidget::create(webViewClient, m_webView, frame);

    m_testWebViewClient = webViewClient;

    return m_webView;
}

WebViewImpl* WebViewHelper::initializeAndLoad(const std::string& url, bool enableJavascript, TestWebFrameClient* webFrameClient, TestWebViewClient* webViewClient, void (*updateSettingsFunc)(WebSettings*))
{
    initialize(enableJavascript, webFrameClient, webViewClient, updateSettingsFunc);

    loadFrame(webView()->mainFrame(), url);

    return webViewImpl();
}

void WebViewHelper::reset()
{
    if (m_webViewWidget) {
        m_webViewWidget->close();
        m_webViewWidget = nullptr;
    }
    if (m_webView) {
        ASSERT(m_webView->mainFrame()->isWebRemoteFrame() || !testClientForFrame(m_webView->mainFrame())->isLoading());
        m_webView->willCloseLayerTreeView();
        m_webView->close();
        m_webView = nullptr;
    }
}

void WebViewHelper::resize(WebSize size)
{
    m_testWebViewClient->clearAnimationScheduled();
    webViewImpl()->resize(size);
    EXPECT_FALSE(m_testWebViewClient->animationScheduled());
    m_testWebViewClient->clearAnimationScheduled();
}

TestWebFrameClient::TestWebFrameClient() : m_loadsInProgress(0)
{
}

WebFrame* TestWebFrameClient::createChildFrame(WebLocalFrame* parent, WebTreeScopeType scope, const WebString& name, const WebString& uniqueName, WebSandboxFlags sandboxFlags, const WebFrameOwnerProperties& frameOwnerProperties)
{
    WebFrame* frame = WebLocalFrame::create(scope, this);
    parent->appendChild(frame);
    return frame;
}

void TestWebFrameClient::frameDetached(WebFrame* frame, DetachType type)
{
    if (type == DetachType::Remove && frame->parent())
        frame->parent()->removeChild(frame);
    frame->close();
}

void TestWebFrameClient::didStartLoading(bool)
{
    ++m_loadsInProgress;
}

void TestWebFrameClient::didStopLoading()
{
    ASSERT(m_loadsInProgress > 0);
    --m_loadsInProgress;
}

void TestWebFrameClient::waitForLoadToComplete()
{
    for (;;) {
        // We call runPendingTasks multiple times as single call of
        // runPendingTasks may not be enough.
        // runPendingTasks only ensures that main thread task queue is empty,
        // and asynchronous parsing make use of off main thread HTML parser.
        testing::runPendingTasks();
        if (!isLoading())
            break;

        testing::yieldCurrentThread();
    }
}

TestWebRemoteFrameClient::TestWebRemoteFrameClient()
    : m_frame(WebRemoteFrameImpl::create(WebTreeScopeType::Document, this))
{
}

void TestWebRemoteFrameClient::frameDetached(DetachType type)
{
    if (type == DetachType::Remove && m_frame->parent())
        m_frame->parent()->removeChild(m_frame);
    m_frame->close();
}

void TestWebViewClient::initializeLayerTreeView()
{
    m_layerTreeView = adoptPtr(Platform::current()->unitTestSupport()->createLayerTreeViewForTesting());
    ASSERT(m_layerTreeView);
}

} // namespace FrameTestHelpers
} // namespace blink


text:
class ACDB_PORT AcPointCloudColorSchemeCollectionReactor
{
public:
    /// <summary>
    /// This callback function gets called after AcDbPointCloudColorMap is changed
    /// while colorMap is opened with write access.
    /// Do not close the colorMap object that is given to this function.
    /// </summary>
    /// <param name="colorMap">The AcDbPointCloudColorMap that is being changed.</param>
    virtual void PointCloudColorSchemeCollectionChanged(class AcDbPointCloudColorMap* colorMap) = 0;

    //////////////////////////////////////////////////////////////////////////////
    /// <summary>
    /// Destructor
    /// </summary>
    virtual ~AcPointCloudColorSchemeCollectionReactor();
};

class PointCloudColorMapImp;

//////////////////////////////////////////////////////////////////////////////
/// <summary>
/// The AcDbPointCloudColorRamp class represents an intensity or elevation color ramp
/// </summary>
class ACDB_PORT AcDbPointCloudColorRamp
{
public:

    //////////////////////////////////////////////////////////////////////////////
    /// <summary>
    /// Default constructor.
    /// </summary>
    AcDbPointCloudColorRamp();

    //////////////////////////////////////////////////////////////////////////////
    /// <summary>
    /// Destructor
    /// </summary>
    ~AcDbPointCloudColorRamp();

    /// <summary>
    /// Get the number of colors in this color ramp
    /// </summary>
    /// <returns> Returns The number of colors in this color ramp. </returns>
    Adesk::Int32            numColors() const;

    /// <summary>
    /// Set the number of colors in this color ramp
    /// </summary>
    /// <param name="count">The color count.</param>
    /// <returns>
    /// Returns Acad::eOk if successful.
    /// If count is not between the minimum number (2) and maximum number (25), returns Acad::eInvalidInput.
    /// </returns>
    /// <remarks>
    /// NOTES: The minimum number is 2, the maximum number of colors is 25.
    /// </remarks>
    Acad::ErrorStatus       setNumColors(Adesk::Int32 count);

    /// <summary>
    /// Gets the color definition at a given index.
    /// </summary>
    /// <param name="c">The index of the color.</param>
    /// <returns> the color definition. </returns>
    AcCmEntityColor         color(int c) const;

    /// <summary>
    /// Sets the color definition at a given index.
    /// </summary>
    /// <param name="c">The index of the color.</param>
    /// <param name="color">The color definition.</param>
    void                    setColor(int c, AcCmEntityColor color);

    /// <summary>
    /// Gets the visibility of a color at a given index.
    /// </summary>
    /// <param name="c">The index of the color.</param>
    /// <returns> Returns whether the color is visible or not. </returns>
    bool                    visibility(int c) const;

    /// <summary>
    /// Sets the visibility of a color at a given index.
    /// </summary>
    /// <param name="c">The index of the color.</param>
    /// <param name="visibility">Specifies whether the color is visible or not.</param>
    void                    setVisibility(int c, bool visibility);

    /// <summary>
    /// Copies the color ramp definition from the given ramp.
    /// </summary>
    /// <param name="source">The color ramp to copy from.</param>
    void                    setFrom(const AcDbPointCloudColorRamp* source);

    /// <summary>
    /// Gets the name of this ramp.
    /// </summary>
    /// <returns> Returns the name of the ramp. </returns>
    const AcString          name() const;

    /// <summary>
    /// Set the name of this ramp.
    /// </summary>
    /// <param name="name">The color ramp name.</param>
    /// <returns>
    /// Returns Acad::eOk if successful or Acad::eInvalidInput otherwise.
    /// </returns>
    Acad::ErrorStatus       setName(const AcString& name);

private:
friend class PointCloudColorMapImp;
    Acad::ErrorStatus       dwgOutFields(AcDbDwgFiler* pFiler) const;
    Acad::ErrorStatus       dwgInFields(AcDbDwgFiler* pFiler);
    Acad::ErrorStatus       dxfOutFields(AcDbDxfFiler* pFiler) const;
    Acad::ErrorStatus       dxfInFields(AcDbDxfFiler* pFiler);

    class PointCloudColorRampImp* pImpl;
};

//////////////////////////////////////////////////////////////////////////////
/// <summary>
/// The AcDbPointCloudClassificationColorRamp class represents a classification color ramp
/// </summary>
class ACDB_PORT AcDbPointCloudClassificationColorRamp
{
public:

    //////////////////////////////////////////////////////////////////////////////
    /// <summary>
    /// Default constructor for an AcDbPointCloudClassificationColorRamp.
    /// </summary>
    AcDbPointCloudClassificationColorRamp();

    //////////////////////////////////////////////////////////////////////////////
    /// <summary>
    /// Destructor
    /// </summary>
    ~AcDbPointCloudClassificationColorRamp();

    /// <summary>
    /// Gets the number of colors in this color ramp
    /// </summary>
    /// <returns> Returns number of colors in this color ramp. </returns>
    Adesk::Int32            numColors() const;

    /// <summary>
    /// Gets the color definition at a given index.
    /// </summary>
    /// <param name="c">The index of the color.</param>
    /// <returns> the color definition. </returns>
    AcCmEntityColor         color(int c) const;

    /// <summary>
    /// Sets the color definition at a given index.
    /// </summary>
    /// <param name="c">The index of the color.</param>
    /// <param name="color">The color definition.</param>
    void                    setColor(int c, AcCmEntityColor color);

    /// <summary>
    /// Gets the visibility of the color at a given index.
    /// </summary>
    /// <param name="c">The index of the color.</param>
    /// <returns> the color visibility. </returns>
    bool                    visibility(int c) const;

    /// <summary>
    /// Sets the visibility of the color at a given index.
    /// </summary>
    /// <param name="c">The index of the color.</param>
    /// <param name="visibility">Specifies whether the color is visible or not.</param>
    void                    setVisibility(int c, bool visibility);

    /// <summary>
    /// Copies the color ramp definition from a given ramp.
    /// </summary>
    /// <param name="source">The color ramp to copy from.</param>
    void                    setFrom(const AcDbPointCloudClassificationColorRamp* source);

    /// <summary>
    /// Get the name of this ramp
    /// </summary>
    /// <returns> Returns the name of the ramp. </returns>
    const AcString          name() const;

    /// <summary>
    /// Set the name of this ramp
    /// </summary>
    /// <param name="name">The color ramp name.</param>
    /// <returns>
    /// Returns Acad::eOk if successful or Acad::eInvalidInput otherwise.
    /// </returns>
    Acad::ErrorStatus       setName(const AcString& name);

private:
friend class PointCloudColorMapImp;
    Acad::ErrorStatus       dwgOutFields(AcDbDwgFiler* pFiler) const;
    Acad::ErrorStatus       dwgInFields(AcDbDwgFiler* pFiler);
    Acad::ErrorStatus       dxfOutFields(AcDbDxfFiler* pFiler) const;
    Acad::ErrorStatus       dxfInFields(AcDbDxfFiler* pFiler);

    class PointCloudClassificationColorRampImp* pImpl;
};

/// <summary>
/// The AcDbPointCloudColorMap class stores all color map ramp definitions.
/// There is only one AcDbPointCloudColorMap object per database.
/// The user can use getColorMap() to retrieve the AcDbPointCloudColorMap object.
/// There are two kinds of color ramps:
/// intensity or elevation color ramps (which are used when the point cloud is stylized by intensity or elevation),
/// and classification color ramps (which are used when the point cloud is stylized by classification).
/// The color ramps are indexed by GUIDs inside the AcDbPointCloudColorMap object,
/// and point clouds reference these ramps by GUIDs.
/// </summary>
class ACDB_PORT AcDbPointCloudColorMap : public AcDbObject
{
friend class PointCloudColorMapImp;
friend class AcDbPointCloudMgr;

    static const Adesk::UInt16  kCurrentObjectVersion;

public:
    ACRX_DECLARE_MEMBERS(AcDbPointCloudColorMap);

    /// <summary>
    /// Gets the color map object for the given point cloud. Do not use the constructors directly.
    /// </summary>
    /// <returns>
    /// Returns Acad::eOk if successful or Acad::eInvalidInput otherwise.
    /// </returns>
    /// <param name="id">Output for the AcDbObjectId of the color map object.</param>
    /// <param name="pDb">The database to be searched.</param>
    /// <param name="bCreateIfNone">Whether to create a new color map if none exists.</param>
    static Acad::ErrorStatus getColorMap(AcDbObjectId& id, AcDbDatabase* pDb, bool bCreateIfNone = true);

    //////////////////////////////////////////////////////////////////////////////
    /// <summary>
    /// Destructor
    /// </summary>
    virtual ~AcDbPointCloudColorMap();

    /// <summary>
    /// Registers a AcPointCloudColorSchemeCollectionReactor, which will be notified when the color map ramps are changed.
    /// </summary>
    /// <param name="pReactor">The AcPointCloudColorSchemeCollectionReactor to add.</param>
    void                            addColorSchemeCollectionReactor(AcPointCloudColorSchemeCollectionReactor* pReactor);

    /// <summary>
    /// Removes a AcPointCloudColorSchemeCollectionReactor.
    /// </summary>
    /// <param name="pReactor">The AcPointCloudColorSchemeCollectionReactor to remove.</param>
    void                            removeColorSchemeCollectionReactor(AcPointCloudColorSchemeCollectionReactor* pReactor);

    /// <summary>
    /// Forcefully notifies all of the  AcPointCloudColorSchemeCollectionReactor objects.
    /// </summary>
    void                            notifyColorSchemeCollectionChanged() const;

    // Intensity

    /// <summary>
    /// Gets the default intensity color scheme's GUID.
    /// </summary>
    /// <returns> Returns the default intensity color scheme's GUID. </returns>
    const AcString                  defaultIntensityColorScheme() const;

    /// <summary>
    /// Sets the default intensity color scheme's GUID
    /// </summary>
    /// <param name="GUID">The the default intensity color scheme's GUID .</param>
    /// <returns> Returns true upon success. </returns>
    bool                            setDefaultIntensityColorScheme(const AcString GUID);

    // Elevation

    /// <summary>
    /// Gets the default elevation color scheme's GUID
    /// </summary>
    /// <returns> Returns the default elevation color scheme's GUID. </returns>
    const AcString                  defaultElevationColorScheme() const;

    /// <summary>
    /// Sets the default elevation color scheme's GUID
    /// </summary>
    /// <param name="GUID">The default elevation color scheme's GUID .</param>
    /// <returns> Returns true upon success. </returns>
    bool                            setDefaultElevationColorScheme(const AcString GUID);

    // Classification

    /// <summary>
    /// Gets the default classification color scheme's GUID
    /// </summary>
    /// <returns> Returns default classification color scheme's GUID. </returns>
    const AcString                  defaultClassificationColorScheme() const;

    /// <summary>
    /// Sets the default classification color scheme's GUID
    /// </summary>
    /// <param name="GUID">The default classification color scheme's GUID.</param>
    /// <returns> Returns true upon success. </returns>
    bool                            setDefaultClassificationColorScheme(const AcString GUID);

    // Color Schemes

    /// <summary>
    /// Gets the complete list of GUIDs for each intensity and elevation color scheme in this map.
    /// </summary>
    /// <returns> Returns the list of intensity and elevation color scheme's GUIDs in this map. </returns>
    AcArray<AcString>               colorSchemeGUIDs() const;

    /// <summary>
    /// Given a GUID, gets the color ramp definition.
    /// </summary>
    /// <param name="GUID">The color scheme GUID.</param>
    /// <param name="target">The color ramp definition.</param>
    /// <returns> Returns true upon success. </returns>
    bool                            colorScheme(const wchar_t* GUID, AcDbPointCloudColorRamp& target) const;

    /// <summary>
    /// Tests whether a color scheme with the GUID exists or not.
    /// </summary>
    /// <param name="GUID">The color scheme GUID.</param>
    /// <returns> Returns true if the color scheme exists. </returns>
    bool                            hasColorScheme(const wchar_t* GUID) const;

    /// <summary>
    /// Sets the definition of an intensity or elevation color ramp for the given the GUID.
    /// </summary>
    /// <param name="GUID">The color scheme's GUID.</param>
    /// <param name="source">The color ramp definition.</param>
    /// <returns> Returns true upon success. </returns>
    bool                            setColorScheme(const wchar_t* GUID, const AcDbPointCloudColorRamp& source);

    /// <summary>
    /// Deletes the color scheme with the given GUID.
    /// </summary>
    /// <param name="GUID">The color scheme's GUID.</param>
    /// <returns> Returns true upon success. </returns>
    bool                            deleteColorScheme(const wchar_t* GUID);

    /// <summary>
    /// Gets the complete list of GUIDs for all classification color schemes in this map.
    /// </summary>
    /// <returns> Returns the list of classification color scheme GUIDs. </returns>
    AcArray<AcString>               classificationSchemeGUIDs() const;

    /// <summary>
    /// Given a GUID, gets the classification color ramp definition.
    /// </summary>
    /// <param name="GUID">The color scheme's GUID.</param>
    /// <param name="target">The color ramp definition.</param>
    /// <returns> Returns true upon success. </returns>
    bool                            classificationScheme(const wchar_t* GUID, AcDbPointCloudClassificationColorRamp& target) const;

    /// <summary>
    /// Tests whether the classification color scheme with the GUID exists or not.
    /// </summary>
    /// <param name="GUID">The color scheme's GUID.</param>
    /// <returns> Returns true if the color scheme exists. </returns>
    bool                            hasClassificationScheme(const wchar_t* GUID) const;

    /// <summary>
    /// Sets the given color scheme with the given GUID.
    /// </summary>
    /// <param name="GUID">The color scheme's GUID.</param>
    /// <param name="source">The color ramp definition.</param>
    /// <returns> Returns true upon success. </returns>
    bool                            setClassificationScheme(const wchar_t* GUID, const AcDbPointCloudClassificationColorRamp& source);

    /// <summary>
    /// Deletes the classification color ramp for the given GUID.
    /// </summary>
    /// <param name="GUID">The color scheme's GUID.</param>
    /// <returns> Returns true upon success. </returns>
    bool                            deleteClassificationScheme(const wchar_t* GUID);

    /// <summary>
    /// Get a list of intensity or elevation color ramps that are being used by any point cloud.
    /// </summary>
    /// <param name="GUIDs">Output parameter for the color schemes' GUIDs that are in use.</param>
    void                            getColorSchemeInUse(AcArray<AcString>& GUIDs) const;

    /// <summary>
    /// Get a list of classification color ramps that are being used by any point cloud.
    /// </summary>
    /// <param name="GUIDs">Output parameter for the color schemes' GUIDs that are in use.</param>
    void                            getClassificationColorSchemeInUse(AcArray<AcString>& GUIDs) const;

    /// <summary>
    /// This function is called by dwgIn(). Its purpose is to allow this object to read in its data.
    /// </summary>
    /// <param name="pFiler">
    /// The filer to use to read in the object's data
    /// </param>
    /// <returns>
    /// Returns Acad::eOk if successful.
    /// </returns>
    virtual Acad::ErrorStatus       dwgInFields(AcDbDwgFiler* pFiler) override;

    /// <summary>
    /// This function is called by dwgOut(). Its purpose is to allow this object to write out its data.
    /// </summary>
    /// <param name="pFiler">
    /// The filer to use to write out the object's data
    /// </param>
    /// <returns>
    /// Returns Acad::eOk if successful.
    /// </returns>
    virtual Acad::ErrorStatus       dwgOutFields(AcDbDwgFiler* pFiler) const override;

    /// <summary>
    /// This function is called by dxfIn(). Its purpose is to allow this object to read in its data.
    /// </summary>
    /// <param name="pFiler">
    /// The filer to use to read in the object's data
    /// </param>
    /// <returns>
    /// Returns Acad::eOk if successful.
    /// </returns>
    virtual Acad::ErrorStatus       dxfInFields(AcDbDxfFiler* pFiler) override;

    /// <summary>
    /// This function is called by dxfOut(). Its purpose is to allow this object to write out its data.
    /// </summary>
    /// <param name="pFiler">
    /// The filer to use to write out the object's data
    /// </param>
    /// <returns>
    /// Returns Acad::eOk if successful.
    /// </returns>
    virtual Acad::ErrorStatus       dxfOutFields(AcDbDxfFiler* pFiler) const override;

    /// <summary>
    /// Called from within the close() method, before anything else is done.
    /// </summary>
    /// <returns>
    /// Returns Acad::eOk when closing can be done successfully. However,
    /// if this method returns anything other than Acad::eOk,then the
    /// close operation is immediately terminated.
    /// </returns>
    virtual Acad::ErrorStatus       subClose() override;

private:
    AcDbPointCloudColorMap();
    AcDbPointCloudColorMap(bool initializeDefaults);
    PointCloudColorMapImp *pImpl;
};


text:
package com.b2international.snowowl.core.request.suggest;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;

import org.elasticsearch.core.Map;
import org.hibernate.validator.constraints.NotEmpty;

import com.b2international.snowowl.core.ServiceProvider;
import com.b2international.snowowl.core.authorization.AuthorizationService;
import com.b2international.snowowl.core.events.Request;
import com.b2international.snowowl.core.events.util.Promise;
import com.b2international.snowowl.core.identity.User;
import com.b2international.snowowl.eventbus.IEventBus;
import com.google.common.collect.Iterables;

/**
 * @since 8.5.1
 */
public final class ConceptSuggestionBulkRequest implements Request<ServiceProvider, List<Suggestions>> {

	private static final long serialVersionUID = 1L;

	@NotEmpty
	private List<ConceptSuggestionRequest> requests;

	@NotNull
	@Min(1)
	private Integer batchSize;

	@NotNull
	@Min(1)
	private Integer batchTimeout;

	ConceptSuggestionBulkRequest() {
	}

	void setRequests(List<ConceptSuggestionRequest> requests) {
		this.requests = requests;
	}

	void setBatchSize(int batchSize) {
		this.batchSize = batchSize;
	}

	void setBatchTimeout(int batchTimeout) {
		this.batchTimeout = batchTimeout;
	}

	@Override
	public List<Suggestions> execute(ServiceProvider context) {
		// cache accessible resources before executing any of the specified suggestion requests, so that we won't hit the authorization service multiple times from multiple threads
		User user = context.service(User.class);
		context
			.optionalService(AuthorizationService.class)
			.orElse(AuthorizationService.DEFAULT)
			.getAccessibleResources(context, user);

		final List<Suggestions> response = new ArrayList<>(requests.size());
		for (Iterable<ConceptSuggestionRequest> batch : Iterables.partition(requests, batchSize)) {
			final List<Promise<Suggestions>> batchResponse = new ArrayList<>(batchSize);
			batch.forEach(request -> {
				// pass the prefetched User with accessible resource information forward, so that nested suggestion requests can use the cached info
				batchResponse.add(request.async(Map.of(User.class, user)).execute(context.service(IEventBus.class)).fail(err -> {
					// TODO report error for this batch in the response
					context.log().error("Failed to compute suggestions for request: {}", request, err);
					return new Suggestions(List.of(), 0, 0);
				}));
			});
			// wait for batch completion then proceed to next batch, a batch must complete in under the specified minutes (default 2 min, configurable)
			Promise.all(batchResponse)
				.getSync(batchTimeout, TimeUnit.SECONDS)
				.stream()
				.filter(Suggestions.class::isInstance)
				.map(Suggestions.class::cast)
				.forEach(response::add);
		}
		return response;
	}

}


text:
<?php

defined('PHPFOX') or exit('NO DICE!');

class AdvancedMarketplace_Component_Block_FrontEnd_View_textline extends Phpfox_Component
{
	public function process()
	{
		$aField = $this->getParam("aField");
		$cfInfors = $this->getParam("cfInfors");

		$sDisplay = $cfInfors[$aField["var_type"]]["tag"];

		$sDisplay = str_replace("jh_#%id%#_", "custom_field_" . $aField["field_id"], $sDisplay);
		$sDisplay = str_replace("jh_#%name%#_", sprintf("customfield[%s]",$aField["field_id"]), $sDisplay);
		$sDisplay = str_replace("jh_#%value%#_", $aField["field_id"], $sDisplay);
		$sDisplay = str_replace("jh_#%class%#_", "cus_textline", $sDisplay);
		$sDisplay = str_replace("jh_#%custom_attribute%#_", "", $sDisplay);
		$sDisplay = str_replace("jh_#%text%#_", $aField["data"], $sDisplay);
		// var_dump($aField);exit;
		// var_dump($sDisplay);exit;
		// var_dump($cfInfors);
		$this->template()->assign(array(
			"sPhraseVarName" => $aField["phrase_var_name"],
			"sDisplay" => $sDisplay
		));
		// return "block";
	}
}
?>


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

	<meta content="text/html;charset=utf-8" http-equiv="Content-Type"></meta>
    <title>Maize Sequence Read Mapper</title>
    <link href="img/favicon.ico" rel="shortcut icon">

    <link type="text/css" rel="stylesheet" href="css/main.css"></link>


text:
const urljoin = require('url-join');
const fs = require('fs-extra');
const request = require('request-promise');
const cachedRequest = require('cached-request')(request);
const path = require('path');
const _ = require('lodash');
const stream = require('stream');
const Promise = require('bluebird');

module.exports = function(app) {
  var config = app.web.services.get('storage');
  var project = app.web.project;
  var bucket = config.buckets.pages.host;
  var cacheDirectory = path.join(project.paths.core.cache, 'private-pages');
  var ttl = 5 * 60 * 1000;

  var normalizeOptions = cachedRequest.getValue('normalizeOptions');
  var hashKey = cachedRequest.getValue('hashKey');

  return function(data) {
    var key = urljoin(data.remotePath, 'index.html');
    var options = {
      url: key
    };

    var cacheKey = JSON.stringify(normalizeOptions(options));
    cacheKey = hashKey(cacheKey);

    var cachedFilePath = path.join(cacheDirectory, cacheKey + '');
    var headersPath = path.join(cacheDirectory, cacheKey + '.json');

    var params = {
      Bucket: bucket,
      Key: key
    };

    return Promise.resolve()
      .then(function() {
        return fs.pathExists(headersPath).then(function(exists) {
          console.log('headersPath exist', exists);

          if (!exists) {
            return false;
          }
          return fs.pathExists(cachedFilePath);
        });
      })
      .then(function(exists) {
        console.log('cachedFilePath exist', exists);

        if (!exists) {
          return false;
        }
        return fs.stat(headersPath).then(function(stats) {
          if (stats.mtime.getTime() + ttl < Date.now()) {
            return false;
          }
          return fs.readJson(headersPath).then(function(headers) {
            for (var key in headers) {
              let value = headers[key];
              data.res.set(key, value);
            }
            fs.createReadStream(cachedFilePath).pipe(data.res);
            return true;
          });
        });
      })
      .then(function(sent) {
        if (sent) {
          return;
        }

        return app.storage
          .headObject({
            Bucket: bucket,
            Key: key
          })
          .then(function(storageObjectHead) {
            var headers = _.zipObject(
              [
                'content-encoding',
                'content-type',
                'content-length',
                'last-modified'
              ],
              _.values(
                _.pick(storageObjectHead, [
                  'ContentEncoding',
                  'ContentType',
                  'ContentLength',
                  'LastModified'
                ])
              )
            );

            for (var key in headers) {
              let value = headers[key];
              data.res.set(key, value);
            }

            return fs.outputFile(headersPath, JSON.stringify(headers));
          })
          .then(function() {
            return fs.remove(cachedFilePath);
          })
          .then(function() {
            return fs.ensureFile(cachedFilePath);
          })
          .then(function() {
            var responseWriter = fs.createWriteStream(cachedFilePath);

            var readableStream = app.storage
              .getObjectStream(params)
              .on('error', function(err) {
                data.next(err);
              });

            readableStream = readableStream.pipe(new stream.PassThrough());
            readableStream.pipe(data.res);

            readableStream = readableStream.pipe(new stream.PassThrough());
            readableStream.pipe(responseWriter);

            return readableStream;
          });
      })
      .catch(function(err) {
        data.next(err);
      });
  };
};


text:
package org.jcodings.spi;

import java.nio.charset.Charset;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

/**
 * An SPI character set provider for ISO-8859-16.
 */
public class Charsets extends java.nio.charset.spi.CharsetProvider {
    private static final List<Charset> charsets = Collections.singletonList((Charset) ISO_8859_16.INSTANCE);
    public Iterator<Charset> charsets() {
        return charsets.iterator();
    }

    public Charset charsetForName(String charsetName) {
        if ("ISO-8859-16".equals(charsetName) || ISO_8859_16.INSTANCE.aliases().contains(charsetName)) {
            return ISO_8859_16.INSTANCE;
        }
        return null;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Text;

namespace SyntaxNodeAnalyzer
{
    [DiagnosticAnalyzer(LanguageNames.CSharp)]
    public class SyntaxNodeAnalyzerAnalyzer : DiagnosticAnalyzer
    {
        //Each analyzer needs a public id to identify each DiagnosticDescriptor and subsequently fix diagnostics in CodeFixProvider.cs
        public const string spacingRuleId = "IfSpacing001";

        //If the analyzer finds an issue, it will report the DiagnosticDescriptor rule
        internal static DiagnosticDescriptor Rule = new DiagnosticDescriptor(id: spacingRuleId, defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true, title: "Enter a title for this diagnostic", messageFormat: "Enter a message to be displayed with this diagnostic", category: "Enter a category for this diagnostic");
        //id: Identifies each rule. Same as the public constant declared above
        //defaultSeverity: Is set to DiagnosticSeverity.[severity] where severity can be Error, Warning, Hidden or Info, but can only be Error or Warning for the purposes of this tutorial
        //isEnabledByDefault: Determines whether the analyzer is enabled by default or if the user must manually enable it. Generally set to true

        public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
        {
            get
            {
                //This array contains all the diagnostics that can be shown to the user
                return ImmutableArray.Create(Rule);
            }
        }

        public override void Initialize(AnalysisContext context)
        {
            //Calls the method (first argument) to perform analysis whenever this is a change to a SyntaxNode of kind IfStatement
            context.RegisterSyntaxNodeAction(AnalyzeIfStatement, SyntaxKind.IfStatement);
        }

        //This method, which is the method that is registered within Initialize, performs the analysis of the Syntax Tree when an IfStatementSyntax Node is found. If the analysis finds an error, a diagnostic is reported
        //In this tutorial, this method will walk through the Syntax Tree seen in IfSyntaxTree.jpg and determine if the if-statement being analyzed has the correct spacing
        private void AnalyzeIfStatement(SyntaxNodeAnalysisContext context)
        {
            //The SyntaxNode found by the Initialize method should be cast to the expected type. Here, this type is IfStatementSyntax
            var ifStatement = (IfStatementSyntax)context.Node;

            //This statement navigates down the syntax tree one level to extract the 'if' keyword
            var ifKeyword = ifStatement.IfKeyword;

            if (ifKeyword.HasTrailingTrivia)
            {
                if (ifKeyword.TrailingTrivia.Count == 1)
                {
                    var trailingTrivia = ifKeyword.TrailingTrivia.First();

                    if (trailingTrivia.Kind() == SyntaxKind.WhitespaceTrivia)
                    {
                        if (trailingTrivia.ToString() == " ")
                        {
                            //If the analyzer is satisfied that there is only a single whitespace between 'if' and '(', it will return from this method without reporting a diagnostic
                            return;
                        }
                    }
                }
            }

            //Extracts the opening parenthesis of the if-statement condition
            var openParen = ifStatement.OpenParenToken;

            //Determines the start of the span of the diagnostic that will be reported, ie the start of the squiggle
            var startDiagnosticSpan = ifKeyword.SpanStart;

            //Determines the end of the span of the diagnostic that will be reported
            var endDiagnosticSpan = openParen.SpanStart;

            //The span is the range of integers that define the position of the characters the red squiggle will underline
            var diagnosticSpan = TextSpan.FromBounds(startDiagnosticSpan, endDiagnosticSpan);

            //Uses the span created above to create a location for the diagnostic squiggle to appear within the syntax tree passed in as an argument
            var diagnosticLocation = Location.Create(ifStatement.SyntaxTree, diagnosticSpan);

            //Holds the diagnostic and all necessary information to be reported
            var diagnostic = Diagnostic.Create(Rule, diagnosticLocation);

            //Sends diagnostic information to the IDE to be shown to the user
            context.ReportDiagnostic(diagnostic);
        }
    }
}


text:
package com.intellij.android.designer.model.layout.relative;

import com.intellij.android.designer.designSurface.feedbacks.TextFeedback;
import com.intellij.android.designer.model.RadViewComponent;
import com.intellij.designer.designSurface.FeedbackLayer;
import org.jetbrains.annotations.NotNull;

import java.awt.*;

/**
 * The {@link com.intellij.designer.designSurface.feedbacks.AbstractTextFeedback} class does not support multiline text, so we
 * have to manage multiple {@link com.intellij.designer.designSurface.feedbacks.AbstractTextFeedback} objects, one for each line.
 */
public class MultiLineTooltipManager {
  /** Horizontal delta from the mouse cursor to shift the tooltip by */
  private static final int OFFSET_X = 20;

  /** Vertical delta from the mouse cursor to shift the tooltip by */
  private static final int OFFSET_Y = 20;

  private final TextFeedback[] myTextFeedbacks;
  @NotNull private final Dimension[] mySizes;
  @NotNull private final boolean[] myVisible;

  @NotNull private final FeedbackLayer myLayer;

  public MultiLineTooltipManager(@NotNull FeedbackLayer layer, int maxLines) {
    myLayer = layer;

    myTextFeedbacks = new TextFeedback[maxLines];
    mySizes = new Dimension[maxLines];
    myVisible = new boolean[maxLines];
  }

  @NotNull
  public TextFeedback getFeedback(int line) {
    assert line < myTextFeedbacks.length;

    TextFeedback feedback = myTextFeedbacks[line];
    if (feedback == null) {
      feedback = new TextFeedback();
      myTextFeedbacks[line] = feedback;
      myLayer.add(feedback);
    }

    return feedback;
  }

  public void setVisible(int line, boolean visible) {
    myVisible[line] = visible;
  }

  public void dispose() {
    for (TextFeedback feedback : myTextFeedbacks) {
      if (feedback != null) {
        myLayer.remove(feedback);
      }
    }
  }

  private Dimension getPreferredSize() {
    int width = 0;
    int height = 0;

    for (int i = 0; i < myTextFeedbacks.length; i++) {
      TextFeedback feedback = myTextFeedbacks[i];
      if (feedback != null && myVisible[i]) {
        Dimension preferredSize = feedback.getPreferredSize();
        width = Math.max(width, preferredSize.width);
        height += preferredSize.height;
        mySizes[i] = preferredSize;
      }
    }

    // Some padding
    width += 2;
    height += 2;

    return new Dimension(width, height);
  }

  /**
   * Update the tooltip such that it is placed within the given container layout.
   *
   * @param container the layout
   * @param mouseLocation the mouse location
   */
  public void update(RadViewComponent container, Point mouseLocation) {
    // Produce the bounds of the container
    Rectangle bounds = container.getBounds(myLayer);
    Dimension preferredSize = getPreferredSize();
    // TODO: Push it out of the way based on the mouse location, with a timer

    int x = bounds.x + bounds.width / 2 - preferredSize.width / 2;
    int y = bounds.y - 1 - preferredSize.height;
    if (y < 0) {
      y = bounds.y + bounds.height - preferredSize.height - 1;
    }

    for (int i = 0; i < myTextFeedbacks.length; i++) {
      TextFeedback feedback = myTextFeedbacks[i];
      if (feedback != null) {
        if (myVisible[i]) {
          int height = mySizes[i].height;
          feedback.setBounds(x, y, preferredSize.width, height);
          y += height;
          feedback.setVisible(true);
        } else {
          feedback.setVisible(false);
        }
      }
    }
  }

  /**
   * Update the tooltip and position it relative to the given x,y mouse position. The
   * {@code below} and {@code toRightOf} flags can be used to push the tooltip out
   * of the way; if you for example happen to be resizing the bottom right corner
   * of a view, then you'd probably want the tooltip above and to the left, such that
   * it does not obscure potential constraints to the right and below matched by the corner.
   *
   * @param below     if true, place the label below the y position
   * @param toRightOf if true, place the label to the right of the x position
   * @param x         the x position
   * @param y         the y position
   */
  public void update(boolean below, boolean toRightOf, int x, int y) {
    Dimension preferredSize = getPreferredSize();
    if (below) {
      y += OFFSET_Y;
    }
    else {
      y -= OFFSET_Y;
      y -= preferredSize.height;
    }

    if (toRightOf) {
      x += OFFSET_X;
    }
    else {
      x -= OFFSET_X;
      x -= preferredSize.width;
    }

    for (int i = 0; i < myTextFeedbacks.length; i++) {
      TextFeedback feedback = myTextFeedbacks[i];
      if (feedback != null) {
        if (myVisible[i]) {
          int height = mySizes[i].height;
          feedback.setBounds(x, y, preferredSize.width, height);
          y += height;
          feedback.setVisible(true);
        }
        else {
          feedback.setVisible(false);
        }
      }
    }
  }
}


text:
This code is described in the following section(s) of [`methods/methods_release1.md`](https://github.com/biocore/emp/blob/master/methods/methods_release1.md):

**1.2:**

* `deblur/run_deblur_emp_original.sh` (pre-release version used for this meta-analysis)
* `deblur/run_deblur_emp_new.sh` (using published Deblur version)
* `closed-ref/closed_reference_otu_picking.ipynb`
* `open-ref/open_reference_otu_picking.ipynb`

**1.3:**

* `deblur/run_sepp.sh`


text:
=begin rdoc
=Alien Ruby RFID Library
==alientaglist.rb

A simple class to hold an array of taglist data elements.

(The format of strings handled by the build_tag method is assumed to be compatible with Alien's 'text' taglist format.)

Copyright 2008, Alien Technology Corporation. All rights reserved.
=end

#Takes a string returned from a Taglist function call and builds an array of tags.

module Alien
  class AlienTagList < Array

    def initialize(taglist_string="")
      super()
      string_to_taglist(taglist_string) if taglist_string != ""
    end

    # Takes a taglist string from a reader and appends it to the array.
    def string_to_taglist(taglist_string)
      lines = taglist_string.split("\r\n")

      lines.each do |line|
        if line != "(No Tags)"
          add_tag(AlienTag.new(line))
        end
      end

      return self
    end

    # Adds an AlienTag to the list.
    def add_tag(t)
      self.push(t)
      return self
    end

    # A little regular expression scanner. Looks at the list of tags and returns a
    # new taglist containing those tag IDs that match a regular expression filter.
    def filter(filter)
      tl = AlienTagList.new

      self.each do |ele|
        if ele.tag =~ filter
          tl.add_tag(ele)
        end
      end

      return tl
    end

    # A self-modifying version of filter_taglist.
    # Excercise caution. Elements in the taglist array that do not match
    # the regular expression are deleted.
    def filter!(filter)
      self.delete_if { |ele| !(ele.tag =~ filter)}
      return self
    end

  end #class AlienTagList
end


text:
package org.finra.herd.service.activiti.task;

import org.activiti.engine.delegate.DelegateExecution;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.finra.herd.model.api.xml.EmrCluster;
import org.finra.herd.model.api.xml.EmrClusterCreateRequest;
import org.finra.herd.model.api.xml.EmrClusterDefinition;
import org.springframework.stereotype.Component;

/**
 * An Activiti task that creates the EMR cluster
 *

 *
 *

 * <extensionElements>
 *   <activiti:field name="namespaceCode" stringValue="" />
 *   <activiti:field name="emrClusterDefinitionName" stringValue="" />
 *   <activiti:field name="emrClusterName" stringValue="" />
 *   <activiti:field name="dryRun" stringValue="" />
 *   <activiti:field name="contentType" stringValue="" />
 *   <activiti:field name="emrClusterDefinitionOverride" stringValue="" />
 * </extensionElements>
 *

 */
@Component
public class CreateEmrCluster extends BaseEmrCluster
{
    private static final Logger LOGGER = Logger.getLogger(CreateEmrCluster.class);

    @Override
    public void executeImpl(DelegateExecution execution) throws Exception
    {
        // Create the request.
        EmrClusterCreateRequest request = new EmrClusterCreateRequest();
        request.setNamespace(activitiHelper.getExpressionVariableAsString(namespace, execution));
        request.setEmrClusterDefinitionName(activitiHelper.getExpressionVariableAsString(emrClusterDefinitionName, execution));
        request.setEmrClusterName(activitiHelper.getExpressionVariableAsString(emrClusterName, execution));
        request.setDryRun(activitiHelper.getExpressionVariableAsBoolean(dryRun, execution, "dryRun", false, false));

        String contentTypeString = activitiHelper.getExpressionVariableAsString(contentType, execution);
        String emrClusterDefinitionOverrideString = activitiHelper.getExpressionVariableAsString(emrClusterDefinitionOverride, execution);

        if (StringUtils.isNotBlank(contentTypeString) && StringUtils.isBlank(emrClusterDefinitionOverrideString))
        {
            throw new IllegalArgumentException("emrClusterDefinitionOverride is required when contentType is specified");
        }
        else if (StringUtils.isBlank(contentTypeString) && StringUtils.isNotBlank(emrClusterDefinitionOverrideString))
        {
            throw new IllegalArgumentException("contentType is required when emrClusterDefinitionOverride is specified");
        }
        else if (StringUtils.isNotBlank(contentTypeString) && StringUtils.isNotBlank(emrClusterDefinitionOverrideString))
        {
            EmrClusterDefinition emrClusterDefinitionOverride =
                    getRequestObject(contentTypeString, emrClusterDefinitionOverrideString, EmrClusterDefinition.class);
            request.setEmrClusterDefinitionOverride(emrClusterDefinitionOverride);
        }

        // Create the cluster in a new transaction.
        EmrCluster emrCluster = emrService.createCluster(request);

        // Set workflow variables based on the result EMR cluster that was created.
        setResultWorkflowVariables(execution, emrCluster);
        LOGGER.info(activitiHelper.getProcessIdentifyingInformation(execution) + " EMR cluster started with cluster Id: " + emrCluster.getId());
    }
}


text:
extern "C"
{
#endif

ROSIDL_TYPESUPPORT_COREDX_C_PUBLIC
extern const char * rosidl_typesupport_coredx_c__identifier;

#ifdef __cplusplus
}
#endif

#endif  // ROSIDL_TYPESUPPORT_COREDX_C__IDENTIFIER_H_


text:
Compute the power spectrum of the magnetic field given the Schmidt seminormalized magnetic potential spherical harmonic coefficients.

# Usage

call SHMagPowerSpectrum (`c`, `a`, `r`, `lmax`, `spectrum`)

# Parameters

`c` : input, real\*8, dimension (2, `lmax`+1, `lmax`+1)
:   The Schmidt seminormalized spherical harmonic coefficients of the magnetic potential.

`a` : input, real\*8
:   The reference radius of the magnetic potential spherical harmonic coefficients.

`r` : input, real\*8
:   The radius to evaluate the magnetic field.

`lmax` : input, integer
:   The maximum spherical harmonic degree to calculate the power spectrum.

`spectrum` : output, real\*8, dimension (`lmax`+1)
:   The power spectrum of the magnetic field.

# Description

`SHMagPowerSpectrum` will calculate the power spectrum of the magnetic field at radius `r` given the magnetic potential Schmidt seminormalized spherical harmonic coefficients `c` evaluated at radius `a`. For a given degree `l`, this is explicitly calculated as:

`S(l) = (l+1) (a/r)**(2l+4) Sum_{m=0}^l [ c(1, l+1, m+1)**2 + c(2, l+1, m+1)**2 ].`

# See also

[shmagpowerl](shmagpowerl.html)


text:
<?php

class msetting extends CI_Model{
	function tampil(){
		return $this->db->get('admin');
	}

	function tampilAdmin($where){
		return $this->db->get_where('admin',$where);
	}

	function edit($id,$edit){
		$this->db->where('id',$id)->update('admin',$edit);
	}
}
?>


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta content="width=device=width, initial-scale=1, maximum-scale=1" name="viewport">
    <title>Calcular distancia</title>

Calcular distancia

    <form name="regmod" action="controlle.php" method="post">

        <input type="number" name="x1" placeholder="x1" required>

        <input type="number" name="x2" placeholder="x2" required>

        <input type="number" name="y1" placeholder="y1" required>

        <input type="number" name="y2" placeholder="y2" required>

        <input type="submit" value="Cadastrar">
        <input type="reset" value="Limpar">
      </form>


text:
package org.keycloak.testsuite.forms;

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

import javax.mail.internet.MimeMessage;

import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.TargetsContainer;
import org.jboss.arquillian.graphene.page.Page;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.keycloak.OAuth2Constants;
import org.keycloak.admin.client.resource.UserResource;
import org.keycloak.models.AuthenticationFlowModel;
import org.keycloak.models.RealmModel;
import org.keycloak.models.utils.DefaultAuthenticationFlows;
import org.keycloak.models.utils.TimeBasedOTP;
import org.keycloak.representations.idm.AuthenticationFlowRepresentation;
import org.keycloak.representations.idm.RealmRepresentation;
import org.keycloak.representations.idm.UserRepresentation;
import org.keycloak.testsuite.AbstractTestRealmKeycloakTest;
import org.keycloak.testsuite.admin.ApiUtil;
import org.keycloak.testsuite.admin.authentication.AbstractAuthenticationTest;
import org.keycloak.testsuite.model.ClientModelTest;
import org.keycloak.testsuite.pages.AccountTotpPage;
import org.keycloak.testsuite.pages.AppPage;
import org.keycloak.testsuite.pages.ErrorPage;
import org.keycloak.testsuite.pages.LoginConfigTotpPage;
import org.keycloak.testsuite.pages.LoginPage;
import org.keycloak.testsuite.pages.LoginPasswordResetPage;
import org.keycloak.testsuite.pages.LoginPasswordUpdatePage;
import org.keycloak.testsuite.pages.LoginTotpPage;
import org.keycloak.testsuite.pages.LoginUsernameOnlyPage;
import org.keycloak.testsuite.pages.PasswordPage;
import org.keycloak.testsuite.runonserver.RunOnServer;
import org.keycloak.testsuite.runonserver.RunOnServerDeployment;
import org.keycloak.testsuite.util.FlowUtil;
import org.keycloak.testsuite.util.GreenMailRule;
import org.keycloak.testsuite.util.MailUtils;
import org.keycloak.testsuite.util.URLUtils;
import org.keycloak.testsuite.util.UserBuilder;

import static org.junit.Assert.assertEquals;
import static org.keycloak.testsuite.arquillian.DeploymentTargetModifier.AUTH_SERVER_CURRENT;

/**
 * Test for the various alternatives of reset-credentials flow or browser flow (non-default setup of the  flows)
 *
 * @author Marek Posolda
 * @author Jan Lieskovsky
 */
public class ResetCredentialsAlternativeFlowsTest extends AbstractTestRealmKeycloakTest {

    @Deployment
    @TargetsContainer(AUTH_SERVER_CURRENT)
    public static WebArchive deploy() {
        return RunOnServerDeployment.create(UserResource.class, ClientModelTest.class)
                .addPackages(true,
                        "org.keycloak.testsuite",
                        "org.keycloak.testsuite.model");
    }

    private String userId;

    @Rule
    public GreenMailRule greenMail = new GreenMailRule();

    @Page
    protected LoginPage loginPage;

    @Page
    protected LoginUsernameOnlyPage loginUsernameOnlyPage;

    @Page
    protected PasswordPage passwordPage;

    @Page
    protected LoginPasswordResetPage resetPasswordPage;

    @Page
    protected LoginPasswordUpdatePage updatePasswordPage;

    @Page
    protected AccountTotpPage accountTotpPage;

    @Page
    protected LoginConfigTotpPage totpPage;

    @Page
    protected LoginTotpPage loginTotpPage;

    @Page
    protected ErrorPage errorPage;

    @Page
    protected AppPage appPage;

    protected TimeBasedOTP totp = new TimeBasedOTP();

    @Override
    public void configureTestRealm(RealmRepresentation testRealm) {
    }

    @Before
    public void setup() {
        log.info("Adding login-test user");
        UserRepresentation user = UserBuilder.create()
                .username("login-test")
                .email("login@test.com")
                .enabled(true)
                .build();

        userId = ApiUtil.createUserAndResetPasswordWithAdminClient(testRealm(), user, "password");
        getCleanup().addUserId(userId);
    }

    // Test with default reset-credentials flow and alternative browser flow with separate username and password screen.
    //
    // Click "Forget password" on browser flow passwordPAge and assert that button "Back" is not available as we switched to
    // different flow (reset-credentials" flow).
    @Test
    public void testBackButtonWhenSwitchToResetCredentialsFlowFromAlternativeBrowserFlow() {
        try {
            BrowserFlowTest.configureBrowserFlowWithAlternativeCredentials(testingClient);

            // Provide username and then click "Forget password"
            provideUsernameAndClickResetPassword("login-test");

            // Click "back to login" link. Should be on password page of the browser flow (under URL "authenticate")
            resetPasswordPage.backToLogin();
            passwordPage.assertCurrent();
            Assert.assertTrue(URLUtils.currentUrlMatches("/login-actions/authenticate"));
            passwordPage.assertBackButtonAvailability(true);

            // Click "back". Should be on usernameForm
            passwordPage.clickBackButton();
            loginUsernameOnlyPage.assertCurrent();
        } finally {
            revertFlows();
        }
    }

    // Test with default reset-credentials flow and alternative browser flow with separate username and password screen.
    //
    // Provide username and click "Forget password" on browser flow. Then provide non-existing username in reset-credentials 1st screen.
    // User should be cleared from authentication context and no email should be sent
    @Test
    public void testNotExistingUserProvidedInResetCredentialsFlow() {
        try {
            BrowserFlowTest.configureBrowserFlowWithAlternativeCredentials(testingClient);

            // Provide username and then click "Forget password"
            provideUsernameAndClickResetPassword("login-test");

            // Provide non-existent username after "login-test" user already set in the context by browser flow
            resetPasswordPage.changePassword("non-existent");

            loginUsernameOnlyPage.assertCurrent();
            assertEquals("You should receive an email shortly with further instructions.", loginUsernameOnlyPage.getSuccessMessage());

            // Assert no email was sent as user was cleared
            assertEquals(0, greenMail.getReceivedMessages().length);

        } finally {
            revertFlows();
        }
    }

    // Test with default reset-credentials flow and alternative browser flow with separate username and password screen.
    //
    // Provide username and click "Forget password" on browser flow. Then provide different username in reset-credentials 1st screen than provided earlier
    // on browser flow username screen. There should be an error and no email should be sent
    @Test
    public void testDifferentUserProvidedInResetCredentialsFlow() {
        try {
            BrowserFlowTest.configureBrowserFlowWithAlternativeCredentials(testingClient);

            // Provide username and then click "Forget password"
            provideUsernameAndClickResetPassword("login-test");

            // Provide existing username "test-user@localhost" for different user than "login-test", which was set earlier by browser flow
            resetPasswordPage.changePassword("test-user@localhost");

            // Should be on error page
            errorPage.assertCurrent();

            // Assert no email was sent
            assertEquals(0, greenMail.getReceivedMessages().length);
        } finally {
            revertFlows();
        }
    }

    // Test with default reset-credentials flow and alternative browser flow with separate username and password screen.
    //
    // Provide username and click "Forget password" on browser flow. Then provide same username in reset-credentials 1st screen than provided earlier
    // on browser flow username screen. There should be an email successfully sent.
    @Test
    public void testSameUserProvidedInResetCredentialsFlow() {
        try {
            BrowserFlowTest.configureBrowserFlowWithAlternativeCredentials(testingClient);

            // Provide username and then click "Forget password"
            provideUsernameAndClickResetPassword("login-test");

            // Provide same username "login-test" as earlier in browser flow
            resetPasswordPage.changePassword("login-test");

            loginUsernameOnlyPage.assertCurrent();
            assertEquals("You should receive an email shortly with further instructions.", loginUsernameOnlyPage.getSuccessMessage());

            // Assert email was sent
            assertEquals(1, greenMail.getReceivedMessages().length);
        } finally {
            revertFlows();
        }
    }

    // Test with alternative reset-credentials flow with removed ResetCredentialChooseUser authenticator and with alternative browser
    // flow with separate username and password screen.
    //
    // Provide username and click "Forget password" on browser flow. Then provide same username in reset-credentials 1st screen than provided earlier
    // on browser flow username screen. There should be an email successfully sent.
    @Test
    public void testResetCredentialsFlowWithUsernameProvidedFromBrowserFlow() throws Exception {
        try {
            BrowserFlowTest.configureBrowserFlowWithAlternativeCredentials(testingClient);
            final String newFlowAlias = "resetcred - alternative";
            // Configure reset-credentials flow without ResetCredentialsChooseUser authenticator
            configureResetCredentialsRemoveExecutionsAndBindTheFlow(
                    newFlowAlias,
                    Arrays.asList("reset-credentials-choose-user")
            );

            // provides username
            loginUsernameOnlyPage.open();
            loginUsernameOnlyPage.login("login-test");

            Assert.assertTrue(passwordPage.isCurrent());

            // Click "Forget password"
            passwordPage.clickResetPassword();

            // Should be directly back on the loginPage with the message about sent email
            loginUsernameOnlyPage.assertCurrent();
            assertEquals("You should receive an email shortly with further instructions.", loginUsernameOnlyPage.getSuccessMessage());

            // Assert email was sent
            assertEquals(1, greenMail.getReceivedMessages().length);

            // Successfully reset password
            MimeMessage message = greenMail.getReceivedMessages()[0];

            String changePasswordUrl = MailUtils.getPasswordResetEmailLink(message);

            driver.navigate().to(changePasswordUrl.trim());

            updatePasswordPage.assertCurrent();
            updatePasswordPage.changePassword("resetPassword", "resetPassword");

            // Assert user authenticated
            Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType());
            Assert.assertNotNull(oauth.getCurrentQuery().get(OAuth2Constants.CODE));
        } finally {
            revertFlows();
        }
    }

    private void provideUsernameAndClickResetPassword(String username) {
        // provides username
        loginUsernameOnlyPage.open();
        loginUsernameOnlyPage.login(username);

        Assert.assertTrue(passwordPage.isCurrent());

        // Click "Forget password"
        passwordPage.clickResetPassword();

        // Assert switched to the "reset-credentials" flow, but button "back" not available
        resetPasswordPage.assertCurrent();
        Assert.assertTrue(URLUtils.currentUrlMatches("/login-actions/reset-credentials"));
        resetPasswordPage.assertBackButtonAvailability(false);
    }

    private void revertFlows() {
        List<AuthenticationFlowRepresentation> flows = testRealm().flows().getFlows();

        // Set default flows
        RealmRepresentation realm = testRealm().toRepresentation();
        realm.setBrowserFlow(DefaultAuthenticationFlows.BROWSER_FLOW);
        realm.setResetCredentialsFlow(DefaultAuthenticationFlows.RESET_CREDENTIALS_FLOW);
        testRealm().update(realm);

        // Delete flows previously created within various tests
        final List<String> aliasesOfExistingFlows = Arrays.asList(
                "browser - alternative",
                "resetcred - alternative",
                "resetcred - KEYCLOAK-11753 - test"
        );

        for(String existingFlowAlias : aliasesOfExistingFlows) {
            AuthenticationFlowRepresentation flowRepresentation = AbstractAuthenticationTest.findFlowByAlias(existingFlowAlias, flows);
            if (flowRepresentation != null) {
                testRealm().flows().deleteFlow(flowRepresentation.getId());
            }
        }
    }

    // Create a copy of the default reset credentials flow with the specified flow alias if it doesn't exist yet
    // Remove execution(s), specified by (a list of) providerId(s) from the flow
    // Finally bind / define the flow as the reset credential one
    private void configureResetCredentialsRemoveExecutionsAndBindTheFlow(String newFlowAlias, List<String> providerIdsToRemove) {
        testingClient.server("test").run(session -> {
            // Create a copy of the default reset credentials flow with the specified flow alias if it doesn't exist yet
            if(session.getContext().getRealm().getFlowByAlias(newFlowAlias) == null) {
                FlowUtil.inCurrentRealm(session).copyResetCredentialsFlow(newFlowAlias);
            }
        });

        for(String providerId : providerIdsToRemove) {
            // For each execution to be removed its index within the flow based on providerId
            int executionIndex = realmsResouce().realm("test").flows().getExecutions(newFlowAlias)
                    .stream()
                    .filter(e -> e.getProviderId().equals(providerId))
                    .mapToInt(e -> e.getIndex())
                    .findFirst()
                    .getAsInt();

            // Remove the execution(s)
            testingClient.server("test").run(session -> FlowUtil.inCurrentRealm(session)
                    .selectFlow(newFlowAlias)
                    .removeExecution(executionIndex)
            );
        }

        // Bind the flow as the reset-credentials one
        testingClient.server("test").run(session -> FlowUtil.inCurrentRealm(session)
                .selectFlow(newFlowAlias)
                .defineAsResetCredentialsFlow()
        );
    }

    @Test
    public void resetCredentialsVerifyCustomOtpLabelSetProperly() {
        try {
            // Make a copy of the default Reset Credentials flow, but:
            // * Without 'Send Reset Email' authenticator,
            // * Without 'Reset Password' authenticator
            final String newFlowAlias = "resetcred - KEYCLOAK-11753 - test";
            configureResetCredentialsRemoveExecutionsAndBindTheFlow(
                    newFlowAlias,
                    Arrays.asList("reset-credential-email", "reset-password")
            );

            // Login & set up the initial OTP code for the user
            loginPage.open();
            loginPage.login("login@test.com", "password");
            accountTotpPage.open();
            Assert.assertTrue(accountTotpPage.isCurrent());
            String customOtpLabel = "my-original-otp-label";
            accountTotpPage.configure(totp.generateTOTP(accountTotpPage.getTotpSecret()), customOtpLabel);

            // Logout
            oauth.openLogout();

            // Go to login page & click "Forgot password" link to perform the custom 'Reset Credential' flow
            loginPage.open();
            loginPage.resetPassword();

            // Should be on reset password page now. Provide email of the user & click Submit button
            Assert.assertTrue(resetPasswordPage.isCurrent());
            resetPasswordPage.changePassword("login@test.com");

            // Since 'Send Reset Email' & 'Reset Password' authenticators got removed above,
            // the next action should be 'Reset OTP' -- verify that
            Assert.assertTrue(totpPage.isCurrent());

            // Provide updated form of the OTP label, to be used within 'Reset OTP' (next) step
            customOtpLabel = "my-reset-otp-label";

            // Reset OTP label to a custom value as part of Reset Credentials flow
            totpPage.configure(totp.generateTOTP(totpPage.getTotpSecret()), customOtpLabel);

            // Open OTP Authenticator account page
            accountTotpPage.open();
            Assert.assertTrue(accountTotpPage.isCurrent());

            // Verify OTP authenticator with requested label was created
            String pageSource = driver.getPageSource();
            Assert.assertTrue(pageSource.contains(customOtpLabel));

        // Undo setup changes performed within the test
        } finally {
            revertFlows();
        }
    }
}


text:
"""Defines utility methods for testing products"""
from __future__ import unicode_literals

import hashlib

import django.utils.timezone as timezone

from job.test import utils as job_utils
from product.models import FileAncestryLink
from storage.models import ScaleFile
from storage.test import utils as storage_utils

def create_file_link(ancestor=None, descendant=None, job=None, job_exe=None, recipe=None, batch=None):
    """Creates a file ancestry link model for unit testing

    :returns: The file ancestry link model
    :rtype: :class:`product.models.FileAncestryLink`
    """

    if not job:
        if descendant and descendant.job:
            job = descendant.job
        else:
            job = job_utils.create_job()
    if not job_exe:
        if descendant and descendant.job_exe:
            job_exe = descendant.job_exe
        else:
            job_exe = job_utils.create_job_exe(job_type=job.job_type, job=job)

    return FileAncestryLink.objects.create(ancestor=ancestor, descendant=descendant, job=job, job_exe=job_exe,
                                           recipe=recipe, batch=batch)

def create_product(job_exe=None, workspace=None, has_been_published=False, is_published=False, uuid=None,
                   file_name='my_test_file.txt', file_path='/file/path/my_test_file.txt', media_type='text/plain',
                   file_size=100, countries=None, is_superseded=False, superseded=None):
    """Creates a product file model for unit testing

    :returns: The product model
    :rtype: :class:`storage.models.ScaleFile`
    """

    if not job_exe:
        job_exe = job_utils.create_job_exe()
    if not workspace:
        workspace = storage_utils.create_workspace()

    if not uuid:
        builder = hashlib.md5()
        builder.update(str(job_exe.job.job_type.id))
        builder.update(file_name)
        uuid = builder.hexdigest()

    if is_superseded and not superseded:
        superseded = timezone.now()

    product_file = ScaleFile.objects.create(file_type='PRODUCT', job_exe=job_exe, job=job_exe.job,
                                            job_type=job_exe.job.job_type, has_been_published=has_been_published,
                                            is_published=is_published, uuid=uuid, file_name=file_name,
                                            media_type=media_type, file_size=file_size, file_path=file_path,
                                            workspace=workspace, is_superseded=is_superseded, superseded=superseded)
    if countries:
        product_file.countries = countries
        product_file.save()
    return product_file


text:
layout: empty/tags
regenerate: true
title: Tags
---