text:
<!DOCTYPE html>

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>The source code</title>
  <link href="../prettify/prettify.css" type="text/css" rel="stylesheet" />

/**
 * @class Ext.data.StoreManager
 * @extends Ext.util.MixedCollection
 * <p>Contains a collection of all stores that are created that have an identifier.
 * An identifier can be assigned by setting the {@link Ext.data.AbstractStore#storeId storeId}
 * property. When a store is in the StoreManager, it can be referred to via it's identifier:
 * <pre><code>
Ext.create('Ext.data.Store', {
    model: 'SomeModel',
    storeId: 'myStore'
});

var store = Ext.data.StoreManager.lookup('myStore');
 * </code></pre>
 * Also note that the {@link #lookup} method is aliased to {@link Ext#getStore} for convenience.</p>
 * <p>
 * If a store is registered with the StoreManager, you can also refer to the store by it's identifier when
 * registering it with any Component that consumes data from a store:
 * <pre><code>
Ext.create('Ext.data.Store', {
    model: 'SomeModel',
    storeId: 'myStore'
});

Ext.create('Ext.view.View', {
    store: 'myStore',
    // other configuration here
});
 * </code></pre>
 * </p>
 * @singleton
 * @docauthor Evan Trimboli <evan@sencha.com>
 * TODO: Make this an AbstractMgr
 */
Ext.define('Ext.data.StoreManager', {
    extend: 'Ext.util.MixedCollection',
    alternateClassName: ['Ext.StoreMgr', 'Ext.data.StoreMgr', 'Ext.StoreManager'],
    singleton: true,
    uses: ['Ext.data.ArrayStore'],

    /**
     * @cfg {Object} listeners @hide
     */

    /**
     * Registers one or more Stores with the StoreManager. You do not normally need to register stores
     * manually.  Any store initialized with a {@link Ext.data.Store#storeId} will be auto-registered.
     * @param {Ext.data.Store} store1 A Store instance
     * @param {Ext.data.Store} store2 (optional)
     * @param {Ext.data.Store} etc... (optional)
     */
    register : function() {
        for (var i = 0, s; (s = arguments[i]); i++) {
            this.add(s);
        }
    },

    /**
     * Unregisters one or more Stores with the StoreManager
     * @param {String/Object} id1 The id of the Store, or a Store instance
     * @param {String/Object} id2 (optional)
     * @param {String/Object} etc... (optional)
     */
    unregister : function() {
        for (var i = 0, s; (s = arguments[i]); i++) {
            this.remove(this.lookup(s));
        }
    },

    /**
     * Gets a registered Store by id
     * @param {String/Object} id The id of the Store, or a Store instance, or a store configuration
     * @return {Ext.data.Store}
     */
    lookup : function(store) {
        // handle the case when we are given an array or an array of arrays.
        if (Ext.isArray(store)) {
            var fields = ['field1'],
                expand = !Ext.isArray(store[0]),
                data = store,
                i,
                len;

            if(expand){
                data = [];
                for (i = 0, len = store.length; i < len; ++i) {
                    data.push([store[i]]);
                }
            } else {
                for(i = 2, len = store[0].length; i <= len; ++i){
                    fields.push('field' + i);
                }
            }
            return Ext.create('Ext.data.ArrayStore', {
                data  : data,
                fields: fields,
                autoDestroy: true,
                autoCreated: true,
                expanded: expand
            });
        }

        if (Ext.isString(store)) {
            // store id
            return this.get(store);
        } else {
            // store instance or store config
            return Ext.data.AbstractStore.create(store);
        }
    },

    // getKey implementation for MixedCollection
    getKey : function(o) {
         return o.storeId;
    }
}, function() {
    /**
     * <p>Creates a new store for the given id and config, then registers it with the {@link Ext.data.StoreManager Store Mananger}.
     * Sample usage:</p>
    <pre><code>
    Ext.regStore('AllUsers', {
        model: 'User'
    });

    //the store can now easily be used throughout the application
    new Ext.List({
        store: 'AllUsers',
        ... other config
    });
    </code></pre>
     * @param {String} id The id to set on the new store
     * @param {Object} config The store config
     * @param {Constructor} cls The new Component class.
     * @member Ext
     * @method regStore
     */
    Ext.regStore = function(name, config) {
        var store;

        if (Ext.isObject(name)) {
            config = name;
        } else {
            config.storeId = name;
        }

        if (config instanceof Ext.data.Store) {
            store = config;
        } else {
            store = Ext.create('Ext.data.Store', config);
        }

        return Ext.data.StoreManager.register(store);
    };

    /**
     * Gets a registered Store by id (shortcut to {@link Ext.data.StoreManager#lookup})
     * @param {String/Object} id The id of the Store, or a Store instance
     * @return {Ext.data.Store}
     * @member Ext
     * @method getStore
     */
    Ext.getStore = function(name) {
        return Ext.data.StoreManager.lookup(name);
    };
});


text:
<?php

namespace frontend\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\RefSoalanPenilaianPendidikanPenganjurInstructor;

/**
 * RefSoalanPenilaianPendidikanPenganjurInstructorSearch represents the model behind the search form about `app\models\RefSoalanPenilaianPendidikanPenganjurInstructor`.
 */
class RefSoalanPenilaianPendidikanPenganjurInstructorSearch extends RefSoalanPenilaianPendidikanPenganjurInstructor
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'aktif', 'created_by', 'updated_by'], 'integer'],
            [['desc', 'created', 'updated'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = RefSoalanPenilaianPendidikanPenganjurInstructor::find();

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        $query->andFilterWhere([
            'id' => $this->id,
            'aktif' => $this->aktif,
            'created_by' => $this->created_by,
            'updated_by' => $this->updated_by,
            'created' => $this->created,
            'updated' => $this->updated,
        ]);

        $query->andFilterWhere(['like', 'desc', $this->desc]);

        return $dataProvider;
    }
}

redpajama_set_name: RedPajamaGithub


text:
require 'test_helper'

describe "Redis::DistributedStore" do
  def setup
    @dmr = Redis::DistributedStore.new [
      { :host => "localhost", :port => "6380", :db => 0 },
      { :host => "localhost", :port => "6381", :db => 0 }
    ]
    @rabbit = OpenStruct.new :name => "bunny"
    @white_rabbit = OpenStruct.new :color => "white"
    @dmr.set "rabbit", @rabbit
  end

  def teardown
    @dmr.ring.nodes.each { |server| server.flushdb }
  end

  it "accepts connection params" do
    dmr = Redis::DistributedStore.new [ :host => "localhost", :port => "6380", :db => "1" ]
    dmr.ring.nodes.size == 1
    mr = dmr.ring.nodes.first
    _(mr.to_s).must_equal("Redis Client connected to localhost:6380 against DB 1")
  end

  it "forces reconnection" do
    @dmr.nodes.each do |node|
      node.expects(:reconnect)
    end

    @dmr.reconnect
  end

  it "sets an object" do
    @dmr.set "rabbit", @white_rabbit
    _(@dmr.get("rabbit")).must_equal(@white_rabbit)
  end

  it "gets an object" do
    _(@dmr.get("rabbit")).must_equal(@rabbit)
  end

  it "mget" do
    @dmr.set "rabbit2", @white_rabbit
    begin
      @dmr.mget "rabbit", "rabbit2" do |rabbits|
        rabbit, rabbit2 = rabbits
        _(rabbits.length).must_equal(2)
        _(rabbit).must_equal(@rabbit)
        _(rabbit2).must_equal(@white_rabbit)
      end
    rescue Redis::Distributed::CannotDistribute
      # Not supported on redis-rb < 4, and hence Ruby < 2.2.
    end
  end

  it "mapped_mget" do
    @dmr.set "rabbit2", @white_rabbit
    begin
      result = @dmr.mapped_mget("rabbit", "rabbit2")
      _(result.keys).must_equal %w[ rabbit rabbit2 ]
      _(result["rabbit"]).must_equal @rabbit
      _(result["rabbit2"]).must_equal @white_rabbit
    rescue Redis::Distributed::CannotDistribute
      # Not supported on redis-rb < 4, and hence Ruby < 2.2.
    end
  end

  it "passes through ring replica options" do
    dmr = Redis::DistributedStore.new [
                                    { :host => "localhost", :port => "6380", :db => 0 },
                                    { :host => "localhost", :port => "6381", :db => 0 }
                                ], replicas: 1024
    _(dmr.ring.replicas).must_equal 1024
  end

  it "uses a custom ring object" do
    my_ring = Redis::HashRing.new
    dmr = Redis::DistributedStore.new [
                                          { :host => "localhost", :port => "6380", :db => 0 },
                                          { :host => "localhost", :port => "6381", :db => 0 }
                                      ], ring: my_ring
    _(dmr.ring).must_equal my_ring
    _(dmr.ring.nodes.length).must_equal 2
  end

  describe '#redis_version' do
    it 'returns redis version' do
      @dmr.nodes.first.expects(:redis_version)
      @dmr.redis_version
    end
  end

  describe '#supports_redis_version?' do
    it 'returns redis version' do
      @dmr.nodes.first.expects(:supports_redis_version?).with('2.8.0')
      @dmr.supports_redis_version?('2.8.0')
    end
  end

  describe "namespace" do
    it "uses namespaced key" do
      @dmr = Redis::DistributedStore.new [
        { :host => "localhost", :port => "6380", :db => 0 },
        { :host => "localhost", :port => "6381", :db => 0 }
      ], :namespace => "theplaylist"

      @dmr.expects(:node_for).with("theplaylist:rabbit").returns(@dmr.nodes.first)
      @dmr.get "rabbit"
    end
  end
end


text:
package net.runelite.client.plugins.mta.enchantment;

import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import lombok.extern.slf4j.Slf4j;
import net.runelite.api.Client;
import net.runelite.api.GameState;
import net.runelite.api.ItemID;
import net.runelite.api.Player;
import net.runelite.api.Tile;
import net.runelite.api.TileItem;
import net.runelite.api.coords.WorldPoint;
import net.runelite.api.events.GameStateChanged;
import net.runelite.api.events.GameTick;
import net.runelite.api.events.ItemDespawned;
import net.runelite.api.events.ItemSpawned;
import net.runelite.client.eventbus.Subscribe;
import net.runelite.client.plugins.mta.MTAConfig;
import net.runelite.client.plugins.mta.MTARoom;

@Slf4j
public class EnchantmentRoom extends MTARoom
{
	private static final int MTA_ENCHANT_REGION = 13462;

	private final Client client;
	private final List<WorldPoint> dragonstones = new ArrayList<>();
	private boolean hintSet;

	@Inject
	private EnchantmentRoom(MTAConfig config, Client client)
	{
		super(config);
		this.client = client;
	}

	@Subscribe
	public void onGameStateChanged(GameStateChanged gameStateChanged)
	{
		if (gameStateChanged.getGameState() == GameState.LOADING)
		{
			dragonstones.clear();
			if (hintSet)
			{
				client.clearHintArrow();
				hintSet = false;
			}
		}
	}

	@Subscribe
	public void onGameTick(GameTick event)
	{
		if (!inside() || !config.enchantment())
		{
			return;
		}

		WorldPoint nearest = findNearestStone();
		if (nearest != null)
		{
			client.setHintArrow(nearest);
			hintSet = true;
		}
		else
		{
			client.clearHintArrow();
			hintSet = false;
		}
	}

	private WorldPoint findNearestStone()
	{
		WorldPoint nearest = null;
		double dist = Double.MAX_VALUE;
		WorldPoint local = client.getLocalPlayer().getWorldLocation();
		for (WorldPoint worldPoint : dragonstones)
		{
			double currDist = local.distanceTo(worldPoint);
			if (nearest == null || currDist < dist)
			{
				dist = currDist;
				nearest = worldPoint;
			}
		}
		return nearest;
	}

