text:
package org.elasticsearch.gateway.local;

import org.apache.lucene.util.LuceneTestCase.Slow;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthStatus;
import org.elasticsearch.action.admin.indices.status.IndexShardStatus;
import org.elasticsearch.action.admin.indices.status.IndicesStatusResponse;
import org.elasticsearch.action.admin.indices.status.ShardStatus;
import org.elasticsearch.client.Client;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.routing.allocation.allocator.BalancedShardsAllocator;
import org.elasticsearch.cluster.routing.allocation.decider.DisableAllocationDecider;
import org.elasticsearch.common.Priority;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.FilterBuilders;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.test.AbstractIntegrationTest;
import org.elasticsearch.test.AbstractIntegrationTest.ClusterScope;
import org.elasticsearch.test.AbstractIntegrationTest.Scope;
import org.elasticsearch.test.TestCluster.RestartCallback;
import org.junit.Test;

import static org.elasticsearch.client.Requests.clusterHealthRequest;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.test.hamcrest.ElasticSearchAssertions.assertHitCount;
import static org.hamcrest.Matchers.*;

/**
 *
 */
@ClusterScope(numNodes=0, scope=Scope.TEST)
public class SimpleRecoveryLocalGatewayTests extends AbstractIntegrationTest {

    private ImmutableSettings.Builder settingsBuilder() {
        return ImmutableSettings.settingsBuilder().put("gateway.type", "local");
    }

    @Test
    @Slow
    public void testX() throws Exception {

        cluster().startNode(settingsBuilder().put("index.number_of_shards", 1).build());

        String mapping = XContentFactory.jsonBuilder().startObject().startObject("type1")
                .startObject("properties").startObject("appAccountIds").field("type", "string").endObject().endObject()
                .endObject().endObject().string();
        client().admin().indices().prepareCreate("test").addMapping("type1", mapping).execute().actionGet();

        client().prepareIndex("test", "type1", "10990239").setSource(jsonBuilder().startObject()
                .field("_id", "10990239")
                .startArray("appAccountIds").value(14).value(179).endArray().endObject()).execute().actionGet();
        client().prepareIndex("test", "type1", "10990473").setSource(jsonBuilder().startObject()
                .field("_id", "10990473")
                .startArray("appAccountIds").value(14).endArray().endObject()).execute().actionGet();
        client().prepareIndex("test", "type1", "10990513").setSource(jsonBuilder().startObject()
                .field("_id", "10990513")
                .startArray("appAccountIds").value(14).value(179).endArray().endObject()).execute().actionGet();
        client().prepareIndex("test", "type1", "10990695").setSource(jsonBuilder().startObject()
                .field("_id", "10990695")
                .startArray("appAccountIds").value(14).endArray().endObject()).execute().actionGet();
        client().prepareIndex("test", "type1", "11026351").setSource(jsonBuilder().startObject()
                .field("_id", "11026351")
                .startArray("appAccountIds").value(14).endArray().endObject()).execute().actionGet();

        client().admin().indices().prepareRefresh().execute().actionGet();
        assertHitCount(client().prepareCount().setQuery(termQuery("appAccountIds", 179)).execute().actionGet(), 2);
        cluster().fullRestart();

        logger.info("Running Cluster Health (wait for the shards to startup)");
        ClusterHealthResponse clusterHealth = client().admin().cluster().health(clusterHealthRequest().waitForYellowStatus().waitForActiveShards(1)).actionGet();
        logger.info("Done Cluster Health, status " + clusterHealth.getStatus());
        assertThat(clusterHealth.isTimedOut(), equalTo(false));
        assertThat(clusterHealth.getStatus(), equalTo(ClusterHealthStatus.YELLOW));

        client().admin().indices().prepareRefresh().execute().actionGet();
        assertHitCount(client().prepareCount().setQuery(termQuery("appAccountIds", 179)).execute().actionGet(), 2);

        cluster().fullRestart();

        logger.info("Running Cluster Health (wait for the shards to startup)");
        clusterHealth = client().admin().cluster().health(clusterHealthRequest().waitForYellowStatus().waitForActiveShards(1)).actionGet();
        logger.info("Done Cluster Health, status " + clusterHealth.getStatus());
        assertThat(clusterHealth.isTimedOut(), equalTo(false));
        assertThat(clusterHealth.getStatus(), equalTo(ClusterHealthStatus.YELLOW));

        client().admin().indices().prepareRefresh().execute().actionGet();
        assertHitCount(client().prepareCount().setQuery(termQuery("appAccountIds", 179)).execute().actionGet(), 2);
    }

    @Test
    @Slow
    public void testSingleNodeNoFlush() throws Exception {

        cluster().startNode(settingsBuilder().put("index.number_of_shards", 1).build());

        String mapping = XContentFactory.jsonBuilder().startObject().startObject("type1")
                .startObject("properties").startObject("field").field("type", "string").endObject().startObject("num").field("type", "integer").endObject().endObject()
                .endObject().endObject().string();
        client().admin().indices().prepareCreate("test").addMapping("type1", mapping).execute().actionGet();

        for (int i = 0; i < 100; i++) {
            client().prepareIndex("test", "type1", "1").setSource(jsonBuilder().startObject().field("_id", "1").field("field", "value1").startArray("num").value(14).value(179).endArray().endObject()).execute().actionGet();
            client().prepareIndex("test", "type1", "2").setSource(jsonBuilder().startObject().field("_id", "2").field("field", "value2").startArray("num").value(14).endArray().endObject()).execute().actionGet();
        }

        client().admin().indices().prepareRefresh().execute().actionGet();
        for (int i = 0; i < 10; i++) {
            assertHitCount(client().prepareCount().setQuery(matchAllQuery()).execute().actionGet(), 2);
            assertHitCount(client().prepareCount().setQuery(termQuery("field", "value1")).execute().actionGet(), 1);
            assertHitCount(client().prepareCount().setQuery(termQuery("field", "value2")).execute().actionGet(), 1);
            assertHitCount(client().prepareCount().setQuery(termQuery("num", 179)).execute().actionGet(), 1);
        }

        cluster().fullRestart();

        logger.info("Running Cluster Health (wait for the shards to startup)");
        ClusterHealthResponse clusterHealth = client().admin().cluster().health(clusterHealthRequest().waitForYellowStatus().waitForActiveShards(1)).actionGet();
        logger.info("Done Cluster Health, status " + clusterHealth.getStatus());
        assertThat(clusterHealth.isTimedOut(), equalTo(false));
        assertThat(clusterHealth.getStatus(), equalTo(ClusterHealthStatus.YELLOW));

        for (int i = 0; i < 10; i++) {
            assertHitCount(client().prepareCount().setQuery(matchAllQuery()).execute().actionGet(), 2);
            assertHitCount(client().prepareCount().setQuery(termQuery("field", "value1")).execute().actionGet(), 1);
            assertHitCount(client().prepareCount().setQuery(termQuery("field", "value2")).execute().actionGet(), 1);
            assertHitCount(client().prepareCount().setQuery(termQuery("num", 179)).execute().actionGet(), 1);
        }

        cluster().fullRestart();

        logger.info("Running Cluster Health (wait for the shards to startup)");
        clusterHealth = client().admin().cluster().health(clusterHealthRequest().waitForYellowStatus().waitForActiveShards(1)).actionGet();
        logger.info("Done Cluster Health, status " + clusterHealth.getStatus());
        assertThat(clusterHealth.isTimedOut(), equalTo(false));
        assertThat(clusterHealth.getStatus(), equalTo(ClusterHealthStatus.YELLOW));

        for (int i = 0; i < 10; i++) {
            assertHitCount(client().prepareCount().setQuery(matchAllQuery()).execute().actionGet(), 2);
            assertHitCount(client().prepareCount().setQuery(termQuery("field", "value1")).execute().actionGet(), 1);
            assertHitCount(client().prepareCount().setQuery(termQuery("field", "value2")).execute().actionGet(), 1);
            assertHitCount(client().prepareCount().setQuery(termQuery("num", 179)).execute().actionGet(), 1);
        }
    }

    @Test
    @Slow
    public void testSingleNodeWithFlush() throws Exception {

        cluster().startNode(settingsBuilder().put("index.number_of_shards", 1).build());
        client().prepareIndex("test", "type1", "1").setSource(jsonBuilder().startObject().field("field", "value1").endObject()).execute().actionGet();
        client().admin().indices().prepareFlush().execute().actionGet();
        client().prepareIndex("test", "type1", "2").setSource(jsonBuilder().startObject().field("field", "value2").endObject()).execute().actionGet();
        client().admin().indices().prepareRefresh().execute().actionGet();

        assertHitCount(client().prepareCount().setQuery(matchAllQuery()).execute().actionGet(), 2);

        cluster().fullRestart();

        logger.info("Running Cluster Health (wait for the shards to startup)");
        ClusterHealthResponse clusterHealth = client().admin().cluster().health(clusterHealthRequest().waitForYellowStatus().waitForActiveShards(1)).actionGet();
        logger.info("Done Cluster Health, status " + clusterHealth.getStatus());
        assertThat(clusterHealth.isTimedOut(), equalTo(false));
        assertThat(clusterHealth.getStatus(), equalTo(ClusterHealthStatus.YELLOW));

        for (int i = 0; i < 10; i++) {
            assertHitCount(client().prepareCount().setQuery(matchAllQuery()).execute().actionGet(), 2);
        }

        cluster().fullRestart();

        logger.info("Running Cluster Health (wait for the shards to startup)");
        clusterHealth = client().admin().cluster().health(clusterHealthRequest().waitForYellowStatus().waitForActiveShards(1)).actionGet();
        logger.info("Done Cluster Health, status " + clusterHealth.getStatus());
        assertThat(clusterHealth.isTimedOut(), equalTo(false));
        assertThat(clusterHealth.getStatus(), equalTo(ClusterHealthStatus.YELLOW));

        for (int i = 0; i < 10; i++) {
            assertHitCount(client().prepareCount().setQuery(matchAllQuery()).execute().actionGet(), 2);
        }
    }

