text:
namespace boost {

  template <class Visitor, class Graph>
  class DFSVisitorConcept {
  public:
    void constraints() {
      function_requires< CopyConstructibleConcept<Visitor> >();
      vis.initialize_vertex(u, g);
      vis.start_vertex(u, g);
      vis.discover_vertex(u, g);
      vis.examine_edge(e, g);
      vis.tree_edge(e, g);
      vis.back_edge(e, g);
      vis.forward_or_cross_edge(e, g);
      vis.finish_vertex(u, g);
    }
  private:
    Visitor vis;
    Graph g;
    typename graph_traits<Graph>::vertex_descriptor u;
    typename graph_traits<Graph>::edge_descriptor e;
  };

  namespace detail {

    struct nontruth2 {
      template<class T, class T2>
      bool operator()(const T&, const T2&) const { return false; }
    };

// Define BOOST_RECURSIVE_DFS to use older, recursive version.
// It is retained for a while in order to perform performance
// comparison.
#ifndef BOOST_RECURSIVE_DFS

    // If the vertex u and the iterators ei and ei_end are thought of as the
    // context of the algorithm, each push and pop from the stack could
    // be thought of as a context shift.
    // Each pass through "while (ei != ei_end)" may refer to the out-edges of
    // an entirely different vertex, because the context of the algorithm
    // shifts every time a white adjacent vertex is discovered.
    // The corresponding context shift back from the adjacent vertex occurs
    // after all of its out-edges have been examined.
    //
    // See http://lists.boost.org/MailArchives/boost/msg48752.php for FAQ.

    template <class IncidenceGraph, class DFSVisitor, class ColorMap,
            class TerminatorFunc>
    void depth_first_visit_impl
      (const IncidenceGraph& g,
       typename graph_traits<IncidenceGraph>::vertex_descriptor u,
       DFSVisitor& vis,
       ColorMap color, TerminatorFunc func = TerminatorFunc())
    {
      function_requires<IncidenceGraphConcept<IncidenceGraph> >();
      function_requires<DFSVisitorConcept<DFSVisitor, IncidenceGraph> >();
      typedef typename graph_traits<IncidenceGraph>::vertex_descriptor Vertex;
      function_requires< ReadWritePropertyMapConcept<ColorMap, Vertex> >();
      typedef typename property_traits<ColorMap>::value_type ColorValue;
      function_requires< ColorValueConcept<ColorValue> >();
      typedef color_traits<ColorValue> Color;
      typedef typename graph_traits<IncidenceGraph>::out_edge_iterator Iter;
      typedef std::pair<Vertex, std::pair<Iter, Iter> > VertexInfo;

      Iter ei, ei_end;
      std::vector<VertexInfo> stack;

      // Possible optimization for vector
      //stack.reserve(num_vertices(g));

      typedef typename unwrap_reference<TerminatorFunc>::type TF;

      put(color, u, Color::gray());
      vis.discover_vertex(u, g);
      tie(ei, ei_end) = out_edges(u, g);
      // Variable is needed to workaround a borland bug.
      TF& fn = static_cast<TF&>(func);
      if (fn(u, g)) {
          // If this vertex terminates the search, we push empty range
          stack.push_back(std::make_pair(u, std::make_pair(ei_end, ei_end)));
      } else {
          stack.push_back(std::make_pair(u, std::make_pair(ei, ei_end)));
      }
      while (!stack.empty()) {
        VertexInfo& back = stack.back();
        u = back.first;
        tie(ei, ei_end) = back.second;
        stack.pop_back();
        while (ei != ei_end) {
          Vertex v = target(*ei, g);
          vis.examine_edge(*ei, g);
          ColorValue v_color = get(color, v);
          if (v_color == Color::white()) {
            vis.tree_edge(*ei, g);
            stack.push_back(std::make_pair(u, std::make_pair(++ei, ei_end)));
            u = v;
            put(color, u, Color::gray());
            vis.discover_vertex(u, g);
            tie(ei, ei_end) = out_edges(u, g);
            if (fn(u, g)) {
                ei = ei_end;
            }
          } else if (v_color == Color::gray()) {
            vis.back_edge(*ei, g);
            ++ei;
          } else {
            vis.forward_or_cross_edge(*ei, g);
            ++ei;
          }
        }
        put(color, u, Color::black());
        vis.finish_vertex(u, g);
      }
    }

#else // BOOST_RECURSIVE_DFS is defined

    template <class IncidenceGraph, class DFSVisitor, class ColorMap,
              class TerminatorFunc>
    void depth_first_visit_impl
      (const IncidenceGraph& g,
       typename graph_traits<IncidenceGraph>::vertex_descriptor u,
       DFSVisitor& vis,  // pass-by-reference here, important!
       ColorMap color, TerminatorFunc func)
    {
      function_requires<IncidenceGraphConcept<IncidenceGraph> >();
      function_requires<DFSVisitorConcept<DFSVisitor, IncidenceGraph> >();
      typedef typename graph_traits<IncidenceGraph>::vertex_descriptor Vertex;
      function_requires< ReadWritePropertyMapConcept<ColorMap, Vertex> >();
      typedef typename property_traits<ColorMap>::value_type ColorValue;
      function_requires< ColorValueConcept<ColorValue> >();
      typedef color_traits<ColorValue> Color;
      typename graph_traits<IncidenceGraph>::out_edge_iterator ei, ei_end;

      put(color, u, Color::gray());          vis.discover_vertex(u, g);

      typedef typename unwrap_reference<TerminatorFunc>::type TF;
      // Variable is needed to workaround a borland bug.
      TF& fn = static_cast<TF&>(func);
      if (!fn(u, g))
        for (tie(ei, ei_end) = out_edges(u, g); ei != ei_end; ++ei) {
          Vertex v = target(*ei, g);           vis.examine_edge(*ei, g);
          ColorValue v_color = get(color, v);
          if (v_color == Color::white()) {     vis.tree_edge(*ei, g);
          depth_first_visit_impl(g, v, vis, color, func);
          } else if (v_color == Color::gray()) vis.back_edge(*ei, g);
          else                                 vis.forward_or_cross_edge(*ei, g);
        }
      put(color, u, Color::black());         vis.finish_vertex(u, g);
    }

#endif

  } // namespace detail

  template <class VertexListGraph, class DFSVisitor, class ColorMap>
  void
  depth_first_search(const VertexListGraph& g, DFSVisitor vis, ColorMap color,
                     typename graph_traits<VertexListGraph>::vertex_descriptor start_vertex)
  {
    typedef typename graph_traits<VertexListGraph>::vertex_descriptor Vertex;
    function_requires<DFSVisitorConcept<DFSVisitor, VertexListGraph> >();
    typedef typename property_traits<ColorMap>::value_type ColorValue;
    typedef color_traits<ColorValue> Color;

    typename graph_traits<VertexListGraph>::vertex_iterator ui, ui_end;
    for (tie(ui, ui_end) = vertices(g); ui != ui_end; ++ui) {
      Vertex u = implicit_cast<Vertex>(*ui);
      put(color, u, Color::white()); vis.initialize_vertex(u, g);
    }

    if (start_vertex != implicit_cast<Vertex>(*vertices(g).first)){ vis.start_vertex(start_vertex, g);
      detail::depth_first_visit_impl(g, start_vertex, vis, color,
                                     detail::nontruth2());
    }

    for (tie(ui, ui_end) = vertices(g); ui != ui_end; ++ui) {
      Vertex u = implicit_cast<Vertex>(*ui);
      ColorValue u_color = get(color, u);
      if (u_color == Color::white()) {       vis.start_vertex(u, g);
        detail::depth_first_visit_impl(g, u, vis, color, detail::nontruth2());
      }
    }
  }

  template <class VertexListGraph, class DFSVisitor, class ColorMap>
  void
  depth_first_search(const VertexListGraph& g, DFSVisitor vis, ColorMap color)
  {
    typedef typename boost::graph_traits<VertexListGraph>::vertex_iterator vi;
    std::pair<vi, vi> verts = vertices(g);
    if (verts.first == verts.second)
      return;

    depth_first_search(g, vis, color, *verts.first);
  }

  template <class Visitors = null_visitor>
  class dfs_visitor {
  public:
    dfs_visitor() { }
    dfs_visitor(Visitors vis) : m_vis(vis) { }

    template <class Vertex, class Graph>
    void initialize_vertex(Vertex u, const Graph& g) {
      invoke_visitors(m_vis, u, g, ::boost::on_initialize_vertex());
    }
    template <class Vertex, class Graph>
    void start_vertex(Vertex u, const Graph& g) {
      invoke_visitors(m_vis, u, g, ::boost::on_start_vertex());
    }
    template <class Vertex, class Graph>
    void discover_vertex(Vertex u, const Graph& g) {
      invoke_visitors(m_vis, u, g, ::boost::on_discover_vertex());
    }
    template <class Edge, class Graph>
    void examine_edge(Edge u, const Graph& g) {
      invoke_visitors(m_vis, u, g, ::boost::on_examine_edge());
    }
    template <class Edge, class Graph>
    void tree_edge(Edge u, const Graph& g) {
      invoke_visitors(m_vis, u, g, ::boost::on_tree_edge());
    }
    template <class Edge, class Graph>
    void back_edge(Edge u, const Graph& g) {
      invoke_visitors(m_vis, u, g, ::boost::on_back_edge());
    }
    template <class Edge, class Graph>
    void forward_or_cross_edge(Edge u, const Graph& g) {
      invoke_visitors(m_vis, u, g, ::boost::on_forward_or_cross_edge());
    }
    template <class Vertex, class Graph>
    void finish_vertex(Vertex u, const Graph& g) {
      invoke_visitors(m_vis, u, g, ::boost::on_finish_vertex());
    }

    BOOST_GRAPH_EVENT_STUB(on_initialize_vertex,dfs)
    BOOST_GRAPH_EVENT_STUB(on_start_vertex,dfs)
    BOOST_GRAPH_EVENT_STUB(on_discover_vertex,dfs)
    BOOST_GRAPH_EVENT_STUB(on_examine_edge,dfs)
    BOOST_GRAPH_EVENT_STUB(on_tree_edge,dfs)
    BOOST_GRAPH_EVENT_STUB(on_back_edge,dfs)
    BOOST_GRAPH_EVENT_STUB(on_forward_or_cross_edge,dfs)
    BOOST_GRAPH_EVENT_STUB(on_finish_vertex,dfs)

  protected:
    Visitors m_vis;
  };
  template <class Visitors>
  dfs_visitor<Visitors>
  make_dfs_visitor(Visitors vis) {
    return dfs_visitor<Visitors>(vis);
  }
  typedef dfs_visitor<> default_dfs_visitor;

  // Named Parameter Variant
  template <class VertexListGraph, class P, class T, class R>
  void
  depth_first_search(const VertexListGraph& g,
                     const bgl_named_params<P, T, R>& params)
  {
    typedef typename boost::graph_traits<VertexListGraph>::vertex_iterator vi;
    std::pair<vi, vi> verts = vertices(g);
    if (verts.first == verts.second)
      return;
    using namespace boost::graph::keywords;
    typedef bgl_named_params<P, T, R> params_type;
    BOOST_GRAPH_DECLARE_CONVERTED_PARAMETERS(params_type, params)
    depth_first_search
      (g,
       arg_pack[_visitor | make_dfs_visitor(null_visitor())],
       boost::detail::color_map_maker<VertexListGraph, arg_pack_type>::make_map(g, arg_pack),
       arg_pack[_root_vertex | *vertices(g).first]
      );
  }

  template <class IncidenceGraph, class DFSVisitor, class ColorMap>
  void depth_first_visit
    (const IncidenceGraph& g,
     typename graph_traits<IncidenceGraph>::vertex_descriptor u,
     DFSVisitor vis, ColorMap color)
  {
    vis.start_vertex(u, g);
    detail::depth_first_visit_impl(g, u, vis, color, detail::nontruth2());
  }

