text:
(function (context) {
  "use strict";

  var TheGraph = context.TheGraph;

  // Initialize namespace for configuration and factory functions.
  TheGraph.config.node = {
    snap: TheGraph.config.nodeSize,
    container: {},
    background: {
      className: "node-bg"
    },
    border: {
      className: "node-border drag",
      rx: TheGraph.config.nodeRadius,
      ry: TheGraph.config.nodeRadius
    },
    innerRect: {
      className: "node-rect drag",
      x: 0,
      y: 0,
      rx: TheGraph.config.nodeRadius,
      ry: TheGraph.config.nodeRadius
    },
    inports: {
      className: "inports"
    },
    outports: {
      className: "outports"
    },
    labelBackground: {
      className: "node-label-bg"
    },
    labelText: {
      className: "node-label"
    }
  };

  // These factories use generic factories from the core, but
  // each is called separately allowing developers to intercept
  // individual elements of the node creation.
  TheGraph.factories.node = {
    createNodeGroup: TheGraph.factories.createGroup,
    createNodeBackgroundRect: TheGraph.factories.createRect,
    createNodeBorderRect: TheGraph.factories.createRect,
    createNodeInnerRect: TheGraph.factories.createRect,
    createNodeIconText: TheGraph.factories.createText,
    createNodeIconSVG: TheGraph.factories.createImg,
    createNodeInportsGroup: TheGraph.factories.createGroup,
    createNodeOutportsGroup: TheGraph.factories.createGroup,
    createNodeLabelGroup: TheGraph.factories.createGroup,
    createNodeLabelRect: TheGraph.factories.createRect,
    createNodeLabelText: TheGraph.factories.createText,
    createNodeSublabelGroup: TheGraph.factories.createGroup,
    createNodeSublabelRect: TheGraph.factories.createRect,
    createNodeSublabelText: TheGraph.factories.createText,
    createNodePort: createNodePort
  };

  function createNodePort(options) {
    return TheGraph.Port(options);
  }

  // PolymerGestures monkeypatch
  PolymerGestures.dispatcher.gestures.forEach( function (gesture) {
    // hold
    if (gesture.HOLD_DELAY) {
      gesture.HOLD_DELAY = 500;
    }
    // track
    if (gesture.WIGGLE_THRESHOLD) {
      gesture.WIGGLE_THRESHOLD = 8;
    }
  });

  // Node view
  TheGraph.Node = React.createFactory( React.createClass({
    displayName: "TheGraphNode",
    mixins: [
      TheGraph.mixins.Tooltip
    ],
    contentClass: false,

    componentDidMount: function () {
      var domNode = this.getDOMNode();

      // Dragging
      domNode.addEventListener("trackstart", this.onTrackStart);

      // Tap to select
      if (this.props.onNodeSelection) {
        domNode.addEventListener("tap", this.onNodeSelection, true);
      }

      // Context menu
      if (this.props.showContext) {
        this.getDOMNode().addEventListener("contextmenu", this.showContext);
        this.getDOMNode().addEventListener("hold", this.showContext);
      }

      if (Tower) {
        Tower.dataReceived.add(this.onDataReceived);
      } else {
        console.log('TOWER NOT FOUND');
      }
    },

    componentWillUnmount: function () {
      Tower.dataReceived.remove(this.onDataReceived);
    },

    onDataReceived: function (data, edgeInfo) {
      if (edgeInfo.trgt.id === this.props.nodeID) {
        this.triggerActiveIndicator();
        this.setState({data: data});
      }
    },

    onNodeSelection: function (event) {
      // Don't tap app (unselect)
      event.stopPropagation();

      var toggle = (TheGraph.metaKeyPressed || event.pointerType==="touch");
      this.props.onNodeSelection(this.props.nodeID, this.props.node, toggle);
    },

    getInitialState: function () {
      return {
        indicatorActive: false,
        data: undefined
      };
    },

    onTrackStart: function (event) {
      // Don't drag graph
      event.stopPropagation();

      // Don't change selection
      event.preventTap();

      // Don't drag under menu
      if (this.props.app.menuShown) { return; }

      // Don't drag while pinching
      if (this.props.app.pinching) { return; }

      var domNode = this.getDOMNode();
      domNode.addEventListener("track", this.onTrack);
      domNode.addEventListener("trackend", this.onTrackEnd);

      // Moving a node should only be a single transaction
      if (this.props.export) {
        this.props.graph.startTransaction('moveexport');
      } else {
        this.props.graph.startTransaction('movenode');
      }
    },
    onTrack: function (event) {
      // Don't fire on graph
      event.stopPropagation();

      var scale = this.props.app.state.scale;
      var deltaX = Math.round( event.ddx / scale );
      var deltaY = Math.round( event.ddy / scale );

      // Fires a change event on noflo graph, which triggers redraw
      if (this.props.export) {
        var newPos = {
          x: this.props.export.metadata.x + deltaX,
          y: this.props.export.metadata.y + deltaY
        };
        if (this.props.isIn) {
          this.props.graph.setInportMetadata(this.props.exportKey, newPos);
        } else {
          this.props.graph.setOutportMetadata(this.props.exportKey, newPos);
        }
      } else {
        this.props.graph.setNodeMetadata(this.props.nodeID, {
          x: this.props.node.metadata.x + deltaX,
          y: this.props.node.metadata.y + deltaY
        });
      }
    },
    onTrackEnd: function (event) {
      // Don't fire on graph
      event.stopPropagation();

      var domNode = this.getDOMNode();
      domNode.removeEventListener("track", this.onTrack);
      domNode.removeEventListener("trackend", this.onTrackEnd);

      // Snap to grid
      var snapToGrid = true;
      var snap = TheGraph.config.node.snap / 2;
      if (snapToGrid) {
        var x, y;
        if (this.props.export) {
          var newPos = {
            x: Math.round(this.props.export.metadata.x/snap) * snap,
            y: Math.round(this.props.export.metadata.y/snap) * snap
          };
          if (this.props.isIn) {
            this.props.graph.setInportMetadata(this.props.exportKey, newPos);
          } else {
            this.props.graph.setOutportMetadata(this.props.exportKey, newPos);
          }
        } else {
          this.props.graph.setNodeMetadata(this.props.nodeID, {
            x: Math.round(this.props.node.metadata.x/snap) * snap,
            y: Math.round(this.props.node.metadata.y/snap) * snap
          });
        }
      }

      // Moving a node should only be a single transaction
      if (this.props.export) {
        this.props.graph.endTransaction('moveexport');
      } else {
        this.props.graph.endTransaction('movenode');
      }
    },
    showContext: function (event) {
      // Don't show native context menu
      event.preventDefault();

      // Don't tap graph on hold event
      event.stopPropagation();
      if (event.preventTap) { event.preventTap(); }

      // Get mouse position
      var x = event.x || event.clientX || 0;
      var y = event.y || event.clientY || 0;

      // App.showContext
      this.props.showContext({
        element: this,
        type: (this.props.export ? (this.props.isIn ? "graphInport" : "graphOutport") : "node"),
        x: x,
        y: y,
        graph: this.props.graph,
        itemKey: (this.props.export ? this.props.exportKey : this.props.nodeID),
        item: (this.props.export ? this.props.export : this.props.node)
      });
    },
    getContext: function (menu, options, hide) {
      // If this node is an export
      if (this.props.export) {
        return TheGraph.Menu({
          menu: menu,
          options: options,
          triggerHideContext: hide,
          label: this.props.exportKey
        });
      }

      // Absolute position of node
      var x = options.x;
      var y = options.y;
      var scale = this.props.app.state.scale;
      var appX = this.props.app.state.x;
      var appY = this.props.app.state.y;
      var nodeX = (this.props.x + this.props.width / 2) * scale + appX;
      var nodeY = (this.props.y + this.props.height / 2) * scale + appY;
      var deltaX = nodeX - x;
      var deltaY = nodeY - y;
      var ports = this.props.ports;
      var processKey = this.props.nodeID;
      var highlightPort = this.props.highlightPort;

      // If there is a preview edge started, only show connectable ports
      if (this.props.graphView.state.edgePreview) {
        if (this.props.graphView.state.edgePreview.isIn) {
          // Show outputs
          return TheGraph.NodeMenuPorts({
            ports: ports.outports,
            triggerHideContext: hide,
            isIn: false,
            scale: scale,
            processKey: processKey,
            deltaX: deltaX,
            deltaY: deltaY,
            translateX: x,
            translateY: y,
            nodeWidth: this.props.width,
            nodeHeight: this.props.height,
            highlightPort: highlightPort
          });
        } else {
          // Show inputs
          return TheGraph.NodeMenuPorts({
            ports: ports.inports,
            triggerHideContext: hide,
            isIn: true,
            scale: scale,
            processKey: processKey,
            deltaX: deltaX,
            deltaY: deltaY,
            translateX: x,
            translateY: y,
            nodeWidth: this.props.width,
            nodeHeight: this.props.height,
            highlightPort: highlightPort
          });
        }
      }

      // Default, show whole node menu
      return TheGraph.NodeMenu({
        menu: menu,
        options: options,
        triggerHideContext: hide,
        label: this.props.label,
        graph: this.props.graph,
        graphView: this.props.graphView,
        node: this,
        icon: this.props.icon,
        ports: ports,
        process: this.props.node,
        processKey: processKey,
        x: x,
        y: y,
        nodeWidth: this.props.width,
        nodeHeight: this.props.height,
        deltaX: deltaX,
        deltaY: deltaY,
        highlightPort: highlightPort
      });
    },
    getTooltipTrigger: function () {
      return this.getDOMNode();
    },
    shouldShowTooltip: function () {
      return (this.props.app.state.scale < TheGraph.zbpNormal);
    },
    shouldComponentUpdate: function (nextProps, nextState) {
      return (
        nextProps.x !== this.props.x ||
        nextProps.y !== this.props.y ||
        nextProps.icon !== this.props.icon ||
        nextProps.label !== this.props.label ||
        nextProps.sublabel !== this.props.sublabel ||
        nextProps.ports !== this.props.ports ||
        nextProps.selected !== this.props.selected ||
        nextProps.error !== this.props.error ||
        nextProps.highlightPort !== this.props.highlightPort ||
        nextProps.ports.dirty === true ||
        nextState.indicatorActive !== this.state.indicatorActive ||
        nextState.data !== this.state.data
      );
    },

    triggerActiveIndicator: function () {
      clearTimeout(this.ledTimeout);
      this.ledTimeout = setTimeout(function () {
        this.setState({indicatorActive: false});
      }.bind(this), 300);

      if (!this.state.indicatorActive) {
        this.setState({indicatorActive: true});
      }
    },

    render: function() {
      if (this.props.ports.dirty) {
        // This tag is set when an edge or iip changes port colors
        this.props.ports.dirty = false;
      }

      var label = this.props.nodeID;

      if (this.props.data && this.props.data.IN) {
        label = this.props.data.IN;
      }

      var sublabel = this.props.sublabel;
      if (!sublabel || sublabel === label) {
        sublabel = "";
      }
      var x = this.props.x;
      var y = this.props.y;
      var width = this.props.width;
      var height = this.props.height;

      // Ports
      var keys, count;
      var processKey = this.props.nodeID;
      var app = this.props.app;
      var graph = this.props.graph;
      var node = this.props.node;
      var isExport = (this.props.export !== undefined);
      var showContext = this.props.showContext;
      var highlightPort = this.props.highlightPort;

      // Inports
      var inports = this.props.ports.inports;
      keys = Object.keys(inports);
      count = keys.length;
      // Make views
      var inportViews = keys.map(function(key){
        var info = inports[key];
        var props = {
          app: app,
          graph: graph,
          node: node,
          key: processKey + ".in." + info.label,
          label: info.label,
          processKey: processKey,
          isIn: true,
          isExport: isExport,
          nodeX: x,
          nodeY: y,
          nodeWidth: width,
          nodeHeight: height,
          x: info.x,
          y: info.y,
          port: {process:processKey, port:info.label, type:info.type},
          highlightPort: highlightPort,
          route: info.route,
          showContext: showContext
        };
        return TheGraph.factories.node.createNodePort(props);
      });

      // Outports
      var outports = this.props.ports.outports;
      keys = Object.keys(outports);
      count = keys.length;
      var outportViews = keys.map(function(key){
        var info = outports[key];
        var props = {
          app: app,
          graph: graph,
          node: node,
          key: processKey + ".out." + info.label,
          label: info.label,
          processKey: processKey,
          isIn: false,
          isExport: isExport,
          nodeX: x,
          nodeY: y,
          nodeWidth: width,
          nodeHeight: height,
          x: info.x,
          y: info.y,
          port: {process:processKey, port:info.label, type:info.type},
          highlightPort: highlightPort,
          route: info.route,
          showContext: showContext
        };
        return TheGraph.factories.node.createNodePort(props);
      });

      var backgroundRectOptions = TheGraph.merge(TheGraph.config.node.background, { width: this.props.width, height: this.props.height });
      var backgroundRect = TheGraph.factories.node.createNodeBackgroundRect.call(this, backgroundRectOptions);

      var borderRectOptions = TheGraph.merge(TheGraph.config.node.border, { width: this.props.width, height: this.props.height });
      var borderRect = TheGraph.factories.node.createNodeBorderRect.call(this, borderRectOptions);

      var innerRectOptions = TheGraph.merge(TheGraph.config.node.innerRect, { width: this.props.width, height: this.props.height });
      var innerRect = TheGraph.factories.node.createNodeInnerRect.call(this, innerRectOptions);

      var inportsOptions = TheGraph.merge(TheGraph.config.node.inports, { children: inportViews });
      var inportsGroup = TheGraph.factories.node.createNodeInportsGroup.call(this, inportsOptions);

      var outportsOptions = TheGraph.merge(TheGraph.config.node.outports, { children: outportViews });
      var outportsGroup = TheGraph.factories.node.createNodeOutportsGroup.call(this, outportsOptions);

      var dataIndicatorOuter = TheGraph.factories.createCircle({cx: 15, cy: this.props.height - 15, r: 4, className: 'indicator-outer'});

      var dataIndciatorInnerClassName = 'indicator-inner';
      if (this.state.indicatorActive) {
        dataIndciatorInnerClassName += ' active';
      }
      var dataIndicatorInner = TheGraph.factories.createCircle({cx: 15, cy: this.props.height - 15, r: 2, className: dataIndciatorInnerClassName});

      var labelTextOptions = TheGraph.merge(TheGraph.config.node.labelText, { x: 28, y: this.props.height - 14, children: label });
      var labelText = TheGraph.factories.node.createNodeLabelText.call(this, labelTextOptions);

      var labelGroupOptions = TheGraph.merge(TheGraph.config.node.labelBackground);
      var labelGroup = TheGraph.factories.node.createNodeLabelGroup.call(this, labelGroupOptions , [labelText]);

      var content;
      if (this.props.children) {
        content = React.createElement(this.props.children.class, {nodeID: this.props.nodeID});
      }

      var contentContainer = TheGraph.factories.createSvg.call(this, {
        className: 'content',
        width: this.props.width,
        height: this.props.height - 32
      } , [content]);

      var header = TheGraph.NodeHeader({
        text: label,
        active: this.state.indicatorActive,
        y: this.props.height - 32,
        width: this.props.width
      });

      var nodeContents = [
        backgroundRect,
        borderRect,
        innerRect,
        inportsGroup,
        outportsGroup,
       /* dataIndicatorOuter,
        dataIndicatorInner,
        labelGroup,*/
        header,
        contentContainer
      ];

      var nodeOptions = {
        className: "node drag"+
        (this.props.selected ? " selected" : "")+
        (this.props.error ? " error" : ""),
        name: this.props.nodeID,
        key: this.props.nodeID,
        title: label,
        transform: "translate("+x+","+y+")"
      };
      nodeOptions = TheGraph.merge(TheGraph.config.node.container, nodeOptions);

      return TheGraph.factories.node.createNodeGroup.call(this, nodeOptions, nodeContents);
    }
  }));

  function buildLabelRectOptions(height, x, y, len, className) {

    var width = len * height * 2/3;
    var radius = height / 2;
    x -= width / 2;
    y -= height / 2;

    var result = {
      className: className,
      height: height * 1.1,
      width: width,
      rx: radius,
      ry: radius,
      x: x,
      y: y
    };

    return result;
  }

})(this);


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using SuperMap.Web.Core;
using SuperMap.Web.Utilities;
using System.Collections.ObjectModel;
using System.Windows;

