<commit_before>/*
 Licensed to the Apache Software Foundation (ASF) under one or more
 contributor license agreements.  See the NOTICE file distributed with
 this work for additional information regarding copyright ownership.
 The ASF licenses this file to You 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.
*/

// #/:core/query
sammy.get
(
  /^#\/([\w\d-]+)\/(query)$/,
  function( context )
  {
    var core_basepath = this.active_core.attr( 'data-basepath' );
    var content_element = $( '#content' );

    $.get
    (
      'tpl/query.html',
      function( template )
      {
        content_element
          .html( template );

        var query_element = $( '#query', content_element );
        var query_form = $( '#form form', query_element );
        var url_element = $( '#url', query_element );
        var result_element = $( '#result', query_element );
        var response_element = $( '#response iframe', result_element );

        url_element
          .die( 'change' )
          .live
          (
            'change',
            function( event )
            {
              var check_iframe_ready_state = function()
              {
                var iframe_element = response_element.get(0).contentWindow.document || response_element.get(0).document;

                if( !iframe_element )
                {
                  console.debug( 'no iframe_element found', response_element );
                  return false;
                }

                url_element
                  .addClass( 'loader' );

                if( 'complete' === iframe_element.readyState )
                {
                  url_element
                    .removeClass( 'loader' );
                }
                else
                {
                  window.setTimeout( check_iframe_ready_state, 100 );
                }
              }
              check_iframe_ready_state();

              response_element
                .attr( 'src', this.href );

              if( !response_element.hasClass( 'resized' ) )
              {
                response_element
                  .addClass( 'resized' )
                  .css( 'height', $( '#main' ).height() - 60 );
              }
            }
          )

        $( '.optional legend input[type=checkbox]', query_form )
          .die( 'change' )
          .live
          (
            'change',
            function( event )
            {
              var fieldset = $( this ).parents( 'fieldset' );

              this.checked
                ? fieldset.addClass( 'expanded' )
                : fieldset.removeClass( 'expanded' );
            }
          )

        for( var key in context.params )
        {
          if( 'string' === typeof context.params[key] )
          {
            $( '[name="' + key + '"]', query_form )
              .val( context.params[key] );
          }
        }

        query_form
          .die( 'submit' )
          .live
          (
            'submit',
            function( event )
            {
              var form_map = {};
              var form_values = [];
              var all_form_values = query_form.formToArray();

              for( var i = 0; i < all_form_values.length; i++ )
              {
                if( !all_form_values[i].value || 0 === all_form_values[i].value.length )
                {
                  continue;
                }

                var name_parts = all_form_values[i].name.split( '.' );
                if( 1 < name_parts.length && !form_map[name_parts[0]] )
                {
                  console.debug( 'skip "' + all_form_values[i].name + '", parent missing' );
                  continue;
                }

                form_map[all_form_values[i].name] = all_form_values[i].value;
                form_values.push( all_form_values[i] );
              }

              var query_url = window.location.protocol + '//' + window.location.host
                            + core_basepath + '/select?' + $.param( form_values );

              url_element
                .attr( 'href', query_url )
                .text( query_url )
                .trigger( 'change' );

              result_element
                .show();

              return false;
            }
          );
      }
    );
  }
);<commit_msg>SOLR-3325: linking to query UI with parameters will execute them<commit_after>/*
 Licensed to the Apache Software Foundation (ASF) under one or more
 contributor license agreements.  See the NOTICE file distributed with
 this work for additional information regarding copyright ownership.
 The ASF licenses this file to You 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.
*/

// #/:core/query
sammy.get
(
  /^#\/([\w\d-]+)\/(query)$/,
  function( context )
  {
    var core_basepath = this.active_core.attr( 'data-basepath' );
    var content_element = $( '#content' );

    $.get
    (
      'tpl/query.html',
      function( template )
      {
        content_element
          .html( template );

        var query_element = $( '#query', content_element );
        var query_form = $( '#form form', query_element );
        var url_element = $( '#url', query_element );
        var result_element = $( '#result', query_element );
        var response_element = $( '#response iframe', result_element );

        url_element
          .die( 'change' )
          .live
          (
            'change',
            function( event )
            {
              var check_iframe_ready_state = function()
              {
                var iframe_element = response_element.get(0).contentWindow.document || response_element.get(0).document;

                if( !iframe_element )
                {
                  console.debug( 'no iframe_element found', response_element );
                  return false;
                }

                url_element
                  .addClass( 'loader' );

                if( 'complete' === iframe_element.readyState )
                {
                  url_element
                    .removeClass( 'loader' );
                }
                else
                {
                  window.setTimeout( check_iframe_ready_state, 100 );
                }
              }
              check_iframe_ready_state();

              response_element
                .attr( 'src', this.href );

              if( !response_element.hasClass( 'resized' ) )
              {
                response_element
                  .addClass( 'resized' )
                  .css( 'height', $( '#main' ).height() - 60 );
              }
            }
          )

        $( '.optional legend input[type=checkbox]', query_form )
          .die( 'change' )
          .live
          (
            'change',
            function( event )
            {
              var fieldset = $( this ).parents( 'fieldset' );

              this.checked
                ? fieldset.addClass( 'expanded' )
                : fieldset.removeClass( 'expanded' );
            }
          );

        query_form
          .die( 'submit' )
          .live
          (
            'submit',
            function( event )
            {
              var form_map = {};
              var form_values = [];
              var all_form_values = query_form.formToArray();

              for( var i = 0; i < all_form_values.length; i++ )
              {
                if( !all_form_values[i].value || 0 === all_form_values[i].value.length )
                {
                  continue;
                }

                var name_parts = all_form_values[i].name.split( '.' );
                if( 1 < name_parts.length && !form_map[name_parts[0]] )
                {
                  console.debug( 'skip "' + all_form_values[i].name + '", parent missing' );
                  continue;
                }

                form_map[all_form_values[i].name] = all_form_values[i].value;
                form_values.push( all_form_values[i] );
              }

              var query_url = window.location.protocol + '//' + window.location.host
                            + core_basepath + '/select?' + $.param( form_values );

              url_element
                .attr( 'href', query_url )
                .text( query_url )
                .trigger( 'change' );

              result_element
                .show();

              return false;
            }
          );

        var fields = 0;
        for( var key in context.params )
        {
          if( 'string' === typeof context.params[key] )
          {
            fields++;
            $( '[name="' + key + '"]', query_form )
              .val( context.params[key] );
          }
        }

        if( 0 !== fields )
        {
          query_form
            .trigger( 'submit' );
        }
      }
    );
  }
);<|endoftext|>


<commit_before>// The relative or absolute URL of your SimianGrid map tile folder
var TILE_HOST = "/Grid/map/";

var CLICK_HANDLER = sample_handler;

// The maximum width/height of the grid in regions (must be a power of two)
var GRID_WIDTH_IN_REGIONS = 1048576;
// Map from a GRID_WIDTH_IN_REGIONS x GRID_WIDTH_IN_REGIONS square to Lat/Long (0, 0),(-90, 90)
var SCALE_FACTOR = 90.0 / GRID_WIDTH_IN_REGIONS;

// Override the default Mercator projection with Euclidean projection
// (insert oblig. Flatland reference here)
function EuclideanProjection() {
};

EuclideanProjection.prototype.fromLatLngToPoint = function(latLng, opt_point) {
	var point = opt_point || new google.maps.Point(0, 0);

    point.x = latLng.lng() / SCALE_FACTOR;
    point.y = latLng.lat() / SCALE_FACTOR;

	return point;
};

EuclideanProjection.prototype.fromPointToLatLng = function(point) {
    var lng = point.x * SCALE_FACTOR;
    var lat = point.y * SCALE_FACTOR;

	return new google.maps.LatLng(lat, lng, true);
};

// Configure options for the map
var imageMapOptions = {
	getTileUrl: function(coord, zoom) {
		var gridZoom = 8 - zoom;
	    var regions_per_tile_edge = Math.pow(2, gridZoom - 1);

	    // Convert from tile coordinates to world coordinates
		var x = coord.x * regions_per_tile_edge;
		var y = coord.y * regions_per_tile_edge;

		// Flip the y axis
	    y = -y;

	    // Orient the y axis from the bottom-left corner instead of the top-left
	    y -= regions_per_tile_edge;

	    // Adjust x/y to the lower-left tile for this zoom level
	    x -= x % regions_per_tile_edge;
	    y -= y % regions_per_tile_edge;

	    return TILE_HOST + "map-" + gridZoom + "-" + x + "-" + y + "-objects.png";
	},
	tileSize: new google.maps.Size(256, 256),
	minZoom: 0,
	maxZoom: 7,
	isPng: true
};

var imageMapType = new google.maps.ImageMapType(imageMapOptions);
imageMapType.projection = new EuclideanProjection();
var map;

var scale = 90.0 / 1048576;
function convert_grid_pos(x, y)
{
    var real_x = ( x * 2 ) * scale;
    var real_y = ( y * 2 ) * scale;
    return new google.maps.LatLng(-real_x, real_y);
}

function handle_click(event)
{
    var x = event.latLng.b;
    var y = event.latLng.c;
    var real_x = 0 - Math.ceil(( x / scale) / 2);
    var real_y = Math.floor(( y / scale) / 2);
    CLICK_HANDLER(real_x, real_y);
}

function sample_handler(x, y)
{
    alert('X : ' + x + " Y : " + y);
}

function initialize_map(tile_host, x, y, zoom, click_handler) {
    var mapOptions = {
        mapTypeControl: false,
        backgroundColor: "#1D475F",
        center: convert_grid_pos(x, y),
        zoom: zoom
    };
    TILE_HOST = tile_host;
    if ( click_handler != undefined ) {
        CLICK_HANDLER = click_handler;
    }
	map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
	// Now attach the grid map type to the map's registry
	map.mapTypes.set('grid', imageMapType);
	// We can now set the map to use the 'grid' map type
	map.setMapTypeId('grid');

	google.maps.event.addListener(map, 'click', handle_click);
}

function center_map(x, y, zoom)
{
	if ( zoom == undefined ) {
		zoom = 7;
	}

	map.panTo(convert_grid_pos(x, y));
	map.setZoom(zoom);
}

function load_region_by_pos(x, y)
{
    var data = {
        'x' : x,
        'y' : y
    };
    div_loader("view_coord", "#region_info", data);
	$("#search_results").dialog('close');
	$("#region_info").dialog('open');
}

function load_search_result(scene_id)
{
	var data = {
		'is_search' : true
	};
    div_loader("info/" + scene_id + "/inline", "#region_info", data);
	$("#region_info").dialog('open');
}
<commit_msg>* partial fix for #78 - details_popup corresponds with right region<commit_after>// The relative or absolute URL of your SimianGrid map tile folder
var TILE_HOST = "/Grid/map/";

var CLICK_HANDLER = sample_handler;

// The maximum width/height of the grid in regions (must be a power of two)
var GRID_WIDTH_IN_REGIONS = 1048576;
// Map from a GRID_WIDTH_IN_REGIONS x GRID_WIDTH_IN_REGIONS square to Lat/Long (0, 0),(-90, 90)
var SCALE_FACTOR = 90.0 / GRID_WIDTH_IN_REGIONS;

// Override the default Mercator projection with Euclidean projection
// (insert oblig. Flatland reference here)
function EuclideanProjection() {
};

EuclideanProjection.prototype.fromLatLngToPoint = function(latLng, opt_point) {
	var point = opt_point || new google.maps.Point(0, 0);

    point.x = latLng.lng() / SCALE_FACTOR;
    point.y = latLng.lat() / SCALE_FACTOR;

	return point;
};