  template <class IncidenceGraph, class DFSVisitor, class ColorMap,
            class TerminatorFunc>
  void depth_first_visit
    (const IncidenceGraph& g,
     typename graph_traits<IncidenceGraph>::vertex_descriptor u,
     DFSVisitor vis, ColorMap color, TerminatorFunc func = TerminatorFunc())
  {
    vis.start_vertex(u, g);
    detail::depth_first_visit_impl(g, u, vis, color, func);
  }
} // namespace boost

#ifdef BOOST_GRAPH_USE_MPI
#  include <boost/graph/distributed/depth_first_search.hpp>
#endif

#endif


text:
stackview
=========

Simple tool that helps visualize symbols within a hex dump of the stack. It is
designed for embedded software crashes where a dump of thread stack memory is available,
but no stack trace is available.

Build
=====

[Install Go](http://golang.org/doc/install). Go 1.1 is required.

    go get github.com/mikezuff/stackview
    cd $GOPATH/src/github.com/mikezuff/stackview
    go build stackview.go

Usage
=====

 `stackview <elfBinary> <stackDump>`

 `stackview vxWorks.st stack.dump`

To turn the file stack.dump from this:

    0x094bd740:  00d07ca8 0161d6d4 099d0168 00000072   *.|....a.h...r...*
    0x094bd750:  0161d520 000000cd 099d0128 094bd770   * .a.....(...p.K.*
    0x094bd760:  00d063f4 0161d6d4 00000000 099d0168   *.c....a.....h...*
    0x094bd770:  094bd790 00d07ca8 0161d6d4 0161d520   *..K..|....a. .a.*
    0x094bd780:  000000cd 099d0128 094bd79c 00d063f4   *....(.....K..c..*
    0x094bd790:  0161d6d4 00000000 099d0168 0161d520   *..a.....h... .a.*
    ...

Into this:
![alt text](https://raw.github.com/mikezuff/stackview/master/screenshot.png "Screenshot")

Hacking
=======

Stackview is written to handle vxworks and rmios kernel executables. You may need
to adjust it for your system.

Stackview uses regular expressions to parse the source address and dump bytes from a hexdump.
If you are getting format errors when stackview is loading your dump, you may need to
edit DataLineRE or OffsetLineRE or replace GeneralDumpParser with something specific
to your needs.

If func IgnoreSymbol returns true, the symbol name won't be printed in the output.

redpajama_set_name: RedPajamaGithub


text:
package edu.berkeley.icsi.xnet;

public class MotionChannel {
	public static final int NOT_STARTED = 0;
	public static final int ONGOING = 1;
	public static final int ARRIVED = 2;
	public static final int RESTARTED = 3;
	private Mover mover;
	private double currentY;
	private double currentX;
	private double targetX;
	private double targetY;
	private double speed;
	private double tolerance;
	private boolean collide;
	private int status = NOT_STARTED;

	public MotionChannel() {
	}
	public void setMover(Mover mover) {
		this.mover = mover;
	}
	public Mover getMover() {
		return mover;
	}
	public void updateCurrentLocation(double x, double y) {
		this.currentX = x;
		this.currentY = y;
//		System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSSSS").format(new Date(System.currentTimeMillis()))+
//				"MorseChannel.updateCurrentLocation x: "+x+" y: "+y);
	}
	public void updateTargetLocation(double x, double y) {
		this.targetX = x;
		this.targetY = y;
//		System.out.println("MorseChannel.updateTargetLocation x: "+x+" y: "+y);
	}
	public double getCurrentX() {
		return currentX;
	}
	public double getCurrentY() {
		return currentY;
	}
	public double getTargetX() {
		return targetX;
	}
	public double getTargetY() {
		return targetY;
	}
	public double getSpeed() {
		return speed;
	}
	public void setSpeed(double speed) {
		this.speed = speed;
	}
	public double getTolerance() {
		return tolerance;
	}
	public void setTolerance(double tolerance) {
		this.tolerance = tolerance;
	}
	public boolean isCollide() {
		return collide;
	}
	public void setCollide(boolean collide) {
		this.collide = collide;
	}
	public int getStatus() {
		return status ;
	}
	public void setStatus(int status) {
//		System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSSSS").format(new Date(System.currentTimeMillis()))+
//				"MotionChannel.setStatus: "+status);
		this.status = status;
	}
}


text:
namespace remoting {

RendererProxy::RendererProxy(
    scoped_refptr<base::SingleThreadTaskRunner> task_runner)
    : task_runner_(task_runner),
      ui_task_poster_(new remoting::QueuedTaskPoster(task_runner_)) {}

RendererProxy::~RendererProxy() = default;

void RendererProxy::Initialize(base::WeakPtr<GlRenderer> renderer) {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  renderer_ = renderer;
}

void RendererProxy::SetTransformation(const ViewMatrix& transformation) {
  // Viewport and cursor movements need to be synchronized into the same frame.
  RunTaskOnProperThread(
      base::BindOnce(&GlRenderer::OnPixelTransformationChanged, renderer_,
                     transformation.ToMatrixArray()),
      true);
}

void RendererProxy::SetCursorPosition(float x, float y) {
  RunTaskOnProperThread(
      base::BindOnce(&GlRenderer::OnCursorMoved, renderer_, x, y), true);
}

void RendererProxy::SetCursorVisibility(bool visible) {
  // Cursor visibility and position should be synchronized.
  RunTaskOnProperThread(base::BindOnce(&GlRenderer::OnCursorVisibilityChanged,
                                       renderer_, visible),
                        true);
}

void RendererProxy::StartInputFeedback(float x, float y, float diameter) {
  RunTaskOnProperThread(base::BindOnce(&GlRenderer::OnCursorInputFeedback,
                                       renderer_, x, y, diameter),
                        false);
}

void RendererProxy::RunTaskOnProperThread(base::OnceClosure task,
                                          bool needs_synchronization) {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  if (task_runner_->BelongsToCurrentThread()) {
    std::move(task).Run();
    return;
  }

  if (needs_synchronization) {
    ui_task_poster_->AddTask(std::move(task));
    return;
  }

  task_runner_->PostTask(FROM_HERE, std::move(task));
}

}  // namespace remoting


text:
// Package grpcvtworkerclient contains the gRPC version of the vtworker client protocol.
package grpcvtworkerclient

import (
	"flag"

	"golang.org/x/net/context"
	"google.golang.org/grpc"

	"github.com/youtube/vitess/go/vt/grpcclient"
	"github.com/youtube/vitess/go/vt/logutil"
	"github.com/youtube/vitess/go/vt/vterrors"
	"github.com/youtube/vitess/go/vt/worker/vtworkerclient"

	logutilpb "github.com/youtube/vitess/go/vt/proto/logutil"
	vtrpcpb "github.com/youtube/vitess/go/vt/proto/vtrpc"
	vtworkerdatapb "github.com/youtube/vitess/go/vt/proto/vtworkerdata"
	vtworkerservicepb "github.com/youtube/vitess/go/vt/proto/vtworkerservice"
)

var (
	cert = flag.String("vtworker_client_grpc_cert", "", "the cert to use to connect")
	key  = flag.String("vtworker_client_grpc_key", "", "the key to use to connect")
	ca   = flag.String("vtworker_client_grpc_ca", "", "the server ca to use to validate servers when connecting")
	name = flag.String("vtworker_client_grpc_server_name", "", "the server name to use to validate server certificate")
)

type gRPCVtworkerClient struct {
	cc *grpc.ClientConn
	c  vtworkerservicepb.VtworkerClient
}

func gRPCVtworkerClientFactory(addr string) (vtworkerclient.Client, error) {
	// create the RPC client
	opt, err := grpcclient.SecureDialOption(*cert, *key, *ca, *name)
	if err != nil {
		return nil, err
	}
	cc, err := grpcclient.Dial(addr, grpcclient.FailFast(false), opt)
	if err != nil {
		return nil, vterrors.Errorf(vtrpcpb.Code_DEADLINE_EXCEEDED, "grpcclient.Dial() err: %v", err)
	}
	c := vtworkerservicepb.NewVtworkerClient(cc)

	return &gRPCVtworkerClient{
		cc: cc,
		c:  c,
	}, nil
}

type eventStreamAdapter struct {
	stream vtworkerservicepb.Vtworker_ExecuteVtworkerCommandClient
}

func (e *eventStreamAdapter) Recv() (*logutilpb.Event, error) {
	le, err := e.stream.Recv()
	if err != nil {
		return nil, vterrors.FromGRPC(err)
	}
	return le.Event, nil
}

// ExecuteVtworkerCommand is part of the VtworkerClient interface.
func (client *gRPCVtworkerClient) ExecuteVtworkerCommand(ctx context.Context, args []string) (logutil.EventStream, error) {
	query := &vtworkerdatapb.ExecuteVtworkerCommandRequest{
		Args: args,
	}

	stream, err := client.c.ExecuteVtworkerCommand(ctx, query)
	if err != nil {
		return nil, vterrors.FromGRPC(err)
	}
	return &eventStreamAdapter{stream}, nil
}

// Close is part of the VtworkerClient interface.
func (client *gRPCVtworkerClient) Close() {
	client.cc.Close()
}

func init() {
	vtworkerclient.RegisterFactory("grpc", gRPCVtworkerClientFactory)
}


text:
package vg.civcraft.mc.civmodcore.entities;

import com.google.common.base.Strings;
import javax.annotation.Nonnull;
import lombok.experimental.UtilityClass;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.TranslatableComponent;
import org.bukkit.entity.EntityType;

/**
 * Class of static APIs for Entities.
 */
@UtilityClass
public final class EntityUtils {

	/**
	 * Attempts to retrieve an entity type by its slug or id.
	 *
	 * @param value The value to search for a matching entity type by.
	 * @return Returns a matched entity type or null.
	 */
	@SuppressWarnings("deprecation")
	public static EntityType getEntityType(final String value) {
		if (Strings.isNullOrEmpty(value)) {
			return null;
		}
		try {
			return EntityType.valueOf(value.toUpperCase());
		}
		catch (final Throwable ignored) { }
		try {
			final EntityType type = EntityType.fromId(Short.parseShort(value));
			if (type != null) {
				return type;
			}
		}
		catch (final Throwable ignored) { }
		return null;
	}

	/**
	 * @param entityType The entity type to translate.
	 * @return Returns a translatable component based on the given entity type.
	 */
	public static TranslatableComponent asTranslatable(@Nonnull final EntityType entityType) {
		return Component.translatable(entityType.translationKey());
	}

}


text:
angular.module('bootstrapLightbox', [
  'ngTouch',
  'ui.bootstrap',
  'chieffancypants.loadingBar',
]);
angular.module('bootstrapLightbox').run(['$templateCache', function($templateCache) {
  'use strict';

  $templateCache.put('lightbox.html',
    "

<button class=close aria-hidden=true ng-click=$dismiss()>×</button>
‹ Previous Open image in new tab Next ›

{{Lightbox.imageCaption}}

"
  );

}]);
angular.module('bootstrapLightbox').service('ImageLoader', function ($q) {
  /**
   * Load the image at the given URL.
   * @param  {String}  url
   * @return {Promise} A $q promise that resolves when the image has loaded
   *   successfully.
   */
  this.load = function (url) {
    var deferred = $q.defer();

    var image = new Image();

    // when the image has loaded
    image.onload = function () {
      // check image properties for possible errors
      if ((typeof this.complete === 'boolean' && this.complete === false) ||
          (typeof this.naturalWidth === 'number' && this.naturalWidth === 0)) {
        deferred.reject();
      }

      deferred.resolve(image);
    };

    // when the image fails to load
    image.onerror = function () {
      deferred.reject();
    };

    // start loading the image
    image.src = url;

    return deferred.promise;
  };
});
angular.module('bootstrapLightbox').provider('Lightbox', function () {
  /**
   * Template URL passed into $modal.open().
   * @type {String}
   */
  this.templateUrl = 'lightbox.html';

  /**
   * @param  {*}      image An element in the array of images.
   * @return {String}       The URL of the given image.
   */
  this.getImageUrl = function (image) {
    return image.url;
  };

  /**
   * @param  {*}      image An element in the array of images.
   * @return {String}       The caption of the given image.
   */
  this.getImageCaption = function (image) {
    return image.caption;
  };

  /**
   * Calculate the max and min limits to the width and height of the displayed
   *   image (all are optional). The max dimensions override the min
   *   dimensions if they conflict.
   * @param  {Object} dimensions Contains the properties windowWidth,
   *   windowHeight, imageWidth, imageHeight.
   * @return {Object} May optionally contain the properties minWidth,
   *   minHeight, maxWidth, maxHeight.
   */
  this.calculateImageDimensionLimits = function (dimensions) {
    if (dimensions.windowWidth >= 768) {
      return {
        // 92px = 2 * (30px margin of .modal-dialog
        //             + 1px border of .modal-content
        //             + 15px padding of .modal-body)
        // with the goal of 30px side margins; however, the actual side margins
        // will be slightly less (at 22.5px) due to the vertical scrollbar
        'maxWidth': dimensions.windowWidth - 92,
        // 126px = 92px as above
        //         + 34px outer height of .lightbox-nav
        'maxHeight': dimensions.windowHeight - 126
      };
    } else {
      return {
        // 52px = 2 * (10px margin of .modal-dialog
        //             + 1px border of .modal-content
        //             + 15px padding of .modal-body)
        'maxWidth': dimensions.windowWidth - 52,
        // 86px = 52px as above
        //        + 34px outer height of .lightbox-nav
        'maxHeight': dimensions.windowHeight - 86
      };
    }
  };

  /**
   * Calculate the width and height of the modal. This method gets called
   *   after the width and height of the image, as displayed inside the modal,
   *   are calculated.
   * @param  {Object} dimensions Contains the properties windowWidth,
   *   windowHeight, imageDisplayWidth, imageDisplayHeight.
   * @return {Object} Must contain the properties width and height.
   */
  this.calculateModalDimensions = function (dimensions) {
    // 400px = arbitrary min width
    // 32px = 2 * (1px border of .modal-content
    //             + 15px padding of .modal-body)
    var width = Math.max(400, dimensions.imageDisplayWidth + 32);

    // 200px = arbitrary min height
    // 66px = 32px as above
    //        + 34px outer height of .lightbox-nav
    var height = Math.max(200, dimensions.imageDisplayHeight + 66);

    // first case:  the modal width cannot be larger than the window width
    //              20px = arbitrary value larger than the vertical scrollbar
    //                     width in order to avoid having a horizontal scrollbar
    // second case: Bootstrap modals are not centered below 768px
    if (width >= dimensions.windowWidth - 20 || dimensions.windowWidth < 768) {
      width = 'auto';
    }

    // the modal height cannot be larger than the window height
    if (height >= dimensions.windowHeight) {
      height = 'auto';
    }

    return {
      'width': width,
      'height': height
    };
  };

  this.$get = function ($document, $modal, $timeout, cfpLoadingBar,
      ImageLoader) {
    // array of all images to be shown in the lightbox (not Image objects)
    var images = [];

    // the index of the image currently shown (Lightbox.image)
    var index = -1;

    /**
     * The service object for the lightbox.
     * @type {Object}
     */
    var Lightbox = {};

    // set the configurable properties and methods, the defaults of which are
    // defined above
    Lightbox.templateUrl = this.templateUrl;
    Lightbox.getImageUrl = this.getImageUrl;
    Lightbox.getImageCaption = this.getImageCaption;
    Lightbox.calculateImageDimensionLimits = this.calculateImageDimensionLimits;
    Lightbox.calculateModalDimensions = this.calculateModalDimensions;

    /**
     * Whether keyboard navigation is currently enabled for navigating through
     *   images in the lightbox.
     * @type {Boolean}
     */
    Lightbox.keyboardNavEnabled = false;

    /**
     * The current image.
     * @type {*}
     */
    Lightbox.image = {};

    /**
     * The URL of the current image. This is a property of the service rather
     *   than of Lightbox.image because Lightbox.image need not be an object,
     *   and besides it would be poor practice to alter the given objects.
     * @type {String}
     */
    // Lightbox.imageUrl = '';

    /**
     * The caption of the current image. See the description of
     *   Lightbox.imageUrl.
     * @type {String}
     */
    // Lightbox.imageCaption = '';

    /**
     * Open the lightbox modal.
     * @param  {Array}  newImages An array of images. Each image may be of any
     *   type.
     * @param  {Number} newIndex  The index in newImages to set as the current
     *   image.
     */
    Lightbox.openModal = function (newImages, newIndex) {
      images = newImages;
      Lightbox.setImage(newIndex);

      $modal.open({
        'templateUrl': Lightbox.templateUrl,
        'controller': ['$scope', function ($scope) {
          // $scope is the modal scope, a child of $rootScope
          $scope.Lightbox = Lightbox;

          Lightbox.keyboardNavEnabled = true;
        }],
        'windowClass': 'lightbox-modal'
      }).result.finally(function () { // close
        // prevent the lightbox from flickering from the old image when it gets
        // opened again
        Lightbox.image = {};
        Lightbox.imageUrl = null;
        Lightbox.imageCaption = null;

        Lightbox.keyboardNavEnabled = false;

        // complete any lingering loading bar progress
        cfpLoadingBar.complete();
      });
    };

    /**
     * This method can be used in all methods which navigate/change the
     *   current image.
     * @param {Number} newIndex The index in the array of images to set as the
     *   new current image.
     */
    Lightbox.setImage = function (newIndex) {
      if (!(newIndex in images)) {
        throw 'Invalid image.';
      }

      cfpLoadingBar.start();

      var success = function () {
        index = newIndex;
        Lightbox.image = images[index];

        cfpLoadingBar.complete();
      };

      var imageUrl = Lightbox.getImageUrl(images[newIndex]);

      // load the image before setting it, so everything in the view is updated
      // at the same time; otherwise, the previous image remains while the
      // current image is loading
      ImageLoader.load(imageUrl).then(function () {
        success();

        // set the url and caption
        Lightbox.imageUrl = imageUrl;
        Lightbox.imageCaption = Lightbox.getImageCaption(Lightbox.image);
      }, function () {
        success();

        // blank image
        Lightbox.imageUrl = '//:0';
        // use the caption to show the user an error
        Lightbox.imageCaption = 'Failed to load image';
      });
    };

    /**
     * Navigate to the first image.
     */
    Lightbox.firstImage = function () {
      Lightbox.setImage(0);
    };

    /**
     * Navigate to the previous image.
     */
    Lightbox.prevImage = function () {
      Lightbox.setImage((index - 1 + images.length) % images.length);
    };

    /**
     * Navigate to the next image.
     */
    Lightbox.nextImage = function () {
      Lightbox.setImage((index + 1) % images.length);
    };

    /**
     * Navigate to the last image.
     */
    Lightbox.lastImage = function () {
      Lightbox.setImage(images.length - 1);
    };

    /**
     * Call this method to set both the array of images and the current image
     *   (based on the current index). A use case is when the image collection
     *   gets changed dynamically in some way while the lightbox is still open.
     * @param {Array} newImages The new array of images.
     */
    Lightbox.setImages = function (newImages) {
      images = newImages;
      Lightbox.setImage(index);
    };

    /**
     * Bind the left and right arrow keys for image navigation. This event
     *   handler never gets unbinded. Disable this using the
     *   keyboardNavEnabled flag. It is automatically disabled when
     *   the target is an input and or a textarea.
     */
    $document.bind('keydown', function (event) {
      if (!Lightbox.keyboardNavEnabled) {
        return;
      }

      // method of Lightbox to call
      var method = null;

      switch (event.which) {
      case 39: // right arrow key
        method = 'nextImage';
        break;
      case 37: // left arrow key
        method = 'prevImage';
        break;
      }

      if (method !== null && ['input', 'textarea'].indexOf(
          event.target.tagName.toLowerCase()) === -1) {
        // the view doesn't update without a manual digest
        $timeout(function () {
          Lightbox[method]();
        });

        event.preventDefault();
      }
    });

    return Lightbox;
  };
});
/**
 * This attribute directive is used in an img element in the modal template in
 *   place of src. It handles resizing both the img element and its relevant
 *   parent elements within the modal.
 */
angular.module('bootstrapLightbox').directive('lightboxSrc', function ($window,
    ImageLoader, Lightbox) {
  /**
   * Calculate the dimensions to display the image. The max dimensions
   *   override the min dimensions if they conflict.
   */
  var calculateImageDisplayDimensions = function (dimensions) {
    var w = dimensions.width;
    var h = dimensions.height;
    var minW = dimensions.minWidth;
    var minH = dimensions.minHeight;
    var maxW = dimensions.maxWidth;
    var maxH = dimensions.maxHeight;

    var displayW = w;
    var displayH = h;

    // resize the image if it is too small
    if (w < minW && h < minH) {
      // the image is both too thin and short, so compare the aspect ratios to
      // determine whether to min the width or height
      if (w / h > maxW / maxH) {
        displayH = minH;
        displayW = Math.round(w * minH / h);
      } else {
        displayW = minW;
        displayH = Math.round(h * minW / w);
      }
    } else if (w < minW) {
      // the image is too thin
      displayW = minW;
      displayH = Math.round(h * minW / w);
    } else if (h < minH) {
      // the image is too short
      displayH = minH;
      displayW = Math.round(w * minH / h);
    }

    // resize the image if it is too large
    if (w > maxW && h > maxH) {
      // the image is both too tall and wide, so compare the aspect ratios
      // to determine whether to max the width or height
      if (w / h > maxW / maxH) {
        displayW = maxW;
        displayH = Math.round(h * maxW / w);
      } else {
        displayH = maxH;
        displayW = Math.round(w * maxH / h);
      }
    } else if (w > maxW) {
      // the image is too wide
      displayW = maxW;
      displayH = Math.round(h * maxW / w);
    } else if (h > maxH) {
      // the image is too tall
      displayH = maxH;
      displayW = Math.round(w * maxH / h);
    }

    return {
      'width': displayW || 0,
      'height': displayH || 0 // NaN is possible when dimensions.width is 0
    };
  };

  // the dimensions of the image
  var imageWidth = 0;
  var imageHeight = 0;

  return {
    'link': function (scope, element, attrs) {
      // resize the img element and the containing modal
      var resize = function () {
        // get the window dimensions
        var windowWidth = $window.innerWidth;
        var windowHeight = $window.innerHeight;

        // calculate the max/min dimensions for the image
        var imageDimensionLimits = Lightbox.calculateImageDimensionLimits({
          'windowWidth': windowWidth,
          'windowHeight': windowHeight,
          'imageWidth': imageWidth,
          'imageHeight': imageHeight
        });

        // calculate the dimensions to display the image
        var imageDisplayDimensions = calculateImageDisplayDimensions(
          angular.extend({
            'width': imageWidth,
            'height': imageHeight,
            'minWidth': 1,
            'minHeight': 1,
            'maxWidth': 3000,
            'maxHeight': 3000,
          }, imageDimensionLimits)
        );

        // calculate the dimensions of the modal container
        var modalDimensions = Lightbox.calculateModalDimensions({
          'windowWidth': windowWidth,
          'windowHeight': windowHeight,
          'imageDisplayWidth': imageDisplayDimensions.width,
          'imageDisplayHeight': imageDisplayDimensions.height
        });

        // resize the image
        element.css({
          'width': imageDisplayDimensions.width + 'px',
          'height': imageDisplayDimensions.height + 'px'
        });

        // setting the height on .modal-dialog does not expand the div with the
        // background, which is .modal-content
        angular.element(
          document.querySelector('.lightbox-modal .modal-dialog')
        ).css({
          'width': modalDimensions.width + 'px'
        });

        // .modal-content has no width specified; if we set the width on
        // .modal-content and not on .modal-dialog, .modal-dialog retains its
        // default width of 600px and that places .modal-content off center
        angular.element(
          document.querySelector('.lightbox-modal .modal-content')
        ).css({
          'height': modalDimensions.height + 'px'
        });
      };

      // load the new image whenever the attr changes
      scope.$watch(function () {
        return attrs.lightboxSrc;
      }, function (src) {
        // blank the image before resizing the element; see
        // http://stackoverflow.com/questions/5775469/whats-the-valid-way-to-include-an-image-with-no-src
        element[0].src = '//:0';

        ImageLoader.load(src).then(function (image) {
          // these variables must be set before resize(), as they are used in it
          imageWidth = image.naturalWidth;
          imageHeight = image.naturalHeight;

          // resize the img element and the containing modal
          resize();

          // show the image
          element[0].src = src;
        });
      });

      // resize the image and modal whenever the window gets resized
      angular.element($window).on('resize', resize);
    }
  };
});


text:
namespace {

const int kMaxTrackingId = 0xffff;  // TRKID_MAX in kernel.

struct TouchCalibration {
  int bezel_left;
  int bezel_right;
  int bezel_top;
  int bezel_bottom;
};

void GetTouchCalibration(TouchCalibration* cal) {
  std::vector<std::string> parts;
  if (Tokenize(base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
                   switches::kTouchCalibration),
               ",", &parts) >= 4) {
    if (!base::StringToInt(parts[0], &cal->bezel_left))
      LOG(ERROR) << "Incorrect left border calibration value passed.";
    if (!base::StringToInt(parts[1], &cal->bezel_right))
      LOG(ERROR) << "Incorrect right border calibration value passed.";
    if (!base::StringToInt(parts[2], &cal->bezel_top))
      LOG(ERROR) << "Incorrect top border calibration value passed.";
    if (!base::StringToInt(parts[3], &cal->bezel_bottom))
      LOG(ERROR) << "Incorrect bottom border calibration value passed.";
  }
}

int32_t AbsCodeToMtCode(int32_t code) {
  switch (code) {
    case ABS_X:
      return ABS_MT_POSITION_X;
    case ABS_Y:
      return ABS_MT_POSITION_Y;
    case ABS_PRESSURE:
      return ABS_MT_PRESSURE;
    case ABS_DISTANCE:
      return ABS_MT_DISTANCE;
    default:
      return -1;
  }
}

}  // namespace

namespace ui {

TouchEventConverterEvdev::TouchEventConverterEvdev(
    int fd,
    base::FilePath path,
    int id,
    InputDeviceType type,
    DeviceEventDispatcherEvdev* dispatcher)
    : EventConverterEvdev(fd, path, id, type),
      dispatcher_(dispatcher),
      syn_dropped_(false),
      has_mt_(false),
      touch_points_(0),
      next_tracking_id_(0),
      current_slot_(0) {
  if (base::CommandLine::ForCurrentProcess()->HasSwitch(
          switches::kExtraTouchNoiseFiltering)) {
    touch_noise_finder_.reset(new TouchNoiseFinder);
  }
}

TouchEventConverterEvdev::~TouchEventConverterEvdev() {
  Stop();
  close(fd_);
}

void TouchEventConverterEvdev::Initialize(const EventDeviceInfo& info) {
  has_mt_ = info.HasMultitouch();

  if (has_mt_) {
    pressure_min_ = info.GetAbsMinimum(ABS_MT_PRESSURE);
    pressure_max_ = info.GetAbsMaximum(ABS_MT_PRESSURE);
    x_min_tuxels_ = info.GetAbsMinimum(ABS_MT_POSITION_X);
    x_num_tuxels_ = info.GetAbsMaximum(ABS_MT_POSITION_X) - x_min_tuxels_ + 1;
    y_min_tuxels_ = info.GetAbsMinimum(ABS_MT_POSITION_Y);
    y_num_tuxels_ = info.GetAbsMaximum(ABS_MT_POSITION_Y) - y_min_tuxels_ + 1;
    touch_points_ =
        std::min<int>(info.GetAbsMaximum(ABS_MT_SLOT) + 1, kNumTouchEvdevSlots);
    current_slot_ = info.GetAbsValue(ABS_MT_SLOT);
  } else {
    pressure_min_ = info.GetAbsMinimum(ABS_PRESSURE);
    pressure_max_ = info.GetAbsMaximum(ABS_PRESSURE);
    x_min_tuxels_ = info.GetAbsMinimum(ABS_X);
    x_num_tuxels_ = info.GetAbsMaximum(ABS_X) - x_min_tuxels_ + 1;
    y_min_tuxels_ = info.GetAbsMinimum(ABS_Y);
    y_num_tuxels_ = info.GetAbsMaximum(ABS_Y) - y_min_tuxels_ + 1;
    touch_points_ = 1;
    current_slot_ = 0;
  }

  // Apply --touch-calibration.
  if (type() == INPUT_DEVICE_INTERNAL) {
    TouchCalibration cal = {};
    GetTouchCalibration(&cal);
    x_min_tuxels_ += cal.bezel_left;
    x_num_tuxels_ -= cal.bezel_left + cal.bezel_right;
    y_min_tuxels_ += cal.bezel_top;
    y_num_tuxels_ -= cal.bezel_top + cal.bezel_bottom;

    VLOG(1) << "applying touch calibration: "
            << base::StringPrintf("[%d, %d, %d, %d]", cal.bezel_left,
                                  cal.bezel_right, cal.bezel_top,
                                  cal.bezel_bottom);
  }

  events_.resize(touch_points_);

  if (has_mt_) {
    for (size_t i = 0; i < events_.size(); ++i) {
      events_[i].x = info.GetAbsMtSlotValue(ABS_MT_POSITION_X, i);
      events_[i].y = info.GetAbsMtSlotValue(ABS_MT_POSITION_Y, i);
      events_[i].tracking_id = info.GetAbsMtSlotValue(ABS_MT_TRACKING_ID, i);
      events_[i].touching = (events_[i].tracking_id >= 0);
      events_[i].slot = i;

      // Dirty the slot so we'll update the consumer at the first opportunity.
      // We can't dispatch here as this is currently called on the worker pool.
      // TODO(spang): Move initialization off worker pool.
      events_[i].altered = true;

      // Optional bits.
      events_[i].radius_x =
          info.GetAbsMtSlotValueWithDefault(ABS_MT_TOUCH_MAJOR, i, 0) / 2.0f;
      events_[i].radius_y =
          info.GetAbsMtSlotValueWithDefault(ABS_MT_TOUCH_MINOR, i, 0) / 2.0f;
      events_[i].pressure =
          ScalePressure(info.GetAbsMtSlotValue(ABS_MT_PRESSURE, i));
    }
  } else {
    // TODO(spang): Add key state to EventDeviceInfo to allow initial contact.
    events_[0].x = 0;
    events_[0].y = 0;
    events_[0].tracking_id = -1;
    events_[0].touching = false;
    events_[0].slot = 0;
    events_[0].radius_x = 0;
    events_[0].radius_y = 0;
    events_[0].pressure = 0;
  }
}

bool TouchEventConverterEvdev::Reinitialize() {
  EventDeviceInfo info;
  if (info.Initialize(fd_)) {
    Initialize(info);
    return true;
  }
  return false;
}

bool TouchEventConverterEvdev::HasTouchscreen() const {
  return true;
}

gfx::Size TouchEventConverterEvdev::GetTouchscreenSize() const {
  return gfx::Size(x_num_tuxels_, y_num_tuxels_);
}

int TouchEventConverterEvdev::GetTouchPoints() const {
  return touch_points_;
}

void TouchEventConverterEvdev::OnFileCanReadWithoutBlocking(int fd) {
  input_event inputs[kNumTouchEvdevSlots * 6 + 1];
  ssize_t read_size = read(fd, inputs, sizeof(inputs));
  if (read_size < 0) {
    if (errno == EINTR || errno == EAGAIN)
      return;
    if (errno != ENODEV)
      PLOG(ERROR) << "error reading device " << path_.value();
    Stop();
    return;
  }

  if (ignore_events_)
    return;

  for (unsigned i = 0; i < read_size / sizeof(*inputs); i++) {
    if (!has_mt_) {
      // Emulate the device as an MT device with only 1 slot by inserting extra
      // MT protocol events in the stream.
      EmulateMultitouchEvent(inputs[i]);
    }

    ProcessMultitouchEvent(inputs[i]);
  }
}

void TouchEventConverterEvdev::ProcessMultitouchEvent(
    const input_event& input) {
  if (input.type == EV_SYN) {
    ProcessSyn(input);
  } else if (syn_dropped_) {
    // Do nothing. This branch indicates we have lost sync with the driver.
  } else if (input.type == EV_ABS) {
    if (events_.size() <= current_slot_) {
      LOG(ERROR) << "current_slot_ (" << current_slot_
                 << ") >= events_.size() (" << events_.size() << ")";
    } else {
      ProcessAbs(input);
    }
  } else if (input.type == EV_KEY) {
    ProcessKey(input);
  } else {
    NOTIMPLEMENTED() << "invalid type: " << input.type;
  }
}

void TouchEventConverterEvdev::EmulateMultitouchEvent(
    const input_event& event) {
  input_event emulated_event = event;

  if (event.type == EV_ABS) {
    emulated_event.code = AbsCodeToMtCode(event.code);
    if (emulated_event.code >= 0)
      ProcessMultitouchEvent(emulated_event);
  } else if (event.type == EV_KEY && event.code == BTN_TOUCH) {
    emulated_event.type = EV_ABS;
    emulated_event.code = ABS_MT_TRACKING_ID;
    emulated_event.value = event.value ? NextTrackingId() : -1;
    ProcessMultitouchEvent(emulated_event);
  }
}

void TouchEventConverterEvdev::ProcessKey(const input_event& input) {
  switch (input.code) {
    case BTN_TOUCH:
      break;
    default:
      NOTIMPLEMENTED() << "invalid code for EV_KEY: " << input.code;
  }
}

void TouchEventConverterEvdev::ProcessAbs(const input_event& input) {
  switch (input.code) {
    case ABS_MT_TOUCH_MAJOR:
      // TODO(spang): If we have all of major, minor, and orientation,
      // we can scale the ellipse correctly. However on the Pixel we get
      // neither minor nor orientation, so this is all we can do.
      events_[current_slot_].radius_x = input.value / 2.0f;
      break;
    case ABS_MT_TOUCH_MINOR:
      events_[current_slot_].radius_y = input.value / 2.0f;
      break;
    case ABS_MT_POSITION_X:
      events_[current_slot_].x = input.value;
      break;
    case ABS_MT_POSITION_Y:
      events_[current_slot_].y = input.value;
      break;
    case ABS_MT_TRACKING_ID:
      if (input.value < 0) {
        events_[current_slot_].touching = false;
      } else {
        events_[current_slot_].touching = true;
        events_[current_slot_].cancelled = false;
      }
      events_[current_slot_].tracking_id = input.value;
      break;
    case ABS_MT_PRESSURE:
      events_[current_slot_].pressure = ScalePressure(input.value);
      break;
    case ABS_MT_SLOT:
      if (input.value >= 0 &&
          static_cast<size_t>(input.value) < events_.size()) {
        current_slot_ = input.value;
      } else {
        LOG(ERROR) << "invalid touch event index: " << input.value;
        return;
      }
      break;
    default:
      DVLOG(5) << "unhandled code for EV_ABS: " << input.code;
      return;
  }
  events_[current_slot_].altered = true;
}

void TouchEventConverterEvdev::ProcessSyn(const input_event& input) {
  switch (input.code) {
    case SYN_REPORT:
      if (syn_dropped_) {
        // Have to re-initialize.
        if (Reinitialize()) {
          syn_dropped_ = false;
        } else {
          LOG(ERROR) << "failed to re-initialize device info";
        }
      } else {
        ReportEvents(EventConverterEvdev::TimeDeltaFromInputEvent(input));
      }
      break;
    case SYN_DROPPED:
      // Some buffer has overrun. We ignore all events up to and
      // including the next SYN_REPORT.
      syn_dropped_ = true;
      break;
    default:
      NOTIMPLEMENTED() << "invalid code for EV_SYN: " << input.code;
  }
}

EventType TouchEventConverterEvdev::GetEventTypeForTouch(
    const InProgressTouchEvdev& touch) {
  if (touch.cancelled)
    return ET_UNKNOWN;

  if (touch_noise_finder_ && touch_noise_finder_->SlotHasNoise(touch.slot)) {
    if (touch.touching && !touch.was_touching)
      return ET_UNKNOWN;
    return ET_TOUCH_CANCELLED;
  }

  if (touch.touching)
    return touch.was_touching ? ET_TOUCH_MOVED : ET_TOUCH_PRESSED;
  return touch.was_touching ? ET_TOUCH_RELEASED : ET_UNKNOWN;
}

void TouchEventConverterEvdev::ReportEvent(const InProgressTouchEvdev& event,
                                           EventType event_type,
                                           const base::TimeDelta& timestamp) {
  dispatcher_->DispatchTouchEvent(TouchEventParams(
      id_, event.slot, event_type, gfx::PointF(event.x, event.y),
      gfx::Vector2dF(event.radius_x, event.radius_y), event.pressure,
      timestamp));
}

void TouchEventConverterEvdev::ReportEvents(base::TimeDelta delta) {
  if (touch_noise_finder_)
    touch_noise_finder_->HandleTouches(events_, delta);

  for (size_t i = 0; i < events_.size(); i++) {
    InProgressTouchEvdev* event = &events_[i];
    if (!event->altered)
      continue;

    EventType event_type = GetEventTypeForTouch(*event);
    if (event_type == ET_UNKNOWN || event_type == ET_TOUCH_CANCELLED)
      event->cancelled = true;

    if (event_type != ET_UNKNOWN)
      ReportEvent(*event, event_type, delta);

    event->was_touching = event->touching;
    event->altered = false;
  }
}

float TouchEventConverterEvdev::ScalePressure(int32_t value) {
  float pressure = value - pressure_min_;
  if (pressure_max_ - pressure_min_)
    pressure /= pressure_max_ - pressure_min_;
  return pressure;
}

int TouchEventConverterEvdev::NextTrackingId() {
  return next_tracking_id_++ & kMaxTrackingId;
}

}  // namespace ui


text:
using EntityFramework.DynamicFilters;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using Vstack.Common.Extensions;
using Vstack.Services.Data.EntityFramework.Conventions;
using Vstack.Services.Domain;
using Vstack.Services.General;

namespace Vstack.Services.Data.EntityFramework
{
    public class VstackEfDbContext : DbContext
    {
        public VstackEfDbContext(string connectionString)
            : base(connectionString)
        {
        }

        public void SetDeletedState(DeletedState deletedState)
        {
            switch (deletedState)
            {
                case DeletedState.Undeleted:
                    this.EnableFilter(GlobalFilter.Undeleted.ToString());
                    break;
                case DeletedState.Deleted:
                    this.EnableFilter(GlobalFilter.Deleted.ToString());
                    break;
            }
        }

        public void DetachExistingEntitiesAndAttachDomains<TDmn>(IEnumerable<TDmn> domains)
            where TDmn : class, IDataDomain
        {
            domains.ValidateNotNull();
            foreach (DbEntityEntry entity in this.ChangeTracker.Entries().Where(e => e.State == EntityState.Added || e.State == EntityState.Modified || e.State == EntityState.Deleted))
            {
                this.Entry(entity.Entity).State = EntityState.Detached;
            }

            foreach (TDmn domain in domains)
            {
                this.Entry(domain).State = domain.Id > 0 ? EntityState.Modified : EntityState.Added;
            }
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.ValidateNotNull();

            modelBuilder.Conventions.Add(new DateTime2Convention());
            modelBuilder.Filter(GlobalFilter.Undeleted.ToString(), (IDataDomain e) => !e.UtcDateDeleted.HasValue);
            modelBuilder.Filter(GlobalFilter.Deleted.ToString(), (IDataDomain e) => e.UtcDateDeleted.HasValue);
            modelBuilder.DisableFilterGlobally(GlobalFilter.Undeleted.ToString());
            modelBuilder.DisableFilterGlobally(GlobalFilter.Deleted.ToString());
        }
    }
}


text:
import lejos.nxt.*;
import lejos.nxt.comm.*;
import java.io.*;

/**
 * Receive data from another NXT, a PC, a phone,
 * or another bluetooth device.
 *
 * Waits for a connection, receives an int and returns
 * its negative as a reply, 100 times, and then closes
 * the connection, and waits for a new one.
 *
 * @author Lawrie Griffiths
 *
 */
public class BTReceive {

	public static void main(String [] args)  throws Exception
	{
		String connected = "Connected";
        String waiting = "Waiting...";
        String closing = "Closing...";

		while (true)
		{
			LCD.drawString(waiting,0,0);
			LCD.refresh();

	        BTConnection btc = Bluetooth.waitForConnection();

			LCD.clear();
			LCD.drawString(connected,0,0);
			LCD.refresh();

			DataInputStream dis = btc.openDataInputStream();
			DataOutputStream dos = btc.openDataOutputStream();

			for(int i=0;i<100;i++) {
				int n = dis.readInt();
				LCD.drawInt(n,7,0,1);
				LCD.refresh();
				dos.writeInt(-n);
				dos.flush();
			}

			dis.close();
			dos.close();
			Thread.sleep(100); // wait for data to drain
			LCD.clear();
			LCD.drawString(closing,0,0);
			LCD.refresh();
			btc.close();
			LCD.clear();
		}
	}
}


text:
<?php

namespace AppBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use AppBundle\Entity\MflTipoRecaudo;
use AppBundle\Form\MflTipoRecaudoType;

/**
 * MflTipoRecaudo controller.
 *
 * @Route("/mfltiporecaudo")
 */
class MflTipoRecaudoController extends Controller
{
    /**
     * Lists all MflTipoRecaudo entities.
     *
     * @Route("/", name="tipoRecaudo_index")
     * @Method("GET")
     */
    public function indexAction()
    {
        $helpers = $this->get("app.helpers");
        $em = $this->getDoctrine()->getManager();
        $mflTiposRecaudo = $em->getRepository('AppBundle:MflTipoRecaudo')->findBy(
            array('estado' => 1)
        );
        $response = array(
                    'status' => 'success',
                    'code' => 200,
                    'msj' => "Listado de tipos de recaudo",
                    'data'=> $mflTiposRecaudo,
            );

        return $helpers->json($response);
    }

    /**
     * Creates a new MflTipoRecaudo entity.
     *
     * @Route("/new", name="tipoRecaudo_new")
     * @Method({"GET", "POST"})
     */
    public function newAction(Request $request)
    {
        $helpers = $this->get("app.helpers");
        $hash = $request->get("authorization", null);
        $authCheck = $helpers->authCheck($hash);
        if ($authCheck== true) {
            $json = $request->get("json",null);
            $params = json_decode($json);

            /*if (count($params)==0) {
                $response = array(
                    'status' => 'error',
                    'code' => 400,
                    'msj' => "los campos no pueden estar vacios",
                );
            }else{*/
                $nombre = $params->nombre;

                $em = $this->getDoctrine()->getManager();
                $tipoRecaudo = $em->getRepository('AppBundle:MflTipoRecaudo')->findOneByNombre($params->nombre);

                if ($tipoRecaudo==null) {
                    $tipoRecaudo = new MflTipoRecaudo();

                    $tipoRecaudo->setNombre(strtoupper($nombre));
                    $tipoRecaudo->setEstado(true);

                    $em->persist($tipoRecaudo);
                    $em->flush();
                    $response = array(
                        'status' => 'success',
                        'code' => 200,
                        'msj' => "MflTipoRecaudo creado con exito",
                    );
                }else{
                    $response = array(
                        'status' => 'error',
                        'code' => 400,
                        'msj' => "El nombre del tipoRecaudo ya se encuentra registrado",
                    );
                }

            //}
        }else{
            $response = array(
                'status' => 'error',
                'code' => 400,
                'msj' => "Autorizacion no valida",
            );
            }
        return $helpers->json($response);
    }

    /**
     * Finds and displays a MflTipoRecaudo entity.
     *
     * @Route("/show/{id}", name="tipoRecaudo_show")
     * @Method("POST")
     */
    public function showAction(Request $request,$id)
    {
        $helpers = $this->get("app.helpers");
        $hash = $request->get("authorization", null);
        $authCheck = $helpers->authCheck($hash);

        if ($authCheck == true) {
            $em = $this->getDoctrine()->getManager();
            $tipoRecaudo = $em->getRepository('AppBundle:MflTipoRecaudo')->find($id);
            $response = array(
                    'status' => 'success',
                    'code' => 200,
                    'msj' => "tipoRecaudo encontrado",
                    'data'=> $tipoRecaudo,
            );
        }else{
            $response = array(
                    'status' => 'error',
                    'code' => 400,
                    'msj' => "Autorizacion no valida",
                );
        }
        return $helpers->json($response);
    }

    /**
     * Displays a form to edit an existing MflTipoRecaudo entity.
     *
     * @Route("/edit", name="tipoRecaudo_edit")
     * @Method({"GET", "POST"})
     */
    public function editAction(Request $request)
    {
        $helpers = $this->get("app.helpers");
        $hash = $request->get("authorization", null);
        $authCheck = $helpers->authCheck($hash);

        if ($authCheck==true) {
            $json = $request->get("json",null);
            $params = json_decode($json);

            $em = $this->getDoctrine()->getManager();

            $tipoRecaudo = $em->getRepository('AppBundle:MflTipoRecaudo')->find($params->id);
            if ($tipoRecaudo!=null) {

                $tipoRecaudo->setNombre(strtoupper($params->nombre));

                $em = $this->getDoctrine()->getManager();
                $em->persist($tipoRecaudo);
                $em->flush();

                $response = array(
                    'status' => 'success',
                    'code' => 200,
                    'msj' => "tipoRecaudo editada con exito",
                );
            }else{
                $response = array(
                    'status' => 'error',
                    'code' => 400,
                    'msj' => "La tipoRecaudo no se encuentra en la base de datos",
                );
            }
        }else{
            $response = array(
                    'status' => 'error',
                    'code' => 400,
                    'msj' => "Autorizacion no valida para editar banco",
                );
        }

        return $helpers->json($response);
    }

    /**
     * Deletes a MflTipoRecaudo entity.
     *
     * @Route("/{id}/delete", name="tipoRecaudo_delete")
     * @Method("POST")
     */
    public function deleteAction(Request $request,$id)
    {
        $helpers = $this->get("app.helpers");
        $hash = $request->get("authorization", null);
        $authCheck = $helpers->authCheck($hash);
        if ($authCheck==true) {
            $em = $this->getDoctrine()->getManager();
            $tipoRecaudo = $em->getRepository('AppBundle:MflTipoRecaudo')->find($id);

            $tipoRecaudo->setEstado(0);
            $em = $this->getDoctrine()->getManager();
                $em->persist($tipoRecaudo);
                $em->flush();
            $response = array(
                    'status' => 'success',
                        'code' => 200,
                        'msj' => "tipoRecaudo eliminado con exito",
                );
        }else{
            $response = array(
                    'status' => 'error',
                    'code' => 400,
                    'msj' => "Autorizacion no valida",
                );
        }
        return $helpers->json($response);
    }

    /**
     * Creates a form to delete a MflTipoRecaudo entity.
     *
     * @param MflTipoRecaudo $tipoRecaudo The MflTipoRecaudo entity
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm(MflTipoRecaudo $tipoRecaudo)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('tipoRecaudo_delete', array('id' => $tipoRecaudo->getId())))
            ->setMethod('DELETE')
            ->getForm()
        ;
    }

    /**
     * datos para select 2
     *
     * @Route("/select", name="tipoRecaudo_select")
     * @Method({"GET", "POST"})
     */
    public function selectAction()
    {
    $helpers = $this->get("app.helpers");
    $em = $this->getDoctrine()->getManager();
    $tipoRecaudos = $em->getRepository('AppBundle:MflTipoRecaudo')->findBy(
        array('estado' => 1)
    );
    $response=null;
    foreach ($tipoRecaudos as $key => $tipoRecaudo) {
        $response[$key] = array(
            'value' => $tipoRecaudo->getId(),
            'label' => $tipoRecaudo->getNombre(),
        );
      }
       return $helpers->json($response);
    }
}


text:
require 'spec_helper'

module KnowledgeBase
  describe Sectionables::Gallery do
  end
end


text:
<?php

// Require the base class.
require_once dirname(__DIR__) . "/BaseExample.php";
require_once 'utils/CreativeAssetUtils.php';

/**
 * This example creates a tracking creative associated with a given advertiser.
 *
 * Tags: creatives.insert
 *
 * @author api.jimper@gmail.com (Jonathon Imperiosi)
 */
class CreateTrackingCreative extends BaseExample {
  /**
   * (non-PHPdoc)
   * @see BaseExample::getInputParameters()
   * @return array
   */
  protected function getInputParameters() {
    return array(
        array('name' => 'user_profile_id',
              'display' => 'User Profile ID',
              'required' => true),
        array('name' => 'advertiser_id',
              'display' => 'Advertiser ID',
              'required' => true)
    );
  }

  /**
   * (non-PHPdoc)
   * @see BaseExample::run()
   */
  public function run() {
    $values = $this->formValues;

    printf(
        '
Creating tracking creative for advertiser ID %s
',
        $values['advertiser_id']
    );

    $creative = new Google_Service_Dfareporting_Creative();
    $creative->setAdvertiserId($values['advertiser_id']);
    $creative->setName('Test tracking creative');
    $creative->setType('TRACKING_TEXT');

    $result = $this->service->creatives->insert($values['user_profile_id'],
        $creative);

    $this->printResultsTable('Tracking creative created.', array($result));
  }

  /**
   * (non-PHPdoc)
   * @see BaseExample::getName()
   * @return string
   */
  public function getName() {
    return 'Create Tracking Creative';
  }

  /**
   * (non-PHPdoc)
   * @see BaseExample::getResultsTableHeaders()
   * @return array
   */
  public function getResultsTableHeaders() {
    return array(
        'id' => 'Creative ID',
        'name' => 'Creative Name',
        'type' => 'Creative type'
    );
  }
}


text:
module Jekyll
  module PaginateV2::AutoPages

    class Utils

      # Static: returns a fully formatted string with the tag macro (:tag) replaced
      #
      def self.format_tag_macro(toFormat, tag, slugify_config=nil)
        slugify_mode = slugify_config.has_key?('mode') ? slugify_config['mode'] : nil
        slugify_cased = slugify_config.has_key?('cased') ? slugify_config['cased'] : false
        return toFormat.sub(':tag', Jekyll::Utils.slugify(tag.to_s, mode:slugify_mode, cased:slugify_cased))
      end #function format_tag_macro

      # Static: returns a fully formatted string with the category macro (:cat) replaced
      #
      def self.format_cat_macro(toFormat, category, slugify_config=nil)
        slugify_mode = slugify_config.has_key?('mode') ? slugify_config['mode'] : nil
        slugify_cased = slugify_config.has_key?('cased') ? slugify_config['cased'] : false
        return toFormat.sub(':cat', Jekyll::Utils.slugify(category.to_s, mode:slugify_mode, cased:slugify_cased))
      end #function format_cat_macro

      # Static: returns a fully formatted string with the collection macro (:coll) replaced
      #
      def self.format_coll_macro(toFormat, collection, slugify_config=nil)
        slugify_mode = slugify_config.has_key?('mode') ? slugify_config['mode'] : nil
        slugify_cased = slugify_config.has_key?('cased') ? slugify_config['cased'] : false
        return toFormat.sub(':coll', Jekyll::Utils.slugify(collection.to_s, mode:slugify_mode, cased:slugify_cased))
      end #function format_coll_macro

      # Static: returns all documents from all collections defined in the hash of collections passed in
      # excludes all pagination pages though
      def self.collect_all_docs(site_collections)
        coll = []
        site_collections.each do |coll_name, coll_data|
          if !coll_data.nil?
            coll += coll_data.docs.select { |doc| !doc.data.has_key?('pagination') }.each{ |doc| doc.data['__coll'] = coll_name } # Exclude all pagination pages and then for every page store it's collection name
          end
        end
        return coll
      end

      def self.ap_index_posts_by(all_posts, index_key)
        return nil if all_posts.nil?
        return all_posts if index_key.nil?
        index = {}
        all_posts.each do |post|
          next if post.data.nil?
          next if !post.data.has_key?(index_key)
          next if post.data[index_key].nil?
          next if post.data[index_key].size <= 0
          next if post.data[index_key].to_s.strip.length == 0

          # Only tags and categories come as premade arrays, locale does not, so convert any data
          # elements that are strings into arrays
          post_data = post.data[index_key]
          if post_data.is_a?(String)
            post_data = post_data.split(/;|,|\s/)
          end

          post_data.each do |key|
            key = key.strip
            # If the key is a delimetered list of values
            # (meaning the user didn't use an array but a string with commas)
            key.split(/;|,/).each do |raw_k_split|
              k_split = raw_k_split.to_s.downcase.strip #Clean whitespace and junk
              if !index.has_key?(k_split)
                # Need to store the original key value here so that I can present it to the users as a page variable they can use (unmodified, e.g. tags not being 'sci-fi' but "Sci-Fi")
                # Also, only interested in storing all the keys not the pages in this case
                index[k_split.to_s] = [k_split.to_s, raw_k_split.to_s]
              end
            end
          end
        end
        return index
      end # function index_posts_by

    end # class Utils

  end # module PaginateV2
end # module Jekyll


text:
package pr0304Barracks.data;

import pr0304Barracks.contracts.Repository;
import pr0304Barracks.contracts.Unit;
import sun.reflect.generics.reflectiveObjects.NotImplementedException;

import java.util.Map;
import java.util.TreeMap;

public class UnitRepository implements Repository {

	private Map<String, Integer> amountOfUnits;

	public UnitRepository() {
		this.amountOfUnits = new TreeMap<>();
	}

	public void addUnit(Unit unit) {
		String unitType = unit.getClass().getSimpleName();
		if (!this.amountOfUnits.containsKey(unitType)) {
			this.amountOfUnits.put(unitType, 0);
		}

		int newAmount = this.amountOfUnits.get(unitType) + 1;
		this.amountOfUnits.put(unitType, newAmount);
	}

	public String getStatistics() {
		StringBuilder statBuilder = new StringBuilder();
		for (Map.Entry<String, Integer> entry : amountOfUnits.entrySet()) {
			String formatedEntry =
					String.format("%s -> %d%n", entry.getKey(), entry.getValue());
			statBuilder.append(formatedEntry);
		}
		statBuilder.setLength(statBuilder.length() - 1);

		return statBuilder.toString();
	}

	public void removeUnit(String unitType) {
		// TODO: implement for problem 4
		throw new NotImplementedException();
	}
}


text:
/**
 * Heaviside
 * General-purpose pub/sub usable in-window and cross-domain.
 *
 * @author Kyle Edwards <edwards.kyle.a@gmail.com>
 * @version 0.1.0
 */

"use strict";

var Heaviside,
    _listeners,
    _run,
    _extractParams,
    _UID = 0;

/**
 * Store of subscriber queues.
 * @private
 */
_listeners = {};

/**
 * Runs through callbacks and executes with payload data.
 *
 * @param {string}     key            Pub/sub message channel key
 * @param {?any}       params         Data payload for subscribers
 * @return {void}
 * @private
 */
_run = function (key, params) {

  var listeners,
      llen;

  if (!key || 'undefined' === typeof _listeners[key])
    return;

  listeners = _listeners[key];
  llen = listeners.length;

  while (llen--)
    listeners[llen](params);

};

Heaviside = {

  /**
   * Publishes a Heaviside event to a target Window object
   * or, if not provided, to the current Heaviside event
   * listeners.
   *
   * @param {Window}   targetWindow   Target Iframe Window object
   * @param {string}   key            Pub/sub message channel key
   * @param {?any}     data           Data payload for subscribers
   * @param {?string}  targetOrigin   Optional origin for x-domain messaging
   * @return {void}
   */
  publish: function (targetWindow, key, data, targetOrigin) {

    if (typeof targetWindow !== 'object' ||
        typeof targetWindow.postMessage !== 'function') {

      targetOrigin = data;
      data = key;
      key = targetWindow;
      _run(key, data);

    } else {

      if (typeof key === 'string')
        key = [key];

      if (typeof data !== 'undefined')
        key.push(data);

      if (typeof targetOrigin === 'undefined')
        targetOrigin = '*';

      key._isHeaviside = true;
      targetWindow.postMessage(key, targetOrigin);

    }

  },

  /**
   * Subscribes to a Heaviside event with a function callback.
   *
   * @param {string}   key            Pub/sub message channel key
   * @param {function} data           Data payload for subscribers
   * @return {boolean|integer}
   */
  subscribe: function (key, callback) {

    if (typeof callback !== 'function')
      return false;

    if ('undefined' === typeof _listeners[key])
      _listeners[key] = [];

    callback.uid = _UID;
    _listeners[key].push(callback);
    return _UID++;

  },

  /**
   * Removes a subscribed callback from the queue.
   *
   * @param {integer}  uid            Callback id returned upon subscription
   * @return {boolean}
   */
  unsubscribe: function (uid) {

    var key,
        llen;

    for (var key in _listeners) {

      if (!_listeners.hasOwnProperty(key))
        continue;

      llen = _listeners[key].length;
      while (llen--) {
        if (_listeners[key][llen].uid === uid) {
          _listeners[key].splice(llen, 1);
          return true;
        }
      }

    }

    return false;

  }

};

/**
 * Initialize message reciever for x-domain Heaviside exchanges.
 */
window.addEventListener('message', function (e) {

  var key,
      params;

  /* If message is not an intended Heaviside array, return. */
  if (!e.data._isHeaviside)
    return;

  key = e.data[0];
  params = e.data[1];

  _run(key, params);

});

module.exports = Heaviside;


text:
/**
 * Expose `Memory`.
 */

module.exports = Memory;

/**
 * Module dependencies.
 */

var Connector = require('./base-connector')
  , debug = require('debug')('memory')
  , util = require('util')
  , inherits = util.inherits
  , assert = require('assert')
  , JdbMemory = require('loopback-datasource-juggler/lib/connectors/memory');

/**
 * Create a new `Memory` connector with the given `options`.
 *
 * @param {Object} options
 * @return {Memory}
 */

function Memory() {
  // TODO implement entire memory connector
}

/**
 * Inherit from `DBConnector`.
 */

inherits(Memory, Connector);

/**
 * JugglingDB Compatibility
 */

Memory.initialize = JdbMemory.initialize;


text:
<?php
/**
 * License 2015
 *
 * @author Joseph Deray <joseph.deray@wolfe.com>
 */
namespace Giftcards\ModRewriteBundle;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Bundle\Bundle;

class GiftcardsModRewriteBundle extends Bundle
{
}


text:
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    <title>Feed Viewer 3 (ARIA)</title>

    <link rel="stylesheet" type="text/css" href="../../resources/css/ext-all.css" />

    <link rel="stylesheet" type="text/css" href="feed-viewer.css" />

        {pubDate:date("M j, Y, g:i a")}

{title}

by {author:defaultValue("Unknown")}

{content:this.getBody}


text:
package com.afollestad.materialdialogs.prefs;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Build;
import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;

import com.afollestad.materialdialogs.MaterialDialog;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author Marc Holder Kluver (marchold), Aidan Follestad (afollestad)
 */
public class MaterialListPreference extends ListPreference {

    private Context context;
    private MaterialDialog mDialog;

    public MaterialListPreference(Context context) {
        super(context);
        init(context);
    }

    public MaterialListPreference(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    private void init(Context context) {
        this.context = context;
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.GINGERBREAD_MR1)
            setWidgetLayoutResource(0);
    }

    @Override
    public void setEntries(CharSequence[] entries) {
        super.setEntries(entries);
        if (mDialog != null)
            mDialog.setItems(entries);
    }

    @Override
    public Dialog getDialog() {
        return mDialog;
    }

    @Override
    protected void showDialog(Bundle state) {
        if (getEntries() == null || getEntryValues() == null) {
            throw new IllegalStateException(
                    "ListPreference requires an entries array and an entryValues array.");
        }

        int preselect = findIndexOfValue(getValue());
        MaterialDialog.Builder builder = new MaterialDialog.Builder(context)
                .title(getDialogTitle())
                .content(getDialogMessage())
                .icon(getDialogIcon())
                .negativeText(getNegativeButtonText())
                .items(getEntries())
                .autoDismiss(true) // immediately close the dialog after selection
                .itemsCallbackSingleChoice(preselect, new MaterialDialog.ListCallbackSingleChoice() {
                    @Override
                    public boolean onSelection(MaterialDialog dialog, View itemView, int which, CharSequence text) {
                        onClick(null, DialogInterface.BUTTON_POSITIVE);
                        if (which >= 0 && getEntryValues() != null) {
                            String value = getEntryValues()[which].toString();
                            if (callChangeListener(value) && isPersistent())
                                setValue(value);
                        }
                        return true;
                    }
                });

        final View contentView = onCreateDialogView();
        if (contentView != null) {
            onBindDialogView(contentView);
            builder.customView(contentView, false);
        } else {
            builder.content(getDialogMessage());
        }

        PreferenceManager pm = getPreferenceManager();
        try {
            Method method = pm.getClass().getDeclaredMethod(
                    "registerOnActivityDestroyListener",
                    PreferenceManager.OnActivityDestroyListener.class);
            method.setAccessible(true);
            method.invoke(pm, this);
        } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
            e.printStackTrace();
        }

        mDialog = builder.build();
        if (state != null)
            mDialog.onRestoreInstanceState(state);
        mDialog.show();
    }

    @Override
    public void setValue(String value) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            super.setValue(value);
        } else {
            String oldValue = getValue();
            super.setValue(value);
            if (!TextUtils.equals(value, oldValue))
                notifyChanged();
        }
    }
}