namespace SuperMap.Web.Clustering
{
    /// ${mapping_FeaturesClusterer_Title}
    public abstract class FeaturesClusterer : Clusterer
    {
        private BackgroundWorker clusterThread;
        private ObservableCollection<GeoRegion> geosClone;
        FeatureCollection featuresClone;
        ///
        ///     ${pubilc_Constructors_Initializes} <see cref="FeaturesClusterer">FeaturesClusterer</see> ${pubilc_Constructors_instance}
        ///
        protected FeaturesClusterer()
        {
            this.Radius = MagicNumber.FEATURESCLUSTERER_DEFAULT_RADIUS;
            newregionCol = new ObservableCollection<GeoRegion>();
        }
        /// ${mapping_FeaturesClusterer_method_OnCreateFeature_D}
        /// <param name="cluster">${mapping_FeaturesClusterer_method_OnCreateFeature_param_cluster}</param>
        /// <param name="center">${mapping_FeaturesClusterer_method_OnCreateFeature_param_center}</param>
        /// <param name="maxClusterCount">${mapping_FeaturesClusterer_method_OnCreateFeature_param_maxClusterCount}</param>
        protected abstract Feature OnCreateFeature(FeatureCollection cluster, GeoPoint center, int maxClusterCount);

        /// ${mapping_Clusterer_method_ClusterFeaturesAsync_D}
        /// <param name="features">${mapping_Clusterer_method_ClusterFeaturesAsync_param_features}</param>
        /// <param name="resolution">${mapping_Clusterer_method_ClusterFeaturesAsync_param_resolution}</param>
        public override void ClusterFeaturesAsync(IEnumerable<Feature> features, double resolution)
        {
            if (features == null)
            {
                base.OnClusteringCompleted(new FeatureCollection());
            }
            else
            {
                if (this.clusterThread != null)
                {
                    this.clusterThread.RunWorkerCompleted -= new RunWorkerCompletedEventHandler(clusterThread_RunWorkerCompleted);
                    if (this.clusterThread.IsBusy)
                    {
                        this.clusterThread.CancelAsync();
                    }
                    this.clusterThread = null;
                }
                this.clusterThread = new BackgroundWorker() { WorkerSupportsCancellation = true };
                this.clusterThread.RunWorkerCompleted += new RunWorkerCompletedEventHandler(clusterThread_RunWorkerCompleted);

                featuresClone = new FeatureCollection();
                foreach (Feature item in features)
                {
                    featuresClone.Add(item);
                }

                geosClone = new ObservableCollection<GeoRegion>();
                if (this.RegionCollection != null)
                {
                    foreach (var geo in this.RegionCollection)
                    {
                        geosClone.Add(geo);
                    }
                }

                this.clusterThread.DoWork += (s, e) =>
                {
                    e.Result = ClusterGeoPoints(featuresClone, this.Radius, resolution, this.clusterThread, geosClone);
                };
                this.clusterThread.RunWorkerAsync(new object[] { featuresClone, resolution, geosClone, this.Dispatcher });
            }
        }

        private void clusterThread_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if ((!e.Cancelled) && (e.Result != null))
            {
                Dictionary<int, Cluster> result = e.Result as Dictionary<int, Cluster>;
                if (result != null)
                {
                    FeatureCollection clusters = new FeatureCollection();
                    int num = 0;
                    foreach (int num2 in result.Keys)
                    {
                        if (result.ContainsKey(num2))
                            num = Math.Max(result[num2].Count, num);
                    }
                    foreach (int num3 in result.Keys)
                    {
                        if (result.ContainsKey(num3) && result[num3].Features.Count == 1)
                        {
                            clusters.Add(result[num3].Features[0]);
                        }
                        else if (result.ContainsKey(num3))
                        {
                            Feature item = this.OnCreateFeature(result[num3].Features, new GeoPoint(result[num3].X, result[num3].Y), num);
                            item.DisableToolTip = true;
                            item.SetValue(Clusterer.ClusterProperty, result[num3].Features);
                            clusters.Add(item);
                        }
                    }
                    base.OnClusteringCompleted(clusters);
                }
            }
        }