EuclideanProjection.prototype.fromPointToLatLng = function(point) {
    var lng = point.x * SCALE_FACTOR;
    var lat = point.y * SCALE_FACTOR;

	return new google.maps.LatLng(lat, lng, true);
};

// Configure options for the map
var imageMapOptions = {
	getTileUrl: function(coord, zoom) {
		var gridZoom = 8 - zoom;
	    var regions_per_tile_edge = Math.pow(2, gridZoom - 1);

	    // Convert from tile coordinates to world coordinates
		var x = coord.x * regions_per_tile_edge;
		var y = coord.y * regions_per_tile_edge;

		// Flip the y axis
	    y = -y;

	    // Orient the y axis from the bottom-left corner instead of the top-left
	    y -= regions_per_tile_edge;

	    // Adjust x/y to the lower-left tile for this zoom level
	    x -= x % regions_per_tile_edge;
	    y -= y % regions_per_tile_edge;

	    return TILE_HOST + "map-" + gridZoom + "-" + x + "-" + y + "-objects.png";
	},
	tileSize: new google.maps.Size(256, 256),
	minZoom: 0,
	maxZoom: 7,
	isPng: true
};

var imageMapType = new google.maps.ImageMapType(imageMapOptions);
imageMapType.projection = new EuclideanProjection();
var map;

var scale = 90.0 / 1048576;
function convert_grid_pos(x, y)
{
    var real_x = ( x * 2 ) * scale;
    var real_y = ( y * 2 ) * scale;
    return new google.maps.LatLng(-real_x, real_y);
}

function handle_click(event)
{
    var x = event.latLng.lng();
    var y = event.latLng.lat();
	console.log('what ' + x + '/' + y);
    var real_x = Math.ceil(( x / scale) / 2) - 1;
    var real_y = 0 - Math.floor(( y / scale) / 2) - 1;
	console.log('whattt ' + real_x + '/' + real_y);
    CLICK_HANDLER(real_x, real_y);
}

function sample_handler(x, y)
{
    alert('X : ' + x + " Y : " + y);
}

function initialize_map(tile_host, x, y, zoom, click_handler) {
    var mapOptions = {
        mapTypeControl: false,
        backgroundColor: "#1D475F",
        center: convert_grid_pos(x, y),
        zoom: zoom
    };
    TILE_HOST = tile_host;
    if ( click_handler != undefined ) {
        CLICK_HANDLER = click_handler;
    }
	map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
	// Now attach the grid map type to the map's registry
	map.mapTypes.set('grid', imageMapType);
	// We can now set the map to use the 'grid' map type
	map.setMapTypeId('grid');

	google.maps.event.addListener(map, 'click', handle_click);
}

function center_map(x, y, zoom)
{
	if ( zoom == undefined ) {
		zoom = 7;
	}

	map.panTo(convert_grid_pos(x, y));
	map.setZoom(zoom);
}

function load_region_by_pos(x, y)
{
    var data = {
        'x' : x,
        'y' : y
    };
    div_loader("view_coord", "#region_info", data);
	$("#search_results").dialog('close');
	$("#region_info").dialog('open');
}

function load_search_result(scene_id)
{
	var data = {
		'is_search' : true
	};
    div_loader("info/" + scene_id + "/inline", "#region_info", data);
	$("#region_info").dialog('open');
}
<|endoftext|>


<commit_before>;
var gauge_CpuFreq;          // #cpuContainer
var label_CpuFreq;          // #cpuValue
var label_CpuRange;         // #cpuLimits

function cpuFreq_OnReady() {

    gauge_CpuFreq = $("#cpuContainer");
    label_CpuRange = $("#cpuLimits");
    label_CpuFreq = $("#cpuValue");

    gauge_CpuFreq.jqxGauge({
        ranges: [
            { startValue: 100, endValue: 700, style: { fill: '#4bb648', stroke: '#4bb648' }, endWidth: 4, startWidth: 2 },
            { startValue: 700, endValue: 1000, style: { fill: '#fbd109', stroke: '#fbd109' }, endWidth: 6, startWidth: 4 },
            { startValue: 1000, endValue: 1300, style: { fill: '#ff8000', stroke: '#ff8000' }, endWidth: 8, startWidth: 6 },
            { startValue: 1300, endValue: 1600, style: { fill: '#e02629', stroke: '#e02629' }, endWidth: 10, startWidth: 8 }
        ],
        ticksMinor: { interval: 125/2, size: '4%' },
        ticksMajor: { interval: 250, size: '8%' },
        width: 259,
        height: 259,
        min: 100,
        max: 1600,
        value: 10,
        colorScheme: 'scheme05',
        animationDuration: 700,
        labels: {
            distance: '43%',
            position: 'none',
            interval: 250,
            offset: [0, -10],
            visible: true,
            formatValue: function (value) { return value + ""; }
        }
    });

    gauge_CpuFreq.on('valueChanging', function (e) {
        label_CpuFreq.html("CPU: " + Math.round(e.args.value) + ' MHz');
    });

    gauge_CpuFreq.jqxGauge('value', 50);

}
<commit_msg>fixed min of CPU Gauge<commit_after>;
var gauge_CpuFreq;          // #cpuContainer
var label_CpuFreq;          // #cpuValue
var label_CpuRange;         // #cpuLimits

function cpuFreq_OnReady() {

    gauge_CpuFreq = $("#cpuContainer");
    label_CpuRange = $("#cpuLimits");
    label_CpuFreq = $("#cpuValue");

    gauge_CpuFreq.jqxGauge({
        ranges: [
            { startValue: 100, endValue: 700, style: { fill: '#4bb648', stroke: '#4bb648' }, endWidth: 4, startWidth: 2 },
            { startValue: 700, endValue: 1000, style: { fill: '#fbd109', stroke: '#fbd109' }, endWidth: 6, startWidth: 4 },
            { startValue: 1000, endValue: 1300, style: { fill: '#ff8000', stroke: '#ff8000' }, endWidth: 8, startWidth: 6 },
            { startValue: 1300, endValue: 1600, style: { fill: '#e02629', stroke: '#e02629' }, endWidth: 10, startWidth: 8 }
        ],
        ticksMinor: { interval: 125/2, size: '4%' },
        ticksMajor: { interval: 250, size: '8%' },
        width: 259,
        height: 259,
        min: 60,
        max: 1600,
        value: 10,
        colorScheme: 'scheme05',
        animationDuration: 700,
        labels: {
            distance: '43%',
            position: 'none',
            interval: 250,
            offset: [0, -10],
            visible: true,
            formatValue: function (value) { return value + ""; }
        }
    });

    gauge_CpuFreq.on('valueChanging', function (e) {
        label_CpuFreq.html("CPU: " + Math.round(e.args.value) + ' MHz');
    });

    gauge_CpuFreq.jqxGauge('value', 50);

}
<|endoftext|>


<commit_before>// Chrome == Boolean(window.chrome)
// JSC == Safari == !/\n{2,}/.test(Function())
<commit_msg>Worked on browser detection<commit_after>/*
==================================================================================================
  Core - JavaScript Foundation
  Copyright 2013 Sebastian Werner
==================================================================================================
*/

"use strict";

(function(global, RegExp)
{
  var name = jasy.Env.getValue("engine");
  var version = null;
  var agent = navigator.userAgent.toLowerCase();

  if (jasy.Env.isSet("engine", "trident"))
  {
    if (/(msie) ([0-9.]+)/.exec(agent))
    {
      name = "ie";
      version = RegExp.$2;
    }
  }
  else if (jasy.Env.isSet("engine", "gecko"))
  {
    if (/(firefox)\/([0-9.]+)/.exec(agent))
    {
      name = RegExp.$1;
      version = RegExp.$2;
    }
  }
  else if (jasy.Env.isSet("engine", "webkit"))
  {
    // Behavior test first (differences between JS engines V8 vs. Nitro)
    if (!/\n{2,}/.test(Function()) && /version\/([0-9.]+)/.exec(agent))
    {
      name = "safari";
      version = RegExp.$1;
    }
    else if ((global.chrome || global.chromium) && (/opr\/([0-9.]+)/.exec(agent) || /(chrome)\/([0-9.]+)/.exec(agent)))
    {
      if (RegExp.$2)
      {
        name = "chrome";
        version = RegExp.$2;
      }
      else
      {
        name = "opera";
        version = RegExp.$1;
      }
    }
  }
  else if (jasy.Env.isSet("engine", "presto") && (/version\/([0-9.]+)/.exec(agent) || /opera ([0-9.]+)/.exec(agent)))
  {
    name = "opera";
    version = RegExp.$1;
  }

  var value = name;
  var major = null;

  if (version != null && version != "")
  {
    major = parseInt(version || "", 10);
    value += " " + major;
  }

  /**
   * Browser version info
   */
  core.Module("core.detect.Browser",
  {
    VALUE : value,
    VERSION : major,
    FULLVERSION : version,
    NAME : name
  });
})(core.Main.getGlobal(), RegExp);
  <|endoftext|>


<commit_before>enyo.kind({
  name: "MainMenuPane",
  classes: "enyo-unselectable",
  components: [
    // height necessary.
    { name: "menupane", kind: "rwatkins.MenuPane",
      style: "height: 100%; width: 100%;",
      onViewChange: "viewChangeHandler",
      onMenuOpen: "menuOpenHandler",
      onMenuClose: "menuCloseHandler",
      menu: [
        { content: "Men" + unescape("%FC"), classes: "menu-header" },
        { content: "Aktuell", view: "latest", classes: "menu-item latest" },
        { content: "Heute", view: "today", classes: "menu-item today" },
        { content: "Einstellungen", view: "settings", classes: "menu-item settings" },
        { content: "Impressum", view: "impressum", classes: "menu-item impressum" }
      ],
      components: [
        { name: "latest", classes: "view", components: [
            { name: "latestToolbar", kind: "Toolbar", header: "Aktuell", classes: "latest", onToggleMenu: "toolbarToggleMenuHandler", onHeader: "toolbarToggleMenuHandler" },
            { kind: "enyo.Scroller", strategyKind: "TouchScrollStrategy", components: [
              { kind: "LatestView", name: "latestView", classes: "content"}
            ]}
        ]},
        { name: "today", classes: "view", components: [
            { name: "todayToolbar", kind: "Toolbar", header: "Heute", classes: "today", onToggleMenu: "toolbarToggleMenuHandler", onHeader: "toolbarToggleMenuHandler" },
            { kind: "enyo.Scroller", strategyKind: "TouchScrollStrategy", components: [
              { kind: "TodayView", name: "todayView", classes: "content"}
            ]}
        ]},
        { name: "settings", classes: "view", components: [
            { name: "settingsToolbar", kind: "Toolbar", header: "Einstellungen", classes: "settings", onToggleMenu: "toolbarToggleMenuHandler", onHeader: "toolbarToggleMenuHandler" },
            { kind: "enyo.Scroller", strategyKind: "TouchScrollStrategy", components: [
              { kind: "SettingsView", name: "settingsView", classes: "content"}
            ]}
        ]},
        { name: "impressum", classes: "view", components: [
            { kind: "Toolbar", header: "Impressum", classes: "impressum", onToggleMenu: "toolbarToggleMenuHandler", onHeader: "toolbarToggleMenuHandler" },
            { kind: "enyo.Scroller", strategyKind: "TouchScrollStrategy", components: [
              { kind: "ImpressumView", name: "impressumView", classes: "content"}
            ]}
        ]}
      ]
    }
  ],
  //* @protected
  create: function() {
    this.inherited(arguments);
    // init model for selected location
    var locationId = localStorage.getItem("locationId");
    if (locationId == null) {
	locationId = 1;
    }
    var locationModel = new LocationModel({locationId: locationId});
    // init model for latestView
    var latestModel = new LatestModel({locationId: locationId});
    latestModel.fetch();
    this.$.latestView.set("latestModel", latestModel);
    // init todayView
    var date = new Date();
    this.$.todayToolbar.setHeader("Heute - " + date.getDate() + '.' + (date.getMonth()+1) + "." + date.getFullYear());
    var todayModel = new TodayModel();
    todayModel.addListener("change", function(record, event) {
      app.$.mainView.$.MainMenuPane.updateTodayView(record);
    }, false);
    todayModel.fetch();
    // init settingsview
    var settingsModel = new SettingsModel();
    settingsModel.fetch();
    this.$.settingsView.set("settingsModel", settingsModel);
    this.$.settingsView.set("locationModel", locationModel);
    this.$.settingsView.set("latestModel", latestModel);
    // init model for impressumView
    this.$.impressumView.set("appModel", new AppModel());
  },
  updateTodayView: function(record) {
    this.$.todayView.loadChart(record);
  },
  viewChangeHandler: function(inSender, inEvent) {
    this.log();
  },
  menuOpenHandler: function(inSender, inEvent) {
    this.log();
  },
  menuCloseHandler: function(inSender, inEvent) {
    this.log();
  },
  secondaryMenuOpenHandler: function(inSender, inEvent) {
    this.log();
  },
  secondaryMenuCloseHandler: function(inSender, inEvent) {
    this.log();
  },

  toolbarToggleMenuHandler: function(inSender, inEvent) {
    this.log();
    this.$.menupane.toggleMenu();
  },
  toolbarToggleSecondaryMenuHandler: function(inSender, inEvent) {
    this.log();
    this.$.menupane.toggleSecondaryMenu();
  }

});