text:
package io.github.zutherb.appstash.shop.repository.order.model;

import org.bson.types.ObjectId;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author zutherb
 */
@Document(collection = Order.COLLECTION_NAME)
public class Order implements Serializable {
    public static final String COLLECTION_NAME = "order";

    @Id
    private ObjectId id;

    @Indexed(unique = true)
    private long orderId;

    private ObjectId userId;
    private List<OrderItem> orderItems;

    @Indexed
    private Date orderDate = new Date();

    private DeliveryAddress deliveryAddress;

    private Supplier supplier;

    private String sessionId;

    public Order(long orderId, ObjectId userId, List<OrderItem> orderItems, DeliveryAddress deliveryAddress, String sessionId) {
        this.orderId = orderId;
        this.userId = userId;
        this.orderItems = orderItems;
        this.deliveryAddress = deliveryAddress;
        this.sessionId = sessionId;
    }

    public Order() {}

    public long getOrderId() {
        return orderId;
    }

    public void setOrderId(Long orderId) {
        this.orderId = orderId;
    }

    public ObjectId getUserId() {
        return userId;
    }

    public void setUserId(ObjectId userId) {
        this.userId = userId;
    }

    public List<OrderItem> getOrderItems() {
        if (orderItems == null) {
            orderItems = new ArrayList<>();
        }
        return orderItems;
    }