	@Subscribe
	public void onItemSpawned(ItemSpawned itemSpawned)
	{
		final TileItem item = itemSpawned.getItem();
		final Tile tile = itemSpawned.getTile();

		if (item.getId() == ItemID.DRAGONSTONE_6903)
		{
			WorldPoint location = tile.getWorldLocation();
			log.debug("Adding dragonstone at {}", location);
			dragonstones.add(location);
		}
	}

	@Subscribe
	public void onItemDespawned(ItemDespawned itemDespawned)
	{
		final TileItem item = itemDespawned.getItem();
		final Tile tile = itemDespawned.getTile();

		if (item.getId() == ItemID.DRAGONSTONE_6903)
		{
			WorldPoint location = tile.getWorldLocation();
			log.debug("Removed dragonstone at {}", location);
			dragonstones.remove(location);
		}
	}

	@Override
	public boolean inside()
	{
		Player player = client.getLocalPlayer();
		return player != null && player.getWorldLocation().getRegionID() == MTA_ENCHANT_REGION
			&& player.getWorldLocation().getPlane() == 0;
	}
}


text:
from gym.spaces import Space
from typing import List, Optional, Union, TYPE_CHECKING

from ray.rllib.models.action_dist import ActionDistribution
from ray.rllib.models.modelv2 import ModelV2
from ray.rllib.policy.sample_batch import SampleBatch
from ray.rllib.utils.annotations import DeveloperAPI
from ray.rllib.utils.framework import try_import_torch, TensorType
from ray.rllib.utils.typing import LocalOptimizer, TrainerConfigDict

if TYPE_CHECKING:
    from ray.rllib.policy.policy import Policy

_, nn = try_import_torch()

@DeveloperAPI
class Exploration:
    """Implements an exploration strategy for Policies.

    An Exploration takes model outputs, a distribution, and a timestep from
    the agent and computes an action to apply to the environment using an
    implemented exploration schema.
    """

    def __init__(self, action_space: Space, *, framework: str,
                 policy_config: TrainerConfigDict, model: ModelV2,
                 num_workers: int, worker_index: int):
        """
        Args:
            action_space (Space): The action space in which to explore.
            framework (str): One of "tf" or "torch".
            policy_config (TrainerConfigDict): The Policy's config dict.
            model (ModelV2): The Policy's model.
            num_workers (int): The overall number of workers used.
            worker_index (int): The index of the worker using this class.
        """
        self.action_space = action_space
        self.policy_config = policy_config
        self.model = model
        self.num_workers = num_workers
        self.worker_index = worker_index
        self.framework = framework
        # The device on which the Model has been placed.
        # This Exploration will be on the same device.
        self.device = None
        if isinstance(self.model, nn.Module):
            params = list(self.model.parameters())
            if params:
                self.device = params[0].device

    @DeveloperAPI
    def before_compute_actions(
            self,
            *,
            timestep: Optional[Union[TensorType, int]] = None,
            explore: Optional[Union[TensorType, bool]] = None,
            tf_sess: Optional["tf.Session"] = None,
            **kwargs):
        """Hook for preparations before policy.compute_actions() is called.

        Args:
            timestep (Optional[Union[TensorType, int]]): An optional timestep
                tensor.
            explore (Optional[Union[TensorType, bool]]): An optional explore
                boolean flag.
            tf_sess (Optional[tf.Session]): The tf-session object to use.
            **kwargs: Forward compatibility kwargs.
        """
        pass

    @DeveloperAPI
    def get_exploration_action(self,
                               *,
                               action_distribution: ActionDistribution,
                               timestep: Union[TensorType, int],
                               explore: bool = True):
        """Returns a (possibly) exploratory action and its log-likelihood.

        Given the Model's logits outputs and action distribution, returns an
        exploratory action.

        Args:
            action_distribution (ActionDistribution): The instantiated
                ActionDistribution object to work with when creating
                exploration actions.
            timestep (Union[TensorType, int]): The current sampling time step.
                It can be a tensor for TF graph mode, otherwise an integer.
            explore (Union[TensorType, bool]): True: "Normal" exploration
                behavior. False: Suppress all exploratory behavior and return
                a deterministic action.

        Returns:
            Tuple:
            - The chosen exploration action or a tf-op to fetch the exploration
              action from the graph.
            - The log-likelihood of the exploration action.
        """
        pass

    @DeveloperAPI
    def on_episode_start(self,
                         policy,
                         *,
                         environment=None,
                         episode=None,
                         tf_sess=None):
        """Handles necessary exploration logic at the beginning of an episode.

        Args:
            policy (Policy): The Policy object that holds this Exploration.
            environment (BaseEnv): The environment object we are acting in.
            episode (int): The number of the episode that is starting.
            tf_sess (Optional[tf.Session]): In case of tf, the session object.
        """
        pass

    @DeveloperAPI
    def on_episode_end(self,
                       policy,
                       *,
                       environment=None,
                       episode=None,
                       tf_sess=None):
        """Handles necessary exploration logic at the end of an episode.

        Args:
            policy (Policy): The Policy object that holds this Exploration.
            environment (BaseEnv): The environment object we are acting in.
            episode (int): The number of the episode that is starting.
            tf_sess (Optional[tf.Session]): In case of tf, the session object.
        """
        pass

    @DeveloperAPI
    def postprocess_trajectory(self,
                               policy: "Policy",
                               sample_batch,
                               tf_sess=None):
        """Handles post-processing of done episode trajectories.

        Changes the given batch in place. This callback is invoked by the
        sampler after policy.postprocess_trajectory() is called.

        Args:
            policy (Policy): The owning policy object.
            sample_batch (SampleBatch): The SampleBatch object to post-process.
            tf_sess (Optional[tf.Session]): An optional tf.Session object.
        """
        return sample_batch

    @DeveloperAPI
    def get_exploration_optimizer(self, optimizers: List[LocalOptimizer]):
        """May add optimizer(s) to the Policy's own `optimizers`.

        The number of optimizers (Policy's plus Exploration's optimizers) must
        match the number of loss terms produced by the Policy's loss function
        and the Exploration component's loss terms.

        Args:
            optimizers (List[LocalOptimizer]): The list of the Policy's
                local optimizers.

        Returns:
            List[LocalOptimizer]: The updated list of local optimizers to use
                on the different loss terms.
        """
        return optimizers

    @DeveloperAPI
    def get_exploration_loss(self, policy_loss: List[TensorType],
                             train_batch: SampleBatch):
        """May add loss term(s) to the Policy's own loss(es).

        Args:
            policy_loss (List[TensorType]): Loss(es) already calculated by the
                Policy's own loss function and maybe the Model's custom loss.
            train_batch (SampleBatch): The training data to calculate the
                loss(es) for. This train data has already gone through
                this Exploration's `preprocess_train_batch()` method.

        Returns:
            List[TensorType]: The updated list of loss terms.
                This may be the original Policy loss(es), altered, and/or new
                loss terms added to it.
        """
        return policy_loss

    @DeveloperAPI
    def get_info(self, sess=None):
        """Returns a description of the current exploration state.

        This is not necessarily the state itself (and cannot be used in
        set_state!), but rather useful (e.g. debugging) information.

        Args:
            sess (Optional[tf.Session]): An optional tf Session object to use.

        Returns:
            dict: A description of the Exploration (not necessarily its state).
                This may include tf.ops as values in graph mode.
        """
        return {}


text:
<head>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="{{ site.description }}">
	<link rel="shortcut icon" href="{{ "/img/favicon.ico" | prepend: site.baseurl }}">

    <title>{% if page.title %}{{ page.title }} - {{ site.title }}{% else %}{{ site.title }}{% endif %}</title>

    <link rel="canonical" href="{{ page.url | replace:'index.html','' | prepend: site.baseurl | prepend: site.url }}">

    <!-- Bootstrap Core CSS -->
    <link rel="stylesheet" href="{{ "/css/bootstrap.min.css" | prepend: site.baseurl }}">

    <!-- Custom CSS -->
    <link rel="stylesheet" href="{{ "/css/clean-blog.css" | prepend: site.baseurl }}">

    <!-- Pygments Github CSS -->
    <link rel="stylesheet" href="{{ "/css/syntax.css" | prepend: site.baseurl }}">

    <!-- Custom Fonts -->
    <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href='//fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
    <link href='//fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>

    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
        <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
        <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->
    <!-- baidu analyze -->
    <script>
	var _hmt = _hmt || [];
	(function() {
	  var hm = document.createElement("script");
	  hm.src = "//hm.baidu.com/hm.js?7068b1fbc824972f73bae59d1842763c";
	  var s = document.getElementsByTagName("script")[0];
	  s.parentNode.insertBefore(hm, s);
	})();
	</script>

</head>


text:
..  _PostMessage:

Using PostMessage to interact with the |wac| application iframe
===============================================================

..  spelling::

    msg
    ui
    wdUserSession

..  default-domain:: js

You can integrate your own UI into Office Online applications. This way, you can use your UI for actions on Office
documents, such as sharing.

To integrate with Office Online in this way, implement the
`HTML5 Web Messaging protocol <http://www.w3.org/TR/webmessaging/>`_. The Web Messaging protocol,
also known as PostMessage, allows the |wac| frame to communicate with its parent :term:`host page`, and
vice-versa. The following example shows the general syntax for PostMessage. In this example, ``otherWindow`` is a
reference to another window that ``msg`` will be posted to.

..  function:: otherWindow.postMessage(msg, targetOrigin)

    :param string msg: A string (or JSON object) that contains the message
        data.
    :param string targetOrigin: Specifies what the origin of ``otherWindow`` must be for the event to be dispatched.
        This value will be set to the :term:`PostMessageOrigin` property provided in :ref:`CheckFileInfo`. The literal
        string ``*``, while supported in the PostMessage protocol, is not allowed by Office Online.

Message format
--------------

All messages posted to and from the Office Online application frame are posted using the
:func:`~otherWindow.postMessage` function. Each message (the ``msg`` parameter in the
:func:`~otherWindow.postMessage` function) is a JSON-formatted object of the form:

..  data:: message

    **MessageId** *(string)*
        The name of the message being posted.
    **SendTime** *(long)*
        The time the message was sent, expressed as milliseconds since
        midnight 1 January 1970 UTC.

        ..  tip:: You can get this value in most modern browsers using the ``Date.now()`` method in JavaScript.

    **Values** *(JSON-formatted object)*
        The data associated with the message. This varies per message.

The following example shows the msg parameter for the :data:`Host_PerfTiming` message.

..  code-block:: JSON

    {
        "MessageId": "Host_PerfTiming",
        "SendTime": 1329014075000,
        "Values": {
            "Click": 1329014074800,
            "Iframe": 1329014074950,
            "HostFrameFetchStart": 1329014074970,
            "RedirectCount": 1
        }
    }

Sending messages to the Office Online iframe
--------------------------------------------

To send messages to the Office Online iframe, you must set the PostMessageOrigin property in your WOPI CheckFileInfo
response to the URL of your host page. If you do not do this, Office Online will ignore any messages you send to its
iframe.

You can send the following messages; all others are ignored:

* :data:`Blur_Focus`
* :data:`Grab_Focus`
* :data:`Host_PerfTiming`
* :data:`Host_PostmessageReady`

..  data:: Blur_Focus

    The Blur_Focus message signals the Office Online application to stop aggressively grabbing focus. Hosts should
    send this message whenever the host application UI is drawn over the Office Online frame, so that the Office
    application does not interfere with the UI behavior of the host.

    This message only affects Office Online edit modes; it does not affect view modes.

    ..  tip::
        When the host application displays UI over Office Online, it should put a full-screen dimming effect over the
        Office Online UI, so that it is clear that the Office application is not interactive.

    ..  attribute:: Values
        :noindex:

        *Empty.*

    ..  rubric:: Example Message:

    ..  code-block:: JSON

        {
            "MessageId": "Blur_Focus",
            "SendTime": 1329014075000,
            "Values": { }
        }