enyo.kind({
	  name: "Toolbar",
	  kind: "onyx.Toolbar",
    classes: "toolbar",
	  published: {
	    header: ""
	  },
	  events: {
	    onHeader: "",
	    onToggleMenu: ""
	  },

	  components: [
	    { kind: "onyx.Grabber", ontap: "doToggleMenu", style: "float: left;" },
	    { name: "header", content: "", ontap: "doHeader", style: "padding-top: 4px" }
	  ],

	  create: function() {
	    this.inherited(arguments);
	    this.headerChanged();
	  },

	  headerChanged: function() {
	    this.$.header.setContent(this.getHeader());
	  }

});
<commit_msg>formatter<commit_after>enyo.kind({
  name: "MainMenuPane",
  classes: "enyo-unselectable",
  components: [
    // height necessary.
    { name: "menupane", kind: "rwatkins.MenuPane",
      style: "height: 100%; width: 100%;",
      onViewChange: "viewChangeHandler",
      onMenuOpen: "menuOpenHandler",
      onMenuClose: "menuCloseHandler",
      menu: [
        { content: "Men" + unescape("%FC"), classes: "menu-header" },
        { content: "Aktuell", view: "latest", classes: "menu-item latest" },
        { content: "Heute", view: "today", classes: "menu-item today" },
        { content: "Einstellungen", view: "settings", classes: "menu-item settings" },
        { content: "Impressum", view: "impressum", classes: "menu-item impressum" }
      ],
      components: [
        { name: "latest", classes: "view", components: [
            { name: "latestToolbar", kind: "Toolbar", header: "Aktuell", classes: "latest", onToggleMenu: "toolbarToggleMenuHandler", onHeader: "toolbarToggleMenuHandler" },
            { kind: "enyo.Scroller", strategyKind: "TouchScrollStrategy", components: [
              { kind: "LatestView", name: "latestView", classes: "content"}
            ]}
        ]},
        { name: "today", classes: "view", components: [
            { name: "todayToolbar", kind: "Toolbar", header: "Heute", classes: "today", onToggleMenu: "toolbarToggleMenuHandler", onHeader: "toolbarToggleMenuHandler" },
            { kind: "enyo.Scroller", strategyKind: "TouchScrollStrategy", components: [
              { kind: "TodayView", name: "todayView", classes: "content"}
            ]}
        ]},
        { name: "settings", classes: "view", components: [
            { name: "settingsToolbar", kind: "Toolbar", header: "Einstellungen", classes: "settings", onToggleMenu: "toolbarToggleMenuHandler", onHeader: "toolbarToggleMenuHandler" },
            { kind: "enyo.Scroller", strategyKind: "TouchScrollStrategy", components: [
              { kind: "SettingsView", name: "settingsView", classes: "content"}
            ]}
        ]},
        { name: "impressum", classes: "view", components: [
            { kind: "Toolbar", header: "Impressum", classes: "impressum", onToggleMenu: "toolbarToggleMenuHandler", onHeader: "toolbarToggleMenuHandler" },
            { kind: "enyo.Scroller", strategyKind: "TouchScrollStrategy", components: [
              { kind: "ImpressumView", name: "impressumView", classes: "content"}
            ]}
        ]}
      ]
    }
  ],
  //* @protected
  create: function() {
    this.inherited(arguments);
    // init model for selected location
    var locationId = localStorage.getItem("locationId");
    if (locationId == null) {
      locationId = 1;
    }
    var locationModel = new LocationModel({locationId: locationId});
    // init model for latestView
    var latestModel = new LatestModel({locationId: locationId});
    latestModel.fetch();
    this.$.latestView.set("latestModel", latestModel);
    // init todayView
    var date = new Date();
    this.$.todayToolbar.setHeader("Heute - " + date.getDate() + '.' + (date.getMonth()+1) + "." + date.getFullYear());
    var todayModel = new TodayModel();
    todayModel.addListener("change", function(record, event) {
      app.$.mainView.$.MainMenuPane.updateTodayView(record);
    }, false);
    todayModel.fetch();
    // init settingsview
    var settingsModel = new SettingsModel();
    settingsModel.fetch();
    this.$.settingsView.set("settingsModel", settingsModel);
    this.$.settingsView.set("locationModel", locationModel);
    this.$.settingsView.set("latestModel", latestModel);
    // init model for impressumView
    this.$.impressumView.set("appModel", new AppModel());
  },
  updateTodayView: function(record) {
    this.$.todayView.loadChart(record);
  },
  viewChangeHandler: function(inSender, inEvent) {
    this.log();
  },
  menuOpenHandler: function(inSender, inEvent) {
    this.log();
  },
  menuCloseHandler: function(inSender, inEvent) {
    this.log();
  },
  secondaryMenuOpenHandler: function(inSender, inEvent) {
    this.log();
  },
  secondaryMenuCloseHandler: function(inSender, inEvent) {
    this.log();
  },

  toolbarToggleMenuHandler: function(inSender, inEvent) {
    this.log();
    this.$.menupane.toggleMenu();
  },
  toolbarToggleSecondaryMenuHandler: function(inSender, inEvent) {
    this.log();
    this.$.menupane.toggleSecondaryMenu();
  }

});

enyo.kind({
	  name: "Toolbar",
	  kind: "onyx.Toolbar",
    classes: "toolbar",
	  published: {
	    header: ""
	  },
	  events: {
	    onHeader: "",
	    onToggleMenu: ""
	  },

	  components: [
	    { kind: "onyx.Grabber", ontap: "doToggleMenu", style: "float: left;" },
	    { name: "header", content: "", ontap: "doHeader", style: "padding-top: 4px" }
	  ],

	  create: function() {
	    this.inherited(arguments);
	    this.headerChanged();
	  },

	  headerChanged: function() {
	    this.$.header.setContent(this.getHeader());
	  }

});
<|endoftext|>


<commit_before>import Webiny from 'Webiny';

class FileReader extends Webiny.Ui.Component {

    constructor(props) {
        super(props);

        this.bindMethods('onChange', 'getFiles', 'readFiles');
    }

    getFiles() {
        ReactDOM.findDOMNode(this).click();
    }

    onChange(e) {
        this.readFiles(e.target.files);
    }

    readFiles(files) {
        const output = [];
        const errors = [];
        let loadedFiles = 0;

        _.each(files, file => {
            const reader = new window.FileReader();

            reader.onload = ((f) => {
                return (e) => {
                    loadedFiles++;
                    const data = {
                        name: f.name,
                        size: f.size,
                        type: f.type
                    };

                    let errorMessage = null;
                    if (this.props.accept.length && this.props.accept.indexOf(file.type) === -1) {
                        errorMessage = 'Unsupported file type (' + file.type + ')';
                    } else if (this.props.sizeLimit < file.size) {
                        errorMessage = 'File is too big';
                    }

                    if (!errorMessage) {
                        data.src = e.target.result;
                        output.push(data);
                    } else {
                        data.message = errorMessage;
                        errors.push(data);
                    }

                    if (loadedFiles === files.length) {
                        this.props.onChange.apply(this, this.props.multiple ? [output, errors] : [output[0] || null, errors[0] || null]);
                        ReactDOM.findDOMNode(this).value = null;
                    }
                };
            })(file);

            reader.readAsDataURL(file);
        });
    }
}

FileReader.defaultProps = {
    accept: '',
    multiple: false,
    sizeLimit: 2097152, // 10485760
    renderer() {
        return (
            <input
                accept={this.props.accept}
                style={{display: 'none'}}
                type="file"
                multiple={this.props.multiple}
                onChange={this.onChange}/>
        );
    }
};

export default FileReader;<commit_msg>eslint<commit_after>import Webiny from 'Webiny';

class FileReader extends Webiny.Ui.Component {

	constructor(props) {
		super(props);

		this.bindMethods('onChange', 'getFiles', 'readFiles');
	}

	getFiles() {
		ReactDOM.findDOMNode(this).click();
	}

	onChange(e) {
		this.readFiles(e.target.files);
	}

	readFiles(files) {
		const output = [];
		const errors = [];
		let loadedFiles = 0;

		_.each(files, file => {
			const reader = new window.FileReader();

			reader.onload = ((f) => {
				return (e) => {
					loadedFiles++;
					const data = {
						name: f.name,
						size: f.size,
						type: f.type
					};

					let errorMessage = null;
					if (this.props.accept.length && this.props.accept.indexOf(file.type) === -1) {
						errorMessage = 'Unsupported file type (' + file.type + ')';
					} else if (this.props.sizeLimit < file.size) {
						errorMessage = 'File is too big';
					}

					if (!errorMessage) {
						data.src = e.target.result;
						output.push(data);
					} else {
						data.message = errorMessage;
						errors.push(data);
					}

					if (loadedFiles === files.length) {
						this.props.onChange.apply(this, this.props.multiple ? [output, errors] : [output[0] || null, errors[0] || null]);
						ReactDOM.findDOMNode(this).value = null;
					}
				};
			})(file);

			reader.readAsDataURL(file);
		});
	}
}

FileReader.defaultProps = {
	accept: '',
	multiple: false,
	sizeLimit: 2097152, // 10485760
	renderer() {
		return (
			<input
				accept={this.props.accept}
				style={{display: 'none'}}
				type="file"
				multiple={this.props.multiple}
				onChange={this.onChange}/>
		);
	}
};

export default FileReader;<|endoftext|>


