text:
#ifndef PCL_FILTERS_IMPL_VOXEL_GRID_H_
#define PCL_FILTERS_IMPL_VOXEL_GRID_H_

#include <pcl/common/common.h>
#include <pcl/common/io.h>
#include <pcl/filters/voxel_grid.h>

///////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> void
pcl::getMinMax3D (const typename pcl::PointCloud<PointT>::ConstPtr &cloud,
                  const std::string &distance_field_name, float min_distance, float max_distance,
                  Eigen::Vector4f &min_pt, Eigen::Vector4f &max_pt, bool limit_negative)
{
  Eigen::Array4f min_p, max_p;
  min_p.setConstant (FLT_MAX);
  max_p.setConstant (-FLT_MAX);

  // Get the fields list and the distance field index
  std::vector<pcl::PCLPointField> fields;
  int distance_idx = pcl::getFieldIndex (*cloud, distance_field_name, fields);

  float distance_value;
  // If dense, no need to check for NaNs
  if (cloud->is_dense)
  {
    for (size_t i = 0; i < cloud->points.size (); ++i)
    {
      // Get the distance value
      const uint8_t* pt_data = reinterpret_cast<const uint8_t*> (&cloud->points[i]);
      memcpy (&distance_value, pt_data + fields[distance_idx].offset, sizeof (float));

      if (limit_negative)
      {
        // Use a threshold for cutting out points which inside the interval
        if ((distance_value < max_distance) && (distance_value > min_distance))
          continue;
      }
      else
      {
        // Use a threshold for cutting out points which are too close/far away
        if ((distance_value > max_distance) || (distance_value < min_distance))
          continue;
      }
      // Create the point structure and get the min/max
      pcl::Array4fMapConst pt = cloud->points[i].getArray4fMap ();
      min_p = min_p.min (pt);
      max_p = max_p.max (pt);
    }
  }
  else
  {
    for (size_t i = 0; i < cloud->points.size (); ++i)
    {
      // Get the distance value
      const uint8_t* pt_data = reinterpret_cast<const uint8_t*> (&cloud->points[i]);
      memcpy (&distance_value, pt_data + fields[distance_idx].offset, sizeof (float));

      if (limit_negative)
      {
        // Use a threshold for cutting out points which inside the interval
        if ((distance_value < max_distance) && (distance_value > min_distance))
          continue;
      }
      else
      {
        // Use a threshold for cutting out points which are too close/far away
        if ((distance_value > max_distance) || (distance_value < min_distance))
          continue;
      }

      // Check if the point is invalid
      if (!pcl_isfinite (cloud->points[i].x) ||
          !pcl_isfinite (cloud->points[i].y) ||
          !pcl_isfinite (cloud->points[i].z))
        continue;
      // Create the point structure and get the min/max
      pcl::Array4fMapConst pt = cloud->points[i].getArray4fMap ();
      min_p = min_p.min (pt);
      max_p = max_p.max (pt);
    }
  }
  min_pt = min_p;
  max_pt = max_p;
}

///////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> void
pcl::getMinMax3D (const typename pcl::PointCloud<PointT>::ConstPtr &cloud,
                  const std::vector<int> &indices,
                  const std::string &distance_field_name, float min_distance, float max_distance,
                  Eigen::Vector4f &min_pt, Eigen::Vector4f &max_pt, bool limit_negative)
{
  Eigen::Array4f min_p, max_p;
  min_p.setConstant (FLT_MAX);
  max_p.setConstant (-FLT_MAX);

  // Get the fields list and the distance field index
  std::vector<pcl::PCLPointField> fields;
  int distance_idx = pcl::getFieldIndex (*cloud, distance_field_name, fields);

  float distance_value;
  // If dense, no need to check for NaNs
  if (cloud->is_dense)
  {
    for (std::vector<int>::const_iterator it = indices.begin (); it != indices.end (); ++it)
    {
      // Get the distance value
      const uint8_t* pt_data = reinterpret_cast<const uint8_t*> (&cloud->points[*it]);
      memcpy (&distance_value, pt_data + fields[distance_idx].offset, sizeof (float));

      if (limit_negative)
      {
        // Use a threshold for cutting out points which inside the interval
        if ((distance_value < max_distance) && (distance_value > min_distance))
          continue;
      }
      else
      {
        // Use a threshold for cutting out points which are too close/far away
        if ((distance_value > max_distance) || (distance_value < min_distance))
          continue;
      }
      // Create the point structure and get the min/max
      pcl::Array4fMapConst pt = cloud->points[*it].getArray4fMap ();
      min_p = min_p.min (pt);
      max_p = max_p.max (pt);
    }
  }
  else
  {
    for (std::vector<int>::const_iterator it = indices.begin (); it != indices.end (); ++it)
    {
      // Get the distance value
      const uint8_t* pt_data = reinterpret_cast<const uint8_t*> (&cloud->points[*it]);
      memcpy (&distance_value, pt_data + fields[distance_idx].offset, sizeof (float));

      if (limit_negative)
      {
        // Use a threshold for cutting out points which inside the interval
        if ((distance_value < max_distance) && (distance_value > min_distance))
          continue;
      }
      else
      {
        // Use a threshold for cutting out points which are too close/far away
        if ((distance_value > max_distance) || (distance_value < min_distance))
          continue;
      }

      // Check if the point is invalid
      if (!pcl_isfinite (cloud->points[*it].x) ||
          !pcl_isfinite (cloud->points[*it].y) ||
          !pcl_isfinite (cloud->points[*it].z))
        continue;
      // Create the point structure and get the min/max
      pcl::Array4fMapConst pt = cloud->points[*it].getArray4fMap ();
      min_p = min_p.min (pt);
      max_p = max_p.max (pt);
    }
  }
  min_pt = min_p;
  max_pt = max_p;
}

struct cloud_point_index_idx
{
  unsigned int idx;
  unsigned int cloud_point_index;