        /// ${mapping_Clusterer_method_CancelAsync_D}
        public override void CancelAsync()
        {
            if ((this.clusterThread != null) && this.clusterThread.IsBusy)
            {
                this.clusterThread.RunWorkerCompleted -= new RunWorkerCompletedEventHandler(this.clusterThread_RunWorkerCompleted);
                this.clusterThread.CancelAsync();
            }
            this.clusterThread = null;
        }

        private static Dictionary<int, Cluster> ClusterGeoPoints(IEnumerable<Feature> features, int radius, double resolution, BackgroundWorker worker, ObservableCollection<GeoRegion> geos)
        {
            Dictionary<int, Cluster> dictionary;

            if (geos.Count > 0)
            {
                dictionary = AssignGeoPointsToClusters(features, geos);
            }
            else
            {
                bool flag = false;
                GeoPoint bottomLeft = GetBottomLeft(features);
                double diameter = (radius * 2) * resolution;
                dictionary = AssignGeoPointsToClusters(features, bottomLeft, diameter);

                do
                {
                    if (worker.CancellationPending)
                    {
                        return null;
                    }
                    dictionary = MergeOverlappingClusters(diameter, dictionary, bottomLeft, out flag, worker);
                } while (flag);
            }

            if (worker.CancellationPending)
            {
                return null;
            }
            return dictionary;
        }

        private static GeoPoint GetBottomLeft(IEnumerable<Feature> features)
        {
            GeoPoint point = new GeoPoint(double.MaxValue, double.MaxValue);
            foreach (Feature f in features)
            {
                if ((f != null) && (f.Geometry != null))
                {
                    GeoPoint geometry = f.Geometry as GeoPoint;
                    if (geometry == null)
                    {
                        geometry = new GeoPoint(f.Geometry.Bounds.Center.X, f.Geometry.Bounds.Center.Y); ;
                    }
                    if (!double.IsNaN(geometry.X) && !double.IsNaN(geometry.Y))
                    {
                        point.X = Math.Min(point.X, geometry.X);
                        point.Y = Math.Min(point.Y, geometry.Y);
                    }
                }
            }
            return point;
        }

        private static Dictionary<int, Cluster> AssignGeoPointsToClusters(IEnumerable<Feature> features, ObservableCollection<GeoRegion> geos)
        {
            Dictionary<int, Cluster> dictionary = new Dictionary<int, Cluster>();
            GeoPoint gp = null;
            foreach (Feature feature in features)
            {
                if (feature.Geometry == null)
                {
                    continue;
                }
                gp = feature.Geometry as GeoPoint;

                if (gp == null)
                {
                    Rectangle2D bounds = feature.Geometry.Bounds;
                    if (bounds.IsEmpty)
                    {
                        continue;
                    }
                    gp = new GeoPoint(bounds.Center.X, bounds.Center.Y);
                }

                bool isContained = false;
                double x = gp.X;
                double y = gp.Y;

                foreach (GeoRegion clusterRegion in geos)
                {
                    if (clusterRegion.Bounds.Contains(x, y) && clusterRegion.Contains(x, y))
                    {
                        int key = -geos.IndexOf(clusterRegion);
                        if (dictionary.ContainsKey(key))
                        {
                            Cluster cluster = dictionary[key];
                            cluster.X += x;
                            cluster.Y += y;
                            cluster.Features.Add(feature);
                        }//有就合并
                        else
                        {
                            dictionary[key] = new Cluster(x, y);
                            dictionary[key].Features.Add(feature);
                        }//没有就new一个
                        isContained = true;
                        break;
                    }
                }
                int key1 = feature.GetHashCode();
                if (!isContained)
                {
                    if (!dictionary.ContainsKey(key1))
                    {
                        dictionary[key1] = new Cluster(gp.X, gp.Y);
                        dictionary[key1].Features.Add(feature);
                    }
                }
            }

            Cluster cltValue;
            int featuresCount = 0;
            foreach (var clt in dictionary)
            {
                cltValue = clt.Value;
                featuresCount = cltValue.Features.Count;
                clt.Value.X = cltValue.X / featuresCount;
                clt.Value.Y = cltValue.Y / featuresCount;
            }

            return dictionary;
        }

        //遍历每一个点,把其归类,得到最终的聚类点Cluster,其所在格网index的X/Y组成Key
        private static Dictionary<int, Cluster> AssignGeoPointsToClusters(IEnumerable<Feature> features, GeoPoint bottomLeft, double diameter)
        {
            Dictionary<int, Cluster> dictionary = new Dictionary<int, Cluster>();
            GeoPoint gp = null;
            foreach (Feature feature in features)
            {
                if (feature.Geometry == null)
                {
                    continue;
                }
                if (feature.Geometry is GeoPoint)
                {
                    gp = feature.Geometry as GeoPoint;
                }
                else
                {
                    Rectangle2D bounds = feature.Geometry.Bounds;
                    if (bounds.IsEmpty)
                    {
                        continue;
                    }
                    gp = new GeoPoint(bounds.Center.X, bounds.Center.Y);
                }

                double x = gp.X;
                double y = gp.Y;
                int cx = (int)Math.Round((x - bottomLeft.X) / diameter);
                int cy = (int)Math.Round((y - bottomLeft.Y) / diameter);
                int key = (cx << 16) | cy;//int是32位的  左16位是x,右16位是y
                if (dictionary.ContainsKey(key))
                {
                    Cluster cluster = dictionary[key];
                    cluster.X = (cluster.X + x) / 2.0;
                    cluster.Y = (cluster.Y + y) / 2.0;
                    cluster.Features.Add(feature);
                }//有就合并
                else
                {
                    dictionary[key] = new Cluster(x, y, cx, cy);
                    dictionary[key].Features.Add(feature);
                }//没有就new一个
            }
            return dictionary;
        }

        private static Dictionary<int, Cluster> MergeOverlappingClusters(double diameter, Dictionary<int, Cluster> orig, GeoPoint lowerLeft, out bool overlapExists, BackgroundWorker worker)
        {
            overlapExists = false;
            Dictionary<int, Cluster> dictionary = new Dictionary<int, Cluster>();
            foreach (int key in orig.Keys)
            {
                Cluster cluster = orig[key];
                if (cluster.Count != 0)
                {
                    overlapExists = SearchAndMerge(cluster, -1, -1, diameter, orig, overlapExists);
                    overlapExists = SearchAndMerge(cluster, -1, 0, diameter, orig, overlapExists);
                    overlapExists = SearchAndMerge(cluster, -1, 1, diameter, orig, overlapExists);

                    overlapExists = SearchAndMerge(cluster, 0, -1, diameter, orig, overlapExists);
                    overlapExists = SearchAndMerge(cluster, 0, 1, diameter, orig, overlapExists);

                    overlapExists = SearchAndMerge(cluster, 1, -1, diameter, orig, overlapExists);
                    overlapExists = SearchAndMerge(cluster, 1, 0, diameter, orig, overlapExists);
                    overlapExists = SearchAndMerge(cluster, 1, 1, diameter, orig, overlapExists);

                    int x = (int)Math.Round((double)((cluster.X - lowerLeft.X) / diameter));
                    int y = (int)Math.Round((double)((cluster.Y - lowerLeft.Y) / diameter));
                    cluster.Cx = x;
                    cluster.Cy = y;
                    int num4 = (x << 16) | y;
                    dictionary[num4] = cluster;
                    if (worker.CancellationPending)
                    {
                        return null;
                    }
                }
            }
            return dictionary;
        }

        private static bool SearchAndMerge(Cluster cluster, int ox, int oy, double diameter, Dictionary<int, Cluster> orig, bool overlapExists)
        {
            int x = cluster.Cx + ox;
            int y = cluster.Cy + oy;
            int key = (x << 16) | y;
            if (orig.ContainsKey(key) && (orig[key].Count > 0))
            {
                Cluster neighbour = orig[key];
                double distanceX = neighbour.X - cluster.X;
                double distanceY = neighbour.Y - cluster.Y;
                if ((Math.Sqrt((distanceX * distanceX) + (distanceY * distanceY)) < diameter) && (neighbour != cluster))
                {
                    overlapExists = true;
                    Merge(cluster, neighbour);
                }
            }
            return overlapExists;
        }

        private static void Merge(Cluster source, Cluster neighbour)
        {
            double num = source.Count + neighbour.Count;
            source.X = ((source.Count * source.X) + (neighbour.Count * neighbour.X)) / num;
            source.Y = ((source.Count * source.Y) + (neighbour.Count * neighbour.Y)) / num;
            foreach (Feature feature in neighbour.Features)
            {
                source.Features.Add(feature);
            }
            neighbour.Features.Clear();
        }

        /// ${mapping_FeaturesClusterer_attribute_radius}
        public int Radius { get; set; }