<commit_before>/**
enyo.TouchScroller is a touch based scroller that integrates the scrolling simulation provided
by enyo.ScrollMath
into a Control.

enyo.ScrollMath is not typically created in application code.
*/
enyo.kind({
	name: "enyo.TouchScrollStrategy",
	kind: enyo.ScrollStrategy,
	/**
		If true, the scroller will not propagate dragstart events that cause it to start scrolling (defaults to true)
	*/
	preventDragPropagation: true,
	events: {
		onScrollStart: "doScrollStart",
		onScroll: "doScroll",
		onScrollStop: "doScrollStop"
	},
	//* @protected
	handlers: {
		flick: "flickHandler",
		hold: "holdHandler",
		dragstart: "dragstartHandler",
		drag: "dragHandler",
		dragfinish: "dragfinishHandler",
		mousewheel: "mousewheelHandler",
		touchmove: "touchmoveHandler"
	},
	classes: "enyo-touch-scroller",
	components: [
		{name: "scroll", kind: "ScrollMath"},
		{name: "client", classes: "enyo-fit enyo-touch-scroller", attributes: {"onscroll": enyo.bubbler}}
	],
	horizontalChanged: function() {
		this.$.scroll.horizontal = this.horizontal;
	},
	verticalChanged: function() {
		this.$.scroll.vertical = this.vertical;
	},
	calcScrollNode: function() {
		return this.$.client.hasNode();
	},
	calcAutoScrolling: function() {
		var v = this.vertical == "auto";
		var h = this.horizontal == "auto";
		if ((v || h) && this.scrollNode) {
			var b = this.getBounds();
			if (v) {
				this.$.scroll.vertical = this.node.scrollHeight > b.height;
			}
			if (h) {
				this.$.scroll.horizontal = this.node.scrollWidth > b.width;
			}
		}
	},
	shouldDrag: function(e) {
		var requestV = e.vertical;
		var canH = this.$.scroll.horizontal;
		var canV = this.$.scroll.vertical;
		return requestV && canV || !requestV && canH;
	},
	flickHandler: function(inSender, e) {
		var onAxis = Math.abs(e.xVelocity) > Math.abs(e.yVelocity) ? this.horizontal : this.vertical;
		if (onAxis) {
			this.$.scroll.flick(e);
			return this.preventDragPropagation;
		}
	},
	holdHandler: function(inSender, e) {
		if (this.$.scroll.isScrolling() && !this.$.scroll.isInOverScroll()) {
			this.$.scroll.stop(e);
			return true;
		}
	},
	touchmoveHandler: function(inSender, e) {
		e.preventDefault();
	},
	// special synthetic DOM events served up by the Gesture system
	dragstartHandler: function(inSender, inEvent) {
		this.calcAutoScrolling();
		this.dragging = this.shouldDrag(inEvent);
		if (this.dragging) {
			this.$.scroll.startDrag(inEvent);
			if (this.preventDragPropagation) {
				return true;
			}
		}
	},
	dragHandler: function(inSender, inEvent) {
		if (this.dragging) {
			this.$.scroll.drag(inEvent);
		}
	},
	dragfinishHandler: function(inSender, inEvent) {
		if (this.dragging) {
			inEvent.preventTap();
			this.$.scroll.dragFinish();
			this.dragging = false;
		}
	},
	mousewheelHandler: function(inSender, e) {
		if (!this.dragging && this.$.scroll.mousewheel(e)) {
			e.preventDefault();
			return true;
		}
	},
	scrollStart: function(inSender) {
		if (this.scrollNode) {
			var b = this.$.client.getBounds();
			inSender.bottomBoundary = b.height - this.scrollNode.scrollHeight;
			inSender.rightBoundary = b.width - this.scrollNode.scrollWidth;
			this.doScrollStart(inSender);
		}
	},
	scroll: function(inSender) {
		this.effectScroll(-inSender.x, -inSender.y);
		this.doScroll(inSender);
	},
	scrollStop: function(inSender) {
		this.effectOverscroll(null, null);
		this.doScrollStop(inSender);
	},
	setScrollLeft: function() {
		this.inherited(arguments);
		var s = this.$.scroll;
		s.x = s.x0 = -this.getScrollLeft();
	},
	setScrollTop: function() {
		this.inherited(arguments);
		var s = this.$.scroll;
		s.y = s.y0 = -this.getScrollTop();;
	},
	effectScroll: function(inX, inY) {
		if (this.scrollNode) {
			this.scrollNode.scrollLeft = inX;
			this.scrollNode.scrollTop = inY;
			this.effectOverscroll(inX, inY);
		}
	},
	effectOverscroll: function(inX, inY) {
		var n = this.scrollNode;
		var o = "";
		if (inY != n.scrollTop && inY !== null) {
			o += " translateY(" + (n.scrollTop - inY) + "px)";
		}
		if (inX != n.scrollLeft && inX !== null) {
			o += " translateX(" + (n.scrollLeft - inX) + "px)";
		}
		if (n) {
			var s = n.style;
			s.webkitTransform = s.MozTransform = s.msTransform = s.transform = o;
		}
	}
});
<commit_msg>* syncronize scroll math with automatic scrolling. * correct auto scroll calculation typo * prevent overscroll code from jumping in when scroller is in range.<commit_after>/**
enyo.TouchScroller is a touch based scroller that integrates the scrolling simulation provided
by enyo.ScrollMath
into a Control.

enyo.ScrollMath is not typically created in application code.
*/
enyo.kind({
	name: "enyo.TouchScrollStrategy",
	kind: enyo.ScrollStrategy,
	/**
		If true, the scroller will not propagate dragstart events that cause it to start scrolling (defaults to true)
	*/
	preventDragPropagation: true,
	events: {
		onScrollStart: "doScrollStart",
		onScroll: "doScroll",
		onScrollStop: "doScrollStop"
	},
	//* @protected
	handlers: {
		flick: "flickHandler",
		hold: "holdHandler",
		dragstart: "dragstartHandler",
		drag: "dragHandler",
		dragfinish: "dragfinishHandler",
		mousewheel: "mousewheelHandler",
		touchmove: "touchmoveHandler"
	},
	classes: "enyo-touch-scroller",
	components: [
		{name: "scroll", kind: "ScrollMath"},
		{name: "client", classes: "enyo-fit enyo-touch-scroller", attributes: {"onscroll": enyo.bubbler}}
	],
	rendered: function() {
		this.inherited(arguments);
		this.syncScrollMath();
	},
	scrollHandler: function() {
		this.syncScrollMath();
	},
	horizontalChanged: function() {
		this.$.scroll.horizontal = this.horizontal;
	},
	verticalChanged: function() {
		this.$.scroll.vertical = this.vertical;
	},
	calcScrollNode: function() {
		return this.$.client.hasNode();
	},
	calcAutoScrolling: function() {
		var v = this.vertical == "auto";
		var h = this.horizontal == "auto";
		if ((v || h) && this.scrollNode) {
			var b = this.getBounds();
			if (v) {
				this.$.scroll.vertical = this.scrollNode.scrollHeight > b.height;
			}
			if (h) {
				this.$.scroll.horizontal = this.scrollNode.scrollWidth > b.width;
			}
		}
	},
	shouldDrag: function(e) {
		var requestV = e.vertical;
		var canH = this.$.scroll.horizontal;
		var canV = this.$.scroll.vertical;
		return requestV && canV || !requestV && canH;
	},
	flickHandler: function(inSender, e) {
		var onAxis = Math.abs(e.xVelocity) > Math.abs(e.yVelocity) ? this.horizontal : this.vertical;
		if (onAxis) {
			this.$.scroll.flick(e);
			return this.preventDragPropagation;
		}
	},
	holdHandler: function(inSender, e) {
		if (this.$.scroll.isScrolling() && !this.$.scroll.isInOverScroll()) {
			this.$.scroll.stop(e);
			return true;
		}
	},
	touchmoveHandler: function(inSender, e) {
		e.preventDefault();
	},
	// special synthetic DOM events served up by the Gesture system
	dragstartHandler: function(inSender, inEvent) {
		this.calcAutoScrolling();
		this.dragging = this.shouldDrag(inEvent);
		if (this.dragging) {
			this.$.scroll.startDrag(inEvent);
			if (this.preventDragPropagation) {
				return true;
			}
		}
	},
	dragHandler: function(inSender, inEvent) {
		if (this.dragging) {
			this.$.scroll.drag(inEvent);
		}
	},
	dragfinishHandler: function(inSender, inEvent) {
		if (this.dragging) {
			inEvent.preventTap();
			this.$.scroll.dragFinish();
			this.dragging = false;
		}
	},
	mousewheelHandler: function(inSender, e) {
		if (!this.dragging && this.$.scroll.mousewheel(e)) {
			e.preventDefault();
			return true;
		}
	},
	scrollStart: function(inSender) {
		if (this.scrollNode) {
			var b = this.$.client.getBounds();
			inSender.bottomBoundary = b.height - this.scrollNode.scrollHeight;
			inSender.rightBoundary = b.width - this.scrollNode.scrollWidth;
			this.doScrollStart(inSender);
		}
	},
	scroll: function(inSender) {
		this.effectScroll(-inSender.x, -inSender.y);
		this.doScroll(inSender);
	},
	scrollStop: function(inSender) {
		this.effectOverscroll(null, null);
		this.doScrollStop(inSender);
	},
	syncScrollMath: function() {
		var s = this.$.scroll;
		if (!s.isScrolling()) {
			s.setScrollX(-this.getScrollLeft());
			s.setScrollY(-this.getScrollTop());
		}
	},
	effectScroll: function(inX, inY) {
		if (this.scrollNode) {
			this.scrollNode.scrollLeft = inX;
			this.scrollNode.scrollTop = inY;
			this.effectOverscroll(Math.round(inX), Math.round(inY));
		}
	},
	effectOverscroll: function(inX, inY) {
		var n = this.scrollNode;
		var o = "";
		if (inY !== null && inY - n.scrollTop > 1) {
			o += " translateY(" + (n.scrollTop - inY) + "px)";
		}
		if (inX !== null && inX - n.scrollLeft > 1) {
			o += " translateX(" + (n.scrollLeft - inX) + "px)";
		}
		if (n) {
			var s = n.style;
			s.webkitTransform = s.MozTransform = s.msTransform = s.transform = o;
		}
	}
});
<|endoftext|>


<commit_before>var {removeMidItemFromArray } = require('../questions/removeMidItemFromArray.js');

describe('移除一个数组中位于中间的元素', function(){
    it('检查未给定数组的情况', function(){
        var result = removeMidItemFromArray();
        expect(result).toBe(undefined);
    });
});<commit_msg>add the sepc file for the remove middle item from an array<commit_after>var {removeMidItemFromArray } = require('../questions/removeMidItemFromArray.js');

describe('移除一个数组中位于中间的元素', function(){
    it('检查未给定数组的情况', function(){
        var result = removeMidItemFromArray();
        expect(result).toBe(undefined);
    });
    it('给定一个空数组的情况', function(){
        var result = removeMidItemFromArray([]);
        expect(result).toEqual([]);
    });
    it('给定数组中只有一个元素的情况', function(){
        var result = removeMidItemFromArray([1]);
        expect(result).toEqual([]);
    });
    it('给定数组中有两个元素的情况', function(){
        var result = removeMidItemFromArray([1,2]);
        expect(result).toEqual([]);
    });
    it('给定数组中有三个元素的情况', function(){
        var result = removeMidItemFromArray([1,2,3]);
        expect(result).toEqual([1,3]);
    });
    it('给定数组中有四个元素的情况', function(){
        var result = removeMidItemFromArray([1,2,3,4]);
        expect(result).toEqual([1,4]);
    });
});<|endoftext|>


<commit_before>// Queue
//

var lib = require('./lib')
  , util = require('util')
  , couch = require('./couch')
  , assert = require('assert')
  , message = require('./message')
  , queue_ddoc = require('./ddoc')
  , querystring = require('querystring')
  ;

//
// Constants
//

var DEFAULT_VISIBILITY_TIMEOUT = 30;
var QUEUE_DDOC_ID_RE           = /^_design\/CQS\/([a-zA-Z0-9_-]{1,80})$/;

//
// API
//