  cloud_point_index_idx (unsigned int idx_, unsigned int cloud_point_index_) : idx (idx_), cloud_point_index (cloud_point_index_) {}
  bool operator < (const cloud_point_index_idx &p) const { return (idx < p.idx); }
};

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> void
pcl::VoxelGrid<PointT>::applyFilter (PointCloud &output)
{
  // Has the input dataset been set already?
  if (!input_)
  {
    PCL_WARN ("[pcl::%s::applyFilter] No input dataset given!\n", getClassName ().c_str ());
    output.width = output.height = 0;
    output.points.clear ();
    return;
  }

  // Copy the header (and thus the frame_id) + allocate enough space for points
  output.height       = 1;                    // downsampling breaks the organized structure
  output.is_dense     = true;                 // we filter out invalid points

  Eigen::Vector4f min_p, max_p;
  // Get the minimum and maximum dimensions
  if (!filter_field_name_.empty ()) // If we don't want to process the entire cloud...
    getMinMax3D<PointT> (input_, *indices_, filter_field_name_, static_cast<float> (filter_limit_min_), static_cast<float> (filter_limit_max_), min_p, max_p, filter_limit_negative_);
  else
    getMinMax3D<PointT> (*input_, *indices_, min_p, max_p);

  // Check that the leaf size is not too small, given the size of the data
  int64_t dx = static_cast<int64_t>((max_p[0] - min_p[0]) * inverse_leaf_size_[0])+1;
  int64_t dy = static_cast<int64_t>((max_p[1] - min_p[1]) * inverse_leaf_size_[1])+1;
  int64_t dz = static_cast<int64_t>((max_p[2] - min_p[2]) * inverse_leaf_size_[2])+1;

  if( (dx*dy*dz) > static_cast<int64_t>(std::numeric_limits<int32_t>::max()) )
  {
    PCL_WARN("[pcl::%s::applyFilter] Leaf size is too small for the input dataset. Integer indices would overflow.", getClassName().c_str());
    output = *input_;
    return;
  }

  // Compute the minimum and maximum bounding box values
  min_b_[0] = static_cast<int> (floor (min_p[0] * inverse_leaf_size_[0]));
  max_b_[0] = static_cast<int> (floor (max_p[0] * inverse_leaf_size_[0]));
  min_b_[1] = static_cast<int> (floor (min_p[1] * inverse_leaf_size_[1]));
  max_b_[1] = static_cast<int> (floor (max_p[1] * inverse_leaf_size_[1]));
  min_b_[2] = static_cast<int> (floor (min_p[2] * inverse_leaf_size_[2]));
  max_b_[2] = static_cast<int> (floor (max_p[2] * inverse_leaf_size_[2]));

  // Compute the number of divisions needed along all axis
  div_b_ = max_b_ - min_b_ + Eigen::Vector4i::Ones ();
  div_b_[3] = 0;

  // Set up the division multiplier
  divb_mul_ = Eigen::Vector4i (1, div_b_[0], div_b_[0] * div_b_[1], 0);

  int centroid_size = 4;
  if (downsample_all_data_)
    centroid_size = boost::mpl::size<FieldList>::value;

  // ---[ RGB special case
  std::vector<pcl::PCLPointField> fields;
  int rgba_index = -1;
  rgba_index = pcl::getFieldIndex (*input_, "rgb", fields);
  if (rgba_index == -1)
    rgba_index = pcl::getFieldIndex (*input_, "rgba", fields);
  if (rgba_index >= 0)
  {
    rgba_index = fields[rgba_index].offset;
    centroid_size += 3;
  }

  std::vector<cloud_point_index_idx> index_vector;
  index_vector.reserve (indices_->size ());

  // If we don't want to process the entire cloud, but rather filter points far away from the viewpoint first...
  if (!filter_field_name_.empty ())
  {
    // Get the distance field index
    std::vector<pcl::PCLPointField> fields;
    int distance_idx = pcl::getFieldIndex (*input_, filter_field_name_, fields);
    if (distance_idx == -1)
      PCL_WARN ("[pcl::%s::applyFilter] Invalid filter field name. Index is %d.\n", getClassName ().c_str (), distance_idx);

    // First pass: go over all points and insert them into the index_vector vector
    // with calculated idx. Points with the same idx value will contribute to the
    // same point of resulting CloudPoint
    for (std::vector<int>::const_iterator it = indices_->begin (); it != indices_->end (); ++it)
    {
      if (!input_->is_dense)
        // Check if the point is invalid
        if (!pcl_isfinite (input_->points[*it].x) ||
            !pcl_isfinite (input_->points[*it].y) ||
            !pcl_isfinite (input_->points[*it].z))
          continue;

      // Get the distance value
      const uint8_t* pt_data = reinterpret_cast<const uint8_t*> (&input_->points[*it]);
      float distance_value = 0;
      memcpy (&distance_value, pt_data + fields[distance_idx].offset, sizeof (float));

      if (filter_limit_negative_)
      {
        // Use a threshold for cutting out points which inside the interval
        if ((distance_value < filter_limit_max_) && (distance_value > filter_limit_min_))
          continue;
      }
      else
      {
        // Use a threshold for cutting out points which are too close/far away
        if ((distance_value > filter_limit_max_) || (distance_value < filter_limit_min_))
          continue;
      }

      int ijk0 = static_cast<int> (floor (input_->points[*it].x * inverse_leaf_size_[0]) - static_cast<float> (min_b_[0]));
      int ijk1 = static_cast<int> (floor (input_->points[*it].y * inverse_leaf_size_[1]) - static_cast<float> (min_b_[1]));
      int ijk2 = static_cast<int> (floor (input_->points[*it].z * inverse_leaf_size_[2]) - static_cast<float> (min_b_[2]));

      // Compute the centroid leaf index
      int idx = ijk0 * divb_mul_[0] + ijk1 * divb_mul_[1] + ijk2 * divb_mul_[2];
      index_vector.push_back (cloud_point_index_idx (static_cast<unsigned int> (idx), *it));
    }
  }
  // No distance filtering, process all data
  else
  {
    // First pass: go over all points and insert them into the index_vector vector
    // with calculated idx. Points with the same idx value will contribute to the
    // same point of resulting CloudPoint
    for (std::vector<int>::const_iterator it = indices_->begin (); it != indices_->end (); ++it)
    {
      if (!input_->is_dense)
        // Check if the point is invalid
        if (!pcl_isfinite (input_->points[*it].x) ||
            !pcl_isfinite (input_->points[*it].y) ||
            !pcl_isfinite (input_->points[*it].z))
          continue;

      int ijk0 = static_cast<int> (floor (input_->points[*it].x * inverse_leaf_size_[0]) - static_cast<float> (min_b_[0]));
      int ijk1 = static_cast<int> (floor (input_->points[*it].y * inverse_leaf_size_[1]) - static_cast<float> (min_b_[1]));
      int ijk2 = static_cast<int> (floor (input_->points[*it].z * inverse_leaf_size_[2]) - static_cast<float> (min_b_[2]));

      // Compute the centroid leaf index
      int idx = ijk0 * divb_mul_[0] + ijk1 * divb_mul_[1] + ijk2 * divb_mul_[2];
      index_vector.push_back (cloud_point_index_idx (static_cast<unsigned int> (idx), *it));
    }
  }

  // Second pass: sort the index_vector vector using value representing target cell as index
  // in effect all points belonging to the same output cell will be next to each other
  std::sort (index_vector.begin (), index_vector.end (), std::less<cloud_point_index_idx> ());

  // Third pass: count output cells
  // we need to skip all the same, adjacenent idx values
  unsigned int total = 0;
  unsigned int index = 0;
  while (index < index_vector.size ())
  {
    unsigned int i = index + 1;
    while (i < index_vector.size () && index_vector[i].idx == index_vector[index].idx)
      ++i;
    ++total;
    index = i;
  }

  // Fourth pass: compute centroids, insert them into their final position
  output.points.resize (total);
  if (save_leaf_layout_)
  {
    try
    {
      // Resizing won't reset old elements to -1.  If leaf_layout_ has been used previously, it needs to be re-initialized to -1
      uint32_t new_layout_size = div_b_[0]*div_b_[1]*div_b_[2];
      //This is the number of elements that need to be re-initialized to -1
      uint32_t reinit_size = std::min (static_cast<unsigned int> (new_layout_size), static_cast<unsigned int> (leaf_layout_.size()));
      for (uint32_t i = 0; i < reinit_size; i++)
      {
        leaf_layout_[i] = -1;
      }
      leaf_layout_.resize (new_layout_size, -1);
    }
    catch (std::bad_alloc&)
    {
      throw PCLException("VoxelGrid bin size is too low; impossible to allocate memory for layout",
        "voxel_grid.hpp", "applyFilter");
    }
    catch (std::length_error&)
    {
      throw PCLException("VoxelGrid bin size is too low; impossible to allocate memory for layout",
        "voxel_grid.hpp", "applyFilter");
    }
  }

  index = 0;
  Eigen::VectorXf centroid = Eigen::VectorXf::Zero (centroid_size);
  Eigen::VectorXf temporary = Eigen::VectorXf::Zero (centroid_size);

  for (unsigned int cp = 0; cp < index_vector.size ();)
  {
    // calculate centroid - sum values from all input points, that have the same idx value in index_vector array
    if (!downsample_all_data_)
    {
      centroid[0] = input_->points[index_vector[cp].cloud_point_index].x;
      centroid[1] = input_->points[index_vector[cp].cloud_point_index].y;
      centroid[2] = input_->points[index_vector[cp].cloud_point_index].z;
    }
    else
    {
      // ---[ RGB special case
      if (rgba_index >= 0)
      {
        // Fill r/g/b data, assuming that the order is BGRA
        pcl::RGB rgb;
        memcpy (&rgb, reinterpret_cast<const char*> (&input_->points[index_vector[cp].cloud_point_index]) + rgba_index, sizeof (RGB));
        centroid[centroid_size-3] = rgb.r;
        centroid[centroid_size-2] = rgb.g;
        centroid[centroid_size-1] = rgb.b;
      }
      pcl::for_each_type <FieldList> (NdCopyPointEigenFunctor <PointT> (input_->points[index_vector[cp].cloud_point_index], centroid));
    }

    unsigned int i = cp + 1;
    while (i < index_vector.size () && index_vector[i].idx == index_vector[cp].idx)
    {
      if (!downsample_all_data_)
      {
        centroid[0] += input_->points[index_vector[i].cloud_point_index].x;
        centroid[1] += input_->points[index_vector[i].cloud_point_index].y;
        centroid[2] += input_->points[index_vector[i].cloud_point_index].z;
      }
      else
      {
        // ---[ RGB special case
        if (rgba_index >= 0)
        {
          // Fill r/g/b data, assuming that the order is BGRA
          pcl::RGB rgb;
          memcpy (&rgb, reinterpret_cast<const char*> (&input_->points[index_vector[i].cloud_point_index]) + rgba_index, sizeof (RGB));
          temporary[centroid_size-3] = rgb.r;
          temporary[centroid_size-2] = rgb.g;
          temporary[centroid_size-1] = rgb.b;
        }
        pcl::for_each_type <FieldList> (NdCopyPointEigenFunctor <PointT> (input_->points[index_vector[i].cloud_point_index], temporary));
        centroid += temporary;
      }
      ++i;
    }

    // index is centroid final position in resulting PointCloud
    if (save_leaf_layout_)
      leaf_layout_[index_vector[cp].idx] = index;

    centroid /= static_cast<float> (i - cp);

    // store centroid
    // Do we need to process all the fields?
    if (!downsample_all_data_)
    {
      output.points[index].x = centroid[0];
      output.points[index].y = centroid[1];
      output.points[index].z = centroid[2];
    }
    else
    {
      pcl::for_each_type<FieldList> (pcl::NdCopyEigenPointFunctor <PointT> (centroid, output.points[index]));
      // ---[ RGB special case
      if (rgba_index >= 0)
      {
        // pack r/g/b into rgb
        float r = centroid[centroid_size-3], g = centroid[centroid_size-2], b = centroid[centroid_size-1];
        int rgb = (static_cast<int> (r) << 16) | (static_cast<int> (g) << 8) | static_cast<int> (b);
        memcpy (reinterpret_cast<char*> (&output.points[index]) + rgba_index, &rgb, sizeof (float));
      }
    }
    cp = i;
    ++index;
  }
  output.width = static_cast<uint32_t> (output.points.size ());
}

#define PCL_INSTANTIATE_VoxelGrid(T) template class PCL_EXPORTS pcl::VoxelGrid<T>;
#define PCL_INSTANTIATE_getMinMax3D(T) template PCL_EXPORTS void pcl::getMinMax3D<T> (const pcl::PointCloud<T>::ConstPtr &, const std::string &, float, float, Eigen::Vector4f &, Eigen::Vector4f &, bool);

#endif    // PCL_FILTERS_IMPL_VOXEL_GRID_H_


text:
package xyz.vopen.cartier.classified.logger;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * xyz.vopen.cartier.classified.logger
 *
 * @author Elve.xu [xuhw@yyft.com]
 * @version v1.0 - 14/08/2017.
 */
public class PatternBQ {
    public static void main (String[] args) {
        String str = "if a ansda {} asda , { } sadasdas,{}{}";
        Pattern pattern = Pattern.compile("\\{}|\\{\\s+}");
        Matcher matcher = pattern.matcher(str);
        while (matcher.find()) {
            System.out.println(matcher.group() + matcher.start());
        }

    }
}

redpajama_set_name: RedPajamaGithub