    public Date getOrderDate() {
        return orderDate;
    }

    public void setOrderDate(Date orderDate) {
        this.orderDate = orderDate;
    }

    public DeliveryAddress getDeliveryAddress() {
        return deliveryAddress;
    }

    public void setDeliveryAddress(DeliveryAddress deliveryAddress) {
        this.deliveryAddress = deliveryAddress;
    }

    public Supplier getSupplier() {
        return supplier;
    }

    public void setSupplier(Supplier supplier) {
        this.supplier = supplier;
    }

    public String getSessionId() {
        return sessionId;
    }

    public void setSessionId(String sessionId) {
        this.sessionId = sessionId;
    }

    public void setOrderId(long orderId) {
        this.orderId = orderId;
    }

    public BigDecimal getItemCount() {
        return new OrderItemAggregator() {
            @Override
            protected BigDecimal add(BigDecimal sum, OrderItem orderItem) {
                return sum.add(BigDecimal.ONE);
            }
        }.aggregate();
    }

    public BigDecimal getItemPriceSum() {
        return new OrderItemAggregator() {
            @Override
            protected BigDecimal add(BigDecimal sum, OrderItem orderItem) {
                return sum.add(BigDecimal.valueOf(orderItem.getProduct().getPrice()));
            }
        }.aggregate();
    }