..  data:: Grab_Focus

    The Grab_Focus message signals the Office Online application to resume aggressively grabbing focus. Hosts should
    send this message whenever the host application UI that is drawn over the Office Online frame is closing. This
    allows the Office application to resume functioning.

    This message only affects Office Online edit modes; it does not affect view modes.

    ..  attribute:: Values
        :noindex:

        *Empty.*

    ..  rubric:: Example Message:

    ..  code-block:: JSON

        {
            "MessageId": "Grab_Focus",
            "SendTime": 1329014075000,
            "Values": { }
        }

..  data:: Host_PerfTiming

    Provides performance related timestamps from the host page. Hosts should send this message when the Office
    Online frame is created so load performance can be more accurately tracked.

    ..  attribute:: Values
        :noindex:

        **Click** *(integer)*
            The timestamp, in ticks, when the user selected a link that launched the Office Online application. For
            example, if the host exposed a link in its UI that launches an Office Online application, this timestamp
            is the time the user originally selected that link.

        **Iframe** *(integer)*
            The timestamp, in ticks, when the host created the Office Online iframe when the user selected the link.

        **HostFrameFetchStart** *(integer)*
            The result of the `PerformanceTiming.fetchStart`_ attribute, if the browser supports the
            `W3C NavigationTiming API`_. If the NavigationTiming API is not supported by the browser, this is 0.

        **RedirectCount** *(integer)*
            The result of the `PerformanceNavigation.redirectCount`_ attribute, if the browser supports the
            `W3C NavigationTiming API`_. If the NavigationTiming API is not supported by the browser, this is 0.

.. _W3C NavigationTiming API: http://www.w3.org/TR/navigation-timing/
.. _PerformanceTiming.fetchStart: http://www.w3.org/TR/navigation-timing/#dom-performancetiming-fetchstart
.. _PerformanceNavigation.redirectCount: http://www.w3.org/TR/navigation-timing/#dom-performancenavigation-redirectcount

    ..  rubric:: Example Message:

    ..  code-block:: JSON

        {
            "MessageId": "Host_PerfTiming",
            "SendTime": 1329014075000,
            "Values": {
                "Click": 1329014074800,
                "Iframe": 1329014074950,
                "HostFrameFetchStart": 1329014074970,
                "RedirectCount": 1
            }
        }

..  data:: Host_PostmessageReady

    Office Online delay-loads much of its JavaScript code, including most of its PostMessage senders and listeners.
    You might choose to follow this pattern in your WOPI host page. This means that your outer host page and the
    Office Online iframe must coordinate to ensure that each is ready to receive and respond to messages.

    To enable this coordination, Office Online sends the :data:`App_LoadingStatus` message only after all of its message
    senders and listeners are available. In addition, Office Online listens for the :data:`Host_PostmessageReady`
    message from the outer frame. Until it receives this message, some UI, such as the **Share** button, is disabled.

    Until your host page receives the :data:`App_LoadingStatus` message, the Office Online frame cannot respond to any
    incoming messages except :data:`Host_PostmessageReady`. Office Online does not delay-load its
    :data:`Host_PostmessageReady` listener; it is available almost immediately upon iframe load.

    If you are delay-loading your PostMessage code, you must ensure that your :data:`App_LoadingStatus` listener is not
    delay-loaded. This will ensure that you can receive the :data:`App_LoadingStatus` message even if your other
    PostMessage code has not yet loaded.

    The following is the typical flow:

    1. Host page begins loading.
    2. Office Online frame begins loading. Some UI elements are disabled, because :data:`Host_PostmessageReady` has
       not yet been sent by the host page.
    3. Host page finishes loading and sends :data:`Host_PostmessageReady`. No other messages are sent because the
       host page hasn't received the :data:`App_LoadingStatus` message from the Office Online frame.
    4. Office Online frame receives :data:`Host_PostmessageReady`.
    5. Office Online frame finishes loading and sends :data:`App_LoadingStatus` to host page.
    6. Host page and Office Online communicate by using other PostMessage messages.

    ..  attribute:: Values
        :noindex:

        *Empty.*

    ..  rubric:: Example Message:

    ..  code-block:: JSON

        {
            "MessageId": "Host_PostmessageReady",
            "SendTime": 1329014075000,
            "Values": { }
        }

Listening to messages from the Office Online iframe
---------------------------------------------------

The Office Online iframe will send messages to the host page. On the receiving end, the host page will receive a
MessageEvent. The origin property of the MessageEvent is the origin of the message, and the data property is the
message being sent. The following code example shows how you might consume a message.

.. code-block:: javascript

    function handlePostMessage(e) {
        // The actual message is contained in the data property of the event.
        var msg = JSON.parse(e.data);

        // The message ID is now a property of the message object.
        var msgId = msg.MessageId;

        // The message parameters themselves are in the Values
        // parameter on the message object.
        var msgData = msg.Values;

        // Do something with the message here.
    }
    window.addEventListener('message', handlePostMessage, false);

The host page receives the following messages; all others are ignored:

* :data:`App_LoadingStatus`
* :data:`Edit_Notification`
* :data:`File_Rename`
* :data:`UI_Close`
* :data:`UI_Edit`
* :data:`UI_Sharing`
* :data:`UI_Workflow`

..  _outgoing postmessage common values:

Common Values
~~~~~~~~~~~~~

In addition to message-specific values passed with each message, Office Online sends the following common values with
every outgoing PostMessage:

..  glossary::
    :sorted:

    ui-language *(string)*
        The LCID of the language Office Online was loaded in. This value will not match the value provided using the
        :term:`UI_LLCC` placeholder. Instead, this value will be the numeric LCID value (as a *string*) that
        corresponds to the language used. See :ref:`languages` for more information.

        This value may be needed in the event that Office Online renders using a language different than the one
        requested by the host, which may occur if Office Online is not localized in the language requested. In that
        case, the host may choose to draw its own UI in the same language that Office Online used.

    wdUserSession *(string)*
        The ID of the Office Online session. This value can be logged by host and used when
        :ref:`troubleshooting <troubleshooting>` issues with Office Online. See :ref:`session id` for more
        information about this value.

..  data:: App_LoadingStatus

    The App_LoadingStatus message is posted after the Office Online application frame has loaded. Until the host
    receives this message, it must assume that the Office Online frame cannot react to any incoming messages except
    :data:`Host_PostmessageReady`.

    ..  attribute:: Values
        :noindex:

        DocumentLoadedTime *(long)*
            The time that the frame was loaded.

    ..  rubric:: Example Message:

    ..  code-block:: JSON

        {
            "MessageId": "App_LoadingStatus",
            "SendTime": 1329014075000,
            "Values": {
                "DocumentLoadedTime": 1329014074983,
                "wdUserSession": "3692f636-2add-4b64-8180-42e9411c4984",
                "ui-language": "en-us"
            }
        }

..  data:: Edit_Notification

    The Edit_Notification message is posted when the user first makes an edit to a document, and every five minutes
    thereafter, if the user has made edits in the last five minutes. Hosts can use this message to gauge whether
    users are interacting with Office Online. In coauthoring sessions, hosts cannot use the WOPI calls for
    this purpose.

    To send this message, the :term:`EditNotificationPostMessage` property in the :ref:`CheckFileInfo` response from
    the host must be set to ``true``. Otherwise Office Online will not send this message.

    ..  attribute:: Values
        :noindex:

        :ref:`Common values <outgoing postmessage common values>` only.

    ..  rubric:: Example Message:

    ..  code-block:: JSON

        {
            "MessageId": "Edit_Notification",
            "SendTime": 1329014075000,
            "Values": {
                "wdUserSession": "3692f636-2add-4b64-8180-42e9411c4984",
                "ui-language": "en-us"
            }
        }

..  data:: File_Rename

    The File_Rename message is posted when the user renames the current file in Office Online. The host can use this
    message to optionally update the UI, such as the title of the page.

    ..  note::
        If the host does not return the :term:`SupportsRename` parameter in their :ref:`CheckFileInfo` response, then
        the rename UI will not be available in Office Online.

    ..  attribute:: Values
        :noindex:

        NewName *(string)*
            The new name of the file.

    ..  rubric:: Example Message:

    ..  code-block:: JSON

        {
            "MessageId": "File_Rename",
            "SendTime": 1329014075000,
            "Values": {
                "NewName": "Renamed Document",
                "wdUserSession": "3692f636-2add-4b64-8180-42e9411c4984",
                "ui-language": "en-us"
            }
        }

..  data:: UI_Close

    The UI_Close message is posted when the Office Online application is closing, either due to an error or a user
    action. Typically, the URL specified in the :term:`CloseUrl` property in the :ref:`CheckFileInfo` response is
    displayed. However, hosts can intercept this message instead and navigate in an appropriate way.

    To send this message, the :term:`ClosePostMessage` property in the :ref:`CheckFileInfo` response from the host
    must be set to ``true``. Otherwise Office Online will not send this message.

    ..  attribute:: Values
        :noindex:

        :ref:`Common values <outgoing postmessage common values>` only.

    ..  rubric:: Example Message:

    ..  code-block:: JSON

        {
            "MessageId": "UI_Close",
            "SendTime": 1329014075000,
            "Values": {
                "wdUserSession": "3692f636-2add-4b64-8180-42e9411c4984",
                "ui-language": "en-us"
            }
        }

..  data:: UI_Edit

    The UI_Edit message is posted when the user activates the *Edit* UI in Office Online. This UI is only visible
    when using the :wopi:action:`view` action.

    To send this message, the :term:`EditModePostMessage` property in the :ref:`CheckFileInfo` response from the host
    must be set to ``true``. Otherwise Office Online will not send this message and will redirect the inner iframe to
    an edit action URL instead.

    Hosts may choose to use this message in cases where they want more control over the user's transition to edit
    mode. For example, a host may wish to prompt the user for some additional host-specific information before
    navigating.

    ..  attribute:: Values
        :noindex:

        :ref:`Common values <outgoing postmessage common values>` only.

    ..  rubric:: Example Message:

    ..  code-block:: JSON

        {
            "MessageId": "UI_Edit",
            "SendTime": 1329014075000,
            "Values": {
                "wdUserSession": "3692f636-2add-4b64-8180-42e9411c4984",
                "ui-language": "en-us"
            }
        }

..  data:: UI_Sharing

    The UI_Sharing message is posted when the user activates the *Share* UI in Office Online. The host should use this
    message to trigger any custom sharing UI.

    To send this message, the :term:`FileSharingPostMessage` property in the :ref:`CheckFileInfo` response from the
    host must be set to ``true``. Otherwise Office Online will not send this message.

    ..  attribute:: Values
        :noindex:

        :ref:`Common values <outgoing postmessage common values>` only.

    ..  rubric:: Example Message:

    ..  code-block:: JSON

        {
            "MessageId": "UI_Sharing",
            "SendTime": 1329014075000,
            "Values": {
                "wdUserSession": "3692f636-2add-4b64-8180-42e9411c4984",
                "ui-language": "en-us"
            }
        }

..  data:: UI_Workflow

    The UI_Workflow message is posted when the user activates the *Workflow* UI in Office Online. The host should use
    this message to trigger any custom workflow UI.

    To send this message, the :term:`WorkflowPostMessage` property in the :ref:`CheckFileInfo` response from the
    host must be set to ``true``. Otherwise Office Online will not send this message.

    ..  attribute:: Values
        :noindex:

        WorkflowType *(string)*
            The :term:`WorkflowType` associated with the message. This will match one of the values provided by the
            host in the :term:`WorkflowType` property in :ref:`CheckFileInfo`.

    ..  rubric:: Example Message:

    ..  code-block:: JSON

        {
            "MessageId": "UI_Workflow",
            "SendTime": 1329014075000,
            "Values": {
                "WorkflowType": "Submit",
                "wdUserSession": "3692f636-2add-4b64-8180-42e9411c4984",
                "ui-language": "en-us"
            }
        }


