<commit_before>module('Numericality options');

// test('when value is a number', function() {
  // var element = $('<input type="text" />');
  // var options = { messages: { numericality: "failed validation" } };
  // element.val('123');
  // equal(ClientSideValidations.validators.local.numericality(element, options), undefined);
// });

// test('when value is a decimal number', function() {
  // var element = $('<input type="text" />');
  // var options = { messages: { numericality: "failed validation" } };
  // element.val('123.456');
  // equal(ClientSideValidations.validators.local.numericality(element, options), undefined);
// });

// test('when there is a custom numericality pattern', function() {
  // var element = $('<input type="text" />');
  // var options = { messages: { numericality: "failed validation" } };
  // var oldPattern = ClientSideValidations.patterns.numericality;
  // element.val('123,45');
  // ClientSideValidations.patterns.numericality = /^-?(?:\d+|\d{1,3}(?:\.\d{3})+)(?:,\d*)?$/;
  // equal(ClientSideValidations.validators.local.numericality(element, options), undefined);
  // ClientSideValidations.patterns.numericality = oldPattern;
// });

// test('when value is not a number', function() {
  // var element = $('<input type="text" />');
  // var options = { messages: { numericality: "failed validation" } };
  // element.val('abc123');
  // equal(ClientSideValidations.validators.local.numericality(element, options), "failed validation");
// });

// test('when no value', function() {
  // var element = $('<input type="text" />');
  // var options = { messages: { numericality: "failed validation" } };
  // equal(ClientSideValidations.validators.local.numericality(element, options), "failed validation");
// });

test('when no value and allowing blank', function() {
  var element = $('<input type="text" />');
  var options = { messages: { numericality: "failed validation" }, allow_blank: true };
  equal(ClientSideValidations.validators.local.numericality(element, options), undefined);
});

// test('when bad value and allowing blank', function() {
  // var element = $('<input type="text" />');
  // var options = { messages: { numericality: "failed validation" }, allow_blank: true };
  // element.val('abc123');
  // equal(ClientSideValidations.validators.local.numericality(element, options), "failed validation");
// });

// test('when only allowing integers and value is integer', function() {
  // var element = $('<input type="text" />');
  // var options = { messages: { only_integer: "failed validation", numericality: "failed validation" }, only_integer: true };
  // element.val('123');
  // equal(ClientSideValidations.validators.local.numericality(element, options), undefined);
// });

// test('when only allowing integers and value is integer with whitespace', function() {
  // var element = $('<input type="text" />');
  // var options = { messages: { only_integer: "failed validation", numericality: "failed validation" }, only_integer: true };
  // element.val(' 123 ');
  // equal(ClientSideValidations.validators.local.numericality(element, options), undefined);
// });

// test('when only allowing integers and value has a negative or positive sign', function() {
  // var element = $('<input type="text" />');
  // var options = { messages: { only_integer: "failed validation", numericality: "failed validation" }, only_integer: true };
  // element.val('-23');
  // equal(ClientSideValidations.validators.local.numericality(element, options), undefined);
  // element.val('+23');
  // equal(ClientSideValidations.validators.local.numericality(element, options), undefined);
// });

// test('when only allowing integers and value is not integer', function() {
  // var element = $('<input type="text" />');
  // var options = { messages: { only_integer: "failed validation", numericality: "failed validation" }, only_integer: true };
  // element.val('123.456');
  // equal(ClientSideValidations.validators.local.numericality(element, options), "failed validation");
// });

// test('when only allowing values greater than 10 and value is greater than 10', function() {
  // var element = $('<input type="text" />');
  // var options = { messages: { greater_than: "failed validation", numericality: "failed validation" }, greater_than: 10 };
  // element.val('11');
  // equal(ClientSideValidations.validators.local.numericality(element, options), undefined);
// });

// test('when only allowing values greater than 10 and value is 10', function() {
  // var element = $('<input type="text" />');
  // var options = { messages: { greater_than: "failed validation", numericality: "failed validation" }, greater_than: 10 };
  // element.val('10');
  // equal(ClientSideValidations.validators.local.numericality(element, options), "failed validation");
// });

// test('when only allowing values greater than or equal to 10 and value is 10', function() {
  // var element = $('<input type="text" />');
  // var options = { messages: { greater_than_or_equal_to: "failed validation", numericality: "failed validation" }, greater_than_or_equal_to: 10 };
  // element.val('10');
  // equal(ClientSideValidations.validators.local.numericality(element, options), undefined);
// });

// test('when only allowing values greater than or equal to 10 and value is 9', function() {
  // var element = $('<input type="text" />');
  // var options = { messages: { greater_than_or_equal_to: "failed validation", numericality: "failed validation" }, greater_than_or_equal_to: 10 };
  // element.val('9');
  // equal(ClientSideValidations.validators.local.numericality(element, options), "failed validation");
// });

// test('when only allowing values less than 10 and value is less than 10', function() {
  // var element = $('<input type="text" />');
  // var options = { messages: { less_than: "failed validation", numericality: "failed validation" }, less_than: 10 };
  // element.val('9');
  // equal(ClientSideValidations.validators.local.numericality(element, options), undefined);
// });

// test('when only allowing values less than 10 and value is 10', function() {
  // var element = $('<input type="text" />');
  // var options = { messages: { less_than: "failed validation", numericality: "failed validation" }, less_than: 10 };
  // element.val('10');
  // equal(ClientSideValidations.validators.local.numericality(element, options), "failed validation");
// });

// test('when only allowing values less than or equal to 10 and value is 10', function() {
  // var element = $('<input type="text" />');
  // var options = { messages: { less_than_or_equal_to: "failed validation", numericality: "failed validation" }, less_than_or_equal_to: 10 };
  // element.val('10');
  // equal(ClientSideValidations.validators.local.numericality(element, options), undefined);
// });

// test('when only allowing values less than or equal to 10 and value is 11', function() {
  // var element = $('<input type="text" />');
  // var options = { messages: { less_than_or_equal_to: "failed validation", numericality: "failed validation" }, less_than_or_equal_to: 10 };
  // element.val('11');
  // equal(ClientSideValidations.validators.local.numericality(element, options), "failed validation");
// });

// test('when only allowing values equal to 10 and value is 10', function() {
  // var element = $('<input type="text" />');
  // var options = { messages: { equal_to: "failed validation", numericality: "failed validation" }, equal_to: 10 };
  // element.val('10');
  // equal(ClientSideValidations.validators.local.numericality(element, options), undefined);
// });

// test('when only allowing values equal to 10 and value is 11', function() {
  // var element = $('<input type="text" />');
  // var options = { messages: { equal_to: "failed validation", numericality: "failed validation" }, equal_to: 10 };
  // element.val('11');
  // equal(ClientSideValidations.validators.local.numericality(element, options), "failed validation");
// });

// test('when only allowing value equal to 0 and value is 1', function() {
  // var element = $('<input type="text" />');
  // var options = { messages: { equal_to: "failed validation", numericality: "failed validation" }, equal_to: 0 };
  // element.val('1');
  // equal(ClientSideValidations.validators.local.numericality(element, options), "failed validation");
// });

// test('when only allowing odd values and the value is odd', function() {
  // var element = $('<input type="text" />');
  // var options = { messages: { odd: "failed validation", numericality: "failed validation" }, odd: true };
  // element.val('11');
  // equal(ClientSideValidations.validators.local.numericality(element, options), undefined);
// });

// test('when only allowing odd values and the value is even', function() {
  // var element = $('<input type="text" />');
  // var options = { messages: { odd: "failed validation", numericality: "failed validation" }, odd: true };
  // element.val('10');
  // equal(ClientSideValidations.validators.local.numericality(element, options), "failed validation");
// });

// test('when only allowing even values and the value is even', function() {
  // var element = $('<input type="text" />');
  // var options = { messages: { even: "failed validation", numericality: "failed validation" }, even: true };
  // element.val('10');
  // equal(ClientSideValidations.validators.local.numericality(element, options), undefined);
// });

// test('when only allowing even values and the value is odd', function() {
  // var element = $('<input type="text" />');
  // var options = { messages: { even: "failed validation", numericality: "failed validation" }, even: true };
  // element.val('11');
  // equal(ClientSideValidations.validators.local.numericality(element, options), "failed validation");
// });

// test('when value refers to another present input', function() {
  // var form = $('<form />')
  // var element_1 = $('<input type="text" name="points_1" />');
  // var element_2 = $('<input type="text" name="points_2" />');
  // var options   = { messages: { greater_than: "failed to be greater", numericality: "failed validation" }, greater_than: 'points_2' };

  // form.append(element_1).append(element_2);
  // $('#qunit-fixture')
    // .append(form);

  // element_1.val(0)
  // element_2.val(1)
  // equal(ClientSideValidations.validators.local.numericality(element_1, options), "failed to be greater");
  // element_1.val(2)
  // equal(ClientSideValidations.validators.local.numericality(element_1, options), undefined);
// });

// test('when value refers to another present input but with more than one match', function() {
  // var form = $('<form />')
  // var element_1 = $('<input type="text" name="points_1" />');
  // var element_2 = $('<input type="text" name="points_2" />');
  // var element_3 = $('<input type="text" name="points_21" />');
  // var options   = { messages: { greater_than: "failed to be greater", numericality: "failed validation" }, greater_than: 'points_2' };

  // form.append(element_1).append(element_2).append(element_3);
  // $('#qunit-fixture')
    // .append(form);

  // element_1.val(1)
  // element_2.val(2)
  // element_3.val(0)
  // equal(ClientSideValidations.validators.local.numericality(element_1, options), undefined);
// });
<commit_msg>fixup! Fix #425<commit_after>module('Numericality options');

test('when value is a number', function() {
  var element = $('<input type="text" />');
  var options = { messages: { numericality: "failed validation" } };
  element.val('123');
  equal(ClientSideValidations.validators.local.numericality(element, options), undefined);
});

test('when value is a decimal number', function() {
  var element = $('<input type="text" />');
  var options = { messages: { numericality: "failed validation" } };
  element.val('123.456');
  equal(ClientSideValidations.validators.local.numericality(element, options), undefined);
});

test('when there is a custom numericality pattern', function() {
  var element = $('<input type="text" />');
  var options = { messages: { numericality: "failed validation" } };
  var oldPattern = ClientSideValidations.patterns.numericality;
  element.val('123,45');
  ClientSideValidations.patterns.numericality = /^-?(?:\d+|\d{1,3}(?:\.\d{3})+)(?:,\d*)?$/;
  equal(ClientSideValidations.validators.local.numericality(element, options), undefined);
  ClientSideValidations.patterns.numericality = oldPattern;
});

test('when value is not a number', function() {
  var element = $('<input type="text" />');
  var options = { messages: { numericality: "failed validation" } };
  element.val('abc123');
  equal(ClientSideValidations.validators.local.numericality(element, options), "failed validation");
});

test('when no value', function() {
  var element = $('<input type="text" />');
  var options = { messages: { numericality: "failed validation" } };
  equal(ClientSideValidations.validators.local.numericality(element, options), "failed validation");
});

test('when no value and allowing blank', function() {
  var element = $('<input type="text" />');
  var options = { messages: { numericality: "failed validation" }, allow_blank: true };
  equal(ClientSideValidations.validators.local.numericality(element, options), undefined);
});

test('when bad value and allowing blank', function() {
  var element = $('<input type="text" />');
  var options = { messages: { numericality: "failed validation" }, allow_blank: true };
  element.val('abc123');
  equal(ClientSideValidations.validators.local.numericality(element, options), "failed validation");
});

test('when only allowing integers and value is integer', function() {
  var element = $('<input type="text" />');
  var options = { messages: { only_integer: "failed validation", numericality: "failed validation" }, only_integer: true };
  element.val('123');
  equal(ClientSideValidations.validators.local.numericality(element, options), undefined);
});

test('when only allowing integers and value is integer with whitespace', function() {
  var element = $('<input type="text" />');
  var options = { messages: { only_integer: "failed validation", numericality: "failed validation" }, only_integer: true };
  element.val(' 123 ');
  equal(ClientSideValidations.validators.local.numericality(element, options), undefined);
});