    public BigDecimal getTotalSum() {
        return getItemPriceSum();
    }

    private abstract class OrderItemAggregator {
        public BigDecimal aggregate() {
            BigDecimal sum = BigDecimal.ZERO;
            for (OrderItem orderItem : getOrderItems()) {
                sum = add(sum, orderItem);
            }
            return sum;
        }

        protected abstract BigDecimal add(BigDecimal sum, OrderItem orderItem);
    }
}


text:
using QuantConnect.Data;

namespace QuantConnect.Algorithm.CSharp.Benchmarks
{
    /// <summary>
    /// Benchmark Algorithm: Pure processing of 1 equity second resolution with the same benchmark.
    /// </summary>
    /// <remarks>
    /// This should eliminate the synchronization part of LEAN and focus on measuring the performance of a single datafeed and event handling system.
    /// </remarks>
    public class EmptySingleSecuritySecondEquityBenchmark : QCAlgorithm
    {
        public override void Initialize()
        {
            SetStartDate(2008, 01, 01);
            SetEndDate(2008, 06, 01);
            SetBenchmark(dt => 1m);
            AddEquity("SPY", Resolution.Second);
        }

        public override void OnData(Slice data)
        {
        }
    }
}


text:
package io.crnk.reactive;

import io.crnk.core.boot.CrnkBoot;
import io.crnk.core.exception.ResourceNotFoundException;
import io.crnk.core.module.SimpleModule;
import io.crnk.core.queryspec.QuerySpec;
import io.crnk.core.resource.list.ResourceList;
import io.crnk.reactive.model.SlowTask;
import io.crnk.reactive.repository.ReactiveResourceRepositoryBase;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import reactor.core.publisher.Mono;

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