    @Test
    @Slow
    public void testTwoNodeFirstNodeCleared() throws Exception {

        final String firstNode = cluster().startNode(settingsBuilder().put("index.number_of_shards", 1).build());
        cluster().startNode(settingsBuilder().put("index.number_of_shards", 1).build());

        client().prepareIndex("test", "type1", "1").setSource(jsonBuilder().startObject().field("field", "value1").endObject()).execute().actionGet();
        client().admin().indices().prepareFlush().execute().actionGet();
        client().prepareIndex("test", "type1", "2").setSource(jsonBuilder().startObject().field("field", "value2").endObject()).execute().actionGet();
        client().admin().indices().prepareRefresh().execute().actionGet();

        logger.info("Running Cluster Health (wait for the shards to startup)");
        ClusterHealthResponse clusterHealth = client().admin().cluster().health(clusterHealthRequest().waitForGreenStatus().waitForActiveShards(2)).actionGet();
        logger.info("Done Cluster Health, status " + clusterHealth.getStatus());
        assertThat(clusterHealth.isTimedOut(), equalTo(false));
        assertThat(clusterHealth.getStatus(), equalTo(ClusterHealthStatus.GREEN));

        for (int i = 0; i < 10; i++) {
            assertHitCount(client().prepareCount().setQuery(matchAllQuery()).execute().actionGet(), 2);
        }

        cluster().fullRestart(new RestartCallback() {
            @Override
            public Settings onNodeStopped(String nodeName) throws Exception {
                return settingsBuilder().put("gateway.recover_after_nodes", 2).build();
            }

            @Override
            public boolean clearData(String nodeName) {
                return firstNode.equals(nodeName);
            }

        });

        logger.info("Running Cluster Health (wait for the shards to startup)");
        clusterHealth = client().admin().cluster().health(clusterHealthRequest().waitForGreenStatus().waitForActiveShards(2)).actionGet();
        logger.info("Done Cluster Health, status " + clusterHealth.getStatus());
        assertThat(clusterHealth.isTimedOut(), equalTo(false));
        assertThat(clusterHealth.getStatus(), equalTo(ClusterHealthStatus.GREEN));

        for (int i = 0; i < 10; i++) {
            assertHitCount(client().prepareCount().setQuery(matchAllQuery()).execute().actionGet(), 2);
        }
    }

    @Test
    @Slow
    public void testLatestVersionLoaded() throws Exception {
        // clean two nodes

        cluster().startNode(settingsBuilder().put("index.number_of_shards", 1).put("gateway.recover_after_nodes", 2).build());
        cluster().startNode(settingsBuilder().put("index.number_of_shards", 1).put("gateway.recover_after_nodes", 2).build());

        client().prepareIndex("test", "type1", "1").setSource(jsonBuilder().startObject().field("field", "value1").endObject()).execute().actionGet();
        client().admin().indices().prepareFlush().execute().actionGet();
        client().prepareIndex("test", "type1", "2").setSource(jsonBuilder().startObject().field("field", "value2").endObject()).execute().actionGet();
        client().admin().indices().prepareRefresh().execute().actionGet();

        logger.info("--> running cluster_health (wait for the shards to startup)");
        ClusterHealthResponse clusterHealth = client().admin().cluster().health(clusterHealthRequest().waitForGreenStatus().waitForActiveShards(2)).actionGet();
        logger.info("--> done cluster_health, status " + clusterHealth.getStatus());
        assertThat(clusterHealth.isTimedOut(), equalTo(false));
        assertThat(clusterHealth.getStatus(), equalTo(ClusterHealthStatus.GREEN));

        for (int i = 0; i < 10; i++) {
            assertHitCount(client().prepareCount().setQuery(matchAllQuery()).execute().actionGet(), 2);
        }

        logger.info("--> closing first node, and indexing more data to the second node");
        cluster().fullRestart(new RestartCallback() {

            @Override
            public void doAfterNodes(int numNodes, Client client) throws Exception {
                if (numNodes == 1) {
                    logger.info("--> one node is closed - start indexing data into the second one");
                    client.prepareIndex("test", "type1", "3").setSource(jsonBuilder().startObject().field("field", "value3").endObject()).execute().actionGet();
                    client.admin().indices().prepareRefresh().execute().actionGet();

                    for (int i = 0; i < 10; i++) {
                        assertHitCount(client.prepareCount().setQuery(matchAllQuery()).execute().actionGet(), 3);
                    }

                    logger.info("--> add some metadata, additional type and template");
                    client.admin().indices().preparePutMapping("test").setType("type2")
                            .setSource(jsonBuilder().startObject().startObject("type1").startObject("_source").field("enabled", false).endObject().endObject().endObject())
                            .execute().actionGet();
                    client.admin().indices().preparePutTemplate("template_1")
                            .setTemplate("te*")
                            .setOrder(0)
                            .addMapping("type1", XContentFactory.jsonBuilder().startObject().startObject("type1").startObject("properties")
                                    .startObject("field1").field("type", "string").field("store", "yes").endObject()
                                    .startObject("field2").field("type", "string").field("store", "yes").field("index", "not_analyzed").endObject()
                                    .endObject().endObject().endObject())
                            .execute().actionGet();
                    client.admin().indices().prepareAliases().addAlias("test", "test_alias", FilterBuilders.termFilter("field", "value")).execute().actionGet();
                    logger.info("--> starting two nodes back, verifying we got the latest version");
                }

            }

        });

        logger.info("--> running cluster_health (wait for the shards to startup)");
        clusterHealth = client().admin().cluster().health(clusterHealthRequest().waitForGreenStatus().waitForActiveShards(2)).actionGet();
        logger.info("--> done cluster_health, status " + clusterHealth.getStatus());
        assertThat(clusterHealth.isTimedOut(), equalTo(false));
        assertThat(clusterHealth.getStatus(), equalTo(ClusterHealthStatus.GREEN));

        for (int i = 0; i < 10; i++) {
            assertHitCount(client().prepareCount().setQuery(matchAllQuery()).execute().actionGet(), 3);
        }

        ClusterState state = client().admin().cluster().prepareState().execute().actionGet().getState();
        assertThat(state.metaData().index("test").mapping("type2"), notNullValue());
        assertThat(state.metaData().templates().get("template_1").template(), equalTo("te*"));
        assertThat(state.metaData().index("test").aliases().get("test_alias"), notNullValue());
        assertThat(state.metaData().index("test").aliases().get("test_alias").filter(), notNullValue());
    }

    @Test
    @Slow
    public void testReusePeerRecovery() throws Exception {

        ImmutableSettings.Builder settings = settingsBuilder()
                .put("action.admin.cluster.node.shutdown.delay", "10ms")
                .put("gateway.recover_after_nodes", 4)

                .put(BalancedShardsAllocator.SETTING_THRESHOLD, 1.1f); // use less agressive settings

        cluster().startNode(settings);
        cluster().startNode(settings);
        cluster().startNode(settings);
        cluster().startNode(settings);

        logger.info("--> indexing docs");
        for (int i = 0; i < 1000; i++) {
            client().prepareIndex("test", "type").setSource("field", "value").execute().actionGet();
            if ((i % 200) == 0) {
                client().admin().indices().prepareFlush().execute().actionGet();
            }
        }
        logger.info("Running Cluster Health");
        ClusterHealthResponse clusterHealth = client().admin().cluster().health(clusterHealthRequest().waitForGreenStatus().waitForRelocatingShards(0)).actionGet();
        logger.info("Done Cluster Health, status " + clusterHealth.getStatus());
        assertThat(clusterHealth.isTimedOut(), equalTo(false));
        assertThat(clusterHealth.getStatus(), equalTo(ClusterHealthStatus.GREEN));

        logger.info("--> shutting down the nodes");
        // Disable allocations while we are closing nodes
        client().admin().cluster().prepareUpdateSettings().setTransientSettings(settingsBuilder().put(DisableAllocationDecider.CLUSTER_ROUTING_ALLOCATION_DISABLE_ALLOCATION, true)).execute().actionGet();
        cluster().fullRestart();

        logger.info("Running Cluster Health");
        clusterHealth = client().admin().cluster().health(clusterHealthRequest().waitForGreenStatus().waitForActiveShards(10)).actionGet();
        logger.info("Done Cluster Health, status " + clusterHealth.getStatus());
        assertThat(clusterHealth.isTimedOut(), equalTo(false));
        assertThat(clusterHealth.getStatus(), equalTo(ClusterHealthStatus.GREEN));

        logger.info("--> shutting down the nodes");
        // Disable allocations while we are closing nodes
        client().admin().cluster().prepareUpdateSettings().setTransientSettings(settingsBuilder().put(DisableAllocationDecider.CLUSTER_ROUTING_ALLOCATION_DISABLE_ALLOCATION, true)).execute().actionGet();
        cluster().fullRestart();

        logger.info("Running Cluster Health");
        clusterHealth = client().admin().cluster().health(clusterHealthRequest().waitForGreenStatus().waitForActiveShards(10)).actionGet();
        logger.info("Done Cluster Health, status " + clusterHealth.getStatus());
        assertThat(clusterHealth.isTimedOut(), equalTo(false));
        assertThat(clusterHealth.getStatus(), equalTo(ClusterHealthStatus.GREEN));

        IndicesStatusResponse statusResponse = client().admin().indices().prepareStatus("test").setRecovery(true).execute().actionGet();
        for (IndexShardStatus indexShardStatus : statusResponse.getIndex("test")) {
            for (ShardStatus shardStatus : indexShardStatus) {
                if (!shardStatus.getShardRouting().primary()) {
                    logger.info("--> shard {}, recovered {}, reuse {}", shardStatus.getShardId(), shardStatus.getPeerRecoveryStatus().getRecoveredIndexSize(), shardStatus.getPeerRecoveryStatus().getReusedIndexSize());
                    assertThat(shardStatus.getPeerRecoveryStatus().getRecoveredIndexSize().bytes(), greaterThan(0l));
                    assertThat(shardStatus.getPeerRecoveryStatus().getReusedIndexSize().bytes(), greaterThan(0l));
                    assertThat(shardStatus.getPeerRecoveryStatus().getReusedIndexSize().bytes(), greaterThan(shardStatus.getPeerRecoveryStatus().getRecoveredIndexSize().bytes()));
                }
            }
        }
    }

    @Test
    @Slow
    public void testRecoveryDifferentNodeOrderStartup() throws Exception {
        // we need different data paths so we make sure we start the second node fresh

        final String node_1 = cluster().startNode(settingsBuilder().put("path.data", "data/data1").build());

        client().prepareIndex("test", "type1", "1").setSource("field", "value").execute().actionGet();

        cluster().startNode(settingsBuilder().put("path.data", "data/data2").build());

        ClusterHealthResponse health = client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setWaitForGreenStatus().execute().actionGet();
        assertThat(health.isTimedOut(), equalTo(false));

        cluster().fullRestart(new RestartCallback() {

            @Override
            public boolean doRestart(String nodeName) {
                return !node_1.equals(nodeName);
            }
        });

        health = client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setWaitForYellowStatus().execute().actionGet();
        assertThat(health.isTimedOut(), equalTo(false));

        assertThat(client().admin().indices().prepareExists("test").execute().actionGet().isExists(), equalTo(true));
        assertHitCount(client().prepareCount("test").setQuery(QueryBuilders.matchAllQuery()).execute().actionGet(), 1);
    }

}