        private ObservableCollection<GeoRegion> newregionCol;
        private ObservableCollection<GeoRegion> oldregionCol;
        /// ${mapping_FeaturesClusterer_attribute_RegionCollection}
        public ObservableCollection<GeoRegion> RegionCollection
        {
            get { return newregionCol; }
            set
            {
                if (oldregionCol != value && oldregionCol != null)
                {
                    oldregionCol.CollectionChanged -= (s, e) => { base.OnPropertyChanged("RegionCollection"); };
                    oldregionCol = newregionCol;
                }
                newregionCol = value;
                if (newregionCol != null)
                {
                    newregionCol.CollectionChanged += (s, e) =>
                    {
                        base.OnPropertyChanged("RegionCollection");
                    };
                }
                base.OnPropertyChanged("RegionCollection");
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------

using Microsoft.Azure.Commands.Automation.Common;
using Microsoft.Azure.Commands.Automation.Properties;
using System;

namespace Microsoft.Azure.Commands.Automation.Model
{
    public class CredentialInfo
    {
         /// <summary>
        /// Initializes a new instance of the <see cref="CredentialInfo"/> class.
        /// </summary>
        /// <param name="Credential">
        /// The Credential.
        /// </param>
        public CredentialInfo(string accountAcccountName, WindowsAzure.Management.Automation.Models.Credential credential)
        {
            Requires.Argument("credential", credential).NotNull();
            this.AutomationAccountName = accountAcccountName;
            this.Name = credential.Name;

            if (credential.Properties == null) return;

            this.Description = credential.Properties.Description;
            this.CreationTime = credential.Properties.CreationTime.ToLocalTime();
            this.LastModifiedTime = credential.Properties.LastModifiedTime.ToLocalTime();
            this.UserName = credential.Properties.UserName;
        }

         /// <summary>
        /// Initializes a new instance of the <see cref="CredentialInfo"/> class.
        /// </summary>
        public CredentialInfo()
        {
        }

        /// <summary>
        /// Gets or sets the automaiton account name.
        /// </summary>
        public string AutomationAccountName { get; set; }
        public string Name { get; set; }
        public string UserName { get; set; }

        public string Description { get; set; }

        public DateTimeOffset CreationTime { get; set; }

        public DateTimeOffset LastModifiedTime { get; set; }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
    android:src="@drawable/pattern8_pattern_58c"
    android:tileMode="repeat" /><!-- From: file:/C:/Users/Nimish/Desktop/Final_Project/My_Notes/app/src/main/res/drawable/pad_bg_repeat.xml -->


text:
package com.mmnaseri.cs.ctci.ch02;

/**
 * @author Mohammad Milad Naseri (mmnaseri@programmer.net)
 * @since 1.0 (11/25/16, 2:11 PM)
 */
public class LinkedNodeBuilder {

    @SafeVarargs
    public static <E> DefaultSinglyLinkedNode<E> buildSinglyLinkedList(E... items) {
        if (items.length == 0) {
            return null;
        }
        final DefaultSinglyLinkedNode<E> head = new DefaultSinglyLinkedNode<>();
        head.setData(items[0]);
        DefaultSinglyLinkedNode<E> current = head;
        for (int i = 1; i < items.length; i++) {
            final DefaultSinglyLinkedNode<E> node = new DefaultSinglyLinkedNode<>();
            node.setData(items[i]);
            current.setNext(node);
            current = node;
        }
        return head;
    }

}


text:
import unittest
import atmospy
import pandas as pd
import os
import statsmodels.api as sm

def linear_eval(X1, X2):
    '''Perform evaluation (slope, r2) on a linear model
    '''
    df = pd.DataFrame.from_dict({'X1': X1, 'X2': X2}).dropna(how = 'any')

    model   = sm.OLS(df.X2, df.X1)
    results = model.fit()

    return (results.params[0], results.rsquared)

class SetupTestCase(unittest.TestCase):
    def setUp(self):

        self.number     = atmospy.io.SMPS()
        self.log_number = atmospy.io.SMPS()
        self.diameter   = atmospy.io.SMPS()
        self.surface    = atmospy.io.SMPS()
        self.volume     = atmospy.io.SMPS()

        self.number.load(os.path.join(os.getcwd(), "tests/data/SMPS_Number.txt"))
        self.log_number.load(os.path.join(os.getcwd(), "tests/data/SMPS_Log_Number.txt"))
        self.diameter.load(os.path.join(os.getcwd(), "tests/data/SMPS_Log_Diameter.txt"))
        self.surface.load(os.path.join(os.getcwd(), "tests/data/SMPS_Log_Surface.txt"))
        self.volume.load(os.path.join(os.getcwd(), "tests/data/SMPS_Log_Volume.txt"))

    def tearDown(self):
        pass

    def test_generic_smps(self):
        threshold = 0.99
        lbounds = 0.99
        ubounds = 1.01

        # Create the distribution and run the stats
        d = atmospy.aerosols.ParticleDistribution(histogram = self.number.histogram, bins = self.number.bins)

        d.compute()
        d.statistics()

        # Now that we've performed the calculations, make sure they're correct!
        # Number-weighted first...
        res_num1 = linear_eval(self.number.data['Total Concentration'], d.stats['Number', :, 'N Total'])
        res_num2 = linear_eval(self.number.data['Mean'], d.stats['Number', :, 'Mean'])
        res_num3 = linear_eval(self.number.data['Geo. Mean'], d.stats['Number', :, 'GM'])
        res_num4 = linear_eval(self.number.data['Geo Std Dev'], d.stats['Number', :, 'GSD'])

        self.assertTrue(res_num1[0] >= lbounds and res_num1[0] <= ubounds and res_num1[1] >= threshold)
        self.assertTrue(res_num2[0] >= lbounds and res_num2[0] <= ubounds and res_num2[1] >= threshold)
        self.assertTrue(res_num3[0] >= lbounds and res_num3[0] <= ubounds and res_num3[1] >= threshold)
        self.assertTrue(res_num4[0] >= lbounds and res_num4[0] <= ubounds and res_num4[1] >= threshold)

        # Diameter-weighted first...
        res_diam1 = linear_eval(self.diameter.data['Mean'], d.stats['Diameter', :, 'Mean'])
        res_diam2 = linear_eval(self.diameter.data['Geo. Mean'], d.stats['Diameter', :, 'GM'])
        res_diam3 = linear_eval(self.diameter.data['Geo Std Dev'], d.stats['Diameter', :, 'GSD'])

        self.assertTrue(res_diam1[0] >= lbounds and res_diam1[0] <= ubounds and res_diam1[1] >= threshold)
        self.assertTrue(res_diam2[0] >= lbounds and res_diam2[0] <= ubounds and res_diam2[1] >= threshold)
        self.assertTrue(res_diam3[0] >= lbounds and res_diam3[0] <= ubounds and res_diam3[1] >= threshold)

        # Surface Area-weighted first...
        res_sa1 = linear_eval(self.surface.data['Mean'], d.stats['Surface Area', :, 'Mean'])
        res_sa2 = linear_eval(self.surface.data['Geo. Mean'], d.stats['Surface Area', :, 'GM'])
        res_sa3 = linear_eval(self.surface.data['Geo Std Dev'], d.stats['Surface Area', :, 'GSD'])

        self.assertTrue(res_sa1[0] >= lbounds and res_sa1[0] <= ubounds and res_sa1[1] >= threshold)
        self.assertTrue(res_sa2[0] >= lbounds and res_sa2[0] <= ubounds and res_sa2[1] >= threshold)
        self.assertTrue(res_sa3[0] >= lbounds and res_sa3[0] <= ubounds and res_sa3[1] >= threshold)

        # Volume-weighted first...
        res_vol1 = linear_eval(self.volume.data['Mean'], d.stats['Volume', :, 'Mean'])
        res_vol2 = linear_eval(self.volume.data['Geo. Mean'], d.stats['Volume', :, 'GM'])
        res_vol3 = linear_eval(self.volume.data['Geo Std Dev'], d.stats['Volume', :, 'GSD'])

        self.assertTrue(res_vol1[0] >= lbounds and res_vol1[0] <= ubounds and res_vol1[1] >= threshold)
        self.assertTrue(res_vol2[0] >= lbounds and res_vol2[0] <= ubounds and res_vol2[1] >= threshold)
        self.assertTrue(res_vol3[0] >= lbounds and res_vol3[0] <= ubounds and res_vol3[1] >= threshold)

    def test_log_number_smps(self):
        threshold   = 0.99
        ubounds     = 1.01
        lbounds     = 0.99

        d = atmospy.aerosols.ParticleDistribution( histogram = self.log_number.histogram, bins = self.log_number.bins )

        d.compute()
        d.statistics()

        # Now that we've performed the calculations, make sure they're correct!
        # Number-weighted first...
        res_num1 = linear_eval(self.number.data['Total Concentration'], self.log_number.data['Total Concentration'])
        res_num2 = linear_eval(self.number.data['Mean'], d.stats['Number', :, 'Mean'])
        res_num3 = linear_eval(self.number.data['Geo. Mean'], d.stats['Number', :, 'GM'])
        res_num4 = linear_eval(self.number.data['Geo Std Dev'], d.stats['Number', :, 'GSD'])

        self.assertTrue(res_num1[0] >= lbounds and res_num1[0] <= ubounds and res_num1[1] >= threshold)
        self.assertTrue(res_num2[0] >= lbounds and res_num2[0] <= ubounds and res_num2[1] >= threshold)
        self.assertTrue(res_num3[0] >= lbounds and res_num3[0] <= ubounds and res_num3[1] >= threshold)
        self.assertTrue(res_num4[0] >= lbounds and res_num4[0] <= ubounds and res_num4[1] >= threshold)

        # Diameter-weighted first...
        res_diam1 = linear_eval(self.diameter.data['Mean'], d.stats['Diameter', :, 'Mean'])
        res_diam2 = linear_eval(self.diameter.data['Geo. Mean'], d.stats['Diameter', :, 'GM'])
        res_diam3 = linear_eval(self.diameter.data['Geo Std Dev'], d.stats['Diameter', :, 'GSD'])

        self.assertTrue(res_diam1[0] >= lbounds and res_diam1[0] <= ubounds and res_diam1[1] >= threshold)
        self.assertTrue(res_diam2[0] >= lbounds and res_diam2[0] <= ubounds and res_diam2[1] >= threshold)
        self.assertTrue(res_diam3[0] >= lbounds and res_diam3[0] <= ubounds and res_diam3[1] >= threshold)

        # Surface Area-weighted first...
        res_sa1 = linear_eval(self.surface.data['Mean'], d.stats['Surface Area', :, 'Mean'])
        res_sa2 = linear_eval(self.surface.data['Geo. Mean'], d.stats['Surface Area', :, 'GM'])
        res_sa3 = linear_eval(self.surface.data['Geo Std Dev'], d.stats['Surface Area', :, 'GSD'])

        self.assertTrue(res_sa1[0] >= lbounds and res_sa1[0] <= ubounds and res_sa1[1] >= threshold)
        self.assertTrue(res_sa2[0] >= lbounds and res_sa2[0] <= ubounds and res_sa2[1] >= threshold)
        self.assertTrue(res_sa3[0] >= lbounds and res_sa3[0] <= ubounds and res_sa3[1] >= threshold)

        # Volume-weighted first...
        res_vol1 = linear_eval(self.volume.data['Mean'], d.stats['Volume', :, 'Mean'])
        res_vol2 = linear_eval(self.volume.data['Geo. Mean'], d.stats['Volume', :, 'GM'])
        res_vol3 = linear_eval(self.volume.data['Geo Std Dev'], d.stats['Volume', :, 'GSD'])

        self.assertTrue(res_vol1[0] >= lbounds and res_vol1[0] <= ubounds and res_vol1[1] >= threshold)
        self.assertTrue(res_vol2[0] >= lbounds and res_vol2[0] <= ubounds and res_vol2[1] >= threshold)
        self.assertTrue(res_vol3[0] >= lbounds and res_vol3[0] <= ubounds and res_vol3[1] >= threshold)


text:
EXPMatcherInterface(haveLayoutConstraint, (NSLayoutConstraint *expected));

#define hasLayoutConstraint haveLayoutConstraint


text:
package chapter4;

import base.Question;

public class Q5_Validate_BST implements Question {
  class Node {
    int max= 0;
    Node left;
    Node right;
    int value = 0;
    Node(int value){
      this.value=value;
    }
  }

  @Override
  public void run() {
    // BST =  left <= value < right
    // Traverse in order.
    Node root = new Node(5);

    root.left = new Node(3);
    Node n1 = new Node(6);
    root.right = n1;

    n1.left = new Node(4);
    n1.right = new Node(8);

    System.out.println( "Tree is valid: " + checkB( root ));

  }

  private boolean checkB(Node root) {

      return false;
  }
}


text:
package com.altoukhov.svsync;

import java.util.Objects;
import org.joda.time.DateTime;

/**
 * @author Alex Altoukhov
 */
public class FileSnapshot {

    private String fileName;
    private DateTime modifiedTimestamp;
    private long fileSize;
    private String relativePath;
    private String previousPath;

    public String getFileName() {
        return fileName;
    }

    public DateTime getModifiedTimestamp() {
        return modifiedTimestamp;
    }

    public long getFileSize() {
        return fileSize;
    }

    public String getRelativePath() {
        return relativePath;
    }

    public String getPreviousPath() {
        return previousPath;
    }

    public void setPreviousPath(String previousPath) {
        this.previousPath = previousPath;
    }

    public FileSnapshot(String name, long size, DateTime lastModified, String relativePath) {
        this.fileName = name;
        this.fileSize = size;
        this.modifiedTimestamp = lastModified.minusMillis(lastModified.getMillisOfSecond());
        this.relativePath = relativePath;
    }

    @Override
    public String toString() {
        return "FileSnapshot{" + "fileName=" + fileName + ", modifiedTimestamp=" + modifiedTimestamp + ", fileSize=" + fileSize + ", relativePath=" + relativePath + ((previousPath != null)?(", previousPath=" + previousPath) : "") + '}';
    }

    @Override
    public int hashCode() {
        int hash = 7;
        hash = 53 * hash + Objects.hashCode(this.fileName);
        hash = 53 * hash + Objects.hashCode(this.modifiedTimestamp);
        hash = 53 * hash + (int) (this.fileSize ^ (this.fileSize >>> 32));
        return hash;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final FileSnapshot other = (FileSnapshot) obj;
        if (!Objects.equals(this.fileName, other.fileName)) {
            return false;
        }
        if (!Objects.equals(this.modifiedTimestamp, other.modifiedTimestamp)) {
            return false;
        }
        if (this.fileSize != other.fileSize) {
            return false;
        }
        return true;
    }

    public Boolean isLargeFile() {
        return fileSize > Integer.MAX_VALUE;
    }
}


text:
module Repertoire
  module Faceting
    module Model #:nodoc:
      extend ActiveSupport::Concern

      SIGNATURE_WASTAGE_THRESHOLD = 0.15
      DEFAULT_SIGNATURE_COLUMN    = 'id'
      PACKED_SIGNATURE_COLUMN     = '_packed_id'

      included do |base|
        base.singleton_class.delegate :refine, :minimum, :nils, :reorder, :to_sql, :to => :scoped_all

        base.class_attribute(:facets)
        base.facets = HashWithIndifferentAccess.new
      end

      #
      # == Facet declarations
      #
      # Facet declarations consist of a facet name and an optional ActiveRecord relation that describes
      # the attribute column to facet over, any joins necessary to reach it, and other defaults. They
      # work similarly to Rails scoped queries.  For example:
      #
      #   class Nobelist < ActiveRecord::Base
      #     include Repertoire::Faceting::Model
      #     has_many :affiliations
      #
      #     facet :discipline
      #     facet :degree,     joins(:affiliations).group('affiliations.degree')
      #     facet :birthdate,  order('birthdate ASC')
      #   end
      #
      # Implicitly, any facet declaration is an SQL aggregate that divides the attribute values into discrete
      # groups.  When no relation is provided, /model/.group(/facet name/) is assumed by default.  So the
      # discipline facet declaration above is equivalent to
      #
      #   facet :discipline, group(:discipline)
      #
      # and the grouping on degree could be left out.  You can use this behavior to construct a facet
      # from differently-named columns:
      #
      #   facet :balloon_color, group(:color)
      #
      # or to synthesize values using an SQL expression:
      #
      #   facet :birth_year, group('EXTRACT(year FROM birthdate)')
      #
      # As shown above, facets can be constructed from an arbitrary set of joined tables.
      #
      # == Nested facets
      #
      # Facets can be built from a nested hierarchy of values by providing multiple group columns.  In this
      # case, value counts are aggregated at each level in turn.
      #
      #   facet :birth_place, group(:birth_country, :birth_state, :birth_city)
      #
      # As for basic facets, nested facets may consist of SQL expressions.  This is particularly useful in
      # faceting over data in more complex types such as dates or geographical regions:
      #
      #   facet :birth_date, group('EXTRACT(year FROM birthdate)', 'EXTRACT(month FROM birthdate)', 'EXTRACT(day FROM birthdate)')
      #
      # == Facet options
      #
      # The following query options can also be specified in the facet declaration.
      #
      # [order] Order for facet value counts.  Two computed columns are available, "count" and another with the
      #         facet's name.  For example, to order a genre facet alphanumerically within each descending count:
      #           facet :genre, order('count DESC', 'genre ASC')
      #
      # [nils] Whether to include null facet values in the results or not.  Defaults to true:
      #          facet :genre, nils(false)
      #
      # [minimum] Cut-off below which facet value counts should not be listed:
      #             facet :genre, minimum(5)
      #
      # == Executing Queries
      #
      # Facet value count and result queries follow the format familiar from ActiveRecord group and count
      # aggregation.  This allows you to execute a facet value count query given a base set of records.
      #
      #   Nobelist.where("name LIKE 'Robert%'").count(:discipline)
      #
      # To incorporate refinements on other facets on this model, use refine:
      #
      #   Nobelist.refine(:nobel_year => 2001, :degree => 'Ph.D.').count(:discipline)
      #
      # If you provide multiple values for a simple facet refinement, they are interpreted as a logical "or":
      #
      #   Nobelist.refine(:nobel_year => [2000, 2001])     # => 'WHERE name IN (2000, 2001)'
      #
      # In the case of a nested facet, multiple values identify levels in the taxonomy:
      #
      #   Nobelist.refine(:birth_place => [ 'Ukraine', 'Kiev' ]).count(:nobel_year)
      #
      # Refinements are integrated into result queries automatically:
      #
      #   Nobelist.refine(:birth_place => [ 'Ukraine', 'Kiev' ]).all
      #
      # == Index access
      #
      # As you will have noted already, facet counts and queries are quite similar to their ActiveRecord/SQL
      # counterparts.  Behind the scenes, the Repertoire faceting code re-writes your query.
      #
      # Facets defined on associations are joined and limited automatically, and facet indices in the database
      # are used wherever possible rather than querying the model table.
      #
      # == Facet registration
      #
      # The system supports plugins for new facet type implementations.  When a new facet is declared, the
      # available facet implementations are polled until one claims the new relation.  For example, of the
      # built-in facet implementations, BasicFacet claims facets with a single group column, and NestedFacet
      # claims those with several group columns.  If several facet implementations claim a facet, the one
      # that registered later wins.
      #
      # See AbstractFacet for more details.
      #
      module ClassMethods

        #
        # N.B. client code can detect which models are faceted using
        #      "respond_to?(:facet?)"
        #

        # Declare a facet by name
        def facet(name, rel=nil)
          name = name.to_sym

          # default: group by column with facet name, order by count descending
          rel ||= scoped_all
          rel = rel.group(name)                           if rel.group_values.empty?
          rel = rel.order(["count DESC", "#{name} ASC"])  if rel.order_values.empty?

          # locate facet implementation that can handle relation
          facets[name] = Facets::AbstractFacet.mixin(name, rel)
        end

        # Is there a facet by this name?
        def facet?(name)
          facets.key?(name.to_sym)
        end

        # All defined facets by name
        def facet_names
          facets.keys
        end

        # Returns a list of the facets that currently have indices declared
        def indexed_facets
          connection.indexed_facets(table_name)
        end

        # Drops any unused facet indices, updates its packed ids, then recreates
        # indices for the facets with the provided names.  If no names are provided,
        # then the existing facet indices are refreshed.
        #
        # If a signature id column name is provided, it will be used to build the
        # bitset indices. Otherwise the indexer will add or remove a new packed
        # id column as appropriate.
        #
        # Examples:
        #
        # === Refresh existing facet indices
        #
        #   Nobelist.index_facets
        #
        # === Adjust which facets are indexed
        #
        #   Nobelist.index_facets([:degree, :nobel_year])
        #
        # === Drop all facet indices, but add/remove packed id as necessary
        #
        #   Nobelist.index_facets([])
        #
        # === Drop absolutely everything, force manual faceting using 'id'
        #     column
        #
        #   Nobelist.index_facets([], 'id')
        #
        def index_facets(next_indexes=nil, next_faceting_id=nil)
          # default: update existing facets
          current_indexes = indexed_facets
          next_indexes ||= current_indexes

          # sanity checks
          current_indexes = current_indexes.map { |name| name.to_sym }
          next_indexes    = next_indexes.map    { |name| name.to_sym }
          (current_indexes | next_indexes).each do
            |name| raise QueryError, "Unknown facet #{name}" unless facet?(name)
          end

          # determine best column for signature bitsets, unless set manually
          next_faceting_id ||= if signature_wastage(DEFAULT_SIGNATURE_COLUMN) < SIGNATURE_WASTAGE_THRESHOLD
            DEFAULT_SIGNATURE_COLUMN
          else
            PACKED_SIGNATURE_COLUMN
          end

          # default behavior: no changes to packed id column
          drop_packed_id = create_packed_id = false

          # default behavior: adjust facet indexes
          drop_list    = current_indexes - next_indexes
          refresh_list = next_indexes & current_indexes
          create_list  = next_indexes - current_indexes

          # adding or removing a packed id column
          if next_faceting_id != faceting_id
            drop_packed_id   = (next_faceting_id == DEFAULT_SIGNATURE_COLUMN)
            create_packed_id = (next_faceting_id != DEFAULT_SIGNATURE_COLUMN)
          end

          # special case: repacking an existing packed id column
          if next_faceting_id == faceting_id && next_faceting_id != DEFAULT_SIGNATURE_COLUMN
            drop_packed_id = create_packed_id = (signature_wastage > SIGNATURE_WASTAGE_THRESHOLD)
          end

          # changing item ids invalidates all existing facet indices
          if drop_packed_id || create_packed_id
            drop_list, refresh_list, create_list = [ current_indexes, [], next_indexes ]
          end

          connection.transaction do
            # adjust faceting id column
            connection.remove_column(table_name, PACKED_SIGNATURE_COLUMN)           if drop_packed_id
            connection.add_column(table_name, PACKED_SIGNATURE_COLUMN, "SERIAL")    if create_packed_id
            @faceting_id = next_faceting_id

            # adjust facet indices
            drop_list.each    { |name| facets[name].drop_index }
            refresh_list.each { |name| facets[name].refresh_index }
            create_list.each  { |name| facets[name].create_index }
          end

          # TODO. in a nested transaction, this would need to fire after the final commit...
          reset_column_information

        end

        # Over-rides reset_column_information in ActiveRecord::ModelSchema
        def reset_column_information
          @faceting_id = nil
          super
        end

        # Returns the name of the id column to use for constructing bitset signatures
        # over this model.
        def faceting_id
          @faceting_id ||= [PACKED_SIGNATURE_COLUMN, DEFAULT_SIGNATURE_COLUMN].detect { |c| column_names.include?(c) }
        end

        # Returns the proportion of wasted slots in 0..max(id)
        def signature_wastage(signature_column = nil)
          signature_column ||= faceting_id
          connection.signature_wastage(table_name, signature_column)
        end

        # Returns the row count and most recent update timestamp for a model table; or nil if
        # there is no updated_at field.
        def stat_table(timestamp_column = nil)
          timestamp_column ||= "updated_at"
          connection.stat_table(table_name) if column_names.include?(timestamp_column)
        end

        # Return a key suitable for use in HTTP headers, either for the base model table or one of its
        # facets.
        #
        # If the name of an indexed facet is provided, the timestamp of the facet index table is used
        # to construct the facet's cache key. This ensures that facet counts expire when the facet is
        # re-indexed (and not before).
        #
        # If the name of an unindexed facet is given, a cache key for the entire model table is provided.
        # This ensures that faceted browsers over live data expire facet count caches when the base
        # model table is updated.
        #
        # Calling facet_cache_key with no arguments returns a cache key for the entire model table. The
        # key is a combination of the most recent update_at column value and the table row count. If
        # the model has no updated_at attribute, caching is disabled.
        #
        # See the FAQ for additional information.
        def facet_cache_key(facet = nil)
          facet = facet.try(:to_s)
          result = nil

          stats = facets[facet].stat_table if facet_names.include?(facet)
          stats ||= stat_table

          result = { :etag => stats[:count], :last_modified => stats[:timestamp] } if stats.present?

          result
        end

        # Once clients have migrated to Rails 4, delete and replace with 'all' where this is called
        #
        # c.f. http://stackoverflow.com/questions/18198963/with-rails-4-model-scoped-is-deprecated-but-model-all-cant-replace-it
        def scoped_all
          where(nil)
        end

      end
    end
  end
end


text:
scatterbrains
=============

The License is bullshit - if anyone knows of a license which is like "Modify and contribute back and don't sue me", let me know


text:
{% load static %}

  <button
    class="login_button"
    type="button"
    onclick="menue_nutzer_umklappen(this)"
    >{{ user.email }}
  </button>

{{ user.first_name }} {{ user.last_name }}

{{ user.my_profile.get_stufe.bezeichnung }}

Profil

Unterstützen

Guthaben: {{ user.my_profile.guthaben }}

Warenkorb {{ cart.item_count }}

Bestellungen

Abmelden

  Warenkorb {{ cart.item_count }}

{% if request.user.is_staff %}

    Datenbank (Admin)

    Control-Panel

{% endif %}


text:
@interface LoadXIBDynamically : NSObject

/////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
#pragma mark properties

@property(nonatomic, readonly) NSUInteger port;
@property(nonatomic, readonly) NSString* path;

/////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
#pragma mark public instance methods
-(BOOL)setupWebDAVServer;
-(BOOL)setupWebDAVServerWithPort:(NSUInteger)port;
-(BOOL)setupWebDAVServerWithBasePath:(NSString*)path port:(NSUInteger)port;

/////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
#pragma mark public class methods
+ (instancetype)sharedInstance;

@end


text:
var util = require('util')
var async = require('async')
  , debug = require('debug')
  , events = require('events')
  , assert = require('assert')
  , obj_diff = require('obj_diff').defaults({couchdb: true})

var EventEmitter = events.EventEmitter2 || events.EventEmitter
var TICK = typeof global.setImmediate !== 'function' ? process.nextTick : setImmediate

require('defaultable').def(module,
  { 'log'                : debug('txn:couchdb')
  , 'pouchdb_log'        : debug('txn:pouchdb')
  , 'timestamps'         : false
  , 'timestamp_generator': function() { return new Date(); }
  , 'create'             : false
  , 'max_tries'          : 5
  , 'after'              : null
  , 'delay'              : 100
  , 'timeout'            : 15 * 1000
  , 'operation'          : null
  , 'strictSSL'          : true
  , 'maxSockets'         : 100
  , 'proxy'              : null
  , 'req'                : null
  , 'pouchdb'            : null
  , 'couch'              : null
  , 'db'                 : null
  , 'id'                 : null
  , 'test_callback'      : null
  }, function(module, exports, DEFAULT, require) {

var lib = require('./lib');

// The main API is the shortcut function, but the object API is also available.
module.exports = couch_doc_txn
module.exports.Txn = Transaction
module.exports.Transaction = Transaction
module.exports.PouchDB = {Transaction:Transaction, txn:pouch_doc_txn, txn_map:pouch_map}

function pouch_map(opts, operation, callback) {
  var self = this
  async.map(opts, run, done)

  function run(opt, to_async) {
    pouch_doc_txn.call(self, opt, operation, function(er, doc, txr) {
      if (er)
        return to_async(er)
      return to_async(null, {doc:doc, txr:txr})
    })
  }

  function done(er, results) {
    if (er)
      return callback(er)

    var docs = results.map(result => result.doc)
    var txrs = results.map(result => result.txr)

    callback(null, docs, txrs)
  }
}

function pouch_doc_txn(opts, operation, callback) {
  opts = opts || {}
  opts.pouchdb = this
  return couch_doc_txn(opts, operation, callback)
}

function couch_doc_txn(fetch_req, operation, callback) {
  assert.equal('function', typeof callback, 'Need callback');

  // Allow specifying options in the req object.
  var opts = {};
  for (var key in DEFAULT)
    if(key !== 'req' && key !== 'operation')
      if(key in fetch_req) {
        opts[key] = fetch_req[key];
        delete fetch_req[key];
      }

  if(fetch_req.doc) {
    opts.doc = fetch_req.doc;
    delete fetch_req.doc;
  }

  opts.req       = fetch_req;
  opts.operation = operation;

  if (opts.pouchdb)
    var txn = new PouchTransaction(opts)
  else
    var txn = new Transaction(opts)

  txn.on('timeout', function() {
    var err = new Error('Transaction ('+txn.name+') timeout');
    err.timeout = true;
    return callback(err);
  })

  txn.on('exhausted', function(tries) {
    var err = new Error('Transaction ('+txn.name+') exhausted after '+tries+' conflicts');
    err.conflict = true;
    err.tries = tries;
    return callback(err);
  })

  txn.on('error', function(er) {
    return callback(er);
  })

  txn.on('done', function(doc) {
    // A huge string of no-op changes can push the stack too deeply.
    TICK(function() {
      callback(null, doc, txn);
    })
  })

  txn.start();
  return txn;
}

util.inherits(Transaction, EventEmitter);
function Transaction (opts) {
  var self = this;
  EventEmitter.call(self);

  self.type = 'couchdb'

  self.req                 = opts.req                 || DEFAULT.req;
  self.couch               = opts.couch               || DEFAULT.couch;
  self.db                  = opts.db                  || DEFAULT.db;
  self.id                  = opts.id                  || DEFAULT.id;
  self.doc                 = opts.doc                 || null;
  self.operation           = opts.operation           || DEFAULT.operation;
  self.timeout             = opts.timeout             || DEFAULT.timeout;
  self.delay               = opts.delay               || DEFAULT.delay;
  self.log                 = opts.log                 || DEFAULT.log;
  self.timestamp_generator = opts.timestamp_generator || DEFAULT.timestamp_generator;

  // These can be falsy.
  self.after      = ('after'      in opts) ? opts.after      : DEFAULT.after;
  self.create     = ('create'     in opts) ? opts.create     : DEFAULT.create;
  self.timestamps = ('timestamps' in opts) ? opts.timestamps : DEFAULT.timestamps;
  self.max_tries  = ('max_tries'  in opts) ? opts.max_tries  : DEFAULT.max_tries;
} // Transaction

Transaction.prototype.start = function() {
  var self = this;

  if(!self.req)
    return self.emit('error', new Error('Required req object'));

  if(self.doc && !self.doc._id)
    return self.emit('error', new Error('Required doc._id value'));
  if(self.doc)
    self.id = self.doc._id

  // TODO:
  // ID Encoding stuff should not be in this library. Or, at least it should not be here. The ID should be encoded in the HTTP code.
  if(self.id && self.pouchdb)
    self.log('Skip ID encoding for PouchDB')
  else if (self.id)
    self.id = lib.enc_id(self.id)

  self.prep_params()

  assert.ok(self.max_tries > 0, 'max_tries must be 1 or greater');
  assert.ok(self.timeout > 0, 'timeout must be 1 or greater');
  assert.equal(typeof self.operation, 'function', 'Data operation required');

  self.name = self.operation.name || 'Untitled';
  self.fetches = 0;
  self.stores = 0
  self.tries = 0;
  return self.attempt();
}

// Prepare for an HTTP transaction.
Transaction.prototype.prep_params = function() {
  var self = this

  var has_uri   = !! (self.req.uri || self.req.url);
  var has_couch = !! (self.couch || self.db || self.id);

  assert.ok(has_uri || has_couch, 'Must provide .uri or .couch/.db/.id parameters');
  if(has_uri)
    assert.equal(false, has_couch, 'Clashing .uri/.url and .couch/.db/.id parameters');
  if(has_couch) {
    assert.ok(self.couch && self.db && self.id, 'Must set all .couch, .db, and .id parameters');
    assert.equal(false, has_uri, 'Clashing .uri/.url and .couch/.db/.id parameters');
  }

  self.uri = self.req.uri || self.req.url || [self.couch, self.db, self.id].join('/');
  assert.ok(self.uri, 'Must set .uri or else .couch, .db, and .id');
}

Transaction.prototype.attempt = function() {
  var self = this;

  if(self.tries >= self.max_tries) {
    self.log('Too many tries ('+self.name+'): ' + self.tries);
    return self.emit('exhausted', self.tries);
  }

  if(self.retry_timer)
    return self.emit('error', new Error('retry_timer already set: ' + self.name));

  var delay;
  if(self.tries == 0 && ! self.after)
    return go(); // No delay.
  else if(self.tries == 0 && self.after) {
    delay = self.after;
    self.log('Initial delay before first run ('+self.name+'): ' + delay);
    self.retry_timer = setTimeout(go, delay);
  }
  else {
    delay = self.delay * Math.pow(2, self.tries);
    self.log('Delay until next attempt ('+self.name+'): ' + delay);
    self.retry_timer = setTimeout(go, delay);
  }

  function go() {
    clearTimeout(self.retry_timer);
    delete self.retry_timer;

    self.tries += 1;
    self.emit('attempt', self.tries);
    self.run();
  }
}

Transaction.prototype.run = function() {
  var self = this;
  self.log('Transaction %s (%s/%s): %s', self.name, self.tries, self.max_tries, self.uri || self.id)

  if(self.doc) {
    self.log('Skip fetch, assuming known doc: ' + self.doc._id)
    return run_op(self.doc, !('_rev' in self.doc))
  }

  self.fetches += 1;
  self.get(function (er, res, couch_doc) {
    var is_create = !!self.create && res.statusCode == 404 && couch_doc.error == 'not_found';
    if(er && !is_create)
      return self.emit('error', er);

    if(is_create) {
      self.is_create = true
      couch_doc = { "_id": decodeURIComponent(self.id || self.uri_to_id(self.uri)) };
      self.log('Create new doc: %j', couch_doc)
    } else
      self.is_create = false

    return run_op(couch_doc, is_create);
  })

  function run_op(doc, is_create) {
    if(!doc._id)
      return self.emit('error', new Error('No _id: ' + lib.JS(doc)));
    if(!doc._rev && !is_create)
      return self.emit('error', new Error('No _rev: ' + lib.JS(doc)));

    self.log('Run operation (create=%j): %s', is_create, doc._id)
    delete self.doc; // In case it was provided.

    var original = { "doc": lib.JDUP(doc)
                   , "id" : doc._id
                   , "rev": doc._rev
                   };

    if(self.op_timer)
      return self.emit('error', new Error('op_timer already set: ' + self.name));

    var already_done = false;
    self.op_timer = setTimeout(on_timeout, self.timeout);
    function on_timeout() {
      self.op_timer = null;
      already_done = true;
      return self.emit('timeout');
    }

    // Execute the operation.
    self.operation(doc, op_done);

    function op_done(er, new_doc) {
      clearTimeout(self.op_timer);
      delete self.op_timer;

      if(already_done) {
        self.log('Ignore operation after timeout');
        return self.emit('ignore');
      } else
        already_done = true;

      if(er)
        return self.emit('error', er);

      if(new_doc) {
        self.log('Use new doc: %j', new_doc)
        self.emit('replace', doc, new_doc);
        doc = new_doc;
      }

      var diff = obj_diff(original.doc, doc)
      self.log('Operation diff (%s): %j', self.name, diff)

      if(!self.is_create && diff.atmost()) {
        self.log('Skip txn update for unchanged doc: ' + original.id);
        return self.emit('done', doc);
      }

      self.emit('change', diff);

      doc._id = original.id;
      if(original.rev)
        doc._rev = original.rev;

      if(!! self.timestamps) {
        doc.updated_at = JSON.stringify(self.timestamp_generator()).replace(/"/g, '');
        if(is_create)
          doc.created_at = doc.created_at || doc.updated_at;
      }

      self.log('Update transaction (%s): %s', self.name, self.uri || self.id)
      self.stores += 1
      self.put(doc, function(er, res, result) {
        if(er && res && res.statusCode === 409 && result.error === "conflict") {
          // Retryable error.
          self.log('Conflict: '+self.name);
          self.emit('conflict', self.tries);
          return self.attempt();
        }

        if(er)
          // Normal error, non-retryable.
          return self.emit('error', er);

        // Success.
        if (DEFAULT.test_callback)
          DEFAULT.test_callback() // The only purpose for this is for the test suite to confirm that DEFAULT is working.

        doc._rev = result.rev;
        return self.emit('done', doc);
      })
    }
  } // run_op
}

Transaction.prototype.get = function(callback) {
  var self = this
  self.log('Fetch doc: ' + (self.id || self.uri_to_id(self.uri)))

  self.req.method = 'GET';
  self.req.uri = self.uri;
  delete self.req.url;

  return lib.req_couch(self.req, callback)
}

Transaction.prototype.put = function(doc, callback) {
  var self = this
  var update_req = {method:'PUT', uri:self.uri, json:doc}
  self.log('Update request: %j', update_req)
  return lib.req_couch(update_req, callback)
}

Transaction.prototype.cancel = function() {
  clearTimeout(self.retry_timer);
  clearTimeout(self.op_timer);

  self.log('Cancelling transaction try: ' + self.tries);
  self.retry_timer = null;
  self.op_timer    = null;

  self.emit('cancel', self.tries);
}

// The caller might override this if using some unknown URL scheme.
Transaction.prototype.uri_to_id = function(uri) {
  var parts = uri.split('/');
  return parts[ parts.length - 1 ];
}

//
// PouchTransaction is a thin subclass of Transaction
//

util.inherits(PouchTransaction, Transaction)
function PouchTransaction (opts) {
  var self = this
  Transaction.call(self, opts)

  self.type = 'pouch'
  self.log = opts.log || DEFAULT.pouchdb_log
  self.pouchdb = opts.pouchdb || DEFAULT.pouchdb
}

PouchTransaction.prototype.prep_params = function() {
  var self = this

  self.log('Prep PouchDB')
  assert.ok(!self.req.uri && !self.req.url, 'PouchDB disallows .url or .uri parameters')
  assert.ok(self.id, 'Must provide .id parameter')
  assert.ok(self.pouchdb, 'Must provide .pouchdb parameter')
}

PouchTransaction.prototype.get = function(callback) {
  var self = this
  self.log('Fetch doc: %s', self.id)

  return self.pouchdb.get(self.id, function(er, doc) {
    // The callback wants request-style [er, response, body] parameters.
    if (er && (!er.status || !er.name))
      callback(er) // Unknown error: .status or .name is missing.
    else if (er)
      callback(er, {statusCode:er.status}, {error:er.name}) // e.g. status=404 name=not_found
    else
      callback(null, {statusCode:200}, doc)
  })
}

PouchTransaction.prototype.put = function(doc, callback) {
  var self = this
  self.log('Put doc: %j', doc)

  // The callback wants request-style [er, response, body] parameters.
  return self.pouchdb.put(doc, function(er, result) {
    if (er && (!er.status || !er.name))
      callback(er) // Unknown error: .status or .name is missing.
    else if (er)
      callback(er, {statusCode:er.status}, {error:er.name}) // e.g. status=409 name=conflict
    else
      callback(null, {statusCode:201}, result)
  })
}

}, require) // defaultable


text:
package merlin.ianusinc.ianusinchq.init;

import merlin.ianusinc.ianusinchq.IanusIncHq;
import merlin.ianusinc.ianusinchq.Reference;
import merlin.ianusinc.ianusinchq.blocks.CustomNugget;
import merlin.ianusinc.ianusinchq.items.CustomIngot;
import merlin.ianusinc.ianusinchq.items.DedicatedBlockItem;
import net.minecraft.block.Block;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.item.Item;
import net.minecraft.item.ItemBlock;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.event.RegistryEvent;
import net.minecraftforge.fml.common.registry.ForgeRegistries;

import java.util.ArrayList;

/**
 * Created by Seine Eiligkeit on 29.06.2017.
 */
public class ItemInit {

    public static Item tutorial_ingot;
    public static Item tutorial_nugget;

    public static ArrayList<Item> itemList = new ArrayList<>();

    public static void prepareItems(){
        IanusIncHq.LOGGER.info("Item Preparation starts now");

        tutorial_ingot = new CustomIngot("tutorial_ingot");
        tutorial_nugget = new CustomNugget("tutorial_nugget");

        itemList.add(tutorial_nugget);
        itemList.add(tutorial_ingot);
    }
    public static void addItemBlockToItems(Block block){
        ItemBlock itemblock = new ItemBlock(block);
        itemblock.setRegistryName(block.getRegistryName());
        itemList.add(itemblock);
    }
    public static void addDedicatedBlockItemToItems(DedicatedBlockItem item){
        Item dedicatedItem = item;
        item.setRegistryName(item.getMyBlock().getRegistryName());
        itemList.add(item);
    }

    public static void registerItems(RegistryEvent.Register<Item> event){
        IanusIncHq.LOGGER.info("Item Registration starts now");
        for(Item item : itemList){
            IanusIncHq.LOGGER.info("Going to register: " + item.getUnlocalizedName() +"...");
            event.getRegistry().register(item);
            IanusIncHq.LOGGER.info("\t\tSet ModelResourceLocation to " + Reference.MODID + ":" + item.getRegistryName());
            ModelLoader.setCustomModelResourceLocation(
                    item,
                    0,
                    new ModelResourceLocation(Reference.MODID + ":" + item.getUnlocalizedName().substring(5))
            );
            IanusIncHq.LOGGER.info("Done registering: " + item.getUnlocalizedName() +"...");
        }
        IanusIncHq.LOGGER.info("Done Item registration...");
    }
}


text:
<?php

namespace BlogBundle\Entity;

/**
 * Tag
 */
class Tag
{
    /**
     * @var integer
     */
    private $id;

    /**
     * @var string
     */
    private $name;

    /**
     * @var string
     */
    private $description;

	protected $entryTag;

	public function __construct() {
		$this->entryTag = new \Doctrine\Common\Collections\ArrayCollection();
	}

	/**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set name
     *
     * @param string $name
     *
     * @return Tag
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set description
     *
     * @param string $description
     *
     * @return Tag
     */
    public function setDescription($description)
    {
        $this->description = $description;

        return $this;
    }

    /**
     * Get description
     *
     * @return string
     */
    public function getDescription()
    {
        return $this->description;
    }

	public function getEntryTag(){
		return $this->entryTag;
	}

    /**
     * Add entryTag
     *
     * @param \BlogBundle\Entity\EntryTag $entryTag
     *
     * @return Tag
     */
    public function addEntryTag(\BlogBundle\Entity\EntryTag $entryTag)
    {
        $this->entryTag[] = $entryTag;

        return $this;
    }

    /**
     * Remove entryTag
     *
     * @param \BlogBundle\Entity\EntryTag $entryTag
     */
    public function removeEntryTag(\BlogBundle\Entity\EntryTag $entryTag)
    {
        $this->entryTag->removeElement($entryTag);
    }
}


text:
$(function(){
	localStorage.lang = localStorage.lang || "en";
	if(localStorage.lang == "en"){
		console.log("EN");
		$("#headerToggleLang").addClass("langCN");
	}
	else if(localStorage.lang == "cn"){
		console.log("CN");
		$("#headerToggleLang").addClass("langEN");
	}

	$("#headerToggleLang").on("click", function(){
		$logo = $("#headerToggleLang");
		if(localStorage.lang == "cn"){
			localStorage.lang = "en";
			location.reload();
		}
		else{
			localStorage.lang = "cn";
			location.reload();
		}
	});

	if($('.carousel').length > 0){
		$('.carousel').fadeIn('slow', function(){
			$('.fade').addClass('in');
		});
	}
	else{
			$('.fade').addClass('in');
	}

	$('.carousel').carousel({
        interval: 3000 //changes the speed
    });
	setTimeout(function(){
		$("li.active > a").click(function(e){
			e.preventDefault();
		});
	}, 500);

	$(".serviceBlock").height($(".serviceBlock").width());
	$(window).resize(function(){
		$(".serviceBlock").height($(".serviceBlock").width());
		var $contactLogo = $(".contact_logo > img");
		if($contactLogo){
			$contactLogo.width("100%");
		}
	});

	$(".btnMediaToVideo").on("click", function(){
		$(".mediaToVideo").fadeOut(500,function(){
			$(".mediaToGallery").fadeIn(500);
		});
		$("#galleryTab").animate({
			opacity:0,
			left: -$("#galleryTab").width()
		}, 500, function(){
			$("#galleryTab").css("display", "none");
			$("#videoTab").css("display", "inline-block");
			$("#videoTab").animate({
				opacity: 1,
				right:0
			},500);
		});
	});

	$(".btnMediaToGallery").on("click", function(){
		$(".mediaToGallery").fadeOut(500,function(){
			$(".mediaToVideo").fadeIn(500);
		});
		$("#videoTab").animate({
			opacity:0,
			right: -$("#videoTab").width()
		}, 500, function(){
			$("#videoTab").css("display", "none");
			$("#galleryTab").css("display", "inline-block");
			$("#galleryTab").animate({
				opacity: 1,
				left: 0
			},500);
		});
	});
});


text: My new portfolio site.


text:
The application is a simulation of a toy robot moving on a square tabletop

application should accept the below commands;

- PLACE X,Y,F - X and Y axis indicates the position of the robot while F indicates facing direction
- MOVE - move to a one position forward where the robot is currently facing.
- LEFT - turn left from the direction that the robot is currently facing.
- RIGHT - turn right from the direction that the robot is currently facing.
- REPORT - prints the current status of the robot, eg: 3,3,NORTH

## Flow Chart
Describes the highlevel architecture of the program.
![alt tag](https://github.com/hasanthaera/rea_robot/blob/master/doc/robot.png)

## Prerequisites

- Eclipse
- Java 8
- JUnit 4

## Installing

Please clone or download the rea_robot repository and open the project using eclipse. You could easily run the project from eclipse as a Java Application.

```
clone https://github.com/hasanthaera/rea_robot.git
```

## Running the tests

JUNIT test cases are included in the test package, to run the test cases write click on the project "Run As" -> "Run Configurations" then double click on the JUnit setting on left pannel of the window then click "Run"

This will excecute the test cases included in the RobotMoverTest class.

## Sample Input/Output - test data

### Example a

    PLACE 0,0,NORTH
    MOVE
    REPORT

Expected output:

    0,1,NORTH

### Example b

    PLACE 0,0,NORTH
    LEFT
    REPORT

Expected output:

    0,0,WEST

### Example c

    PLACE 1,2,EAST
    MOVE
    MOVE
    LEFT
    MOVE
    REPORT

Expected output

    3,3,NORTH


text:
package org.fest.swing.driver;

import static org.fest.util.Lists.newArrayList;

import java.util.Collection;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

/**
 * Tests for {@link JTabbedPaneDriver#selectTab(javax.swing.JTabbedPane, int)}.
 *
 * @author Alex Ruiz
 * @author Yvonne Wang
 */
@RunWith(Parameterized.class)
public class JTabbedPaneDriver_selectTabByIndex_withManyIndices_Test extends JTabbedPaneDriver_TestCase {
  private final int index;

  @Parameters
  public static Collection<Object[]> indices() {
    return newArrayList(tabIndices());
  }

  public JTabbedPaneDriver_selectTabByIndex_withManyIndices_Test(int index) {
    this.index = index;
  }

  @Test
  public void should_select_tab() {
    showWindow();
    driver.selectTab(tabbedPane, index);
    assertThatSelectedTabIndexIs(index);
  }
}


text:
/**
 *
 */
package me.learn.personal.month3;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * Title 1451 : Given a sentence text (A sentence is a string of space-separated
 * words) in the following format:
 *
 * First letter is in upper case. Each word in text are separated by a single
 * space.
 *
 * Your task is to rearrange the words in text such that all words are
 * rearranged in an increasing order of their lengths. If two words have the
 * same length, arrange them in their original order.
 *
 * Return the new text following the format shown above.
 *
 *
 *
 * Example 1:
 *
 * Input: text = "Leetcode is cool" Output: "Is cool leetcode" Explanation:
 * There are 3 words, "Leetcode" of length 8, "is" of length 2 and "cool" of
 * length 4. Output is ordered by length and the new first word starts with
 * capital letter.
 *
 * Example 2:
 *
 * Input: text = "Keep calm and code on" Output: "On and keep calm code"
 * Explanation: Output is ordered as follows: "On" 2 letters. "and" 3 letters.
 * "keep" 4 letters in case of tie order by position in original text. "calm" 4
 * letters. "code" 4 letters.
 *
 *
 *
 * @author bramanarayan
 * @date Jul 14, 2020
 */
public class RearrangeWordsInSentence {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		RearrangeWordsInSentence solution = new RearrangeWordsInSentence();
		System.out.println(solution.arrangeWords("Leetcode is Cool"));
		System.out.println(solution.arrangeWords("Keep calm and code on"));
	}

	// split based on length.
	public String arrangeWords(String text) {
		Map<Integer, List<String>> m = new TreeMap<Integer, List<String>>();
		String[] tokens = text.split("\\s+");

		// Prepare a map of count -> strings
		for (String s : tokens) {
			int length = s.length();
			if (m.containsKey(length)) {
				m.get(length).add(s);
			} else {
				List<String> list = new ArrayList<String>();
				list.add(s);
				m.put(length, list);
			}
		}

		// Now iterate the map based on length. its already sorted cos of TreeMap
		StringBuilder sb = new StringBuilder();
		m.entrySet().forEach(x -> {
			for (String s : x.getValue()) {
				sb.append(s.toLowerCase() + " ");
			}
		});

		// The first letterneed to be upper case..so...
		char first = sb.charAt(0);
		sb.setCharAt(0, Character.toUpperCase(first));

		return sb.toString().trim();

	}

}


text:
#pragma once

namespace humoto
{
    /**
     * @brief MPC controller for Pepper
     *
     * @ingroup Modules
     * @{
     * @defgroup pepper_mpc pepper_mpc
     * @}
     *
     * @ingroup pepper_mpc
     */
    namespace pepper_mpc
    {
    }
}

#include "pepper_mpc/common.h"
#include "pepper_mpc/two_point_mass_model.h"
#include "pepper_mpc/model_state.h"
#include "pepper_mpc/model.h"
#include "pepper_mpc/preview_horizon.h"
#include "pepper_mpc/mpc_mg.h"

#include "pepper_mpc/task_basevelocityref.h"
#include "pepper_mpc/task_bodypositionref.h"
#include "pepper_mpc/task_basevelocitybounds.h"
#include "pepper_mpc/task_bodypositionbounds.h"
#include "pepper_mpc/task_coppositionbounds.h"
#include "pepper_mpc/task_baseaccelerationbounds.h"
#include "pepper_mpc/task_basejerkminimization.h"
#include "pepper_mpc/task_bodyjerkminimization.h"
#include "pepper_mpc/task_copcentering.h"
#include "pepper_mpc/task_basepositionref.h"

#ifdef HUMOTO_USE_CONFIG
#include "pepper_mpc/configurable_optimization_problem.h"
#endif