public class ReactiveRepositoryBaseTest {

	private Map<Long, SlowTask> tasks = new HashMap<>();

	private ReactiveResourceRepositoryBase base = new ReactiveResourceRepositoryBase(SlowTask.class) {
		@Override
		public Mono<ResourceList> findAll(QuerySpec querySpec) {
			return Mono.just(querySpec.apply(tasks.values()));
		}
	};
	private SlowTask task;

	@Before
	public void setup() {
		tasks.clear();

		SimpleModule baseModule = new SimpleModule("test");
		baseModule.addRepository(base);

		CrnkBoot boot = new CrnkBoot();
		boot.addModule(baseModule);
		boot.addModule(new ReactiveModule());
		boot.boot();
		base.setResourceRegistry(boot.getResourceRegistry());

		task = new SlowTask();
		task.setId(1L);
		task.setName("test");
		tasks.put(task.getId(), task);
	}

	@Test
	public void checkFindAll() {
		QuerySpec querySpec = new QuerySpec(SlowTask.class);
		Mono<ResourceList> mono = base.findAll(querySpec);
		Assert.assertEquals(1, mono.block().size());
	}

	@Test
	public void checkFindExistingOne() {
		QuerySpec querySpec = new QuerySpec(SlowTask.class);
		Assert.assertSame(task, base.findOne(1L, querySpec).block());
	}