text:
follow
======

Fody Addin, API, and tooling for tracking processes


text:
<?xml version="1.0"?>
<Document>

	<Sentence>
		<value>You can still do normal activities, such as traveling, playing sports, swimming, doing things with your family, and working.</value>
		<pattern_crowdsource> You can still do normal activities, such as traveling, playing [[sports|C0038039]], [[swimming|C0039003]], doing things with your family, and working.		</pattern_crowdsource>
		<annotations>
			<annotation>
				<surface-form>normal</surface-form>
				<RDF-ID>C0205307</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>activities</surface-form>
				<RDF-ID>C0441655</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>traveling</surface-form>
				<RDF-ID>C0040802</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>sports</surface-form>
				<RDF-ID>C0038039</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>swimming</surface-form>
				<RDF-ID>C0039003</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>family</surface-form>
				<RDF-ID>C0015576</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>working</surface-form>
				<RDF-ID>C0043227</RDF-ID>
			</annotation>
		</annotations>
		<triples>
			<triple>C0039003 ISA C0038039</triple>
		</triples>
	</Sentence>
	<Sentence>
		<value>A continent ileostomy is a different type of ileostomy.</value>
		<pattern_crowdsource> A [[continent ileostomy|C0023985]] is a different type of [[ileostomy|C0020883]].		</pattern_crowdsource>
		<annotations>
			<annotation>
				<surface-form>continent ileostomy</surface-form>
				<RDF-ID>C0023985</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>different</surface-form>
				<RDF-ID>C1547020</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>type</surface-form>
				<RDF-ID>C1547052</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>ileostomy</surface-form>
				<RDF-ID>C0020883</RDF-ID>
			</annotation>
		</annotations>
		<triples>
			<triple>C0023985 ISA C0020883</triple>
		</triples>
	</Sentence>

</Document>


text:
name          = 'murmur'
log_path      = ::File.join(node[:central][:log], name)
logfile_path  = ::File.join(log_path, "#{name}.log")
ssl_cert_path = ::File.join('/etc/ssl/certs', "#{name}.crt")
ssl_key_path  = ::File.join('/etc/ssl', "#{name}.key")

log 'Ensuring Murmur log directory...'
directory log_path do
  owner 'root'
  group 'mumble-server'
  mode '0755'
end

log 'Configuring Murmur...'
template '/etc/mumble-server.ini' do
  source "mumble-server.ini.erb"
  variables({
    logfile_path: logfile_path,
    password: node[name][:password],
    ssl_cert_path: ssl_cert_path,
    ssl_key_path: ssl_key_path,
  })
  owner 'root'
  group 'mumble-server'
  mode '0644'
end

if node[name][:ssl_cert].to_s != ''

  log "Installing SSL certificate for #{name}..."

  file ssl_cert_path do
    owner 'root'
    group 'mumble-server'
    content node[name][:ssl_cert]
    mode '0644'
  end

  file ssl_key_path do
    owner 'root'
    group 'mumble-server'
    content node[name][:ssl_key]
    mode '0640'
  end

end


text:
package banman

// Reason includes the different possible reasons which caused us to ban a peer.
type Reason uint8

// We prevent using `iota` to ensure the order does not have the value since
// these are serialized within the database.
const (
	// ExcedeedBanThreshold signals that a peer exceeded its ban threshold.
	ExceededBanThreshold Reason = 1

	// NoCompactFilters signals that a peer was unable to serve us compact
	// filters.
	NoCompactFilters Reason = 2

	// InvalidFilterHeader signals that a peer served us an invalid filter
	// header.
	InvalidFilterHeader Reason = 3

	// InvalidFilterHeaderCheckpoint signals that a peer served us an
	// invalid filter header checkpoint.
	InvalidFilterHeaderCheckpoint Reason = 4
)

// String returns a human-readable description for the reason a peer was banned.
func (r Reason) String() string {
	switch r {
	case ExceededBanThreshold:
		return "peer exceeded ban threshold"

	case NoCompactFilters:
		return "peer was unable to serve compact filters"

	case InvalidFilterHeader:
		return "peer served invalid filter header"

	case InvalidFilterHeaderCheckpoint:
		return "peer served invalid filter header checkpoint"

	default:
		return "unknown reason"
	}
}


text:
import {
  CancelResponse,
  ContinueResponse,
  ParametersGatherer
} from '@salesforce/salesforcedx-utils-vscode';
import {
  ComponentSet,
  registry,
  SourceComponent
} from '@salesforce/source-deploy-retrieve';
import { expect } from 'chai';
import * as path from 'path';
import { join } from 'path';
import * as sinon from 'sinon';
import { window } from 'vscode';
import * as vscode from 'vscode';
import {
  CommandletExecutor,
  CompositeParametersGatherer,
  DemoModePromptGatherer,
  EmptyParametersGatherer,
  FileSelection,
  FileSelector,
  SelectOutputDir,
  SfdxCommandlet,
  SimpleGatherer
} from '../../../../src/commands/util';
import {
  PromptConfirmGatherer,
  SelectLwcComponentDir
} from '../../../../src/commands/util/parameterGatherers';
import { nls } from '../../../../src/messages';
import { SfdxPackageDirectories } from '../../../../src/sfdxProject';
import { workspaceUtils } from '../../../../src/util';

const SFDX_SIMPLE_NUM_OF_DIRS = 16;