function Queue (opts) {
  var self = this;

  self.name = opts.name || opts.QueueName || opts._str || null;
  self.time_C = opts.time_C || null;
  self.db = new couch.Database({'couch':opts.couch, 'db':opts.db, time_C:self.time_C});

  self.VisibilityTimeout = opts.DefaultVisibilityTimeout || opts.VisibilityTimeout || DEFAULT_VISIBILITY_TIMEOUT;

  self.cache_confirmation = true;

  self.log = lib.log4js().getLogger('queue/' + (self.name || 'untitled'));
  self.log.setLevel(lib.LOG_LEVEL);
}

Queue.prototype.confirm =
Queue.prototype.confirmed = function after_confirmed(opt, callback) {
  var self = this;

  if(!callback && typeof opt === 'function') {
    callback = opt;
    opt = '';
  }

  assert.ok(callback);
  assert.ok(self.db);

  self.db.confirmed(function(er) {
    if(er)
      return callback(er);

    var confirmer = self.db.known_queues[self.name];
    if(!confirmer || opt === '--force' || !self.cache_confirmation)
      confirmer = self.db.known_queues[self.name] = new lib.Once;

    confirmer.on_done(function(er, ddoc) {
      if(er)
        return callback(er);

      // Copy all attributes from the API.
      self.import_ddoc(ddoc);
      return callback(null, self);
    })

    confirmer.job(confirm_queue);
  })

  function confirm_queue(done) {
    var doc_id = new queue_ddoc.DDoc(self)._id;
    self.log.debug('Confirming queue: ' + doc_id);
    self.db.request(lib.enc_id(doc_id), function(er, resp, ddoc) {
      done(er, ddoc);
    })
  }
}

Queue.prototype.create = function create_queue(callback) {
  var self = this;
  assert.ok(callback);

  var ddoc = new queue_ddoc.DDoc(self);
  if(self.skip_browser)
    go();
  else
    ddoc.add_browser(go);

  function go(er) {
    if(er) return callback(er);

    var req = { method: 'PUT'
              , uri   : lib.enc_id(ddoc._id)
              , json  : ddoc
              }

    //console.error('Storing\n' + util.inspect(ddoc));
    self.db.request(req, function(er, resp, body) {
      if(er) return callback(er);

      // Consider myself confirmed as well.
      self.db.known_queues[self.name] = new lib.Once;
      self.db.known_queues[self.name].job(function(done) { done(null, ddoc) });
      self.import_ddoc(ddoc);
      return callback(null, self.name);
    })
  }
}

Queue.prototype.import_ddoc = function(ddoc) {
  var self = this;
  self.ddoc_id = ddoc._id;
  self.ddoc_rev = ddoc._rev;
  lib.copy(ddoc, self, 'uppercase');
}

Queue.prototype.send = function send_message(opts, extra, callback) {
  var self = this;

  if(!callback && typeof extra === 'function') {
    callback = extra;
    extra = null;
  }

  self.confirmed(function(er) {
    if(er) return callback(er);

    opts = lib.opt_def(opts);
    var body = opts._str || opts;
    var msg = new message.Message({ 'couch'  : self.couch
                                  , 'db'     : self.db
                                  , 'queue'  : self
                                  , 'IdExtra': extra
                                  , 'Body'   : body
                                  });
    msg.send(callback);
  })
}

Queue.prototype.receive = function receive_message(opts, callback) {
  var self = this;

  if(typeof opts === 'function') {
    callback = opts;
    opts = 1;
  }

  if(typeof opts === 'number')
    opts = {'MaxNumberOfMessages': opts};

  var msg_count   = opts.MaxNumberOfMessages || 1;
  var vis_timeout = opts.VisibilityTimeout || self.VisibilityTimeout;

  assert.ok(msg_count > 0  , "Message count is too low");
  assert.ok(msg_count <= 10, "Message count is too high");
  assert.ok(vis_timeout >= 0, "Visibility timeout is too low");
  assert.ok(vis_timeout <= 43200, "Visibility timeout is too high");

  self.confirmed(function(er) {
    if(er) return callback(er);

    var startkey = lib.JS([ "" ]);
    var endkey   = lib.JS([ new Date ]); // Anything becoming visible up to now.
    var query = querystring.stringify({ reduce: false
                                      , limit : msg_count
                                      , startkey: startkey
                                      , endkey: endkey
                                      });
    var path = lib.enc_id(self.ddoc_id) + '/_view/visible_at?' + query;
    self.db.request(path, function(er, resp, view) {
      if(er) return callback(er);

      if(view.rows.length === 0)
        return callback(null, []);

      // Don't lose the order CouchDB set for the messages.
      var messages = [], count = 0;
      function on_receive(er, pos, msg) {
        if(er)
          self.log.error('Receive error', er);

        messages[pos] = msg || null;

        count += 1;
        if(count === view.rows.length) {
          messages = messages.filter(function(x) { return !!x });
          callback(null, messages);
        }
      }

      view.rows.forEach(function(row, i) {
        var match = new RegExp('^CQS/' + self.name + '/' + '(.+)$').exec(row.value._id);
        assert.ok(match, "Bad view row: " + lib.JS(row));

        var msg_opts = {};
        lib.copy(row.value, msg_opts, 'uppercase');
        msg_opts.MessageId = match[1];

        var msg = new message.Message(msg_opts);
        msg.queue = self;
        msg.mvcc = {'_id':row.value._id, '_rev':row.value._rev};
        msg.receive(function(er) { on_receive(er, i, msg) });
      })
    })
  })
}

Queue.prototype.set = function set_attrs(opts, callback) {
  var self = this;
  assert.ok(opts);
  assert.ok(callback);
  assert.equal(typeof opts, 'object');

  self.log.debug('Set attributes: ' + self.name);
  self.confirmed('--force', function(er) {
    if(er) return callback(er);

    var ddoc = new queue_ddoc.DDoc(self);
    ddoc._rev = self.ddoc_rev;
    lib.copy(opts, ddoc, 'uppercase');

    if(self.skip_browser)
      go();
    else
      ddoc.add_browser(go);

    function go(er) {
      if(er) return callback(er);

      var req = { method: 'PUT'
                , uri   : lib.enc_id(ddoc._id)
                , json  : ddoc
                }
      self.db.request(req, function(er, resp, body) {
        if(er) return callback(er);

        // SetAttributes was committed, consider myself confirmed as well.
        self.db.known_queues[self.name] = new lib.Once;
        self.db.known_queues[self.name].job(function(done) { done(null, ddoc) });
        self.import_ddoc(ddoc);
        return callback(null);
      })
    }
  })
}

Queue.prototype.GetAttributes = function get_attrs(attrs, callback, extra) {
  var self = this;

  if(!callback && typeof attrs === 'function') {
    callback = attrs;
    attrs = null;
  }

  var confirmer = function(cb) { return self.confirmed(cb) };
  if(attrs === '--force') {
    confirmer = function(cb) { return self.confirmed('--force', cb) };
    attrs = callback;
    callback = extra;
  }

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

  attrs = attrs || ['all'];
  assert.ok(Array.isArray(attrs));
  assert.ok(callback);

  self.log.debug('Get attributes: ' + self.name);
  confirmer(function(er) {
    if(er) return callback(er);
    callback(null, self);
  })
}

function create_queue(opts, cb) {
  var queue = new Queue(opts);
  queue.create(function(er, name) {
    if(er) return cb(er);
    return cb(null, queue);
  })
}

function list_queues(opts, cb) {
  var prefix = opts.prefix || opts._str;

  if(!cb && opts._func)
    cb = opts._func;

  var startkey = '_design/CQS\/';
  var endkey   = '_design/CQS\/';

  if(prefix) {
    startkey += prefix;
    endkey   += prefix;
  }

  endkey += '\ufff0';

  var query = { startkey: lib.JS(startkey)
              , endkey  : lib.JS(endkey)
              };

  var db_url = opts.couch + '/' + opts.db;
  var view = db_url + '/_all_docs?' + querystring.stringify(query);
  lib.req_json({uri:view, time_C:opts.time_C}, function(er, resp, view) {
    if(er) return cb(er);

    function get_queue(row) {
      return new Queue({ couch: opts.couch
                       , db   : opts.db
                       , name : id_to_name(row.id)
                       , time_C: opts.time_C
                       })
    }

    var queues = view.rows.map(get_queue);
    return cb(null, queues);
  })
}

function set_attributes(queue, attrs, callback) {
  return queue.set(attrs, callback);
}

function get_attributes(opts, attrs, callback, extra) {
  var queue = (opts instanceof Queue) ? opts : new Queue(opts);
  return queue.GetAttributes(attrs, callback, extra);
}

function send_message(opts, message, extra, callback) {
  var queue;
  if(opts instanceof Queue)
    queue = opts;
  else if(opts.queue) {
    if(opts.queue instanceof Queue)
      queue = opts.queue
    else
      queue = new Queue({'QueueName':opts.queue, 'couch':opts.couch, 'db':opts.db});
  }
  else
    queue = new Queue(opts);

  if(!callback && typeof extra === 'function') {
    callback = extra;
    extra = null;
  }

  return queue.send(message, extra, callback);
}

function receive_message(opts, callback, extra) {
  var queue;
  if(opts instanceof Queue)
    queue = opts;
  else if(opts._str || opts.queue) {
    if(opts.queue instanceof Queue)
      queue = opts.queue;
    else
      queue = new Queue({'QueueName':opts._str || opts.queue, 'couch':opts.couch, 'db':opts.db});
    delete opts.queue;
    delete opts._str;
  } else
    Queue = new Queue(opts);

  if(typeof callback === 'number' && typeof extra === 'function') {
    opts= { 'MaxNumberOfMessages': callback };
    callback = extra;
  }

  assert.ok(callback);
  return queue.receive(opts, callback);
}

module.exports = { "Queue" : Queue
                 , "create": create_queue
                 , "list"  : list_queues
                 , "send"  : send_message
                 , "receive": receive_message
                 , "set"   : set_attributes
                 , "get"   : get_attributes
                 };

//
// Utilities
//

function id_to_name(id) {
  var match = QUEUE_DDOC_ID_RE.exec(id);
  if(!match)
    throw new Error("Unknown queue ddoc id: " + id);
  return match[1];
}
<commit_msg>Do not repeat function names<commit_after>// Queue
//

var lib = require('./lib')
  , util = require('util')
  , couch = require('./couch')
  , assert = require('assert')
  , message = require('./message')
  , queue_ddoc = require('./ddoc')
  , querystring = require('querystring')
  ;

//
// Constants
//

var DEFAULT_VISIBILITY_TIMEOUT = 30;
var QUEUE_DDOC_ID_RE           = /^_design\/CQS\/([a-zA-Z0-9_-]{1,80})$/;

//
// API
//

function Queue (opts) {
  var self = this;

  self.name = opts.name || opts.QueueName || opts._str || null;
  self.time_C = opts.time_C || null;
  self.db = new couch.Database({'couch':opts.couch, 'db':opts.db, time_C:self.time_C});

  self.VisibilityTimeout = opts.DefaultVisibilityTimeout || opts.VisibilityTimeout || DEFAULT_VISIBILITY_TIMEOUT;

  self.cache_confirmation = true;

  self.log = lib.log4js().getLogger('queue/' + (self.name || 'untitled'));
  self.log.setLevel(lib.LOG_LEVEL);
}