text:
require 'helper'

module UnitTests::TestRunners
end


text:
layout: post
title: The momlife hashtag
categories: Parenting
---

During research for this blog I tried to observe different social media channels and platforms for entries on the subject of **momlife**. Here are some of my insights.

##momlife on Pinterest

Momlife on Pinterest is full of words of advice. Instead of looking at this Social Network you can just buy one of this life saving guidebooks. The #momlife hashtag consist of prayers (Father, fill me with the strength to support, guide and walk my children through the stage they're growing through today.), advcices (How To Keep Baby Occupied All Day) and - of course - tips for beauty and household (20 Life-Changing Hacks for Doing Your Nails).

Feminism? Never heard about. Compatibility of family and career? Not my business. Career Tips für moms? Your kids are your career! Hello Pinterest, wake up. It's 2015!

Pins on Pinterest for [#momlife](https://de.pinterest.com/search/pins/?q=momlife&rs=typed&term_meta[]=momlife|typed)

##momlife on Twitter

Momlife on twitter is mostly fun and sarcasm. I enjoy looking through this hashtag every day. The best Tweets will be retweeted on our [FamilyLife.Rocks Account](https://twitter.com/familyrocksblog). It is so nice to see that other moms struggle too. For me it feels strenghtening and empowering to see momlife besides of perfect world commercials were everyone wears white clean clothes and the air is full with the smell of applepie...

Amongst some of my favorite examples is this tweet by **MommaPebz**

Playdoh is the epitome of love/hate. Hate the mess, love the HOURS of peaceful, content kids. [#momlife](https://twitter.com/hashtag/momlife?src=hash)
-- ››Heidi‹‹ (@MommaPebz) [December 3, 2015](https://twitter.com/MommaPebz/status/672498147390717952)

Twitter will be a standard when looking for inspiration.

Posts on Twitter with hashtag [#momlife](https://twitter.com/hashtag/momlife?src=hash).

##Momlife on Facebook

Momlife on Facebook is nearly as funny as momlife on twitter. The big difference is that there are a lot more entries that contains pictures of the kids. Since we are a no-pictures-of-the-kid's-face-on-the-internet-family we don't support that.

Entries on [Facebook](https://www.facebook.com/hashtag/momlife?fref=ts)

##Momlife on Tumblr

I think the spectrum of momlife posts is biggest on tumblr. Everyday I find Post that praise the inventor of alcohol, celebrates the afterbabybody and the afterbabyworkout or show everyday scenes with the kids.

In my perception, the pro breastfeeding movement is strongest on tumblr. You find a lot of pictures that show the normalcy of nursing without being pornography or too intimate. This is so great! And it s sad at the same time. Why do you need a movement for something that is so natural???

Entries on [Tumblr](https://www.tumblr.com/search/momlife)

##Momlife on Instagram

We are not on Instagram yet but we will see if this will change over time. Can somebody report on the available contents on the theme of momlife on Instagram?


text:
Uno
=======

Play the game Uno over the network, using the Harmonic synchronization
library and the JGrouos networking library.

Uno is interesting in the sense that it contains many aspects also found in
collectible card games:

- a variable number of players
- a modifiable turn order
- multiple zones where cards can reside, including public, private and hidden
  zones
- different kinds of cards that require the player to make extra decisions

of course, it lacks some common aspects:

- strategic decisions that require an AI to really "think" about their decisions
- introducing new objects/cards into the game


text:
/*jslint browser: true*/
/*global Tangram */
var picking = false;
map = (function () {
// (function () {
    // 'use strict';

    // defaults
    var map_start_location = [0, 0, 2]; // world
    var style_file = 'hotel.yaml';

    /*** URL parsing ***/

    // leaflet-style URL hash pattern:
    // #[zoom],[lat],[lng]
    var url_hash = window.location.hash.slice(1).split('/');

    // location
    var defaultpos = true; // use default position
    // location is passed through url
    if (url_hash.length == 3) {
        var defaultpos = false;
        map_start_location = [url_hash[1],url_hash[2], url_hash[0]];
        // convert from strings
        map_start_location = map_start_location.map(Number);
    }

    // normal case, eg: http://tangrams.github.io/nameless-maps/?roads#4/0/0
    var url_search = window.location.search.slice(1).split('/')[0];
    // console.log('url_search', url_search);
    if (url_search.length > 0) {
        style_file = url_search + ".yaml";
        // console.log('style_file', style_file);
    }

    /*** Map ***/

    var map = L.map('map',
        {"keyboardZoomOffset" : .05, "scrollWheelZoom": false }
    );
    map.setView(map_start_location.slice(0, 2), map_start_location[2]);

    var layer = Tangram.leafletLayer({
        scene: style_file,
        attribution: 'Tangram | © OSM contributors | Mapzen'
    });

    window.layer = layer;
    var scene = layer.scene;
    window.scene = scene;
    var latlng = {};

    // setView expects format ([lat, long], zoom)
    var hash = new L.Hash(map);

    function updateKey(value) {
        keytext = value;

        for (layer in scene.config.layers) {
            if (layer == "earth") continue;
            scene.config.layers[layer].properties.key_text = value;
        }
        scene.rebuildGeometry();
        scene.requestRedraw();
    }

    function updateValue(value) {
        valuetext = value;

        for (layer in scene.config.layers) {
            if (layer == "earth") continue;
            scene.config.layers[layer].properties.value_text = value;
        }
        scene.rebuildGeometry();
        scene.requestRedraw();
    }

    // Feature selection
    function initFeatureSelection () {
        var popup = document.getElementById('popup'); // click-popup

        // feature edit popup
        map.getContainer().addEventListener('mousemove', function (event) {
            picking = true;
            latlng = map.mouseEventToLatLng(event);

            var pixel = { x: event.clientX, y: event.clientY };

            scene.getFeatureAt(pixel).then(function(selection) {
                if (!selection || selection.feature == null || selection.feature.properties == null) {
                    picking = false;
                    popup.style.visibility = 'hidden';
                    return;
                }
                var properties = selection.feature.properties;

                // generate osm edit link
                var url = 'https://www.openstreetmap.org/edit?';
                var position = '19' + '/' + latlng.lat + '/' + latlng.lng;

                if (properties.id) {
                    url += 'node=' + properties.id + '#map=' + position;
                }

                var josmUrl = 'http://www.openstreetmap.org/edit?editor=remote#map='+position;

                popup.style.left = (pixel.x + 0) + 'px';
                popup.style.top = (pixel.y + 0) + 'px';

                if ( properties.kind == 'bed_and_breakfast' || properties.kind == 'chalet' || properties.kind == 'hostel' || properties.kind == 'hotel' || properties.kind == 'motel' || properties.kind == 'resort')
                {
	                popup.style.visibility = 'visible';
                    popup.innerHTML = '' + 'You found a lodging feature to enhance!' + '
';
                    popup.appendChild(createEditLinkElement(url, 'iD', 'Edit with iD ➹'));
                    popup.appendChild(createEditLinkElement(josmUrl, 'JOSM', 'Edit with JOSM ➹'));
	            }
            });
        });

        map.getContainer().addEventListener('mousedown', function (event) {
            popup.style.visibility = 'hidden';
        });
    }

    function createEditLinkElement (url, type, label) {
        var el = document.createElement('div');
        var anchor = document.createElement('a');
        el.className = 'labelInner';
        anchor.href = url;
        anchor.target = '_blank';
        anchor.textContent = label;
        anchor.addEventListener('click', function (event) {
            trackOutboundLink(url, 'editing_lodging_features', type);
        }, false);
        el.appendChild(anchor);
        return el;
    }

    /**
    * Function that tracks a click on an outbound link in Google Analytics.
    * This function takes a valid URL string as an argument, and uses that URL string
    * as the event label. Setting the transport method to 'beacon' lets the hit be sent
    * using 'navigator.sendBeacon' in browser that support it.
    */
    function trackOutboundLink (url, post_name, editor) {
       // ga('send', 'event', [eventCategory], [eventAction], [eventLabel], [eventValue], [fieldsObject]);
       ga('send', 'event', 'outbound', post_name, url, {
         'transport': 'beacon',
         // If opening a link in the current window, this opens the url AFTER
         // registering the hit with Analytics. Disabled because here want the
         // link to open in a new window, so this hit can occur in the current tab.
         //'hitCallback': function(){document.location = url;}
       });
    }

	function long2tile(lon,zoom) { return (Math.floor((lon+180)/360*Math.pow(2,zoom))); }
	function lat2tile(lat,zoom)  { return (Math.floor((1-Math.log(Math.tan(lat*Math.PI/180) + 1/Math.cos(lat*Math.PI/180))/Math.PI)/2 *Math.pow(2,zoom))); }

    /***** Render loop *****/

	function addGUI () {
		// Link to edit in OSM - hold 'e' and click
        function onMapClick(e) {
            var pixel = { x: e.clientX, y: e.clientY };
            if (key.shift) {
                var url = 'https://www.openstreetmap.org/edit?';
                scene.getFeatureAt(pixel).then(function(selection) {
                    console.log(selection.feature, selection.changed);

                    if (selection.feature && selection.feature.id) {
                        url += 'way=' + selection.feature.id;
                    }

                    url += '#map=' + map.getZoom() + '/' + latlng.lat + '/' + latlng.lng;

                    window.open(url, '_blank');
                });

            }

            if (key.command) {

                // find minimum max_zoom of all sources
                var max_zoom = 21;
                for (source in scene.config.sources) {
                    if (scene.config.sources.hasOwnProperty(source)) {
                        if (scene.config.sources[source].max_zoom != "undefined") {
                            max_zoom = Math.min(max_zoom, scene.config.sources[source].max_zoom);
                        }
                    }
                }

                var zoom = max_zoom < map.getZoom() ? max_zoom : Math.floor(map.getZoom());
                var tileCoords = { x : long2tile(latlng.lng,zoom), y: lat2tile(latlng.lat,zoom), z: zoom };

                var url = 'http://vector.mapzen.com/osm/all/' + zoom + '/' + tileCoords.x  + '/' + tileCoords.y + '.topojson?api_key=vector-tiles-HqUVidw';
                window.open(url, '_blank');
            }
        }

		map.on('click', onMapClick);
	}

    function inIframe () {
        try {
            return window.self !== window.top;
        } catch (e) {
            return true;
        }
    }

    // Add map
    window.addEventListener('load', function () {
        // Scene initialized
        layer.on('init', function() {
	        addGUI();
            initFeatureSelection();
            var camera = scene.config.cameras[scene.getActiveCamera()];
            // if a camera position is set in the scene file, use that
            if (defaultpos && typeof camera.position != "undefined") {
                map_start_location = [camera.position[1], camera.position[0], camera.position[2]]
            }
            map.setView([map_start_location[0], map_start_location[1]], map_start_location[2]);
        });
        if (!inIframe()) {
            map.scrollWheelZoom.enable();
        }
        layer.addTo(map);
    });

    return map;

}());


text:
import ConfigParser
import logging
import logging.handlers
import os
import subprocess

from nova.rootwrap import filters
from nova.rootwrap import wrapper
from nova import test

class RootwrapTestCase(test.TestCase):

    def setUp(self):
        super(RootwrapTestCase, self).setUp()
        self.filters = [
            filters.RegExpFilter("/bin/ls", "root", 'ls', '/[a-z]+'),
            filters.CommandFilter("/usr/bin/foo_bar_not_exist", "root"),
            filters.RegExpFilter("/bin/cat", "root", 'cat', '/[a-z]+'),
            filters.CommandFilter("/nonexistent/cat", "root"),
            filters.CommandFilter("/bin/cat", "root")  # Keep this one last
            ]

    def test_RegExpFilter_match(self):
        usercmd = ["ls", "/root"]
        filtermatch = wrapper.match_filter(self.filters, usercmd)
        self.assertFalse(filtermatch is None)
        self.assertEqual(filtermatch.get_command(usercmd),
            ["/bin/ls", "/root"])

    def test_RegExpFilter_reject(self):
        usercmd = ["ls", "root"]
        self.assertRaises(wrapper.NoFilterMatched,
            wrapper.match_filter, self.filters, usercmd)

    def test_missing_command(self):
        valid_but_missing = ["foo_bar_not_exist"]
        invalid = ["foo_bar_not_exist_and_not_matched"]
        self.assertRaises(wrapper.FilterMatchNotExecutable,
            wrapper.match_filter, self.filters, valid_but_missing)
        self.assertRaises(wrapper.NoFilterMatched,
            wrapper.match_filter, self.filters, invalid)

    def _test_DnsmasqFilter(self, filter_class, config_file_arg):
        usercmd = ['env', config_file_arg + '=A', 'NETWORK_ID=foobar',
                   'dnsmasq', 'foo']
        f = filter_class("/usr/bin/dnsmasq", "root")
        self.assertTrue(f.match(usercmd))
        self.assertEqual(f.get_command(usercmd), ['/usr/bin/dnsmasq', 'foo'])
        env = f.get_environment(usercmd)
        self.assertEqual(env.get(config_file_arg), 'A')
        self.assertEqual(env.get('NETWORK_ID'), 'foobar')

    def test_DnsmasqFilter(self):
        self._test_DnsmasqFilter(filters.DnsmasqFilter, 'CONFIG_FILE')

    def test_DeprecatedDnsmasqFilter(self):
        self._test_DnsmasqFilter(filters.DeprecatedDnsmasqFilter, 'FLAGFILE')

    def test_KillFilter(self):
        if not os.path.exists("/proc/%d" % os.getpid()):
            self.skipTest("Test requires /proc filesystem (procfs)")
        p = subprocess.Popen(["cat"], stdin=subprocess.PIPE,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.STDOUT)
        try:
            f = filters.KillFilter("root", "/bin/cat", "-9", "-HUP")
            f2 = filters.KillFilter("root", "/usr/bin/cat", "-9", "-HUP")
            usercmd = ['kill', '-ALRM', p.pid]
            # Incorrect signal should fail
            self.assertFalse(f.match(usercmd) or f2.match(usercmd))
            usercmd = ['kill', p.pid]
            # Providing no signal should fail
            self.assertFalse(f.match(usercmd) or f2.match(usercmd))
            # Providing matching signal should be allowed
            usercmd = ['kill', '-9', p.pid]
            self.assertTrue(f.match(usercmd) or f2.match(usercmd))

            f = filters.KillFilter("root", "/bin/cat")
            f2 = filters.KillFilter("root", "/usr/bin/cat")
            usercmd = ['kill', os.getpid()]
            # Our own PID does not match /bin/sleep, so it should fail
            self.assertFalse(f.match(usercmd) or f2.match(usercmd))
            usercmd = ['kill', 999999]
            # Nonexistent PID should fail
            self.assertFalse(f.match(usercmd) or f2.match(usercmd))
            usercmd = ['kill', p.pid]
            # Providing no signal should work
            self.assertTrue(f.match(usercmd) or f2.match(usercmd))
        finally:
            # Terminate the "cat" process and wait for it to finish
            p.terminate()
            p.wait()

    def test_KillFilter_no_raise(self):
        """Makes sure ValueError from bug 926412 is gone"""
        f = filters.KillFilter("root", "")
        # Providing anything other than kill should be False
        usercmd = ['notkill', 999999]
        self.assertFalse(f.match(usercmd))
        # Providing something that is not a pid should be False
        usercmd = ['kill', 'notapid']
        self.assertFalse(f.match(usercmd))

    def test_KillFilter_deleted_exe(self):
        """Makes sure deleted exe's are killed correctly"""
        # See bug #967931.
        def fake_readlink(blah):
            return '/bin/commandddddd (deleted)'

        f = filters.KillFilter("root", "/bin/commandddddd")
        usercmd = ['kill', 1234]
        # Providing no signal should work
        self.stubs.Set(os, 'readlink', fake_readlink)
        self.assertTrue(f.match(usercmd))

    def test_ReadFileFilter(self):
        goodfn = '/good/file.name'
        f = filters.ReadFileFilter(goodfn)
        usercmd = ['cat', '/bad/file']
        self.assertFalse(f.match(['cat', '/bad/file']))
        usercmd = ['cat', goodfn]
        self.assertEqual(f.get_command(usercmd), ['/bin/cat', goodfn])
        self.assertTrue(f.match(usercmd))

    def test_exec_dirs_search(self):
        # This test supposes you have /bin/cat or /usr/bin/cat locally
        f = filters.CommandFilter("cat", "root")
        usercmd = ['cat', '/f']
        self.assertTrue(f.match(usercmd))
        self.assertTrue(f.get_command(usercmd, exec_dirs=['/bin',
            '/usr/bin']) in (['/bin/cat', '/f'], ['/usr/bin/cat', '/f']))

    def test_skips(self):
        # Check that all filters are skipped and that the last matches
        usercmd = ["cat", "/"]
        filtermatch = wrapper.match_filter(self.filters, usercmd)
        self.assertTrue(filtermatch is self.filters[-1])

    def test_RootwrapConfig(self):
        raw = ConfigParser.RawConfigParser()

        # Empty config should raise ConfigParser.Error
        self.assertRaises(ConfigParser.Error, wrapper.RootwrapConfig, raw)

        # Check default values
        raw.set('DEFAULT', 'filters_path', '/a,/b')
        config = wrapper.RootwrapConfig(raw)
        self.assertEqual(config.filters_path, ['/a', '/b'])
        self.assertEqual(config.exec_dirs, os.environ["PATH"].split(':'))
        self.assertFalse(config.use_syslog)
        self.assertEqual(config.syslog_log_facility,
                         logging.handlers.SysLogHandler.LOG_SYSLOG)
        self.assertEqual(config.syslog_log_level, logging.ERROR)

        # Check general values
        raw.set('DEFAULT', 'exec_dirs', '/a,/x')
        config = wrapper.RootwrapConfig(raw)
        self.assertEqual(config.exec_dirs, ['/a', '/x'])

        raw.set('DEFAULT', 'use_syslog', 'oui')
        self.assertRaises(ValueError, wrapper.RootwrapConfig, raw)
        raw.set('DEFAULT', 'use_syslog', 'true')
        config = wrapper.RootwrapConfig(raw)
        self.assertTrue(config.use_syslog)

        raw.set('DEFAULT', 'syslog_log_facility', 'moo')
        self.assertRaises(ValueError, wrapper.RootwrapConfig, raw)
        raw.set('DEFAULT', 'syslog_log_facility', 'local0')
        config = wrapper.RootwrapConfig(raw)
        self.assertEqual(config.syslog_log_facility,
                         logging.handlers.SysLogHandler.LOG_LOCAL0)
        raw.set('DEFAULT', 'syslog_log_facility', 'LOG_AUTH')
        config = wrapper.RootwrapConfig(raw)
        self.assertEqual(config.syslog_log_facility,
                         logging.handlers.SysLogHandler.LOG_AUTH)

        raw.set('DEFAULT', 'syslog_log_level', 'bar')
        self.assertRaises(ValueError, wrapper.RootwrapConfig, raw)
        raw.set('DEFAULT', 'syslog_log_level', 'INFO')
        config = wrapper.RootwrapConfig(raw)
        self.assertEqual(config.syslog_log_level, logging.INFO)


text:
from __future__ import unicode_literals

import datetime

import modelcluster.fields
from django.db import migrations, models
from django.utils.timezone import utc

class Migration(migrations.Migration):

    dependencies = [
        ('newsletter', '0004_auto_20150723_1914'),
        ('articles', '0026_auto_20150728_1823'),
    ]

    operations = [

        migrations.AlterModelOptions(
            name='newsletterexternalarticlelink',
            options={'ordering': ['sort_order']},
        ),
        migrations.RemoveField(
            model_name='newsletterexternalarticlelink',
            name='external_article',
        ),
        migrations.RemoveField(
            model_name='newsletterexternalarticlelink',
            name='id',
        ),
        migrations.RemoveField(
            model_name='newsletterexternalarticlelink',
            name='newsletter',
        ),
        migrations.AddField(
            model_name='newsletterexternalarticlelink',
            name='externalarticle_ptr',
            field=models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, default=1, serialize=False, to='articles.ExternalArticlePage', on_delete=models.deletion.SET_NULL),
            preserve_default=False,
        ),
        migrations.AddField(
            model_name='newsletterexternalarticlelink',
            name='page',
            field=modelcluster.fields.ParentalKey(related_name='external_articles', default=1, to='newsletter.NewsletterPage'),
            preserve_default=False,
        ),
        migrations.AddField(
            model_name='newsletterexternalarticlelink',
            name='sort_order',
            field=models.IntegerField(null=True, editable=False, blank=True),
        ),
    ]


text:
package org.hawkular.agent.monitor.cmd;

import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Optional;

import org.hawkular.agent.monitor.inventory.InventoryIdUtil;
import org.hawkular.agent.monitor.inventory.InventoryIdUtil.ResourceIdParts;
import org.hawkular.agent.monitor.log.AgentLoggers;
import org.hawkular.agent.monitor.log.MsgLogger;
import org.hawkular.agent.monitor.protocol.EndpointService;
import org.hawkular.agent.monitor.protocol.dmr.DMRNodeLocation;
import org.hawkular.agent.monitor.protocol.dmr.DMRSession;
import org.hawkular.bus.common.BasicMessageWithExtraData;
import org.hawkular.bus.common.BinaryData;
import org.hawkular.cmdgw.api.MessageUtils;
import org.hawkular.cmdgw.api.ResourcePathRequest;
import org.hawkular.cmdgw.api.ResourcePathResponse;
import org.hawkular.cmdgw.api.ResponseStatus;
import org.hawkular.cmdgw.api.ServerRefreshIndicator;
import org.hawkular.dmr.api.OperationBuilder.OperationResult;
import org.hawkular.inventory.paths.CanonicalPath;
import org.jboss.as.controller.client.ModelControllerClient;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.Property;

/**
 * A base for {@link Command}s initiated by subclasses of {@link ResourcePathRequest}.
 *
 * Note that this assumes the resource path refers to DMR resource! Thus commands that extend
 * this class will assume to need to access a DMR endpoint and will perform DMR-related operations.
 *
 * @author Peter Palaga
 */
public abstract class AbstractDMRResourcePathCommand //
<REQ extends ResourcePathRequest, RESP extends ResourcePathResponse>
        extends AbstractResourcePathCommand<REQ, RESP> {

    private static final MsgLogger log = AgentLoggers.getLogger(AbstractDMRResourcePathCommand.class);

    public AbstractDMRResourcePathCommand(String operationName, String entityType) {
        super(operationName, entityType);
    }

    @Override
    public BasicMessageWithExtraData<RESP> execute(BasicMessageWithExtraData<REQ> envelope, CommandContext context)
            throws Exception {

        REQ request = envelope.getBasicMessage();
        String rawResourcePath = request.getResourcePath();
        log.infoReceivedResourcePathCommand(this.getOperationName(envelope), this.getEntityType(envelope),
                rawResourcePath);

        RESP response = createResponse();
        MessageUtils.prepareResourcePathResponse(request, response);
        BinaryData binaryData = null;
        ModelControllerClient controllerClient = null;
        long timestampBeforeExecution = System.currentTimeMillis();
        try {
            validate(envelope);

            // Based on the resource ID we need to know which inventory manager is handling it.
            // From the inventory manager, we can get the actual resource.
            CanonicalPath canonicalPath = CanonicalPath.fromString(rawResourcePath);

            String resourceId;
            try {
                resourceId = canonicalPath.ids().getResourcePath().getSegment().getElementId();
            } catch (Exception e) {
                throw new IllegalArgumentException("Bad resource path specified in command: " + rawResourcePath);
            }
            ResourceIdParts idParts = InventoryIdUtil.parseResourceId(resourceId);
            String modelNodePath = idParts.getIdPart();
            validate(modelNodePath, envelope);

            String managedServerName = idParts.getManagedServerName();
            EndpointService<DMRNodeLocation, DMRSession> endpointService = context.getAgentCoreEngine()
                    .getProtocolServices()
                    .getDmrProtocolService()
                    .getEndpointServices()
                    .get(managedServerName);
            if (endpointService == null) {
                throw new IllegalArgumentException(String.format(
                        "Cannot perform [%s] on a [%s] given by inventory path [%s]: unknown managed server [%s]",
                        this.getOperationName(envelope), this.getEntityType(envelope), resourceId, managedServerName));
            }

            validate(envelope, endpointService.getMonitoredEndpoint());

            if (modifiesResource()) {
                if (context.getAgentCoreEngine().isImmutable()) {
                    throw new IllegalStateException("Command not allowed because the agent is immutable");
                }
            }

            DMRSession session = endpointService.openSession();

            controllerClient = session.getClient();

            binaryData = execute(controllerClient, endpointService, modelNodePath, envelope, response, context,
                    session);
            success(envelope, response);

        } catch (Throwable t) {
            response.setStatus(ResponseStatus.ERROR);
            String formattedTimestamp = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mmX").withZone(ZoneOffset.UTC)
                    .format(Instant.ofEpochMilli(timestampBeforeExecution));

            String msg = String.format(
                    "Could not perform [%s] on a [%s] given by inventory path [%s] requested on [%s]: %s",
                    this.getOperationName(envelope), this.getEntityType(envelope), rawResourcePath, formattedTimestamp,
                    t.toString());
            response.setMessage(msg);
            log.debug(msg, t);
        } finally {
            if (controllerClient != null) {
                try {
                    controllerClient.close();
                } catch (Exception e) {
                    log.errorCannotClose(e, controllerClient.getClass().getName());
                }
            }
        }

        return new BasicMessageWithExtraData<>(response, binaryData);

    }

    /**
     * Do whatever with the already validated parameters.
     *
     * @param controllerClient a plain {@link ModelControllerClient}
     * @param endpointService an {@link EndpointService} belonging to the resource
     * @param modelNodePath a DMR path acquired from {@link ResourcePathRequest#getResourcePath()}
     * @param envelope the request
     * @param response the response
     * @param context the {@link CommandContext}
     * @param dmrContext a {@link DMRSession}
     * @return a {@link BinaryData} with binary content if this command returns any
     * @throws Exception if anything goes wrong
     */
    protected abstract BinaryData execute(ModelControllerClient controllerClient,
            EndpointService<DMRNodeLocation, DMRSession> endpointService,
            String modelNodePath, BasicMessageWithExtraData<REQ> envelope, RESP response, CommandContext context,
            DMRSession dmrContext)
            throws Exception;

    /**
     * {@code modelNodePath} validation for subclasses.
     *
     * @param modelNodePath a DMR path to check
     * @param envelope the request the {@code modelNodePath} comes from
     */
    protected abstract void validate(String modelNodePath, BasicMessageWithExtraData<REQ> envelope);

    /**
     * Given the results of an operation, this will set the {@link ServerRefreshIndicator}
     * found in those results in the given response.
     *
     * @param opResults contains the DMR results
     * @param response the response message
     */
    protected void setServerRefreshIndicator(OperationResult<?> opResults, RESP response) {
        Optional<String> processState = opResults.getOptionalProcessState();
        if (processState.isPresent()) {
            try {
                response.setServerRefreshIndicator(ServerRefreshIndicator.fromValue(processState.get().toUpperCase()));
            } catch (Exception e) {
                log.warnf("Cannot set server refresh indicator - process state is invalid", e);
            }
        }
    }

    protected void assertNotRename(ModelNode adr, String newName) {
        List<Property> adrProps = adr.asPropertyList();
        String nameFromPath = adrProps.get(adrProps.size() - 1).getValue().asString();
        if (!nameFromPath.equals(newName)) {
            String msg = String.format("Renaming a [%s] is not supported. Old name: [%s], new name: [%s]",
                    this.getEntityType(null), nameFromPath, newName);
            throw new IllegalArgumentException(msg);
        }
    }
}


text:
<?php

namespace Algolia\AlgoliaSearchBundle\Mapping\Helper;

class ChangeAwareMethod
{
    private $name;

    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    public function getName()
    {
        return $this->name;
    }

    /**
	 * This function violates all OOP design practices
	 * by setting private properties of an external object.
	 *
	 * Well done, PHP :) http://php.net/manual/fr/closure.bind.php
	 *
	 * But we need this, as we can't assume there are setters on all fields.
	 * And this is far more efficient than using a ReflectionClass:
	 * http://ocramius.github.io/blog/accessing-private-php-class-members-without-reflection/
	 */
    private function fillWith($entity, array $data)
    {
        $privateSetter = \Closure::bind(function () use ($data) {
            foreach ($data as $key => $value) {
                $this->$key = $value;
            }
        }, $entity, $entity);

        $privateSetter();

        return $entity;
    }

    public function diff($entity, array $changeSet)
    {
        $oldValues = [];
        foreach ($changeSet as $field => $oldNew) {
            $oldValues[$field] = $oldNew[0];
        }

        $oldValue = $this->evaluateWith($entity, $oldValues);
        $newValue = $this->evaluate($entity);

        return array($newValue, $oldValue);
    }

    public function evaluateWith($entity, array $data)
    {
        $oldEntity = $this->fillWith(clone $entity, $data);

        return $this->evaluate($oldEntity);
    }

    public function evaluate($entity)
    {
        return call_user_func(array($entity, $this->getName()));
    }
}


text:
package org.apache.camel.component.gson.converter;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;

import com.google.gson.Gson;
import org.apache.camel.Converter;
import org.apache.camel.Exchange;
import org.apache.camel.spi.TypeConverterRegistry;

/**
 * GSon {@link org.apache.camel.TypeConverter} that allows converting json to byte buffer/stream oriented output. <br/>
 * This implementation uses a fallback converter.
 */
@Converter(generateLoader = true)
public final class GsonTypeConverters {

    private final Gson gson;

    public GsonTypeConverters() {
        // Default configuration should be okey for conversion purposes
        this.gson = new Gson();
    }

    @Converter(fallback = true)
    public <T> T convertTo(Class<T> type, Exchange exchange, Object value, TypeConverterRegistry registry) throws Exception {
        if (ByteBuffer.class.isAssignableFrom(type)) {
            byte[] out = gson.toJson(value).getBytes(StandardCharsets.UTF_8);
            return type.cast(ByteBuffer.wrap(out));
        } else if (InputStream.class.isAssignableFrom(type)) {
            byte[] out = gson.toJson(value).getBytes(StandardCharsets.UTF_8);
            return type.cast(new ByteArrayInputStream(out));
        }

        return null;
    }

}


text:
from PathFilter import PathFilter

## A PathFilter which filters based on an item from Path.info() and an
# arbitrary match function.
class InfoPathFilter( PathFilter ) :

	def __init__( self, infoKey, matcher, leafOnly=True, userData={} ) :

		PathFilter.__init__( self, userData )

		self.__infoKey = infoKey
		self.__matcher = matcher
		self.__leafOnly = leafOnly

	## Matcher and infoKey are set with one call, as otherwise
	# the intermediate state may yield a new matcher which doesn't work
	# with the old key.
	def setMatcher( self, infoKey, matcher ) :

		self.__infoKey = infoKey
		self.__matcher = matcher
		self.changedSignal()( self )

	def getMatcher( self ) :

		return self.__infoKey, self.__matcher

	def _filter( self, paths ) :

		if self.__matcher is None :
			return paths

		result = []
		for p in paths :
			if self.__leafOnly and not p.isLeaf() :
				result.append( p )
			else :
				i = p.info()
				if self.__infoKey in i :
					if self.__matcher( i[self.__infoKey] ) :
						result.append( p )

		return result


text:
class PhysicalInfraOverviewController < ApplicationController
  extend ActiveSupport::Concern

  include Mixins::GenericSessionMixin

  before_action :check_privileges
  before_action :get_session_data
  after_action :cleanup_action
  after_action :set_session_data

  def show
    assert_privileges('physical_infra_overview_view')
    @lastaction = 'show_dashboard'
    if params[:id].nil?
      @breadcrumbs.clear
    end
  end

  def index
    redirect_to(:action => 'show')
  end

  def title
    _("Physical Providers Overview")
  end

  def self.session_key_prefix
    "physical_infra_overview"
  end

  menu_section :phy
end


text:
namespace Azure.DigitalTwins.Core
{
    /// <summary> Parameter group. </summary>
    internal partial class GetIncomingRelationshipsOptions
    {
        /// <summary> Initializes a new instance of GetIncomingRelationshipsOptions. </summary>
        public GetIncomingRelationshipsOptions()
        {
        }
    }
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: laogui
 * Date: 17/5/9
 * Time: 下午5:13
 */

namespace Sukui;

class Request{
    public $app;
    public $req;
    public $res;
    public $ctx;
    public $response;
    public $originalUrl;
    public $ip;
    public function __construct(Application $app, ServerContext $ctx, \swoole_http_request $req, \swoole_http_response $res) {
        $this->app = $app;
        $this->ctx = $ctx;
        $this->req = $req;
        $this->res = $res;
    }

    public function __get($name) {
        switch ($name){
            case 'rawcontent':
                return $this->req->rawContent();
            case 'post':
                return isset($this->req->post)?$this->req->post:[];
            case 'get':
                return isset($this->req->get)?$this->req->get:[];
            case 'cookie':
            case 'cookies':
                return isset($this->req->cookie) ? $this->req->cookie : [];
            case "request":
                return isset($this->req->request) ? $this->req->request : [];
            case "header":
            case "headers":
                return isset($this->req->header) ? $this->req->header : [];
            case "files":
                return isset($this->req->files) ? $this->req->files : [];
            case "method":
                return $this->req->server["request_method"];
            case "url":
            case "origin":
                return $this->req->server["request_uri"];
            case "path":
                return isset($this->req->server["path_info"]) ? $this->req->server["path_info"] : "";
            case "query":
            case "querystring":
                return isset($this->req->server["query_string"]) ? $this->req->server["query_string"] : "";
            case "host":
            case "hostname":
                return isset($this->req->header["host"]) ? $this->req->header["host"] : "";
            case "protocol":
                return $this->req->server["server_protocol"];
            default:
                return $this->req->$name;
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<template type="basic" name="CpsH1alphaSPINAL" author="Agilent" investigator=""
        time_created="20111219T120000" tabname="AutoSolids Experiments" menu1="Calibration(tancpx)" menu2="H Decoupling" apptype="solidsseq1d"
        application="Solids" scans="CpsH1alphaSPINAL" seqfil="tancpx">
  <protocol title="CpsH1alphaSPINAL" type="protocol">
    <action  type="LIB" status="Ready" lock="off" title="CpsH1alphaSPINAL" exp="CpsH1alphaSPINAL"
        time="1:45" macro="CpsH1alphaSPINAL" data="" />
  </protocol>
</template>


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2014.08.15 at 08:44:37 PM EDT
//

package org.sierraecg.schema.jaxb._1_03;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for anonymous complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType>
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element ref="{http://www3.medical.philips.com}drgcategory" maxOccurs="4" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "drgcategory"
})
@XmlRootElement(name = "drgcategories")
public class Drgcategories {

    protected List<Drgcategory> drgcategory;

    /**
     * Gets the value of the drgcategory property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the drgcategory property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getDrgcategory().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link Drgcategory }
     *
     *
     */
    public List<Drgcategory> getDrgcategory() {
        if (drgcategory == null) {
            drgcategory = new ArrayList<Drgcategory>();
        }
        return this.drgcategory;
    }

}


text:
SHELL = /bin/bash
CRYSTAL ?= crystal
RELEASE=
STATIC ?= ""
LINK_FLAGS = --link-flags ${STATIC}
SRCDIR = ./src/bin
BINDIR = ./bin
SRCS = ${wildcard src/bin/*.cr}
BINS = $(addprefix $(BINDIR)/, $(SRCS:src/bin/%.cr=%))
DATA_GEN = ./bin/kafka-packet -v -X --api-ver

VERSION=
CURRENT_VERSION=$(shell git tag -l | sort -V | tail -1)
GUESSED_VERSION=$(shell git tag -l | sort -V | tail -1 | awk 'BEGIN { FS="." } { $$3++; } { printf "%d.%d.%d", $$1, $$2, $$3 }')
GIT_REV_ID=`(git describe --tags 2>|/dev/null) || (LC_ALL=C date +"%F-%X")`

.PHONY : all build clean test spec ci bin

all: compile

deps:
	@if [ ! -d lib  ]; then \
	  docker-compose run crystal shards update; \
	fi

compile: deps
	docker-compose run crystal make build

release: deps
	docker-compose run crystal make build RELEASE=--release STATIC=-static

clean:
	rm -rf bin tmp

build: clean $(BINS)

$(BINDIR)/%: $(SRCDIR)/%.cr
	@mkdir -p bin
	${CRYSTAL} build ${RELEASE} $^ -o $@ ${LINK_FLAGS}

umount:
	docker run --rm -t -v $$(pwd)/bin:/mnt alpine chown -R $$(id -u):$$(id -g) /mnt

test: check_version_mismatch compile spec

spec:
	docker-compose run spec

spec-clean:
	docker-compose stop
	docker-compose rm -f

.PHONY : check_version_mismatch
check_version_mismatch: shard.yml README.md
	diff -w -c <(grep version: README.md) <(grep ^version: shard.yml)

.PHONY : version
version:
	@if [ "$(VERSION)" = "" ]; then \
	  echo "ERROR: specify VERSION as bellow. (current: $(CURRENT_VERSION))";\
	  echo "  make version VERSION=$(GUESSED_VERSION)";\
	else \
	  sed -i -e 's/^version: .*/version: $(VERSION)/' shard.yml ;\
	  sed -i -e 's/^    version: [0-9]\+\.[0-9]\+\.[0-9]\+/    version: $(VERSION)/' README.md ;\
	  echo git commit -a -m "'$(COMMIT_MESSAGE)'" ;\
	  git commit -a -m 'version: $(VERSION)' ;\
	  git tag "v$(VERSION)" ;\
	fi

.PHONY : bump
bump:
	make version VERSION=$(GUESSED_VERSION) -s

data-gen: bin/kafka-packet
	$(DATA_GEN) 5 data/Produce/5/req.pcap > data/Produce/5/req.text
	$(DATA_GEN) 5 data/Produce/5/res.pcap > data/Produce/5/res.text
	$(DATA_GEN) 5 data/Metadata/5/req.pcap > data/Metadata/5/req.text
	$(DATA_GEN) 5 data/Metadata/5/res.pcap > data/Metadata/5/res.text
	$(DATA_GEN) 1 data/ApiVersions/1/req.pcap > data/ApiVersions/1/req.text
	$(DATA_GEN) 1 data/ApiVersions/1/res.pcap > data/ApiVersions/1/res.text
	$(DATA_GEN) 0 data/InitProducerId/0/req.pcap > data/InitProducerId/0/req.text
	$(DATA_GEN) 0 data/InitProducerId/0/res.pcap > data/InitProducerId/0/res.text


text:
from unittest import TestCase

from mongoengine import connect
from mongoengine.connection import get_db

class MongoTestCase(TestCase):
    """
    TestCase class that clear the collection between the tests
    """

    @property
    def db_name(self):
        from django.conf import settings
        return 'test_%s' % getattr(settings, 'MONGO_DATABASE_NAME', 'dummy')

    def __init__(self, methodName='runtest'):
        connect(self.db_name)
        self.db = get_db()
        super(MongoTestCase, self).__init__(methodName)

    def dropCollections(self):
        for collection in self.db.collection_names():
            if collection.startswith('system.'):
                continue
            self.db.drop_collection(collection)

    def tearDown(self):
        self.dropCollections()


text:
<?php
namespace Underscore\Traits;

use BadMethodCallException;
use Underscore\Dispatch;
use Underscore\Method;
use Underscore\Methods\ArraysMethods;
use Underscore\Methods\StringsMethods;
use Underscore\Parse;

/**
 * Base abstract class for repositories.
 */
abstract class Repository
{
    /**
     * The subject of the repository.
     *
     * @type mixed
     */
    protected $subject;

    /**
     * Custom functions.
     *
     * @type array
     */
    protected static $macros = [];

    /**
     * The method used to convert new subjects.
     *
     * @type string
     */
    protected $typecaster;

    ////////////////////////////////////////////////////////////////////
    /////////////////////////// PUBLIC METHODS /////////////////////////
    ////////////////////////////////////////////////////////////////////

    /**
     * Create a new instance of the repository.
     *
     * @param mixed $subject The repository subject
     */
    public function __construct($subject = null)
    {
        // Assign subject
        $this->subject = $subject ?: $this->getDefault();

        // Convert it if necessary
        $typecaster = $this->typecaster;
        if ($typecaster) {
            $this->$typecaster();
        }

        return $this;
    }

    /**
     * Transform subject to Strings on toString.
     *
     * @return string
     */
    public function __toString()
    {
        return Parse::toString($this->subject);
    }

    /**
     * Create a new Repository.
     */
    public static function create()
    {
        return new static();
    }

    /**
     * Create a new Repository from a subject.
     */
    public static function from($subject)
    {
        return new static($subject);
    }

    /**
     * Get a key from the subject.
     */
    public function __get($key)
    {
        return ArraysMethods::get($this->subject, $key);
    }

    /**
     * Set a value on the subject.
     */
    public function __set($key, $value)
    {
        $this->subject = ArraysMethods::set($this->subject, $key, $value);
    }

    /**
     * Check if the subject is empty.
     *
     * @return bool
     */
    public function isEmpty()
    {
        return empty($this->subject);
    }

    /**
     * Replace the Subject while maintaining chain.
     *
     * @param mixed $value
     */
    public function setSubject($value)
    {
        $this->subject = $value;

        return $this;
    }

    /**
     * Get the subject from the object.
     *
     * @return mixed
     */
    public function obtain()
    {
        return $this->subject;
    }

    /**
     * Extend the class with a custom function.
     *
     * @param string   $method  The macro's name
     * @param Callable $closure The macro
     */
    public static function extend($method, $closure)
    {
        static::$macros[get_called_class()][$method] = $closure;
    }

    ////////////////////////////////////////////////////////////////////
    //////////////////////// METHODS DISPATCHING ///////////////////////
    ////////////////////////////////////////////////////////////////////

    /**
     * Catch aliases and reroute them to the right methods.
     */
    public static function __callStatic($method, $parameters)
    {
        // Get base class and methods class
        $callingClass = static::computeClassToCall(get_called_class(), $method, $parameters);
        $methodsClass = Method::getMethodsFromType($callingClass);

        // Defer to Methods class
        if (method_exists($methodsClass, $method)) {
            return self::callMethod($methodsClass, $method, $parameters);
        }

        // Check for an alias
        if ($alias = Method::getAliasOf($method)) {
            return self::callMethod($methodsClass, $alias, $parameters);
        }

        // Check for parsers
        if (method_exists('Underscore\Parse', $method)) {
            return self::callMethod('Underscore\Parse', $method, $parameters);
        }

        // Defered methods
        if ($defered = Dispatch::toNative($callingClass, $method)) {
            return call_user_func_array($defered, $parameters);
        }

        // Look in the macros
        if ($macro = ArraysMethods::get(static::$macros, $callingClass.'.'.$method)) {
            return call_user_func_array($macro, $parameters);
        }

        throw new BadMethodCallException('The method '.$callingClass.'::'.$method.' does not exist');
    }

    /**
     * Allow the chained calling of methods.
     */
    public function __call($method, $arguments)
    {
        // Get correct class
        $class = Dispatch::toClass($this->subject);

        // Check for unchainable methods
        if (Method::isUnchainable($class, $method)) {
            throw new BadMethodCallException('The method '.$class.'::'.$method.' can\'t be chained');
        }

        // Prepend subject to arguments and call the method
        if (!Method::isSubjectless($method)) {
            array_unshift($arguments, $this->subject);
        }
        $result = $class::__callStatic($method, $arguments);

        // If the method is a breaker, return just the result
        if (Method::isBreaker($method)) {
            return $result;
        } else {
            $this->subject = $result;
        }

        return $this;
    }

    ////////////////////////////////////////////////////////////////////
    ///////////////////////////// HELPERS //////////////////////////////
    ////////////////////////////////////////////////////////////////////

    /**
     * Tries to find the right class to call.
     *
     * @param string $callingClass The original class
     * @param string $method       The method
     * @param array  $arguments    The arguments
     *
     * @return string The correct class
     */
    protected static function computeClassToCall($callingClass, $method, $arguments)
    {
        if (!StringsMethods::find($callingClass, 'Underscore\Types')) {
            if (isset($arguments[0])) {
                $callingClass = Dispatch::toClass($arguments[0]);
            } else {
                $callingClass = Method::findInClasses($callingClass, $method);
            }
        }

        return $callingClass;
    }

    /**
     * Simpler version of call_user_func_array (for performances).
     *
     * @param string $class      The class
     * @param string $method     The method
     * @param array  $parameters The arguments
     */
    protected static function callMethod($class, $method, $parameters)
    {
        switch (count($parameters)) {
            case 0:
                return $class::$method();
            case 1:
                return $class::$method($parameters[0]);
            case 2:
                return $class::$method($parameters[0], $parameters[1]);
            case 3:
                return $class::$method($parameters[0], $parameters[1], $parameters[2]);
            case 4:
                return $class::$method($parameters[0], $parameters[1], $parameters[2], $parameters[3]);
            case 5:
                return $class::$method($parameters[0], $parameters[1], $parameters[2], $parameters[3], $parameters[4]);
        }
    }

    /**
     * Get a default value for a new repository.
     *
     * @return mixed
     */
    protected function getDefault()
    {
        return '';
    }
}


text:
#ifndef SOCKETSTREAMOUTPUTCOLLECTOR_H_
#define SOCKETSTREAMOUTPUTCOLLECTOR_H_

#include "io/AbstractOutputCollector.h"

#include <Poco/Buffer.h>
#include <Poco/Logger.h>
#include <Poco/Net/SocketAddress.h>
#include <Poco/Net/StreamSocket.h>
#include <Poco/Net/SocketStream.h>

namespace Myriad {
/**
 * @addtogroup io
 * @{*/

/**
 * An AbstractOutputCollector subclass that writes the output into the local
 * file system.
 *
 * @author: Alexander Alexandrov <alexander.alexandrov@tu-berlin.de>
 */
template<typename RecordType>
class SocketStreamOutputCollector: public AbstractOutputCollector<RecordType>
{
public:

    /**
     * Constructor.
     *
     * Opens an output stream for the given \p outputPath in a localhost output
     * socket specified by the given \p outputPort.
     */
    SocketStreamOutputCollector(const Path& outputPath, const I16u outputPort, const String& collectorName) :
        AbstractOutputCollector<RecordType>(collectorName),
        _outputPath(outputPath),
        _outputSocket(Poco::Net::IPAddress::IPv4),
        _outputPort(outputPort),
        _outputBufferSize(4194304), // 4MB buffer
        _outputBuffer(_outputBufferSize),
    	_isOpen(false),
        _logger(Logger::get(collectorName))
    {
    }

    /**
     * Copy constructor.
     */
    SocketStreamOutputCollector(const SocketStreamOutputCollector& o) :
        AbstractOutputCollector<RecordType>(o),
        _outputPath(o._outputPath),
        _outputSocket(o._outputSocket),
        _outputPort(o._outputPort),
        _outputBufferSize(4194304), // 4MB buffer
        _outputBuffer(_outputBufferSize),
        _isOpen(false),
        _logger(Logger::get(o._logger.name()))
    {
        if (o._isOpen)
        {
	        open();
        }
    }

    /**
     * Destructor.
     *
     * Closes the internal FileOutputStream instance if opened.
     */
    virtual ~SocketStreamOutputCollector()
    {
        close();
    }

    /**
     * Opens the internal FileOutputStream instance.
     */
    void open()
    {
        if (!_isOpen)
        {
            _logger.debug(format("Opening socket for output path `%s` at port %hu", _outputPath.toString(), _outputPort));

            try
            {
                Poco::Net::StreamSocket socket(Poco::Net::IPAddress::IPv4);
                _outputSocket.connect(Poco::Net::SocketAddress("localhost", _outputPort));
            }
            catch(const Poco::Exception& e)
            {
                throw RuntimeException(format("Could not connect to socket at address localhost:%hu", _outputPort));
            }

            AbstractOutputCollector<RecordType>::writeHeader(_recordsBuffer);
	        _isOpen = true;

	        _recordsBuffer.str("");
			_recordsBuffer.clear();
        }
        else
        {
	        throw LogicException(format("Can't open already opened socket for output path `%s`", _outputPath.toString()));
        }
    }

    /**
     * Closes the internal FileOutputStream instance.
     */
    void close()
    {
        if (_isOpen)
        {
	        _logger.debug(format("Closing socket stream for output path `%s`", _outputPath.toString()));

	        AbstractOutputCollector<RecordType>::writeFooter(_recordsBuffer);
	        flush();
	        _outputSocket.close();
        }
    }

    /**
     * Flushes the internal FileOutputStream instance and resets the flush counter.
     */
    void flush()
    {
        if (_isOpen)
        {
            Poco::Net::SocketStream socketStream(_outputSocket);
            StreamCopier::copyStream(_recordsBuffer, socketStream, _outputBufferSize);
            socketStream.flush();
        }

        _recordsBuffer.str("");
        _recordsBuffer.clear();
    }

    /**
     * Output collection method.
     */
    void collect(const RecordType& record)
    {
    	std::ostream::pos_type p2, p1 = _recordsBuffer.tellp();
        if (p1 == -1)
        {
        	throw RuntimeException("Failed to read before-position from output stream");
        }

        SocketStreamOutputCollector<RecordType>::serialize(_recordsBuffer, record);

        p2 = _recordsBuffer.tellp();
        if (p2 == -1)
        {
        	throw RuntimeException("Failed to read after-position from output stream");
        }

        if (static_cast<size_t>(p2) >= _outputBufferSize)
        {
            writeToOutputSocket();
        }
    }

private:

    /**
     * Writes the contents of the \p _recordsBuffer to the \p _outputSocket.
     *
     * Internally, the operation uses the \p _outputBuffer to perform copy
     * operations of \p _outputBufferSize chars at a time.
     */
    void writeToOutputSocket()
    {
        if (_isOpen)
        {
            size_t N = static_cast<size_t>(_recordsBuffer.tellp()) / _outputBufferSize;

            for (size_t i = 0; i < N; i++)
            {
                _recordsBuffer.read(_outputBuffer.begin(), _outputBufferSize);

                Poco::Net::SocketStream socketStream(_outputSocket);
                socketStream.write(_outputBuffer.begin(), _recordsBuffer.gcount());
            }

            _recordsBuffer.read(_outputBuffer.begin(), _outputBufferSize);
            _recordsBuffer.str("");
            _recordsBuffer.clear();
            _recordsBuffer.write(_outputBuffer.begin(), _recordsBuffer.gcount());
        }
        else
        {
            _recordsBuffer.str("");
            _recordsBuffer.clear();
        }
    }

    /**
     * A stringstream buffer holding the serialized record objects.
     */
    std::stringstream _recordsBuffer;

    /**
     * The path of the underlying OutputStream.
     */
    const Path _outputPath;

    /**
     * The underlying output stream.
     */
    Poco::Net::StreamSocket _outputSocket;

    /**
     * The connection port for the stream socket.
     */
    const I16u _outputPort;

    /**
     * The size of buffer that is flushed to the output stream.
     */
    size_t _outputBufferSize;

    /**
     * A char buffer for transfer from the \p _recordsBuffer to the \p _outputSocket.
     */
    Poco::Buffer<char> _outputBuffer;

    /**
     * A boolean flag indicating that the underlying \p _outputSocket is open.
     */
    bool _isOpen;

    /**
     * Logger instance.
     */
    Logger& _logger;
};

/** @}*/// add to io group
} // namespace Myriad

#endif /* SOCKETSTREAMOUTPUTCOLLECTOR_H_ */


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Threax.AspNetCore.Halcyon.Ext;

namespace TestHalcyonApi.Customizers
{
    /// <summary>
    /// This doesn't do aything useful to the schema, but it does test that the extensions work
    /// </summary>
    public class PointlessSchemaCustomizer : ISchemaCustomizer
    {
        public Task Customize(SchemaCustomizerArgs args)
        {
            if (args.SchemaProperty.ExtensionData == null)
            {
                args.SchemaProperty.ExtensionData = new Dictionary<String, Object>();
            }
            args.SchemaProperty.ExtensionData.Add("x-pointless-addition", DateTime.Now.ToString());

            return Task.FromResult(0);
        }
    }
}


text:
import { Given } from '@cucumber/cucumber';

Given('a passing step', () => {
    // no-op
});


text:
package com.mpush.core.handler;

import com.google.common.base.Strings;
import com.mpush.common.router.RemoteRouter;
import com.mpush.common.user.UserManager;
import com.mpush.core.MPushServer;
import com.mpush.core.router.RouterCenter;
import com.mpush.tools.Jsons;
import com.mpush.tools.common.Profiler;
import com.mpush.tools.config.CC;
import com.mpush.tools.config.ConfigTools;
import com.typesafe.config.ConfigRenderOptions;
import io.netty.channel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.*;

@ChannelHandler.Sharable
public final class AdminHandler extends SimpleChannelInboundHandler<String> {

    private static final Logger LOGGER = LoggerFactory.getLogger(AdminHandler.class);

    private static final String EOL = "\r\n";

    private final LocalDateTime startTime = LocalDateTime.now();

    private final Map<String, OptionHandler> optionHandlers = new HashMap<>();

    private final OptionHandler unsupported_handler = (_1, _2) -> "unsupported option";

    private final MPushServer mPushServer;

    public AdminHandler(MPushServer mPushServer) {
        this.mPushServer = mPushServer;
    }

    public void init() {
        register("help", (ctx, args) ->
                "Option                               Description" + EOL +
                        "------                               -----------" + EOL +
                        "help                                 show help" + EOL +
                        "quit                                 exit console mode" + EOL +
                        "shutdown                             stop mpush server" + EOL +
                        "restart                              restart mpush server" + EOL +
                        "zk:<redis, cs ,gs>                   query zk node" + EOL +
                        "count:<conn, online>                 count conn num or online user count" + EOL +
                        "route:<uid>                          show user route info" + EOL +
                        "push:<uid>, <msg>                    push test msg to client" + EOL +
                        "conf:[key]                           show config info" + EOL +
                        "monitor:[mxBean]                     show system monitor" + EOL +
                        "profile:<1,0>                        enable/disable profile" + EOL
        );

        register("quit", (ctx, args) -> "have a good day!");

        register("shutdown", (ctx, args) -> {
            new Thread(() -> System.exit(0)).start();
            return "try close connect server...";
        });

        register("count", (ctx, args) -> {
            switch (args) {
                case "conn":
                    return mPushServer.getConnectionServer().getConnectionManager().getConnNum();
                case "online": {
                    return mPushServer.getRouterCenter().getUserEventConsumer().getUserManager().getOnlineUserNum();
                }

            }
            return "[" + args + "] unsupported, try help.";
        });

        register("route", (ctx, args) -> {
            if (Strings.isNullOrEmpty(args)) return "please input userId";
            Set<RemoteRouter> routers = mPushServer.getRouterCenter().getRemoteRouterManager().lookupAll(args);
            if (routers.isEmpty()) return "user [" + args + "] offline now.";
            return Jsons.toJson(routers);
        });

        register("conf", (ctx, args) -> {
            if (Strings.isNullOrEmpty(args)) {
                return CC.cfg.root().render(ConfigRenderOptions.concise().setFormatted(true));
            }
            if (CC.cfg.hasPath(args)) {
                return CC.cfg.getAnyRef(args).toString();
            }
            return "key [" + args + "] not find in config";
        });

        register("profile", (ctx, args) -> {
            if (args == null || "0".equals(args)) {
                Profiler.enable(false);
                return "Profiler disabled";
            } else {
                Profiler.enable(true);
                return "Profiler enabled";
            }
        });
    }

    private void register(String option, OptionHandler handler) {
        optionHandlers.put(option, handler);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String request) throws Exception {
        String option = "help";
        String arg = null;
        String[] args = null;
        if (request != null) {
            String[] cmd_args = request.split(" ");
            option = cmd_args[0].trim().toLowerCase();
            if (cmd_args.length == 2) {
                arg = cmd_args[1];
            } else if (cmd_args.length > 2) {
                args = Arrays.copyOfRange(cmd_args, 1, cmd_args.length);
            }
        }
        try {
            Object result = optionHandlers.getOrDefault(option, unsupported_handler).handle(ctx, arg);
            ChannelFuture future = ctx.writeAndFlush(result + EOL + EOL);
            if (option.equals("quit")) {
                future.addListener(ChannelFutureListener.CLOSE);
            }
        } catch (Throwable throwable) {
            ctx.writeAndFlush(throwable.getLocalizedMessage() + EOL + EOL);
            StringWriter writer = new StringWriter(1024);
            throwable.printStackTrace(new PrintWriter(writer));
            ctx.writeAndFlush(writer.toString());
        }
        LOGGER.info("receive admin command={}", request);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ctx.write("Welcome to MPush Console [" + ConfigTools.getLocalIp() + "]!" + EOL);
        ctx.write("since " + startTime + " has running " + startTime.until(LocalDateTime.now(), ChronoUnit.HOURS) + "(h)" + EOL + EOL);
        ctx.write("It is " + new Date() + " now." + EOL + EOL);
        ctx.flush();
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    public interface OptionHandler {
        Object handle(ChannelHandlerContext ctx, String args) throws Exception;
    }
}