test('when only allowing integers and value has a negative or positive sign', function() {
  var element = $('<input type="text" />');
  var options = { messages: { only_integer: "failed validation", numericality: "failed validation" }, only_integer: true };
  element.val('-23');
  equal(ClientSideValidations.validators.local.numericality(element, options), undefined);
  element.val('+23');
  equal(ClientSideValidations.validators.local.numericality(element, options), undefined);
});

test('when only allowing integers and value is not integer', function() {
  var element = $('<input type="text" />');
  var options = { messages: { only_integer: "failed validation", numericality: "failed validation" }, only_integer: true };
  element.val('123.456');
  equal(ClientSideValidations.validators.local.numericality(element, options), "failed validation");
});

test('when only allowing values greater than 10 and value is greater than 10', function() {
  var element = $('<input type="text" />');
  var options = { messages: { greater_than: "failed validation", numericality: "failed validation" }, greater_than: 10 };
  element.val('11');
  equal(ClientSideValidations.validators.local.numericality(element, options), undefined);
});

test('when only allowing values greater than 10 and value is 10', function() {
  var element = $('<input type="text" />');
  var options = { messages: { greater_than: "failed validation", numericality: "failed validation" }, greater_than: 10 };
  element.val('10');
  equal(ClientSideValidations.validators.local.numericality(element, options), "failed validation");
});

test('when only allowing values greater than or equal to 10 and value is 10', function() {
  var element = $('<input type="text" />');
  var options = { messages: { greater_than_or_equal_to: "failed validation", numericality: "failed validation" }, greater_than_or_equal_to: 10 };
  element.val('10');
  equal(ClientSideValidations.validators.local.numericality(element, options), undefined);
});

test('when only allowing values greater than or equal to 10 and value is 9', function() {
  var element = $('<input type="text" />');
  var options = { messages: { greater_than_or_equal_to: "failed validation", numericality: "failed validation" }, greater_than_or_equal_to: 10 };
  element.val('9');
  equal(ClientSideValidations.validators.local.numericality(element, options), "failed validation");
});

test('when only allowing values less than 10 and value is less than 10', function() {
  var element = $('<input type="text" />');
  var options = { messages: { less_than: "failed validation", numericality: "failed validation" }, less_than: 10 };
  element.val('9');
  equal(ClientSideValidations.validators.local.numericality(element, options), undefined);
});

test('when only allowing values less than 10 and value is 10', function() {
  var element = $('<input type="text" />');
  var options = { messages: { less_than: "failed validation", numericality: "failed validation" }, less_than: 10 };
  element.val('10');
  equal(ClientSideValidations.validators.local.numericality(element, options), "failed validation");
});

test('when only allowing values less than or equal to 10 and value is 10', function() {
  var element = $('<input type="text" />');
  var options = { messages: { less_than_or_equal_to: "failed validation", numericality: "failed validation" }, less_than_or_equal_to: 10 };
  element.val('10');
  equal(ClientSideValidations.validators.local.numericality(element, options), undefined);
});

test('when only allowing values less than or equal to 10 and value is 11', function() {
  var element = $('<input type="text" />');
  var options = { messages: { less_than_or_equal_to: "failed validation", numericality: "failed validation" }, less_than_or_equal_to: 10 };
  element.val('11');
  equal(ClientSideValidations.validators.local.numericality(element, options), "failed validation");
});

test('when only allowing values equal to 10 and value is 10', function() {
  var element = $('<input type="text" />');
  var options = { messages: { equal_to: "failed validation", numericality: "failed validation" }, equal_to: 10 };
  element.val('10');
  equal(ClientSideValidations.validators.local.numericality(element, options), undefined);
});

test('when only allowing values equal to 10 and value is 11', function() {
  var element = $('<input type="text" />');
  var options = { messages: { equal_to: "failed validation", numericality: "failed validation" }, equal_to: 10 };
  element.val('11');
  equal(ClientSideValidations.validators.local.numericality(element, options), "failed validation");
});

test('when only allowing value equal to 0 and value is 1', function() {
  var element = $('<input type="text" />');
  var options = { messages: { equal_to: "failed validation", numericality: "failed validation" }, equal_to: 0 };
  element.val('1');
  equal(ClientSideValidations.validators.local.numericality(element, options), "failed validation");
});

test('when only allowing odd values and the value is odd', function() {
  var element = $('<input type="text" />');
  var options = { messages: { odd: "failed validation", numericality: "failed validation" }, odd: true };
  element.val('11');
  equal(ClientSideValidations.validators.local.numericality(element, options), undefined);
});

test('when only allowing odd values and the value is even', function() {
  var element = $('<input type="text" />');
  var options = { messages: { odd: "failed validation", numericality: "failed validation" }, odd: true };
  element.val('10');
  equal(ClientSideValidations.validators.local.numericality(element, options), "failed validation");
});

test('when only allowing even values and the value is even', function() {
  var element = $('<input type="text" />');
  var options = { messages: { even: "failed validation", numericality: "failed validation" }, even: true };
  element.val('10');
  equal(ClientSideValidations.validators.local.numericality(element, options), undefined);
});

test('when only allowing even values and the value is odd', function() {
  var element = $('<input type="text" />');
  var options = { messages: { even: "failed validation", numericality: "failed validation" }, even: true };
  element.val('11');
  equal(ClientSideValidations.validators.local.numericality(element, options), "failed validation");
});

test('when value refers to another present input', function() {
  var form = $('<form />')
  var element_1 = $('<input type="text" name="points_1" />');
  var element_2 = $('<input type="text" name="points_2" />');
  var options   = { messages: { greater_than: "failed to be greater", numericality: "failed validation" }, greater_than: 'points_2' };

  form.append(element_1).append(element_2);
  $('#qunit-fixture')
    .append(form);

  element_1.val(0)
  element_2.val(1)
  equal(ClientSideValidations.validators.local.numericality(element_1, options), "failed to be greater");
  element_1.val(2)
  equal(ClientSideValidations.validators.local.numericality(element_1, options), undefined);
});

test('when value refers to another present input but with more than one match', function() {
  var form = $('<form />')
  var element_1 = $('<input type="text" name="points_1" />');
  var element_2 = $('<input type="text" name="points_2" />');
  var element_3 = $('<input type="text" name="points_21" />');
  var options   = { messages: { greater_than: "failed to be greater", numericality: "failed validation" }, greater_than: 'points_2' };

  form.append(element_1).append(element_2).append(element_3);
  $('#qunit-fixture')
    .append(form);

  element_1.val(1)
  element_2.val(2)
  element_3.val(0)
  equal(ClientSideValidations.validators.local.numericality(element_1, options), undefined);
});
<|endoftext|>


<commit_before>(function() {
  'use strict';

  require('node_modules/reveal.js/css/reveal.css');
  require('node_modules/reveal.js/css/theme/blood.css');
  require('node_modules/font-awesome/css/font-awesome.css');
  require('node_modules/highlight.js/styles/monokai-sublime.css');

  window.hljs = require('highlight.js');
  window.Reveal = require('reveal.js');
  require('./tagcloud');
  require('reveal-code-focus');

  setTimeout(function() {
    window.Reveal.initialize({
      transition: 'convex',
      history: true,
    });
    hljs.initHighlighting();
    RevealCodeFocus();
  }, 1000);

})();
<commit_msg>rework code focus init<commit_after>(function() {
  'use strict';

  require('node_modules/reveal.js/css/reveal.css');
  require('node_modules/reveal.js/css/theme/blood.css');
  require('node_modules/font-awesome/css/font-awesome.css');
  require('node_modules/highlight.js/styles/monokai-sublime.css');

  window.hljs = require('highlight.js');
  window.Reveal = require('reveal.js');
  require('./tagcloud');

  setTimeout(function() {
    window.Reveal.initialize({
      transition: 'convex',
      history: true,
    });
    hljs.initHighlighting();
    require('script!reveal-code-focus');
    RevealCodeFocus();
  }, 1000);

})();
<|endoftext|>


<commit_before>'use strict';

goog.provide('Blockly.Blocks.math');

goog.require('Blockly.Blocks');

Blockly.Blocks.math.HUE = 230;

Blockly.FieldTextInput.math_number_validator = function(text) {
  //return window.isNaN(text) ? null : String(text);
  return String(text);//不再校验
};

Blockly.Blocks['math_number'] = {
  /**
   * Block for numeric value.
   * @this Blockly.Block
   */
  init: function() {
    this.setColour(Blockly.Blocks.math.HUE);
    this.appendDummyInput()
        .appendField(new Blockly.FieldTextInput('0',
        Blockly.FieldTextInput.math_number_validator), 'NUM');
    this.setOutput(true, Number);
    this.setTooltip(Blockly.Msg.MATH_NUMBER_TOOLTIP);
  }
};

Blockly.Blocks['math_arithmetic'] = {
  /**
   * Block for basic arithmetic operator.
   * @this Blockly.Block
   */
  init: function() {
    var OPERATORS =
        [[Blockly.Msg.MATH_ADDITION_SYMBOL, 'ADD'],
         [Blockly.Msg.MATH_SUBTRACTION_SYMBOL, 'MINUS'],
         [Blockly.Msg.MATH_MULTIPLICATION_SYMBOL, 'MULTIPLY'],
         [Blockly.Msg.MATH_DIVISION_SYMBOL, 'DIVIDE'],
		 [Blockly.Msg.MATH_QUYU_SYMBOL, 'QUYU'],
         [Blockly.Msg.MATH_POWER_SYMBOL, 'POWER']];
    //this.setHelpUrl(Blockly.Msg.MATH_ARITHMETIC_HELPURL);
    this.setColour(Blockly.Blocks.math.HUE);
    this.setOutput(true, Number);
    this.appendValueInput('A')
        .setCheck(Number);
    this.appendValueInput('B')
        .setCheck(Number)
        .appendField(new Blockly.FieldDropdown(OPERATORS), 'OP');
    this.setInputsInline(true);
    // Assign 'this' to a variable for use in the tooltip closure below.
    var thisBlock = this;
    this.setTooltip(function() {
      var mode = thisBlock.getFieldValue('OP');
      var TOOLTIPS = {
        'ADD': Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_ADD,
        'MINUS': Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_MINUS,
        'MULTIPLY': Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_MULTIPLY,
        'DIVIDE': Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_DIVIDE,
		'QUYU':Blockly.Msg.MATH_MODULO_TOOLTIP,
        'POWER': Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_POWER
      };
      return TOOLTIPS[mode];
    });
  }
};

Blockly.Blocks['math_bit'] = {
  init: function() {
    var OPERATORS =
        [['&', '&'],
         ['|', '|'],
         ['^', '^'],
        ['>>', '>>'],
        ['<<', '<<']];
    this.setColour(Blockly.Blocks.math.HUE);
    this.setOutput(true, Number);
    this.appendValueInput('A')
        .setCheck(Number);
    this.appendValueInput('B')
        .setCheck(Number)
        .appendField(new Blockly.FieldDropdown(OPERATORS), 'OP');
    this.setInputsInline(true);
	this.setTooltip("位运算");
  }
};