	@Test(expected = ResourceNotFoundException.class)
	public void checkFindNonExistingOne() {
		QuerySpec querySpec = new QuerySpec(SlowTask.class);
		base.findOne(2L, querySpec).block();
	}

	@Test(expected = UnsupportedOperationException.class)
	public void cannotCreateByDefault() {
		base.create(null).block();
	}

	@Test(expected = UnsupportedOperationException.class)
	public void cannotUpdateByDefault() {
		base.save(null).block();
	}

	@Test(expected = UnsupportedOperationException.class)
	public void cannotDeleteByDefault() {
		base.delete(null).block();
	}
}


text:
die() {
	echo " *** ERROR: " $*
	exit 1
}

set -x

[ $BUILD_TARGET != pretty-check ] || {
    export PATH=/tmp/astyle/build/gcc/bin:$PATH || die
    ./bootstrap || die
    ./configure --enable-ftd --enable-cli --enable-diag --enable-dhcp6-client --enable-dhcp6-server --enable-dns-client --enable-commissioner --enable-joiner --with-examples=posix || die
    make pretty-check || die
}

[ $BUILD_TARGET != scan-build ] || {
    ./bootstrap || die
    scan-build ./configure --with-examples=posix --enable-ftd --enable-cli --enable-ncp || die
    scan-build --status-bugs -analyze-headers -v make || die
}

[ $BUILD_TARGET != arm-gcc49 ] || {
    export PATH=/tmp/gcc-arm-none-eabi-4_9-2015q3/bin:$PATH || die

    git checkout -- . || die
    git clean -xfd || die
    ./bootstrap || die
    COMMISSIONER=1 JOINER=1 DHCP6_CLIENT=1 DHCP6_SERVER=1 DNS_CLIENT=1 make -f examples/Makefile-cc2538 || die
    arm-none-eabi-size  output/cc2538/bin/ot-cli-ftd || die
    arm-none-eabi-size  output/cc2538/bin/ot-cli-mtd || die
    arm-none-eabi-size  output/cc2538/bin/ot-ncp-ftd || die
    arm-none-eabi-size  output/cc2538/bin/ot-ncp-mtd || die

    git checkout -- . || die
    git clean -xfd || die
    ./bootstrap || die
    COMMISSIONER=1 JOINER=1 DHCP6_CLIENT=1 DHCP6_SERVER=1 DNS_CLIENT=1 make -f examples/Makefile-da15000 || die
    arm-none-eabi-size  output/da15000/bin/ot-cli-ftd || die
    arm-none-eabi-size  output/da15000/bin/ot-cli-mtd || die
    arm-none-eabi-size  output/da15000/bin/ot-ncp-ftd || die
    arm-none-eabi-size  output/da15000/bin/ot-ncp-mtd || die

    git checkout -- . || die
    git clean -xfd || die
    ./bootstrap || die
    COMMISSIONER=1 JOINER=1 DHCP6_CLIENT=1 DHCP6_SERVER=1 DNS_CLIENT=1 make -f examples/Makefile-nrf52840 || die
    arm-none-eabi-size  output/nrf52840/bin/ot-cli-ftd || die
    arm-none-eabi-size  output/nrf52840/bin/ot-cli-mtd || die
    arm-none-eabi-size  output/nrf52840/bin/ot-ncp-ftd || die
    arm-none-eabi-size  output/nrf52840/bin/ot-ncp-mtd || die

    git checkout -- . || die
    git clean -xfd || die
    ./bootstrap || die
    make -f examples/Makefile-cc2650 || die
    arm-none-eabi-size  output/cc2650/bin/ot-cli-mtd || die
    arm-none-eabi-size  output/cc2650/bin/ot-ncp-mtd || die
}