Queue.prototype.confirm =
Queue.prototype.confirmed = function after_confirmed(opt, callback) {
  var self = this;

  if(!callback && typeof opt === 'function') {
    callback = opt;
    opt = '';
  }

  assert.ok(callback);
  assert.ok(self.db);

  self.db.confirmed(function(er) {
    if(er)
      return callback(er);

    var confirmer = self.db.known_queues[self.name];
    if(!confirmer || opt === '--force' || !self.cache_confirmation)
      confirmer = self.db.known_queues[self.name] = new lib.Once;

    confirmer.on_done(function(er, ddoc) {
      if(er)
        return callback(er);

      // Copy all attributes from the API.
      self.import_ddoc(ddoc);
      return callback(null, self);
    })

    confirmer.job(confirm_queue);
  })

  function confirm_queue(done) {
    var doc_id = new queue_ddoc.DDoc(self)._id;
    self.log.debug('Confirming queue: ' + doc_id);
    self.db.request(lib.enc_id(doc_id), function(er, resp, ddoc) {
      done(er, ddoc);
    })
  }
}

Queue.prototype.create = function create_queue(callback) {
  var self = this;
  assert.ok(callback);

  var ddoc = new queue_ddoc.DDoc(self);
  if(self.skip_browser)
    go();
  else
    ddoc.add_browser(go);

  function go(er) {
    if(er) return callback(er);

    var req = { method: 'PUT'
              , uri   : lib.enc_id(ddoc._id)
              , json  : ddoc
              }

    //console.error('Storing\n' + util.inspect(ddoc));
    self.db.request(req, function(er, resp, body) {
      if(er) return callback(er);

      // Consider myself confirmed as well.
      self.db.known_queues[self.name] = new lib.Once;
      self.db.known_queues[self.name].job(function(done) { done(null, ddoc) });
      self.import_ddoc(ddoc);
      return callback(null, self.name);
    })
  }
}

Queue.prototype.import_ddoc = function(ddoc) {
  var self = this;
  self.ddoc_id = ddoc._id;
  self.ddoc_rev = ddoc._rev;
  lib.copy(ddoc, self, 'uppercase');
}

Queue.prototype.send = function(opts, extra, callback) {
  var self = this;

  if(!callback && typeof extra === 'function') {
    callback = extra;
    extra = null;
  }

  self.confirmed(function(er) {
    if(er) return callback(er);

    opts = lib.opt_def(opts);
    var body = opts._str || opts;
    var msg = new message.Message({ 'couch'  : self.couch
                                  , 'db'     : self.db
                                  , 'queue'  : self
                                  , 'IdExtra': extra
                                  , 'Body'   : body
                                  });
    msg.send(callback);
  })
}

Queue.prototype.receive = function(opts, callback) {
  var self = this;

  if(typeof opts === 'function') {
    callback = opts;
    opts = 1;
  }

  if(typeof opts === 'number')
    opts = {'MaxNumberOfMessages': opts};

  var msg_count   = opts.MaxNumberOfMessages || 1;
  var vis_timeout = opts.VisibilityTimeout || self.VisibilityTimeout;

  assert.ok(msg_count > 0  , "Message count is too low");
  assert.ok(msg_count <= 10, "Message count is too high");
  assert.ok(vis_timeout >= 0, "Visibility timeout is too low");
  assert.ok(vis_timeout <= 43200, "Visibility timeout is too high");

  self.confirmed(function(er) {
    if(er) return callback(er);

    var startkey = lib.JS([ "" ]);
    var endkey   = lib.JS([ new Date ]); // Anything becoming visible up to now.
    var query = querystring.stringify({ reduce: false
                                      , limit : msg_count
                                      , startkey: startkey
                                      , endkey: endkey
                                      });
    var path = lib.enc_id(self.ddoc_id) + '/_view/visible_at?' + query;
    self.db.request(path, function(er, resp, view) {
      if(er) return callback(er);

      if(view.rows.length === 0)
        return callback(null, []);

      // Don't lose the order CouchDB set for the messages.
      var messages = [], count = 0;
      function on_receive(er, pos, msg) {
        if(er)
          self.log.error('Receive error', er);

        messages[pos] = msg || null;

        count += 1;
        if(count === view.rows.length) {
          messages = messages.filter(function(x) { return !!x });
          callback(null, messages);
        }
      }

      view.rows.forEach(function(row, i) {
        var match = new RegExp('^CQS/' + self.name + '/' + '(.+)$').exec(row.value._id);
        assert.ok(match, "Bad view row: " + lib.JS(row));

        var msg_opts = {};
        lib.copy(row.value, msg_opts, 'uppercase');
        msg_opts.MessageId = match[1];

        var msg = new message.Message(msg_opts);
        msg.queue = self;
        msg.mvcc = {'_id':row.value._id, '_rev':row.value._rev};
        msg.receive(function(er) { on_receive(er, i, msg) });
      })
    })
  })
}

Queue.prototype.set = function set_attrs(opts, callback) {
  var self = this;
  assert.ok(opts);
  assert.ok(callback);
  assert.equal(typeof opts, 'object');

  self.log.debug('Set attributes: ' + self.name);
  self.confirmed('--force', function(er) {
    if(er) return callback(er);

    var ddoc = new queue_ddoc.DDoc(self);
    ddoc._rev = self.ddoc_rev;
    lib.copy(opts, ddoc, 'uppercase');

    if(self.skip_browser)
      go();
    else
      ddoc.add_browser(go);

    function go(er) {
      if(er) return callback(er);

      var req = { method: 'PUT'
                , uri   : lib.enc_id(ddoc._id)
                , json  : ddoc
                }
      self.db.request(req, function(er, resp, body) {
        if(er) return callback(er);

        // SetAttributes was committed, consider myself confirmed as well.
        self.db.known_queues[self.name] = new lib.Once;
        self.db.known_queues[self.name].job(function(done) { done(null, ddoc) });
        self.import_ddoc(ddoc);
        return callback(null);
      })
    }
  })
}

Queue.prototype.GetAttributes = function get_attrs(attrs, callback, extra) {
  var self = this;

  if(!callback && typeof attrs === 'function') {
    callback = attrs;
    attrs = null;
  }

  var confirmer = function(cb) { return self.confirmed(cb) };
  if(attrs === '--force') {
    confirmer = function(cb) { return self.confirmed('--force', cb) };
    attrs = callback;
    callback = extra;
  }

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

  attrs = attrs || ['all'];
  assert.ok(Array.isArray(attrs));
  assert.ok(callback);

  self.log.debug('Get attributes: ' + self.name);
  confirmer(function(er) {
    if(er) return callback(er);
    callback(null, self);
  })
}

function create_queue(opts, cb) {
  var queue = new Queue(opts);
  queue.create(function(er, name) {
    if(er) return cb(er);
    return cb(null, queue);
  })
}

function list_queues(opts, cb) {
  var prefix = opts.prefix || opts._str;

  if(!cb && opts._func)
    cb = opts._func;

  var startkey = '_design/CQS\/';
  var endkey   = '_design/CQS\/';

  if(prefix) {
    startkey += prefix;
    endkey   += prefix;
  }

  endkey += '\ufff0';

  var query = { startkey: lib.JS(startkey)
              , endkey  : lib.JS(endkey)
              };

  var db_url = opts.couch + '/' + opts.db;
  var view = db_url + '/_all_docs?' + querystring.stringify(query);
  lib.req_json({uri:view, time_C:opts.time_C}, function(er, resp, view) {
    if(er) return cb(er);

    function get_queue(row) {
      return new Queue({ couch: opts.couch
                       , db   : opts.db
                       , name : id_to_name(row.id)
                       , time_C: opts.time_C
                       })
    }

    var queues = view.rows.map(get_queue);
    return cb(null, queues);
  })
}

function set_attributes(queue, attrs, callback) {
  return queue.set(attrs, callback);
}

function get_attributes(opts, attrs, callback, extra) {
  var queue = (opts instanceof Queue) ? opts : new Queue(opts);
  return queue.GetAttributes(attrs, callback, extra);
}

function send_message(opts, message, extra, callback) {
  var queue;
  if(opts instanceof Queue)
    queue = opts;
  else if(opts.queue) {
    if(opts.queue instanceof Queue)
      queue = opts.queue
    else
      queue = new Queue({'QueueName':opts.queue, 'couch':opts.couch, 'db':opts.db});
  }
  else
    queue = new Queue(opts);

  if(!callback && typeof extra === 'function') {
    callback = extra;
    extra = null;
  }

  return queue.send(message, extra, callback);
}

function receive_message(opts, callback, extra) {
  var queue;
  if(opts instanceof Queue)
    queue = opts;
  else if(opts._str || opts.queue) {
    if(opts.queue instanceof Queue)
      queue = opts.queue;
    else
      queue = new Queue({'QueueName':opts._str || opts.queue, 'couch':opts.couch, 'db':opts.db});
    delete opts.queue;
    delete opts._str;
  } else
    Queue = new Queue(opts);

  if(typeof callback === 'number' && typeof extra === 'function') {
    opts= { 'MaxNumberOfMessages': callback };
    callback = extra;
  }

  assert.ok(callback);
  return queue.receive(opts, callback);
}

module.exports = { "Queue" : Queue
                 , "create": create_queue
                 , "list"  : list_queues
                 , "send"  : send_message
                 , "receive": receive_message
                 , "set"   : set_attributes
                 , "get"   : get_attributes
                 };

//
// Utilities
//

function id_to_name(id) {
  var match = QUEUE_DDOC_ID_RE.exec(id);
  if(!match)
    throw new Error("Unknown queue ddoc id: " + id);
  return match[1];
}
<|endoftext|>


<commit_before>import Chart from "./chart";

export default class RadarChart extends Chart {
	render() {
		super.scale();

		let that = this;

		let pathArr = [];

		// 坐标刻度线
		this.yAxis.forEach((it, i) => {
			pathArr = [];

			let r = this.yAxis[i].number * this.stepLength / 2;
			this.yAxis[i].y = r;

			let total = that.series[0].data.length;
			that.series[0].data.forEach((v, j) => {
				let x = Math.round(Math.cos((j / total) * (2 * Math.PI)) * r) + that.radius / 2;
				let y = Math.round(Math.sin((j / total) * (2 * Math.PI)) * r) + that.radius / 2;

				pathArr.push(x + " " + y + " ");
			});

			pathArr[pathArr.length] = pathArr[0];
			it.path = "M" + pathArr.join("L ");
		});

		// 射线
		let center = (this.radius / 2) + " " + (this.radius / 2);
		let numArr = [];
		let markerPathArr = [];

		let total = this.series[0].data.length;
		for (let i = 0; i < this.series[0].data.length; i++) {
			let outer = this.yAxis[this.yAxis.length - 1];
			this.xAxis[i] = {
				path:"M" + center + " L" + pathArr[i]
			};

			let r = this.series[0].data[i] * this.stepLength / 2;

			let x = Math.round(Math.cos((i / total) * (2 * Math.PI)) * r) + this.radius / 2;
			let y = Math.round(Math.sin((i / total) * (2 * Math.PI)) * r) + this.radius / 2;

			numArr.push(x + " " + y + " ");

			let markerArr = [];
			let markerCorner = 20;
			for (let j=0; j<markerCorner; j++) {
				let m = x + 5 * Math.cos((j / markerCorner) * (2 * Math.PI));
				let n = y + 5 * Math.sin((j / markerCorner) * (2 * Math.PI));

				markerArr.push(m + " " + n + " ");
			}

			markerPathArr.push("M" + markerArr.join("L "));
		}
		numArr[numArr.length] = numArr[0];

		this.dataPath = "M" + numArr.join("L ");
		this.markerPathArr = markerPathArr;
	}
}<commit_msg>雷达图的偏移写错了，半径又除了2……<commit_after>import Chart from "./chart";