Blockly.Blocks['math_trig'] = {
  /**
   * Block for trigonometry operators.
   * @this Blockly.Block
   */
  init: function() {
    var OPERATORS =
        [['sin', 'SIN'],
         ['cos', 'COS'],
         ['tan', 'TAN'],
         ['asin', 'ASIN'],
         ['acos', 'ACOS'],
         ['atan', 'ATAN'],
         ['ln', 'LN'],
         ['log10', 'LOG10'],
         ['e^', 'EXP'],
         ['10^', 'POW10'],
         ['++', '++'],
         ['--', '--'],
         ['~', '~'],
        ];
    //this.setHelpUrl(Blockly.Msg.MATH_TRIG_HELPURL);
    this.setColour(Blockly.Blocks.math.HUE);
    this.setOutput(true, Number);
    this.appendValueInput('NUM')
        .setCheck(Number)
        .appendField(new Blockly.FieldDropdown(OPERATORS), 'OP');
    // Assign 'this' to a variable for use in the tooltip closure below.
    var thisBlock = this;
    this.setTooltip(function() {
      var mode = thisBlock.getFieldValue('OP');
      var TOOLTIPS = {
        'SIN': Blockly.Msg.MATH_TRIG_TOOLTIP_SIN,
        'COS': Blockly.Msg.MATH_TRIG_TOOLTIP_COS,
        'TAN': Blockly.Msg.MATH_TRIG_TOOLTIP_TAN,
        'ASIN': Blockly.Msg.MATH_TRIG_TOOLTIP_ASIN,
        'ACOS': Blockly.Msg.MATH_TRIG_TOOLTIP_ACOS,
        'ATAN': Blockly.Msg.MATH_TRIG_TOOLTIP_ATAN
      };
      return TOOLTIPS[mode];
    });
  }
};

//取整等
Blockly.Blocks['math_to_int']= {
  init: function() {
	var OPERATORS =
        [[Blockly.LANG_MATH_TO_ROUND, 'round'],
         [Blockly.LANG_MATH_TO_CEIL, 'ceil'],
         [Blockly.LANG_MATH_TO_FLOOR, 'floor'],
		 [Blockly.Msg.MATH_ABS, 'abs'],
         [Blockly.Msg.MATH_SQ, 'sq'],
         [Blockly.Msg.MATH_SQRT, 'sqrt']];
    this.setColour(Blockly.Blocks.math.HUE);
    this.appendValueInput('A')
        .setCheck(Number)
        .appendField(new Blockly.FieldDropdown(OPERATORS), 'OP');
    this.setOutput(true, Number);
	var thisBlock = this;
    this.setTooltip(function() {
      var mode = thisBlock.getFieldValue('OP');
      var TOOLTIPS = {
        'sqrt': Blockly.Msg.MATH_SINGLE_TOOLTIP_ROOT,
        'abs': Blockly.Msg.MATH_SINGLE_TOOLTIP_ABS,
        'sq': Blockly.Msg.MATH_SINGLE_TOOLTIP_SQ,
        'log': Blockly.Msg.MATH_SINGLE_TOOLTIP_LN,
        'round': Blockly.Msg.MATH_SINGLE_TOOLTIP_ROUND,
        'ceil': Blockly.Msg.MATH_SINGLE_TOOLTIP_CEIL,
        'floor': Blockly.Msg.MATH_SINGLE_TOOLTIP_FLOOR
      };
      return TOOLTIPS[mode];
    });
  }
};
//最大最小值
Blockly.Blocks['math_max_min']= {
  init: function() {
	var OPERATORS =
        [[Blockly.MIXLY_MAX, 'max'],
		 [Blockly.MIXLY_MIN, 'min'],
        ];
    this.setColour(Blockly.Blocks.math.HUE);
    this.appendValueInput('A')
        .setCheck(Number)
		.setAlign(Blockly.ALIGN_RIGHT)
        .appendField(new Blockly.FieldDropdown(OPERATORS), 'OP')
		.appendField('(');
	this.appendValueInput('B')
        .setCheck(Number)
		.setAlign(Blockly.ALIGN_RIGHT)
        .appendField(',');
	this.appendDummyInput('')
		.setAlign(Blockly.ALIGN_RIGHT)
		.appendField(')');
	this.setInputsInline(true);
    this.setOutput(true, Number);
	var thisBlock = this;
    this.setTooltip(function() {
      var mode = thisBlock.getFieldValue('OP');
      var TOOLTIPS = {
        'max': Blockly.MIXLY_TOOLTIP_MATH_MAX,
        'min': Blockly.MIXLY_TOOLTIP_MATH_MIN
      };
      return TOOLTIPS[mode];
    });
  }
};

Blockly.Blocks['math_random_seed'] = {
    init: function () {
        this.setColour(Blockly.Blocks.math.HUE);
        // this.appendDummyInput()
        //     .appendField(Blockly.LANG_MATH_RANDOM_SEED);
        this.appendValueInput('NUM')
            .setCheck(Number)
            .appendField(Blockly.LANG_MATH_RANDOM_SEED);
        this.setPreviousStatement(true);
        this.setNextStatement(true);
        this.setTooltip(Blockly.MIXLY_TOOLTIP_MATH_RANDOM_SEED);
    }
};

Blockly.Blocks['math_random_int'] = {
  /**
   * Block for random integer between [X] and [Y].
   * @this Blockly.Block
   */
  init: function() {
    this.setColour(Blockly.Blocks.math.HUE);
    this.setOutput(true, Number);
    this.appendValueInput('FROM')
        .setCheck(Number)
        .appendField(Blockly.LANG_MATH_RANDOM_INT_INPUT_FROM);
    this.appendValueInput('TO')
        .setCheck(Number)
        .setAlign(Blockly.ALIGN_RIGHT)
        .appendField(Blockly.LANG_MATH_RANDOM_INT_INPUT_TO);
    this.setInputsInline(true);
    this.setTooltip(Blockly.Msg.MATH_RANDOM_INT_TOOLTIP);
  }
};

Blockly.Blocks['math_constrain'] = {
  /**
   * Block for constraining a number between two limits.
   * @this Blockly.Block
   */
  init: function() {
    this.setColour(Blockly.Blocks.math.HUE);
    this.setOutput(true, Number);
    this.appendValueInput('VALUE')
        .setCheck(Number)
        .appendField(Blockly.LANG_MATH_CONSTRAIN_INPUT_CONSTRAIN);
    this.appendValueInput('LOW')
        .setCheck(Number)
        .appendField(Blockly.LANG_MATH_CONSTRAIN_INPUT_LOW);
    this.appendValueInput('HIGH')
        .setCheck(Number)
        .appendField(Blockly.LANG_MATH_CONSTRAIN_INPUT_HIGH);
    this.setInputsInline(true);
    this.setTooltip(Blockly.Msg.MATH_CONSTRAIN_TOOLTIP);
  }
};

Blockly.Blocks.base_map = {
  init: function() {
    this.setColour(Blockly.Blocks.math.HUE);
    this.appendValueInput("NUM", Number)
        .appendField(Blockly.MIXLY_MAP)
        .setCheck(Number);
    this.appendValueInput("fromLow", Number)
        .appendField(Blockly.MIXLY_MAP_FROM)
        .setCheck(Number);
    this.appendValueInput("fromHigh", Number)
        .appendField(",")
        .setCheck(Number);
    this.appendValueInput("toLow", Number)
        .appendField(Blockly.MIXLY_MAP_TO)
        .setCheck(Number);
    this.appendValueInput("toHigh", Number)
        .appendField(",")
        .setCheck(Number);
    this.appendDummyInput("")
	      .appendField("]");
    this.setInputsInline(true);
    this.setOutput(true);
	this.setTooltip(Blockly.MIXLY_TOOLTIP_MATH_MAP);
  }
};<commit_msg>add helpurl<commit_after>'use strict';

goog.provide('Blockly.Blocks.math');

goog.require('Blockly.Blocks');

Blockly.Blocks.math.HUE = 230;

Blockly.FieldTextInput.math_number_validator = function(text) {
  //return window.isNaN(text) ? null : String(text);
  return String(text);//不再校验
};

Blockly.Blocks['math_number'] = {
  /**
   * Block for numeric value.
   * @this Blockly.Block
   */
   init: function() {
    this.setColour(Blockly.Blocks.math.HUE);
    this.appendDummyInput()
    .appendField(new Blockly.FieldTextInput('0',
      Blockly.FieldTextInput.math_number_validator), 'NUM');
    this.setOutput(true, Number);
    this.setTooltip(Blockly.Msg.MATH_NUMBER_TOOLTIP);
    this.setHelpUrl("https://mixly.readthedocs.io/zh_CN/latest/arduino/04.Mathematics.html#id2");
  }
};

Blockly.Blocks['math_arithmetic'] = {
  /**
   * Block for basic arithmetic operator.
   * @this Blockly.Block
   */
   init: function() {
    var OPERATORS =
    [[Blockly.Msg.MATH_ADDITION_SYMBOL, 'ADD'],
    [Blockly.Msg.MATH_SUBTRACTION_SYMBOL, 'MINUS'],
    [Blockly.Msg.MATH_MULTIPLICATION_SYMBOL, 'MULTIPLY'],
    [Blockly.Msg.MATH_DIVISION_SYMBOL, 'DIVIDE'],
    [Blockly.Msg.MATH_QUYU_SYMBOL, 'QUYU'],
    [Blockly.Msg.MATH_POWER_SYMBOL, 'POWER']];
    //this.setHelpUrl(Blockly.Msg.MATH_ARITHMETIC_HELPURL);
    this.setColour(Blockly.Blocks.math.HUE);
    this.setOutput(true, Number);
    this.appendValueInput('A')
    .setCheck(Number);
    this.setHelpUrl("https://mixly.readthedocs.io/zh_CN/latest/arduino/04.Mathematics.html#id4");
    this.appendValueInput('B')
    .setCheck(Number)
    .appendField(new Blockly.FieldDropdown(OPERATORS), 'OP');
    this.setInputsInline(true);
    // Assign 'this' to a variable for use in the tooltip closure below.
    var thisBlock = this;
    this.setTooltip(function() {
      var mode = thisBlock.getFieldValue('OP');
      var TOOLTIPS = {
        'ADD': Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_ADD,
        'MINUS': Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_MINUS,
        'MULTIPLY': Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_MULTIPLY,
        'DIVIDE': Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_DIVIDE,
        'QUYU':Blockly.Msg.MATH_MODULO_TOOLTIP,
        'POWER': Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_POWER
      };
      return TOOLTIPS[mode];
    });
  }
};

Blockly.Blocks['math_bit'] = {
  init: function() {
    var OPERATORS =
    [['&', '&'],
    ['|', '|'],
    ['^', '^'],
    ['>>', '>>'],
    ['<<', '<<']];
    this.setColour(Blockly.Blocks.math.HUE);
    this.setOutput(true, Number);
    this.appendValueInput('A')
    .setCheck(Number);
    this.appendValueInput('B')
    .setCheck(Number)
    .appendField(new Blockly.FieldDropdown(OPERATORS), 'OP');
    this.setInputsInline(true);
    this.setTooltip("位运算");
    this.setHelpUrl("https://mixly.readthedocs.io/zh_CN/latest/arduino/04.Mathematics.html#id8");
  }
};

Blockly.Blocks['math_trig'] = {
  /**
   * Block for trigonometry operators.
   * @this Blockly.Block
   */
   init: function() {
    var OPERATORS =
    [['sin', 'SIN'],
    ['cos', 'COS'],
    ['tan', 'TAN'],
    ['asin', 'ASIN'],
    ['acos', 'ACOS'],
    ['atan', 'ATAN'],
    ['ln', 'LN'],
    ['log10', 'LOG10'],
    ['e^', 'EXP'],
    ['10^', 'POW10'],
    ['++', '++'],
    ['--', '--'],
    ['~', '~'],
    ];
    //this.setHelpUrl(Blockly.Msg.MATH_TRIG_HELPURL);
    this.setColour(Blockly.Blocks.math.HUE);
    this.setOutput(true, Number);
    this.appendValueInput('NUM')
    .setCheck(Number)
    .appendField(new Blockly.FieldDropdown(OPERATORS), 'OP');
    // Assign 'this' to a variable for use in the tooltip closure below.
    var thisBlock = this;
    this.setHelpUrl("https://mixly.readthedocs.io/zh_CN/latest/arduino/04.Mathematics.html#id17");
    this.setTooltip(function() {
      var mode = thisBlock.getFieldValue('OP');
      var TOOLTIPS = {
        'SIN': Blockly.Msg.MATH_TRIG_TOOLTIP_SIN,
        'COS': Blockly.Msg.MATH_TRIG_TOOLTIP_COS,
        'TAN': Blockly.Msg.MATH_TRIG_TOOLTIP_TAN,
        'ASIN': Blockly.Msg.MATH_TRIG_TOOLTIP_ASIN,
        'ACOS': Blockly.Msg.MATH_TRIG_TOOLTIP_ACOS,
        'ATAN': Blockly.Msg.MATH_TRIG_TOOLTIP_ATAN
      };
      return TOOLTIPS[mode];
    });
  }
};