text:
package org.apache.lucene.analysis.ar;

import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.BaseTokenStreamTestCase;
import org.apache.lucene.analysis.Tokenizer;
import org.apache.lucene.analysis.core.KeywordTokenizer;
import org.apache.lucene.analysis.miscellaneous.KeywordMarkerFilter;
import org.apache.lucene.analysis.util.CharArraySet;

/**
 * Test the Arabic Normalization Filter
 *
 */
public class TestArabicStemFilter extends BaseTokenStreamTestCase {

  public void testAlPrefix() throws IOException {
    check("الحسن", "حسن");
  }

  public void testWalPrefix() throws IOException {
    check("والحسن", "حسن");
  }

  public void testBalPrefix() throws IOException {
    check("بالحسن", "حسن");
  }

  public void testKalPrefix() throws IOException {
    check("كالحسن", "حسن");
  }

  public void testFalPrefix() throws IOException {
    check("فالحسن", "حسن");
  }

  public void testLlPrefix() throws IOException {
    check("للاخر", "اخر");
  }

  public void testWaPrefix() throws IOException {
    check("وحسن", "حسن");
  }

  public void testAhSuffix() throws IOException {
    check("زوجها", "زوج");
  }

  public void testAnSuffix() throws IOException {
    check("ساهدان", "ساهد");
  }

  public void testAtSuffix() throws IOException {
    check("ساهدات", "ساهد");
  }

  public void testWnSuffix() throws IOException {
    check("ساهدون", "ساهد");
  }

  public void testYnSuffix() throws IOException {
    check("ساهدين", "ساهد");
  }

  public void testYhSuffix() throws IOException {
    check("ساهديه", "ساهد");
  }

  public void testYpSuffix() throws IOException {
    check("ساهدية", "ساهد");
  }

  public void testHSuffix() throws IOException {
    check("ساهده", "ساهد");
  }

  public void testPSuffix() throws IOException {
    check("ساهدة", "ساهد");
  }

  public void testYSuffix() throws IOException {
    check("ساهدي", "ساهد");
  }

  public void testComboPrefSuf() throws IOException {
    check("وساهدون", "ساهد");
  }

  public void testComboSuf() throws IOException {
    check("ساهدهات", "ساهد");
  }

  public void testShouldntStem() throws IOException {
    check("الو", "الو");
  }

  public void testNonArabic() throws IOException {
    check("English", "English");
  }

  public void testWithKeywordAttribute() throws IOException {
    CharArraySet set = new CharArraySet(TEST_VERSION_CURRENT, 1, true);
    set.add("ساهدهات");
    ArabicLetterTokenizer tokenStream  = new ArabicLetterTokenizer(TEST_VERSION_CURRENT, new StringReader("ساهدهات"));

    ArabicStemFilter filter = new ArabicStemFilter(new KeywordMarkerFilter(tokenStream, set));
    assertTokenStreamContents(filter, new String[]{"ساهدهات"});
  }

  private void check(final String input, final String expected) throws IOException {
    ArabicLetterTokenizer tokenStream  = new ArabicLetterTokenizer(TEST_VERSION_CURRENT, new StringReader(input));
    ArabicStemFilter filter = new ArabicStemFilter(tokenStream);
    assertTokenStreamContents(filter, new String[]{expected});
  }

  public void testEmptyTerm() throws IOException {
    Analyzer a = new Analyzer() {
      @Override
      protected TokenStreamComponents createComponents(String fieldName, Reader reader) {
        Tokenizer tokenizer = new KeywordTokenizer(reader);
        return new TokenStreamComponents(tokenizer, new ArabicStemFilter(tokenizer));
      }
    };
    checkOneTermReuse(a, "", "");
  }
}

redpajama_set_name: RedPajamaGithub


text:
import Ember from 'ember';
import loginUser from './login-user';
import logoutUser from './logout-user';
import Application from '../../app';
import config from '../../config/environment';

const alreadyShownFactory = () => {
  let alreadyShown = [];
  return (msg, test, opt) => {
    if (test)
      return false;

    if( alreadyShown.indexOf(msg) === -1 ) {
      let warning = 'DEPRECATION: ' + msg;
      if(opt && opt.url) {
        warning += ' See: ' + opt.url;
      }
      console.warn(warning);
      alreadyShown.push(msg);
    }
  };
};
Ember.deprecate = alreadyShownFactory();
Ember.warn = alreadyShownFactory();

//see https://guides.emberjs.com/v2.3.0/configuring-ember/handling-deprecations/
Ember.Debug.registerDeprecationHandler((() => {
  let alreadyShown = [];
  return (message, options, next) => {
    // if(alreadyShown.indexOf(message) === -1) {
    if(false) {
      next(message, options);
      alreadyShown.push(message);
    }
  };
})());

export default function startApp(attrs) {
  let application;

  let attributes = Ember.merge({}, config.APP);
  attributes = Ember.merge(attributes, attrs); // use defaults, but you can override;

  Ember.run(() => {
    application = Application.create(attributes);
    application.setupForTesting();
    application.injectTestHelpers();
  });

  return application;
}


text:
#ifndef QSSL_H
#define QSSL_H

#include <QtCore/qglobal.h>
#include <QtCore/QFlags>

QT_BEGIN_NAMESPACE

namespace QSsl {
    enum KeyType {
        PrivateKey,
        PublicKey
    };

    enum EncodingFormat {
        Pem,
        Der
    };

    enum KeyAlgorithm {
        Opaque,
        Rsa,
        Dsa,
        Ec
    };

    enum AlternativeNameEntryType {
        EmailEntry,
        DnsEntry
    };

#if QT_DEPRECATED_SINCE(5,0)
    typedef AlternativeNameEntryType AlternateNameEntryType;
#endif

    enum SslProtocol {
        SslV3,
        SslV2,
        TlsV1_0,
#if QT_DEPRECATED_SINCE(5,0)
        TlsV1 = TlsV1_0,
#endif
        TlsV1_1,
        TlsV1_2,
        AnyProtocol,
        TlsV1SslV3,
        SecureProtocols,

        TlsV1_0OrLater,
        TlsV1_1OrLater,
        TlsV1_2OrLater,

        UnknownProtocol = -1
    };

    enum SslOption {
        SslOptionDisableEmptyFragments = 0x01,
        SslOptionDisableSessionTickets = 0x02,
        SslOptionDisableCompression = 0x04,
        SslOptionDisableServerNameIndication = 0x08,
        SslOptionDisableLegacyRenegotiation = 0x10,
        SslOptionDisableSessionSharing = 0x20,
        SslOptionDisableSessionPersistence = 0x40
    };
    Q_DECLARE_FLAGS(SslOptions, SslOption)
}

Q_DECLARE_OPERATORS_FOR_FLAGS(QSsl::SslOptions)

QT_END_NAMESPACE

#endif // QSSL_H


text:
layout: post
author: csiu
date: 2017-05-15
title: "Day80: Drawing maps in Python"
categories: update
tags:
  - 100daysofcode
excerpt: Mapping Vancouver, BC
---

In urban data, there is often location information -- which makes me think of maps. And so, for today's project, I use Python to learn how to draw maps.