// tslint:disable:no-unused-expression
describe('Parameter Gatherers', () => {
  describe('EmptyParametersGatherer', () => {
    it('Should always return continue with empty object as data', async () => {
      const gatherer = new EmptyParametersGatherer();
      const response = await gatherer.gather();
      expect(response.type).to.be.eql('CONTINUE');

      const continueResponse = response as ContinueResponse<{}>;
      expect(continueResponse.data).to.be.eql({});
    });
  });

  describe('CompositeParametersGatherer', () => {
    it('Should proceed to next gatherer if previous gatherer in composite gatherer is CONTINUE', async () => {
      const compositeParameterGatherer = new CompositeParametersGatherer(
        new (class implements ParametersGatherer<{}> {
          public async gather(): Promise<
            CancelResponse | ContinueResponse<{}>
          > {
            return { type: 'CONTINUE', data: {} };
          }
        })(),
        new (class implements ParametersGatherer<{}> {
          public async gather(): Promise<
            CancelResponse | ContinueResponse<{}>
          > {
            return { type: 'CONTINUE', data: {} };
          }
        })()
      );

      const response = await compositeParameterGatherer.gather();
      expect(response.type).to.equal('CONTINUE');
    });

    it('Should not proceed to next gatherer if previous gatherer in composite gatherer is CANCEL', async () => {
      const compositeParameterGatherer = new CompositeParametersGatherer(
        new (class implements ParametersGatherer<{}> {
          public async gather(): Promise<
            CancelResponse | ContinueResponse<{}>
          > {
            return { type: 'CANCEL' };
          }
        })(),
        new (class implements ParametersGatherer<{}> {
          public async gather(): Promise<
            CancelResponse | ContinueResponse<{}>
          > {
            throw new Error('This should not be called');
          }
        })()
      );

      await compositeParameterGatherer.gather();
    });

    it('Should call executor if composite gatherer is CONTINUE', async () => {
      let executed = false;
      const commandlet = new SfdxCommandlet(
        new (class {
          public check(): boolean {
            return true;
          }
        })(),
        new CompositeParametersGatherer(
          new (class implements ParametersGatherer<{}> {
            public async gather(): Promise<
              CancelResponse | ContinueResponse<{}>
            > {
              return { type: 'CONTINUE', data: {} };
            }
          })()
        ),
        new (class implements CommandletExecutor<{}> {
          public execute(response: ContinueResponse<{}>): void {
            executed = true;
          }
        })()
      );

      await commandlet.run();

      expect(executed).to.be.true;
    });

    it('Should not call executor if composite gatherer is CANCEL', async () => {
      const commandlet = new SfdxCommandlet(
        new (class {
          public check(): boolean {
            return true;
          }
        })(),
        new CompositeParametersGatherer(
          new (class implements ParametersGatherer<{}> {
            public async gather(): Promise<
              CancelResponse | ContinueResponse<{}>
            > {
              return { type: 'CANCEL' };
            }
          })()
        ),
        new (class implements CommandletExecutor<{}> {
          public execute(response: ContinueResponse<{}>): void {
            throw new Error('This should not be called');
          }
        })()
      );

      await commandlet.run();
    });
  });

  describe('FileSelectionGatherer', () => {
    const displayMessage = 'My sample info';
    const errorMessage = 'You hit an error!';
    const gatherer = new FileSelector(
      displayMessage,
      errorMessage,
      'config/**/*-scratch-def.json'
    );
    let showQuickPickStub: sinon.SinonStub;
    let notificationStub: sinon.SinonStub;
    let fileFinderStub: sinon.SinonStub;

    beforeEach(() => {
      showQuickPickStub = sinon.stub(vscode.window, 'showQuickPick');
      notificationStub = sinon.stub(vscode.window, 'showErrorMessage');
      fileFinderStub = sinon.stub(vscode.workspace, 'findFiles');
    });

    afterEach(() => {
      showQuickPickStub.restore();
      notificationStub.restore();
      fileFinderStub.restore();
    });

    it('Should return continue if file has been selected', async () => {
      fileFinderStub.returns([
        vscode.Uri.file('/somepath/project-scratch-def.json')
      ]);
      showQuickPickStub.returns({
        label: 'project-scratch-def.json',
        description: '/somepath/project-scratch-def.json'
      });

      const response = (await gatherer.gather()) as ContinueResponse<
        FileSelection
      >;

      expect(showQuickPickStub.callCount).to.equal(1);
      expect(response.type).to.equal('CONTINUE');
      expect(response.data.file, 'project-scratch-def.json');
    });

    it('Should return cancel if no file was selected', async () => {
      fileFinderStub.returns([
        vscode.Uri.file('/somepath/project-scratch-def.json')
      ]);
      showQuickPickStub.returns(undefined);

      const response = await gatherer.gather();

      expect(showQuickPickStub.callCount).to.equal(1);
      expect(response.type).to.equal('CANCEL');
    });

    it('Should display error when no files are available for selection', async () => {
      fileFinderStub.returns(new Array());

      const response = await gatherer.gather();

      expect(response.type).to.equal('CANCEL');
      expect(notificationStub.calledOnce).to.be.true;
      expect(notificationStub.getCall(0).args[0]).to.equal(errorMessage);
    });
  });

  // Due to the way the prompt is phrased
  // CONTINUE means that we will execute the forceLogoutAll command
  // CANCEL means that we will not execute the forceLogoutAll command
  describe('DemoModePrompGatherer', () => {
    let showInformationMessageStub: sinon.SinonStub;

    before(() => {
      showInformationMessageStub = sinon.stub(window, 'showInformationMessage');
    });

    after(() => {
      showInformationMessageStub.restore();
    });

    it('Should return CONTINUE if message is Cancel', async () => {
      showInformationMessageStub.onFirstCall().returns('Cancel');
      const gatherer = new DemoModePromptGatherer();
      const result = await gatherer.gather();
      expect(result.type).to.equal('CONTINUE');
      expect((result as ContinueResponse<{}>).data!).to.eql({});
    });

    it('Should return CANCEL if message is Authorize Org', async () => {
      showInformationMessageStub.onFirstCall().returns('Cancel');
      const gatherer = new DemoModePromptGatherer();
      const result = await gatherer.gather();
      expect(result.type).to.equal('CANCEL');
    });
  });

  describe('SelectOutputDir', () => {
    const packageDirs = ['force-app'];

    it('Should correctly build default menu options', async () => {
      const selector = new SelectOutputDir('test');
      const options = selector.getDefaultOptions(['testapp', 'testapp2']);

      expect(options).to.eql([
        join('testapp', SelectOutputDir.defaultOutput, 'test'),
        join('testapp2', SelectOutputDir.defaultOutput, 'test'),
        SelectOutputDir.customDirOption
      ]);
    });

    it('Should generate correct number of custom options for a workspace', async () => {
      const selector = new SelectOutputDir('test');
      const options = selector.getCustomOptions(
        packageDirs,
        workspaceUtils.getRootWorkspacePath()
      );
      expect(options.length).to.be.equal(SFDX_SIMPLE_NUM_OF_DIRS);
    });

    it('Should correctly append type folder to paths for type that requires specific parent folder', () => {
      const selector = new SelectOutputDir('aura', true);
      const options = selector.getCustomOptions(
        packageDirs,
        workspaceUtils.getRootWorkspacePath()
      );

      expect(
        options.every(outputDir => {
          // don't append the type name if the output dir already has that as its name
          return outputDir.endsWith('aura') && !outputDir.endsWith('aura/aura');
        })
      ).to.be.true;
    });

    it('Should gather paths from correct sources and prompt custom dir if chosen', async () => {
      const selector = new SelectOutputDir('test');
      const defaultOptions = selector.getDefaultOptions(packageDirs);
      const customOptions = selector.getCustomOptions(
        packageDirs,
        workspaceUtils.getRootWorkspacePath()
      );
      const getPackageDirPathsStub = sinon.stub(
        SfdxPackageDirectories,
        'getPackageDirectoryPaths'
      );
      const showMenuStub = sinon.stub(selector, 'showMenu');
      const choice = customOptions[5];
      getPackageDirPathsStub.returns(packageDirs);
      showMenuStub.onFirstCall().returns(SelectOutputDir.customDirOption);
      showMenuStub.onSecondCall().returns(choice);

      const response = await selector.gather();

      try {
        expect(showMenuStub.getCall(0).calledWith(defaultOptions)).to.be.true;
        expect(showMenuStub.getCall(1).calledWith(customOptions)).to.be.true;
        expect(response).to.eql({
          type: 'CONTINUE',
          data: { outputdir: choice }
        });
      } finally {
        getPackageDirPathsStub.restore();
        showMenuStub.restore();
      }
    });
  });
  describe('SelectLwcComponentDir', async () => {
    it('Should gather filepath and Lightning web component options', async () => {
      const selector = new SelectLwcComponentDir();
      const packageDirs = ['force-app'];
      const filePath = path.join('force-app', 'main', 'default', 'lwc', 'test');
      const component = SourceComponent.createVirtualComponent(
        {
          name: 'test',
          type: registry.types.lightningcomponentbundle,
          xml: path.join(filePath, 'test.js-meta.xml')
        },
        []
      );
      const mockComponents = new ComponentSet([component]);
      const getPackageDirPathsStub = sinon.stub(
        SfdxPackageDirectories,
        'getPackageDirectoryPaths'
      );
      const getLwcsStub = sinon.stub(ComponentSet, 'fromSource');
      getLwcsStub
        .withArgs(
          path.join(workspaceUtils.getRootWorkspacePath(), packageDirs[0])
        )
        .returns(mockComponents);
      const showMenuStub = sinon.stub(selector, 'showMenu');
      getPackageDirPathsStub.returns(packageDirs);
      const dirChoice = packageDirs[0];
      const componentChoice = component.fullName;
      showMenuStub.onFirstCall().returns(dirChoice);
      showMenuStub.onSecondCall().returns(componentChoice);

      const response = await selector.gather();
      try {
        expect(showMenuStub.getCall(0).calledWith(packageDirs)).to.be.true;
        expect(response).to.eql({
          type: 'CONTINUE',
          data: { outputdir: filePath, fileName: componentChoice }
        });
      } finally {
        getPackageDirPathsStub.restore();
        showMenuStub.restore();
        getLwcsStub.restore();
      }
    });

    it('Should gracefully cancel if LWC is not selected', async () => {
      const selector = new SelectLwcComponentDir();
      const packageDirs = ['force-app'];
      const filePath = path.join('force-app', 'main', 'default', 'lwc', 'test');
      const component = SourceComponent.createVirtualComponent(
        {
          name: 'test',
          type: registry.types.lightningcomponentbundle,
          xml: path.join(filePath, 'test.js-meta.xml')
        },
        []
      );
      const mockComponents = new ComponentSet([component]);
      const getPackageDirPathsStub = sinon.stub(
        SfdxPackageDirectories,
        'getPackageDirectoryPaths'
      );
      const getLwcsStub = sinon.stub(ComponentSet, 'fromSource');
      getLwcsStub
        .withArgs(
          path.join(workspaceUtils.getRootWorkspacePath(), packageDirs[0])
        )
        .returns(mockComponents);
      const showMenuStub = sinon.stub(selector, 'showMenu');
      getPackageDirPathsStub.returns(packageDirs);
      const dirChoice = packageDirs[0];
      showMenuStub.onFirstCall().returns(dirChoice);
      showMenuStub.onSecondCall().returns('');

      const response = await selector.gather();
      try {
        expect(response).to.eql({
          type: 'CANCEL'
        });
      } finally {
        getPackageDirPathsStub.restore();
        showMenuStub.restore();
        getLwcsStub.restore();
      }
    });
  });

  describe('SimpleGatherer', () => {
    it('Should gather input that was given into a ContinueResponse', async () => {
      const input = { a: 'a', b: true, c: 2 };
      const response = await new SimpleGatherer(input).gather();
      expect(response).to.eql({
        type: 'CONTINUE',
        data: input
      });
    });
  });

  describe('PromptConfirmGatherer', () => {
    it('Should return CONTINUE if confirmation to proceed is positive', async () => {
      const promptConfirm = new PromptConfirmGatherer('question');
      const showMenuStub = sinon.stub(promptConfirm, 'showMenu');
      const choice = nls.localize('parameter_gatherer_prompt_confirm_option');
      showMenuStub.onFirstCall().returns(choice);
      const response = await promptConfirm.gather();
      expect(response).to.eql({
        type: 'CONTINUE',
        data: {
          choice
        }
      });
    });

    it('Should return CANCEL if confirmation to proceed is negative', async () => {
      const promptConfirm = new PromptConfirmGatherer('question');
      const showMenuStub = sinon.stub(promptConfirm, 'showMenu');
      const choice = nls.localize('parameter_gatherer_prompt_cancel_option');
      showMenuStub.onFirstCall().returns(choice);
      const response = await promptConfirm.gather();
      expect(response).to.eql({
        type: 'CANCEL'
      });
    });
  });
});


text:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping
>
    <class
        name="edu.wustl.catissuecore.domain.SpecimenEventParameters"
        table="CATISSUE_SPECIMEN_EVENT_PARAM"
		lazy="true"
    >

    <cache usage="read-write" />

        <id
            name="id"
            column="IDENTIFIER"
            type="long"
            length="30"
            unsaved-value="null"
        >
            <generator class="native">
                <param name="sequence">CATISSUE_SPEC_EVENT_PARAM_SEQ</param>
              <!--
                  To add non XDoclet generator parameters, create a file named
                  hibernate-generator-params-SpecimenEventParameters.xml
                  containing the additional parameters and place it in your merge dir.
              -->
            </generator>
        </id>
   <many-to-one
            name="specimenCollectionGroup"
            class="edu.wustl.catissuecore.domain.SpecimenCollectionGroup"
            cascade="none"

            update="true"
            insert="true"
            column="SPECIMEN_COLL_GRP_ID"
        />
        <many-to-one
            name="specimen"
            class="edu.wustl.catissuecore.domain.AbstractSpecimen"
            cascade="none"
			lazy="false"
            update="true"
            insert="true"
            column="SPECIMEN_ID"
        />

        <property
            name="timestamp"
            type="timestamp"
            update="true"
            insert="true"
            column="EVENT_TIMESTAMP"
        />

        <many-to-one
            name="user"
            class="edu.wustl.catissuecore.domain.User"
            cascade="none"

            update="true"
            insert="true"
            column="USER_ID"
        />

        <property
            name="comment"
            type="string"
            update="true"
            insert="true"
            column="COMMENTS"
            length="500"
        />

         <property
            name="activityStatus"
            type="string"
            update="true"
            insert="true"
            column="ACTIVITY_STATUS"
            length="50"
        />

        <!--
            To add non XDoclet property mappings, create a file named
                hibernate-properties-SpecimenEventParameters.xml
            containing the additional properties and place it in your merge dir.
        -->

        <joined-subclass
            name="edu.wustl.catissuecore.domain.TransferEventParameters"
            table="CATISSUE_TRANSFER_EVENT_PARAM"
			lazy="true"
        >
            <key
                column="IDENTIFIER"
            />
        <property
            name="fromPositionDimensionOne"
            type="int"
            update="true"
            insert="true"
            column="FROM_POSITION_DIMENSION_ONE"
            length="30"
        />

        <property
            name="fromPositionDimensionTwo"
            type="int"
            update="true"
            insert="true"
            column="FROM_POSITION_DIMENSION_TWO"
            length="30"
        />

        <property
            name="toPositionDimensionOne"
            type="int"
            update="true"
            insert="true"
            column="TO_POSITION_DIMENSION_ONE"
            length="30"
        />

        <property
            name="toPositionDimensionTwo"
            type="int"
            update="true"
            insert="true"
            column="TO_POSITION_DIMENSION_TWO"
            length="30"
        />

        <many-to-one
            name="toStorageContainer"
            class="edu.wustl.catissuecore.domain.StorageContainer"
            cascade="none"

            update="true"
            insert="true"
            column="TO_STORAGE_CONTAINER_ID"
        />

        <many-to-one
            name="fromStorageContainer"
            class="edu.wustl.catissuecore.domain.StorageContainer"
            cascade="none"

            update="true"
            insert="true"
            column="FROM_STORAGE_CONTAINER_ID"
        />

        </joined-subclass>

        <joined-subclass
            name="edu.wustl.catissuecore.domain.DisposalEventParameters"
            table="CATISSUE_DISPOSAL_EVENT_PARAM"
			lazy="true"
        >
            <key
                column="IDENTIFIER"
            />
        <property
            name="reason"
            type="string"
            update="true"
            insert="true"
            column="REASON"
            length="255"
         />

        </joined-subclass>

    </class>

    <query name="fetchSpecimenEventParameterCollection">
    from edu.wustl.catissuecore.domain.SpecimenEventParameters
    where specimen.id = ? and (activityStatus is null or activityStatus != 'Disabled' )
	</query>

</hibernate-mapping>


text:
package squire.controllers;

import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.image.ImageView;
import javafx.stage.Modality;
import javafx.stage.Stage;
import squire.Main;
import squire.Networking.Request;
import squire.Networking.Response;
import squire.Users.PropertiesController;

import java.net.URL;
import java.util.ResourceBundle;

/**
 * Created by Domn on 4/4/2016.
 */
public class LogInDialogController implements Initializable
{
    @FXML
    private ImageView avatarImageView;
    @FXML
    private TextField usernameTextField;
    @FXML
    private PasswordField passwordPasswordField;
    @FXML
    private CheckBox keepMeLoggedInCheckBox;
    @FXML
    private Button cancelButton;
    @FXML
    private Button logInButton;
    @FXML
    private Hyperlink registerHyperlink;
    @FXML
    private Hyperlink forgotPasswordHyperlink;

    private Stage thisStage;
    private PropertiesController pc;

    @Override
    public void initialize(URL location, ResourceBundle resources)
    {
        // Perform any initialization steps here.
        pc = PropertiesController.getPropertiesController();
        usernameTextField.setText(pc.getProp("username"));
        passwordPasswordField.setText(pc.getProp("password"));

        String signIn = pc.getProp("signInCheckbox");
        if(signIn == null)
        {
            signIn = "";
        }
        if (signIn.equals("true"))
        {
            keepMeLoggedInCheckBox.setSelected(true);
        }
    }