export default class RadarChart extends Chart {
	render() {
		super.scale();

		let that = this;

		let pathArr = [];

		// 坐标刻度线
		this.yAxis.forEach((it, i) => {
			pathArr = [];

			let r = this.yAxis[i].number * this.stepLength / 2;
			this.yAxis[i].y = r;

			let total = that.series[0].data.length;
			that.series[0].data.forEach((v, j) => {
				let x = Math.round(Math.cos((j / total) * (2 * Math.PI)) * r) + that.radius;
				let y = Math.round(Math.sin((j / total) * (2 * Math.PI)) * r) + that.radius;

				pathArr.push(x + " " + y + " ");
			});

			pathArr[pathArr.length] = pathArr[0];
			it.path = "M" + pathArr.join("L ");
		});

		// 射线
		let center = (this.radius) + " " + (this.radius);
		let numArr = [];
		let markerPathArr = [];

		let total = this.series[0].data.length;
		for (let i = 0; i < this.series[0].data.length; i++) {
			let outer = this.yAxis[this.yAxis.length - 1];
			this.xAxis[i] = {
				path:"M" + center + " L" + pathArr[i]
			};

			let r = this.series[0].data[i] * this.stepLength / 2;

			let x = Math.round(Math.cos((i / total) * (2 * Math.PI)) * r) + this.radius;
			let y = Math.round(Math.sin((i / total) * (2 * Math.PI)) * r) + this.radius;

			numArr.push(x + " " + y + " ");

			let markerArr = [];
			let markerCorner = 20;
			for (let j=0; j<markerCorner; j++) {
				let m = x + 5 * Math.cos((j / markerCorner) * (2 * Math.PI));
				let n = y + 5 * Math.sin((j / markerCorner) * (2 * Math.PI));

				markerArr.push(m + " " + n + " ");
			}

			markerPathArr.push("M" + markerArr.join("L "));
		}
		numArr[numArr.length] = numArr[0];

		this.dataPath = "M" + numArr.join("L ");
		this.markerPathArr = markerPathArr;
	}
}<|endoftext|>