//取整等
Blockly.Blocks['math_to_int']= {
  init: function() {
   var OPERATORS =
   [[Blockly.LANG_MATH_TO_ROUND, 'round'],
   [Blockly.LANG_MATH_TO_CEIL, 'ceil'],
   [Blockly.LANG_MATH_TO_FLOOR, 'floor'],
   [Blockly.Msg.MATH_ABS, 'abs'],
   [Blockly.Msg.MATH_SQ, 'sq'],
   [Blockly.Msg.MATH_SQRT, 'sqrt']];
   this.setColour(Blockly.Blocks.math.HUE);
   this.appendValueInput('A')
   .setCheck(Number)
   .appendField(new Blockly.FieldDropdown(OPERATORS), 'OP');
   this.setOutput(true, Number);
   this.setHelpUrl("https://mixly.readthedocs.io/zh_CN/latest/arduino/04.Mathematics.html#id18");
   var thisBlock = this;
   this.setTooltip(function() {
    var mode = thisBlock.getFieldValue('OP');
    var TOOLTIPS = {
      'sqrt': Blockly.Msg.MATH_SINGLE_TOOLTIP_ROOT,
      'abs': Blockly.Msg.MATH_SINGLE_TOOLTIP_ABS,
      'sq': Blockly.Msg.MATH_SINGLE_TOOLTIP_SQ,
      'log': Blockly.Msg.MATH_SINGLE_TOOLTIP_LN,
      'round': Blockly.Msg.MATH_SINGLE_TOOLTIP_ROUND,
      'ceil': Blockly.Msg.MATH_SINGLE_TOOLTIP_CEIL,
      'floor': Blockly.Msg.MATH_SINGLE_TOOLTIP_FLOOR
    };
    return TOOLTIPS[mode];
  });
 }
};
//最大最小值
Blockly.Blocks['math_max_min']= {
  init: function() {
   var OPERATORS =
   [[Blockly.MIXLY_MAX, 'max'],
   [Blockly.MIXLY_MIN, 'min'],
   ];
   this.setColour(Blockly.Blocks.math.HUE);
   this.appendValueInput('A')
   .setCheck(Number)
   .setAlign(Blockly.ALIGN_RIGHT)
   .appendField(new Blockly.FieldDropdown(OPERATORS), 'OP')
   .appendField('(');
   this.appendValueInput('B')
   .setCheck(Number)
   .setAlign(Blockly.ALIGN_RIGHT)
   .appendField(',');
   this.appendDummyInput('')
   .setAlign(Blockly.ALIGN_RIGHT)
   .appendField(')');
   this.setInputsInline(true);
   this.setHelpUrl("https://mixly.readthedocs.io/zh_CN/latest/arduino/04.Mathematics.html#min-max");
   this.setOutput(true, Number);
   var thisBlock = this;
   this.setTooltip(function() {
    var mode = thisBlock.getFieldValue('OP');
    var TOOLTIPS = {
      'max': Blockly.MIXLY_TOOLTIP_MATH_MAX,
      'min': Blockly.MIXLY_TOOLTIP_MATH_MIN
    };
    return TOOLTIPS[mode];
  });
 }
};

Blockly.Blocks['math_random_seed'] = {
  init: function () {
    this.setColour(Blockly.Blocks.math.HUE);
        // this.appendDummyInput()
        //     .appendField(Blockly.LANG_MATH_RANDOM_SEED);
        this.appendValueInput('NUM')
        .setCheck(Number)
        .appendField(Blockly.LANG_MATH_RANDOM_SEED);
        this.setPreviousStatement(true);
        this.setNextStatement(true);
        this.setTooltip(Blockly.MIXLY_TOOLTIP_MATH_RANDOM_SEED);
        this.setHelpUrl("https://mixly.readthedocs.io/zh_CN/latest/arduino/04.Mathematics.html#randomseed");
      }
    };

    Blockly.Blocks['math_random_int'] = {
  /**
   * Block for random integer between [X] and [Y].
   * @this Blockly.Block
   */
   init: function() {
    this.setColour(Blockly.Blocks.math.HUE);
    this.setOutput(true, Number);
    this.appendValueInput('FROM')
    .setCheck(Number)
    .appendField(Blockly.LANG_MATH_RANDOM_INT_INPUT_FROM);
    this.appendValueInput('TO')
    .setCheck(Number)
    .setAlign(Blockly.ALIGN_RIGHT)
    .appendField(Blockly.LANG_MATH_RANDOM_INT_INPUT_TO);
    this.setInputsInline(true);
    this.setTooltip(Blockly.Msg.MATH_RANDOM_INT_TOOLTIP);
    this.setHelpUrl("https://mixly.readthedocs.io/zh_CN/latest/arduino/04.Mathematics.html#random");
  }
};

Blockly.Blocks['math_constrain'] = {
  /**
   * Block for constraining a number between two limits.
   * @this Blockly.Block
   */
   init: function() {
    this.setColour(Blockly.Blocks.math.HUE);
    this.setOutput(true, Number);
    this.appendValueInput('VALUE')
    .setCheck(Number)
    .appendField(Blockly.LANG_MATH_CONSTRAIN_INPUT_CONSTRAIN);
    this.appendValueInput('LOW')
    .setCheck(Number)
    .appendField(Blockly.LANG_MATH_CONSTRAIN_INPUT_LOW);
    this.appendValueInput('HIGH')
    .setCheck(Number)
    .appendField(Blockly.LANG_MATH_CONSTRAIN_INPUT_HIGH);
    this.setInputsInline(true);
    this.setTooltip(Blockly.Msg.MATH_CONSTRAIN_TOOLTIP);
    this.setHelpUrl("https://mixly.readthedocs.io/zh_CN/latest/arduino/04.Mathematics.html#constrain");
  }
};

Blockly.Blocks.base_map = {
  init: function() {
    this.setColour(Blockly.Blocks.math.HUE);
    this.appendValueInput("NUM", Number)
    .appendField(Blockly.MIXLY_MAP)
    .setCheck(Number);
    this.appendValueInput("fromLow", Number)
    .appendField(Blockly.MIXLY_MAP_FROM)
    .setCheck(Number);
    this.appendValueInput("fromHigh", Number)
    .appendField(",")
    .setCheck(Number);
    this.appendValueInput("toLow", Number)
    .appendField(Blockly.MIXLY_MAP_TO)
    .setCheck(Number);
    this.appendValueInput("toHigh", Number)
    .appendField(",")
    .setCheck(Number);
    this.appendDummyInput("")
    .appendField("]");
    this.setInputsInline(true);
    this.setOutput(true);
    this.setTooltip(Blockly.MIXLY_TOOLTIP_MATH_MAP);
    this.setHelpUrl("https://mixly.readthedocs.io/zh_CN/latest/arduino/04.Mathematics.html#map");
  }
};<|endoftext|>


<commit_before>this.sharedFromJavascript = 321;
<commit_msg>Don't use `this` when testing ES5 variable export<commit_after>sharedFromJavascript = 321;
<|endoftext|>


<commit_before>import { isMobile } from './util'

/**
 * Active sidebar when scroll
 * @link https://buble.surge.sh/
 */
export function scrollActiveSidebar () {
  if (isMobile()) return

  let hoveredOverSidebar = false
  const anchors = document.querySelectorAll('.anchor')
  const sidebar = document.querySelector('.sidebar')
  const sidebarHeight = sidebar.clientHeight

  const nav = {}
  const lis = sidebar.querySelectorAll('li')
  let active = sidebar.querySelector('li.active')

  for (let i = 0, len = lis.length; i < len; i += 1) {
    const li = lis[i]
    let href = li.querySelector('a').getAttribute('href')

    if (href !== '/') {
      const match = href.match('#([^#]+)$')
      if (match && match.length) href = match[0].slice(1)
    }

    nav[decodeURIComponent(href)] = li
  }

  function highlight () {
    const top = document.body.scrollTop
    let last

    for (let i = 0, len = anchors.length; i < len; i += 1) {
      const node = anchors[i]

      if (node.offsetTop > top) {
        if (!last) last = node
        break
      } else {
        last = node
      }
    }
    if (!last) return
    const li = nav[last.getAttribute('data-id')]

    if (!li || li === active) return
    if (active) active.classList.remove('active')

    li.classList.add('active')
    active = li

    // scroll into view
    // https://github.com/vuejs/vuejs.org/blob/master/themes/vue/source/js/common.js#L282-L297
    if (!hoveredOverSidebar && !sticky.noSticky) {
      const currentPageOffset = 0
      const currentActiveOffset = active.offsetTop + active.clientHeight + 40
      const currentActiveIsInView = (
        active.offsetTop >= sidebar.scrollTop &&
        currentActiveOffset <= sidebar.scrollTop + sidebarHeight
      )
      const linkNotFurtherThanSidebarHeight = currentActiveOffset - currentPageOffset < sidebarHeight
      const newScrollTop = currentActiveIsInView
        ? sidebar.scrollTop
        : linkNotFurtherThanSidebarHeight
          ? currentPageOffset
          : currentActiveOffset - sidebarHeight

      sidebar.scrollTop = newScrollTop
    }
  }

  window.removeEventListener('scroll', highlight)
  window.addEventListener('scroll', highlight)
  sidebar.addEventListener('mouseover', () => { hoveredOverSidebar = true })
  sidebar.addEventListener('mouseleave', () => { hoveredOverSidebar = false })
}