[ $BUILD_TARGET != arm-gcc54 ] || {
    export PATH=/tmp/gcc-arm-none-eabi-5_4-2016q3/bin:$PATH || die

    git checkout -- . || die
    git clean -xfd || die
    ./bootstrap || die
    COMMISSIONER=1 JOINER=1 DHCP6_CLIENT=1 DHCP6_SERVER=1 DNS_CLIENT=1 make -f examples/Makefile-cc2538 || die
    arm-none-eabi-size  output/cc2538/bin/ot-cli-ftd || die
    arm-none-eabi-size  output/cc2538/bin/ot-cli-mtd || die
    arm-none-eabi-size  output/cc2538/bin/ot-ncp-ftd || die
    arm-none-eabi-size  output/cc2538/bin/ot-ncp-mtd || die

    git checkout -- . || die
    git clean -xfd || die
    ./bootstrap || die
    COMMISSIONER=1 JOINER=1 DHCP6_CLIENT=1 DHCP6_SERVER=1 DNS_CLIENT=1 make -f examples/Makefile-da15000 || die
    arm-none-eabi-size  output/da15000/bin/ot-cli-ftd || die
    arm-none-eabi-size  output/da15000/bin/ot-cli-mtd || die
    arm-none-eabi-size  output/da15000/bin/ot-ncp-ftd || die
    arm-none-eabi-size  output/da15000/bin/ot-ncp-mtd || die

    git checkout -- . || die
    git clean -xfd || die
    ./bootstrap || die
    COMMISSIONER=1 JOINER=1 DHCP6_CLIENT=1 DHCP6_SERVER=1 DNS_CLIENT=1 make -f examples/Makefile-nrf52840 || die
    arm-none-eabi-size  output/nrf52840/bin/ot-cli-ftd || die
    arm-none-eabi-size  output/nrf52840/bin/ot-cli-mtd || die
    arm-none-eabi-size  output/nrf52840/bin/ot-ncp-ftd || die
    arm-none-eabi-size  output/nrf52840/bin/ot-ncp-mtd || die

    git checkout -- . || die
    git clean -xfd || die
    ./bootstrap || die
    make -f examples/Makefile-cc2650 || die
    arm-none-eabi-size  output/cc2650/bin/ot-cli-mtd || die
    arm-none-eabi-size  output/cc2650/bin/ot-ncp-mtd || die
}

[ $BUILD_TARGET != posix ] || {
    sh -c '$CC --version' || die
    sh -c '$CXX --version' || die
    ./bootstrap || die
    make -f examples/Makefile-posix || die
}

[ $BUILD_TARGET != posix-distcheck ] || {
    export ASAN_SYMBOLIZER_PATH=`which llvm-symbolizer-3.4` || die
    export ASAN_OPTIONS=symbolize=1 || die
    ./bootstrap || die
    make -f examples/Makefile-posix distcheck || die
}

[ $BUILD_TARGET != posix-32-bit ] || {
    ./bootstrap || die
    COVERAGE=1 CFLAGS=-m32 CXXFLAGS=-m32 LDFLAGS=-m32 make -f examples/Makefile-posix check || die
}

[ $BUILD_TARGET != posix-ncp-spi ] || {
    ./bootstrap || die
    make -f examples/Makefile-posix check configure_OPTIONS="--enable-ftd --enable-ncp=spi --with-examples=posix --with-platform-info=POSIX" || die
}

[ $BUILD_TARGET != posix-ncp ] || {
    ./bootstrap || die
    COVERAGE=1 NODE_TYPE=ncp-sim make -f examples/Makefile-posix check || die
}


text:
package com.egov.recbot.json;

public class TestResponse {

    private final long id;
    private final String content;

    public TestResponse(long id, String content) {
        this.id = id;
        this.content = content;
    }

    public long getId() {
        return id;
    }

    public String getContent() {
        return content;
    }
}


text:
[![Build Status](http://img.shields.io/travis/wilmoore/sum.js.svg)](https://travis-ci.org/wilmoore/sum.js) [![NPM version](http://img.shields.io/npm/v/sum.js.svg)](https://www.npmjs.org/package/sum.js) [![NPM downloads](http://img.shields.io/npm/dm/sum.js.svg)](https://www.npmjs.org/package/sum.js) [![LICENSE](http://img.shields.io/npm/l/sum.js.svg)](license)

> Sum a list of number literals, nested object property values, or values returned from a custom function for [Node.js][] and the browser.

## Examples

#### Number literals

    sum([1, 2, 3, 4]);
    //=> 10

#### Nested object properties

    var strings = ['literal', 'constructor'];
    sum(strings, 'length');
    //=> 18

#### Custom function

    sum([1, 2, 3, 4], function (n) { n * 60 });
    //=> 600

## Installation

[component](http://component.io/wilmoore/sum.js)

    $ component install wilmoore/sum.js

[bower](http://sindresorhus.com/bower-components/)

    $ bower install sum.js

[npm](https://npmjs.org/package/sum.js)

[![NPM](https://nodei.co/npm/sum.js.png?downloads=true)](https://nodei.co/npm/sum.js/)

[volo](http://volojs.org)

    $ volo add wilmoore/sum.js

[manual][]

1. download

        % curl -#O https://raw.github.com/wilmoore/sum.js/master/sum.min.js
        or
        % curl -#O https://raw.github.com/wilmoore/sum.js/master/sum.js

2. use

        <script src="sum.min.js"></script>
        or
        <script src="sum.js"></script>

## License

  [MIT](license)

[Node.js]:  http://nodejs.org
[manual]:   http://yuiblog.com/blog/2006/06/01/global-domination/


text:
@testset "Get Class Name Function Tests" begin

  @test isdefined(Julz, :get_class_name) == true

  @test_throws MethodError Julz.get_class_name(1)

  @test Julz.get_class_name("first") == "First"

  @test Julz.get_class_name("first class") == "FirstClass"

  @test Julz.get_class_name("first_class") == "FirstClass"

  @test Julz.get_class_name("first-class") == "First-class"

end


text:
require 'spec_helper'
require 'stringio'
require 'redxml/protocol'

RSpec.describe RedXML::Server::ClientWorker do
  describe '#process' do
    let(:client) { StringIO.new }
    let(:response) do
      response = StringIO.new(client.string)
      RedXML::Protocol.read_packet(response)
    end
    subject { described_class.new(client) }

    it 'answers hello with version' do
      subject.process

      expect(response.command).to eq :hello
      expect(response.param).to eq "RedXML-#{RedXML::Server::VERSION}"
    end
  end
end


text:
<!DOCTYPE html>

<meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Forum</title>

    <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">

<link href="css/freelancer.css" rel="stylesheet">

    <link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic" rel="stylesheet" type="text/css">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation Menu
                </button>
                <button class="btn btn-primary lg-12" id="btnIndex">GØTREK</button>

Categories

Rainy Day

Active

Out and About

Road Trip

 Dare

gØTrek's Picks

About

Forum

                        Feedback

<!DOCTYPE html>

    <form action="MAILTO:gotrekgwc@gmail.com" method="post" enctype="text/plain">

Name:

<input type="text" name="name" value="Your name">

E-mail:

<input type="text" name="mail" value="Your email">

Category:

<input class="box" type="text" name="Category" value="Category">

Comment:

<input type="text" name="Comment" value="Comment Here.." size="50">

                    <input type="submit" value="Submit">
                        <input type="reset" value="Reset">
    </form>

Around the Web

                        Copyright © MAAS 2016


text:
<?php

class UpdateTest extends CommandTestCase
{
    public function testUpdateAssets()
    {
        $res = $this->getResources('assets');

        // Ensure the required vendor assets exists.

        $this->installVendorAssets();

        // Ensure the target resource do not exists.

        $res->uninstall();

        // Update resource using the artisan command.

        $this->artisan('adminlte:update');
        $this->assertTrue($res->installed());

        // Clear installed resources.

        $res->uninstall();
        $this->assertFalse($res->installed());
    }

    public function testUpdateAssetsOverwrite()
    {
        $res = $this->getResources('assets');

        // Ensure the required vendor assets exists.

        $this->installVendorAssets();

        // Ensure a target resource exists.

        $this->createDummyResource('assets', $res);

        // Update resource using the artisan command.

        $this->artisan('adminlte:update');
        $this->assertTrue($res->installed());

        // Clear installed resources.

        $res->uninstall();
        $this->assertFalse($res->installed());
    }
}


text:
{% extends "base.html" %}
{% load devicetags %}
{% load i18n %}

{% block title %}
    {% blocktrans %}Transfer ownerships from {{ old_user.name }} to {{ new_user.name }}{% endblocktrans %}
{% endblock %}

{% block header %}{% endblock %}

{% block content %}

                {% get_verbose_name old_user as verbose_name %}
                {% blocktrans %}Do you really want to transfer the {{ verbose_name }} ownerships from {{ old_user }} to {{ new_user }}?{% endblocktrans %}

            <form action="" method="post">
                {% csrf_token %}
                {% trans "No" %}
                <input type="submit" value="Yes" class="btn btn-success"/>
            </form>

{% endblock %}


text:
<?xml version="1.0" encoding="UTF-8"?>
<ldswebml type="image" uri="/media-library/images/gospel-art/book-of-mormon#angel-alma-the-younger-82773" xml:lang="eng" locale="eng" status="publish" xmlns:its="http://www.w3.org/2005/11/its">
  <search-meta>
      <uri-title its:translate="no">angel-alma-the-younger-82773</uri-title>
      <source>angel-alma-the-younger-82773</source>
      <publication-type its:translate="no">image</publication-type>
      <media-type its:translate="no">image</media-type>
      <publication value="ldsorg">LDS.org</publication>
      <publication-date value="2012-07-02">2012-07-02</publication-date>
      <title>Conversion of Alma the Younger</title>
      <description>Conversion of Alma the Younger (Gospel Art Book [2009], no. 77) - Mosiah 27:8–37; Alma 36:3–24</description>
      <collections>
          <collection its:translate="no">global-search</collection>
          <collection its:translate="no">media</collection>
          <collection its:translate="no">images</collection>
      </collections>
      <subjects>
          <subject>alma the younger</subject>
          <subject>sons of mosiah</subject>
          <subject>angel</subject>
          <subject>vision</subject>
          <subject>conversion</subject>
          <subject>book of mormon</subject>
          <subject>repentance</subject>
          <subject>Gospel Art Kit</subject>
      </subjects>
  </search-meta>
  <no-search>
      <path>http://media.ldscdn.org/images/media-library/gospel-art/book-of-mormon/angel-alma-the-younger-82773-gallery.jpg</path>
      <images>
          http://media.ldscdn.org/images/media-library/gospel-art/book-of-mormon/angel-alma-the-younger-82773-thumbnail.jpg
      </images>
          <download-urls>
              <download-url>
                  Mobile
                  <size>557 KB</size>
                  <path>http://media.ldscdn.org/images/media-library/gospel-art/book-of-mormon/angel-alma-the-younger-82773-mobile.jpg</path>
              </download-url>
              <download-url>
                  Tablet
                  <size>758 KB</size>
                  <path>http://media.ldscdn.org/images/media-library/gospel-art/book-of-mormon/angel-alma-the-younger-82773-tablet.jpg</path>
              </download-url>
              <download-url>
                  Print
                  <size>1.4 MB</size>
                  <path>http://media.ldscdn.org/images/media-library/gospel-art/book-of-mormon/angel-alma-the-younger-82773-print.jpg</path>
              </download-url>
              <download-url>
                  Wallpaper
                  <size>2.2 MB</size>
                  <path>http://media.ldscdn.org/images/media-library/gospel-art/book-of-mormon/angel-alma-the-younger-82773-wallpaper.jpg</path>
              </download-url>
          </download-urls>
  </no-search>
</ldswebml>