text:
define([
    'jquery',
    'tiki/tools',
    './util'
], function($, Tools, StickyUtils) {
    'use strict';

var ScrollEvent = StickyUtils.ScrollEvent;

var exp = {};
// class AbstractViewport extends Events.EventEmitter {

var AbstractViewport = Tools.View.extend({

  // ES6
  // constructor() {
  initialize: function() {
    // ES6
    // super();
    this.watchers = [];
  },

  triggerNewScrollEvent: function() {
    // Create and dispatch a new scroll event artificially
    // Reuse the same browser event
    this.onScroll(this.scrollEvent.e, {isArtificial: true});
  },

  recalculateAll: function() {
    // ES5
    this.watchers
      .filter(function(watcher) { return watcher.enabled; })
      .sort(function(a, b) { return b.stackPos - a.stackPos; })
      .forEach(function(watcher) { watcher.trigger('recalculate', this.scrollEvent); }.bind(this));
  },

  broadcastScrollEvent: function(scrollEvent) {
    var directions = scrollEvent.directions || [];
    var verticalDirection = directions[1];

    if (verticalDirection === 'up') {
      // ES6
      // this.watchers
      // .filter(watcher => watcher.enabled)
      // .sort((a, b) => b.stackPos - a.stackPos)
      // .forEach(watcher => this.triggerOne(watcher, scrollEvent));

      // ES5
      this.watchers
      .filter(function(watcher) { return watcher.enabled; })
      .sort(function(a, b) { return b.stackPos - a.stackPos; })
      .forEach(function(watcher) { this.triggerOne(watcher, scrollEvent); }.bind(this));
    }
    else { // Horizontal stacking is not yet supported
      // ES6
      // this.watchers
      // .filter(watcher => watcher.enabled)
      // .sort((a, b) => a.stackPos - b.stackPos)
      // .forEach(watcher => this.triggerOne(watcher, scrollEvent));

      // ES5
      this.watchers
      .filter(function(watcher) { return watcher.enabled; })
      .sort(function(a, b) { return a.stackPos - b.stackPos; })
      .forEach(function(watcher) { this.triggerOne(watcher, scrollEvent); }.bind(this));
    }
  },

  addWatcher: function(watcher) {
    if (watcher.stackPos === undefined) {
      watcher.stackPos = this.watchers.length;
    }
    this.watchers.push(watcher);
  },

  removeWatcher: function(watcher) {
    var index = this.watchers.indexOf(watcher);
    if (index !== -1) {
      this.watchers.splice(index, 1);
    }
  },

  triggerOne: function(watcher, scrollEvent) {

    if (!scrollEvent.hasMutated(watcher.id)) {
      scrollEvent.addMutated(watcher.id);

      var directions = scrollEvent.directions || [];
      var horizontalDirection = directions[0];
      var verticalDirection = directions[1];

      if (scrollEvent.isArtificial) {
        // For scroll events triggered manually by calling triggerNewScrollEvent,
        // fire a "verticalscroll" event to keep the original behavior.
        watcher._onVerticalScroll(scrollEvent);
        return;
      }

      if (horizontalDirection) {
        watcher._onHorizontalScroll(scrollEvent);
      }

      if (verticalDirection) {
        watcher._onVerticalScroll(scrollEvent);
      }
    }
  },

  retriggerScrollEvent: function() {
    // TODO: ..well, retrigger is only necessary if stackheight has changed

    // Update the scrollHeight and dispatch scrollEvent
    if (this.scrollEvent) {
      this.scrollEvent.stackHeight = this.barStack[0].getBoundingClientRect().height;
      this.broadcastScrollEvent(this.scrollEvent);
    }
  },

  refreshStackHeight: function(scrollEvent) {
    scrollEvent.stackHeight = this.barStack[0].getBoundingClientRect().height;
  },

  getScrollDirection: function(scrollLeft, scrollTop) {
    // Get scroll direction
    var direction = null;
    if (this.scrollEvent) {
      var prevScrollLeft = this.scrollEvent.scrollLeft;
      var prevScrollTop = this.scrollEvent.scrollTop;

      if (scrollLeft != prevScrollLeft) {
        direction = scrollLeft > prevScrollLeft ? 'right' : 'left';
      }
      else {
        direction = scrollTop > prevScrollTop ? 'down' : 'up';
      }
    }
    return direction;
  },

  getScrollDirections: function(scrollLeft, scrollTop) {
    // Get scroll direction
    var horizontalDirection = null;
    var verticalDirection = null;
    if (this.scrollEvent) {
      var prevScrollLeft = this.scrollEvent.scrollLeft;
      var prevScrollTop = this.scrollEvent.scrollTop;

      if (scrollLeft != prevScrollLeft) {
        horizontalDirection = scrollLeft > prevScrollLeft ? 'right' : 'left';
      }
      if (scrollTop != prevScrollTop) {
        verticalDirection = scrollTop > prevScrollTop ? 'down' : 'up';
      }
    }
    return [horizontalDirection, verticalDirection];
  },

  onScroll: function(e, options) {
    options = options || {};

    var scrollEvent = this.createScrollEvent(e, options);

    // Keep a reference to the most recent scroll event
    this.scrollEvent = scrollEvent;
    this.broadcastScrollEvent(scrollEvent);
  }
});  // ES5

// ES6
// export class DocumentViewport extends AbstractViewport {
var DocumentViewport = AbstractViewport.extend('DocumentViewport', {

  // constructor(config) {
  //   super();
  //   this.el = document;
  //   this.$el = $(document);

  initialize: function(config) {
    // ES5
    DocumentViewport.__super__.initialize.call(this, config);

    this.groups = {};
    this.stack = $('

');
    this.barStack = this.stack.find('>.bar-stack');
    this.inlineStack = this.stack.find('>.inline-stack');
    this.el.body.insertBefore(this.stack[0], this.el.body.firstChild);
    this.scrollEvent = this.createScrollEvent(null, {isArtificial: true});      // this.$el.on('scroll', _.throttle(this.onScroll, 5).bind(this));
    // this.$el.on('scroll', _.throttle(this.onScroll, 10).bind(this));
    this.$el.on('scroll', this.onScroll.bind(this));
  },

  createScrollEvent: function(e, options) {
    options = options || {};
    var scrollTop = this.el.body.scrollTop || this.el.documentElement.scrollTop || 0;
    var scrollLeft = this.el.body.scrollLeft || this.el.documentElement.scrollLeft || 0;

    return new ScrollEvent({

      direction: this.getScrollDirection(scrollLeft, scrollTop),
      directions: this.getScrollDirections(scrollLeft, scrollTop),
      isArtificial: !!options.isArtificial,
      viewportWidth: $(window).width(), //window.innerWidth,
      viewportHeight: $(window).height(), //window.innerHeight,
      viewportRect: {
          top: 0,
          left: 0
      },
      scrollWidth: this.el.body.scrollWidth,
      scrollHeight: this.el.body.scrollHeight,
      scrollTop: scrollTop,
      scrollLeft: scrollLeft,
      stackHeight: this.barStack[0].getBoundingClientRect().height,
      e: e
    });
  }
}); // ES5

// ES6
// export class ElementViewport extends AbstractViewport {
var ElementViewport = AbstractViewport.extend('ElementViewport', {
  // ES6
  // constructor(config) {
  initialize: function(config) {
    // ES5
    ElementViewport.__super__.initialize.call(this, config);

    // ES6
    // super();
    // this.$el = $(config.el);
    // this.el = this.$el[0];

    this.groups = {};
    this.stack = $('

');
    this.barStack = this.stack.find('>.bar-stack');
    this.inlineStack = this.stack.find('>.inline-stack');
    this.el.insertBefore(this.stack[0], this.el.firstChild);
    this.scrollEvent = this.createScrollEvent(null, {isArtificial: true});
    this.$el.on('scroll', this.onScroll.bind(this));
  },

  createScrollEvent: function(e, options) {
    options = options || {};
    var scrollTop = this.el.scrollTop;
    var scrollLeft = this.el.scrollLeft;
    var rect = this.el.getBoundingClientRect();

    return new ScrollEvent({
      direction: this.getScrollDirection(scrollLeft, scrollTop),
      directions: this.getScrollDirections(scrollLeft, scrollTop),
      isArtificial: !!options.isArtificial,
      viewportWidth: rect.width,
      viewportHeight: rect.height,
      viewportRect: rect,
      scrollWidth: this.el.scrollWidth,
      scrollHeight: this.el.scrollHeight,
      scrollTop: scrollTop,
      scrollLeft: scrollLeft,
      stackHeight: this.barStack[0].getBoundingClientRect().height,
      e: e
    });
  },

  onScroll: function(e) {
    this.stack.css('top', this.el.scrollTop);
    // this.stack.css('left', this.el.scrollLeft);

    // ES6
    // super.onScroll(e);

    // ES5
    ElementViewport.__super__.onScroll.call(this, e);
  }
});

// ES5
return {
  ElementViewport: ElementViewport,
  DocumentViewport: DocumentViewport
}

});


text:
<?php
/* SVN FILE: $Id: cake_web_test_case.php 5 2006-05-28 10:33:04Z phpnut $ */
/**
 * Short description for file.
 *
 * Long description for file
 *
 * PHP versions 4 and 5
 *
 * CakePHP Test Suite <https://trac.cakephp.org/wiki/Developement/TestSuite>
 * Copyright (c) 2006, Larry E. Masters Shorewood, IL. 60431
 * Author(s): Larry E. Masters aka PhpNut <phpnut@gmail.com>
 *
 * Portions modifiied from WACT Test Suite
 * Author(s): Harry Fuecks
 *            Jon Ramsey
 *            Jason E. Sweat
 *            Franco Ponticelli
 *            Lorenzo Alberton
 *
 *  Licensed under The Open Group Test Suite License
 *  Redistributions of files must retain the above copyright notice.
 *
 * @filesource
 * @author       Larry E. Masters aka PhpNut <phpnut@gmail.com>
 * @copyright    Copyright (c) 2006, Larry E. Masters Shorewood, IL. 60431
 * @link         http://www.phpnut.com/projects/
 * @package      tests
 * @subpackage   tests.lib
 * @since        CakePHP Test Suite v 1.0.0.0
 * @version      $Revision: 5 $
 * @modifiedby   $LastChangedBy: phpnut $
 * @lastmodified $Date: 2006-05-28 05:33:04 -0500 (Sun, 28 May 2006) $
 * @license      http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License
 */
/**
 * Short description
 */
	SimpleTestOptions::ignore('CakeWebTestCase');

/**
 * Short description for class.
 *
 * @package    tests
 * @subpackage tests.lib
 * @since      CakePHP Test Suite v 1.0.0.0
 */
class CakeWebTestCase extends WebTestCase {
}
?>

redpajama_set_name: RedPajamaGithub


text:
using System.Collections.Generic;
using NUnit.Framework;
using ProtoBuf.Meta;

namespace ProtoBuf.unittest.Serializers
{
    [TestFixture]
    public class KeyValuePairTests
    {
        [Test]
        public void BasicPairTest()
        {
            var pair = new KeyValuePair<int, string>(123, "abc");
            var model = TypeModel.Create();
            var clone = (KeyValuePair<int, string>)model.DeepClone(pair);
            Assert.AreEqual(pair.Key, clone.Key, "Runtime");
            Assert.AreEqual(pair.Value, clone.Value, "Runtime");

            model.CompileInPlace();
            clone = (KeyValuePair<int, string>)model.DeepClone(pair);
            Assert.AreEqual(pair.Key, clone.Key, "CompileInPlace");
            Assert.AreEqual(pair.Value, clone.Value, "CompileInPlace");

            clone = (KeyValuePair<int, string>)model.Compile().DeepClone(pair);
            Assert.AreEqual(pair.Key, clone.Key, "Compile");
            Assert.AreEqual(pair.Value, clone.Value, "Compile");
        }

        [Test]
        public void DictionaryInt32KeyTest()
        {
            var data = new Dictionary<int, string> { { 123, "abc" }, { 456, "def" } };
            var model = TypeModel.Create();
            var clone = (Dictionary<int, string>)model.DeepClone(data);
            Assert.AreEqual(2, clone.Count);
            Assert.AreEqual("abc", clone[123], "Runtime");
            Assert.AreEqual("def", clone[456], "Runtime");

            model.CompileInPlace();
            clone = (Dictionary<int, string>)model.DeepClone(data);
            Assert.AreEqual(2, clone.Count);
            Assert.AreEqual("abc", clone[123], "CompileInPlace");
            Assert.AreEqual("def", clone[456], "CompileInPlace");

            clone = (Dictionary<int, string>)model.Compile().DeepClone(data);
            Assert.AreEqual(2, clone.Count);
            Assert.AreEqual("abc", clone[123], "Compile");
            Assert.AreEqual("def", clone[456], "Compile");
        }

        [Test]
        public void DictionarySingleKeyTest()
        {
            var data = new Dictionary<float, string> { { 123, "abc" }, { 456, "def" } };
            var model = TypeModel.Create();
            var clone = (Dictionary<float, string>)model.DeepClone(data);
            Assert.AreEqual(2, clone.Count);
            Assert.AreEqual("abc", clone[123], "Runtime");
            Assert.AreEqual("def", clone[456], "Runtime");

            model.CompileInPlace();
            clone = (Dictionary<float, string>)model.DeepClone(data);
            Assert.AreEqual(2, clone.Count);
            Assert.AreEqual("abc", clone[123], "CompileInPlace");
            Assert.AreEqual("def", clone[456], "CompileInPlace");

            clone = (Dictionary<float, string>)model.Compile().DeepClone(data);
            Assert.AreEqual(2, clone.Count);
            Assert.AreEqual("abc", clone[123], "Compile");
            Assert.AreEqual("def", clone[456], "Compile");
        }

        [Test]
        public void TypeWithPairTest()
        {
            var orig = new TypeWithPair { Pair = new KeyValuePair<string, decimal>("abc", 123.45M) };
            var model = TypeModel.Create();
            var clone = (TypeWithPair)model.DeepClone(orig);
            Assert.AreEqual("abc", clone.Pair.Key, "Runtime");
            Assert.AreEqual(123.45M, clone.Pair.Value, "Runtime");

            model.Compile("TypeWithPairTest", "TypeWithPairTest.dll");
            PEVerify.Verify("TypeWithPairTest.dll");

            model.CompileInPlace();
            clone = (TypeWithPair)model.DeepClone(orig);
            Assert.AreEqual("abc", clone.Pair.Key, "CompileInPlace");
            Assert.AreEqual(123.45M, clone.Pair.Value, "CompileInPlace");

            clone = (TypeWithPair)model.Compile().DeepClone(orig);
            Assert.AreEqual("abc", clone.Pair.Key, "Compile");
            Assert.AreEqual(123.45M, clone.Pair.Value, "Compile");
        }

        [Test]
        public void TypeWithDictionaryTest()
        {
            var orig = new TypeWithDictionary { Data = new Dictionary<string, decimal> { { "abc", 123.45M } } };
            var model = TypeModel.Create();
            var clone = (TypeWithDictionary)model.DeepClone(orig);
            Assert.AreEqual(1, clone.Data.Count);
            Assert.AreEqual(123.45M, clone.Data["abc"], "Runtime");

            model.Compile("TypeWithDictionaryTest", "TypeWithDictionaryTest.dll");
            PEVerify.Verify("TypeWithDictionaryTest.dll");

            model.CompileInPlace();
            clone = (TypeWithDictionary)model.DeepClone(orig);
            Assert.AreEqual(1, clone.Data.Count);
            Assert.AreEqual(123.45M, clone.Data["abc"], "Runtime");

            clone = (TypeWithDictionary)model.Compile().DeepClone(orig);
            Assert.AreEqual(1, clone.Data.Count);
            Assert.AreEqual(123.45M, clone.Data["abc"], "Runtime");
        }

        [Test]
        public void ShouldWorkWithAutoLoadDisabledRuntime()
        {
            var orig = new TypeWithDictionary {Data = new Dictionary<string, decimal> {{"abc", 123.45M}}};
            var model = TypeModel.Create();
            model.AutoAddMissingTypes = false;
            model.Add(typeof (TypeWithDictionary), true);
            var clone = (TypeWithDictionary) model.DeepClone(orig);
            Assert.AreEqual(1, clone.Data.Count);
            Assert.AreEqual(123.45M, clone.Data["abc"]);
        }

        [Test]
        public void ShouldWorkWithAutoLoadDisabledAndAddedExplicitlyRuntime()
        {
            var orig = new TypeWithDictionary { Data = new Dictionary<string, decimal> { { "abc", 123.45M } } };
            var model = TypeModel.Create();
            model.AutoAddMissingTypes = false;
            model.Add(typeof(TypeWithDictionary), true);
            model.Add(typeof(KeyValuePair<string,decimal>), true);
            var clone = (TypeWithDictionary)model.DeepClone(orig);
            Assert.AreEqual(1, clone.Data.Count);
            Assert.AreEqual(123.45M, clone.Data["abc"]);
        }
        [Test]
        public void ShouldWorkWithAutoLoadDisabledCompileInPlace()
        {
            var orig = new TypeWithDictionary {Data = new Dictionary<string, decimal> {{"abc", 123.45M}}};
            var model = TypeModel.Create();
            model.AutoAddMissingTypes = false;
            model.Add(typeof (TypeWithDictionary), true);
            model.CompileInPlace();
            var clone = (TypeWithDictionary) model.DeepClone(orig);
            Assert.AreEqual(1, clone.Data.Count);
            Assert.AreEqual(123.45M, clone.Data["abc"]);
        }
        [Test]
        public void ShouldWorkWithAutoLoadDisabledCompile()
        {
            var orig = new TypeWithDictionary { Data = new Dictionary<string, decimal> { { "abc", 123.45M } } };
            var model = TypeModel.Create();
            model.AutoAddMissingTypes = false;
            model.Add(typeof(TypeWithDictionary), true);
            var clone = (TypeWithDictionary)model.Compile().DeepClone(orig);
            Assert.AreEqual(1, clone.Data.Count);
            Assert.AreEqual(123.45M, clone.Data["abc"]);
        }

        [Test]
        public void TypeWithIDictionaryTest()
        {
            var orig = new TypeWithIDictionary { Data = new Dictionary<string, decimal> { { "abc", 123.45M } } };
            var model = TypeModel.Create();
            var clone = (TypeWithIDictionary)model.DeepClone(orig);
            Assert.AreEqual(1, clone.Data.Count);
            Assert.AreEqual(123.45M, clone.Data["abc"], "Runtime");

            model.Compile("TypeWithIDictionary", "TypeWithIDictionary.dll");
            PEVerify.Verify("TypeWithIDictionary.dll");

            model.CompileInPlace();
            clone = (TypeWithIDictionary)model.DeepClone(orig);
            Assert.AreEqual(1, clone.Data.Count);
            Assert.AreEqual(123.45M, clone.Data["abc"], "Runtime");

            clone = (TypeWithIDictionary)model.Compile().DeepClone(orig);
            Assert.AreEqual(1, clone.Data.Count);
            Assert.AreEqual(123.45M, clone.Data["abc"], "Runtime");
        }

        [ProtoContract]
        public class TypeWithPair
        {
            [ProtoMember(1)]
            public KeyValuePair<string, decimal> Pair { get; set; }
        }

        [ProtoContract]
        public class TypeWithDictionary
        {
            [ProtoMember(1)]
            public Dictionary<string, decimal> Data { get; set; }
        }

        [ProtoContract]
        public class TypeWithIDictionary
        {
            [ProtoMember(1)]
            public IDictionary<string, decimal> Data { get; set; }
        }
    }
}


text:
require 'thrift/protocol'
require File.dirname(__FILE__) + '/dynomite_types'


text:
from sympy.core import Set, Dict, Tuple
from .cartan_type import Standard_Cartan
from sympy.matrices import Matrix

class TypeG(Standard_Cartan):

    def __init__(self, n):
        assert n == 2
        Standard_Cartan.__init__(self, "G", 2)

    def dimension(self):
        """
        Returns the dimension of the vector space
        V underlying the Lie algebra
        Example
        ========
        >>> from sympy.liealgebras.cartan_type import CartanType
        >>> c = CartanType("G2")
        >>> c.dimension()
        3
        """
        return 3

    def simple_root(self, i):
        """
        Every lie algebra has a unique root system.
        Given a root system Q, there is a subset of the
        roots such that an element of Q is called a
        simple root if it cannot be written as the sum
        of two elements in Q.  If we let D denote the
        set of simple roots, then it is clear that every
        element of Q can be written as a linear combination
        of elements of D with all coefficients non-negative.

        This method returns the ith simple root of G_2
        Example
        =======
        >>> from sympy.liealgebras.cartan_type import CartanType
        >>> c = CartanType("G2")
        >>> c.simple_root(1)
        [0, 1, -1]

        """
        if i == 1:
            return [0, 1, -1]
        else:
            return [1, -2, 1]

    def positive_roots(self):
        """
        This method generates all the positive roots of
        A_n.  This is half of all of the roots of A_n;
        by multiplying all the positive roots by -1 we
        get the negative roots.

        Example
        ======
        >>> from sympy.liealgebras.cartan_type import CartanType
        >>> c = CartanType("A3")
        >>> c.positive_roots()
        {1: [1, -1, 0, 0], 2: [1, 0, -1, 0], 3: [1, 0, 0, -1], 4: [0, 1, -1, 0],
                5: [0, 1, 0, -1], 6: [0, 0, 1, -1]}
        """

        roots = {1: [0, 1, -1], 2: [1, -2, 1], 3: [1, -1, 0], 4: [1, 0, 1],
                5: [1, 1, -2], 6: [2, -1, -1]}
        return roots

    def roots(self):
        """
        Returns the total number of roots of G_2"
        """
        return 12

    def cartan_matrix(self):
        """
        Returns the Cartan matrix for G_2
        The Cartan matrix matrix for a Lie algebra is
        generated by assigning an ordering to the simple
        roots, (alpha[1], ...., alpha[l]).  Then the ijth
        entry of the Cartan matrix is (<alpha[i],alpha[j]>).

        Example
        =======
        >>> from sympy.liealgebras.cartan_type import CartanType
        >>> c = CartanType("G2")
        >>> c.cartan_matrix()
        Matrix([
            [ 2, -1],
            [-3,  2]])

        """

        m = Matrix( 2, 2, [2, -1, -3, 2])
        return m

    def basis(self):
        """
        Returns the number of independent generators of G_2
        """
        return 14

    def dynkin_diagram(self):
        diag = "0≡<≡0\n1   2"
        return diag


text:
package talecraft.client.render.tileentity;

import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.tileentity.TileEntityRendererDispatcher;
import talecraft.client.ClientResources;
import talecraft.client.render.renderers.BoxRenderer;
import talecraft.proxy.ClientProxy;
import talecraft.tileentity.StorageBlockTileEntity;

public class StorageBlockTileEntityEXTRenderer implements
IEXTTileEntityRenderer<StorageBlockTileEntity> {
	@Override
	public void render(
			StorageBlockTileEntity tileentity,
			TileEntityRendererDispatcher dispatcher, double posX, double posY,
			double posZ, float partialTicks
			) {
		if(!ClientProxy.isInBuildMode())return;

		int[] bounds = tileentity.getBounds();

		if(bounds != null) {
			ClientProxy.mc.renderEngine.bindTexture(ClientResources.texColorWhite);
			GlStateManager.disableCull();

			float minX = bounds[0];
			float minY = bounds[1];
			float minZ = bounds[2];
			float maxX = bounds[3]+1;
			float maxY = bounds[4]+1;
			float maxZ = bounds[5]+1;

			float error = 1f / 1024f;

			minX -= error;
			minY -= error;
			minZ -= error;

			maxX += error;
			maxY += error;
			maxZ += error;

			float[] color = new float[3];
			tileentity.getInvokeColor(color);

			float r = color[0];
			float g = color[1];
			float b = color[2];
			float a = 1f;

			float x = tileentity.getPos().getX() + 0.5f;
			float y = tileentity.getPos().getY() + 0.5f;
			float z = tileentity.getPos().getZ() + 0.5f;

			BoxRenderer.renderWireBoxWithPointAndLines(minX, minY, minZ, maxX, maxY, maxZ, x, y, z, r, g, b, a);

			GlStateManager.enableCull();
		}
	}
}


text:
require 'pathname'
require Pathname(__FILE__).dirname.expand_path.parent.parent + 'spec_helper'

require ROOT_DIR + 'lib/data_mapper/adapters/abstract_adapter'
require __DIR__ + 'adapter_shared_spec'

describe DataMapper::Adapters::AbstractAdapter do
  before do
    @adapter = DataMapper::Adapters::AbstractAdapter.new(:default, 'mock_uri_string')
  end

  it_should_behave_like 'a DataMapper Adapter'

  it "should raise NotImplementedError when #create is called" do
    lambda { @adapter.create(:repository, :instance) }.should raise_error(NotImplementedError)
  end

  it "should raise NotImplementedError when #read is called" do
    lambda { @adapter.read(:repository, :resource, [:key]) }.should raise_error(NotImplementedError)
  end

  it "should raise NotImplementedError when #update is called" do
    lambda { @adapter.update(:repository, :instance) }.should raise_error(NotImplementedError)
  end

  it "should raise NotImplementedError when #delete is called" do
    lambda { @adapter.delete(:repository, :instance) }.should raise_error(NotImplementedError)
  end

  it "should raise NotImplementedError when #read_one is called" do
    lambda { @adapter.read_one(:repository, :query) }.should raise_error(NotImplementedError)
  end

  it "should raise NotImplementedError when #read_set is called" do
    lambda { @adapter.read_set(:repository, :query) }.should raise_error(NotImplementedError)
  end

  it "should raise NotImplementedError when #delete_set is called" do
    lambda { @adapter.delete_set(:repository, :query) }.should raise_error(NotImplementedError)
  end

end


text:
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading.Tasks;
using Elasticsearch.Net;
using FluentAssertions;
using Tests.Framework;
using static Tests.Framework.TimesHelper;
using static Elasticsearch.Net.AuditEvent;

namespace Tests.ClientConcepts.ConnectionPooling.RoundRobin
{
	public class SkippingDeadNodes
	{
		/** Round Robin - Skipping Dead Nodes
		 * When selecting nodes the connection pool will try and skip all the nodes that are marked dead.
		 */

		/** == GetNext
		* GetNext is implemented in a lock free thread safe fashion, meaning each callee gets returned its own cursor to advance
		* over the internal list of nodes. This to guarantee each request that needs to fall over tries all the nodes without
		* suffering from noisy neighboors advancing a global cursor.
		*/

		protected int NumberOfNodes = 3;

		[U] public void EachViewSkipsAheadWithOne()
		{
			var seeds = Enumerable.Range(9200, NumberOfNodes).Select(p => new Node(new Uri("http://localhost:" + p))).ToList();
			var pool = new StaticConnectionPool(seeds, randomize: false);
			for (var i = 0; i < 20; i++)
			{
				var node = pool.CreateView().First();
				node.Uri.Port.Should().Be(9200);
				node = pool.CreateView().First();
				node.Uri.Port.Should().Be(9201);
				node = pool.CreateView().First();
				node.Uri.Port.Should().Be(9202);
			}
		}

		[U] public void EachViewSeesNextButSkipsTheDeadNode()
		{
			var seeds = Enumerable.Range(9200, NumberOfNodes).Select(p => new Node(new Uri("http://localhost:" + p))).ToList();
			seeds.First().MarkDead(DateTime.Now.AddDays(1));
			var pool = new StaticConnectionPool(seeds, randomize: false);
			for (var i = 0; i < 20; i++)
			{
				var node = pool.CreateView().First();
				node.Uri.Port.Should().Be(9201);
				node = pool.CreateView().First();
				node.Uri.Port.Should().Be(9202);
			}
			/** After we marke the first node alive again we expect it to be hit again*/
			seeds.First().MarkAlive();
			for (var i = 0; i < 20; i++)
			{
				var node = pool.CreateView().First();
				node.Uri.Port.Should().Be(9201);
				node = pool.CreateView().First();
				node.Uri.Port.Should().Be(9202);
				node = pool.CreateView().First();
				node.Uri.Port.Should().Be(9200);
			}
		}
		[U] public void ViewSeesResurrectedNodes()
		{
			var dateTimeProvider = new TestableDateTimeProvider();
			var seeds = Enumerable.Range(9200, NumberOfNodes).Select(p => new Node(new Uri("http://localhost:" + p))).ToList();
			seeds.First().MarkDead(dateTimeProvider.Now().AddDays(1));
			var pool = new StaticConnectionPool(seeds, randomize: false, dateTimeProvider: dateTimeProvider);
			for (var i = 0; i < 20; i++)
			{
				var node = pool.CreateView().First();
				node.Uri.Port.Should().Be(9201);
				node = pool.CreateView().First();
				node.Uri.Port.Should().Be(9202);
			}
			/** If we forward our clock 2 days the node that was marked dead until tomorrow (or yesterday!) should be resurrected */
			dateTimeProvider.ChangeTime(d => d.AddDays(2));
			var n = pool.CreateView().First();
			n.Uri.Port.Should().Be(9201);
			n = pool.CreateView().First();
			n.Uri.Port.Should().Be(9202);
			n = pool.CreateView().First();
			n.Uri.Port.Should().Be(9200);
			n.IsResurrected.Should().BeTrue();
		}

		[U, SuppressMessage("AsyncUsage", "AsyncFixer001:Unnecessary async/await usage", Justification = "Its a test")]
		public async Task FallsOverDeadNodes()
		{
			/** A cluster with 2 nodes where the second node fails on ping */
			var audit = new Auditor(() => Framework.Cluster
				.Nodes(4)
				.ClientCalls(p => p.Succeeds(Always))
				.ClientCalls(p => p.OnPort(9201).FailAlways())
				.ClientCalls(p => p.OnPort(9203).FailAlways())
				.StaticConnectionPool()
				.Settings(p=>p.DisablePing())
			);

			await audit.TraceCalls(
				/** The first call goes to 9200 which succeeds */
				new ClientCall {
					{ HealthyResponse, 9200},
					{ pool => pool.Nodes.Where(n=>!n.IsAlive).Should().HaveCount(0) }
				},
				/** The 2nd call does a ping on 9201 because its used for the first time.
				* It fails so we wrap over to node 9202 */
				new ClientCall {
					{ BadResponse, 9201},
					{ HealthyResponse, 9202},
					/** Finally we assert that the connectionpool has one node that is marked as dead */
					{ pool =>  pool.Nodes.Where(n=>!n.IsAlive).Should().HaveCount(1) }
				},
				/** The next call goes to 9203 which fails so we should wrap over */
				new ClientCall {
					{ BadResponse, 9203},
					{ HealthyResponse, 9200},
					{ pool => pool.Nodes.Where(n=>!n.IsAlive).Should().HaveCount(2) }
				},
				new ClientCall {
					{ HealthyResponse, 9202},
					{ pool => pool.Nodes.Where(n=>!n.IsAlive).Should().HaveCount(2) }
				},
				new ClientCall {
					{ HealthyResponse, 9200},
					{ pool => pool.Nodes.Where(n=>!n.IsAlive).Should().HaveCount(2) }
				},
				new ClientCall {
					{ HealthyResponse, 9202},
					{ pool => pool.Nodes.Where(n=>!n.IsAlive).Should().HaveCount(2) }
				},
				new ClientCall {
					{ HealthyResponse, 9200},
					{ pool => pool.Nodes.Where(n=>!n.IsAlive).Should().HaveCount(2) }
				}
			);
		}

		[U, SuppressMessage("AsyncUsage", "AsyncFixer001:Unnecessary async/await usage", Justification = "Its a test")]
		public async Task PicksADifferentNodeEachTimeAnodeIsDown()
		{
			/** A cluster with 2 nodes where the second node fails on ping */
			var audit = new Auditor(() => Framework.Cluster
				.Nodes(4)
				.ClientCalls(p => p.Fails(Always))
				.StaticConnectionPool()
				.Settings(p=>p.DisablePing())
			);

			await audit.TraceCalls(
				/** All the calls fail */
				new ClientCall {
					{ BadResponse, 9200},
					{ BadResponse, 9201},
					{ BadResponse, 9202},
					{ BadResponse, 9203},
					{ MaxRetriesReached },
					{ pool => pool.Nodes.Where(n=>!n.IsAlive).Should().HaveCount(4) }
				},
				/** After all our registered nodes are marked dead we want to sample a single dead node
				* each time to quickly see if the cluster is back up. We do not want to retry all 4
				* nodes
				*/
				new ClientCall {
					{ AllNodesDead },
					{ Resurrection, 9201},
					{ BadResponse, 9201},
					{ pool =>  pool.Nodes.Where(n=>!n.IsAlive).Should().HaveCount(4) }
				},
				new ClientCall {
					{ AllNodesDead },
					{ Resurrection, 9202},
					{ BadResponse, 9202},
					{ pool =>  pool.Nodes.Where(n=>!n.IsAlive).Should().HaveCount(4) }
				},
				new ClientCall {
					{ AllNodesDead },
					{ Resurrection, 9203},
					{ BadResponse, 9203},
					{ pool =>  pool.Nodes.Where(n=>!n.IsAlive).Should().HaveCount(4) }
				},
				new ClientCall {
					{ AllNodesDead },
					{ Resurrection, 9200},
					{ BadResponse, 9200},
					{ pool =>  pool.Nodes.Where(n=>!n.IsAlive).Should().HaveCount(4) }
				}
			);
		}
	}
}


text:
/*
 * refining_driver_private.h
 *
 *  \date       Jun 20, 2011
 *  \author    	Apache Celix Project Team
 *  \copyright	Apache License, Version 2.0
 */
#ifndef REFINING_DRIVER_PRIVATE_H_
#define REFINING_DRIVER_PRIVATE_H_

#include <celix_errno.h>
#include <service_reference.h>
#include <driver.h>

#include "refining_driver_device.h"
#include "base_driver_device.h"

#define REFINING_DRIVER_ID "REFINING_DRIVER"

typedef struct refining_driver *refining_driver_pt;

celix_status_t refiningDriver_create(bundle_context_pt context, apr_pool_t *pool, refining_driver_pt *driver);
celix_status_t refiningDriver_destroy(refining_driver_pt driver);

celix_status_t refiningDriver_createService(refining_driver_pt driver, driver_service_pt *service);

celix_status_t refiningDriver_createDevice(refining_driver_pt driver, service_reference_pt reference, base_driver_device_service_pt baseDevice, refining_driver_device_pt *device);
celix_status_t refiningDriver_destroyDevice(refining_driver_device_pt device);

celix_status_t refiningDriver_attach(void *driver, service_reference_pt reference, char **result);
celix_status_t refiningDriver_match(void *driver, service_reference_pt reference, int *value);

celix_status_t refiningDriverDevice_noDriverFound(device_pt device);
celix_status_t refiningDriverDevice_createService(refining_driver_device_pt, refining_driver_device_service_pt *service);
celix_status_t refiningDriverDevice_getNextWord(refining_driver_device_pt refiningDriverDevice, apr_pool_t *pool, char **word);

#endif /* REFINING_DRIVER_PRIVATE_H_ */


text:
<project name="HelloWorld" basedir="." default="main">

	<property name="src.dir" value="src"/>
	<property name="build.dir" value="build"/>
	<property name="classes.dir" value="${build.dir}/classes"/>
	<property name="jar.dir" value="${build.dir}/jar"/>
	<property name="main-class" value="br.edu.ifsp.arq.cin.ads.ssi.HelloWorld"/>
	<property name="native.include" value="${build.dir}/native/include" />
	<property name="native.dir" value="${src.dir}/native" />

	<target name="clean">
		<delete dir="${build.dir}" />
		<delete file="${native.dir}/libhelloc.so"/>
	</target>

	<target name="compile">
		<mkdir dir="${classes.dir}" />
		<javac srcdir="${src.dir}" destdir="${classes.dir}" />
	</target>

	<target name="native">
		<mkdir dir="${native.include}" />

		<javah destdir="${native.include}" force="yes" classpath="${classes.dir}">
			<class name="${main-class}" />
		</javah>

		<exec executable="make" dir="${native.dir}" />
		<copy file="${native.dir}/libhelloc.so" todir="${jar.dir}"/>
	</target>

	<target name="jar" depends="compile,native">
		<mkdir dir="${jar.dir}" />
		<jar destfile="${jar.dir}/${ant.project.name}.jar" basedir="${classes.dir}">
			<manifest>
				<attribute name="Main-Class" value="${main-class}" />
			</manifest>
		</jar>
	</target>

	<target name="exec">
		<java jar="${jar.dir}/${ant.project.name}.jar" fork="true">
			<sysproperty key="java.library.path" path="${jar.dir}"/>
		</java>
	</target>

	<target name="run" depends="jar,exec"/>

	<target name="clean-build" depends="clean,jar" />
	<target name="main" depends="clean,run" />
</project>


text:
<?php
// We currently don't have any deprecated functions :/
$rc = new ReflectionFunction('var_dump');
var_dump($rc->isDeprecated());


text:
struct WayElement
{
  vector<uint64_t> nodes;
  uint64_t m_wayOsmId;

  explicit WayElement(uint64_t osmId) : m_wayOsmId(osmId) {}

  bool IsValid() const { return !nodes.empty(); }

  uint64_t GetOtherEndPoint(uint64_t id) const
  {
    if (id == nodes.front())
      return nodes.back();

    ASSERT(id == nodes.back(), ());
    return nodes.front();
  }

  template <class ToDo>
  void ForEachPoint(ToDo & toDo) const
  {
    for_each(nodes.begin(), nodes.end(), ref(toDo));
  }

  template <class ToDo>
  void ForEachPointOrdered(uint64_t start, ToDo && toDo)
  {
    ASSERT(!nodes.empty(), ());
    if (start == nodes.front())
      for_each(nodes.begin(), nodes.end(), ref(toDo));
    else
      for_each(nodes.rbegin(), nodes.rend(), ref(toDo));
  }

  template <class TWriter>
  void Write(TWriter & writer) const
  {
    uint64_t count = nodes.size();
    WriteVarUint(writer, count);
    for (uint64_t e : nodes)
      WriteVarUint(writer, e);
  }

  template <class TReader>
  void Read(TReader & reader)
  {
    ReaderSource<MemReader> r(reader);
    uint64_t count = ReadVarUint<uint64_t>(r);
    nodes.resize(count);
    for (uint64_t & e : nodes)
      e = ReadVarUint<uint64_t>(r);
  }

  string ToString() const
  {
    stringstream ss;
    ss << nodes.size() << " " << m_wayOsmId;
    return ss.str();
  }

  string Dump() const
  {
    stringstream ss;
    for (auto const & e : nodes)
      ss << e << ";";
    return ss.str();
  }
};

class RelationElement
{
public:
  using TMembers = vector<pair<uint64_t, string>>;

  TMembers nodes;
  TMembers ways;
  map<string, string> tags;

  bool IsValid() const { return !(nodes.empty() && ways.empty()); }

  string GetType() const
  {
    auto it = tags.find("type");
    return ((it != tags.end()) ? it->second : string());
  }

  bool FindWay(uint64_t id, string & role) const { return FindRoleImpl(ways, id, role); }
  bool FindNode(uint64_t id, string & role) const { return FindRoleImpl(nodes, id, role); }

  template <class ToDo>
  void ForEachWay(ToDo & toDo) const
  {
    for (size_t i = 0; i < ways.size(); ++i)
      toDo(ways[i].first, ways[i].second);
  }

  string GetNodeRole(uint64_t const id) const
  {
    for (size_t i = 0; i < nodes.size(); ++i)
      if (nodes[i].first == id)
        return nodes[i].second;
    return string();
  }

  string GetWayRole(uint64_t const id) const
  {
    for (size_t i = 0; i < ways.size(); ++i)
      if (ways[i].first == id)
        return ways[i].second;
    return string();
  }

  void Swap(RelationElement & rhs)
  {
    nodes.swap(rhs.nodes);
    ways.swap(rhs.ways);
    tags.swap(rhs.tags);
  }

  template <class TWriter>
  void Write(TWriter & writer) const
  {
    auto StringWriter = [&writer, this](string const & str)
    {
      CHECK_LESS(str.size(), numeric_limits<uint16_t>::max(),
                 ("Can't store string greater then 65535 bytes", Dump()));
      uint16_t sz = static_cast<uint16_t>(str.size());
      writer.Write(&sz, sizeof(sz));
      writer.Write(str.data(), sz);
    };

    auto MembersWriter = [&writer, &StringWriter](TMembers const & members)
    {
      uint64_t count = members.size();
      WriteVarUint(writer, count);
      for (auto const & e : members)
      {
        // write id
        WriteVarUint(writer, e.first);
        // write role
        StringWriter(e.second);
      }
    };

    MembersWriter(nodes);
    MembersWriter(ways);

    uint64_t count = tags.size();
    WriteVarUint(writer, count);
    for (auto const & e : tags)
    {
      // write key
      StringWriter(e.first);
      // write value
      StringWriter(e.second);
    }
  }

  template <class TReader>
  void Read(TReader & reader)
  {
    ReaderSource<TReader> r(reader);

    auto StringReader = [&r](string & str)
    {
      uint16_t sz = 0;
      r.Read(&sz, sizeof(sz));
      str.resize(sz);
      r.Read(&str[0], sz);
    };

    auto MembersReader = [&r, &StringReader](TMembers & members)
    {
      uint64_t count = ReadVarUint<uint64_t>(r);
      members.resize(count);
      for (auto & e : members)
      {
        // decode id
        e.first = ReadVarUint<uint64_t>(r);
        // decode role
        StringReader(e.second);
      }
    };

    MembersReader(nodes);
    MembersReader(ways);

    // decode tags
    tags.clear();
    uint64_t count = ReadVarUint<uint64_t>(r);
    for (uint64_t i = 0; i < count; ++i)
    {
      pair<string, string> kv;
      // decode key
      StringReader(kv.first);
      // decode value
      StringReader(kv.second);
      tags.emplace(kv);
    }
  }

  string ToString() const
  {
    stringstream ss;
    ss << nodes.size() << " " << ways.size() << " " << tags.size();
    return ss.str();
  }

  string Dump() const
  {
    stringstream ss;
    for (auto const & e : nodes)
      ss << "n{" << e.first << "," << e.second << "};";
    for (auto const & e : ways)
      ss << "w{" << e.first << "," << e.second << "};";
    for (auto const & e : tags)
      ss << "t{" << e.first << "," << e.second << "};";
    return ss.str();
  }

protected:
  bool FindRoleImpl(TMembers const & container, uint64_t id, string & role) const
  {
    for (auto const & e : container)
    {
      if (e.first == id)
      {
        role = e.second;
        return true;
      }
    }
    return false;
  }
};


text:
using System.IO;
using System.Text.RegularExpressions;
using System.Threading;

namespace SvnAutoCommitter.Core {
    public class FileSystemItem {
        private readonly string _fullPath = "";
        private FileSystemInfo _entry;

        public FileSystemItem(string fullPath) {
            _fullPath = fullPath;
            Refresh();
        }

        public void Refresh() {
            var directory = new DirectoryInfo(_fullPath);
            if (directory.Exists) {
                _entry = directory;
            }

            _entry = new FileInfo(_fullPath);
        }

        public string FullPath {
            get { return _fullPath; }
        }

        public bool IsFile {
            get { return (_entry is FileInfo) && _entry.Exists; }
        }

        public bool IsFolder {
            get { return _entry is DirectoryInfo; }
        }

        public bool Exists {
            get { return _entry.Exists; }
        }

        public bool IsTemp {
            get { return _entry.Attributes != (FileAttributes)(-1) && _entry.Attributes.HasFlag(FileAttributes.Temporary); }
        }

        public bool IsHidden {
            get { return _entry.Attributes != (FileAttributes)(-1) && _entry.Attributes.HasFlag(FileAttributes.Hidden); }
        }

        //Ignore umbraco temp files, svn files, hidden files and folders and temp file and folders
        public bool ShouldBeIgnored {
            get { return Regex.IsMatch(FullPath, "\\\\\\d{18}_") || FullPath.Contains(".svn") || IsHidden || IsTemp; }
        }

        public bool IsFileReadyToRead(int maxTry) {
            var attempt = 0;
            var waitBeforeTry = 1000;
            while (attempt < maxTry) {
                attempt++;
                try {
                    using (new StreamReader(FullPath)) {
                        return true;
                    }
                }
                catch {
                    Thread.Sleep(waitBeforeTry);
                }
            }

            return false;
        }
    }
}


text:
// Copyright (c) All contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace PInvoke
{
    /// <content>
    /// Contains the <see cref="SHGetFolderPathFlags"/> nested type.
    /// </content>
    public partial class Shell32
    {
        /// Flags that specify the path to be returned. Used in cases where the folder associated with a <see cref="KNOWNFOLDERID"/> (or CSIDL) can be moved, renamed, redirected, or roamed across languages by a user or administrator.
        public enum SHGetFolderPathFlags
        {
            /// Retrieve the folder's current path.
            /// <remarks>
            /// The known folder system that underlies <see cref="SHGetFolderPath(System.IntPtr, CSIDL, System.IntPtr, SHGetFolderPathFlags, char*)"/> allows users or administrators to redirect a known folder to a location that suits their needs.
            /// This is achieved by calling IKnownFolderManager::Redirect, which sets the "current" value of the folder associated with the SHGFP_TYPE_CURRENT flag
            /// </remarks>
            SHGFP_TYPE_CURRENT = 0,

            /// Retrieve the folder's default path.
            /// <remarks>
            /// The default value of the folder, which is the location of the folder if a user or administrator had not redirected it elsewhere,
            /// is retrieved by specifying the SHGFP_TYPE_DEFAULT flag. This value can be used to implement a "restore defaults" feature for a known folder.
            /// </remarks>
            SHGFP_TYPE_DEFAULT = 1
        }
    }
}


text:
<!--
    @license
    Copyright (c) 2014 The Polymer Project Authors. All rights reserved.
    This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
    The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
    The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
    Code distributed by Google as part of the polymer project is also
    subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
-->
<!doctype html>
<html>
<head>
  <title>x-palette</title>
  <script src="../platform/platform.js"></script>
  <link rel="import" href="../x-palette/x-palette.html">
  <style>
    html {
      position: relative;
      height: 100%;
    }
    body {
      font-family: Neue Helvetica, Roboto, Arial;
      height: 100%;
      margin: 0;
      overflow: hidden;
    }
    x-palette {
      display: block;
      overflow: hidden;
      position: absolute !important;
      top: 0;
      right: 0;
      bottom: 0;
      left: 0;
    }
  </style>
  <link rel="import" href="../polymer-ui-elements/metadata.html">
</head>
<body>
  <x-palette></x-palette>
  <template>
    <link rel="import" href="../polymer-elements/metadata.html">
    <link rel="import" href="../more-elements/metadata.html">
  </template>
  <script>
    setTimeout(function() {
      var doc = document.querySelector('template').content;
      HTMLImports.importer.load(doc, function() {
        doc.querySelectorAll('link').array().forEach(
          function(link) {
            HTMLImports.parser.parse(link.content);
            CustomElements.parser.parse(link.content);
          }
        );
      });
    }, 2000);
  </script>
</body>
</html>


text:
package io.quarkus.funqy.knative.events;

import java.time.OffsetDateTime;
import java.util.Map;

/**
 * CloudEvent.
 *
 */
public interface CloudEvent<T> {

    String id();

    String specVersion();

    String source();

    String type();

    String subject();

    OffsetDateTime time();

    Map<String, String> extensions();

    String dataSchema();

    String dataContentType();

    T data();

}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
                      http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.xito</groupId>
        <artifactId>module-parent</artifactId>
        <version>2.0-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>

    <artifactId>launcher</artifactId>

    <properties>
        <assemblyLocation>${basedir}/../service-assembly.xml</assemblyLocation>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.xito</groupId>
            <artifactId>bootstrap</artifactId>
            <version>${project.version}</version>
        </dependency>

        <dependency>
            <groupId>org.xito</groupId>
            <artifactId>dazzle</artifactId>
            <version>${project.version}</version>
        </dependency>

        <dependency>
            <groupId>net.sf.jtidy</groupId>
            <artifactId>jtidy</artifactId>
            <version>r938</version>
        </dependency>

        <dependency>
            <groupId>javax</groupId>
            <artifactId>jnlp</artifactId>
            <version>1.0.0</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/jnlp.jar</systemPath>
        </dependency>

        <dependency>
            <groupId>jdom</groupId>
            <artifactId>jdom</artifactId>
            <version>1.1</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-resources-plugin</artifactId>
                <version>2.6</version>
                <executions>
                    <!-- Copy of Service Resources to target -->
                    <execution>
                        <id>copy-libs</id>
                        <!-- here the phase you need -->
                        <phase>package</phase>
                        <goals>
                            <goal>copy-resources</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${project.build.directory}/${project.artifactId}</outputDirectory>
                            <resources>
                                <resource>
                                    <directory>lib</directory>
                                </resource>
                            </resources>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

    <profiles>
        <profile>
            <id>test_exec</id>
            <build>
                <plugins>

                    <!-- Copy the test_exec resources -->
                    <plugin>
                        <artifactId>maven-resources-plugin</artifactId>
                        <version>2.6</version>
                        <executions>
                            <execution>
                                <id>copy-test-exec-resources</id>
                                <phase>package</phase>
                                <goals>
                                    <goal>copy-resources</goal>
                                </goals>
                                <configuration>
                                    <outputDirectory>${project.build.directory}/test_exec</outputDirectory>
                                    <resources>
                                        <resource>
                                            <directory>${basedir}/resources/test_exec</directory>
                                            <filtering>true</filtering>
                                        </resource>
                                    </resources>
                                </configuration>
                            </execution>
                        </executions>
                    </plugin>

                    <!-- Copy the Bootstrap Jar -->
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-dependency-plugin</artifactId>
                        <version>2.8</version>
                        <executions>
                            <execution>
                                <id>copy-bootstrap</id>
                                <phase>package</phase>
                                <goals>
                                    <goal>copy</goal>
                                </goals>
                                <configuration>
                                    <artifactItems>
                                        <artifactItem>
                                            <groupId>org.xito</groupId>
                                            <artifactId>bootstrap</artifactId>
                                            <version>2.0-SNAPSHOT</version>
                                            <type>jar</type>
                                            <stripVersion>false</stripVersion>
                                            <overWrite>true</overWrite>
                                        </artifactItem>
                                    </artifactItems>
                                    <outputDirectory>${project.build.directory}/test_exec</outputDirectory>
                                </configuration>
                            </execution>
                        </executions>
                    </plugin>

                    <!-- Copy and unpack the services into the test_exec dir -->
                    <plugin>

                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-dependency-plugin</artifactId>
                        <version>2.8</version>
                        <executions>
                            <execution>
                                <id>unpack-service-dependencies</id>
                                <phase>package</phase>
                                <goals>
                                    <goal>unpack</goal>
                                </goals>
                                <configuration>
                                    <artifactItems>

                                        <artifactItem>
                                            <groupId>org.xito</groupId>
                                            <artifactId>launcher</artifactId>
                                            <version>${project.version}</version>
                                            <type>zip</type>
                                            <overWrite>true</overWrite>
                                        </artifactItem>

                                        <artifactItem>
                                            <groupId>org.xito</groupId>
                                            <artifactId>xmldocs</artifactId>
                                            <version>${project.version}</version>
                                            <type>zip</type>
                                            <overWrite>true</overWrite>
                                        </artifactItem>

                                        <artifactItem>
                                            <groupId>org.xito</groupId>
                                            <artifactId>prefs</artifactId>
                                            <version>${project.version}</version>
                                            <type>zip</type>
                                            <overWrite>true</overWrite>
                                        </artifactItem>

                                        <artifactItem>
                                            <groupId>org.xito</groupId>
                                            <artifactId>dazzle</artifactId>
                                            <version>${project.version}</version>
                                            <type>zip</type>
                                            <overWrite>true</overWrite>
                                        </artifactItem>

                                        <artifactItem>
                                            <groupId>org.xito</groupId>
                                            <artifactId>jdic</artifactId>
                                            <version>${project.version}</version>
                                            <type>zip</type>
                                            <overWrite>true</overWrite>
                                        </artifactItem>

                                    </artifactItems>
                                    <outputDirectory>${project.build.directory}/test_exec</outputDirectory>
                                </configuration>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>

</project>


text:
import {isCancelError} from '../utils/errors';
import {warn} from '../utils/log';

/** @enum {number} */
const CallbackId = {
  ENTITLEMENTS: 1,
  SUBSCRIBE_REQUEST: 2,
  PAYMENT_RESPONSE: 3,
  LOGIN_REQUEST: 4,
  LINK_PROGRESS: 5,
  LINK_COMPLETE: 6,
  FLOW_STARTED: 7,
  FLOW_CANCELED: 8,
  PAY_CONFIRM_OPENED: 9,
  OFFERS_FLOW_REQUEST: 10,
};

/**
 */
export class Callbacks {
  /**
   */
  constructor() {
    /** @private @const {!Object<CallbackId, function(*)>} */
    this.callbacks_ = {};
    /** @private @const {!Object<CallbackId, *>} */
    this.resultBuffer_ = {};
    /** @private {?Promise} */
    this.paymentResponsePromise_ = null;
  }

  /**
   * @param {function(!Promise<!../api/entitlements.Entitlements>)} callback
   */
  setOnEntitlementsResponse(callback) {
    this.setCallback_(CallbackId.ENTITLEMENTS, callback);
  }

  /**
   * @param {!Promise<!../api/entitlements.Entitlements>} promise
   */
  triggerEntitlementsResponse(promise) {
    return this.trigger_(
      CallbackId.ENTITLEMENTS,
      promise.then((res) => res.clone())
    );
  }

  /**
   * @return {boolean}
   */
  hasEntitlementsResponsePending() {
    return !!this.resultBuffer_[CallbackId.ENTITLEMENTS];
  }

  /**
   * @param {function(!../api/subscriptions.LoginRequest)} callback
   */
  setOnLoginRequest(callback) {
    this.setCallback_(CallbackId.LOGIN_REQUEST, callback);
  }

  /**
   * @param {!../api/subscriptions.LoginRequest} request
   * @return {boolean} Whether the callback has been found.
   */
  triggerLoginRequest(request) {
    return this.trigger_(CallbackId.LOGIN_REQUEST, request);
  }

  /**
   * @param {function()} callback
   */
  setOnLinkProgress(callback) {
    this.setCallback_(CallbackId.LINK_PROGRESS, callback);
  }

  /**
   * @return {boolean} Whether the callback has been found.
   */
  triggerLinkProgress() {
    return this.trigger_(CallbackId.LINK_PROGRESS, true);
  }

  /**
   */
  resetLinkProgress() {
    this.resetCallback_(CallbackId.LINK_PROGRESS);
  }

  /**
   * @param {function()} callback
   */
  setOnLinkComplete(callback) {
    this.setCallback_(CallbackId.LINK_COMPLETE, callback);
  }

  /**
   * @return {boolean} Whether the callback has been found.
   */
  triggerLinkComplete() {
    return this.trigger_(CallbackId.LINK_COMPLETE, true);
  }

  /**
   * @return {boolean}
   */
  hasLinkCompletePending() {
    return !!this.resultBuffer_[CallbackId.LINK_COMPLETE];
  }

  /**
   * @param {function(!../ui/activity-iframe-view.ActivityIframeView)} callback
   */
  setOnPayConfirmOpened(callback) {
    this.setCallback_(CallbackId.PAY_CONFIRM_OPENED, callback);
  }

  /**
   * @param {!../ui/activity-iframe-view.ActivityIframeView} activityIframeView
   * @return {boolean} Whether the callback has been found.
   */
  triggerPayConfirmOpened(activityIframeView) {
    return this.trigger_(CallbackId.PAY_CONFIRM_OPENED, activityIframeView);
  }

  /**
   * @param {function()} callback
   */
  setOnSubscribeRequest(callback) {
    this.setCallback_(CallbackId.SUBSCRIBE_REQUEST, callback);
  }

  /**
   * @return {boolean} Whether the callback has been found.
   */
  triggerSubscribeRequest() {
    return this.trigger_(CallbackId.SUBSCRIBE_REQUEST, true);
  }

  /**
   * @return {boolean}
   */
  hasSubscribeRequestCallback() {
    return !!this.callbacks_[CallbackId.SUBSCRIBE_REQUEST];
  }

  /**
   * @param {function()} callback
   */
  setOnOffersFlowRequest(callback) {
    this.setCallback_(CallbackId.OFFERS_FLOW_REQUEST, callback);
  }

  /**
   * @return {boolean} Whether the callback has been found.
   */
  triggerOffersFlowRequest() {
    return this.trigger_(CallbackId.OFFERS_FLOW_REQUEST, true);
  }

  /**
   * @return {boolean}
   */
  hasOffersFlowRequestCallback() {
    return !!this.callbacks_[CallbackId.OFFERS_FLOW_REQUEST];
  }

  /**
   * @param {function(!Promise<!../api/subscribe-response.SubscribeResponse>)} callback
   */
  setOnSubscribeResponse(callback) {
    warn(
      `[swg.js:setOnSubscribeResponse]: This method has been deprecated, please switch usages to 'setOnPaymentResponse'`
    );
    this.setCallback_(CallbackId.PAYMENT_RESPONSE, callback);
  }

  /**
   * @param {function(!Promise<!../api/subscribe-response.SubscribeResponse>)} callback
   */
  setOnContributionResponse(callback) {
    warn(
      `[swg.js:setOnContributionResponse]: This method has been deprecated, please switch usages to 'setOnPaymentResponse'`
    );
    this.setCallback_(CallbackId.PAYMENT_RESPONSE, callback);
  }

  /**
   * @param {function(!Promise<!../api/subscribe-response.SubscribeResponse>)} callback
   */
  setOnPaymentResponse(callback) {
    this.setCallback_(CallbackId.PAYMENT_RESPONSE, callback);
  }

  /**
   * @param {!Promise<!../api/subscribe-response.SubscribeResponse>} responsePromise
   * @return {boolean} Whether the callback has been found.
   */
  triggerPaymentResponse(responsePromise) {
    this.paymentResponsePromise_ = responsePromise.then(
      (res) => {
        this.trigger_(
          CallbackId.PAYMENT_RESPONSE,
          Promise.resolve(res.clone())
        );
      },
      (reason) => {
        if (isCancelError(reason)) {
          return;
        }
        throw reason;
      }
    );
    return !!this.callbacks_[CallbackId.PAYMENT_RESPONSE];
  }

  /**
   * @return {boolean}
   */
  hasPaymentResponsePending() {
    return !!this.resultBuffer_[CallbackId.PAYMENT_RESPONSE];
  }

  /**
   * @param {function({flow: string, data: !Object})} callback
   */
  setOnFlowStarted(callback) {
    this.setCallback_(CallbackId.FLOW_STARTED, callback);
  }

  /**
   * @param {string} flow
   * @param {!Object=} data
   * @return {boolean} Whether the callback has been found.
   */
  triggerFlowStarted(flow, data = {}) {
    return this.trigger_(CallbackId.FLOW_STARTED, {
      flow,
      data,
    });
  }

  /**
   * @param {function({flow: string, data: !Object})} callback
   */
  setOnFlowCanceled(callback) {
    this.setCallback_(CallbackId.FLOW_CANCELED, callback);
  }

  /**
   * @param {string} flow
   * @param {!Object=} data
   * @return {boolean} Whether the callback has been found.
   */
  triggerFlowCanceled(flow, data = {}) {
    return this.trigger_(CallbackId.FLOW_CANCELED, {
      flow,
      data,
    });
  }

  /**
   * @param {!CallbackId} id
   * @param {function(?)} callback
   * @private
   */
  setCallback_(id, callback) {
    if (this.callbacks_[id]) {
      warn(
        `[swg.js]: You have registered multiple callbacks for the same response.`
      );
    }
    this.callbacks_[id] = callback;
    // If result already exist, execute the callback right away.
    if (id in this.resultBuffer_) {
      this.executeCallback_(id, callback, this.resultBuffer_[id]);
    }
  }

  /**
   * @param {!CallbackId} id
   * @param {*} data
   * @return {boolean}
   * @private
   */
  trigger_(id, data) {
    this.resultBuffer_[id] = data;
    const callback = this.callbacks_[id];
    if (callback) {
      this.executeCallback_(id, callback, data);
    }
    return !!callback;
  }

  /**
   * @param {!CallbackId} id
   * @private
   */
  resetCallback_(id) {
    if (id in this.resultBuffer_) {
      delete this.resultBuffer_[id];
    }
  }

  /**
   * @param {!CallbackId} id
   * @param {function(*)} callback
   * @param {*} data
   * @private
   */
  executeCallback_(id, callback, data) {
    // Always execute callbacks in a microtask.
    Promise.resolve().then(() => {
      callback(data);
      this.resetCallback_(id);
    });
  }
}


text:
'use strict';

const stew = require('broccoli-stew');

module.exports = {
  name: require('./package').name,

  preprocessTree(type, tree) {
    return stew.map(tree, contents => contents.replace('RAW', 'PREPROCESSED'));
  },
};


text:
install_path=$1

ln -s $install_path/bin/zerotier-one /usr/sbin/zerotier-one
ln -s $install_path/bin/zerotier-one /usr/sbin/zerotier-cli
ln -s $install_path/bin/zerotier-one /usr/bin/zerotier-one
ln -s $install_path/bin/zerotier-one /usr/bin/zerotier-cli

ln -s $install_path/ /var/lib/zerotier-one

ln -s $install_path/webpage /var/www/zerotier
ln -s $install_path/cgi/* /var/www/cgi-bin/


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JokeSpider
{
    public class JokeInfo
    {
        public string Title { set; get; }
        public string Content { set; get; }
    }
}


text:
#ifndef FILEINPUT_H
#define FILEINPUT_H

#include "ExceptionBase.h"

using namespace std;

#include <fstream>
#include <iostream>

namespace Bavieca {

/**
	@author daniel <dani.bolanos@gmail.com>
*/
class FileInput {

	private:

		bool m_bBinary;			// whether binary or text mode
		ifstream m_is;
		string m_strFile;

	public:

		// constructor
		FileInput(const char *strFile, bool bBinary);

		// destructor
		~FileInput();

		// open the file
		void open();

		// close the file
		void close();

		// return the file size in bytes
		long size();

		// return the stream
		istream &getStream() {

			return m_is;
		}
};

};	// end-of-namespace

#endif


text:
.class Lcom/android/internal/telephony/cdma/HtcRadio$AlarmIntentReceiver;
.super Landroid/content/BroadcastReceiver;
.source "HtcRadio.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/internal/telephony/cdma/HtcRadio;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x2
    name = "AlarmIntentReceiver"
.end annotation

# instance fields
.field final synthetic this$0:Lcom/android/internal/telephony/cdma/HtcRadio;

# direct methods
.method private constructor <init>(Lcom/android/internal/telephony/cdma/HtcRadio;)V
    .locals 0
    .parameter

    .prologue
    .line 174
    iput-object p1, p0, Lcom/android/internal/telephony/cdma/HtcRadio$AlarmIntentReceiver;->this$0:Lcom/android/internal/telephony/cdma/HtcRadio;

    invoke-direct {p0}, Landroid/content/BroadcastReceiver;-><init>()V

    return-void
.end method

.method synthetic constructor <init>(Lcom/android/internal/telephony/cdma/HtcRadio;Lcom/android/internal/telephony/cdma/HtcRadio$1;)V
    .locals 0
    .parameter "x0"
    .parameter "x1"

    .prologue
    .line 174
    invoke-direct {p0, p1}, Lcom/android/internal/telephony/cdma/HtcRadio$AlarmIntentReceiver;-><init>(Lcom/android/internal/telephony/cdma/HtcRadio;)V

    return-void
.end method

# virtual methods
.method public onReceive(Landroid/content/Context;Landroid/content/Intent;)V
    .locals 4
    .parameter "context"
    .parameter "intent"

    .prologue
    const/4 v3, 0x0

    .line 180
    invoke-virtual {p2}, Landroid/content/Intent;->getAction()Ljava/lang/String;

    move-result-object v0

    const-string v1, "com.android.internal.telephony.cdma-flight.mode"

    invoke-virtual {v0, v1}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z

    move-result v0

    if-eqz v0, :cond_1

    .line 181
    iget-object v0, p0, Lcom/android/internal/telephony/cdma/HtcRadio$AlarmIntentReceiver;->this$0:Lcom/android/internal/telephony/cdma/HtcRadio;

    const-string v1, "timerId"

    iget-object v2, p0, Lcom/android/internal/telephony/cdma/HtcRadio$AlarmIntentReceiver;->this$0:Lcom/android/internal/telephony/cdma/HtcRadio;

    #getter for: Lcom/android/internal/telephony/cdma/HtcRadio;->mFlightModeTimerId:I
    invoke-static {v2}, Lcom/android/internal/telephony/cdma/HtcRadio;->access$100(Lcom/android/internal/telephony/cdma/HtcRadio;)I

    move-result v2

    add-int/lit8 v2, v2, -0x1

    invoke-virtual {p2, v1, v2}, Landroid/content/Intent;->getIntExtra(Ljava/lang/String;I)I

    move-result v1

    #calls: Lcom/android/internal/telephony/cdma/HtcRadio;->timeoutFlightModePerioid(IZ)V
    invoke-static {v0, v1, v3}, Lcom/android/internal/telephony/cdma/HtcRadio;->access$200(Lcom/android/internal/telephony/cdma/HtcRadio;IZ)V

    .line 186
    :cond_0
    :goto_0
    return-void

    .line 183
    :cond_1
    invoke-virtual {p2}, Landroid/content/Intent;->getAction()Ljava/lang/String;

    move-result-object v0

    const-string v1, "com.android.internal.telephony.cdma-flight.workaround"

    invoke-virtual {v0, v1}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z

    move-result v0

    if-eqz v0, :cond_0

    .line 184
    iget-object v0, p0, Lcom/android/internal/telephony/cdma/HtcRadio$AlarmIntentReceiver;->this$0:Lcom/android/internal/telephony/cdma/HtcRadio;

    const-string v1, "timerId"

    iget-object v2, p0, Lcom/android/internal/telephony/cdma/HtcRadio$AlarmIntentReceiver;->this$0:Lcom/android/internal/telephony/cdma/HtcRadio;

    #getter for: Lcom/android/internal/telephony/cdma/HtcRadio;->mWorkaroundTimerId:I
    invoke-static {v2}, Lcom/android/internal/telephony/cdma/HtcRadio;->access$300(Lcom/android/internal/telephony/cdma/HtcRadio;)I

    move-result v2

    add-int/lit8 v2, v2, -0x1

    invoke-virtual {p2, v1, v2}, Landroid/content/Intent;->getIntExtra(Ljava/lang/String;I)I

    move-result v1

    #calls: Lcom/android/internal/telephony/cdma/HtcRadio;->timeoutWorkaroundPerioid(IZ)V
    invoke-static {v0, v1, v3}, Lcom/android/internal/telephony/cdma/HtcRadio;->access$400(Lcom/android/internal/telephony/cdma/HtcRadio;IZ)V

    goto :goto_0
.end method


text:
package ru.burov4j.storm.rabbitmq;

import org.junit.Before;
import org.mockito.Mockito;

import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.spy;

/**
 *
 * @author Andrey Burov
 */
public abstract class StormRabbitMqTest extends RabbitMqTest {

    RabbitMqChannelFactory rabbitMqChannelFactory;

    @Before
    public void setUpChannelFactory() {
        rabbitMqChannelFactory = Mockito.spy(RabbitMqChannelFactory.class);
        doReturn(mockConnectionFactory).when(rabbitMqChannelFactory).createConnectionFactory();
    }
}


text:
path: /velocity-europe-2014-day-2
title: Retour sur la Velocity Barcelone - seconde journée
description: ''
date: '2014-11-24T00:00:00+01:00'
tags:
  - conference
  - velocity
  - webperf
image: velocity_banner2.jpg
imageCredit: oreillyconf
imageCreditLink: ~
authors:
  - name: Baptiste Dupain
    avatar: ~
    email: ~
    twitter: ~
    facebook: ~
    github: ~
  - name: François Verron
    avatar: ~
    email: ~
    twitter: ~
    facebook: ~
    github: ~
  - name: Olivier Mansour
    avatar: ~
    email: ~
    twitter: ~
    facebook: ~
    github: ~
lang: fr
---

# Velocity Barcelone, seconde journée

Deuxième jour de conférence avec un programme encore plus chargé et quelques conférences alléchantes repérées au préalable.

## Morning Keynotes

### Upgrading the Web: Polyfills, Components and the Future of Web Development at Scale - Andrew Betts (FT Labs)

 L'orateur fait remarquer que de nombreux systèmes existent pour packager et gérer les dépendances des applications backends, mais rien n'est disponible pour les composants webs. Il nous a présenté le projet [Origami](http://origami.ft.com/) qui permet de réutiliser massivement des composants HTML.

 Slides : [the Future of Web Development at Scale](http://cdn.oreillystatic.com/en/assets/1/event/121/Upgrading%20the%20Web_%20Polyfills,%20Components%20and%20the%20Future%20of%20Web%20Development%20at%20Scale%20Presentation.pdf)

### Troubleshooting Using HTTP Headers - Steve Miller-Jones (Limelight Networks)

 Slides : [Troubleshooting Using HTTP Headers](http://cdn.oreillystatic.com/en/assets/1/event/121/Troubleshooting%20Using%20HTTP%20Headers%20Presentation.pptx)

  Un employé de Limelight nous a présenté comment l'ajout de headers dans une requête pouvait renvoyer des headers supplémentaires dans la réponse HTTP. Cela peut être utile pour débugguer et analyser un incident.
  Cette présentation nous a rappelé, qu'en interne, [nos gentils ops](https://s3-eu-west-1.amazonaws.com/uploads-eu.hipchat.com/40462/467784/bB5W31POypiBcuF/LSpC0ZX.gif) nous permettent déjà de faire ce genre chose sur nos proxy cache.

### Monitoring without Alerts - and Why it Makes Way More Sense than You Might Think - Alois Reitbauer (ruxit.com)

 Alois Reitbauer a évoqué la solution [Ruxit](https://ruxit.com/) développée depuis plus de trois ans. Cette solution consiste à installer un agent sur vos serveurs qui va automatiquement détecter des anomalies statistiques et corréler cette information avec d'autres déviations dans le but de trouver la *root cause* d'un incident.

 Beaucoup d'autres solutions de ce genre existent (et la plupart étaient dans le salon des sponsors). Nous n'avons pas été totalement convaincu de leurs capacités à détecter des *root cause*, mais elles sont toutes assez intéressantes et matures.

### Lowering the Barrier to Programming - Pamela Fox (Khan Academy)

 Pamela Fox nous a présenté l'initiative [code.org](http://code.org/promote), dont le but est de promouvoir l'enseignement de l'informatique (bon, apparement seulement aux US).

  Elle a également donné quelques conseils si on veut s'investir dans l'enseignement de l'informatique à destination des plus jeunes. Par exemple créer un *code club*.

 Slides : [Lowering the Barrier to Programming](http://cdn.oreillystatic.com/en/assets/1/event/121/Lowering%20the%20Barrier%20to%20Programming%20Presentation.pdf)

### Velocity at GitHub - Brian Doll (GitHub)

 Brian a fait une présentation très ... minimaliste. Il est revenu rapidement sur 7 ans de développement à GitHub et comment ils sont venus à développer l'Enterprise Edition. Il a évoqué différents problèmes que certains de leurs clients avaient et notamment avec l'utilisation de GE en environnement cloud.

 Il a donc annoncé le lancement de GitHub Enterprise 2.0 qui fonctionne maintenant sur AWS (et un changement de la grille tarifaire) !

 J'ai profité d'un instant avec lui pour lui présenter [GitHubTeamReviewer](http://tech.m6web.fr/github-team-reviewer-pull-requests.html) (un outil interne open-sourcé). Il était enchanté de découvrir ce qui avait été fait avec l'API de Github. Il a indiqué que l'entreprise travaillait actuellement sur des vues permettant de pallier aux problèmes résolus par GitHubTeamReviewer.

## HTTP Archive and Google Cloud Dataflow - Ilya Grigorik (Google)

 Ilya Grigorik a présenté [http://bigqueri.es/](http://bigqueri.es/), un outil permettant d'interroger [HTTP archive](http://httparchive.org/). La nouveauté est que le *body* des requêtes est maintenant conservé et que l'on peut l'analyser. Un *engine* Javascript a été intégré au SQL de bigqueries permettant de faire des requêtes très puissantes.

 Pour ceux qui ne voudraient pas se plonger dedans, beaucoup de recherches faites par d'autres utilisateurs sont disponibles et abondamment discutées ([exemple](http://bigqueri.es/t/are-popular-websites-faster/162)).

 ![bigqueries](./bigqueries.jpg)

### Webpagetest-automation 2.0 - Nils Kuhn (iteratec GmbH), Uwe Beßle (iteratec GmbH)

 Webpagetest est un outil formidable mais il est difficile à automatiser. Les orateurs ont présentés un outil pour le faire, permettant donc de réaliser une mesure continuelle de la webperf avec un parcours utilisateur complet - démonstration à l'appui.

 Leur travail est disponible sur GitHub sous licence Apache : [https://github.com/IteraSpeed/OpenSpeedMonitor](https://github.com/IteraSpeed/OpenSpeedMonitor). Un grand merci <3 ! (à 10 minutes sur la vidéo).

![openspeed](./openspeed.jpg)

---

## Etsy's Journey to Building a Continuous Integration Infrastructure for Mobile Apps - Nassim Kammah (Etsy)

Une parmi les très nombreuses conférences Etsy sur la Vélocity (le moment de renouveller les conférenciers ?). Nassim Kammah nous a expliqué comment Etsy délivrait ses applications iOS.

La livraison des applications sous iOS est au même stade que la diffusion des logiciels via CD-ROMs. Partant de ce constat un système de build (avec 25 mac-minis derrière) a été mis en place à chaque commit sur le *master*. On ne peut pas délivrer une version de l'application tous les jours aux clients, mais on peut le faire pour les employés (and *eat your own dog food*) !

Il y a également [un système de gamification](https://github.com/etsy/BugHunt-iOS), autour de l'application livrée journalièrement, afin de motiver tout le monde à trouver des bugs.

![esty-devbuild](./esty-devbuild.jpg)

Des tests unitaires sont mis en place, ainsi que des tests fonctionnels avec [AppThwack](https://appthwack.com/). Il est intéressant de constater qu'ils n'attendent pas, pour les tests fonctionnels, une réussite à 100% de la suite mais une tendance positive.

Les équipes ont également mis en place des *testing dojos* dans lesquels les ingénieurs QA encadrent des salariés d'Etsy et testent à fond les applications.

On peut retrouver tous les éléments de cette conférence sur le [blog technique d'Etsy](https://codeascraft.com/2014/02/28/etsys-journey-to-continuous-integration-for-mobile-apps/).

---

## Recycling: Why the Web is Slowing Your Mobile App - Colin Bendell (Akamai)

Pourquoi recycler nos contenus pour les applications mobiles ?

- accélérer le *time to market*.
- réduire le risque

Les APIs encouragent le recyclage.

![recycling](./recycling.jpg)

Colin Blendel nous encourage à utiliser les mêmes recettes que pour les navigateurs web et à en ajouter d'autres :

 - gérer le pool de connexions en groupant les appels par domaine (quitte à les passer séquentiellement, par exemple, si des cookies sont utilisés),
 - surveiller les *packet eaters* (headers inutiles, *Set-Cookies* répétés),
 - setter correctement *Content-Type* sur des types standard (les exemples de content-type tirés des logs d'Akamai sont assez drôles, comme par exemple test/binary ^^ !),
 - faire un minimum de redirections,
 - fragmenter son cache au minumum (quitte à calculer des clés plus consistantes coté client),
 - ajouter du cache (Max-Age: 30s c'est à peu près du temps réel et ça change tout pour un CDN),
 - préfetcher les urls présentes dans les retours d'API, car on va surement en avoir besoin immédiatement après,
 - ne pas hésiter à mettre CRUD au placard et merger plusieurs appels API en un seul ; il faut trouver une balance efficace pour bien gérer la webperf.

Une présentation dense et vraiment intéressante !

Slides : [Why the Web is Slowing Your Mobile App](http://www.slideshare.net/colinbendell/velocity-eu-2014-recycling-the-web-why)

---

## Breaking News at 1000ms

Le Guardian est un journal Anglais présent sur le web et sur tout type de device. Ils ont récemment fait une refonte de leur site pour passer à une version Responsive avec pour challenge d'afficher son contenu en moins d'une seconde.

Le Guardian c'est 110 000 utilisateurs, 7000 différents devices. L'ancien site avait un début de rendu en 8 secondes pour un affichage complet en 12. Avec la nouvelle version le site s'affiche en 1 seconde et le chargement complet au bout de 3. Quelles sont les principales optimisations ?

Pour commencer, il faut charge le contenu important pour l'utilisateur en premier, à savoir le menu, l'article, et le widget d'article populaire. Le reste du contenu sera chargé dynamiquement en JS.

En ce qui concerne le css, c'est la même chose. Les CSS importantes (critiques) qui concernent l'article et le rendu global sont intégrées *inline*. Ainsi, nous n'avons pas de blocage du rendu de la page. Le reste des css est chargé via Javascript. Avec ce système, on gagne au moins une demi-seconde sur le début d'affichage du contenu.
Pour gagner en fluidité pour les prochains affichages, le css est stocké en localStorage. On gagne ainsi des ressources pour les prochains chargements.

Pour les fonts ? C'est la même chose, elles sont mises en cache dans le localStorage pour supprimer de nouveaux chargements.

Enfin le gros morceau : les images ! Elles sont chargées de façon asynchrone en lazyloading. Cela permet de ne pas bloquer le rendu principal de la page.

En complément, ils ont mis en place des outils, notamment pour monitorer dans Github la taille des Assets afin de vérifier qu'il n'y a pas de grosses variations.

Avec ces optimisations et un système de Proxy qui va gérer les données mises en localStorage, le site peut même être accessible en mode offline.

 - [Github du Front](https://github.com/guardian/frontend)
 - [Slide de la présentation](https://speakerdeck.com/patrickhamann/breaking-news-at-1000ms-velocity-eu-2014)

---

## Offline-first Web Apps

Matt Andrews nous présente comment rendre une application web disponible Offline.

Plusieurs contraintes peuvent nous pousser à avoir besoin d'une app (signet d'accueil) disponible même sans connexion. Que ce soit un article dans le métro ou une carte au milieu de nulle part sans connexion, il y a une réelle attente utilisateur.

Premièrement, il faut activer [AppCache](http://www.w3schools.com/html/html5_app_cache.asp) en précisant qu'il faut faire un petit Hack pour qu'il soit vraiment utile (voir slide).

Ensuite l'utilisation de plusieurs outils nous permet d'arriver à nos fins :
* Utilisation de [FetchApi](https://github.com/github/fetch) : Il permet de remplacer nos appels Ajax avec une fonction succès , d'erreur et les Promises pour charger le contenu, ou lire le cache en cas d'absence de connexion.
* Cache API : Il permet de choisir des Url a mettre en cache. Ainsi que de forcer le contenu de ces urls dans le code.
* Service Worker : Il permet d'intercepter les events de chargement pour ensuite appeler le système de Cache API.

Toutes ces optimisations nous permettent d'accéder au site en Offline. Mais ces optimisations nous permettent aussi d'optimiser le chargement de nos pages puisqu'on limite le nombre d'appels HTTP avec la mise en cache de certaines ressources.

[Slide de la présentation](http://fr.slideshare.net/andrewsmatt/velocity-eu-2014)

---

## Look, Ma, No Image Requests!

Pamela Fox nous présente comment elle a optimisé les images d'un site internet.

La première astuce est de compresser ces images au maximum. Il existe des outils online comme le site [TinyPng](https://tinypng.com/) qui compresse vos images et vous permet de les télécharger directement.

Deuxième astuce, mettre les images dans les css en base 64.
A noter qu'il existe des outils javascript qui effectuent la conversion dans les css à l'aide d'un petit commentaire en bout de ligne (voir les slides de présentation).

Troisième solution : Les Fonts !
Pour remplacer les petites images et surtout pour remplacer les sprites qui ne sont pas forcément adaptés, vous pouvez utiliser des Fonts. L'avantage des fonts est qu'elles peuvent s'adapter facilement en taille et en couleur … Des outils existent déjà pour les générer : [Font Awesome](http://fortawesome.github.io/Font-Awesome/).

Autre astuce, le differ de chargement des images. Pamela nous propose [son outils javascript](https://gist.github.com/pamelafox/8705015), qui va permettre de vous simplifier les chargements. Il est aussi possible de ne charger que les images présentes à l'écran et de charger les suivantes lors du scroll. (lazyload).

Pour les vidéos la même astuce est possible. Puisque les vidéos sont à présent chargées dans des iFrame, leur contenu peut être chargé de façon différé. Attention, il ne faut pas remplir le href par une url blank, sinon on perd en temps de chargement.

[Slide de la présentation](https://speakerdeck.com/pamelafox/look-ma-no-image-requests)

---

## Microservices - What an Ops Team Needs to Know

Slides: [Microservices - What an Ops Team Needs to Know](https://speakerdeck.com/bruntonspall/microservices-what-an-ops-team-needs-to-know)

![govuk](https://www.gov.uk/service-manual/assets/govuk_template/images/opengraph-image.png)

Le buzzword est lâché. Le propos n'était pas ici de troller autour de la notion de micro-services, de l'implémentation ou de leur utilisation, mais plutôt du changement que cela implique pour les équipes d'exploitation.

Souvent considéré comme le goulot d'étranglement de la chaîne de mise en prod, l'exploit' regarde les architectures de micro-services avec circonspection : en plus d'avoir des dépendances entre eux, les composants sont mis à jour indépendamment et régulièrement, on peut donc vite tout casser en prod.
Pourtant en fournissant des [services de bases](http://fr.wikipedia.org/wiki/Pyramide_des_besoins) et des outils aux équipes de développement, on peut augmenter leur autonomie et la disponibilité des infras.

Cela passe par:

- automatiser les VMs ou les containers en prod comme en dev
- un système de métriques "As a Service" (similaire à graphite / statsd)
- un service de log central (logstash/heka/fluentd)
- un outil de déploiement (capistrano/deployinator)

Ces outils et services ainsi fournis vont permettre à l'exploitation de se concentrer sur des problématiques plus complexes. En effet les microservices ont besoin d'outils de diagnostics plus poussés (on citera au passage Zipkin), d'alerting et de monitoring spécialisés par exemple.

![microservices](http://www.tigerteam.dk/wp-content/uploads/2014/05/monolith-sliced-up-into-microservices.png)

Qui dit droits, dit devoirs, et là je paraphraserai notre orateur Michael Brunton-Spall:

> Give developers pagers too !

> Developers should be exposed to the pain they cause

Cela s'inscrit totalement dans le mouvement "You build it, you run it", où les équipes de développement sont responsables de leur code depuis la conception jusqu'à la maintenance en production.

---

## It's 3AM, Do You Know Why You Got Paged ?

Slides: [It's 3AM, Do You Know Why You Got Paged ?](https://speakerdeck.com/ryanfrantz/its-3am-do-you-know-why-you-got-paged)

Ryan Frantz nous a rappellé quelques éléments de bon sens concernant les alertes:

- un contexte: quel hôte ? serveur ? service ? l'impact front / back ?
- l'historique de l'alerte **et** de la métrique: état de la métrique il y a 5min, 15min, 1 jour, 1 semaine, combien de fois a sonné l'alerte aujourd'hui ?
- la raison d'être du check (rédigée par le créateur du check)
- des couleurs et mise en forme permettant de trouver visuellement l'information le plus rapidement possible (rappel il est 3 heure du matin, et peut être daltonien, pensez donc bien à vos codes couleurs)

![alerting](https://pbs.twimg.com/media/B2uhL8fCUAER0dO.jpg:large)
![alerting](https://pbs.twimg.com/media/B2ugOnFCAAAEdgN.jpg:large)

Seule une alerte critique doit vous faire lever à 3H du matin, un volume disque à 80% plein n'est pas réellement grave, cependant si son taux de remplissage est passé de 1% par heure à 300% par heure, cela peut devenir problématique.

Ryan nous a ensuite présenté nagios-herald. Ce plugin nagios permet de multiplexer une alerte dans différent services (cf schéma) ci dessous.

![nagios herald](https://speakerd.s3.amazonaws.com/presentations/1c7b165020ce01328c621a1ab62a9337/slide_26.jpg?1410982160)

Pour ma part je préfère Sensu qui intègre de base ce type de mécanisme. On peut affecter à une alerte un groupe de handlers (alerte hipchat + graphite + logstash par exemple)

---

## Customizing Chef for Fun and Profit

![chef](http://b-i.forbesimg.com/benkepes/files/2013/12/Chef_Vertical_CCan_Reg.png)

Slides: [Customizing Chef for Fun and Profit](http://fr.slideshare.net/jonlives/chefconf-2014)

En suivant les étapes d'application d'une recette Chef, Jon Cowie a distillé son savoir sur la personnalisation de Chef.

Il nous a par exemple démontré qu'il était très simple de développer son propre plugin ohai et ses propres handlers.

J'ai apprécié le passage sur la gestion des événements Chef, en effet la sortie en ligne de commande n'est qu'une des façons de récupérer les logs, les événements sont basés sur un système de pub/sub, on pourrait très bien imaginer la publication en live stream dans un redis ou autre.

Par ailleurs Jon vient de publier un livre sur le sujet:
[O'Reilly - Customizing Chef](http://shop.oreilly.com/product/0636920032984.do)

---

## Mega quiz Velocity

Perry Dyball et Stephen Thair avaient préparé un quiz interactif avec les participants à la conférence. Des questions diverses et variées défilaient sur le grand écran et une application web permettaient à chacun d'y répondre. Un moment fun animé par deux animateurs survoltés.
 Malheuresement il semble que l'application n'aient pas tenu la charge et personne n'a pu voté après la seconde question (la prochaine fois ils devraient nous confier le projet :) ), mais un système de fallback a été prévu, basé sur des feuilles de papier de couleur à brandir bien haut pour répondre aux questions.

 > merci le papier ! :)

 ![quizz](./quizz.jpg)

## Conclusion

 Fin des conférences et direction les soirées offertes par Facebook (où nous avons pu discuter avec Santosh Janardhan, responsable des infrastructures de Facebook ^^ !) et Dyn.

Le résumé de [la première journée]({% post_url 2014-11-19-cr-velocity-barcelona-2014-day-one %}) est également disponible.


text:
package com.esri.arcgis.android.samples.routing;

import java.util.List;

import android.app.Activity;
import android.app.DialogFragment;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.esri.core.geometry.GeometryEngine;
import com.esri.core.geometry.Point;
import com.esri.core.geometry.SpatialReference;
import com.esri.core.tasks.geocode.Locator;
import com.esri.core.tasks.geocode.LocatorFindParameters;
import com.esri.core.tasks.geocode.LocatorGeocodeResult;

/*
 * This fragment displays a dialog box which contains text fields for source and destination addresses.
 * It also contains two icons "My Location" and "Swap Addresses". When user clicks on My Location icon, the focused
 * text field displays the text "My Location". When "Swap Addresses" icon is clicked the addresses in the text boxes are swapped.
 * When the user clicks on the "Route" button, the addresses are geocoded to points which are then used by the RoutingSample activity to
 * display the route.
 *
 */

public class RoutingDialogFragment extends DialogFragment implements
		OnFocusChangeListener, OnClickListener {

	EditText et_source;
	EditText et_destination;
	Locator locator;
	static ProgressDialog dialog;
	static Handler handler;
	Button bGetRoute;

	// For storing the result of Geocoding Task
	List<LocatorGeocodeResult> result_origin = null;
	List<LocatorGeocodeResult> result_destination = null;

	// Interface to be implemented by the activity
	onGetRoute mCallback;

	// To check if the edit text contains "My Location"
	boolean src_isMyLocation = false;
	boolean dest_isMyLocation = false;

	final SpatialReference wm = SpatialReference.create(102100);
	final SpatialReference egs = SpatialReference.create(4326);
	String source;
	String destination;
	// Image views for the icons
	ImageView img_sCancel, img_dCancel, img_myLocaion, img_swap;

	// Runnable to dismiss the process dialog
	static public class MyRunnable implements Runnable {
		public void run() {
			dialog.dismiss();
		}
	}

	// Interface
	public interface onGetRoute {
		public void onDialogRouteClicked(Point p1, Point p2);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		handler = new Handler();
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		try {
			mCallback = (onGetRoute) activity;
		} catch (ClassCastException e) {
			throw new ClassCastException(activity.toString()
					+ " must implement onDrawerListSelectedListener");
		}

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.dialog_layout, container);

		// Set the views from the XML layout
		et_source = (EditText) view.findViewById(R.id.et_source);
		et_destination = (EditText) view.findViewById(R.id.et_destination);
		img_sCancel = (ImageView) view.findViewById(R.id.iv_cancelSource);
		img_dCancel = (ImageView) view.findViewById(R.id.iv_cancelDestination);
		img_swap = (ImageView) view.findViewById(R.id.iv_interchange);
		img_myLocaion = (ImageView) view.findViewById(R.id.iv_myDialogLocation);
		bGetRoute = (Button) view.findViewById(R.id.bGetRoute);

		// Adding custom Listener to edit text views
		et_source.addTextChangedListener(new MyTextWatcher(et_source));
		et_destination
				.addTextChangedListener(new MyTextWatcher(et_destination));

		// Adding Focus Change listener to the edit text views
		et_source.setOnFocusChangeListener(this);
		et_destination.setOnFocusChangeListener(this);

		// Setting onClick listener for the icons on the dialog
		img_dCancel.setOnClickListener(this);
		img_sCancel.setOnClickListener(this);
		img_swap.setOnClickListener(this);
		img_myLocaion.setOnClickListener(this);

		// Adding onClick listener for the button
		bGetRoute.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				source = et_source.getText().toString();
				destination = et_destination.getText().toString();

				// If either of the edit text is empty, display the toast
				if (source.equals("") || destination.equals("")) {
					Toast.makeText(getActivity(), "Place cannot be empty",
							Toast.LENGTH_LONG).show();
					return;
				}

				// Checking if the edit text views contain "My Location"
				if (source.equals("My Location"))
					src_isMyLocation = true;
				if (destination.equals("My Location"))
					dest_isMyLocation = true;

				// If source and destination are not same then geocode the
				// addresses
				if (!source.equals(destination)) {
					// Geocode the addresses
					geocode(source, destination);
				} else {
					Toast.makeText(getActivity(),
							"Source and Destination should be different",
							Toast.LENGTH_LONG).show();
				}

			}
		});

		// Removing title from the dialog box
		getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);

		return view;
	}

	private void geocode(String address1, String address2) {
		try {
			// create Locator parameters from single line address string
			LocatorFindParameters findParams_source = new LocatorFindParameters(
					address1);
			// set the search country to USA
			findParams_source.setSourceCountry("USA");
			// limit the results to 2
			findParams_source.setMaxLocations(2);
			// set address spatial reference to match map
			findParams_source.setOutSR(RoutingSample.map.getSpatialReference());
			// execute async task to geocode address

			LocatorFindParameters findParams_dest = new LocatorFindParameters(
					address2);
			findParams_dest.setSourceCountry("USA");
			findParams_dest.setMaxLocations(2);
			findParams_dest.setOutSR(RoutingSample.map.getSpatialReference());

			Geocoder gcoder = new Geocoder(findParams_source, findParams_dest);
			gcoder.execute();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private class Geocoder extends AsyncTask<Void, Void, Void> {

		// Location Find Parameters for both source and destination addresses
		LocatorFindParameters lfp_start, lfp_dest;

		// Constructor
		public Geocoder(LocatorFindParameters findParams_start,
				LocatorFindParameters findParams_dest) {
			lfp_start = findParams_start;
			lfp_dest = findParams_dest;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// Displaying the Process Dialog
			dialog = ProgressDialog.show(getActivity(), "Routing Sample",
					"Geocoding the addresses ...");

		}

		@Override
		protected Void doInBackground(Void... params) {

			// set the geocode service

			locator = Locator.createOnlineLocator(getResources().getString(
					R.string.geocode_url));
			try {
				// pass address to find method to return point representing
				// address
				if (!src_isMyLocation)
					result_origin = locator.find(lfp_start);
				if (!dest_isMyLocation)
					result_destination = locator.find(lfp_dest);

			} catch (Exception e) {
				e.printStackTrace();
			}

			return null;
		}

		// The result of geocode task is passed as a parameter to map the
		// results

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);

			handler.post(new MyRunnable());
			Point p1 = null;
			Point p2 = null;

			// Projecting the current location to the output spatial ref
			Point currLocation = (Point) GeometryEngine.project(
					RoutingSample.mLocation, egs, wm);

			// Assignign current location to the field with value as
			// "My Location"
			if (src_isMyLocation)
				p1 = currLocation;
			else if (result_origin.size() > 0)
				p1 = result_origin.get(0).getLocation();

			if (dest_isMyLocation)
				p2 = currLocation;
			else if (result_destination.size() > 0)
				p2 = result_destination.get(0).getLocation();

			if (p1 == null) {
				Toast.makeText(getActivity(), "Not a valid source address",
						Toast.LENGTH_LONG).show();
			} else if (p2 == null) {
				Toast.makeText(getActivity(),
						"Not a valid destination address", Toast.LENGTH_LONG)
						.show();
			} else
				mCallback.onDialogRouteClicked(p1, p2);

		}
	}

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

	@Override
	public void onDestroy() {
		super.onDestroy();

	}

	// Custom Listener for the Edit text views
	private class MyTextWatcher implements TextWatcher {

		private View view;

		private MyTextWatcher(View view) {
			this.view = view;
		}

		public void beforeTextChanged(CharSequence charSequence, int i, int i1,
				int i2) {
		}

		public void onTextChanged(CharSequence charSequence, int i, int i1,
				int i2) {
		}

		public void afterTextChanged(Editable editable) {

			// Displaying the cross icon when the edit text views are not empty
			String text = editable.toString();
			switch (view.getId()) {
			case R.id.et_source:
				if (text.length() > 0)
					img_sCancel.setVisibility(View.VISIBLE);
				else
					img_sCancel.setVisibility(View.INVISIBLE);
				break;
			case R.id.et_destination:
				if (text.length() > 0)
					img_dCancel.setVisibility(View.VISIBLE);
				else
					img_dCancel.setVisibility(View.INVISIBLE);

				break;
			}
		}
	}

	@Override
	public void onFocusChange(View v, boolean hasFocus) {

		// Checking the focus of the edit text and displaying the cross icon if
		// it is not empty
		switch (v.getId()) {
		case R.id.et_source:
			if (hasFocus && et_source.getText().toString().length() > 0)
				img_sCancel.setVisibility(View.VISIBLE);
			else
				img_sCancel.setVisibility(View.INVISIBLE);
			break;
		case R.id.et_destination:
			if (hasFocus && et_destination.getText().toString().length() > 0)
				img_dCancel.setVisibility(View.VISIBLE);
			else
				img_dCancel.setVisibility(View.INVISIBLE);

			break;
		}
	}

	// OnClick events for the icons on the dialog box
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.iv_cancelSource:
			// Clearing the text
			et_source.getText().clear();
			break;
		case R.id.iv_cancelDestination:
			// Clearing the text
			et_destination.getText().clear();
			break;
		case R.id.iv_myDialogLocation:

			// Putting "My Location" in the edit text that is in focus
			if (et_source.hasFocus())
				et_source.setText("My Location");
			else
				et_destination.setText("My Location");
			break;
		case R.id.iv_interchange:

			// Swapping the values
			String temp = et_source.getText().toString();
			et_source.setText(et_destination.getText().toString());
			et_destination.setText(temp);
			break;

		}

	}

}