<commit_before>(function(window, undefined) {
    var $ = window.jQuery;

    var rader = function(params) {
        params.root = params.root || this;

        return new init(params);
    };

    // rader object constructor
    var init = function(params) {
        var elements = {},
            delta,
            dir = { // Direction: left-to-right | top-to-bottom
                start: 'left',
                client: 'clientWidth',
                offset: 'offsetWidth',
                size: 'width'
            },
            defaultParams,
            event,
            dom,
            selector,
            drag = -1, // No runner dragged
            runnersInitialPos = [], // Current absolute runners position (before and after drag)
            runnersCurrentPos = [], // Current (in drag mode) absolute runners position
            pointsInRagne = []; // Bool array

        // Event manager
        event = params.event || function(elem, event, func, mode) {
            $(elem)[mode || 'on'](event, func);
        };

        // DOM utility
        dom = params.dom || $;

        // Selector engine
        selector = params.selector || $;

        // Dom initialization
        elements.track = params.root[0];
        elements.trackActive = params.trackActive[0] || params.trackActive;
        elements.points = params.points;
        elements.runners = params.runners;

        // Params initialization
        defaultParams = { // Default input parameters
            stickingRadius: 0,
            bumpRadius: elements.runners[0][dir.offset], // firstRunner.offsetWidth | Height
            points: [],
            start: 0,
            end: 10,
            pointsPos: []
        }
        if (params.pointsPos && params.pointsPos.length) {
            defaultParams.start = params.pointsPos[0];
            defaultParams.end = params.pointsPos[params.pointsPos.length - 1];
        }
        defaultParams.runnersPos = [defaultParams.start, defaultParams.end];
        for (var key in defaultParams) {
            if (params[key] === undefined) {
                params[key] = defaultParams[key];
            }
        }

        delta = Math.abs(params.end - params.start);

        // Validation (dev mode)
        if (params.pointsPos && params.pointsPos.length !== elements.points.length) {
            console.error('params.pointsPos.length !== elements.points.length');
        }
        if (params.runners.length !== elements.runners.length) {
            console.error('params.runners.length !== elements.runners.length');
        }
        if (!selector) {
            console.error('No selector engine found');
        }
        if (!dom) {
            console.error('No dom utility found');
        }
        if (!event) {
            console.error('No event manager found');
        }

        // Text selection start preventing
        function dontStartSelect() {
            return false;
        }

        // Text selection preventing on drag
        function selection(enable) {
            event(document, 'selectstart', dontStartSelect, enable ? 'off' : 'on');
        }

        function getMax(arr) {
            var max = -10000;

            for (var i = 0 ; i < arr.length ; i++) {
                if (max < arr[i]) {
                    max = arr[i];
                }
            }

            return max;
        }

        function getMin(arr) {
            var min = 10000;

            for (var i = 0 ; i < arr.length ; i++) {
                if (min > arr[i]) {
                    min = arr[i];
                }
            }

            return min;
        }

        function limitPos(x) {
            if (x > elements.track[dir.client]) {
                x = elements.track[dir.client];
            }

            if (x < 0) {
                x = 0;
            }

            return x;
        }

        // Converting scale (user-defined) dimension to pixel dimension
        var xToPxMem = [];
        function xToPx(x) {
            if (xToPxMem[x] === undefined) {
                xToPxMem[x] = ((x - params.start) / delta) * elements.track[dir.client];
            }

            return xToPxMem[x];
        }

        var pxToXMem = [];
        function pxToX(px) {
            if (pxToXMem[px] === undefined) {
                pxToXMem[px] = px / elements.track[dir.client] * delta + params.start;
            }

            return pxToXMem[px];
        }

        // Getting coordinate of closest to @x point
        function getXofClosestPoint(x, sign) {
            var xret = x,
                dx,
                px,
                dxmin = 9999;

            for (var i = 0 ; i < params.pointsPos.length ; i++) {
                px = xToPx(params.pointsPos[i]);

                dx = Math.abs(px - x);

                if (dx < dxmin) {
                    xret = px;
                    dxmin = dx;
                }
            }

            return xret;
        }

        // Getting coordinate of closest to @x point from (sign > 0) right / bottom or (sign < 0) left / top
        function getNextStableX(x, sign) {
            var px, dx, dxCl, dxmin = 9999, xret = x, xofClosestPoint = getXofClosestPoint(x);

            dxCl = Math.abs(xofClosestPoint - x);

            // No x correction needed (because x is outside of points gravity)
            if (dxCl > params.stickingRadius) { // 1
                return x;
            }

            for (var i = 0 ; i < params.pointsPos.length ; i++) { // 2
                px = xToPx(params.pointsPos[i]);
                dx = Math.abs(px - x);

                if ((px * sign > x * sign) && dx < dxmin) {
                    dxmin = dx;
                    xret = px;
                }
            }

            if (dxmin < params.stickingRadius) { // 2, 4(partially)
                return xret;
            }

            if (dxmin >= params.stickingRadius) { // 3, 4
                x = limitPos(x - dxCl * sign + params.stickingRadius * sign);

                if (Math.abs(xret - x) < params.stickingRadius) {
                    return xret;
                } else {
                    return x;
                }
            }
        }

        var stickTimeout;
        function tryMoveRunner(num, x) {
            var sign;

            function next(num) {
                return num + 1 * sign;
            }

            // Moving direction
            if (x > runnersCurrentPos[drag]) {
                sign = +1;
            } else if (x < runnersCurrentPos[drag]) {
                sign = -1;
            } else {
                return false; // No main coordinate change
            }

            x = limitPos(x);

            if (drag != num) { // Bumping runner
                x = getNextStableX(x, sign);
            }

            // Sticking runner
            xSticky = getXofClosestPoint(x, sign);
            if (xSticky !== undefined && xSticky !== x && Math.abs(xSticky - x) < params.stickingRadius) {
                if (!stickTimeout && params.transCls) {
                    dom(elements.track).addClass(params.transCls);
                    stickTimeout = setTimeout(function() {
                        dom(elements.track).removeClass(params.transCls);
                        stickTimeout = undefined;
                    }, 500);
                }
                x = xSticky;
            }

            // Bumping neighbour runners
            if (runnersCurrentPos[next(num)] !== undefined &&
                (((runnersCurrentPos[next(num)] - x) < params.bumpRadius && sign > 0) ||
                ((x - runnersCurrentPos[next(num)]) < params.bumpRadius && sign < 0))) {
                var xofNextRunner = tryMoveRunner(next(num), x + sign * params.bumpRadius);

                if (x * sign > (xofNextRunner - params.bumpRadius * sign) * sign) {
                    x = getNextStableX(xofNextRunner - params.bumpRadius * sign, -sign);
                }
            }

            // Positioning elements runner
            runnersCurrentPos[num] = x;
            var pos = {};
            pos[dir.start] = runnersCurrentPos[num] + 'px';
            dom(elements.runners[num]).css(pos);

            return x;
        }

        // Updating points look (in range | not in range)
        function updatePoints(force) {
            if (params.pointInRangeCls) {
                // Cloning pointsInRagne to pointsWasInRagne
                var pointsWasInRagne = [];
                for (var i = 0 ; i < pointsInRagne.length ; i++) {
                    pointsWasInRagne[i] = pointsInRagne[i];
                }

                for (var i = 0 ; i < elements.points.length ; i++) {
                    if (xToPx(params.pointsPos[i]) >= runnersCurrentPos[0] && xToPx(params.pointsPos[i]) <= runnersCurrentPos[runnersCurrentPos.length - 1]) {
                        pointsInRagne[i] = 1;
                    } else {
                        pointsInRagne[i] = 0;
                    }
                }

                for (var i = 0 ; i < pointsInRagne.length ; i++) {
                    if (pointsInRagne[i] != pointsWasInRagne[i] || force) { // Mega profit (+few ms per point change)
                        if (pointsInRagne[i]) {
                            dom(elements.points[i]).addClass(params.pointInRangeCls);
                        } else {
                            dom(elements.points[i]).removeClass(params.pointInRangeCls);
                        }
                    }
                }
            }
        }

        function update(e, force) {
            if (e) {
                var dx = e.clientX - x0drag,
                    pos = {},
                    x;

                x = runnersInitialPos[drag] + dx;
                tryMoveRunner(drag, limitPos(x));
            }

            // Updating activation state of all points
            updatePoints(force);

            // Positioning active track
            var pos = {};
            pos[dir.start] = getMin(runnersCurrentPos) + 'px';
            pos[dir.size] = (getMax(runnersCurrentPos) - getMin(runnersCurrentPos)) + 'px';
            dom(elements.trackActive).css(pos);

            if (typeof params.change === 'function') {
                params.change({
                    minPos: getMin(runnersCurrentPos),
                    maxPos: getMax(runnersCurrentPos),
                    minVal: pxToX(getMin(runnersCurrentPos)),
                    maxVal: pxToX(getMax(runnersCurrentPos))
                });
            }
        }

        // Coordinates initialization
        for (var i = 0 ; i < params.pointsPos.length ; i++) {
            var pos = {};

            pos[dir.start] = xToPx(params.pointsPos[i]) + 'px';
            dom(elements.points[i]).css(pos);
        }

        // Runners position & drag initialization
        for (var i = 0 ; i < params.runnersPos.length ; i++) {
            var pos = {};

            runnersCurrentPos[i] = runnersInitialPos[i] = xToPx(params.runnersPos[i]);
            pos[dir.start] = runnersCurrentPos[i] + 'px';
            dom(elements.runners[i]).css(pos);

            event(elements.runners[i], 'mousedown', (function(n) {
                return function(e) {
                    e.preventDefault(); // Text selection disabling in Opera... and all other browsers?
                    selection(); // Disable text selection in ie8
                    drag = n; // Runner number to be dragged
                }
            })(i));
        }

        // Active track position initialization
        var x1 = xToPx(params.runnersPos[0]),
            x2 = xToPx(params.runnersPos[params.runnersPos.length - 1]),
            pos = {};

        pos[dir.start] = x1 + 'px';
        pos[dir.size] = Math.abs(x2 - x1) + 'px';
        dom(elements.trackActive).css(pos);

        update(0, 1);

        // Dragend
        event(document, 'mouseup blur', function() {
            for (var i = 0 ; i < runnersInitialPos.length ; i++) {
                runnersInitialPos[i] = runnersCurrentPos[i]; // Updating initial pos at dragend
            }

            selection(1); // Enable text selection
            drag = -1;
        });

        // Dragstart
        event(document, 'mousedown', function(e) { // document, not window, for ie8
            x0drag = e.clientX;
        });

        event(document, 'mousemove', function(e) { // document, not window, for ie8
            if (drag != -1) {
                update(e);
            }
        });
    }

    if ($ && $.fn) {
        $.fn.rader = rader;
    }

    window.rader = rader;
})(window);<commit_msg>Right click drag prevented<commit_after>(function(window, undefined) {
    var $ = window.jQuery;

    var rader = function(params) {
        params.root = params.root || this;

        return new init(params);
    };

    // rader object constructor
    var init = function(params) {
        var elements = {},
            delta,
            dir = { // Direction: left-to-right | top-to-bottom
                start: 'left',
                client: 'clientWidth',
                offset: 'offsetWidth',
                size: 'width'
            },
            defaultParams,
            event,
            dom,
            selector,
            drag = -1, // No runner dragged
            runnersInitialPos = [], // Current absolute runners position (before and after drag)
            runnersCurrentPos = [], // Current (in drag mode) absolute runners position
            pointsInRagne = []; // Bool array

        // Event manager
        event = params.event || function(elem, event, func, mode) {
            $(elem)[mode || 'on'](event, func);
        };

        // DOM utility
        dom = params.dom || $;

        // Selector engine
        selector = params.selector || $;

        // Dom initialization
        elements.track = params.root[0];
        elements.trackActive = params.trackActive[0] || params.trackActive;
        elements.points = params.points;
        elements.runners = params.runners;

        // Params initialization
        defaultParams = { // Default input parameters
            stickingRadius: 0,
            bumpRadius: elements.runners[0][dir.offset], // firstRunner.offsetWidth | Height
            points: [],
            start: 0,
            end: 10,
            pointsPos: []
        }
        if (params.pointsPos && params.pointsPos.length) {
            defaultParams.start = params.pointsPos[0];
            defaultParams.end = params.pointsPos[params.pointsPos.length - 1];
        }
        defaultParams.runnersPos = [defaultParams.start, defaultParams.end];
        for (var key in defaultParams) {
            if (params[key] === undefined) {
                params[key] = defaultParams[key];
            }
        }

        delta = Math.abs(params.end - params.start);

        // Validation (dev mode)
        if (params.pointsPos && params.pointsPos.length !== elements.points.length) {
            console.error('params.pointsPos.length !== elements.points.length');
        }
        if (params.runners.length !== elements.runners.length) {
            console.error('params.runners.length !== elements.runners.length');
        }
        if (!selector) {
            console.error('No selector engine found');
        }
        if (!dom) {
            console.error('No dom utility found');
        }
        if (!event) {
            console.error('No event manager found');
        }

        // Text selection start preventing
        function dontStartSelect() {
            return false;
        }

        // Text selection preventing on drag
        function selection(enable) {
            event(document, 'selectstart', dontStartSelect, enable ? 'off' : 'on');
        }

        function getMax(arr) {
            var max = -10000;

            for (var i = 0 ; i < arr.length ; i++) {
                if (max < arr[i]) {
                    max = arr[i];
                }
            }

            return max;
        }

        function getMin(arr) {
            var min = 10000;

            for (var i = 0 ; i < arr.length ; i++) {
                if (min > arr[i]) {
                    min = arr[i];
                }
            }

            return min;
        }

        function limitPos(x) {
            if (x > elements.track[dir.client]) {
                x = elements.track[dir.client];
            }

            if (x < 0) {
                x = 0;
            }

            return x;
        }

        // Converting scale (user-defined) dimension to pixel dimension
        var xToPxMem = [];
        function xToPx(x) {
            if (xToPxMem[x] === undefined) {
                xToPxMem[x] = ((x - params.start) / delta) * elements.track[dir.client];
            }

            return xToPxMem[x];
        }

        var pxToXMem = [];
        function pxToX(px) {
            if (pxToXMem[px] === undefined) {
                pxToXMem[px] = px / elements.track[dir.client] * delta + params.start;
            }

            return pxToXMem[px];
        }

        // Getting coordinate of closest to @x point
        function getXofClosestPoint(x, sign) {
            var xret = x,
                dx,
                px,
                dxmin = 9999;

            for (var i = 0 ; i < params.pointsPos.length ; i++) {
                px = xToPx(params.pointsPos[i]);

                dx = Math.abs(px - x);

                if (dx < dxmin) {
                    xret = px;
                    dxmin = dx;
                }
            }

            return xret;
        }

        // Getting coordinate of closest to @x point from (sign > 0) right / bottom or (sign < 0) left / top
        function getNextStableX(x, sign) {
            var px, dx, dxCl, dxmin = 9999, xret = x, xofClosestPoint = getXofClosestPoint(x);

            dxCl = Math.abs(xofClosestPoint - x);

            // No x correction needed (because x is outside of points gravity)
            if (dxCl > params.stickingRadius) { // 1
                return x;
            }

            for (var i = 0 ; i < params.pointsPos.length ; i++) { // 2
                px = xToPx(params.pointsPos[i]);
                dx = Math.abs(px - x);

                if ((px * sign > x * sign) && dx < dxmin) {
                    dxmin = dx;
                    xret = px;
                }
            }

            if (dxmin < params.stickingRadius) { // 2, 4(partially)
                return xret;
            }

            if (dxmin >= params.stickingRadius) { // 3, 4
                x = limitPos(x - dxCl * sign + params.stickingRadius * sign);

                if (Math.abs(xret - x) < params.stickingRadius) {
                    return xret;
                } else {
                    return x;
                }
            }
        }

        var stickTimeout;
        function tryMoveRunner(num, x) {
            var sign;

            function next(num) {
                return num + 1 * sign;
            }

            // Moving direction
            if (x > runnersCurrentPos[drag]) {
                sign = +1;
            } else if (x < runnersCurrentPos[drag]) {
                sign = -1;
            } else {
                return false; // No main coordinate change
            }

            x = limitPos(x);

            if (drag != num) { // Bumping runner
                x = getNextStableX(x, sign);
            }

            // Sticking runner
            xSticky = getXofClosestPoint(x, sign);
            if (xSticky !== undefined && xSticky !== x && Math.abs(xSticky - x) < params.stickingRadius) {
                if (!stickTimeout && params.transCls) {
                    dom(elements.track).addClass(params.transCls);
                    stickTimeout = setTimeout(function() {
                        dom(elements.track).removeClass(params.transCls);
                        stickTimeout = undefined;
                    }, 500);
                }
                x = xSticky;
            }

            // Bumping neighbour runners
            if (runnersCurrentPos[next(num)] !== undefined &&
                (((runnersCurrentPos[next(num)] - x) < params.bumpRadius && sign > 0) ||
                ((x - runnersCurrentPos[next(num)]) < params.bumpRadius && sign < 0))) {
                var xofNextRunner = tryMoveRunner(next(num), x + sign * params.bumpRadius);

                if (x * sign > (xofNextRunner - params.bumpRadius * sign) * sign) {
                    x = getNextStableX(xofNextRunner - params.bumpRadius * sign, -sign);
                }
            }

            // Positioning elements runner
            runnersCurrentPos[num] = x;
            var pos = {};
            pos[dir.start] = runnersCurrentPos[num] + 'px';
            dom(elements.runners[num]).css(pos);

            return x;
        }

        // Updating points look (in range | not in range)
        function updatePoints(force) {
            if (params.pointInRangeCls) {
                // Cloning pointsInRagne to pointsWasInRagne
                var pointsWasInRagne = [];
                for (var i = 0 ; i < pointsInRagne.length ; i++) {
                    pointsWasInRagne[i] = pointsInRagne[i];
                }

                for (var i = 0 ; i < elements.points.length ; i++) {
                    if (xToPx(params.pointsPos[i]) >= runnersCurrentPos[0] && xToPx(params.pointsPos[i]) <= runnersCurrentPos[runnersCurrentPos.length - 1]) {
                        pointsInRagne[i] = 1;
                    } else {
                        pointsInRagne[i] = 0;
                    }
                }

                for (var i = 0 ; i < pointsInRagne.length ; i++) {
                    if (pointsInRagne[i] != pointsWasInRagne[i] || force) { // Mega profit (+few ms per point change)
                        if (pointsInRagne[i]) {
                            dom(elements.points[i]).addClass(params.pointInRangeCls);
                        } else {
                            dom(elements.points[i]).removeClass(params.pointInRangeCls);
                        }
                    }
                }
            }
        }

        function update(e, force) {
            if (e) {
                var dx = e.clientX - x0drag,
                    pos = {},
                    x;

                x = runnersInitialPos[drag] + dx;
                tryMoveRunner(drag, limitPos(x));
            }

            // Updating activation state of all points
            updatePoints(force);

            // Positioning active track
            var pos = {};
            pos[dir.start] = getMin(runnersCurrentPos) + 'px';
            pos[dir.size] = (getMax(runnersCurrentPos) - getMin(runnersCurrentPos)) + 'px';
            dom(elements.trackActive).css(pos);

            if (typeof params.change === 'function') {
                params.change({
                    minPos: getMin(runnersCurrentPos),
                    maxPos: getMax(runnersCurrentPos),
                    minVal: pxToX(getMin(runnersCurrentPos)),
                    maxVal: pxToX(getMax(runnersCurrentPos))
                });
            }
        }

        // Coordinates initialization
        for (var i = 0 ; i < params.pointsPos.length ; i++) {
            var pos = {};

            pos[dir.start] = xToPx(params.pointsPos[i]) + 'px';
            dom(elements.points[i]).css(pos);
        }

        // Runners position & drag initialization
        for (var i = 0 ; i < params.runnersPos.length ; i++) {
            var pos = {};

            runnersCurrentPos[i] = runnersInitialPos[i] = xToPx(params.runnersPos[i]);
            pos[dir.start] = runnersCurrentPos[i] + 'px';
            dom(elements.runners[i]).css(pos);

            event(elements.runners[i], 'mousedown', (function(n) {
                return function(e) {
                    if (e.button != 2) {
                        e.preventDefault(); // Text selection disabling in Opera... and all other browsers?
                        selection(); // Disable text selection in ie8
                        drag = n; // Runner number to be dragged
                    }
                }
            })(i));
        }

        // Active track position initialization
        var x1 = xToPx(params.runnersPos[0]),
            x2 = xToPx(params.runnersPos[params.runnersPos.length - 1]),
            pos = {};

        pos[dir.start] = x1 + 'px';
        pos[dir.size] = Math.abs(x2 - x1) + 'px';
        dom(elements.trackActive).css(pos);

        update(0, 1);

        // Dragend
        event(document, 'mouseup blur', function() {
            for (var i = 0 ; i < runnersInitialPos.length ; i++) {
                runnersInitialPos[i] = runnersCurrentPos[i]; // Updating initial pos at dragend
            }

            selection(1); // Enable text selection
            drag = -1;
        });

        // Dragstart
        event(document, 'mousedown', function(e) { // document, not window, for ie8
            x0drag = e.clientX;
        });

        event(document, 'mousemove', function(e) { // document, not window, for ie8
            if (drag != -1) {
                update(e);
            }
        });
    }

    if ($ && $.fn) {
        $.fn.rader = rader;
    }

    window.rader = rader;
})(window);<|endoftext|>