export function scrollIntoView () {
  const id = window.location.hash.match(/#[^#\/]+$/g)
  if (!id || !id.length) return
  const section = document.querySelector(decodeURIComponent(id[0]))

  if (section) setTimeout(() => section.scrollIntoView(), 0)

  return section
}

/**
 * Acitve link
 */
export function activeLink (dom, activeParent) {
  const host = window.location.href

  dom = typeof dom === 'object' ? dom : document.querySelector(dom)
  if (!dom) return
  let target

  ;[].slice.call(dom.querySelectorAll('a'))
    .sort((a, b) => b.href.length - a.href.length)
    .forEach(node => {
      if (host.indexOf(node.href) === 0 && !target) {
        activeParent
          ? node.parentNode.classList.add('active')
          : node.classList.add('active')
        target = node
      } else {
        activeParent
          ? node.parentNode.classList.remove('active')
          : node.classList.remove('active')
      }
    })

  return target
}

/**
 * sidebar toggle
 */
export function bindToggle (dom) {
  dom = typeof dom === 'object' ? dom : document.querySelector(dom)
  if (!dom) return
  const body = document.body

  dom.addEventListener('click', () => body.classList.toggle('close'))

  if (isMobile()) {
    const sidebar = document.querySelector('.sidebar')
    sidebar.addEventListener('click', () => {
      body.classList.toggle('close')
      setTimeout(() => activeLink(sidebar, true), 0)
    })
  }
}

export function scroll2Top (offset = 0) {
  document.body.scrollTop = offset === true ? 0 : Number(offset)
}

export function sticky () {
  sticky.dom = sticky.dom || document.querySelector('section.cover')
  const coverHeight = sticky.dom.getBoundingClientRect().height

  return (function () {
    if (window.pageYOffset >= coverHeight || sticky.dom.classList.contains('hidden')) {
      document.body.classList.add('sticky')
      sticky.noSticky = false
    } else {
      document.body.classList.remove('sticky')
      sticky.noSticky = true
    }
  })()
}
<commit_msg>fix(event): scroll active sidebar<commit_after>import { isMobile } from './util'

/**
 * Active sidebar when scroll
 * @link https://buble.surge.sh/
 */
export function scrollActiveSidebar () {
  if (isMobile()) return

  let hoveredOverSidebar = false
  const anchors = document.querySelectorAll('.anchor')
  const sidebar = document.querySelector('.sidebar')
  const sidebarContainer = sidebar.querySelector('.sidebar-nav')
  const sidebarHeight = sidebar.clientHeight

  const nav = {}
  const lis = sidebar.querySelectorAll('li')
  let active = sidebar.querySelector('li.active')

  for (let i = 0, len = lis.length; i < len; i += 1) {
    const li = lis[i]
    let href = li.querySelector('a').getAttribute('href')

    if (href !== '/') {
      const match = href.match('#([^#]+)$')
      if (match && match.length) href = match[0].slice(1)
    }

    nav[decodeURIComponent(href)] = li
  }

  function highlight () {
    const top = document.body.scrollTop
    let last

    for (let i = 0, len = anchors.length; i < len; i += 1) {
      const node = anchors[i]

      if (node.offsetTop > top) {
        if (!last) last = node
        break
      } else {
        last = node
      }
    }
    if (!last) return
    const li = nav[last.getAttribute('data-id')]

    if (!li || li === active) return
    if (active) active.classList.remove('active')

    li.classList.add('active')
    active = li

    // scroll into view
    // https://github.com/vuejs/vuejs.org/blob/master/themes/vue/source/js/common.js#L282-L297
    if (!hoveredOverSidebar && !sticky.noSticky) {
      const currentPageOffset = 0
      const currentActiveOffset = active.offsetTop + active.clientHeight + 40
      const currentActiveIsInView = (
        active.offsetTop >= sidebarContainer.scrollTop &&
        currentActiveOffset <= sidebarContainer.scrollTop + sidebarHeight
      )
      const linkNotFurtherThanSidebarHeight = currentActiveOffset - currentPageOffset < sidebarHeight
      const newScrollTop = currentActiveIsInView
        ? sidebarContainer.scrollTop
        : linkNotFurtherThanSidebarHeight
          ? currentPageOffset
          : currentActiveOffset - sidebarHeight

      sidebar.scrollTop = newScrollTop
    }
  }

  window.removeEventListener('scroll', highlight)
  window.addEventListener('scroll', highlight)
  sidebar.addEventListener('mouseover', () => { hoveredOverSidebar = true })
  sidebar.addEventListener('mouseleave', () => { hoveredOverSidebar = false })
}

export function scrollIntoView () {
  const id = window.location.hash.match(/#[^#\/]+$/g)
  if (!id || !id.length) return
  const section = document.querySelector(decodeURIComponent(id[0]))

  if (section) setTimeout(() => section.scrollIntoView(), 0)

  return section
}

/**
 * Acitve link
 */
export function activeLink (dom, activeParent) {
  const host = window.location.href

  dom = typeof dom === 'object' ? dom : document.querySelector(dom)
  if (!dom) return
  let target

  ;[].slice.call(dom.querySelectorAll('a'))
    .sort((a, b) => b.href.length - a.href.length)
    .forEach(node => {
      if (host.indexOf(node.href) === 0 && !target) {
        activeParent
          ? node.parentNode.classList.add('active')
          : node.classList.add('active')
        target = node
      } else {
        activeParent
          ? node.parentNode.classList.remove('active')
          : node.classList.remove('active')
      }
    })

  return target
}

/**
 * sidebar toggle
 */
export function bindToggle (dom) {
  dom = typeof dom === 'object' ? dom : document.querySelector(dom)
  if (!dom) return
  const body = document.body

  dom.addEventListener('click', () => body.classList.toggle('close'))

  if (isMobile()) {
    const sidebar = document.querySelector('.sidebar')
    sidebar.addEventListener('click', () => {
      body.classList.toggle('close')
      setTimeout(() => activeLink(sidebar, true), 0)
    })
  }
}

export function scroll2Top (offset = 0) {
  document.body.scrollTop = offset === true ? 0 : Number(offset)
}

export function sticky () {
  sticky.dom = sticky.dom || document.querySelector('section.cover')
  const coverHeight = sticky.dom.getBoundingClientRect().height

  return (function () {
    if (window.pageYOffset >= coverHeight || sticky.dom.classList.contains('hidden')) {
      document.body.classList.add('sticky')
      sticky.noSticky = false
    } else {
      document.body.classList.remove('sticky')
      sticky.noSticky = true
    }
  })()
}
<|endoftext|>


<commit_before>(function($){
  var $$ = $.qsa, handlers = [], zid = 1;
  function id(element) {
    return element._zid || (element._zid = zid++);
  }
  function find(element, event, fn) {
    return handlers.filter(function(handler){
      return handler && handler.id === id(element) &&
        (!event || handler.event === event) && (!fn || handler.fn === fn);
    });
  }

  $.event = {
    add: function(element, events, fn){
      events.split(/\s/).forEach(function(event){
        var handler = {event: event, id: id(element), fn: fn, i: handlers.length};
        handlers.push(handler);
        element.addEventListener(event, fn, false);
      });
    },
    remove: function(element, events, fn){
      (events || '').split(/\s/).forEach(function(event){
        find(element, event, fn).forEach(function(handler){
          handlers[handler.i] = null;
          element.removeEventListener(handler.event, handler.fn, false);
        });
      });
    }
  };
  $.fn.bind = function(event, callback){
    return this.each(function(element){
      $.event.add(element, event, callback);
    });
  };
  $.fn.unbind = function(event, callback){
    return this.each(function(element){
      $.event.remove(element, event, callback);
    });
  };
  $.fn.delegate = function(selector, event, callback){
    return this.each(function(element){
      $.event.add(element, event, function(e){
        var target = e.target, nodes = $$(element, selector);
        var proxy = {originalEvent: e, liveFired: element};
        while (target && nodes.indexOf(target) < 0) target = target.parentNode;
        $.extend(proxy, e).currentTarget = target;
        if (target && !(target === element) && !(target === document)) callback.call(target, proxy);
      });
    });
  };
  $.fn.live = function(event, callback){
    $(document.body).delegate(this.selector, event, callback); return this;
  };
  $.fn.trigger = function(event){
    return this.each(function(element){
      var e = document.createEvent('Events');
      element.dispatchEvent(e, e.initEvent(event, true, false));
    });
  };
})(Zepto);
<commit_msg>Index handlers by id<commit_after>(function($){
  var $$ = $.qsa, handlers = {}, _zid = 1;
  function zid(element) {
    return element._zid || (element._zid = _zid++);
  }
  function find(element, event, fn) {
    return handlers[zid(element)].filter(function(handler) {
      return handler && (!event || handler.event === event)
        && (!fn || handler.fn === fn);
    });
  }

  $.event = {
    add: function(element, events, fn){
      var id = zid(element);
      handlers[id] || (handlers[id] = []);
      events.split(/\s/).forEach(function(event){
        var handler = {event: event, fn: fn, i: handlers[id].length};
        handlers[id].push(handler);
        element.addEventListener(event, fn, false);
      });
    },
    remove: function(element, events, fn){
      var id = zid(element);
      (events || '').split(/\s/).forEach(function(event){
        find(element, event, fn).forEach(function(handler){
          delete handlers[id][handler.i];
          element.removeEventListener(handler.event, handler.fn, false);
        });
      });
    }
  };
  $.fn.bind = function(event, callback){
    return this.each(function(element){
      $.event.add(element, event, callback);
    });
  };
  $.fn.unbind = function(event, callback){
    return this.each(function(element){
      $.event.remove(element, event, callback);
    });
  };
  $.fn.delegate = function(selector, event, callback){
    return this.each(function(element){
      $.event.add(element, event, function(e){
        var target = e.target, nodes = $$(element, selector);
        var proxy = {originalEvent: e, liveFired: element};
        while (target && nodes.indexOf(target) < 0) target = target.parentNode;
        $.extend(proxy, e).currentTarget = target;
        if (target && !(target === element) && !(target === document)) callback.call(target, proxy);
      });
    });
  };
  $.fn.live = function(event, callback){
    $(document.body).delegate(this.selector, event, callback); return this;
  };
  $.fn.trigger = function(event){
    return this.each(function(element){
      var e = document.createEvent('Events');
      element.dispatchEvent(e, e.initEvent(event, true, false));
    });
  };
})(Zepto);
<|endoftext|>


<commit_before>// Fetches posts and comments efficiently from a Facebook page or group using multiquery FQL.

var config = require('../../../config/secrets').get().facebook;
var ContentService = require('../content-service');
var graph = require('fbgraph');
var util = require('util');
var _ = require('underscore');

// options.url - The url of the Facebook resource
// options.lastReportDate - The time of the last report already fetched (optional)
var FacebookContentService = function(options) {
  graph.setAccessToken(config.accessToken);
  this.fetchType = 'pull';
  this._url = options.url;
  ContentService.call(this, options);
};

util.inherits(FacebookContentService, ContentService);

// Fetch from the Facebook Content Service
// options.maxCount - Max number of reports that will be accepted. (required)
// callback(reportData) - Callback via which to return fetched report data.
// We don't actually care about maxCount in this function, we just rely on Facebook's API limits to limit data per fetch.
// If we return too many items, that is ok, the parent class will handle it.
FacebookContentService.prototype._doFetch = function(options, callback) {
  var self = this;

  if (!this._url) {
    process.nextTick(function() { self.emit('error', new Error('Missing Facebook URL')); });
    callback([]);
    return;
  }

  var queries = {};

  // Determine Source ID of object
  queries.source = 'SELECT id, site, type, url FROM object_url WHERE url = "' + this._url + '"';

  // Fetch posts and comments
  queries.posts = 'SELECT source_id, post_id, updated_time, created_time, actor_id, permalink, message';
  queries.posts += ' FROM stream';
  queries.posts += ' WHERE source_id IN (SELECT id FROM #source)';
  // New comments trigger a fresh updated_time in its parent post
  if (this._lastReportDate) queries.posts += ' AND updated_time > ' + (this._lastReportDate.getTime()/1000);
  queries.posts += ' ORDER BY updated_time';

  // Get new comments associated with posts.
  queries.comments = "SELECT id, fromid, time, text, post_id FROM comment WHERE (post_id IN (SELECT post_id FROM #posts))";
  if (this._lastReportDate) queries.comments += ' AND time > ' + (this._lastReportDate.getTime()/1000);
  queries.comments += ' ORDER BY time';

  queries.authors = 'SELECT id, name FROM profile WHERE id IN (SELECT actor_id FROM #posts) OR id IN (SELECT fromid FROM #comments)';

  this._doRequest(queries, function(err, res) {
    if (err) {
      self.emit('error', new Error(err.message))
      callback([]);
    }

    // This will be an array of info about the source.
    var sourceInfo = _.findWhere(res.data, {name: 'source'}).fql_result_set;

    if (sourceInfo.length === 0) {
      self.emit('error', new Error('Invalid Facebook URL'));
      callback([]);
    } else {
      var posts = _.findWhere(res.data, {name: 'posts'}).fql_result_set;
      var comments = _.findWhere(res.data, {name: 'comments'}).fql_result_set;
      var authors = _.findWhere(res.data, {name: 'authors'}).fql_result_set;
      callback(self._handleResults(posts, comments, authors));
    }
  });
};

// Runs the FQL request
// queries - The queries to run
// callback(err, data) - The callback via which to return the resulting data.
FacebookContentService.prototype._doRequest = function(queries, callback) {
  graph.fql(queries, function(err, res) {
    if (err)
      callback(err, []);
    else
      callback(null, res);
  });
};

// Handle data returned by the FQL query. Returns an array of hashes of report data
// (does not need to be sorted, parent class handles that).
FacebookContentService.prototype._handleResults = function(posts, comments, authors) {
  var self = this;
  var reportData = [];
  var postsById = _.indexBy(posts, 'post_id');

  // Handle each post.
  posts.forEach(function(post) {
    reportData.push(self._parse(post, {type: 'post', authors: authors}));
  });

  // Handle each comment.
  comments.forEach(function(comment) {
    reportData.push(self._parse(comment, {type: 'comment', authors: authors, post: postsById[comment.post_id]}));
  });

  // Remove any that are too old.
  // (Remember, we are grabbing posts by updated_time to get at their comments, but we may have already stored them).
  if (self._lastReportDate)
    reportData = _.filter(reportData, function(rd) { return rd.authoredAt > self._lastReportDate });

  return reportData;
};

// Parse each fql result into our data format
FacebookContentService.prototype._parse = function(data, options) {
  switch (options.type) {
    case 'post':
      return {
        authoredAt: new Date(data.created_time * 1000),
        fetchedAt: new Date(),
        content: data.message,
        author: this._findAuthor(data.actor_id, options.authors),
        url: data.permalink
      };
    case 'comment':
      return {
        authoredAt: new Date(data.time * 1000),
        fetchedAt: new Date(),
        content: data.text,
        author: this._findAuthor(data.fromid, options.authors),
        url: options.post.permalink
      };
  }
};

// Determine the author of a report
FacebookContentService.prototype._findAuthor = function(id, authors) {
  var author = _.findWhere(authors, {id: id});
  if (author) return author.name;
  return id;
};

module.exports = FacebookContentService;
<commit_msg>#1906 - fixed facebook fetching issue<commit_after>// Fetches posts and comments efficiently from a Facebook page or group using multiquery FQL.

var config = require('../../../config/secrets').get().facebook;
var ContentService = require('../content-service');
var graph = require('fbgraph');
var util = require('util');
var _ = require('underscore');

// options.url - The url of the Facebook resource
// options.lastReportDate - The time of the last report already fetched (optional)
var FacebookContentService = function(options) {
  graph.setAccessToken(config.accessToken);
  this.fetchType = 'pull';
  this._url = options.url;
  ContentService.call(this, options);
};

util.inherits(FacebookContentService, ContentService);

// Fetch from the Facebook Content Service
// options.maxCount - Max number of reports that will be accepted. (required)
// callback(reportData) - Callback via which to return fetched report data.
// We don't actually care about maxCount in this function, we just rely on Facebook's API limits to limit data per fetch.
// If we return too many items, that is ok, the parent class will handle it.
FacebookContentService.prototype._doFetch = function(options, callback) {
  var self = this;

  if (!this._url) {
    process.nextTick(function() { self.emit('error', new Error('Missing Facebook URL')); });
    callback([]);
    return;
  }

  var queries = {};

  // Determine Source ID of object
  queries.source = 'SELECT id, site, type, url FROM object_url WHERE url = "' + this._url + '"';

  // Fetch posts and comments
  queries.posts = 'SELECT source_id, post_id, updated_time, created_time, actor_id, permalink, message';
  queries.posts += ' FROM stream';
  queries.posts += ' WHERE source_id IN (SELECT id FROM #source)';
  // New comments trigger a fresh updated_time in its parent post
  if (this._lastReportDate) queries.posts += ' AND updated_time > ' + (this._lastReportDate.getTime()/1000);
  queries.posts += ' ORDER BY updated_time';

  // Get new comments associated with posts.
  queries.comments = "SELECT id, fromid, time, text, post_id FROM comment WHERE (post_id IN (SELECT post_id FROM #posts))";
  if (this._lastReportDate) queries.comments += ' AND time > ' + (this._lastReportDate.getTime()/1000);
  queries.comments += ' ORDER BY time';

  queries.authors = 'SELECT id, name FROM profile WHERE id IN (SELECT actor_id FROM #posts) OR id IN (SELECT fromid FROM #comments)';

  this._doRequest(queries, function(err, res) {
    if (err) {
      self.emit('error', new Error(err.message))
      return callback([]);
    }

    // This will be an array of info about the source.
    var sourceInfo = _.findWhere(res.data, {name: 'source'}).fql_result_set;

    if (sourceInfo.length === 0) {
      self.emit('error', new Error('Invalid Facebook URL'));
      callback([]);
    } else {
      var posts = _.findWhere(res.data, {name: 'posts'}).fql_result_set;
      var comments = _.findWhere(res.data, {name: 'comments'}).fql_result_set;
      var authors = _.findWhere(res.data, {name: 'authors'}).fql_result_set;
      callback(self._handleResults(posts, comments, authors));
    }
  });
};

// Runs the FQL request
// queries - The queries to run
// callback(err, data) - The callback via which to return the resulting data.
FacebookContentService.prototype._doRequest = function(queries, callback) {
  graph.fql(queries, function(err, res) {
    if (err)
      callback(err, []);
    else
      callback(null, res);
  });
};

// Handle data returned by the FQL query. Returns an array of hashes of report data
// (does not need to be sorted, parent class handles that).
FacebookContentService.prototype._handleResults = function(posts, comments, authors) {
  var self = this;
  var reportData = [];
  var postsById = _.indexBy(posts, 'post_id');

  // Handle each post.
  posts.forEach(function(post) {
    reportData.push(self._parse(post, {type: 'post', authors: authors}));
  });

  // Handle each comment.
  comments.forEach(function(comment) {
    reportData.push(self._parse(comment, {type: 'comment', authors: authors, post: postsById[comment.post_id]}));
  });

  // Remove any that are too old.
  // (Remember, we are grabbing posts by updated_time to get at their comments, but we may have already stored them).
  if (self._lastReportDate)
    reportData = _.filter(reportData, function(rd) { return rd.authoredAt > self._lastReportDate });

  return reportData;
};

// Parse each fql result into our data format
FacebookContentService.prototype._parse = function(data, options) {
  switch (options.type) {
    case 'post':
      return {
        authoredAt: new Date(data.created_time * 1000),
        fetchedAt: new Date(),
        content: data.message,
        author: this._findAuthor(data.actor_id, options.authors),
        url: data.permalink
      };
    case 'comment':
      return {
        authoredAt: new Date(data.time * 1000),
        fetchedAt: new Date(),
        content: data.text,
        author: this._findAuthor(data.fromid, options.authors),
        url: options.post.permalink
      };
  }
};

// Determine the author of a report
FacebookContentService.prototype._findAuthor = function(id, authors) {
  var author = _.findWhere(authors, {id: id});
  if (author) return author.name;
  return id;
};

module.exports = FacebookContentService;
<|endoftext|>


<commit_before>apos.define('apostrophe-pieces-widgets-editor', {
  extend: 'apostrophe-widgets-editor',
  construct: function(self, options) {

    // Clone two levels deep so we can add hints without modifying original
    self.schema = _.map(self.schema, function(field) {
      return _.clone(field);
    });

    var join = _.find(self.schema, { name: '_pieces' });
    if (join) {
      _.defaults(join, { hints: {} });
      _.defaults(join.hints, { limit: options.limit });
    }

    self.shouldSkipModal = function() {
      return (self.schema.length === 2) && (self.schema[0].name === 'by') && (self.schema[1].name === '_pieces');
    };

    var superBeforeShow = self.beforeShow;
    self.beforeShow = function(callback) {
      return superBeforeShow(function(err) {
        if (err) {
          return callback(err);
        }
        if (self.shouldSkipModal()) {
          // We're not visible but we still have a role to play. We don't want to rewrite
          // all of the chooser logic for orchestrating "browse" to work without us
          self.$el.css('opacity', 0);
          // TODO: better support for "nominal" modals in modal.js so that we don't have to
          // kill the ability to have the manage modal slide in over whatever preceded this
          // self.$el.removeClass('apos-modal-slideable');
          self.chooser = self.$el.find('[data-chooser]:first').data('aposChooser');
        }
        return callback(null);
      });
    };

    var superAfterShow = self.afterShow;
    self.afterShow = function() {
      superAfterShow();
      if (self.shouldSkipModal()) {
        self.chooser.afterManagerSave = function() {
          self.save();
        };
        self.chooser.afterManagerCancel = function() {
          self.$el.css('opacity', 1);
          self.cancel();
        };
        self.chooser.launchBrowser()
      }
    };
  }
});
<commit_msg>skipable modals: removing apos-modal-slideable class.  fixes bug causing slideshow modals within areas not to be opened<commit_after>apos.define('apostrophe-pieces-widgets-editor', {
  extend: 'apostrophe-widgets-editor',
  construct: function(self, options) {

    // Clone two levels deep so we can add hints without modifying original
    self.schema = _.map(self.schema, function(field) {
      return _.clone(field);
    });

    var join = _.find(self.schema, { name: '_pieces' });
    if (join) {
      _.defaults(join, { hints: {} });
      _.defaults(join.hints, { limit: options.limit });
    }

    self.shouldSkipModal = function() {
      return (self.schema.length === 2) && (self.schema[0].name === 'by') && (self.schema[1].name === '_pieces');
    };

    var superBeforeShow = self.beforeShow;
    self.beforeShow = function(callback) {
      return superBeforeShow(function(err) {
        if (err) {
          return callback(err);
        }
        if (self.shouldSkipModal()) {
          // We're not visible but we still have a role to play. We don't want to rewrite
          // all of the chooser logic for orchestrating "browse" to work without us
          self.$el.css('opacity', 0);
          // TODO: better support for "nominal" modals in modal.js so that we don't have to
          // kill the ability to have the manage modal slide in over whatever preceded this
          self.$el.removeClass('apos-modal-slideable');
          self.chooser = self.$el.find('[data-chooser]:first').data('aposChooser');
        }
        return callback(null);
      });
    };

    var superAfterShow = self.afterShow;
    self.afterShow = function() {
      superAfterShow();
      if (self.shouldSkipModal()) {
        self.chooser.afterManagerSave = function() {
          self.save();
        };
        self.chooser.afterManagerCancel = function() {
          self.$el.css('opacity', 1);
          self.cancel();
        };
        self.chooser.launchBrowser()
      }
    };
  }
});
<|endoftext|>


<commit_before>'use strict';

/*
* The following copyright, license, and long comment were part of the original implementation available as part of [FreeBSD]{@link https://svnweb.freebsd.org/base/release/9.3.0/lib/msun/src/s_sin.c?view=log}.
*
* The implementation follows the original, but has been modified for JavaScript.
*/

/*
* ====================================================
* Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunPro, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ====================================================
*/

// MODULES //

var getHighWord = require( '@stdlib/math/base/utils/float64-get-high-word' );
var kernelCos = require( '@stdlib/math/base/special/kernel-cos' );
var kernelSin = require( '@stdlib/math/base/special/kernel-sin' );
var rempio2 = require( '@stdlib/math/base/special/rempio2' );

// VARIABLES //

// Absolute value mask: 0x7fffffff = 2147483647 => 01111111111111111111111111111111
var ABS_MASK = 0x7fffffff;

// Exponent mask: 0x7ff00000 = 2146435072 => 01111111111100000000000000000000
var EXPONENT_MASK = 0x7ff00000;

// High word for PI/4: 0x3fe921fb = 1072243195 => 00111111111010010010000111111011
var PIO4_HIGH_WORD = 0x3fe921fb;

// 2^-26 = 1.4901161193847656e-8 => 0011111001010000000000000000000000000000000000000000000000000000 => high word => 00111110010100000000000000000000 => 0x3e500000 = 1045430272
var SMALL_HIGH_WORD = 0x3e500000;

// Array for storing remainder elements:
var Y = [ 0.0, 0.0 ];

// MAIN //

/**
* Computes the sine of a number.
*
* #### Method
*
* * Let `S`, `C`, and `T` denote the `sin`, `cos` and `tan`, respectively, on `[-PI/4, +PI/4]`.
* * Reduce the argument `x` to `y1+y2 = x-k*pi/2` in `[-pi/4 , +pi/4]`, and let `n = k mod 4`. We have
*
*   | n   |  sin(x)  |  cos(x)  |  tan(x)  |
*   |:---:|:--------:|:--------:|:--------:|
*   |  0  |     S    |     C    |    T     |
*   |  1  |     C    |    -S    |   -1/T   |
*   |  2  |    -S    |    -C    |    T     |
*   |  3  |    -C    |     S    |   -1/T   |
*
*
* @param {number} x - input value (in radians)
* @returns {number} sine
*
* @example
* var v = sin( 0.0 );
* // returns ~0.0
*
* @example
* var v = sin( Math.PI/2.0 );
* // returns ~1.0
*
* @example
* var v = sin( -Math.PI/6.0 );
* // returns ~-0.5
*
* @example
* var v = sin( NaN );
* // returns NaN
*/
function sin( x ) {
	var ix;
	var n;
	var z;

	z = 0.0;
	ix = getHighWord( x );

	// Case: |x| ~< pi/4
	ix &= ABS_MASK;
	if ( ix <= PIO4_HIGH_WORD ) {
		// Case: |x| ~< 2^-26
		if ( ix < SMALL_HIGH_WORD ) {
			return x;
		}
		return kernelSin( x, z, 0 );
	}
	// Case: x is NaN or infinity
	if ( ix >= EXPONENT_MASK ) {
		return NaN;
	}
	// Argument reduction...
	n = rempio2( x, Y );
	switch ( n & 3 ) {
	case 0:
		return kernelSin( Y[0], Y[1] );
	case 1:
		return kernelCos( Y[0], Y[1] );
	case 2:
		return -kernelSin( Y[0], Y[1] );
	default:
		return -kernelCos( Y[0], Y[1] );
	}
} // end FUNCTION sin()

// EXPORTS //

module.exports = sin;
<commit_msg>Use TeX and remove unnecessary variable<commit_after>'use strict';

/*
* The following copyright, license, and long comment were part of the original implementation available as part of [FreeBSD]{@link https://svnweb.freebsd.org/base/release/9.3.0/lib/msun/src/s_sin.c?view=log}.
*
* The implementation follows the original, but has been modified for JavaScript.
*/

/*
* ====================================================
* Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunPro, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ====================================================
*/

// MODULES //

var getHighWord = require( '@stdlib/math/base/utils/float64-get-high-word' );
var kernelCos = require( '@stdlib/math/base/special/kernel-cos' );
var kernelSin = require( '@stdlib/math/base/special/kernel-sin' );
var rempio2 = require( '@stdlib/math/base/special/rempio2' );

// VARIABLES //

// Absolute value mask: 0x7fffffff = 2147483647 => 01111111111111111111111111111111
var ABS_MASK = 0x7fffffff;

// Exponent mask: 0x7ff00000 = 2146435072 => 01111111111100000000000000000000
var EXPONENT_MASK = 0x7ff00000;

// High word for PI/4: 0x3fe921fb = 1072243195 => 00111111111010010010000111111011
var PIO4_HIGH_WORD = 0x3fe921fb;

// 2^-26 = 1.4901161193847656e-8 => 0011111001010000000000000000000000000000000000000000000000000000 => high word => 00111110010100000000000000000000 => 0x3e500000 = 1045430272
var SMALL_HIGH_WORD = 0x3e500000;

// Array for storing remainder elements: (note that, in c, this is not thread safe)
var Y = [ 0.0, 0.0 ];

// MAIN //

/**
* Computes the sine of a number.
*
* ## Method
*
* * Let \\(S\\), \\(C\\), and \\(T\\) denote the \\(\sin\\), \\(\cos\\), and \\(\tan\\), respectively, on \\([-\pi/4, +\pi/4]\\).
*
* * Reduce the argument \\(x\\) to \\(y1+y2 = x-k\pi/2\\) in \\([-\pi/4, +\pi/4]\\), and let \\(n = k \mod 4\\).
*
* * We have
*
*   | n   |  sin(x)  |  cos(x)  |  tan(x)  |
*   |:---:|:--------:|:--------:|:--------:|
*   |  0  |     S    |     C    |    T     |
*   |  1  |     C    |    -S    |   -1/T   |
*   |  2  |    -S    |    -C    |    T     |
*   |  3  |    -C    |     S    |   -1/T   |
*
*
* @param {number} x - input value (in radians)
* @returns {number} sine
*
* @example
* var v = sin( 0.0 );
* // returns ~0.0
*
* @example
* var v = sin( Math.PI/2.0 );
* // returns ~1.0
*
* @example
* var v = sin( -Math.PI/6.0 );
* // returns ~-0.5
*
* @example
* var v = sin( NaN );
* // returns NaN
*/
function sin( x ) {
	var ix;
	var n;

	ix = getHighWord( x );
	ix &= ABS_MASK;

	// Case: |x| ~< π/4
	if ( ix <= PIO4_HIGH_WORD ) {
		// Case: |x| ~< 2^-26
		if ( ix < SMALL_HIGH_WORD ) {
			return x;
		}
		return kernelSin( x, 0.0 );
	}
	// Case: x is NaN or infinity
	if ( ix >= EXPONENT_MASK ) {
		return NaN;
	}
	// Argument reduction...
	n = rempio2( x, Y );
	switch ( n & 3 ) {
	case 0:
		return kernelSin( Y[ 0 ], Y[ 1 ] );
	case 1:
		return kernelCos( Y[ 0 ], Y[ 1 ] );
	case 2:
		return -kernelSin( Y[ 0 ], Y[ 1 ] );
	default:
		return -kernelCos( Y[ 0 ], Y[ 1 ] );
	}
} // end FUNCTION sin()

// EXPORTS //

module.exports = sin;
<|endoftext|>


<commit_before>'use strict';

/*
* The following copyright, license, and long comment were part of the original implementation available as part of [FreeBSD]{@link https://svnweb.freebsd.org/base/release/9.3.0/lib/msun/src/s_sin.c?view=log}.
*
* The implementation follows the original, but has been modified for JavaScript.
*/

/*
* ====================================================
* Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunPro, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ====================================================
*/

// MODULES //

var getHighWord = require( '@stdlib/math/base/utils/float64-get-high-word' );
var kernelCos = require( './kernel_cos.js' );
var kernelSin = require( './sin_kernel.js' );
var remPio2 = require( './rem_pio2.js' );

// VARIABLES //

// Absolute value mask: 0x7fffffff = 2147483647 => 01111111111111111111111111111111
var ABS_MASK = 0x7fffffff;

// Exponent mask: 0x7ff00000 = 2146435072 => 01111111111100000000000000000000
var EXPONENT_MASK = 0x7ff00000;

// High word for PI/4: 0x3fe921fb = 1072243195 => 00111111111010010010000111111011
var PIO4_HIGH_WORD = 0x3fe921fb;

// 2^-26 = 1.4901161193847656e-8 => 0011111001010000000000000000000000000000000000000000000000000000 => high word => 00111110010100000000000000000000 => 0x3e500000 = 1045430272
var SMALL_HIGH_WORD = 0x3e500000;

// Array for storing remainder elements:
var Y = [ 0.0, 0.0 ];

// MAIN //

/**
* Computes the sine of a number.
*
* #### Method
*
* * Let `S`, `C`, and `T` denote the `sin`, `cos` and `tan`, respectively, on `[-PI/4, +PI/4]`.
* * Reduce the argument `x` to `y1+y2 = x-k*pi/2` in `[-pi/4 , +pi/4]`, and let `n = k mod 4`. We have
*
* | n   |  sin(x)  |  cos(x)  |  tan(x)  |
* | --- |----------|----------|----------|
* |  0  |     S    |     C    |    T     |
* |  1  |     C    |    -S    |   -1/T   |
* |  2  |    -S    |    -C    |    T     |
* |  3  |    -C    |     S    |   -1/T   |
*
*
* @param {number} x - input value
* @returns {number} sine (in radians)
*
* @example
* var v = sin( 0.0 );
* // returns ~0.0
*
* @example
* var v = sin( Math.PI/2.0 );
* // returns ~1.0
*
* @example
* var v = sin( -Math.PI/6.0 );
* // returns ~-0.5
*
* @example
* var v = sin( NaN );
* // returns NaN
*/
function sin( x ) {
	var ix;
	var n;
	var z;

	z = 0.0;
	ix = getHighWord( x );

	// Case: x is NaN or infinity
	if ( ix >= EXPONENT_MASK ) {
		return NaN;
	}
	// Case: |x| ~< pi/4
	ix &= ABS_MASK;
	if ( ix <= PIO4_HIGH_WORD ) {
		// Case: |x| ~< 2^-26
		if ( ix < SMALL_HIGH_WORD ) {
			return x;
		}
		return kernelSin( x, z, 0 );
	}
	// Argument reduction...
	n = remPio2( x, Y );
	switch ( n & 3 ) {
	case 0:
		return kernelSin( Y[0], Y[1], 1 );
	case 1:
		return kernelCos( Y[0], Y[1] );
	case 2:
		return -kernelSin( Y[0], Y[1], 1 );
	default:
		return -kernelCos( Y[0], Y[1] );
	}
} // end FUNCTION sin()

// EXPORTS //

module.exports = sin;
<commit_msg>Fix case placement<commit_after>'use strict';

/*
* The following copyright, license, and long comment were part of the original implementation available as part of [FreeBSD]{@link https://svnweb.freebsd.org/base/release/9.3.0/lib/msun/src/s_sin.c?view=log}.
*
* The implementation follows the original, but has been modified for JavaScript.
*/

/*
* ====================================================
* Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunPro, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ====================================================
*/

// MODULES //

var getHighWord = require( '@stdlib/math/base/utils/float64-get-high-word' );
var kernelCos = require( './kernel_cos.js' );
var kernelSin = require( './sin_kernel.js' );
var remPio2 = require( './rem_pio2.js' );

// VARIABLES //

// Absolute value mask: 0x7fffffff = 2147483647 => 01111111111111111111111111111111
var ABS_MASK = 0x7fffffff;

// Exponent mask: 0x7ff00000 = 2146435072 => 01111111111100000000000000000000
var EXPONENT_MASK = 0x7ff00000;

// High word for PI/4: 0x3fe921fb = 1072243195 => 00111111111010010010000111111011
var PIO4_HIGH_WORD = 0x3fe921fb;

// 2^-26 = 1.4901161193847656e-8 => 0011111001010000000000000000000000000000000000000000000000000000 => high word => 00111110010100000000000000000000 => 0x3e500000 = 1045430272
var SMALL_HIGH_WORD = 0x3e500000;

// Array for storing remainder elements:
var Y = [ 0.0, 0.0 ];

// MAIN //

/**
* Computes the sine of a number.
*
* #### Method
*
* * Let `S`, `C`, and `T` denote the `sin`, `cos` and `tan`, respectively, on `[-PI/4, +PI/4]`.
* * Reduce the argument `x` to `y1+y2 = x-k*pi/2` in `[-pi/4 , +pi/4]`, and let `n = k mod 4`. We have
*
* | n   |  sin(x)  |  cos(x)  |  tan(x)  |
* | --- |----------|----------|----------|
* |  0  |     S    |     C    |    T     |
* |  1  |     C    |    -S    |   -1/T   |
* |  2  |    -S    |    -C    |    T     |
* |  3  |    -C    |     S    |   -1/T   |
*
*
* @param {number} x - input value
* @returns {number} sine (in radians)
*
* @example
* var v = sin( 0.0 );
* // returns ~0.0
*
* @example
* var v = sin( Math.PI/2.0 );
* // returns ~1.0
*
* @example
* var v = sin( -Math.PI/6.0 );
* // returns ~-0.5
*
* @example
* var v = sin( NaN );
* // returns NaN
*/
function sin( x ) {
	var ix;
	var n;
	var z;

	z = 0.0;
	ix = getHighWord( x );

	// Case: |x| ~< pi/4
	ix &= ABS_MASK;
	if ( ix <= PIO4_HIGH_WORD ) {
		// Case: |x| ~< 2^-26
		if ( ix < SMALL_HIGH_WORD ) {
			return x;
		}
		return kernelSin( x, z, 0 );
	}
	// Case: x is NaN or infinity
	if ( ix >= EXPONENT_MASK ) {
		return NaN;
	}
	// Argument reduction...
	n = remPio2( x, Y );
	switch ( n & 3 ) {
	case 0:
		return kernelSin( Y[0], Y[1], 1 );
	case 1:
		return kernelCos( Y[0], Y[1] );
	case 2:
		return -kernelSin( Y[0], Y[1], 1 );
	default:
		return -kernelCos( Y[0], Y[1] );
	}
} // end FUNCTION sin()

// EXPORTS //

module.exports = sin;
<|endoftext|>


<commit_before>import Component from '@ember/component';
import { inject as service } from '@ember/service';
import { once } from '@ember/runloop';
import { set, get, observer, setProperties } from '@ember/object';

export default Component.extend({
  router:     service(),
  gitService: service('pipeline-github'),

  oauthType:        'github',
  oauthHost:        'github.com',
  provider:         null,
  errors:           null,
  useGloableConfig: true,
  githubAuthConfig: null,
  testing:          false,
  secure:           true,
  isEnterprise:     false,

  didReceiveAttrs() {
    setProperties(this, {
      homePageURL:    window.location.origin,
      destinationUrl: window.location.origin
    });
  },

  actions: {
    changeOauthSource(useGloableConfig) {
      set(this, 'useGloableConfig', useGloableConfig);
    },

    githubAuthConfigAuthenticate() {
      const githubAuthConfig = get(this, 'githubAuthConfig');

      this.send(null, 'authenticate', get(githubAuthConfig, 'clientId'), get(githubAuthConfig, 'hostName'), get(githubAuthConfig, 'tls'), true)
    },

    authenticate(cb, client, host, isTls, inheritAuth, callBack) {
      const clientId = client || get(this, 'oauthModel.clientId');
      let hostname = host || get(this, 'oauthModel.hostName') || get(this, 'oauthHost');
      const tls = isTls === undefined ? get(this, 'oauthModel.scheme') : isTls;
      const scheme = tls ? 'https://' : 'http://';
      const authorizeURL = `${ scheme }${ hostname }${ this.getOauthUrl(clientId) }`;

      set(this, 'testing', true);
      get(this, 'gitService').authorizeTest(
        authorizeURL,
        (err, code) => {
          if (err) {
            this.send('gotError', err);
            set(this, 'testing', false);
            if ( cb ) {
              cb();
            }
          } else {
            callBack && callBack(code) || this.send('gotCode', code, hostname, tls, inheritAuth, cb);
          }
        }
      );
    },

    gotCode(code, hostname, tls, inheritAuth, cb) {
      const provider = get(this, 'provider');
      const oauthModel = get(this, 'oauthModel');
      const param = {
        code,
        clientId:     oauthModel.clientId,
        clientSecret: oauthModel.clientSecret,
        redirectUrl:  `${ get(this, 'destinationUrl') }/verify-auth`,
        inheritAuth:  !!inheritAuth,
        hostname,
        tls,
      };

      provider.doAction('testAndApply', param).then(() => {
        set(this, 'testing', false);
        if ( cb ) {
          cb();
        }
        get(this, 'router').transitionTo('authenticated.project.pipeline.repositories');
      }).catch((res) => {
        this.send('gotError', res);
        set(this, 'testing', false);
        if ( cb ) {
          cb();
        }
      });
    },

    gotError(err) {
      if ( get(err, 'message') ) {
        this.send('showError', get(err, 'message') + (get(err, 'detail') ? `(${ get(err, 'detail') })` : ''));
      } else {
        this.send('showError', `Error (${ get(err, 'status') } - ${ get(err, 'code') })`);
      }

      set(this, 'testing', false);
    },

    showError(msg) {
      set(this, 'errors', [msg]);
      window.scrollY = 10000;
    },
  },

  enterpriseDidChange: observer('isEnterprise', 'oauthModel.hostName', 'secure', function() {
    if (get(this, 'oauthModel.isAuth')) {
      return
    }
    once(this, 'updateEnterprise');
  }),

  getOauthUrl(clientId) {
    return `/login/oauth/authorize?client_id=${ clientId }&response_type=code&scope=repo+admin%3Arepo_hook`;
  },

  updateEnterprise() {
    if (get(this, 'isEnterprise')) {
      let hostname = get(this, 'oauthModel.hostName') || '';
      const match = hostname.match(/^http(s)?:\/\//i);

      if (match) {
        setProperties(this, {
          secure:                (match[1] || '').toLowerCase() === 's',
          'oauthModel.hostName': hostname.substr(match[0].length).replace(/\/.*$/, '')
        });
      }
    } else {
      setProperties(this, {
        secure:                true,
        'oauthModel.hostName': null
      });
    }

    set(this, 'oauthModel.scheme', get(this, 'secure'));
  },
});
<commit_msg>Fix typo<commit_after>import Component from '@ember/component';
import { inject as service } from '@ember/service';
import { once } from '@ember/runloop';
import { set, get, observer, setProperties } from '@ember/object';

export default Component.extend({
  router:     service(),
  gitService: service('pipeline-github'),

  oauthType:        'github',
  oauthHost:        'github.com',
  provider:         null,
  errors:           null,
  useGloableConfig: true,
  githubAuthConfig: null,
  testing:          false,
  secure:           true,
  isEnterprise:     false,

  didReceiveAttrs() {
    setProperties(this, {
      homePageURL:    window.location.origin,
      destinationUrl: window.location.origin
    });
  },

  actions: {
    changeOauthSource(useGloableConfig) {
      set(this, 'useGloableConfig', useGloableConfig);
    },

    githubAuthConfigAuthenticate() {
      const githubAuthConfig = get(this, 'githubAuthConfig');

      this.send('authenticate', null, get(githubAuthConfig, 'clientId'), get(githubAuthConfig, 'hostName'), get(githubAuthConfig, 'tls'), true)
    },

    authenticate(cb, client, host, isTls, inheritAuth, callBack) {
      const clientId = client || get(this, 'oauthModel.clientId');
      let hostname = host || get(this, 'oauthModel.hostName') || get(this, 'oauthHost');
      const tls = isTls === undefined ? get(this, 'oauthModel.scheme') : isTls;
      const scheme = tls ? 'https://' : 'http://';
      const authorizeURL = `${ scheme }${ hostname }${ this.getOauthUrl(clientId) }`;

      set(this, 'testing', true);
      get(this, 'gitService').authorizeTest(
        authorizeURL,
        (err, code) => {
          if (err) {
            this.send('gotError', err);
            set(this, 'testing', false);
            if ( cb ) {
              cb();
            }
          } else {
            callBack && callBack(code) || this.send('gotCode', code, hostname, tls, inheritAuth, cb);
          }
        }
      );
    },

    gotCode(code, hostname, tls, inheritAuth, cb) {
      const provider = get(this, 'provider');
      const oauthModel = get(this, 'oauthModel');
      const param = {
        code,
        clientId:     oauthModel.clientId,
        clientSecret: oauthModel.clientSecret,
        redirectUrl:  `${ get(this, 'destinationUrl') }/verify-auth`,
        inheritAuth:  !!inheritAuth,
        hostname,
        tls,
      };

      provider.doAction('testAndApply', param).then(() => {
        set(this, 'testing', false);
        if ( cb ) {
          cb();
        }
        get(this, 'router').transitionTo('authenticated.project.pipeline.repositories');
      }).catch((res) => {
        this.send('gotError', res);
        set(this, 'testing', false);
        if ( cb ) {
          cb();
        }
      });
    },

    gotError(err) {
      if ( get(err, 'message') ) {
        this.send('showError', get(err, 'message') + (get(err, 'detail') ? `(${ get(err, 'detail') })` : ''));
      } else {
        this.send('showError', `Error (${ get(err, 'status') } - ${ get(err, 'code') })`);
      }

      set(this, 'testing', false);
    },

    showError(msg) {
      set(this, 'errors', [msg]);
      window.scrollY = 10000;
    },
  },

  enterpriseDidChange: observer('isEnterprise', 'oauthModel.hostName', 'secure', function() {
    if (get(this, 'oauthModel.isAuth')) {
      return
    }
    once(this, 'updateEnterprise');
  }),

  getOauthUrl(clientId) {
    return `/login/oauth/authorize?client_id=${ clientId }&response_type=code&scope=repo+admin%3Arepo_hook`;
  },

  updateEnterprise() {
    if (get(this, 'isEnterprise')) {
      let hostname = get(this, 'oauthModel.hostName') || '';
      const match = hostname.match(/^http(s)?:\/\//i);

      if (match) {
        setProperties(this, {
          secure:                (match[1] || '').toLowerCase() === 's',
          'oauthModel.hostName': hostname.substr(match[0].length).replace(/\/.*$/, '')
        });
      }
    } else {
      setProperties(this, {
        secure:                true,
        'oauthModel.hostName': null
      });
    }

    set(this, 'oauthModel.scheme', get(this, 'secure'));
  },
});
<|endoftext|>


<commit_before>import debug from 'debug'
import React, { Component, PropTypes } from 'react'
import { Link } from 'react-router'

import Modal from '../../common/modal'
import { Tab, TabItems, TabItem, TabPanel } from '../../common/tab'
import btnStyles from '../../../styles/btn.css'
import styles from './tree-selector.css'

const d = debug('keik:gh:components:repository:partial:tree-selector')

export default class Entries extends Component {
  static propTypes = {
    branches: PropTypes.arrayOf(PropTypes.string).isRequired,
  }

  render = () => {
    d('render')
    const { branches, params: { owner, repo }, tags } = this.props
    return (

        <button
          className={btnStyles.defaultSmBtn}
          onClick={(e) => {this._branchMenuModal.open()}}
        >
          Branch:
          master

        </button>
        <Modal
          className={styles.branchMenuModal}
          width={300}
          ref={c => this._branchMenuModal = c}
        >

            Switch branches/tags
            <button
              className={styles.closeBtn}
              onClick={(e) => {this._branchMenuModal.close()}}
            >

            </button>

              <input placeholder="Find a tag..." />

            <Tab>
              <TabItems>
                <TabItem target="branches" active>Branches</TabItem>
                <TabItem target="tags">Tags</TabItem>
              </TabItems>
              <TabPanel name="branches">

                  {branches.map(branch => (

                       <Link to={`/${owner}/${repo}/tree/${branch}`}>
                         {branch}
                       </Link>

                   ))}

              </TabPanel>
              <TabPanel name="tags">

                  {tags.map(tag => (

                       <Link to={`/${owner}/${repo}/tree/${tag}`}>
                         {tag}
                       </Link>

                   ))}

              </TabPanel>
            </Tab>

        </Modal>

    )
  }
}
<commit_msg>Fix tree selector to show current tree<commit_after>import debug from 'debug'
import React, { Component, PropTypes } from 'react'
import { Link } from 'react-router'

import Modal from '../../common/modal'
import { Tab, TabItems, TabItem, TabPanel } from '../../common/tab'
import btnStyles from '../../../styles/btn.css'
import styles from './tree-selector.css'

const d = debug('keik:gh:components:repository:partial:tree-selector')

export default class Entries extends Component {
  static propTypes = {
    branches: PropTypes.arrayOf(PropTypes.string).isRequired,
  }

  render = () => {
    d('render')
    const { branches, params: { owner, repo, tree='master' }, tags } = this.props
    return (

        <button
          className={btnStyles.defaultSmBtn}
          onClick={(e) => {this._branchMenuModal.open()}}
        >
          Branch:
          {tree}

        </button>
        <Modal
          className={styles.branchMenuModal}
          width={300}
          ref={c => this._branchMenuModal = c}
        >

            Switch branches/tags
            <button
              className={styles.closeBtn}
              onClick={(e) => {this._branchMenuModal.close()}}
            >

            </button>

              <input placeholder="Find a tag..." />

            <Tab>
              <TabItems>
                <TabItem target="branches" active>Branches</TabItem>
                <TabItem target="tags">Tags</TabItem>
              </TabItems>
              <TabPanel name="branches">

                  {branches.map(branch => (

                       <Link to={`/${owner}/${repo}/tree/${branch}`}>
                         {branch}
                       </Link>

                   ))}

              </TabPanel>
              <TabPanel name="tags">

                  {tags.map(tag => (

                       <Link to={`/${owner}/${repo}/tree/${tag}`}>
                         {tag}
                       </Link>

                   ))}

              </TabPanel>
            </Tab>

        </Modal>

    )
  }
}
<|endoftext|>