    @FXML
    private void onCancelButtonClick(ActionEvent event)
    {
        thisStage = (Stage) cancelButton.getScene().getWindow();
        System.out.println("Cancel button clicked.");
        thisStage.close();
    }

    @FXML
    private void onLogInButtonClick(ActionEvent event)
    {

        String username = usernameTextField.getText();
        String password = passwordPasswordField.getText();

        sendRequest(username, password);
    }

    public void sendRequest(String username, String password)
    {

        thisStage = (Stage) logInButton.getScene().getWindow();
        Response res = new Request("user/login")
                .set("username", username)
                .set("password", password)
                .send();

        if (res.getSuccess())
        {
            Main.setSessionID((String)res.get("sessionID"));
            System.out.println("Login successful.");
            Main.userNotLoggedIn.setValue(false);

            //Save the login option if checked
            if (keepMeLoggedInCheckBox.isSelected())
            {
                pc.setProp("username", usernameTextField.getText());
                pc.setProp("password", passwordPasswordField.getText());
                pc.setProp("signInCheckbox", "true");
                pc.saveProps();
            }

            HomeController.userName = usernameTextField.getText();
            thisStage.close();
        }
        else
        {
            //incorrect password
        }
    }

    @FXML
    private void onRegisterHyperlinkClick(ActionEvent event)
    {
        FXMLLoader loader = new FXMLLoader();
        Stage dialogStage = new Stage();
        Parent root = null;
        dialogStage.setTitle("Register for sQuire");
        dialogStage.initModality(Modality.WINDOW_MODAL);
        dialogStage.initOwner(registerHyperlink.getScene().getWindow());
        dialogStage.setResizable(false);
        try
        {
            root = loader.load(getClass().getResource("/fxml/RegisterDialog.fxml"));
            Scene scene = new Scene(root);
            dialogStage.setScene(scene);
            dialogStage.showAndWait();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}


text:
package com.github.rholder.esthree.cli;

import com.github.rholder.esthree.Main;
import io.airlift.command.ParseArgumentsUnexpectedException;
import org.junit.Assert;
import org.junit.Test;

import java.io.IOException;

public class LbCommandTest extends LbCommand {

    @Test
    public void noParameters() {
        Main main = new Main();
        main.parseGlobalCli("lb");
        main.command.parse();
    }

    @Test
    public void help() {
        Main main = new Main();
        main.parseGlobalCli("lb", "-h");
        main.command.parse();
    }

    @Test
    public void happyPath() throws IOException {
        Main main = new Main();
        main.parseGlobalCli("lb");
        main.command.parse();

        LbCommand c = (LbCommand) main.command;
        Assert.assertEquals(DEFAULT_LIST_BUCKET_FORMAT, c.listBucketFormat);
    }

    @Test
    public void happyPathWithFormat() throws IOException {
        Main main = new Main();
        main.parseGlobalCli("lb", "-lbf", "%3   %1$tF %1$tR   s3://%2$s");
        main.command.parse();

        LbCommand c = (LbCommand) main.command;
        Assert.assertEquals("%3   %1$tF %1$tR   s3://%2$s", c.listBucketFormat);
    }

    @Test
    public void garbageParameter() throws IOException {
        Main main = new Main();
        try {
            main.parseGlobalCli("lb", "potato");
            Assert.fail("Expected ParseArgumentsUnexpectedException");
        } catch (ParseArgumentsUnexpectedException e) {
            Assert.assertEquals("Found unexpected parameters: [potato]", e.getMessage());
        }
    }
}


text:
Rails.application.config.middleware.use OmniAuth::Builder do
  provider :bouncer, ENV['BOUNCER_KEY'], ENV['BOUNCER_SECRET'], ENV['BOUNCER_SITE_URL']
end


text:
extern "C" {
#endif

#ifdef HAVE_RB_CSTR2INUM
VALUE string_spec_rb_cstr2inum(VALUE self, VALUE str, VALUE inum) {
  int num = FIX2INT(inum);
  return rb_cstr2inum(RSTRING_PTR(str), num);
}
#endif

#ifdef HAVE_RB_STR2CSTR
VALUE string_spec_rb_str2cstr(VALUE self, VALUE str, VALUE return_length) {
  if(return_length == Qtrue) {
    long len = 0;
    char* ptr = rb_str2cstr(str, &len);
    VALUE ary = rb_ary_new();
    rb_ary_push(ary, rb_str_new2(ptr));
    rb_ary_push(ary, INT2FIX(len));
    return ary;
  } else {
    return rb_str_new2(rb_str2cstr(str, NULL));
  }
}

VALUE string_spec_rb_str2cstr_replace(VALUE self, VALUE str) {
  char* ptr = rb_str2cstr(str, NULL);
  ptr[0] = 'f'; ptr[1] = 'o'; ptr[2] = 'o'; ptr[3] = 0;
  return Qnil;
}
#endif

#ifdef HAVE_RB_STR2INUM
VALUE string_spec_rb_str2inum(VALUE self, VALUE str, VALUE inum) {
  int num = FIX2INT(inum);
  return rb_str2inum(str, num);
}
#endif

#ifdef HAVE_RB_STR_APPEND
VALUE string_spec_rb_str_append(VALUE self, VALUE str, VALUE str2) {
  return rb_str_append(str, str2);
}
#endif

#ifdef HAVE_RB_STR_BUF_CAT
VALUE string_spec_rb_str_buf_cat(VALUE self, VALUE str) {
  const char *question_mark = "?";
  rb_str_buf_cat(str, question_mark, strlen(question_mark));
  return str;
}
#endif

#ifdef HAVE_RB_STR_CAT
VALUE string_spec_rb_str_cat(VALUE self, VALUE str) {
  return rb_str_cat(str, "?", 1);
}
#endif

#ifdef HAVE_RB_STR_CAT2
VALUE string_spec_rb_str_cat2(VALUE self, VALUE str) {
  return rb_str_cat2(str, "?");
}
#endif

#ifdef HAVE_RB_STR_CMP
VALUE string_spec_rb_str_cmp(VALUE self, VALUE str1, VALUE str2) {
  return INT2NUM(rb_str_cmp(str1, str2));
}
#endif

#ifdef HAVE_RB_STR_DUP
VALUE string_spec_rb_str_dup(VALUE self, VALUE str) {
  return rb_str_dup(str);
}
#endif

#ifdef HAVE_RB_STR_FREEZE
VALUE string_spec_rb_str_freeze(VALUE self, VALUE str) {
  return rb_str_freeze(str);
}
#endif

#ifdef HAVE_RB_STR_INTERN
VALUE string_spec_rb_str_intern(VALUE self, VALUE str) {
  return rb_str_intern(str);
}
#endif

#ifdef HAVE_RB_STR_LEN
VALUE string_spec_rb_str_len(VALUE self, VALUE str) {
  return INT2FIX(rb_str_len(str));
}
#endif

#ifdef HAVE_RB_STR_NEW
VALUE string_spec_rb_str_new(VALUE self, VALUE str, VALUE len) {
  return rb_str_new(RSTRING_PTR(str), FIX2INT(len));
}
#endif

#ifdef HAVE_RB_STR_NEW2
VALUE string_spec_rb_str_new2(VALUE self) {
  return rb_str_new2("hello\0invisible");
}

VALUE string_spec_rb_str_new2_with_null(VALUE self) {
  return rb_str_new2(NULL);
}
#endif

#ifdef HAVE_RB_STR_NEW3
VALUE string_spec_rb_str_new3(VALUE self, VALUE str) {
  return rb_str_new3(str);
}
#endif

#ifdef HAVE_RB_STR_PLUS
VALUE string_spec_rb_str_plus(VALUE self, VALUE str1, VALUE str2) {
  return rb_str_plus(str1, str2);
}
#endif

#ifdef HAVE_RB_STR_PTR
VALUE string_spec_rb_str_ptr_iterate(VALUE self, VALUE str) {
  int i;
  char* ptr;

  ptr = rb_str_ptr(str);
  for(i = 0; i < RSTRING_LEN(str); i++) {
    rb_yield(INT2FIX(ptr[i]));
  }
  return Qnil;
}

VALUE string_spec_rb_str_ptr_assign(VALUE self, VALUE str, VALUE chr) {
  int i;
  char c;
  char* ptr;

  ptr = rb_str_ptr(str);
  c = FIX2INT(chr);

  for(i = 0; i < RSTRING_LEN(str); i++) {
    ptr[i] = c;
  }
  return Qnil;
}

VALUE string_spec_rb_str_ptr_assign_call(VALUE self, VALUE str) {
  char *ptr = rb_str_ptr(str);

  ptr[1] = 'x';
  rb_str_concat(str, rb_str_new2("d"));
  return str;
}

VALUE string_spec_rb_str_ptr_assign_funcall(VALUE self, VALUE str) {
  char *ptr = rb_str_ptr(str);

  ptr[1] = 'x';
  rb_str_flush(str);
  rb_funcall(str, rb_intern("<<"), 1, rb_str_new2("e"));
  return str;
}
#endif

#ifdef HAVE_RB_STR_PTR_READONLY
VALUE string_spec_rb_str_ptr_readonly_iterate(VALUE self, VALUE str) {
  int i;
  char* ptr;

  ptr = rb_str_ptr_readonly(str);
  for(i = 0; i < RSTRING_LEN(str); i++) {
    rb_yield(INT2FIX(ptr[i]));
  }
  return Qnil;
}

VALUE string_spec_rb_str_ptr_readonly_assign(VALUE self, VALUE str, VALUE chr) {
  int i;
  char c;
  char* ptr;

  ptr = rb_str_ptr_readonly(str);
  c = FIX2INT(chr);

  for(i = 0; i < RSTRING_LEN(str); i++) {
    ptr[i] = c;
  }
  return Qnil;
}

VALUE string_spec_rb_str_ptr_readonly_append(VALUE self, VALUE str, VALUE more) {
  char *ptr = rb_str_ptr_readonly(str);

  rb_str_concat(str, more);

  return rb_str_new2(ptr);
}
#endif

#ifdef HAVE_RB_STR_RESIZE
VALUE string_spec_rb_str_resize(VALUE self, VALUE str, VALUE size) {
  return rb_str_resize(str, FIX2INT(size));
}

VALUE string_spec_rb_str_resize_RSTRING_LEN(VALUE self, VALUE str, VALUE size) {
  VALUE modified = rb_str_resize(str, FIX2INT(size));
  return INT2FIX(RSTRING_LEN(modified));
}
#endif

#ifdef HAVE_RB_STR_SPLIT
VALUE string_spec_rb_str_split(VALUE self, VALUE str) {
  return rb_str_split(str, ",");
}
#endif

#ifdef HAVE_RB_STR_SUBSTR
VALUE string_spec_rb_str_substr(VALUE self, VALUE str, VALUE beg, VALUE len) {
  return rb_str_substr(str, FIX2INT(beg), FIX2INT(len));
}
#endif

#ifdef HAVE_RB_STR_TO_STR
VALUE string_spec_rb_str_to_str(VALUE self, VALUE arg) {
  return rb_str_to_str(arg);
}
#endif

#ifdef HAVE_RSTRING
VALUE string_spec_RSTRING_len(VALUE self, VALUE str) {
  return INT2FIX(RSTRING(str)->len);
}

VALUE string_spec_RSTRING_ptr_iterate(VALUE self, VALUE str) {
  int i;
  char* ptr;

  ptr = RSTRING(str)->ptr;
  for(i = 0; i < RSTRING_LEN(str); i++) {
    rb_yield(INT2FIX(ptr[i]));
  }
  return Qnil;
}

VALUE string_spec_RSTRING_ptr_assign(VALUE self, VALUE str, VALUE chr) {
  int i;
  char c;
  char* ptr;

  ptr = RSTRING(str)->ptr;
  c = FIX2INT(chr);

  for(i = 0; i < RSTRING_LEN(str); i++) {
    ptr[i] = c;
  }
  return Qnil;
}

VALUE string_spec_RSTRING_ptr_assign_call(VALUE self, VALUE str) {
  char *ptr = RSTRING(str)->ptr;

  ptr[1] = 'x';
  rb_str_concat(str, rb_str_new2("d"));
  return str;
}

VALUE string_spec_RSTRING_ptr_assign_funcall(VALUE self, VALUE str) {
  char *ptr = RSTRING(str)->ptr;

  ptr[1] = 'x';
  rb_funcall(str, rb_intern("<<"), 1, rb_str_new2("e"));
  return str;
}
#endif

#ifdef HAVE_RSTRING_LEN
VALUE string_spec_RSTRING_LEN(VALUE self, VALUE str) {
  return INT2FIX(RSTRING_LEN(str));
}
#endif

#ifdef HAVE_RSTRING_PTR
VALUE string_spec_RSTRING_PTR_iterate(VALUE self, VALUE str) {
  int i;
  char* ptr;

  ptr = RSTRING_PTR(str);
  for(i = 0; i < RSTRING_LEN(str); i++) {
    rb_yield(INT2FIX(ptr[i]));
  }
  return Qnil;
}

VALUE string_spec_RSTRING_PTR_assign(VALUE self, VALUE str, VALUE chr) {
  int i;
  char c;
  char* ptr;

  ptr = RSTRING_PTR(str);
  c = FIX2INT(chr);

  for(i = 0; i < RSTRING_LEN(str); i++) {
    ptr[i] = c;
  }
  return Qnil;
}

VALUE string_spec_RSTRING_PTR_after_funcall(VALUE self, VALUE str, VALUE cb) {
  // Silence gcc 4.3.2 warning about computed value not used
  if(RSTRING_PTR(str)) { // force it out
    rb_funcall(cb, rb_intern("call"), 1, str);
  }

  return rb_str_new2(RSTRING_PTR(str));
}
#endif

#ifdef HAVE_STR2CSTR
VALUE string_spec_STR2CSTR(VALUE self, VALUE str) {
  return rb_str_new2(STR2CSTR(str));
}

VALUE string_spec_STR2CSTR_replace(VALUE self, VALUE str) {
  char* ptr = STR2CSTR(str);
  ptr[0] = 'f'; ptr[1] = 'o'; ptr[2] = 'o'; ptr[3] = 0;
  return Qnil;
}
#endif

#ifdef HAVE_STRINGVALUE
VALUE string_spec_StringValue(VALUE self, VALUE str) {
  return StringValue(str);
}
#endif

void Init_string_spec() {
  VALUE cls;
  cls = rb_define_class("CApiStringSpecs", rb_cObject);

#ifdef HAVE_RB_CSTR2INUM
  rb_define_method(cls, "rb_cstr2inum", string_spec_rb_cstr2inum, 2);
#endif

#ifdef HAVE_RB_STR2CSTR
  rb_define_method(cls, "rb_str2cstr", string_spec_rb_str2cstr, 2);
  rb_define_method(cls, "rb_str2cstr_replace", string_spec_rb_str2cstr_replace, 1);
#endif

#ifdef HAVE_RB_STR2INUM
  rb_define_method(cls, "rb_str2inum", string_spec_rb_str2inum, 2);
#endif

#ifdef HAVE_RB_STR_APPEND
  rb_define_method(cls, "rb_str_append", string_spec_rb_str_append, 2);
#endif

#ifdef HAVE_RB_STR_BUF_CAT
  rb_define_method(cls, "rb_str_buf_cat", string_spec_rb_str_buf_cat, 1);
#endif

#ifdef HAVE_RB_STR_CAT
  rb_define_method(cls, "rb_str_cat", string_spec_rb_str_cat, 1);
#endif

#ifdef HAVE_RB_STR_CAT2
  rb_define_method(cls, "rb_str_cat2", string_spec_rb_str_cat2, 1);
#endif

#ifdef HAVE_RB_STR_CMP
  rb_define_method(cls, "rb_str_cmp", string_spec_rb_str_cmp, 2);
#endif

#ifdef HAVE_RB_STR_DUP
  rb_define_method(cls, "rb_str_dup", string_spec_rb_str_dup, 1);
#endif

#ifdef HAVE_RB_STR_FLUSH
#endif

#ifdef HAVE_RB_STR_FREEZE
  rb_define_method(cls, "rb_str_freeze", string_spec_rb_str_freeze, 1);
#endif

#ifdef HAVE_RB_STR_INTERN
  rb_define_method(cls, "rb_str_intern", string_spec_rb_str_intern, 1);
#endif

#ifdef HAVE_RB_STR_LEN
  rb_define_method(cls, "rb_str_len", string_spec_rb_str_len, 1);
#endif

#ifdef HAVE_RB_STR_NEW
  rb_define_method(cls, "rb_str_new", string_spec_rb_str_new, 2);
#endif

#ifdef HAVE_RB_STR_NEW2
  rb_define_method(cls, "rb_str_new2", string_spec_rb_str_new2, 0);
  rb_define_method(cls, "rb_str_new2_with_null", string_spec_rb_str_new2_with_null, 0);
#endif

#ifdef HAVE_RB_STR_NEW3
  rb_define_method(cls, "rb_str_new3", string_spec_rb_str_new3, 1);
#endif

#ifdef HAVE_RB_STR_PLUS
  rb_define_method(cls, "rb_str_plus", string_spec_rb_str_plus, 2);
#endif

#ifdef HAVE_RB_STR_PTR
  rb_define_method(cls, "rb_str_ptr_iterate", string_spec_rb_str_ptr_iterate, 1);
  rb_define_method(cls, "rb_str_ptr_assign", string_spec_rb_str_ptr_assign, 2);
  rb_define_method(cls, "rb_str_ptr_assign_call", string_spec_rb_str_ptr_assign_call, 1);
  rb_define_method(cls, "rb_str_ptr_assign_funcall",
      string_spec_rb_str_ptr_assign_funcall, 1);
#endif

#ifdef HAVE_RB_STR_PTR_READONLY
  rb_define_method(cls, "rb_str_ptr_readonly_iterate",
      string_spec_rb_str_ptr_readonly_iterate, 1);
  rb_define_method(cls, "rb_str_ptr_readonly_assign",
      string_spec_rb_str_ptr_readonly_assign, 2);
  rb_define_method(cls, "rb_str_ptr_readonly_append",
      string_spec_rb_str_ptr_readonly_append, 2);
#endif

#ifdef HAVE_RB_STR_RESIZE
  rb_define_method(cls, "rb_str_resize", string_spec_rb_str_resize, 2);
  rb_define_method(cls, "rb_str_resize_RSTRING_LEN",
      string_spec_rb_str_resize_RSTRING_LEN, 2);
#endif

#ifdef HAVE_RB_STR_SPLIT
  rb_define_method(cls, "rb_str_split", string_spec_rb_str_split, 1);
#endif

#ifdef HAVE_RB_STR_SUBSTR
  rb_define_method(cls, "rb_str_substr", string_spec_rb_str_substr, 3);
#endif

#ifdef HAVE_RB_STR_TO_STR
  rb_define_method(cls, "rb_str_to_str", string_spec_rb_str_to_str, 1);
#endif

#ifdef HAVE_RSTRING
  rb_define_method(cls, "RSTRING_ptr_iterate", string_spec_RSTRING_ptr_iterate, 1);
  rb_define_method(cls, "RSTRING_ptr_assign", string_spec_RSTRING_ptr_assign, 2);
  rb_define_method(cls, "RSTRING_ptr_assign_call", string_spec_RSTRING_ptr_assign_call, 1);
  rb_define_method(cls, "RSTRING_ptr_assign_funcall",
      string_spec_RSTRING_ptr_assign_funcall, 1);
  rb_define_method(cls, "RSTRING_len", string_spec_RSTRING_len, 1);
#endif

#ifdef HAVE_RSTRING_LEN
  rb_define_method(cls, "RSTRING_LEN", string_spec_RSTRING_LEN, 1);
#endif

#ifdef HAVE_RSTRING_PTR
  rb_define_method(cls, "RSTRING_PTR_iterate", string_spec_RSTRING_PTR_iterate, 1);
  rb_define_method(cls, "RSTRING_PTR_assign", string_spec_RSTRING_PTR_assign, 2);
  rb_define_method(cls, "RSTRING_PTR_after_funcall",
      string_spec_RSTRING_PTR_after_funcall, 2);
#endif

#ifdef HAVE_STR2CSTR
  rb_define_method(cls, "STR2CSTR", string_spec_STR2CSTR, 1);
  rb_define_method(cls, "STR2CSTR_replace", string_spec_STR2CSTR_replace, 1);
#endif

#ifdef HAVE_STRINGVALUE
  rb_define_method(cls, "StringValue", string_spec_StringValue, 1);
#endif
}

#ifdef __cplusplus
}
#endif


text:
package org.ilrt.mca.rest.providers;

import org.apache.log4j.Logger;
import org.ilrt.mca.RdfMediaType;
import org.ilrt.mca.rest.resources.SparqlEndpointResource;

import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyWriter;
import javax.ws.rs.ext.Provider;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

@Provider
@Produces({MediaType.WILDCARD, RdfMediaType.APPLICATION_RDF_XML, RdfMediaType.TEXT_RDF_N3,
        MediaType.APPLICATION_JSON, RdfMediaType.SPARQL_RESULTS_JSON,
        RdfMediaType.SPARQL_RESULTS_XML})
public class SparqlQueryResultsProvider
        implements MessageBodyWriter<SparqlEndpointResource.SparqlQueryResults>{

    @Override
    public boolean isWriteable(Class<?> aClass, Type type, Annotation[] annotations,
                               MediaType mediaType) {
        return SparqlEndpointResource.SparqlQueryResults.class.isAssignableFrom(aClass);
    }

    @Override
    public long getSize(SparqlEndpointResource.SparqlQueryResults sparqlQueryResults,
                        Class<?> aClass, Type type, Annotation[] annotations, MediaType mediaType) {
        return -1;
    }

    @Override
    public void writeTo(SparqlEndpointResource.SparqlQueryResults sparqlQueryResults,
                        Class<?> aClass, Type type, Annotation[] annotations, MediaType mediaType,
                        MultivaluedMap<String, Object> stringObjectMultivaluedMap,
                        OutputStream outputStream) throws IOException, WebApplicationException {

        logger.info("Executing and streaming the SPARQL results");
        sparqlQueryResults.executeAndStreamResults(outputStream, mediaType);
    }

    private final Logger logger = Logger.getLogger(SparqlQueryResultsProvider.class);
}


text:
int main ()
{
    //  Prepare our context and socket
    zmq::context_t context (1);
    zmq::socket_t socket (context, ZMQ_REQ);

    std::cout << "Connecting to hello world server…" << std::endl;
    socket.connect ("tcp://localhost:5555");

    //  Do 10 requests, waiting each time for a response
    for (int request_nbr = 0; request_nbr != 10; request_nbr++) {
        zmq::message_t request (5);
        memcpy (request.data (), "Hello", 5);
        std::cout << "Sending Hello " << request_nbr << "…" << std::endl;
        socket.send (request);

        //  Get the reply.
        zmq::message_t reply;
        socket.recv (&reply);
        std::cout << "Received World " << request_nbr << std::endl;
    }
    return 0;
}


text:
require File.expand_path('../../../spec_helper', __FILE__)
require File.expand_path('../fixtures/classes', __FILE__)
require File.expand_path('../shared/readlines', __FILE__)

describe "IO#readlines" do
  before :each do
    @io = IOSpecs.io_fixture "lines.txt"
  end

  after :each do
    @io.close unless @io.closed?
  end

  ruby_version_is "1.9" do
    before :each do
      @orig_exteenc = Encoding.default_external
      Encoding.default_external = Encoding::UTF_8
    end

    after :each do
      Encoding.default_external = @orig_exteenc
    end
  end

  it "raises an IOError if the stream is closed" do
    @io.close
    lambda { @io.readlines }.should raise_error(IOError)
  end

  describe "when passed no arguments" do
    before :each do
      @sep, $/ = $/, " "
    end

    after :each do
      $/ = @sep
    end

    it "returns an Array containing lines based on $/" do
      @io.readlines.should == IOSpecs.lines_space_separator
    end
  end

  describe "when passed no arguments" do
    it "updates self's position" do
      @io.readlines
      @io.pos.should eql(137)
    end

    it "updates self's lineno based on the number of lines read" do
      @io.readlines
      @io.lineno.should eql(9)
    end

    it "does not change $_" do
      $_ = "test"
      @io.readlines
      $_.should == "test"
    end

    it "returns an empty Array when self is at the end" do
      @io.readlines.should == IOSpecs.lines
      @io.readlines.should == []
    end
  end

  describe "when passed nil" do
    it "returns the remaining content as one line starting at the current position" do
      @io.readlines(nil).should == [IOSpecs.lines.join]
    end
  end

  describe "when passed an empty String" do
    it "returns an Array containing all paragraphs" do
      @io.readlines("").should == IOSpecs.paragraphs
    end
  end

  describe "when passed a separator" do
    it "returns an Array containing lines based on the separator" do
      @io.readlines("r").should == IOSpecs.lines_r_separator
    end

    it "returns an empty Array when self is at the end" do
      @io.readlines
      @io.readlines("r").should == []
    end

    it "updates self's lineno based on the number of lines read" do
      @io.readlines("r")
      @io.lineno.should eql(5)
    end

    it "updates self's position based on the number of characters read" do
      @io.readlines("r")
      @io.pos.should eql(137)
    end

    it "does not change $_" do
      $_ = "test"
      @io.readlines("r")
      $_.should == "test"
    end

    it "tries to convert the passed separator to a String using #to_str" do
      obj = mock('to_str')
      obj.stub!(:to_str).and_return("r")
      @io.readlines(obj).should == IOSpecs.lines_r_separator
    end
  end

  describe "when passed a string that starts with a |" do
    it "gets data from the standard out of the subprocess" do
      lines = IO.readlines("|sh -c 'echo hello;echo line2'")
      lines.should == ["hello\n", "line2\n"]
    end

    it "gets data from a fork when passed -" do
      lines = IO.readlines("|-")

      if lines # parent
        lines.should == ["hello\n", "from a fork\n"]
      else
        puts "hello"
        puts "from a fork"
        exit!
      end
    end
  end
end

describe "IO#readlines" do
  before :each do
    @name = tmp("io_readlines")
  end

  after :each do
    rm_r @name
  end

  it "raises an IOError if the stream is opened for append only" do
    lambda do
      File.open(@name, fmode("a:utf-8")) { |f| f.readlines }
    end.should raise_error(IOError)
  end

  it "raises an IOError if the stream is opened for write only" do
    lambda do
      File.open(@name, fmode("w:utf-8")) { |f| f.readlines }
    end.should raise_error(IOError)
  end
end

ruby_version_is ""..."1.9" do
  describe "IO.readlines" do
    before :each do
      @name = fixture __FILE__, "lines.txt"
      ScratchPad.record []
    end

    it_behaves_like :io_readlines, :readlines
    it_behaves_like :io_readlines_options_18, :readlines
  end
end

ruby_version_is "1.9" do
  describe "IO.readlines" do
    before :each do
      @external = Encoding.default_external
      Encoding.default_external = Encoding::UTF_8

      @name = fixture __FILE__, "lines.txt"
      ScratchPad.record []
    end

    after :each do
      Encoding.default_external = @external
    end

    it "does not change $_" do
      $_ = "test"
      IO.readlines(@name)
      $_.should == "test"
    end

    it_behaves_like :io_readlines, :readlines
    it_behaves_like :io_readlines_options_19, :readlines
  end
end


text:
namespace data
{
    struct PureMVCTest
    { };
}

namespace testgroup
{
    typedef tut::test_group<data::PureMVCTest> pure_mvc_test_t;
    typedef pure_mvc_test_t::object object;
    pure_mvc_test_t pure_mvc_test("_PureMVCTest");
}

namespace tut
{
    using namespace testgroup;
    using namespace data;
    using namespace PureMVC;
    using namespace PureMVC::Core;
    using namespace PureMVC::Interfaces;
    using namespace PureMVC::Patterns;

    template<> template<>
    void object::test<1>(void)
    {
        set_test_name("testGetFacadeNames");

        std::auto_ptr<IAggregate<std::string> > names = getFacadeKeys();
        std::auto_ptr<IIterator<std::string> > iterator = names->getIterator();
        std::size_t count = 0;

#if defined(_DEBUG) || defined(DEBUG)
        std::cout << std::endl <<"The list name of Facade: " << std::endl;
#endif
        while(iterator->moveNext()) {
            ++count;
#if defined(_DEBUG) || defined(DEBUG)
            std::cout <<count << ". " <<iterator->getCurrent() << std::endl;
#endif
        }

        ensure_equals( "Expecting number of Facade equal 10 ", count, 10);
    }

    template<> template<>
    void object::test<2>(void)
    {
        set_test_name("testGetControllerNames");

        std::auto_ptr<IAggregate<std::string> > names = PureMVC::getControllerKeys();
        std::auto_ptr<IIterator<std::string> > iterator = names->getIterator();
        std::size_t count = 0;

#if defined(_DEBUG) || defined(DEBUG)
        std::cout << std::endl <<"The list name of Controller: " << std::endl;
#endif
        while(iterator->moveNext()) {
            ++count;
#if defined(_DEBUG) || defined(DEBUG)
            std::cout <<count << ". " <<iterator->getCurrent() << std::endl;
#endif
        }

        ensure_equals( "Expecting number of Controller equal 17 ", count, 17);
    }

    template<> template<>
    void object::test<3>(void)
    {
        set_test_name("testGetModelNames");

        std::auto_ptr<IAggregate<std::string> > names = PureMVC::getModelKeys();
        std::auto_ptr<IIterator<std::string> > iterator = names->getIterator();
        std::size_t count = 0;

#if defined(_DEBUG) || defined(DEBUG)
        std::cout << std::endl <<"The list name of Model: " << std::endl;
#endif
        while(iterator->moveNext()) {
            ++count;
#if defined(_DEBUG) || defined(DEBUG)
            std::cout <<count << ". " <<iterator->getCurrent() << std::endl;
#endif
        }

        ensure_equals( "Expecting number of Model equal 17 ", count, 17);
    }

    template<> template<>
    void object::test<4>(void)
    {
        set_test_name("testGetViewNames");

        std::auto_ptr<IAggregate<std::string> > names = PureMVC::getViewKeys();
        std::auto_ptr<IIterator<std::string> > iterator = names->getIterator();
        std::size_t count = 0;

#if defined(_DEBUG) || defined(DEBUG)
        std::cout << std::endl <<"The list name of View: " << std::endl;
#endif
        while(iterator->moveNext()) {
            ++count;
#if defined(_DEBUG) || defined(DEBUG)
            std::cout <<count << ". " <<iterator->getCurrent() << std::endl;
#endif
        }

        ensure_equals( "Expecting number of View equal 30 ", count, 30);
    }

    template<> template<>
    void object::test<5>(void)
    {
        set_test_name("testRemoveFacade");

        bool exist = false;

        Facade::getInstance("testRemoveFacade");

        std::auto_ptr<IAggregate<std::string> > names = getFacadeKeys();
        std::auto_ptr<IIterator<std::string> > iterator = names->getIterator();

        while(iterator->moveNext())
            if (iterator->getCurrent() == "testRemoveFacade")
            {
                exist = true;
                break;
            }

        ensure("Expecting Facade testRemoveFacade is existed!", exist);

        removeFacade("testRemoveFacade");

        names = getFacadeKeys();
        iterator = names->getIterator();

        exist = false;

        while(iterator->moveNext())
            if (iterator->getCurrent() == "testRemoveFacade")
            {
                exist = true;
                break;
            }

        ensure("Expecting Facade testRemoveFacade is removed!", !exist);
    }

    template<> template<>
    void object::test<6>(void)
    {
        set_test_name("testRemoveController");

        bool exist = false;

        Controller::getInstance("testRemoveController");

        std::auto_ptr<IAggregate<std::string> > names = getControllerKeys();
        std::auto_ptr<IIterator<std::string> > iterator = names->getIterator();

        while(iterator->moveNext())
            if (iterator->getCurrent() == "testRemoveController")
            {
                exist = true;
                break;
            }

        ensure("Expecting Controller testRemoveController is existed!", exist);

        removeController("testRemoveController");

        names = getControllerKeys();
        iterator = names->getIterator();

        exist = false;

        while(iterator->moveNext())
            if (iterator->getCurrent() == "testRemoveController")
            {
                exist = true;
                break;
            }

        ensure("Expecting Controller testRemoveController is removed!", !exist);
    }

    template<> template<>
    void object::test<7>(void)
    {
        set_test_name("testRemoveModel");

        bool exist = false;

        Model::getInstance("testRemoveController");

        std::auto_ptr<IAggregate<std::string> > names = getModelKeys();
        std::auto_ptr<IIterator<std::string> > iterator = names->getIterator();

        while(iterator->moveNext())
            if (iterator->getCurrent() == "testRemoveController")
            {
                exist = true;
                break;
            }

        ensure("Expecting Model testRemoveController is existed!", exist);

        removeModel("testRemoveController");

        names = getModelKeys();
        iterator = names->getIterator();

        exist = false;

        while(iterator->moveNext())
            if (iterator->getCurrent() == "testRemoveController")
            {
                exist = true;
                break;
            }

        ensure("Expecting Model testRemoveController is removed!", !exist);
    }

    template<> template<>
    void object::test<8>(void)
    {
        set_test_name("testRemoveView");

        bool exist = false;

        View::getInstance("testRemoveController");

        std::auto_ptr<IAggregate<std::string> > names = getViewKeys();
        std::auto_ptr<IIterator<std::string> > iterator = names->getIterator();

        while(iterator->moveNext())
            if (iterator->getCurrent() == "testRemoveController")
            {
                exist = true;
                break;
            }

        ensure("Expecting View testRemoveController is existed!", exist);

        removeView("testRemoveController");

        names = getModelKeys();
        iterator = names->getIterator();

        exist = false;

        while(iterator->moveNext())
            if (iterator->getCurrent() == "testRemoveController")
            {
                exist = true;
                break;
            }

        ensure("Expecting View testRemoveController is removed!", !exist);
    }

    template<> template<>
    void object::test<9>(void)
    {
        set_test_name("testBroadcastNotification");
        Facade::getInstance("testBroadcastNotification_1").registerCommand("calculateValue", new PureMVCTestCommand);
        Facade::getInstance("testBroadcastNotification_2").registerCommand("calculateValue", new PureMVCTestCommand2);
        Facade::getInstance("testBroadcastNotification_3").registerCommand("calculateValue", new PureMVCTestCommand3);
        Facade::getInstance("testBroadcastNotification_4").registerCommand("calculateValue", new PureMVCTestCommand4);
        int value = 5;
        broadcastNotification("calculateValue", &value);
        removeFacade("testBroadcastNotification_1");
        removeFacade("testBroadcastNotification_2");
        removeFacade("testBroadcastNotification_3");
        removeFacade("testBroadcastNotification_4");
        ensure_equals( "Expecting value == 600", value, 600 );
    }
}