The Jupyter Notebook for this little project is found [here](https://nbviewer.jupyter.org/github/csiu/100daysofcode/blob/master/misc/day80.ipynb).

### Python's Basemap module

Using the [Basemap](https://matplotlib.org/basemap/api/basemap_api.html) module, we are able to do stuff like draw the earth.

```python
from mpl_toolkits.basemap import Basemap as Basemap

Map = Basemap()

Map.drawcoastlines()
Map.drawcountries()
Map.drawmapboundary()
Map.fillcontinents(color = 'coral')
```

### Orthographic projection

We can also draw the earth as a sphere in an orthographic projection. The following example (centred on Vancouver, BC) is from [Cameron Cooke's "The Big Picture"](http://cgcooke.github.io/The-Big-Picture/).

```python
Map = Basemap(projection='ortho', lat_0=49, lon_0=-123, resolution='l')

# draw coastlines, country boundaries, fill continents.
Map.drawcoastlines(linewidth=0.25)
Map.drawcountries(linewidth=0.25)
Map.fillcontinents()

# draw the edge of the map projection region (the projection limb)
Map.drawmapboundary()

# draw lat/lon grid lines every 30 degrees.
Map.drawmeridians(np.arange(0,360,30))
Map.drawparallels(np.arange(-90,90,30))
```

### Mercator projection

Finally, we show the traditional 2D mercator projection of Vancouver, BC. The longitude and latitude coordinates are as follows:

```python
# Coordinates for Vancouver, BC
Van_lon = -123.1207
Van_lat = 49.2827
```

This figure is based on code found in [Bill Mill's "Simple maps in Python"](https://github.com/BillMills/python-mapping).

```python
Map = Basemap(
    projection='merc', resolution='h', area_thresh=0.1,
    lat_0=Van_lat, lon_0=Van_lon,
    llcrnrlat=Van_lat-1.5, llcrnrlon=Van_lon-1.25,
    urcrnrlat=Van_lat+1.5, urcrnrlon=Van_lon+2
)

# draw coastlines, country boundaries, fill continents.
Map.drawcoastlines(linewidth=0.25)
Map.drawcountries(linewidth=0.25)
Map.fillcontinents()

# draw the edge of the map projection region (the projection limb)
Map.drawmapboundary()

# draw rivers
Map.drawrivers(color='b', linewidth=1)

# draw lat/lon grid lines
Map.drawmeridians([int(Van_lon+i) for i in range(-1,3,)], labels=[1,0,0,1])
Map.drawparallels([int(Van_lat+i) for i in range(-1,3,)], labels=[1,0,0,1])

# label Vancouver
x,y = Map(Van_lon, Van_lat)
Map.plot(x, y, 'r*', markersize=24)
plt.annotate('Vancouver', xy=(x,y), xytext=(10,10), textcoords='offset points', fontsize=16)
```


text:
RSpec.describe StackMaster::Command do
  let(:command_class) {
    Class.new do
      include StackMaster::Command

      def initialize(callable = nil, halt = nil)
        @callable = callable
        @halt = halt
      end

      attr_reader :finished

      def perform
        instance_eval(&@callable) if @callable
        halt! if @halt
        @finished = true
        false
      end
    end
  }

  context 'when failed is not called' do
    it 'is successful' do
      expect(command_class.perform.success?).to eq true
    end
  end

  context 'when failed is called' do
    it 'is not successful' do
      expect(command_class.perform(proc { failed }).success?).to eq false
    end
  end

  describe '#halt!' do
    it 'exits the command' do
      expect(command_class.perform(nil, true).finished).to_not eq true
    end
  end

  context 'when a CF error occurs' do
    it 'outputs the message' do
      error_proc = proc {
        raise Aws::CloudFormation::Errors::ServiceError.new('a', 'the message')
      }
      expect { command_class.perform(error_proc) }.to output(/the message/).to_stderr
    end
  end

  context 'when a template compilation error occurs' do
    subject(:command) { command_class.new(error_proc) }

    let(:error_proc) do
      proc do
        raise StackMaster::TemplateCompiler::TemplateCompilationFailed, 'the message'
      end
    end

    it 'outputs the message' do
      expect { command.perform }.to output(/the message/).to_stderr
    end

    context 'when the error has a cause' do
      let(:error_proc) do
        proc do
          begin
            raise RuntimeError, 'the cause message'
          rescue
            raise StackMaster::TemplateCompiler::TemplateCompilationFailed, 'the message'
          end
        end
      end

      it 'outputs the cause message' do
        expect { command.perform }.to output(/Caused by: RuntimeError the cause message/).to_stderr
      end
    end

    context 'when --trace is set' do
      before { command.instance_variable_set(:@options, spy(trace: true)) }

      it 'outputs the backtrace' do
        expect { command.perform }.to output(%r{spec/stack_master/command_spec.rb:[\d]*:in }).to_stderr
      end
    end

    context 'when --trace is not set' do
      before { command.instance_variable_set(:@options, spy(trace: nil)) }

      it 'does not output the backtrace' do
        expect { command.perform }.not_to output(%r{spec/stack_master/command_spec.rb:[\d]*:in }).to_stderr
      end

      it 'informs to set --trace option to see the backtrace' do
        expect { command.perform }.to output(/Use --trace to view backtrace/).to_stderr
      end
    end
  end
end


text:
package com.chatalytics.compute.web.realtime;

import com.chatalytics.compute.web.resources.StatusResource;
import com.chatalytics.core.config.ChatAlyticsConfig;
import com.sun.jersey.api.core.PackagesResourceConfig;
import com.sun.jersey.spi.container.servlet.ServletContainer;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.websocket.jsr356.server.deploy.WebSocketServerContainerInitializer;

import javax.servlet.ServletException;
import javax.websocket.DeploymentException;
import javax.websocket.server.ServerContainer;

/**
 * Factory for building the realtime compute server
 *
 * @author giannis
 */
public class ComputeRealtimeServerFactory {

    /**
     * Creates a new {@link ComputeRealtimeServer}
     *
     * @param config
     *            The chatalytics config
     * @return A newly created {@link ComputeRealtimeServer}
     */
    public static ComputeRealtimeServer createComputeRealtimeServer(ChatAlyticsConfig config) {
        Server server = new Server(config.computeConfig.rtComputePort);
        ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
        context.setContextPath("/");

        ServletHolder jerseyServlet = context.addServlet(ServletContainer.class, "/*");
        jerseyServlet.setInitParameter(PackagesResourceConfig.PROPERTY_PACKAGES,
                                       StatusResource.class.getPackage().toString());
        server.setHandler(context);
        ServerContainer wscontainer;
        try {
            wscontainer = WebSocketServerContainerInitializer.configureContext(context);
            wscontainer.addEndpoint(RealtimeResource.class);
        } catch (ServletException | DeploymentException e) {
            throw new RuntimeException("Can't instantiate websocket. Reason: " + e.getMessage());
        }

        return new ComputeRealtimeServer(server);
    }

}


text:
package lambdacalc;

public interface DeBruijnRenamer {

	/**
	 * Renames a free term in a lambda expression.
	 *
	 * <pre>
	 * subst "y" "x" (y); // (x)
	 * </pre>
	 */
	DeBruijn rename(String from, String to, DeBruijn subject);

}


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

<title>TextInputCallback (Java Platform SE 8 )</title>
<meta name="date" content="2014-12-17">
<meta name="keywords" content="javax.security.auth.callback.TextInputCallback class">
<meta name="keywords" content="getPrompt()">
<meta name="keywords" content="getDefaultText()">
<meta name="keywords" content="setText()">
<meta name="keywords" content="getText()">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Java™ Platform
Standard Ed. 8

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

compact1, compact2, compact3

javax.security.auth.callback

Class TextInputCallback

java.lang.Object

javax.security.auth.callback.TextInputCallback

All Implemented Interfaces:

Serializable, Callback

Direct Known Subclasses:

RealmCallback

public class TextInputCallback
extends Object
implements Callback, Serializable

 Underlying security services instantiate and pass a
 TextInputCallback to the handle
 method of a CallbackHandler to retrieve generic text
 information.

See Also:

CallbackHandler,
Serialized Form

Constructor Summary

Constructors

Constructor and Description

TextInputCallback(String prompt)

Construct a TextInputCallback with a prompt.

TextInputCallback(String prompt,
                 String defaultText)

Construct a TextInputCallback with a prompt
 and default input value.

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

String
getDefaultText()

Get the default text.

String
getPrompt()

Get the prompt.

String
getText()

Get the retrieved text.

void
setText(String text)

Set the retrieved text.

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

TextInputCallback

public TextInputCallback(String prompt)

Construct a TextInputCallback with a prompt.

Parameters:

prompt - the prompt used to request the information.

Throws:

IllegalArgumentException - if prompt is null
                  or if prompt has a length of 0.

TextInputCallback

public TextInputCallback(String prompt,
                         String defaultText)

Construct a TextInputCallback with a prompt
 and default input value.

Parameters:

prompt - the prompt used to request the information.

defaultText - the text to be used as the default text displayed
                  with the prompt.

Throws:

IllegalArgumentException - if prompt is null,
                  if prompt has a length of 0,
                  if defaultText is null
                  or if defaultText has a length of 0.

Method Detail

getPrompt

public String getPrompt()

Get the prompt.

Returns:

the prompt.

getDefaultText

public String getDefaultText()

Get the default text.

Returns:

the default text, or null if this TextInputCallback
          was not instantiated with defaultText.

setText

public void setText(String text)

Set the retrieved text.

Parameters:

text - the retrieved text, which may be null.

See Also:

getText()

getText

public String getText()

Get the retrieved text.

Returns:

the retrieved text, which may be null.

See Also:

setText(java.lang.String)

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Java™ Platform
Standard Ed. 8

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

 Submit a bug or feature
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
 Copyright © 1993, 2015, Oracle and/or its affiliates.  All rights reserved.


text:
var connection = require('../db/dbconnect');
var Repository = require('./generalRepository');
var Section = require('./../schemas/sectionSchema');
function SectionRepository(){
    Repository.prototype.constructor.call(this);
    this.model = Section;
}

SectionRepository.prototype = new Repository();

module.exports = new SectionRepository();


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorPrimary"
    tools:context="com.icodechef.android.tick.MainActivity">

    <include layout="@layout/toolbar"/>
    <include layout="@layout/content_main"/>

</android.support.design.widget.CoordinatorLayout>


text:
module Fog
  module DNS
    class AzureRM
      # Real class for DNS Request
      class Real
        def delete_record_set(resource_group, name, zone_name, record_type)
          msg = "Deleting Record Set #{name} from Resource Group #{resource_group}."
          Fog::Logger.debug msg
          begin
            @dns_client.record_sets.delete(resource_group, zone_name, name, record_type)
          rescue MsRestAzure::AzureOperationError => e
            raise_azure_exception(e, msg)
          end
          Fog::Logger.debug "Record Set #{name} Deleted Successfully."
          true
        end
      end

      # Mock class for DNS Request
      class Mock
        def delete_record_set(*)
          Fog::Logger.debug 'Record Set name deleted successfully.'
          true
        end
      end
    end
  end
end


text:
<?xml version="1.0"?>
<!--

-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Catalog:etc/catalog_attributes.xsd">
    <group name="group_one">
        <attribute name="test_attribute"/>
    </group>
    <group name="group_two">
        <attribute name="attribute_one"/>
        <attribute name="attribute_two"/>
    </group>
</config>


text:
require 'yaml'
require 'open-uri'
require 'fileutils'
require 'digest'

module TravisJava
  module IBMJava
    def install_ibmjava(version)
      attribute_key = "ibmjava" + version.to_s
      java_home = ::File.join(node['travis_java']['jvm_base_dir'], node['travis_java'][attribute_key]['jvm_name'])
      pinned_release = node['travis_java'][attribute_key]['pinned_release']
      arch = node['travis_java']['arch']
      arch = "x86_64" if arch == "amd64"
      index_yml = ::File.join("https://public.dhe.ibm.com/ibmdl/export/pub/systems/cloud/runtimes/java/meta/sdk",
                              node['travis_java']['ibmjava']['platform'], arch, "index.yml")

      # Obtain the uri of the latest IBM Java build for the specified version from index.yml
      if pinned_release
        entry = find_version_entry(index_yml, pinned_release)
      else
        entry = find_version_entry(index_yml, version)
      end

      # Download and install the IBM Java build
      install_build(entry, java_home, version)

      # Delete IBM Java installable and installer properties file
      delete_files(version)

      link_cacerts(java_home, version)
    end

    # This method downloads and installs the java build
    # @param [Hash] entry - latest entry from the index.yml for the specified ibm java version containing uri
    # @param [String] java_home - directory path where IBM Java will be installed
    # @param [String] version - java version
    # @return - None

    def install_build(entry, java_home, version)
      installer = File.join(Dir.tmpdir, "ibmjava" + version.to_s + "-installer")
      properties = File.join(Dir.tmpdir, "installer.properties")
      expected_checksum = entry['sha256sum']

      # Download the IBM Java installer from source url to the local machine
      remote_file installer do
        src_url = entry['uri']
        source src_url.to_s
        mode '0755'
        checksum entry['sha256sum']
        action :create
        notifies :run, "ruby_block[Verify Checksum of #{installer} file]", :immediately
      end

      # Verify Checksum of the downloaded IBM Java build
      ruby_block "Verify Checksum of #{installer} file" do
        block do
          checksum = Digest::SHA256.hexdigest(File.read(installer))
          if checksum != expected_checksum
            raise "Checksum of the downloaded IBM Java build #{checksum} does not match the expected checksum #{expected_checksum}"
          end
        end
        action :nothing
      end

      # Create installer properties for silent installation
      file "Create installer properties file for IBM Java#{version}" do
        path properties
        content "INSTALLER_UI=silent\nUSER_INSTALL_DIR=#{java_home}\nLICENSE_ACCEPTED=TRUE\n"
        action :create
      end

      # Install IBM Java build
      execute "Install IBM Java#{version} build" do
        command "#{installer} -i silent -f #{properties}"
        action :run
      end
    end

    def link_cacerts(java_home, version)
      link "#{java_home}/jre/lib/security/cacerts" do
        to '/etc/ssl/certs/java/cacerts'
        not_if { version > 8 }
      end

      link "#{java_home}/lib/security/cacerts" do
        to '/etc/ssl/certs/java/cacerts'
        not_if { version <= 8 }
      end
    end

    # This method deletes the IBM Java installable and installer properties files
    # @param [String] version - java version
    # @return - None

    def delete_files(version)
      installer = File.join(Dir.tmpdir, "ibmjava" + version.to_s + "-installer")
      properties = File.join(Dir.tmpdir, "installer.properties")
      file "Delete properties file for IBM Java#{version}" do
        path properties
        action :delete
      end

      file installer do
        action :delete
      end
    end

    # This method returns a hash containing the uri and checksum of the latest release by parsing the index.yml file
    # @param [String] url - url of index.yml file
    # @param [String] version - java version
    # @return [Hash] finalversion - latest entry from the index.yml for the specified IBM Java version containing uri
    #                               and sha256sum
    def find_version_entry(url, version)
      finalversion = nil
      version = '1.'.concat(version.to_s) unless version.to_s.include?('.')
      yaml_content = open(url.to_s, &:read)
      entries = YAML.safe_load(yaml_content)
      entries.each do |entry|
        finalversion = entry[1] if entry[0].to_s.start_with?(version.to_s)
      end
      finalversion
    end
  end
end


text:
package org.scaladebugger.api.debuggers
import com.sun.jdi.connect.{AttachingConnector, Connector}
import com.sun.jdi.{VirtualMachine, VirtualMachineManager}
import org.scaladebugger.api.profiles.ProfileManager
import org.scaladebugger.api.utils.LoopingTaskRunner
import org.scaladebugger.api.virtualmachines.{ScalaVirtualMachine, ScalaVirtualMachineManager, StandardScalaVirtualMachine}
import org.scaladebugger.test.helpers.ParallelMockFunSpec

import scala.collection.JavaConverters._

class AttachingDebuggerSpec extends ParallelMockFunSpec
{
  private def createConnectorArgumentMock(
    setter: Boolean = false,
    getter: Option[String] = None
  ) = {
    val mockConnectorArgument = mock[Connector.Argument]
    if (getter.nonEmpty)
      (mockConnectorArgument.value _).expects().returning(getter.get).once()
    if (setter) (mockConnectorArgument.setValue _).expects(*).once()
    mockConnectorArgument
  }

  private val testPort = 1234
  private val testHostname = "some hostname"
  private val testTimeout = 9876

  private val mockVirtualMachineManager = mock[VirtualMachineManager]
  private val mockScalaVirtualMachineManager = mock[ScalaVirtualMachineManager]
  private val mockVirtualMachine = mock[VirtualMachine]
  private val mockProfileManager = mock[ProfileManager]
  private val mockLoopingTaskRunner = mock[LoopingTaskRunner]
  private val mockAddNewScalaVirtualMachineFunc = mockFunction[
    ScalaVirtualMachineManager, VirtualMachine, ProfileManager,
    LoopingTaskRunner, ScalaVirtualMachine
  ]

  private class TestScalaVirtualMachine extends StandardScalaVirtualMachine(
    mockScalaVirtualMachineManager, mockVirtualMachine, mockProfileManager,
    mockLoopingTaskRunner
  )
  private val mockScalaVirtualMachine = mock[TestScalaVirtualMachine]

  private class TestAttachingDebugger(
    override val isAvailable: Boolean = true,
    private val shouldJdiLoad: Boolean = true,
    private val customScalaVirtualMachine: Option[StandardScalaVirtualMachine] = Some(null)
  ) extends AttachingDebugger(
    virtualMachineManager = mockVirtualMachineManager,
    profileManager        = mockProfileManager,
    loopingTaskRunner     = mockLoopingTaskRunner,
    port                  = testPort,
    hostname              = testHostname,
    timeout               = testTimeout
  ) {
    override protected def addNewScalaVirtualMachine(
      scalaVirtualMachineManager: ScalaVirtualMachineManager,
      virtualMachine: VirtualMachine,
      profileManager: ProfileManager,
      loopingTaskRunner: LoopingTaskRunner
    ): ScalaVirtualMachine = mockAddNewScalaVirtualMachineFunc(
      scalaVirtualMachineManager,
      virtualMachine,
      profileManager,
      loopingTaskRunner
    )

    override def assertJdiLoaded(): Unit =
      if (!shouldJdiLoad) throw new AssertionError
  }

  describe("AttachingDebugger") {
    describe("#start") {
      it("should throw an exception if unable to load JDI") {
        val attachingDebugger = new TestAttachingDebugger(shouldJdiLoad = false)

        intercept[AssertionError] {
          attachingDebugger.start((_) => {})
        }
      }

      it("should throw an exception if already started") {
        val attachingDebugger = new TestAttachingDebugger(shouldJdiLoad = true)

        // MOCK ===============================================================
        val mockAttachingConnector = mock[AttachingConnector]

        (mockAttachingConnector.name _).expects()
          .returning("com.sun.jdi.SocketAttach")

        (mockVirtualMachineManager.attachingConnectors _).expects()
          .returning(Seq(mockAttachingConnector).asJava)

        (mockAttachingConnector.defaultArguments _).expects().returning(Map(
          "hostname" -> createConnectorArgumentMock(setter = true),
          "port" -> createConnectorArgumentMock(setter = true),
          "timeout" -> createConnectorArgumentMock(setter = true)
        ).asJava)

        (mockAttachingConnector.attach _).expects(*).once()
        (mockLoopingTaskRunner.start _).expects().once()
        mockAddNewScalaVirtualMachineFunc.expects(*, *, *, *)
          .returning(stub[TestScalaVirtualMachine]).once()
        // MOCK ===============================================================

        attachingDebugger.start((_) => {})

        intercept[AssertionError] {
          attachingDebugger.start((_) => {})
        }
      }

      it("should throw an exception if unable to get the attaching connector") {
        val attachingDebugger = new TestAttachingDebugger(shouldJdiLoad = true)
        (mockVirtualMachineManager.attachingConnectors _).expects()
          .returning((Nil: Seq[AttachingConnector]).asJava)

        intercept[AssertionError] {
          attachingDebugger.start((_) => {})
        }
      }

      it("should invoke the callback function with the new virtual machine") {
        val expected = stub[TestScalaVirtualMachine]
        val attachingDebugger = new TestAttachingDebugger(shouldJdiLoad = true)

        // MOCK ===============================================================
        val mockAttachingConnector = mock[AttachingConnector]

        (mockAttachingConnector.name _).expects()
          .returning("com.sun.jdi.SocketAttach")

        (mockVirtualMachineManager.attachingConnectors _).expects()
          .returning(Seq(mockAttachingConnector).asJava)

        (mockAttachingConnector.defaultArguments _).expects().returning(Map(
          "hostname" -> createConnectorArgumentMock(setter = true),
          "port" -> createConnectorArgumentMock(setter = true),
          "timeout" -> createConnectorArgumentMock(setter = true)
        ).asJava)

        (mockAttachingConnector.attach _).expects(*)
          .returning(mockVirtualMachine).once()
        (mockLoopingTaskRunner.start _).expects().once()
        mockAddNewScalaVirtualMachineFunc.expects(*, *, *, *)
          .returning(expected).once()
        // MOCK ===============================================================

        var actual: ScalaVirtualMachine = null
        attachingDebugger.start(actual = _)

        actual should be (expected)
      }

      it("should apply any pending requests to the virtual machine") {
        val attachingDebugger = new TestAttachingDebugger(shouldJdiLoad = true)
        val expected = stub[TestScalaVirtualMachine]
        attachingDebugger.addPendingScalaVirtualMachine(expected)

        // MOCK ===============================================================
        val mockAttachingConnector = mock[AttachingConnector]

        (mockAttachingConnector.name _).expects()
          .returning("com.sun.jdi.SocketAttach")

        (mockVirtualMachineManager.attachingConnectors _).expects()
          .returning(Seq(mockAttachingConnector).asJava)

        (mockAttachingConnector.defaultArguments _).expects().returning(Map(
          "hostname" -> createConnectorArgumentMock(setter = true),
          "port" -> createConnectorArgumentMock(setter = true),
          "timeout" -> createConnectorArgumentMock(setter = true)
        ).asJava)

        (mockAttachingConnector.attach _).expects(*)
          .returning(mockVirtualMachine).once()
        (mockLoopingTaskRunner.start _).expects().once()
        // MOCK ===============================================================

        mockAddNewScalaVirtualMachineFunc.expects(
          attachingDebugger.scalaVirtualMachineManager, mockVirtualMachine, *, *
        ).returning(mockScalaVirtualMachine).once()

        (mockScalaVirtualMachine.processPendingRequests _)
          .expects(expected).once()

        (mockScalaVirtualMachine.initialize _)
          .expects(Debugger.DefaultProfileName, true).once()

        attachingDebugger.start(_ => {})
      }

      it("should initialize the new virtual machine") {
        val attachingDebugger = new TestAttachingDebugger(shouldJdiLoad = true)

        // MOCK ===============================================================
        val mockAttachingConnector = mock[AttachingConnector]

        (mockAttachingConnector.name _).expects()
          .returning("com.sun.jdi.SocketAttach")

        (mockVirtualMachineManager.attachingConnectors _).expects()
          .returning(Seq(mockAttachingConnector).asJava)

        (mockAttachingConnector.defaultArguments _).expects().returning(Map(
          "hostname" -> createConnectorArgumentMock(setter = true),
          "port" -> createConnectorArgumentMock(setter = true),
          "timeout" -> createConnectorArgumentMock(setter = true)
        ).asJava)

        (mockAttachingConnector.attach _).expects(*)
          .returning(mockVirtualMachine).once()
        (mockLoopingTaskRunner.start _).expects().once()
        // MOCK ===============================================================

        mockAddNewScalaVirtualMachineFunc.expects(
          attachingDebugger.scalaVirtualMachineManager, mockVirtualMachine, *, *
        ).returning(mockScalaVirtualMachine).once()

        (mockScalaVirtualMachine.initialize _)
          .expects(Debugger.DefaultProfileName, true).once()

        attachingDebugger.start(_ => {})
      }
    }

    describe("#isRunning") {
      it("should return true if already started") {
        val attachingDebugger = new TestAttachingDebugger(shouldJdiLoad = true)

        // MOCK ===============================================================
        val mockAttachingConnector = mock[AttachingConnector]

        (mockAttachingConnector.name _).expects()
          .returning("com.sun.jdi.SocketAttach")

        (mockVirtualMachineManager.attachingConnectors _).expects()
          .returning(Seq(mockAttachingConnector).asJava)

        (mockAttachingConnector.defaultArguments _).expects().returning(Map(
          "hostname" -> createConnectorArgumentMock(setter = true),
          "port" -> createConnectorArgumentMock(setter = true),
          "timeout" -> createConnectorArgumentMock(setter = true)
        ).asJava)

        (mockAttachingConnector.attach _).expects(*)
          .returning(mockVirtualMachine).once()
        (mockLoopingTaskRunner.start _).expects().once()
        mockAddNewScalaVirtualMachineFunc.expects(*, *, *, *)
          .returning(stub[TestScalaVirtualMachine]).once()
        // MOCK ===============================================================

        attachingDebugger.start(_ => {})

        attachingDebugger.isRunning should be (true)
      }

      it("should return false if not started (or started and then stopped)") {
        val attachingDebugger = new TestAttachingDebugger()
        attachingDebugger.isRunning should be (false)
      }
    }

    describe("#stop") {
      it("should throw an exception if not started") {
        val attachingDebugger = new TestAttachingDebugger()

        intercept[AssertionError] {
          attachingDebugger.stop()
        }
      }

      it("should dispose of the virtual machine mirror") {
        val attachingDebugger = new TestAttachingDebugger(shouldJdiLoad = true)

        // MOCK ===============================================================
        val mockAttachingConnector = mock[AttachingConnector]

        (mockAttachingConnector.name _).expects()
          .returning("com.sun.jdi.SocketAttach")

        (mockVirtualMachineManager.attachingConnectors _).expects()
          .returning(Seq(mockAttachingConnector).asJava)

        (mockAttachingConnector.defaultArguments _).expects().returning(Map(
          "hostname" -> createConnectorArgumentMock(setter = true),
          "port" -> createConnectorArgumentMock(setter = true),
          "timeout" -> createConnectorArgumentMock(setter = true)
        ).asJava)

        (mockAttachingConnector.attach _).expects(*)
          .returning(mockVirtualMachine).once()
        (mockLoopingTaskRunner.start _).expects().once()
        mockAddNewScalaVirtualMachineFunc.expects(*, *, *, *)
          .returning(stub[TestScalaVirtualMachine]).once()
        // MOCK ===============================================================

        attachingDebugger.start((_) => {})

        (mockLoopingTaskRunner.stop _).expects(true).once()
        (mockVirtualMachine.dispose _).expects().once()

        attachingDebugger.stop()
      }
    }

    describe("#process") {
      it("should return Some process if the JVM has been attached") {
        val attachingDebugger = new TestAttachingDebugger(shouldJdiLoad = true)

        // MOCK ===============================================================
        val mockAttachingConnector = mock[AttachingConnector]

        (mockAttachingConnector.name _).expects()
          .returning("com.sun.jdi.SocketAttach")

        (mockVirtualMachineManager.attachingConnectors _).expects()
          .returning(Seq(mockAttachingConnector).asJava)

        (mockAttachingConnector.defaultArguments _).expects().returning(Map(
          "hostname" -> createConnectorArgumentMock(setter = true),
          "port" -> createConnectorArgumentMock(setter = true),
          "timeout" -> createConnectorArgumentMock(setter = true)
        ).asJava)

        (mockAttachingConnector.attach _).expects(*)
          .returning(mockVirtualMachine).once()
        (mockLoopingTaskRunner.start _).expects().once()
        mockAddNewScalaVirtualMachineFunc.expects(*, *, *, *)
          .returning(stub[TestScalaVirtualMachine]).once()
        // MOCK ===============================================================

        val mockProcess = mock[Process]
        (mockVirtualMachine.process _).expects().returning(mockProcess).once()

        attachingDebugger.start((_) => {})

        attachingDebugger.process should be (Some(mockProcess))
      }

      it("should return None if the JVM has not been attached") {
        val attachingDebugger = new TestAttachingDebugger(shouldJdiLoad = true)

        attachingDebugger.process should be (None)
      }
    }
  }
}


text:
<?php

namespace RevyWeather\Services\Mailer;

/**
 * Abstract Mailer
 *
 * @author  Derek Marcinyshyn <derek@marcinyshyn.com>
 * @date    2016-03-25
 */

use Mail;

abstract class AbstractMailer
{

    /**
     * @param $user
     * @param string $subject
     * @param string $view
     * @param array $data
     * @return mixed
     */
    public function sendTo($user, $subject, $view, $data)
    {
        return Mail::queue($view, $data, function ($message) use ($user, $subject) {
            $message->from('info@revyweather.com', 'Revy Weather')
                ->to($user->email, $user->name)
                ->sender('info@revyweather.com', 'Revy Weather')
                ->replyTo('info@revyweather.com', 'Revy Weather')
                ->subject($subject);
        });
    }

    /**
     * @param string $subject
     * @param string $view
     * @param array $data
     * @return mixed
     */
    public function notification($subject, $view, $data)
    {
        return Mail::queue($view, $data, function ($message) use ($subject) {
            $message->from('info@revyweather.com', 'Revy Weather')
                ->to('derek@marcinyshyn.com', 'Derek')
                ->sender('info@revyweather.com', 'Revy Weather')
                ->replyTo('info@revyweather.com', 'Revy Weather')
                ->subject($subject);
        });
    }
}


text:
class UsersController < ApplicationController
  before_action :signed_in_user,
                only: [:edit, :update, :destroy, :following, :followers]
  before_action :correct_user,   only: [:edit, :update]
  before_action :admin_user,     only: :destroy

  respond_to :json, :html

  def index
    @users = User.paginate(page: params[:page])

    respond_with @users
  end

  def show
    @user = User.find(params[:id])

  case params[:category]
    when 'Health'
      @microposts = Micropost.where("category == ? AND user_id = ?", "Health", @user.id).paginate(page: params[:page])
    when 'Fitness'
      @microposts = Micropost.where("category == ? AND user_id = ?", "Fitness", @user.id).paginate(page: params[:page])
    when 'Family'
      @microposts = Micropost.where("category == ? AND user_id = ?", "Family", @user.id).paginate(page: params[:page])
    when 'Religion'
      @microposts = Micropost.where("category == ? AND user_id = ?", "Religion", @user.id).paginate(page: params[:page])
    when 'Relations'
      @microposts = Micropost.where("category == ? AND user_id = ?", "Relations", @user.id).paginate(page: params[:page])
    when 'Leadership'
      @microposts = Micropost.where("category == ? AND user_id = ?", "Leadership", @user.id).paginate(page: params[:page])
    else
     @microposts = @user.microposts.paginate(page: params[:page])
    end
  end

  def new
    @user = User.new
  end

  def create
    @user = User.new(user_params)
    if @user.save
      sign_in @user
      flash[:success] = "Welcome to the Tb!"
      redirect_to @user
    else
      render 'new'
    end
  end

  def edit
  end

  def update
    if @user.update_attributes(user_params)
      flash[:success] = "Profile updated"
      redirect_to @user
    else
      render 'edit'
    end
  end

  def destroy
    User.find(params[:id]).destroy
    flash[:success] = "User destroyed."
    redirect_to users_url
  end

  def following
    @title = "Following"
    @user = User.find(params[:id])
    @users = @user.followed_users.paginate(page: params[:page])
    render 'show_follow'
  end

  def followers
    @title = "Followers"
    @user = User.find(params[:id])
    @users = @user.followers.paginate(page: params[:page])
    render 'show_follow'
  end

  private

    def user_params
      params.require(:user).permit(:name, :email, :password,
                                   :password_confirmation)
    end

    # Before filters

    def correct_user
      @user = User.find(params[:id])
      redirect_to(root_url) unless current_user?(@user)
    end

    def admin_user
      redirect_to(root_url) unless current_user.admin?
    end
  end


text:
package org.keycloak.testsuite.x509;

import org.jboss.arquillian.drone.api.annotation.Drone;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.keycloak.OAuth2Constants;
import org.keycloak.authentication.authenticators.x509.X509AuthenticatorConfigModel;
import org.keycloak.events.Details;
import org.keycloak.events.Errors;
import org.keycloak.representations.AccessToken;
import org.keycloak.representations.RefreshToken;
import org.keycloak.representations.idm.AuthenticatorConfigRepresentation;
import org.keycloak.representations.idm.UserRepresentation;
import org.keycloak.testsuite.AssertEvents;
import org.keycloak.testsuite.util.ContainerAssume;
import org.keycloak.testsuite.util.OAuthClient;
import org.keycloak.testsuite.util.PhantomJSBrowser;
import org.openqa.selenium.WebDriver;

import javax.ws.rs.core.Response;

import static org.hamcrest.Matchers.containsString;
import static org.junit.Assert.assertEquals;
import static org.keycloak.authentication.authenticators.x509.X509AuthenticatorConfigModel.IdentityMapperType.USERNAME_EMAIL;
import static org.keycloak.authentication.authenticators.x509.X509AuthenticatorConfigModel.IdentityMapperType.USER_ATTRIBUTE;
import static org.keycloak.authentication.authenticators.x509.X509AuthenticatorConfigModel.MappingSourceType.ISSUERDN;
import static org.keycloak.authentication.authenticators.x509.X509AuthenticatorConfigModel.MappingSourceType.SUBJECTDN_EMAIL;

/**
 * @author Peter Nalyvayko
 * @version $Revision: 1 $
 * @since 10/28/2016
 */

public class X509DirectGrantTest extends AbstractX509AuthenticationTest {

    @Drone
    @PhantomJSBrowser
    private WebDriver phantomJS;

    @Before
    public void replaceTheDefaultDriver() {
        replaceDefaultWebDriver(phantomJS);
    }

    @Test
    public void loginFailedOnDuplicateUsers() throws Exception {

        AuthenticatorConfigRepresentation cfg = newConfig("x509-directgrant-config", createLoginIssuerDN_OU2CustomAttributeConfig().getConfig());
        String cfgId = createConfig(directGrantExecution.getId(), cfg);
        Assert.assertNotNull(cfgId);

        // Set up the users so that the identity extracted from X509 client cert
        // matches more than a single user to trigger DuplicateModelException.

        UserRepresentation user = testRealm().users().get(userId2).toRepresentation();
        Assert.assertNotNull(user);

        user.singleAttribute("x509_certificate_identity", "Red Hat");
        this.updateUser(user);

        user = testRealm().users().get(userId).toRepresentation();
        Assert.assertNotNull(user);

        user.singleAttribute("x509_certificate_identity", "Red Hat");
        this.updateUser(user);

        events.clear();

        oauth.clientId("resource-owner");
        OAuthClient.AccessTokenResponse response = oauth.doGrantAccessTokenRequest("secret", "", "", null);

        assertEquals(401, response.getStatusCode());
        assertEquals("invalid_request", response.getError());
        Assert.assertThat(response.getErrorDescription(), containsString("X509 certificate authentication's failed."));
    }

    @Test
    public void loginFailedOnInvalidUser() throws Exception {

        AuthenticatorConfigRepresentation cfg = newConfig("x509-directgrant-config", createLoginIssuerDN_OU2CustomAttributeConfig().getConfig());
        String cfgId = createConfig(directGrantExecution.getId(), cfg);
        Assert.assertNotNull(cfgId);

        UserRepresentation user = testRealm().users().get(userId2).toRepresentation();
        Assert.assertNotNull(user);

        user.singleAttribute("x509_certificate_identity", "-");
        this.updateUser(user);

        events.clear();

        oauth.clientId("resource-owner");
        OAuthClient.AccessTokenResponse response = oauth.doGrantAccessTokenRequest("secret", "", "", null);

        events.expectLogin()
                .user((String) null)
                .session((String) null)
                .error(Errors.INVALID_USER_CREDENTIALS)
                .client("resource-owner")
                .removeDetail(Details.CODE_ID)
                .removeDetail(Details.USERNAME)
                .removeDetail(Details.CONSENT)
                .removeDetail(Details.REDIRECT_URI)
                .assertEvent();

        assertEquals(401, response.getStatusCode());
        assertEquals("invalid_grant", response.getError());
        assertEquals("Invalid user credentials", response.getErrorDescription());
    }

    @Test
    public void loginWithNonSupportedCertKeyUsage() throws Exception {
        // Set the X509 authenticator configuration
        AuthenticatorConfigRepresentation cfg = newConfig("x509-directgrant-config",
                createLoginSubjectEmailWithKeyUsage("dataEncipherment").getConfig());
        String cfgId = createConfig(directGrantExecution.getId(), cfg);
        Assert.assertNotNull(cfgId);

        oauth.clientId("resource-owner");
        OAuthClient.AccessTokenResponse response = oauth.doGrantAccessTokenRequest("secret", "", "", null);

        assertEquals(401, response.getStatusCode());
        assertEquals("invalid_request", response.getError());
        Assert.assertThat(response.getErrorDescription(), containsString("Key Usage bit 'dataEncipherment' is not set."));
        events.clear();
    }

    @Test
    public void loginWithNonSupportedCertExtendedKeyUsage() throws Exception {
        // Set the X509 authenticator configuration
        AuthenticatorConfigRepresentation cfg = newConfig("x509-directgrant-config",
                createLoginSubjectEmailWithExtendedKeyUsage("serverAuth").getConfig());
        String cfgId = createConfig(directGrantExecution.getId(), cfg);
        Assert.assertNotNull(cfgId);

        oauth.clientId("resource-owner");
        OAuthClient.AccessTokenResponse response = oauth.doGrantAccessTokenRequest("secret", "", "", null);

        assertEquals(200, response.getStatusCode());
    }

    @Test
    public void loginWithNonMatchingRegex() throws Exception {
        X509AuthenticatorConfigModel config = createLoginIssuerDN_OU2CustomAttributeConfig();
        config.setRegularExpression("INVALID=(.*?)(?:,|$)");
        AuthenticatorConfigRepresentation cfg = newConfig("x509-directgrant-config", config.getConfig());

        String cfgId = createConfig(directGrantExecution.getId(), cfg);
        Assert.assertNotNull(cfgId);

        oauth.clientId("resource-owner");
        OAuthClient.AccessTokenResponse response = oauth.doGrantAccessTokenRequest("secret", "", "", null);

        assertEquals(401, response.getStatusCode());

        AssertEvents.ExpectedEvent expectedEvent = events.expectLogin()
                .user((String) null)
                .session((String) null)
                .error("invalid_user_credentials")
                .client("resource-owner")
                .removeDetail(Details.CODE_ID)
                .removeDetail(Details.CONSENT)
                .removeDetail(Details.REDIRECT_URI);

        addX509CertificateDetails(expectedEvent)
                .assertEvent();
    }

    @Test
    public void loginFailedDisabledUser() throws Exception {
        setUserEnabled("test-user@localhost", false);

        try {
            AuthenticatorConfigRepresentation cfg = newConfig("x509-directgrant-config", createLoginSubjectEmail2UsernameOrEmailConfig().getConfig());
            String cfgId = createConfig(directGrantExecution.getId(), cfg);
            Assert.assertNotNull(cfgId);

            oauth.clientId("resource-owner");
            OAuthClient.AccessTokenResponse response = oauth.doGrantAccessTokenRequest("secret", "", "", null);

            events.expectLogin()
                    .user(userId)
                    .session((String) null)
                    .error(Errors.USER_DISABLED)
                    .client("resource-owner")
                    .detail(Details.USERNAME, "test-user@localhost")
                    .removeDetail(Details.CODE_ID)
                    .removeDetail(Details.CONSENT)
                    .removeDetail(Details.REDIRECT_URI)
                    .assertEvent();

            assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode());
            assertEquals("invalid_grant", response.getError());
            assertEquals("Account disabled", response.getErrorDescription());

        } finally {
            setUserEnabled("test-user@localhost", true);
        }
    }

    @Test
    public void loginCertificateRevoked() throws Exception {
        // Not possible to test file CRL on undertow at this moment - jboss config dir doesn't exist
        ContainerAssume.assumeNotAuthServerUndertow();

        X509AuthenticatorConfigModel config =
                new X509AuthenticatorConfigModel()
                        .setCRLEnabled(true)
                        .setCRLRelativePath(INTERMEDIATE_CA_CRL_PATH)
                        .setConfirmationPageAllowed(true)
                        .setMappingSourceType(SUBJECTDN_EMAIL)
                        .setUserIdentityMapperType(USERNAME_EMAIL);
        AuthenticatorConfigRepresentation cfg = newConfig("x509-directgrant-config", config.getConfig());
        String cfgId = createConfig(directGrantExecution.getId(), cfg);
        Assert.assertNotNull(cfgId);

        oauth.clientId("resource-owner");
        OAuthClient.AccessTokenResponse response = oauth.doGrantAccessTokenRequest("secret", "", "", null);

        assertEquals(401, response.getStatusCode());
        assertEquals("invalid_request", response.getError());
        Assert.assertThat(response.getErrorDescription(), containsString("Certificate has been revoked, certificate's subject:"));

    }

    @Test
    public void loginCertificateNotExpired() throws Exception {
        X509AuthenticatorConfigModel config =
                new X509AuthenticatorConfigModel()
                    .setCertValidationEnabled(true)
                    .setConfirmationPageAllowed(true)
                    .setMappingSourceType(SUBJECTDN_EMAIL)
                    .setUserIdentityMapperType(USERNAME_EMAIL);
        AuthenticatorConfigRepresentation cfg = newConfig("x509-directgrant-config", config.getConfig());
        String cfgId = createConfig(directGrantExecution.getId(), cfg);
        Assert.assertNotNull(cfgId);

        oauth.clientId("resource-owner");
        OAuthClient.AccessTokenResponse response = oauth.doGrantAccessTokenRequest("secret", "", "", null);

        assertEquals(200, response.getStatusCode());
    }

    @Test
    public void loginCertificateExpired() throws Exception {
        X509AuthenticatorConfigModel config =
                new X509AuthenticatorConfigModel()
                    .setCertValidationEnabled(true)
                    .setConfirmationPageAllowed(true)
                    .setMappingSourceType(SUBJECTDN_EMAIL)
                    .setUserIdentityMapperType(USERNAME_EMAIL);
        AuthenticatorConfigRepresentation cfg = newConfig("x509-directgrant-config", config.getConfig());
        String cfgId = createConfig(directGrantExecution.getId(), cfg);
        Assert.assertNotNull(cfgId);

        setTimeOffset(50 * 365 * 24 * 60 * 60);

        oauth.clientId("resource-owner");
        OAuthClient.AccessTokenResponse response = oauth.doGrantAccessTokenRequest("secret", "", "", null);

        setTimeOffset(0);

        assertEquals(401, response.getStatusCode());
        assertEquals("invalid_request", response.getError());
        Assert.assertThat(response.getErrorDescription(), containsString("has expired on:"));
    }

    private void loginForceTemporaryAccountLock() throws Exception {
        X509AuthenticatorConfigModel config = new X509AuthenticatorConfigModel()
                .setMappingSourceType(ISSUERDN)
                .setRegularExpression("OU=(.*?)(?:,|$)")
                .setUserIdentityMapperType(USER_ATTRIBUTE)
                .setCustomAttributeName("x509_certificate_identity");

        AuthenticatorConfigRepresentation cfg = newConfig("x509-directgrant-config", config.getConfig());
        String cfgId = createConfig(directGrantExecution.getId(), cfg);
        Assert.assertNotNull(cfgId);

        UserRepresentation user = testRealm().users().get(userId).toRepresentation();
        Assert.assertNotNull(user);

        user.singleAttribute("x509_certificate_identity", "-");
        this.updateUser(user);

        events.clear();

        oauth.clientId("resource-owner");
        oauth.doGrantAccessTokenRequest("secret", "", "", null);
        oauth.doGrantAccessTokenRequest("secret", "", "", null);
        oauth.doGrantAccessTokenRequest("secret", "", "", null);

        events.clear();
    }

    @Test
    @Ignore
    public void loginFailedTemporarilyDisabledUser() throws Exception {

        loginForceTemporaryAccountLock();

        AuthenticatorConfigRepresentation cfg = newConfig("x509-directgrant-config", createLoginSubjectEmail2UsernameOrEmailConfig().getConfig());
        String cfgId = createConfig(directGrantExecution.getId(), cfg);
        Assert.assertNotNull(cfgId);

        oauth.clientId("resource-owner");
        OAuthClient.AccessTokenResponse response = oauth.doGrantAccessTokenRequest("secret", "", "", null);

        events.expectLogin()
                .user(userId)
                .session((String) null)
                .error(Errors.USER_TEMPORARILY_DISABLED)
                .detail(Details.USERNAME, "test-user@localhost")
                .removeDetail(Details.CODE_ID)
                .removeDetail(Details.CONSENT)
                .removeDetail(Details.REDIRECT_URI)
                .assertEvent();

        assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode());
        assertEquals("invalid_grant", response.getError());
        assertEquals("Account temporarily disabled", response.getErrorDescription());
    }

    private void doResourceOwnerCredentialsLogin(String clientId, String clientSecret, String login, String password) throws Exception {

        oauth.clientId(clientId);
        OAuthClient.AccessTokenResponse response = oauth.doGrantAccessTokenRequest(clientSecret, "", "", null);

        assertEquals(200, response.getStatusCode());

        AccessToken accessToken = oauth.verifyToken(response.getAccessToken());
        RefreshToken refreshToken = oauth.parseRefreshToken(response.getRefreshToken());

        AssertEvents.ExpectedEvent expectedEvent = events.expectLogin()
                .client(clientId)
                .user(userId)
                .session(accessToken.getSessionState())
                .detail(Details.GRANT_TYPE, OAuth2Constants.PASSWORD)
                .detail(Details.TOKEN_ID, accessToken.getId())
                .detail(Details.REFRESH_TOKEN_ID, refreshToken.getId())
                .detail(Details.USERNAME, login)
                .removeDetail(Details.CODE_ID)
                .removeDetail(Details.REDIRECT_URI)
                .removeDetail(Details.CONSENT);

        addX509CertificateDetails(expectedEvent)
                .assertEvent();
    }

    @Test
    public void loginResourceOwnerCredentialsSuccess() throws Exception {
        X509AuthenticatorConfigModel config =
                new X509AuthenticatorConfigModel()
                        .setMappingSourceType(SUBJECTDN_EMAIL)
                        .setUserIdentityMapperType(USERNAME_EMAIL);
        AuthenticatorConfigRepresentation cfg = newConfig("x509-directgrant-config", config.getConfig());
        String cfgId = createConfig(directGrantExecution.getId(), cfg);
        Assert.assertNotNull(cfgId);

        doResourceOwnerCredentialsLogin("resource-owner", "secret", "test-user@localhost", "");
    }

}


text:
<?php

namespace CountryReferential\Controller;

use Zend\Mvc\Controller\AbstractRestfulController;
use Zend\View\Model\ViewModel;
use Zend\View\Model\JsonModel;

class ApiController extends AbstractRestfulController
{
    protected $acceptCriteria = array(
      'Zend\View\Model\ViewModel' => array(
         'application/xml',
      ),
   );

    /**
     * Gère les requêtes entrantes
     *
     * @return type
     */
    public function indexAction()
    {
        if ($this->getRequest()->getMethod() == 'GET') {
            $view = $this->getAction();

            $view->setTemplate("/country-referential/api/get.phtml");

            return $view;
        } else if ($this->getRequest()->getMethod() == "POST") {
            $json = $this->getRequest()->getContent();
            $data = json_decode($json, true);

            $this->save($data);
        } else if ($this->getRequest()->getMethod() == "PATCH") {
            $code = $this->params('code');

            $paysTable = $this->getServiceLocator()->get('pays-table');
            $pays = $paysTable->getPays($code, "", true)[0];

            $dataPays = $pays->toArray();

            $json = $this->getRequest()->getContent();
            $data = array_merge($dataPays, json_decode($json, true));

            if (empty($data['code'])) {
                return false;
            }

            $this->save($data, true);
        } else if ($this->getRequest()->getMethod() == 'DELETE') {
            $this->deleteAction();
        }
    }

    /**
     * Méthode POST
     * @param type $data
     */
    public function save($data, $isApi = false)
    {
        $paysTable = $this->getServiceLocator()->get('pays-table');

        $country = new \CountryReferential\Model\Pays();
        $country->exchangeArray($data);

        $paysTable->saveCountry($country, $isApi);
    }

    /**
     * Méthode GET de l'API
     *
     * @return \Zend\View\Model\JsonModel
     */
    public function getAction()
    {
        $view = $this->acceptableViewModelSelector($this->acceptCriteria, false);

        if (!$view) {
            $view = new JsonModel();
        }

        $code = $this->params('code');
        $fieldsString = $this->params()->fromQuery('fields');

        $paysTable = $this->getServiceLocator()->get('pays-table');

        if (get_class($view) == 'Zend\View\Model\ViewModel') {
            $view->setTerminal(true);

            $this->response->getHeaders()->addHeaderLine('Content-Type', 'text/xml; charset=utf-8');

            $paysList = $paysTable->getPaysXml($code, $fieldsString);
        } else {
            $paysList = $paysTable->getPays($code, $fieldsString);
        }

        $view->setVariable('country', $paysList);

        return $view;
    }

    /**
     * Supprime un pays en BDD
     *
     * @param type $code
     */
    public function deleteAction()
    {
        $code = $this->params('code');

        if ($code) {
            $paysTable = $this->getServiceLocator()->get('pays-table');

            $paysTable->deleteCountry($code);
        }
    }
}


text:
project_path: /web/_project.yaml
book_path: /web/tools/_book.yaml
description: Reference documentation for the "No Element Has a Tabindex Attribute Greater Than Zero" Lighthouse audit.

{# wf_updated_on: 2017-01-23 #}
{# wf_published_on: 2017-01-23 #}

# No Element Has a Tabindex Attribute Greater Than Zero  {: .page-title }

## Why the audit is important {: #why }

The `tabindex` attribute makes elements keyboard navigable.
Positive values indicate an explicit navigation ordering of elements.
Although this is valid, in practice it is extremely hard to do correctly and
creates unusable experiences for users who rely on assistive technologies.

See [Using tabindex](/web/fundamentals/accessibility/focus/using-tabindex)
for more information.

## How to pass the audit {: #how }

<<_shared/query.md>>

Set the `tabindex` of each of these elements to either `-1`, for elements
that should not be keyboard navigable, or `0`, for elements that should. If
you need an element to appear earlier in the tab order, consider moving
it earlier in the DOM.

{% include "web/tools/lighthouse/audits/implementation-heading.html" %}

This audit is powered by the aXe Accessibility Engine. See [Elements should not
have tabindex greater than zero][axe] for more information.

[axe]: https://dequeuniversity.com/rules/axe/1.1/tabindex

{% include "web/tools/lighthouse/audits/_feedback/tabindex.html" %}


text:
package io.cloudslang.lang.systemtests.actions;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.hp.oo.sdk.content.annotations.Action;
import com.hp.oo.sdk.content.annotations.Output;
import com.hp.oo.sdk.content.annotations.Param;
import com.hp.oo.sdk.content.annotations.Response;
import com.hp.oo.sdk.content.plugin.ActionMetadata.MatchType;
import com.hp.oo.sdk.content.plugin.ActionMetadata.ResponseType;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;

public class OpenstackUtils {
	private static final String RETURN_RESULT_KEY = "returnResult";
	private static final String ID_KEY = "id";
	private static final String TOKEN_KEY = "token";
	private static final String TENANT_KEY = "tenant";
	private static final String PARSED_TOKEN_KEY = "parsedToken";
	private static final String PARSED_TENANT_KEY = "parsedTenant";
	private static final String ACCESS_KEY = "access";
	public static final String RETURN_CODE = "returnCode";
	public static final String SUCCESS_CODE = "0";
	public static final String FAILED_CODE = "-1";

	public static final String JSON_AUTHENTICATION_RESPONSE_KEY= "jsonAuthenticationResponse";

	/**
	 * Parses authentication response to get the Tenant and Token and puts them
	 * back in the executionContext.
	 *
	 *
	 */
	@SuppressWarnings("unused")
    @Action(name = "Parse Authentication",
            outputs = {
                    @Output(PARSED_TENANT_KEY),
                    @Output(PARSED_TOKEN_KEY),
                    @Output("returnCode"),
                    @Output("returnResult")
            },
            responses = {
                    @Response(text = "success", field = "returnCode", value = "0", matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.RESOLVED),
                    @Response(text = "failure", field = "returnCode", value = "-1", matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.ERROR)
            }
    )
	public Map<String, String> parseAuthentication(@Param(JSON_AUTHENTICATION_RESPONSE_KEY)String jsonAuthenticationResponse) {

        Map<String, String> results = new HashMap<>();
        try {
            JsonElement parsedResult = new JsonParser().parse(jsonAuthenticationResponse);
            JsonObject parsedObject = parsedResult.getAsJsonObject();
            JsonObject accessObject = parsedObject.getAsJsonObject(ACCESS_KEY);
            JsonObject tokenObject = accessObject.getAsJsonObject(TOKEN_KEY);

            String resultToken = tokenObject.get(ID_KEY).toString();
            resultToken = resultToken.substring(1, resultToken.length() - 1);

            JsonObject tenantObject = tokenObject.getAsJsonObject(TENANT_KEY);
            String resultTenant = tenantObject.get(ID_KEY).toString();
            resultTenant = resultTenant.substring(1, resultTenant.length() - 1);

            results.put(PARSED_TENANT_KEY, resultTenant);
            results.put(PARSED_TOKEN_KEY, resultToken);
            results.put(RETURN_RESULT_KEY, "Parsing successful.");
            if (!(StringUtils.isEmpty(resultToken) && StringUtils.isEmpty(resultTenant))) {
                results.put(RETURN_CODE, SUCCESS_CODE);
            } else {
                results.put(RETURN_CODE, FAILED_CODE);
            }
        } catch(Exception ignored){}
        return results;
	}

}