code
stringlengths
2
1.05M
repo_name
stringlengths
5
114
path
stringlengths
4
991
language
stringclasses
1 value
license
stringclasses
15 values
size
int32
2
1.05M
var _ = require('underscore'); /* A rule should contain explain and rule methods */ // TODO explain explain // TODO explain missing // TODO explain assert function assert (options, password) { return !!password && options.minLength <= password.length; } function explain(options) { if (options.minLength === 1) { return { message: 'Non-empty password required', code: 'nonEmpty' }; } return { message: 'At least %d characters in length', format: [options.minLength], code: 'lengthAtLeast' }; } module.exports = { validate: function (options) { if (!_.isObject(options)) { throw new Error('options should be an object'); } if (!_.isNumber(options.minLength) || _.isNaN(options.minLength)) { throw new Error('length expects minLength to be a non-zero number'); } return true; }, explain: explain, missing: function (options, password) { var explained = explain(options); explained.verified = !!assert(options, password); return explained; }, assert: assert };
nherzalla/ProfileX-1
node_modules/password-sheriff/lib/rules/length.js
JavaScript
mit
1,063
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is JavaScript Engine testing utilities. * * The Initial Developer of the Original Code is * Mozilla Foundation. * Portions created by the Initial Developer are Copyright (C) 2008 * the Initial Developer. All Rights Reserved. * * Contributor(s): Jesse Ruderman * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ var gTestfile = 'regress-463259.js'; //----------------------------------------------------------------------------- var BUGNUMBER = 463259; var summary = 'Do not assert: VALUE_IS_FUNCTION(cx, fval)'; var actual = ''; var expect = ''; printBugNumber(BUGNUMBER); printStatus (summary); jit(true); try { (function(){ eval("(function(){ for (var j=0;j<4;++j) if (j==3) undefined(); })();"); })(); } catch(ex) { } jit(false); reportCompare(expect, actual, summary);
jubos/meguro
deps/spidermonkey/tests/js1_5/Regress/regress-463259.js
JavaScript
mit
2,273
import { rectangle } from 'leaflet'; import boundsType from './types/bounds'; import Path from './Path'; export default class Rectangle extends Path { static propTypes = { bounds: boundsType.isRequired, }; componentWillMount() { super.componentWillMount(); const { bounds, map, ...props } = this.props; this.leafletElement = rectangle(bounds, props); } componentDidUpdate(prevProps) { if (this.props.bounds !== prevProps.bounds) { this.leafletElement.setBounds(this.props.bounds); } this.setStyleIfChanged(prevProps, this.props); } }
TaiwanStat/react-leaflet
src/Rectangle.js
JavaScript
mit
584
/* YUI 3.8.0pr2 (build 154) Copyright 2012 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ YUI.add("dd-drop-plugin",function(e,t){var n=function(e){e.node=e.host,n.superclass.constructor.apply(this,arguments)};n.NAME="dd-drop-plugin",n.NS="drop",e.extend(n,e.DD.Drop),e.namespace("Plugin"),e.Plugin.Drop=n},"3.8.0pr2",{requires:["dd-drop"]});
SHMEDIALIMITED/tallest-tower
node_modules/grunt-contrib/node_modules/grunt-contrib-yuidoc/node_modules/yuidocjs/node_modules/yui/dd-drop-plugin/dd-drop-plugin-min.js
JavaScript
mit
394
//= require d3/d3 //= require jquery.qtip.min //= require simple_statistics gfw.ui.model.CountriesEmbedOverview = cdb.core.Model.extend({ defaults: { graph: 'total_loss', years: true, class: null } }); gfw.ui.view.CountriesEmbedOverview = cdb.core.View.extend({ el: document.body, events: { 'click .graph_tab': '_updateGraph' }, initialize: function() { this.model = new gfw.ui.model.CountriesEmbedOverview(); this.$graph = $('.overview_graph__area'); this.$years = $('.overview_graph__years'); var m = this.m = 40, w = this.w = this.$graph.width()+(m*2), h = this.h = this.$graph.height(), vertical_m = this.vertical_m = 20; this.x_scale = d3.scale.linear() .range([m, w-m]) .domain([2001, 2012]); this.grid_scale = d3.scale.linear() .range([vertical_m, h-vertical_m]) .domain([0, 1]); this.model.bind('change:graph', this._redrawGraph, this); this.model.bind('change:years', this._toggleYears, this); this.model.bind('change:class', this._toggleClass, this); this._initViews(); }, _initViews: function() { this.tooltip = d3.select('body') .append('div') .attr('class', 'tooltip'); this._drawYears(); this._drawGraph(); }, _toggleYears: function() { var that = this; if(this.model.get('years') === false) { this.$years.slideUp(250, function() { $('.overview_graph__axis').slideDown(); }); } else { $('.overview_graph__axis').slideUp(250, function() { that.$years.slideDown(); }); } }, _showYears: function() { if (!this.model.get('years')) { this.model.set('years', true); } }, _hideYears: function() { if (this.model.get('years')) { this.model.set('years', false); } }, _updateGraph: function(e) { e.preventDefault(); var $target = $(e.target).closest('.graph_tab'), graph = $target.attr('data-slug'); if (graph === this.model.get('graph')) { return; } else { $('.graph_tab').removeClass('selected'); $target.addClass('selected'); this.model.set('graph', graph); } }, _redrawGraph: function() { var graph = this.model.get('graph'); $('.overview_graph__title').html(config.GRAPHS[graph].title); $('.overview_graph__legend p').html(config.GRAPHS[graph].subtitle); $('.overview_graph__legend .info').attr('data-source', graph); this.$graph.find('.'+graph); this.$graph.find('.chart').hide(); this.$graph.find('.'+graph).fadeIn(); this._drawGraph(); }, _drawYears: function() { var markup_years = ''; for (var y = 2001; y<=2012; y += 1) { var y_ = this.x_scale(y); if (y === 2001) { y_ -= 25; } else if (y === 2012) { y_ -= 55; } else { y_ -= 40; } markup_years += '<span class="year" style="left:'+y_+'px">'+y+'</span>'; } this.$years.html(markup_years); }, _drawGraph: function() { var that = this; var w = this.w, h = this.h, vertical_m = this.vertical_m, m = this.m, x_scale = this.x_scale; var grid_scale = d3.scale.linear() .range([vertical_m, h-vertical_m]) .domain([1, 0]); d3.select('#chart').remove(); var svg = d3.select('.overview_graph__area') .append('svg:svg') .attr('id', 'chart') .attr('width', w) .attr('height', h); // grid svg.selectAll('line.grid_h') .data(grid_scale.ticks(4)) .enter() .append('line') .attr({ 'class': 'grid grid_h', 'x1': 0, 'x2': w, 'y1': function(d, i) { return grid_scale(d); }, 'y2': function(d, i) { return grid_scale(d); } }); svg.selectAll('line.grid_v') .data(x_scale.ticks(12)) .enter() .append('line') .attr({ 'class': 'grid grid_v', 'y1': h, 'y2': 0, 'x1': function(d) { return x_scale(d); }, 'x2': function(d) { return x_scale(d); } }); var gradient = svg.append('svg:defs') .append('svg:linearGradient') .attr('id', 'gradient') .attr('x1', '0%') .attr('y1', '0%') .attr('x2', '0%') .attr('y2', '100%') .attr('spreadMethod', 'pad'); gradient.append('svg:stop') .attr('offset', '0%') .attr('stop-color', '#CA46FF') .attr('stop-opacity', .5); gradient.append('svg:stop') .attr('offset', '100%') .attr('stop-color', '#D24DFF') .attr('stop-opacity', 1); if (this.model.get('graph') === 'total_loss') { this._showYears(); svg.append('text') .attr('class', 'axis') .attr('id', 'axis_y') .text('Mha') .attr('x', -h/2) .attr('y', 30) .attr('transform', 'rotate(-90)'); var sql = 'SELECT '; for(var y = 2001; y < 2012; y++) { sql += 'SUM(y'+y+') as y'+y+', ' } sql += 'SUM(y2012) as y2012, (SELECT SUM(y2001_y2012)\ FROM countries_gain) as gain\ FROM loss_gt_0'; d3.json('https://wri-01.cartodb.com/api/v2/sql?q='+sql, function(error, json) { var data = json.rows[0]; var data_ = [], gain = null; _.each(data, function(val, key) { if (key === 'gain') { gain = val/12; } else { data_.push({ 'year': key.replace('y',''), 'value': val }); } }); var y_scale = d3.scale.linear() .range([vertical_m, h-vertical_m]) .domain([d3.max(data_, function(d) { return d.value; }), 0]); // area var area = d3.svg.area() .x(function(d) { return x_scale(d.year); }) .y0(h) .y1(function(d) { return y_scale(d.value); }); svg.append('path') .datum(data_) .attr('class', 'area') .attr('d', area) .style('fill', 'url(#gradient)'); // circles svg.selectAll('circle') .data(data_) .enter() .append('svg:circle') .attr('class', 'linedot') .attr('cx', function(d) { return x_scale(d.year); }) .attr('cy', function(d){ return y_scale(d.value); }) .attr('r', 6) .attr('name', function(d) { return '<span>'+d.year+'</span>'+formatNumber(parseFloat(d.value/1000000).toFixed(1))+' Mha'; }) .on('mouseover', function(d) { that.tooltip.html($(this).attr('name')) .style('visibility', 'visible') .style('top', $(this).offset().top-100+'px') .style('left', $(this).offset().left-$('.tooltip').width()/2-4+'px') .attr('class', 'tooltip'); d3.select(this) .transition() .duration(100) .attr('r', 7); // TODO: highlighting the legend }) .on('mouseout', function(d) { that.tooltip.style('visibility', 'hidden'); d3.select(this) .transition() .duration(100) .attr('r', 6); // TODO: highlighting the legend }); var data_gain_ = [ { year: 2001, value: gain }, { year: 2012, value: gain } ]; // line svg.selectAll('line.overview_line') .data(data_gain_) .enter() .append('line') .attr({ 'class': 'overview_line', 'x1': m, 'x2': w-m, 'y1': function(d) { return y_scale(gain); }, 'y2': function(d) { return y_scale(gain); } }); svg.selectAll('circle.gain') .data(data_gain_) .enter() .append('svg:circle') .attr('class', 'linedot gain') .attr('cx', function(d) { return x_scale(d.year); }) .attr('cy', function(d){ return y_scale(d.value); }) .attr('r', 6) .attr('name', function(d) { return '<span>2001-2012</span>'+formatNumber(parseFloat(d.value/1000000).toFixed(1))+' Mha'; }) .on('mouseover', function(d) { that.tooltip.html($(this).attr('name')) .style('visibility', 'visible') .style('top', $(this).offset().top-100+'px') .style('left', $(this).offset().left-$('.tooltip').width()/2-4+'px') .attr('class', 'tooltip gain_tooltip'); d3.select(this) .transition() .duration(100) .attr('r', 7); // TODO: highlighting the legend }) .on('mouseout', function(d) { that.tooltip.style('visibility', 'hidden'); d3.select(this) .transition() .duration(100) .attr('r', 6); // TODO: highlighting the legend }); }); } else if (this.model.get('graph') === 'percent_loss') { this._showYears(); svg.append('text') .attr('class', 'axis') .attr('id', 'axis_y') .text('%') .attr('x', -h/2) .attr('y', 30) .attr('transform', 'rotate(-90)'); var sql = 'WITH loss as (SELECT '; for(var y = 2001; y < 2012; y++) { sql += 'SUM(y'+y+') as sum_loss_y'+y+', '; } sql += 'SUM(y2012) as sum_loss_y2012\ FROM loss_gt_25), extent as (SELECT '; for(var y = 2001; y < 2012; y++) { sql += 'SUM(y'+y+') as sum_extent_y'+y+', '; } sql += 'SUM(y2012) as sum_extent_y2012\ FROM extent_gt_25)\ SELECT '; for(var y = 2001; y < 2012; y++) { sql += 'sum_loss_y'+y+'/sum_extent_y'+y+' as percent_loss_'+y+', '; } sql += 'sum_loss_y2012/sum_extent_y2012 as percent_loss_2012, (SELECT SUM(y2001_y2012)/('; for(var y = 2001; y < 2012; y++) { sql += 'sum_extent_y'+y+' + '; } sql += 'sum_extent_y2012)\ FROM countries_gain) as gain\ FROM loss, extent'; d3.json('https://wri-01.cartodb.com/api/v2/sql?q='+encodeURIComponent(sql), function(json) { var data = json.rows[0]; var data_ = [], gain = null; _.each(data, function(val, key) { if (key === 'gain') { gain = val/12; } else { data_.push({ 'year': key.replace('percent_loss_',''), 'value': val }); } }); var y_scale = grid_scale; // area var area = d3.svg.area() .x(function(d) { return x_scale(d.year); }) .y0(h) .y1(function(d) { return y_scale(d.value*100); }); svg.append('path') .datum(data_) .attr('class', 'area') .attr('d', area) .style('fill', 'url(#gradient)'); // circles svg.selectAll('circle') .data(data_) .enter() .append('svg:circle') .attr('class', 'linedot') .attr('cx', function(d) { return x_scale(d.year); }) .attr('cy', function(d){ return y_scale(d.value*100); }) .attr('r', 6) .attr('name', function(d) { return '<span>'+d.year+'</span>'+parseFloat(d.value*100).toFixed(2)+' %'; }) .on('mouseover', function(d) { that.tooltip.html($(this).attr('name')) .style('visibility', 'visible') .style('top', $(this).offset().top-100+'px') .style('left', $(this).offset().left-$('.tooltip').width()/2-4+'px') .attr('class', 'tooltip'); d3.select(this) .transition() .duration(100) .attr('r', 7); // TODO: highlighting the legend }) .on('mouseout', function(d) { that.tooltip.style('visibility', 'hidden'); d3.select(this) .transition() .duration(100) .attr('r', 6); // TODO: highlighting the legend }); var data_gain_ = [ { year: 2001, value: gain }, { year: 2012, value: gain } ]; // line svg.selectAll('line.overview_line') .data(data_gain_) .enter() .append('line') .attr({ 'class': 'overview_line', 'x1': m, 'x2': w-m, 'y1': function(d) { return y_scale(gain*100); }, 'y2': function(d) { return y_scale(gain*100); } }); // circles svg.selectAll('circle.gain') .data(data_gain_) .enter() .append('svg:circle') .attr('class', 'linedot gain') .attr('cx', function(d) { return x_scale(d.year); }) .attr('cy', function(d){ return y_scale(d.value*100); }) .attr('r', 6) .attr('name', function(d) { return '<span>2001-2012</span>'+parseFloat(d.value*100).toFixed(2)+' %'; }) .on('mouseover', function(d) { that.tooltip.html($(this).attr('name')) .style('visibility', 'visible') .style('top', $(this).offset().top-100+'px') .style('left', $(this).offset().left-$('.tooltip').width()/2-4+'px') .attr('class', 'tooltip gain_tooltip'); d3.select(this) .transition() .duration(100) .attr('r', 7); // TODO: highlighting the legend }) .on('mouseout', function(d) { that.tooltip.style('visibility', 'hidden'); d3.select(this) .transition() .duration(100) .attr('r', 6); // TODO: highlighting the legend }); }); } else if (this.model.get('graph') === 'total_extent') { this._showYears(); svg.append('text') .attr('class', 'axis') .attr('id', 'axis_y') .text('Mha') .attr('x', -h/2) .attr('y', 30) .attr('transform', 'rotate(-90)'); var gradient_extent = svg.append('svg:defs') .append('svg:linearGradient') .attr('id', 'gradient_extent') .attr('x1', '0%') .attr('y1', '0%') .attr('x2', '0%') .attr('y2', '100%') .attr('spreadMethod', 'pad'); gradient_extent.append('svg:stop') .attr('offset', '0%') .attr('stop-color', '#98BD17') .attr('stop-opacity', .5); gradient_extent.append('svg:stop') .attr('offset', '100%') .attr('stop-color', '#98BD17') .attr('stop-opacity', 1); var sql = 'SELECT '; for(var y = 2001; y < 2012; y++) { sql += 'SUM(loss.y'+y+') as loss_y'+y+', '; } sql += 'SUM(loss.y2012) as loss_y2012, '; for(var y = 2001; y < 2012; y++) { sql += 'SUM(extent.y'+y+') as extent_y'+y+', '; } sql += 'SUM(extent.y2012) as extent_y2012\ FROM loss_gt_25 loss, extent_gt_25 extent\ WHERE loss.iso = extent.iso'; d3.json('https://wri-01.cartodb.com/api/v2/sql?q='+encodeURIComponent(sql), function(json) { var data = json.rows[0]; var data_ = [], data_loss_ = [], data_extent_ = []; _.each(data, function(val, key) { var year = key.split('_y')[1]; var obj = _.find(data_, function(obj) { return obj.year == year; }); if(obj === undefined) { data_.push({ 'year': year }); } if (key.indexOf('loss_y') != -1) { data_loss_.push({ 'year': key.split('_y')[1], 'value': val }); } if (key.indexOf('extent_y') != -1) { data_extent_.push({ 'year': key.split('extent_y')[1], 'value': val }); } }); _.each(data_, function(val) { var loss = _.find(data_loss_, function(obj) { return obj.year == val.year; }), extent = _.find(data_extent_, function(obj) { return obj.year == val.year; }); _.extend(val, { 'loss': loss.value, 'extent': extent.value }); }); var domain = [d3.max(data_, function(d) { return d.extent; }), 0]; var y_scale = d3.scale.linear() .range([vertical_m, h-vertical_m]) .domain(domain); // area var area_loss = d3.svg.area() .x(function(d) { return x_scale(d.year); }) .y0(h) .y1(function(d) { return y_scale(d.loss); }); var area_extent = d3.svg.area() .x(function(d) { return x_scale(d.year); }) .y0(function(d) { return y_scale(d.extent); }) .y1(function(d) { return y_scale(d.loss); }); svg.append('path') .datum(data_) .attr('class', 'area') .attr('d', area_loss) .style('fill', 'url(#gradient)'); svg.append('path') .datum(data_) .attr('class', 'area') .attr('d', area_extent) .style('fill', 'url(#gradient_extent)'); // circles svg.selectAll('circle') .data(data_loss_) .enter() .append('svg:circle') .attr('class', 'linedot') .attr('cx', function(d) { return x_scale(d.year); }) .attr('cy', function(d){ return y_scale(d.value); }) .attr('r', 6) .attr('name', function(d) { return '<span>'+d.year+'</span>'+formatNumber(parseFloat(d.value/1000000).toFixed(1))+' Mha'; }) .on('mouseover', function(d) { that.tooltip.html($(this).attr('name')) .style('visibility', 'visible') .style('top', $(this).offset().top-100+'px') .style('left', $(this).offset().left-$('.tooltip').width()/2-4+'px') .attr('class', 'tooltip'); d3.select(this) .transition() .duration(100) .attr('r', 7); // TODO: highlighting the legend }) .on('mouseout', function(d) { that.tooltip.style('visibility', 'hidden'); d3.select(this) .transition() .duration(100) .attr('r', 6); // TODO: highlighting the legend }); svg.selectAll('circle.gain') .data(data_extent_) .enter() .append('svg:circle') .attr('class', 'linedot gain') .attr('cx', function(d) { return x_scale(d.year); }) .attr('cy', function(d){ return y_scale(d.value); }) .attr('r', 6) .attr('name', function(d) { return '<span>'+d.year+'</span>'+formatNumber(parseFloat(d.value/1000000).toFixed(1))+' Mha'; }) .on('mouseover', function(d) { that.tooltip.html($(this).attr('name')) .style('visibility', 'visible') .style('top', $(this).offset().top-100+'px') .style('left', $(this).offset().left-$('.tooltip').width()/2-4+'px') .attr('class', 'tooltip gain_tooltip'); d3.select(this) .transition() .duration(100) .attr('r', 7); // TODO: highlighting the legend }) .on('mouseout', function(d) { that.tooltip.style('visibility', 'hidden'); d3.select(this) .transition() .duration(100) .attr('r', 6); // TODO: highlighting the legend }); }); } else if (this.model.get('graph') === 'ratio') { this._hideYears(); svg.append('text') .attr('class', 'axis light') .attr('id', 'axis_y') .text('Cover gain 2001-2012') .attr('x', -(h/2)) .attr('y', 30) .attr('transform', 'rotate(-90)'); var shadow = svg.append('svg:defs') .append('svg:filter') .attr('id', 'shadow') .attr('x', '0%') .attr('y', '0%') .attr('width', '200%') .attr('height', '200%') shadow.append('svg:feOffset') .attr('result', 'offOut') .attr('in', 'SourceAlpha') .attr('dx', 0) .attr('dy', 0); shadow.append('svg:feGaussianBlur') .attr('result', 'blurOut') .attr('in', 'offOut') .attr('stdDeviation', 1); shadow.append('svg:feBlend') .attr('in', 'SourceGraphic') .attr('in2', 'blurOut') .attr('mode', 'normal'); var sql = 'WITH loss as (SELECT iso, SUM('; for(var y = 2001; y < 2012; y++) { sql += 'loss.y'+y+' + '; } sql += 'loss.y2012) as sum_loss\ FROM loss_gt_50 loss\ GROUP BY iso), gain as (SELECT g.iso, SUM(y2001_y2012) as sum_gain\ FROM countries_gain g, loss_gt_50 loss\ WHERE loss.iso = g.iso\ GROUP BY g.iso), ratio as ('; sql += 'SELECT c.iso, c.name, c.enabled, loss.sum_loss as loss, gain.sum_gain as gain, loss.sum_loss/gain.sum_gain as ratio\ FROM loss, gain, gfw2_countries c\ WHERE sum_gain IS NOT null\ AND NOT sum_gain = 0\ AND c.iso = gain.iso\ AND c.iso = loss.iso\ ORDER BY loss.sum_loss DESC\ LIMIT 50) '; sql += 'SELECT *\ FROM ratio\ WHERE ratio IS NOT null\ ORDER BY ratio DESC'; d3.json('https://wri-01.cartodb.com/api/v2/sql?q='+encodeURIComponent(sql), function(json) { var data = json.rows; var log_m = 50; var y_scale = d3.scale.linear() .range([h, 0]) .domain([0, d3.max(data, function(d) { return d.gain; })]); var x_scale = d3.scale.linear() .range([m, w-m]) .domain([d3.min(data, function(d) { return d.loss; }), d3.max(data, function(d) { return d.loss; })]); var x_log_scale = d3.scale.log() .range([m, w-m]) .domain([d3.min(data, function(d) { return d.loss; }), d3.max(data, function(d) { return d.loss; })]); var y_log_scale = d3.scale.log() .range([h-log_m, m]) .domain([d3.min(data, function(d) { return d.gain; }), d3.max(data, function(d) { return d.gain; })]); var r_scale = d3.scale.linear() .range(['yellow', 'red']) .domain([0, d3.max(data, function(d) { return d.ratio; })]); that.linearRegressionLine(svg, json, x_scale, y_scale); // circles w/ magic numbers :( var circle_attr = { 'cx': function(d) { return d.loss >= 1 ? x_log_scale(d.loss) : m; }, 'cy': function(d) { return d.gain >= 1 ? y_log_scale(d.gain) : h-log_m; }, 'r': '5', 'name': function(d) { return d.name; }, 'class': function(d) { return d.enabled ? 'ball ball_link' : 'ball ball_nolink'; } }; var data_ = [], data_link_ = [], exclude = ['Saint Barthélemy', 'Saint Kitts and Nevis', 'Saint Pierre and Miquelon', 'Virgin Islands', 'Oman', 'Gibraltar', 'Saudi Arabia', 'French Polynesia', 'Samoa', 'Western Sahara', 'United Arab Emirates']; _.each(data, function(row) { if (!_.contains(exclude, row.name)) { if (row.enabled === true) { data_link_.push(row); } else { data_.push(row); } } }); var circles_link = svg.selectAll('circle.ball_link') .data(data_link_) .enter() .append('a') .attr('xlink:href', function(d) { return '/country/' + d.iso }) .attr('target', '_blank') .append('svg:circle') .attr(circle_attr) .style('fill', function(d) { return r_scale(d.ratio); }) .style('filter', 'url(#shadow)') .on('mouseover', function() { d3.select(d3.event.target) .transition() .attr('r', '7') .style('opacity', 1); var t = $(this).offset().top - 80, l = $(this).offset().left, r = $(this).attr('r'), tip = $('.tooltip').width()/2; that.tooltip.html($(this).attr('name')) .style('visibility', 'visible') .style('top', parseInt(t, 10)+'px') .style('left', parseInt(l, 10)+parseInt(r, 10)-parseInt(tip, 10)-10+'px') .attr('class', 'tooltip gain_tooltip'); }) .on('mouseenter', function() { d3.select(d3.event.target) .transition() .attr('r', '7') .style('opacity', 1); var t = $(this).offset().top - 80, l = $(this).offset().left, r = $(this).attr('r'), tip = $('.tooltip').width()/2; that.tooltip.html($(this).attr('name')) .style('visibility', 'visible') .style('top', parseInt(t, 10)+'px') .style('left', parseInt(l, 10)+parseInt(r, 10)-parseInt(tip, 10)+'px') .attr('class', 'tooltip gain_tooltip'); }) .on('mouseout', function() { d3.select(d3.event.target) .transition() .attr('r', '5') .style('opacity', .8); that.tooltip.style('visibility', 'hidden'); }); var circles = svg.selectAll('circle.ball_nolink') .data(data_) .enter() .append('svg:circle') .attr(circle_attr) .style('filter', 'url(#shadow)') .on('mouseover', function() { d3.select(d3.event.target) .transition() .attr('r', '7') .style('opacity', 1); var t = $(this).offset().top - 80, l = $(this).offset().left, r = $(this).attr('r'), tip = $('.tooltip').width()/2; that.tooltip.html($(this).attr('name')) .style('visibility', 'visible') .style('top', parseInt(t, 10)+'px') .style('left', parseInt(l, 10)+parseInt(r, 10)-parseInt(tip, 10)-10+'px') .attr('class', 'tooltip gain_tooltip'); }) .on('mouseenter', function() { d3.select(d3.event.target) .transition() .attr('r', '7') .style('opacity', 1); var t = $(this).offset().top - 80, l = $(this).offset().left, r = $(this).attr('r'), tip = $('.tooltip').width()/2; that.tooltip.html($(this).attr('name')) .style('visibility', 'visible') .style('top', parseInt(t, 10)+'px') .style('left', parseInt(l, 10)+parseInt(r, 10)-parseInt(tip, 10)+'px') .attr('class', 'tooltip gain_tooltip'); }) .on('mouseout', function() { d3.select(d3.event.target) .transition() .attr('r', '5') .style('opacity', .8); that.tooltip.style('visibility', 'hidden'); }); }); } else if (this.model.get('graph') === 'domains') { this._showYears(); var sql = 'SELECT name, '; for(var y = 2001; y < 2012; y++) { sql += 'y'+y+', ' } sql += 'y2012, GREATEST(' for(var y = 2001; y < 2012; y++) { sql += 'y'+y+', ' } sql += 'y2012) as max\ FROM countries_domains'; d3.json('https://wri-01.cartodb.com/api/v2/sql?q='+sql, function(error, json) { var data = json.rows; var r_scale = d3.scale.linear() .range([5, 30]) // max ball radius .domain([0, d3.max(data, function(d) { return d.max; })]) for(var j = 0; j < data.length; j++) { var data_ = [], domain = ''; _.each(data[j], function(val, key) { if (key !== 'max') { if (key === 'name') { domain = val.toLowerCase(); } else { data_.push({ 'year': key.replace('y',''), 'value': val }); } } }); svg.append('text') .attr('class', 'label') .attr('id', 'label_'+domain) .text(domain) .attr('x', function() { var l = x_scale(2002) - $(this).width()/2; return l; }) .attr('y', (h/5)*(j+.6)); var circle_attr = { 'cx': function(d, i) { return x_scale(2001 + i); }, 'cy': function(d) { return (h/5)*(j+1); }, 'r': function(d) { return r_scale(d.value); }, 'class': function(d) { return 'ball'; } }; svg.selectAll('circle.domain_'+domain) .data(data_) .enter() .append('svg:circle') .attr(circle_attr) .attr('data-slug', domain) .attr('name', function(d) { return '<span>'+d.year+'</span>'+formatNumber(parseFloat(d.value/1000000).toFixed(1))+' Mha'; }) .style('fill', function(d) { return config.GRAPHCOLORS[domain]; }) .on('mouseover', function() { d3.select(d3.event.target) .transition() .attr('r', function(d) { return circle_attr.r(d) + 2; }) .style('opacity', 1); var t = $(this).offset().top - 100, l = $(this).offset().left, r = $(this).attr('r'), tip = $('.tooltip').width()/2, slug = $(this).attr('data-slug'); that.tooltip.html($(this).attr('name')) .style('visibility', 'visible') .style('top', parseInt(t, 10)+'px') .style('left', parseInt(l, 10)+parseInt(r, 10)-parseInt(tip, 10)-10+'px') .attr('class', 'tooltip') .attr('data-slug', 'tooltip') .style('color', function() { if (slug === 'subtropical') { return '#FFC926' } else { return config.GRAPHCOLORS[slug]; } }); }) .on('mouseenter', function() { d3.select(d3.event.target) .transition() .attr('r', function(d) { return circle_attr.r(d) + 2; }) .style('opacity', 1); var t = $(this).offset().top - 80, l = $(this).offset().left, r = $(this).attr('r'), tip = $('.tooltip').width()/2, slug = $(this).attr('data-slug'); that.tooltip.html($(this).attr('name')) .style('visibility', 'visible') .style('top', parseInt(t, 10)+'px') .style('left', parseInt(l, 10)+parseInt(r, 10)-parseInt(tip, 10)-10+'px') .attr('class', 'tooltip') .attr('data-slug', 'tooltip') .style('color', function() { if (domain === 'subtropical') { return config.GRAPHCOLORS[domain]; } }); }) .on('mouseout', function() { d3.select(d3.event.target) .transition() .attr('r', function(d) { return circle_attr.r(d); }) .style('opacity', .8); that.tooltip .style('color', '') .style('visibility', 'hidden'); }); } }); } }, linearRegressionLine: function(svg, dataset, x_log_scale, y_log_scale) { var that = this; // linear regresion line var lr_line = ss.linear_regression() .data(dataset.rows.map(function(d) { return [d.loss, d.gain]; })) .line(); var line = d3.svg.line() .x(x_log_scale) .y(function(d) { return that.y_log_scale(lr_line(d));} ) var x0 = x_log_scale.domain()[0]; var x1 = x_log_scale.domain()[1]; var lr = svg.selectAll('.linear_regression').data([0]); var attrs = { "x1": x_log_scale(x0), "y1": y_log_scale(lr_line(x0)), "x2": x_log_scale(x1), "y2": y_log_scale(lr_line(x1)), "stroke-width": 1.3, "stroke": "white", "stroke-dasharray": "7,5" }; lr.enter() .append("line") .attr('class', 'linear_regression') .attr(attrs); lr.transition().attr(attrs); } }); gfw.ui.view.CountriesEmbedShow = cdb.core.View.extend({ el: document.body, events: { 'click .forma_dropdown-link': '_openDropdown', 'click .hansen_dropdown-link': '_openDropdown', 'click .hansen_dropdown-menu a': '_redrawCircle' }, initialize: function() { this.iso = this.options.iso; this._initViews(); this._initHansenDropdown(); }, _initViews: function() { this._drawCircle('forma', 'lines', { iso: this.iso }); this._drawCircle('forest_loss', 'bars', { iso: this.iso, dataset: 'loss' }); }, _initFormaDropdown: function() { $('.forma_dropdown-link').qtip({ show: 'click', hide: { event: 'click unfocus' }, content: { text: $('.forma_dropdown-menu') }, position: { my: 'bottom right', at: 'top right', target: $('.forma_dropdown-link'), adjust: { x: -10 } }, style: { tip: { corner: 'bottom right', mimic: 'bottom center', border: 1, width: 10, height: 6 } } }); }, _initHansenDropdown: function() { this.dropdown = $('.hansen_dropdown-link').qtip({ show: 'click', hide: { event: 'click unfocus' }, content: { text: $('.hansen_dropdown-menu') }, position: { my: 'top right', at: 'bottom right', target: $('.hansen_dropdown-link'), adjust: { x: 10 } }, style: { tip: { corner: 'top right', mimic: 'top center', border: 1, width: 10, height: 6 } } }); }, _openDropdown: function(e) { e.preventDefault(); }, _redrawCircle: function(e) { e.preventDefault(); var dataset = $(e.target).attr('data-slug'), subtitle = $(e.target).text(); var api = this.dropdown.qtip('api'); api.hide(); $('.hansen_dropdown-link').html(subtitle); if(dataset === 'countries_gain') { this._drawCircle('forest_loss', 'comp', { iso: this.iso }); } else { this._drawCircle('forest_loss', 'bars', { iso: this.iso, dataset: dataset }); } }, _drawCircle: function(id, type, options) { var that = this; var $graph = $('.'+id), $amount = $('.'+id+' .graph-amount'), $date = $('.'+id+' .graph-date'), $coming_soon = $('.'+id+' .coming_soon'), $action = $('.'+id+' .action'); $('.graph.'+id+' .frame_bkg').empty(); $graph.addClass('ghost'); $amount.html(''); $date.html(''); $coming_soon.hide(); var width = options.width || 256, height = options.height || width, h = 100, // maxHeight radius = width / 2; var graph = d3.select('.graph.'+id+' .frame_bkg') .append('svg:svg') .attr('class', type) .attr('width', width) .attr('height', height); var dashedLines = [ { x1:17, y:height/4, x2:239, color: '#ccc' }, { x1:0, y:height/2, x2:width, color: '#ccc' }, { x1:17, y:3*height/4, x2:239, color: '#ccc' } ]; // Adds the dotted lines _.each(dashedLines, function(line) { graph.append('svg:line') .attr('x1', line.x1) .attr('y1', line.y) .attr('x2', line.x2) .attr('y2', line.y) .style('stroke-dasharray', '2,2') .style('stroke', line.color); }); var sql = ["SELECT date_trunc('month', date) as date, COUNT(*) as alerts", 'FROM forma_api', "WHERE iso = '"+options.iso+"'", "GROUP BY date_trunc('month', date)", "ORDER BY date_trunc('month', date) ASC"].join(' '); if (type === 'lines') { d3.json('https://wri-01.cartodb.com/api/v2/sql?q='+sql, function(json) { if(json && json.rows.length > 0) { $graph.removeClass('ghost'); $action.removeClass('disabled'); that._initFormaDropdown(); var data = json.rows.slice(1, json.rows.length - 1); } else { $coming_soon.show(); return; } var x_scale = d3.scale.linear() .domain([0, data.length - 1]) .range([0, width - 80]); var max = d3.max(data, function(d) { return parseFloat(d.alerts); }); if (max === d3.min(data, function(d) { return parseFloat(d.alerts); })) { h = h/2; } var y_scale = d3.scale.linear() .domain([0, max]) .range([0, h]); var line = d3.svg.line() .x(function(d, i) { return x_scale(i); }) .y(function(d, i) { return h - y_scale(d.alerts); }) .interpolate('basis'); var marginLeft = 40, marginTop = radius - h/2; $amount.html('<span>'+formatNumber(data[data.length - 1].alerts)+'</span>'); var date = new Date(data[data.length - 1].date), form_date = 'Alerts in ' + config.MONTHNAMES[date.getMonth()] + ' ' + date.getFullYear(); $date.html(form_date); graph.append('svg:path') .attr('transform', 'translate(' + marginLeft + ',' + marginTop + ')') .attr('d', line(data)) .on('mousemove', function(d) { var index = Math.round(x_scale.invert(d3.mouse(this)[0])); if (data[index]) { // if there's data $amount.html('<span>'+formatNumber(data[index].alerts)+'</span>'); var date = new Date(data[index].date), form_date = 'Alerts in ' + config.MONTHNAMES[date.getMonth()] + ' ' + date.getFullYear(); $date.html(form_date); var cx = d3.mouse(this)[0] + marginLeft; var cy = h - y_scale(data[index].alerts) + marginTop; graph.select('.forma_marker') .attr('cx', cx) .attr('cy', cy); } }); graph.append('svg:circle') .attr('class', 'forma_marker') .attr('cx', -10000) .attr('cy',100) .attr('r', 5); }); } else if (type === 'bars') { var sql = "SELECT "; if (options.dataset === 'loss') { sql += "year, loss_gt_0 loss FROM umd WHERE iso='"+options.iso+"'"; } else if (options.dataset === 'extent') { sql += "year, extent_gt_25 extent FROM umd WHERE iso='"+options.iso+"'"; } d3.json('https://wri-01.cartodb.com/api/v2/sql?q='+sql, function(json) { if(json) { $graph.removeClass('ghost'); var data = json.rows; } else { $coming_soon.show(); return; } var data_ = []; _.each(data, function(val, key) { if (val.year >= 2001) { data_.push({ 'year': val.year, 'value': eval('val.'+options.dataset) }); } }); $amount.html('<span>'+formatNumber(parseInt(data_[data_.length - 1].value, 10))+'</span>'); $date.html('Hectares in ' + data_[data_.length - 1].year); var marginLeft = 40, marginTop = radius - h/2 + 5; var y_scale = d3.scale.linear() .domain([0, d3.max(data_, function(d) { return parseFloat(d.value); })]) .range([height, marginTop*2]); var barWidth = (width - 80) / data_.length; var bar = graph.selectAll('g') .data(data_) .enter() .append('g') .attr('transform', function(d, i) { return 'translate(' + (marginLeft + i * barWidth) + ','+ -marginTop+')'; }); bar.append('svg:rect') .attr('class', function(d, i) { if(i === 11) { // last year index return 'last bar' } else { return 'bar' } }) .attr('y', function(d) { return y_scale(d.value); }) .attr('height', function(d) { return height - y_scale(d.value); }) .attr('width', barWidth - 1) .on('mouseover', function(d) { d3.selectAll('.bar').style('opacity', '.5'); d3.select(this).style('opacity', '1'); $amount.html('<span>'+formatNumber(parseInt(d.value, 10))+'</span>'); $date.html('Hectares in ' + d.year); }); }); } else if (type === 'comp') { var sql = "SELECT iso, sum(umd.loss_gt_0) loss, max(umd.gain) gain FROM umd WHERE iso='"+options.iso+"' GROUP BY iso"; d3.json('https://wri-01.cartodb.com/api/v2/sql?q='+encodeURIComponent(sql), function(json) { if(json) { $graph.removeClass('ghost'); var data = json.rows[0]; } else { $coming_soon.show(); return; } var data_ = [{ 'key': 'Tree cover gain', 'value': data.gain }, { 'key': 'Tree cover loss', 'value': data.loss }]; $amount.html('<span>'+formatNumber(parseInt(data_[data_.length - 1].value, 10))+'</span>'); $date.html('Ha '+data_[data_.length - 1].key); var barWidth = (width - 80) / 12; var marginLeft = 40 + barWidth*5, marginTop = radius - h/2 + 5; var y_scale = d3.scale.linear() .domain([0, d3.max(data_, function(d) { return parseFloat(d.value); })]) .range([height, marginTop*2]); var bar = graph.selectAll('g') .data(data_) .enter() .append('g') .attr('transform', function(d, i) { return 'translate(' + (marginLeft + i * barWidth) + ',' + -marginTop + ')'; }); bar.append('svg:rect') .attr('class', function(d, i) { if (i === 1) { // last bar index return 'last bar' } else { return 'bar' } }) .attr('y', function(d) { return y_scale(d.value); }) .attr('height', function(d) { return height - y_scale(d.value); }) .attr('width', barWidth - 1) .style('fill', '#FFC926') .style('shape-rendering', 'crispEdges') .on('mouseover', function(d) { d3.selectAll('.bar').style('opacity', '.5'); d3.select(this).style('opacity', '1'); $amount.html('<span>'+formatNumber(parseFloat(d.value).toFixed(1))+'</span>'); $date.html('Ha '+d.key); }); }); } } });
apercas/gfw
app/assets/javascripts/embed_countries.js
JavaScript
mit
43,948
declare module 'fast-memoize' { declare type Cache<K, V> = { get: (key: K) => V, set: (key: K, value: V) => void, has: (key: K) => boolean } declare type Options = { cache?: Cache<*, *>; serializer?: (...args: any[]) => any; strategy?: <T>(fn: T, options?: Options) => T; } declare module.exports: <T>(fn: T, options?: Options) => T; }
splodingsocks/FlowTyped
definitions/npm/fast-memoize_v2.x.x/flow_v0.53.x-v0.103.x/fast-memoize_v2.x.x.js
JavaScript
mit
374
angular.module('ualib.imageCarousel', ['angular-carousel']) .constant('VIEW_IMAGES_URL', '//wwwdev2.lib.ua.edu/erCarousel/api/slides/active') .factory('imageCarouselFactory', ['$http', 'VIEW_IMAGES_URL', function imageCarouselFactory($http, url){ return { getData: function(){ return $http({method: 'GET', url: url, params: {}}); } }; }]) .controller('imageCarouselCtrl', ['$scope', '$q', 'imageCarouselFactory', function imageCarouselCtrl($scope, $q, imageCarouselFactory){ $scope.slides = null; function loadImages(slides, i, len, deferred){ i = i ? i : 0; len = len ? len : slides.length; deferred = deferred ? deferred : $q.defer(); if (len < 1){ deferred.resolve(slides); } else{ var image = new Image(); image.onload = function(){ slides[i].styles = 'url('+this.src+')'; slides[i].image = this; if (i+1 === len){ deferred.resolve(slides); } else { i++; loadImages(slides, i, len, deferred); } }; image.src = slides[i].image; } return deferred.promise; } imageCarouselFactory.getData() .success(function(data) { loadImages(data.slides).then(function(slides){ $scope.slides = slides; }); }) .error(function(data, status, headers, config) { console.log(data); }); }]) .directive('ualibImageCarousel', [ function() { return { restrict: 'AC', controller: 'imageCarouselCtrl', link: function(scope, elm, attrs, Ctrl){ var toggleLock = false; scope.isLocked = false; scope.pause = function(){ toggleLock = true; scope.isLocked = true; }; scope.play = function(){ toggleLock = false; scope.isLocked = false; }; scope.mouseToggle = function(){ if (!toggleLock){ scope.isLocked = !scope.isLocked; } }; } }; }]);
8bitsquid/roots-ualib
assets/js/_ualib_imageCarousel.js
JavaScript
mit
2,702
import { ListWrapper } from 'angular2/src/facade/collection'; import { stringify, isBlank } from 'angular2/src/facade/lang'; import { BaseException, WrappedException } from 'angular2/src/facade/exceptions'; function findFirstClosedCycle(keys) { var res = []; for (var i = 0; i < keys.length; ++i) { if (ListWrapper.contains(res, keys[i])) { res.push(keys[i]); return res; } else { res.push(keys[i]); } } return res; } function constructResolvingPath(keys) { if (keys.length > 1) { var reversed = findFirstClosedCycle(ListWrapper.reversed(keys)); var tokenStrs = reversed.map(k => stringify(k.token)); return " (" + tokenStrs.join(' -> ') + ")"; } else { return ""; } } /** * Base class for all errors arising from misconfigured providers. */ export class AbstractProviderError extends BaseException { constructor(injector, key, constructResolvingMessage) { super("DI Exception"); this.keys = [key]; this.injectors = [injector]; this.constructResolvingMessage = constructResolvingMessage; this.message = this.constructResolvingMessage(this.keys); } addKey(injector, key) { this.injectors.push(injector); this.keys.push(key); this.message = this.constructResolvingMessage(this.keys); } get context() { return this.injectors[this.injectors.length - 1].debugContext(); } } /** * Thrown when trying to retrieve a dependency by `Key` from {@link Injector}, but the * {@link Injector} does not have a {@link Provider} for {@link Key}. * * ### Example ([live demo](http://plnkr.co/edit/vq8D3FRB9aGbnWJqtEPE?p=preview)) * * ```typescript * class A { * constructor(b:B) {} * } * * expect(() => Injector.resolveAndCreate([A])).toThrowError(); * ``` */ export class NoProviderError extends AbstractProviderError { constructor(injector, key) { super(injector, key, function (keys) { var first = stringify(ListWrapper.first(keys).token); return `No provider for ${first}!${constructResolvingPath(keys)}`; }); } } /** * Thrown when dependencies form a cycle. * * ### Example ([live demo](http://plnkr.co/edit/wYQdNos0Tzql3ei1EV9j?p=info)) * * ```typescript * var injector = Injector.resolveAndCreate([ * provide("one", {useFactory: (two) => "two", deps: [[new Inject("two")]]}), * provide("two", {useFactory: (one) => "one", deps: [[new Inject("one")]]}) * ]); * * expect(() => injector.get("one")).toThrowError(); * ``` * * Retrieving `A` or `B` throws a `CyclicDependencyError` as the graph above cannot be constructed. */ export class CyclicDependencyError extends AbstractProviderError { constructor(injector, key) { super(injector, key, function (keys) { return `Cannot instantiate cyclic dependency!${constructResolvingPath(keys)}`; }); } } /** * Thrown when a constructing type returns with an Error. * * The `InstantiationError` class contains the original error plus the dependency graph which caused * this object to be instantiated. * * ### Example ([live demo](http://plnkr.co/edit/7aWYdcqTQsP0eNqEdUAf?p=preview)) * * ```typescript * class A { * constructor() { * throw new Error('message'); * } * } * * var injector = Injector.resolveAndCreate([A]); * try { * injector.get(A); * } catch (e) { * expect(e instanceof InstantiationError).toBe(true); * expect(e.originalException.message).toEqual("message"); * expect(e.originalStack).toBeDefined(); * } * ``` */ export class InstantiationError extends WrappedException { constructor(injector, originalException, originalStack, key) { super("DI Exception", originalException, originalStack, null); this.keys = [key]; this.injectors = [injector]; } addKey(injector, key) { this.injectors.push(injector); this.keys.push(key); } get wrapperMessage() { var first = stringify(ListWrapper.first(this.keys).token); return `Error during instantiation of ${first}!${constructResolvingPath(this.keys)}.`; } get causeKey() { return this.keys[0]; } get context() { return this.injectors[this.injectors.length - 1].debugContext(); } } /** * Thrown when an object other then {@link Provider} (or `Type`) is passed to {@link Injector} * creation. * * ### Example ([live demo](http://plnkr.co/edit/YatCFbPAMCL0JSSQ4mvH?p=preview)) * * ```typescript * expect(() => Injector.resolveAndCreate(["not a type"])).toThrowError(); * ``` */ export class InvalidProviderError extends BaseException { constructor(provider) { super("Invalid provider - only instances of Provider and Type are allowed, got: " + provider.toString()); } } /** * Thrown when the class has no annotation information. * * Lack of annotation information prevents the {@link Injector} from determining which dependencies * need to be injected into the constructor. * * ### Example ([live demo](http://plnkr.co/edit/rHnZtlNS7vJOPQ6pcVkm?p=preview)) * * ```typescript * class A { * constructor(b) {} * } * * expect(() => Injector.resolveAndCreate([A])).toThrowError(); * ``` * * This error is also thrown when the class not marked with {@link Injectable} has parameter types. * * ```typescript * class B {} * * class A { * constructor(b:B) {} // no information about the parameter types of A is available at runtime. * } * * expect(() => Injector.resolveAndCreate([A,B])).toThrowError(); * ``` */ export class NoAnnotationError extends BaseException { constructor(typeOrFunc, params) { super(NoAnnotationError._genMessage(typeOrFunc, params)); } static _genMessage(typeOrFunc, params) { var signature = []; for (var i = 0, ii = params.length; i < ii; i++) { var parameter = params[i]; if (isBlank(parameter) || parameter.length == 0) { signature.push('?'); } else { signature.push(parameter.map(stringify).join(' ')); } } return "Cannot resolve all parameters for " + stringify(typeOrFunc) + "(" + signature.join(', ') + "). " + 'Make sure they all have valid type or annotations.'; } } /** * Thrown when getting an object by index. * * ### Example ([live demo](http://plnkr.co/edit/bRs0SX2OTQiJzqvjgl8P?p=preview)) * * ```typescript * class A {} * * var injector = Injector.resolveAndCreate([A]); * * expect(() => injector.getAt(100)).toThrowError(); * ``` */ export class OutOfBoundsError extends BaseException { constructor(index) { super(`Index ${index} is out-of-bounds.`); } } // TODO: add a working example after alpha38 is released /** * Thrown when a multi provider and a regular provider are bound to the same token. * * ### Example * * ```typescript * expect(() => Injector.resolveAndCreate([ * new Provider("Strings", {useValue: "string1", multi: true}), * new Provider("Strings", {useValue: "string2", multi: false}) * ])).toThrowError(); * ``` */ export class MixingMultiProvidersWithRegularProvidersError extends BaseException { constructor(provider1, provider2) { super("Cannot mix multi providers and regular providers, got: " + provider1.toString() + " " + provider2.toString()); } } //# sourceMappingURL=exceptions.js.map
binariedMe/blogging
node_modules/angular2/es6/prod/src/core/di/exceptions.js
JavaScript
mit
7,494
// Help functions /* * Return a string with all helper functions whose name contains the 'substring'; * if the 'searchDescription' is true, then also search the function description"); */ function getHelp(substring, searchDescription) { return framework.getJavaScriptHelp(".*(?i:" + substring + ").*", searchDescription); } framework.addJavaScriptHelp("help", "substring, fileName", "output all the helper functions whose name contains the given 'substring'"); function help(substring, fileName) { if (arguments.length > 1) { write(getHelp(substring, false), fileName); } else if (arguments.length > 0) { write(getHelp(substring, false)); } else { write(getHelp("", false)); } } framework.addJavaScriptHelp("apropos", "substring, fileName", "output all the helper functions whose name or description contains the given 'substring'"); function apropos(substring, fileName) { if (arguments.length > 1) { write(getHelp(substring, true), fileName); } else if (arguments.length > 0) { write(getHelp(substring, true)); } else { write(getHelp("", true)); } } framework.addJavaScriptHelp("helpRegex", "regex, fileName", "output all helper functions whose name matches 'regex'"); function helpRegex(regex, fileName) { if (arguments.length > 1) { write(framework.getJavaScriptHelp(regex, false), fileName); } else if (arguments.length > 0) { write(framework.getJavaScriptHelp(regex, false)); } }
workcraft/workcraft
workcraft/WorkcraftCore/res/scripts/core-help.js
JavaScript
mit
1,523
FullCalendar.globalLocales.push(function () { 'use strict'; var it = { code: 'it', week: { dow: 1, // Monday is the first day of the week. doy: 4, // The week that contains Jan 4th is the first week of the year. }, buttonText: { prev: 'Prec', next: 'Succ', today: 'Oggi', month: 'Mese', week: 'Settimana', day: 'Giorno', list: 'Agenda', }, weekText: 'Sm', allDayText: 'Tutto il giorno', moreLinkText(n) { return '+altri ' + n }, noEventsText: 'Non ci sono eventi da visualizzare', }; return it; }());
unaio/una
upgrade/files/11.0.4-12.0.0.B1/files/plugins_public/fullcalendar/locale/it.js
JavaScript
mit
612
/* @flow */ /*eslint-disable no-undef, no-unused-vars, no-console*/ import _, { compose, pipe, curry, filter, find, isNil, repeat, replace, zipWith } from "ramda"; import { describe, it } from 'flow-typed-test'; const ns: Array<number> = [1, 2, 3, 4, 5]; const ss: Array<string> = ["one", "two", "three", "four"]; const obj: { [k: string]: number } = { a: 1, c: 2 }; const objMixed: { [k: string]: mixed } = { a: 1, c: "d" }; const os: Array<{ [k: string]: * }> = [{ a: 1, c: "d" }, { b: 2 }]; const str: string = "hello world"; // Math { const partDiv: (a: number) => number = _.divide(6); const div: number = _.divide(6, 2); //$FlowExpectedError const div2: number = _.divide(6, true); } // String { const ss: Array<string | void> = _.match(/h/, "b"); describe('replace', () => { it('should supports replace by string', () => { const r1: string = replace(",", "|", "b,d,d"); const r2: string = replace(",")("|", "b,d,d"); const r3: string = replace(",")("|")("b,d,d"); const r4: string = replace(",", "|")("b,d,d"); }); it('should supports replace by RegExp', () => { const r1: string = replace(/[,]/, "|", "b,d,d"); const r2: string = replace(/[,]/)("|", "b,d,d"); const r3: string = replace(/[,]/)("|")("b,d,d"); const r4: string = replace(/[,]/, "|")("b,d,d"); }); it('should supports replace by RegExp with replacement fn', () => { const fn = (match: string, g1: string): string => g1; const r1: string = replace(/([,])d/, fn, "b,d,d"); const r2: string = replace(/([,])d/)(fn, "b,d,d"); const r3: string = replace(/([,])d/)(fn)("b,d,d"); const r4: string = replace(/([,])d/, fn)("b,d,d"); }); }); const ss2: Array<string> = _.split(",", "b,d,d"); const ss1: boolean = _.test(/h/, "b"); const s: string = _.trim("s"); const x: string = _.head("one"); const sss: string = _.concat("H", "E"); const sss1: string = _.concat("H")("E"); const ssss: string = _.drop(1, "EF"); const ssss1: string = _.drop(1)("E"); const ssss2: string = _.dropLast(1, "EF"); const ys: string = _.nth(2, "curry"); const ys1: string = _.nth(2)("curry"); } //Type { const x: boolean = _.is(Number, 1); const x1: boolean = isNil(1); // should refine type const x1a: ?{ a: number } = { a: 1 }; //$FlowExpectedError x1a.a; if (!isNil(x1a)) { x1a.a; } const x2: boolean = _.propIs(1, "num", { num: 1 }); }
flowtype/flow-typed
definitions/npm/ramda_v0.27.x/flow_v0.76.x-v0.103.x/test_ramda_v0.27.x_misc.js
JavaScript
mit
2,464
'use strict'; exports.up = function (knex) { return knex.schema.createTable('migration_test_trx_1', function (t) { t.increments(); t.string('name'); }); }; exports.down = function (knex) { return knex.schema.dropTable('migration_test_trx_1'); };
tgriesser/knex
test/integration/migrate/test_per_migration_trx_enabled/20131019235242_migration_1.js
JavaScript
mit
262
/** * @author mrdoob / http://mrdoob.com/ * @author bhouston / http://exocortex.com/ */ ( function ( THREE ) { THREE.Raycaster = function ( origin, direction, near, far ) { this.ray = new THREE.Ray( origin, direction ); // normalized ray.direction required for accurate distance calculations if( this.ray.direction.lengthSq() > 0 ) { this.ray.direction.normalize(); } this.near = near || 0; this.far = far || Infinity; }; var sphere = new THREE.Sphere(); var localRay = new THREE.Ray(); var facePlane = new THREE.Plane(); var intersectPoint = new THREE.Vector3(); var matrixPosition = new THREE.Vector3(); var inverseMatrix = new THREE.Matrix4(); var descSort = function ( a, b ) { return a.distance - b.distance; }; var intersectObject = function ( object, raycaster, intersects ) { if ( object instanceof THREE.Particle ) { matrixPosition.getPositionFromMatrix( object.matrixWorld ); var distance = raycaster.ray.distanceToPoint( matrixPosition ); if ( distance > object.scale.x ) { return intersects; } intersects.push( { distance: distance, point: object.position, face: null, object: object } ); } else if ( object instanceof THREE.Mesh ) { // Checking boundingSphere distance to ray matrixPosition.getPositionFromMatrix( object.matrixWorld ); sphere.set( matrixPosition, object.geometry.boundingSphere.radius * object.matrixWorld.getMaxScaleOnAxis() ); if ( ! raycaster.ray.isIntersectionSphere( sphere ) ) { return intersects; } // Checking faces var geometry = object.geometry; var vertices = geometry.vertices; var isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial; var objectMaterials = isFaceMaterial === true ? object.material.materials : null; var side = object.material.side; var a, b, c, d; var precision = raycaster.precision; object.matrixRotationWorld.extractRotation( object.matrixWorld ); inverseMatrix.getInverse( object.matrixWorld ); localRay.copy( raycaster.ray ).applyMatrix4( inverseMatrix ); for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) { var face = geometry.faces[ f ]; var material = isFaceMaterial === true ? objectMaterials[ face.materialIndex ] : object.material; if ( material === undefined ) continue; facePlane.setFromNormalAndCoplanarPoint( face.normal, vertices[face.a] ); var planeDistance = localRay.distanceToPlane( facePlane ); // bail if raycaster and plane are parallel if ( Math.abs( planeDistance ) < precision ) continue; // if negative distance, then plane is behind raycaster if ( planeDistance < 0 ) continue; // check if we hit the wrong side of a single sided face side = material.side; if( side !== THREE.DoubleSide ) { var planeSign = localRay.direction.dot( facePlane.normal ); if( ! ( side === THREE.FrontSide ? planeSign < 0 : planeSign > 0 ) ) continue; } // this can be done using the planeDistance from localRay because localRay wasn't normalized, but ray was if ( planeDistance < raycaster.near || planeDistance > raycaster.far ) continue; intersectPoint = localRay.at( planeDistance, intersectPoint ); // passing in intersectPoint avoids a copy if ( face instanceof THREE.Face3 ) { a = vertices[ face.a ]; b = vertices[ face.b ]; c = vertices[ face.c ]; if ( ! THREE.Triangle.containsPoint( intersectPoint, a, b, c ) ) continue; } else if ( face instanceof THREE.Face4 ) { a = vertices[ face.a ]; b = vertices[ face.b ]; c = vertices[ face.c ]; d = vertices[ face.d ]; if ( ( ! THREE.Triangle.containsPoint( intersectPoint, a, b, d ) ) && ( ! THREE.Triangle.containsPoint( intersectPoint, b, c, d ) ) ) continue; } else { // This is added because if we call out of this if/else group when none of the cases // match it will add a point to the intersection list erroneously. throw Error( "face type not supported" ); } intersects.push( { distance: planeDistance, // this works because the original ray was normalized, and the transformed localRay wasn't point: raycaster.ray.at( planeDistance ), face: face, faceIndex: f, object: object } ); } } }; var intersectDescendants = function ( object, raycaster, intersects ) { var descendants = object.getDescendants(); for ( var i = 0, l = descendants.length; i < l; i ++ ) { intersectObject( descendants[ i ], raycaster, intersects ); } }; // THREE.Raycaster.prototype.precision = 0.0001; THREE.Raycaster.prototype.set = function ( origin, direction ) { this.ray.set( origin, direction ); // normalized ray.direction required for accurate distance calculations if( this.ray.direction.length() > 0 ) { this.ray.direction.normalize(); } }; THREE.Raycaster.prototype.intersectObject = function ( object, recursive ) { var intersects = []; if ( recursive === true ) { intersectDescendants( object, this, intersects ); } intersectObject( object, this, intersects ); intersects.sort( descSort ); return intersects; }; THREE.Raycaster.prototype.intersectObjects = function ( objects, recursive ) { var intersects = []; for ( var i = 0, l = objects.length; i < l; i ++ ) { intersectObject( objects[ i ], this, intersects ); if ( recursive === true ) { intersectDescendants( objects[ i ], this, intersects ); } } intersects.sort( descSort ); return intersects; }; }( THREE ) );
DLar/three.js
src/core/Raycaster.js
JavaScript
mit
5,607
'use strict'; require('../../modules/es.weak-set'); require('../../modules/esnext.weak-set.from'); var WeakSet = require('../../internals/path').WeakSet; var weakSetfrom = WeakSet.from; module.exports = function from(source, mapFn, thisArg) { return weakSetfrom.call(typeof this === 'function' ? this : WeakSet, source, mapFn, thisArg); };
AntonyThorpe/knockout-apollo
tests/node_modules/core-js/features/weak-set/from.js
JavaScript
mit
343
/** @babel */ /** @jsx etch.dom **/ import etch from 'etch'; export default class WelcomeView { constructor(props) { this.props = props; etch.initialize(this); this.element.addEventListener('click', event => { const link = event.target.closest('a'); if (link && link.dataset.event) { this.props.reporterProxy.sendEvent( `clicked-welcome-${link.dataset.event}-link` ); } }); } didChangeShowOnStartup() { atom.config.set('welcome.showOnStartup', this.checked); } update() {} serialize() { return { deserializer: 'WelcomeView', uri: this.props.uri }; } render() { return ( <div className="welcome"> <div className="welcome-container"> <header className="welcome-header"> <a href="https://atom.io/"> <svg className="welcome-logo" width="330px" height="68px" viewBox="0 0 330 68" version="1.1" > <g stroke="none" stroke-width="1" fill="none" fill-rule="evenodd" > <g transform="translate(2.000000, 1.000000)"> <g transform="translate(96.000000, 8.000000)" fill="currentColor" > <path d="M185.498,3.399 C185.498,2.417 186.34,1.573 187.324,1.573 L187.674,1.573 C188.447,1.573 189.01,1.995 189.5,2.628 L208.676,30.862 L227.852,2.628 C228.272,1.995 228.905,1.573 229.676,1.573 L230.028,1.573 C231.01,1.573 231.854,2.417 231.854,3.399 L231.854,49.403 C231.854,50.387 231.01,51.231 230.028,51.231 C229.044,51.231 228.202,50.387 228.202,49.403 L228.202,8.246 L210.151,34.515 C209.729,35.148 209.237,35.428 208.606,35.428 C207.973,35.428 207.481,35.148 207.061,34.515 L189.01,8.246 L189.01,49.475 C189.01,50.457 188.237,51.231 187.254,51.231 C186.27,51.231 185.498,50.458 185.498,49.475 L185.498,3.399 L185.498,3.399 Z" /> <path d="M113.086,26.507 L113.086,26.367 C113.086,12.952 122.99,0.941 137.881,0.941 C152.77,0.941 162.533,12.811 162.533,26.225 L162.533,26.367 C162.533,39.782 152.629,51.792 137.74,51.792 C122.85,51.792 113.086,39.923 113.086,26.507 M158.74,26.507 L158.74,26.367 C158.74,14.216 149.89,4.242 137.74,4.242 C125.588,4.242 116.879,14.075 116.879,26.225 L116.879,26.367 C116.879,38.518 125.729,48.491 137.881,48.491 C150.031,48.491 158.74,38.658 158.74,26.507" /> <path d="M76.705,5.155 L60.972,5.155 C60.06,5.155 59.287,4.384 59.287,3.469 C59.287,2.556 60.059,1.783 60.972,1.783 L96.092,1.783 C97.004,1.783 97.778,2.555 97.778,3.469 C97.778,4.383 97.005,5.155 96.092,5.155 L80.358,5.155 L80.358,49.405 C80.358,50.387 79.516,51.231 78.532,51.231 C77.55,51.231 76.706,50.387 76.706,49.405 L76.706,5.155 L76.705,5.155 Z" /> <path d="M0.291,48.562 L21.291,3.05 C21.783,1.995 22.485,1.292 23.75,1.292 L23.891,1.292 C25.155,1.292 25.858,1.995 26.348,3.05 L47.279,48.421 C47.49,48.843 47.56,49.194 47.56,49.546 C47.56,50.458 46.788,51.231 45.803,51.231 C44.961,51.231 44.329,50.599 43.978,49.826 L38.219,37.183 L9.21,37.183 L3.45,49.897 C3.099,50.739 2.538,51.231 1.694,51.231 C0.781,51.231 0.008,50.529 0.008,49.685 C0.009,49.404 0.08,48.983 0.291,48.562 L0.291,48.562 Z M36.673,33.882 L23.749,5.437 L10.755,33.882 L36.673,33.882 L36.673,33.882 Z" /> </g> <g> <path d="M40.363,32.075 C40.874,34.44 39.371,36.77 37.006,37.282 C34.641,37.793 32.311,36.29 31.799,33.925 C31.289,31.56 32.791,29.23 35.156,28.718 C37.521,28.207 39.851,29.71 40.363,32.075" fill="currentColor" /> <path d="M48.578,28.615 C56.851,45.587 58.558,61.581 52.288,64.778 C45.822,68.076 33.326,56.521 24.375,38.969 C15.424,21.418 13.409,4.518 19.874,1.221 C22.689,-0.216 26.648,1.166 30.959,4.629" stroke="currentColor" stroke-width="3.08" stroke-linecap="round" /> <path d="M7.64,39.45 C2.806,36.94 -0.009,33.915 0.154,30.79 C0.531,23.542 16.787,18.497 36.462,19.52 C56.137,20.544 71.781,27.249 71.404,34.497 C71.241,37.622 68.127,40.338 63.06,42.333" stroke="currentColor" stroke-width="3.08" stroke-linecap="round" /> <path d="M28.828,59.354 C23.545,63.168 18.843,64.561 15.902,62.653 C9.814,58.702 13.572,42.102 24.296,25.575 C35.02,9.048 48.649,-1.149 54.736,2.803 C57.566,4.639 58.269,9.208 57.133,15.232" stroke="currentColor" stroke-width="3.08" stroke-linecap="round" /> </g> </g> </g> </svg> <h1 className="welcome-title"> A hackable text editor for the 21<sup>st</sup> Century </h1> </a> </header> <section className="welcome-panel"> <p>For help, please visit</p> <ul> <li> The{' '} <a href="https://www.atom.io/docs" dataset={{ event: 'atom-docs' }} > Atom docs </a>{' '} for Guides and the API reference. </li> <li> The Atom forum at{' '} <a href="https://github.com/atom/atom/discussions" dataset={{ event: 'discussions' }} > Github Discussions </a> </li> <li> The{' '} <a href="https://github.com/atom" dataset={{ event: 'atom-org' }} > Atom org </a> . This is where all GitHub-created Atom packages can be found. </li> </ul> </section> <section className="welcome-panel"> <label> <input className="input-checkbox" type="checkbox" checked={atom.config.get('welcome.showOnStartup')} onchange={this.didChangeShowOnStartup} /> Show Welcome Guide when opening Atom </label> </section> <footer className="welcome-footer"> <a href="https://atom.io/" dataset={{ event: 'footer-atom-io' }}> atom.io </a>{' '} <span className="text-subtle">×</span>{' '} <a className="icon icon-octoface" href="https://github.com/" dataset={{ event: 'footer-octocat' }} /> </footer> </div> </div> ); } getURI() { return this.props.uri; } getTitle() { return 'Welcome'; } isEqual(other) { return other instanceof WelcomeView; } }
PKRoma/atom
packages/welcome/lib/welcome-view.js
JavaScript
mit
7,386
'use strict'; angular.module('sw.plugin.split', ['sw.plugins']) .factory('split', function ($q) { return { execute: execute }; function execute (url, swagger) { var deferred = $q.defer(); if (swagger && swagger.swagger && !swagger.tags) { var tags = {}; angular.forEach(swagger.paths, function (path, key) { var t = key.replace(/^\/?([^\/]+).*$/g, '$1'); tags[t] = true; angular.forEach(path, function (method) { if (!method.tags || !method.tags.length) { method.tags = [t]; } }); }); swagger.tags = []; Object.keys(tags).forEach(function (tag) { swagger.tags.push({name: tag}); }); } deferred.resolve(true); return deferred.promise; } }) .run(function (plugins, split) { plugins.add(plugins.BEFORE_PARSE, split); });
darosh/angular-swagger-ui-material
src/plugins/before-parse/split.js
JavaScript
mit
1,127
/*----------------------------------------------------------------------------------- /* /* Main JS /* -----------------------------------------------------------------------------------*/ (function($) { /*---------------------------------------------------- */ /* Preloader ------------------------------------------------------ */ $(window).load(function() { // will first fade out the loading animation $("#status").fadeOut("slow"); // will fade out the whole DIV that covers the website. $("#preloader").delay(500).fadeOut("slow").remove(); $('.js #hero .hero-image img').addClass("animated fadeInUpBig"); $('.js #hero .buttons a.trial').addClass("animated shake"); }) /*---------------------------------------------------- */ /* Mobile Menu ------------------------------------------------------ */ var toggle_button = $("<a>", { id: "toggle-btn", html : "Menu", title: "Menu", href : "#" } ); var nav_wrap = $('nav#nav-wrap') var nav = $("ul#nav"); /* id JS is enabled, remove the two a.mobile-btns and dynamically prepend a.toggle-btn to #nav-wrap */ nav_wrap.find('a.mobile-btn').remove(); nav_wrap.prepend(toggle_button); toggle_button.on("click", function(e) { e.preventDefault(); nav.slideToggle("fast"); }); if (toggle_button.is(':visible')) nav.addClass('mobile'); $(window).resize(function(){ if (toggle_button.is(':visible')) nav.addClass('mobile'); else nav.removeClass('mobile'); }); $('ul#nav li a').on("click", function(){ if (nav.hasClass('mobile')) nav.fadeOut('fast'); }); /*----------------------------------------------------*/ /* FitText Settings ------------------------------------------------------ */ setTimeout(function() { $('h1.responsive-headline').fitText(1.2, { minFontSize: '25px', maxFontSize: '40px' }); }, 100); /*----------------------------------------------------*/ /* Smooth Scrolling ------------------------------------------------------ */ $('.smoothscroll').on('click', function (e) { e.preventDefault(); var target = this.hash, $target = $(target); $('html, body').stop().animate({ 'scrollTop': $target.offset().top }, 800, 'swing', function () { window.location.hash = target; }); }); /*----------------------------------------------------*/ /* Highlight the current section in the navigation bar ------------------------------------------------------*/ var sections = $("section"), navigation_links = $("#nav-wrap a"); sections.waypoint( { handler: function(event, direction) { var active_section; active_section = $(this); if (direction === "up") active_section = active_section.prev(); var active_link = $('#nav-wrap a[href="#' + active_section.attr("id") + '"]'); navigation_links.parent().removeClass("current"); active_link.parent().addClass("current"); }, offset: '35%' }); /*----------------------------------------------------*/ /* FitVids /*----------------------------------------------------*/ $(".fluid-video-wrapper").fitVids(); /*----------------------------------------------------*/ /* Waypoints Animations ------------------------------------------------------ */ $('.js .design').waypoint(function() { $('.js .design .feature-media').addClass( 'animated pulse' ); }, { offset: 'bottom-in-view' }); $('.js .responsive').waypoint(function() { $('.js .responsive .feature-media').addClass( 'animated pulse' ); }, { offset: 'bottom-in-view' }); $('.js .cross-browser').waypoint(function() { $('.js .cross-browser .feature-media').addClass( 'animated pulse' ); }, { offset: 'bottom-in-view' }); $('.js .video').waypoint(function() { $('.js .video .feature-media').addClass( 'animated pulse' ); }, { offset: 'bottom-in-view' }); $('.js #subscribe').waypoint(function() { $('.js #subscribe input[type="email"]').addClass( 'animated fadeInLeftBig show' ); $('.js #subscribe input[type="submit"]').addClass( 'animated fadeInRightBig show' ); }, { offset: 'bottom-in-view' }); /*----------------------------------------------------*/ /* Flexslider /*----------------------------------------------------*/ $('.flexslider').flexslider({ namespace: "flex-", controlsContainer: ".flex-container", animation: 'slide', controlNav: true, directionNav: false, smoothHeight: true, slideshowSpeed: 7000, animationSpeed: 600, randomize: false, }); /*----------------------------------------------------*/ /* ImageLightbox /*----------------------------------------------------*/ if($("html").hasClass('cssanimations')) { var activityIndicatorOn = function() { $( '<div id="imagelightbox-loading"><div></div></div>' ).appendTo( 'body' ); }, activityIndicatorOff = function() { $( '#imagelightbox-loading' ).remove(); }, overlayOn = function() { $( '<div id="imagelightbox-overlay"></div>' ).appendTo( 'body' ); }, overlayOff = function() { $( '#imagelightbox-overlay' ).remove(); }, closeButtonOn = function( instance ) { $( '<a href="#" id="imagelightbox-close" title="close"><i class="fa fa fa-times"></i></a>' ).appendTo( 'body' ).on( 'click touchend', function(){ $( this ).remove(); instance.quitImageLightbox(); return false; }); }, closeButtonOff = function() { $( '#imagelightbox-close' ).remove(); }, captionOn = function() { var description = $( 'a[href="' + $( '#imagelightbox' ).attr( 'src' ) + '"] img' ).attr( 'alt' ); if( description.length > 0 ) $( '<div id="imagelightbox-caption">' + description + '</div>' ).appendTo( 'body' ); }, captionOff = function() { $( '#imagelightbox-caption' ).remove(); }; var instanceA = $( 'a[data-imagelightbox="a"]' ).imageLightbox( { onStart: function() { overlayOn(); closeButtonOn( instanceA ); }, onEnd: function() { overlayOff(); captionOff(); closeButtonOff(); activityIndicatorOff(); }, onLoadStart: function() { captionOff(); activityIndicatorOn(); }, onLoadEnd: function() { captionOn(); activityIndicatorOff(); } }); } else { /*----------------------------------------------------*/ /* prettyPhoto for old IE /*----------------------------------------------------*/ $("#screenshots").find(".item-wrap a").attr("rel","prettyPhoto[pp_gal]"); $("a[rel^='prettyPhoto']").prettyPhoto( { animation_speed: 'fast', /* fast/slow/normal */ slideshow: false, /* false OR interval time in ms */ autoplay_slideshow: false, /* true/false */ opacity: 0.80, /* Value between 0 and 1 */ show_title: true, /* true/false */ allow_resize: true, /* Resize the photos bigger than viewport. true/false */ default_width: 500, default_height: 344, counter_separator_label: '/', /* The separator for the gallery counter 1 "of" 2 */ theme: 'pp_default', /* light_rounded / dark_rounded / light_square / dark_square / facebook */ hideflash: false, /* Hides all the flash object on a page, set to TRUE if flash appears over prettyPhoto */ wmode: 'opaque', /* Set the flash wmode attribute */ autoplay: true, /* Automatically start videos: True/False */ modal: false, /* If set to true, only the close button will close the window */ overlay_gallery: false, /* If set to true, a gallery will overlay the fullscreen image on mouse over */ keyboard_shortcuts: true, /* Set to false if you open forms inside prettyPhoto */ deeplinking: false, social_tools: false }); } })(jQuery);
wassapste97/sitomio
resources/js/main.js
JavaScript
mit
8,220
/** * @license Highcharts Gantt JS v7.2.0 (2019-09-03) * * CurrentDateIndicator * * (c) 2010-2019 Lars A. V. Cabrera * * License: www.highcharts.com/license */ 'use strict'; (function (factory) { if (typeof module === 'object' && module.exports) { factory['default'] = factory; module.exports = factory; } else if (typeof define === 'function' && define.amd) { define('highcharts/modules/current-date-indicator', ['highcharts'], function (Highcharts) { factory(Highcharts); factory.Highcharts = Highcharts; return factory; }); } else { factory(typeof Highcharts !== 'undefined' ? Highcharts : undefined); } }(function (Highcharts) { var _modules = Highcharts ? Highcharts._modules : {}; function _registerModule(obj, path, args, fn) { if (!obj.hasOwnProperty(path)) { obj[path] = fn.apply(null, args); } } _registerModule(_modules, 'parts-gantt/CurrentDateIndicator.js', [_modules['parts/Globals.js']], function (H) { /* * * * (c) 2016-2019 Highsoft AS * * Author: Lars A. V. Cabrera * * License: www.highcharts.com/license * * !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!! * * */ var addEvent = H.addEvent, Axis = H.Axis, PlotLineOrBand = H.PlotLineOrBand, merge = H.merge, wrap = H.wrap; var defaultConfig = { /** * Show an indicator on the axis for the current date and time. Can be a * boolean or a configuration object similar to * [xAxis.plotLines](#xAxis.plotLines). * * @sample gantt/current-date-indicator/demo * Current date indicator enabled * @sample gantt/current-date-indicator/object-config * Current date indicator with custom options * * @type {boolean|*} * @default true * @extends xAxis.plotLines * @excluding value * @product gantt * @apioption xAxis.currentDateIndicator */ currentDateIndicator: true, color: '#ccd6eb', width: 2, label: { /** * Format of the label. This options is passed as the fist argument to * [dateFormat](/class-reference/Highcharts#dateFormat) function. * * @type {string} * @default '%a, %b %d %Y, %H:%M' * @product gantt * @apioption xAxis.currentDateIndicator.label.format */ format: '%a, %b %d %Y, %H:%M', formatter: function (value, format) { return H.dateFormat(format, value); }, rotation: 0, style: { fontSize: '10px' } } }; /* eslint-disable no-invalid-this */ addEvent(Axis, 'afterSetOptions', function () { var options = this.options, cdiOptions = options.currentDateIndicator; if (cdiOptions) { cdiOptions = typeof cdiOptions === 'object' ? merge(defaultConfig, cdiOptions) : merge(defaultConfig); cdiOptions.value = new Date(); if (!options.plotLines) { options.plotLines = []; } options.plotLines.push(cdiOptions); } }); addEvent(PlotLineOrBand, 'render', function () { // If the label already exists, update its text if (this.label) { this.label.attr({ text: this.getLabelText(this.options.label) }); } }); wrap(PlotLineOrBand.prototype, 'getLabelText', function (defaultMethod, defaultLabelOptions) { var options = this.options; if (options.currentDateIndicator && options.label && typeof options.label.formatter === 'function') { options.value = new Date(); return options.label.formatter .call(this, options.value, options.label.format); } return defaultMethod.call(this, defaultLabelOptions); }); }); _registerModule(_modules, 'masters/modules/current-date-indicator.src.js', [], function () { }); }));
extend1994/cdnjs
ajax/libs/highcharts/7.2.0/modules/current-date-indicator.src.js
JavaScript
mit
4,598
var dep = require('./dep'); dep('');
gsteacy/ts-loader
test/execution-tests/1.8.2_allowJs-entryFileIsJs/src/app.js
JavaScript
mit
37
/** * @license Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'magicline', 'it', { title: 'Inserisci paragrafo qui' } );
SeeyaSia/www
web/libraries/ckeditor/plugins/magicline/lang/it.js
JavaScript
gpl-2.0
247
import React from "react"; import PropTypes from "prop-types"; import Box from "grommet/components/Box"; import Paragraph from "grommet/components/Paragraph"; import Label from "grommet/components/Label"; import FormLayer from "../components/FormLayer"; class LayerObjectFieldTemplate extends React.Component { constructor(props) { super(props); this.state = { layerActive: false }; } _onClick() { this.setState({ layerActive: true }); } render() { if (this.props.idSchema["$id"] == "root") { return <Box>{this.props.properties.map(prop => prop.content)}</Box>; } else { return ( <Box className="grommetux-form-field" direction="row" wrap={false}> { <FormLayer layerActive={this.state.layerActive} onClose={(() => { this.setState({ layerActive: false }); }).bind(this)} properties={this.props.properties.map(prop => prop.content)} /> } <Box flex={true}> <Box align="center"> <Label size="small" strong="none" uppercase={true}> {this.props.title} </Label> </Box> {this.props.description ? ( <Paragraph size="small">{this.props.description}</Paragraph> ) : null} </Box> </Box> ); } } } LayerObjectFieldTemplate.propTypes = { title: PropTypes.string, description: PropTypes.string, required: PropTypes.bool, idSchema: PropTypes.object, uiSchema: PropTypes.object, properties: PropTypes.object }; export default LayerObjectFieldTemplate;
pamfilos/data.cern.ch
ui/cap-react/src/components/drafts/form/themes/grommet-preview/templates/LayerObjectFieldTemplate.js
JavaScript
gpl-2.0
1,677
var UserInformation_AccountStore = new Ext.data.Store({ fields:[ {name : 'Name'}, {name : 'ID'}, {name : 'Mail'}, {name : 'Roles'} ], reader : AccountReader }); var UserInformationItem = [ { fieldLabel : 'User ID', name : 'id', readOnly : true }, { fieldLabel : 'User Name', name : 'username', allowBlank : false, regex : /^[^"'\\><&]*$/, regexText : 'deny following char " < > \\ & \'' }, { id : 'UserInformation_Form_Password', fieldLabel : 'Password', name : 'passwd', inputType : 'password', listeners : { 'change': function() { if (this.getValue() == "") { Ext.getCmp('UserInformationManagement_Page').getTopToolbar().get('UserInformation_UpdateAccountBtn').setDisabled(false); Ext.getCmp("UserInformation_Form_reenter").allowBlank = true; } else { Ext.getCmp('UserInformationManagement_Page').getTopToolbar().get('UserInformation_UpdateAccountBtn').setDisabled(true); Ext.getCmp("UserInformation_Form_reenter").allowBlank = false; } } } }, { id : 'UserInformation_Form_reenter', fieldLabel : 'Re-enter', initialPassField : 'passwd', name : 'reenter', inputType : 'password', initialPassField: 'UserInformation_Form_Password', vtype : 'pwdvalid', listeners : { 'change': function() { if (Ext.getCmp("UserInformation_Form_Password").getValue() == "") { Ext.getCmp('UserInformationManagement_Page').getTopToolbar().get('UserInformation_UpdateAccountBtn').setDisabled(true); this.allowBlank = true; } else { Ext.getCmp('UserInformationManagement_Page').getTopToolbar().get('UserInformation_UpdateAccountBtn').setDisabled(false); this.allowBlank = false; } } } }, { fieldLabel : 'E-mail Address', name : 'email', vtype : 'email', allowBlank : false } ]; // the form is for UserInformation Page ezScrum.UserInformationForm = Ext.extend(ezScrum.layout.InfoForm, { id : 'UserInformation_Management_From', url : 'getUserData.do', modifyurl : 'updateAccount.do' , store : UserInformation_AccountStore, width:500, bodyStyle:'padding:50px', monitorValid : true, buttonAlign:'center', initComponent : function() { var config = { items : [UserInformationItem], buttons : [{ formBind : true, text : 'Submit', scope : this, handler : this.submit, disabled : true }] } Ext.apply(this, Ext.apply(this.initialConfig, config)); ezScrum.UserInformationForm.superclass.initComponent.apply(this, arguments); }, submit : function() { Ext.getCmp('UserInformationManagement_Page').doModify(); }, loadDataModel: function() { UserManagementMainLoadMaskShow(); Ext.Ajax.request({ scope : this, url : this.url, success: function(response) { UserInformation_AccountStore.loadData(response.responseXML); var record = UserInformation_AccountStore.getAt(0); this.setDataModel(record); UserManagementMainLoadMaskHide(); }, failure: function(response) { UserManagementMainLoadMaskHide(); Ext.example.msg('Server Error', 'Sorry, the connection is failure.'); } }); }, setDataModel: function(record) { this.getForm().reset(); this.getForm().setValues({ id : record.data['ID'], username: record.data['Name'], passwd : '', reenter : '', email : record.data['Mail'] }); }, doModify: function() { UserManagementMainLoadMaskShow(); Ext.Ajax.request({ scope : this, url : this.modifyurl, params : this.getForm().getValues(), success : function(response) { UserInformation_AccountStore.loadData(response.responseXML); var record = UserInformation_AccountStore.getAt(0); if (record) { Ext.example.msg('Update Account', 'Update Account Success'); } else { Ext.example.msg('Update Account', 'Update Account Failure'); } UserManagementMainLoadMaskHide(); }, failure:function(response){ UserManagementMainLoadMaskHide(); Ext.example.msg('Server Error', 'Sorry, the connection is failure.'); } }); } }); Ext.reg('UserInformationForm', ezScrum.UserInformationForm);
chusiang/ezScrum_Ubuntu
WebContent/javascript/ezScrumPanel/UserInformationManagementFormPanel.js
JavaScript
gpl-2.0
4,497
(function ($) { providers_small.mailru = { name: 'mail.ru', url: "javascript: $('#mail_ru_auth_login a').click();" }; openid.getBoxHTML__mailru = openid.getBoxHTML; openid.getBoxHTML = function (box_id, provider, box_size, index) { if (box_id == 'mailru') { var no_sprite = this.no_sprite; this.no_sprite = true; var result = this.getBoxHTML__mailru(box_id, provider, box_size, index); this.no_sprite = no_sprite; return result; } return this.getBoxHTML__mailru(box_id, provider, box_size, index); } Drupal.behaviors.openid_selector_mailru = { attach: function (context) { $('#mail_ru_auth_login').hide(); }} })(jQuery);
janicak/C-Db
sites/all/modules/openid_selector/openid_selector_mailru.js
JavaScript
gpl-2.0
650
/* Class: Graphic.Ellipse Shape implementation of an ellipse. Author: Sébastien Gruhier, <http://www.xilinus.com> License: MIT-style license. See Also: <Shape> */ Graphic.Ellipse = Class.create(); Object.extend(Graphic.Ellipse.prototype, Graphic.Shape.prototype); // Keep parent initialize Graphic.Ellipse.prototype._shapeInitialize = Graphic.Shape.prototype.initialize; Object.extend(Graphic.Ellipse.prototype, { initialize: function(renderer) { this._shapeInitialize(renderer, "ellipse"); Object.extend(this.attributes, {cx: 0, cy: 0, rx: 0, ry: 0}) return this; }, getSize: function() { return {w: 2 * this.attributes.rx, h: 2 * this.attributes.ry} }, setSize: function(width, height) { var location = this.getLocation(); this._setAttributes({rx: width/2, ry: height/2}); this.setLocation(location.x, location.y); return this; }, getLocation: function() { return {x: this.attributes.cx - this.attributes.rx, y: this.attributes.cy - this.attributes.ry} }, setLocation: function(x, y) { this._setAttributes({cx: x + this.attributes.rx, cy: y + this.attributes.ry}); return this; } })
j9recurses/whirld
vendor/assets/components/cartagen/lib/prototype-graphic/src/shape/ellipse.js
JavaScript
gpl-3.0
1,191
define(["ng", "lodash"], function(ng, _){ "use strict"; var DashboardVM = function DashboardVM($scope, $rootScope){ var _self = this; this.toggleHStretch = function(isOn){ _self.setOptions(options); }; this.updateOptions = function(options){ ng.extend(_self, options); }; this.resetOptions = function(){ _self.updateOptions(_self.attr); }; this.setAttr = function(attr){ _self.attr=attr; _self.updateOptions(attr); }; this.remove = function(target){ // _.remove(_self.items, {name: target}); delete _self.items[target]; console.debug("remove _self.items", _self.items); }; this.items = $scope.dashboardItems; // this.items = [ // { // name: "survival1", // title: "survival1", // content: "moving around" // }, // { // name: "hcl1", // title: "hcl1", // content: "moving around" // }, // { // name: "ttest1", // title: "ttest1", // content: "moving around" // }, // { // name: "limma1", // title: "limma1", // content: "moving around" // }, // { // name: "deseq1", // title: "deseq1", // content: "moving around" // }, // { // name: "nmf", // title: "nmf", // content: "moving around" // }, // { // name: "kmeans1", // title: "kmeans1", // content: "moving around" // } // ]; $scope.$on("ui:dashboard:addItem", function($event, data){ var exists = _.find(_self.items, {name: data.name}); if(exists){ $rootScope.$broadcast("ui:analysisLog.append", "info", "Cannot add analysis '" + data.name + "' to the dashboard. It is already there."); }else{ _self.items.$add(data); } }); $scope.$on("ui:dashboard:removeItem", function($event, data){ console.debug("on ui:dashboard:removeItem", $event, data); _self.remove(data.name); }); }; DashboardVM.$inject=["$scope", "$rootScope"]; DashboardVM.$name="DashboardVMController"; return DashboardVM; });
apartensky/mev
web/src/main/javascript/edu/dfci/cccb/mev/web/ui/app/widgets/dashboard/controllers/DashboardVM.js
JavaScript
gpl-3.0
1,974
modules.define( 'spec', ['button', 'i-bem__dom', 'chai', 'jquery', 'BEMHTML'], function(provide, Button, BEMDOM, chai, $, BEMHTML) { var expect = chai.expect; describe('button_type_link', function() { var button; beforeEach(function() { button = buildButton({ block : 'button', mods : { type : 'link' }, url : '/' }); }); afterEach(function() { BEMDOM.destruct(button.domElem); }); describe('url', function() { it('should properly gets url', function() { button.domElem.attr('href').should.be.equal('/'); button.getUrl().should.be.equal('/'); }); it('should properly sets url', function() { button.setUrl('/bla'); button.domElem.attr('href').should.be.equal('/bla'); button.getUrl().should.be.equal('/bla'); }); }); describe('disabled', function() { it('should remove "href" attribute if disabled before init', function() { BEMDOM.destruct(button.domElem); // we need to destruct default button from beforeEach button = buildButton({ block : 'button', mods : { type : 'link', disabled : true }, url : '/' }); button.getUrl().should.be.equal('/'); expect(button.domElem.attr('href')).to.be.undefined; }); it('should update attributes properly', function() { button.setMod('disabled'); button.domElem.attr('aria-disabled').should.be.equal('true'); expect(button.domElem.attr('href')).to.be.undefined; button.delMod('disabled'); button.domElem.attr('href').should.be.equal('/'); expect(button.domElem.attr('aria-disabled')).to.be.undefined; }); }); function buildButton(bemjson) { return BEMDOM.init($(BEMHTML.apply(bemjson)) .appendTo('body')) .bem('button'); } }); provide(); });
dojdev/bem-components
common.blocks/button/_type/button_type_link.spec.js
JavaScript
mpl-2.0
2,043
// |jit-test| allow-oom; allow-unhandlable-oom gcparam("maxBytes", gcparam("gcBytes") + 4*1024); var max = 400; function f(b) { if (b) { f(b - 1); } else { g = { apply:function(x,y) { } }; } g.apply(null, arguments); } f(max - 1);
Yukarumya/Yukarum-Redfoxes
js/src/jit-test/tests/baseline/bug847425.js
JavaScript
mpl-2.0
294
import Analyzer from 'parser/core/Analyzer'; import RESOURCE_TYPES from 'game/RESOURCE_TYPES'; class Insanity extends Analyzer { _insanityEvents = []; on_toPlayer_energize(event) { if (event.resourceChangeType === RESOURCE_TYPES.INSANITY.id) { this._insanityEvents = [ ...this._insanityEvents, event, ]; } } get events() { return this._insanityEvents; } } export default Insanity;
ronaldpereira/WoWAnalyzer
src/parser/priest/shadow/modules/core/Insanity.js
JavaScript
agpl-3.0
435
Clazz.declarePackage ("org.jmol.shapespecial"); Clazz.load (["org.jmol.shape.AtomShape", "org.jmol.atomdata.RadiusData", "org.jmol.util.BitSet"], "org.jmol.shapespecial.Dots", ["java.util.Hashtable", "org.jmol.constant.EnumVdw", "org.jmol.geodesic.EnvelopeCalculation", "org.jmol.util.BitSetUtil", "$.Colix", "$.Escape", "$.Logger", "$.Matrix3f", "$.StringXBuilder"], function () { c$ = Clazz.decorateAsClass (function () { this.ec = null; this.isSurface = false; this.bsOn = null; this.bsSelected = null; this.bsIgnore = null; this.thisAtom = 0; this.thisRadius = 0; this.thisArgb = 0; this.rdLast = null; Clazz.instantialize (this, arguments); }, org.jmol.shapespecial, "Dots", org.jmol.shape.AtomShape); Clazz.prepareFields (c$, function () { this.bsOn = new org.jmol.util.BitSet (); this.rdLast = new org.jmol.atomdata.RadiusData (null, 0, null, null); }); Clazz.defineMethod (c$, "initShape", function () { Clazz.superCall (this, org.jmol.shapespecial.Dots, "initShape", []); this.translucentAllowed = false; this.ec = new org.jmol.geodesic.EnvelopeCalculation (this.viewer, this.atomCount, this.mads); }); Clazz.defineMethod (c$, "getSize", function (atomIndex) { return (this.mads == null ? Clazz.doubleToInt (Math.floor (this.ec.getRadius (atomIndex) * 2000)) : this.mads[atomIndex] * 2); }, "~N"); Clazz.defineMethod (c$, "setProperty", function (propertyName, value, bs) { if ("init" === propertyName) { this.initialize (); return; }if ("translucency" === propertyName) { if (!this.translucentAllowed) return; }if ("ignore" === propertyName) { this.bsIgnore = value; return; }if ("select" === propertyName) { this.bsSelected = value; return; }if ("radius" === propertyName) { this.thisRadius = (value).floatValue (); if (this.thisRadius > 16) this.thisRadius = 16; return; }if ("colorRGB" === propertyName) { this.thisArgb = (value).intValue (); return; }if ("atom" === propertyName) { this.thisAtom = (value).intValue (); if (this.thisAtom >= this.atoms.length) return; this.atoms[this.thisAtom].setShapeVisibility (this.myVisibilityFlag, true); this.ec.allocDotsConvexMaps (this.atomCount); return; }if ("dots" === propertyName) { if (this.thisAtom >= this.atoms.length) return; this.isActive = true; this.ec.setFromBits (this.thisAtom, value); this.atoms[this.thisAtom].setShapeVisibility (this.myVisibilityFlag, true); if (this.mads == null) { this.ec.setMads (null); this.mads = Clazz.newShortArray (this.atomCount, 0); for (var i = 0; i < this.atomCount; i++) if (this.atoms[i].isInFrame () && this.atoms[i].isShapeVisible (this.myVisibilityFlag)) try { this.mads[i] = Clazz.floatToShort (this.ec.getAppropriateRadius (i) * 1000); } catch (e) { if (Clazz.exceptionOf (e, Exception)) { } else { throw e; } } this.ec.setMads (this.mads); }this.mads[this.thisAtom] = Clazz.floatToShort (this.thisRadius * 1000); if (this.colixes == null) { this.colixes = Clazz.newShortArray (this.atomCount, 0); this.paletteIDs = Clazz.newByteArray (this.atomCount, 0); }this.colixes[this.thisAtom] = org.jmol.util.Colix.getColix (this.thisArgb); this.bsOn.set (this.thisAtom); return; }if ("refreshTrajectories" === propertyName) { bs = (value)[1]; var m4 = (value)[2]; if (m4 == null) return; var m = new org.jmol.util.Matrix3f (); m4.getRotationScale (m); this.ec.reCalculate (bs, m); return; }if (propertyName === "deleteModelAtoms") { var firstAtomDeleted = ((value)[2])[1]; var nAtomsDeleted = ((value)[2])[2]; org.jmol.util.BitSetUtil.deleteBits (this.bsOn, bs); this.ec.deleteAtoms (firstAtomDeleted, nAtomsDeleted); }Clazz.superCall (this, org.jmol.shapespecial.Dots, "setProperty", [propertyName, value, bs]); }, "~S,~O,org.jmol.util.BitSet"); Clazz.defineMethod (c$, "initialize", function () { this.bsSelected = null; this.bsIgnore = null; this.isActive = false; if (this.ec == null) this.ec = new org.jmol.geodesic.EnvelopeCalculation (this.viewer, this.atomCount, this.mads); }); Clazz.overrideMethod (c$, "setSizeRD", function (rd, bsSelected) { if (rd == null) rd = new org.jmol.atomdata.RadiusData (null, 0, org.jmol.atomdata.RadiusData.EnumType.ABSOLUTE, null); if (this.bsSelected != null) bsSelected = this.bsSelected; if (org.jmol.util.Logger.debugging) { org.jmol.util.Logger.debug ("Dots.setSize " + rd.value); }var isVisible = true; var setRadius = 3.4028235E38; this.isActive = true; switch (rd.factorType) { case org.jmol.atomdata.RadiusData.EnumType.OFFSET: break; case org.jmol.atomdata.RadiusData.EnumType.ABSOLUTE: if (rd.value == 0) isVisible = false; setRadius = rd.value; default: rd.valueExtended = this.viewer.getCurrentSolventProbeRadius (); } var maxRadius; switch (rd.vdwType) { case org.jmol.constant.EnumVdw.ADPMIN: case org.jmol.constant.EnumVdw.ADPMAX: case org.jmol.constant.EnumVdw.HYDRO: case org.jmol.constant.EnumVdw.TEMP: maxRadius = setRadius; break; case org.jmol.constant.EnumVdw.IONIC: maxRadius = this.modelSet.getMaxVanderwaalsRadius () * 2; break; default: maxRadius = this.modelSet.getMaxVanderwaalsRadius (); } var newSet = (this.rdLast.value != rd.value || this.rdLast.valueExtended != rd.valueExtended || this.rdLast.factorType !== rd.factorType || this.rdLast.vdwType !== rd.vdwType || this.ec.getDotsConvexMax () == 0); if (isVisible) { for (var i = bsSelected.nextSetBit (0); i >= 0; i = bsSelected.nextSetBit (i + 1)) if (!this.bsOn.get (i)) { this.bsOn.set (i); newSet = true; } } else { var isAll = (bsSelected == null); var i0 = (isAll ? this.atomCount - 1 : bsSelected.nextSetBit (0)); for (var i = i0; i >= 0; i = (isAll ? i - 1 : bsSelected.nextSetBit (i + 1))) this.bsOn.setBitTo (i, false); }for (var i = this.atomCount; --i >= 0; ) { this.atoms[i].setShapeVisibility (this.myVisibilityFlag, this.bsOn.get (i)); } if (!isVisible) return; if (newSet) { this.mads = null; this.ec.newSet (); }var dotsConvexMaps = this.ec.getDotsConvexMaps (); if (dotsConvexMaps != null) { for (var i = this.atomCount; --i >= 0; ) if (this.bsOn.get (i)) { dotsConvexMaps[i] = null; } }if (dotsConvexMaps == null) { this.colixes = Clazz.newShortArray (this.atomCount, 0); this.paletteIDs = Clazz.newByteArray (this.atomCount, 0); }this.ec.calculate (rd, maxRadius, this.bsOn, this.bsIgnore, !this.viewer.getDotSurfaceFlag (), this.viewer.getDotsSelectedOnlyFlag (), this.isSurface, true); this.rdLast = rd; }, "org.jmol.atomdata.RadiusData,org.jmol.util.BitSet"); Clazz.overrideMethod (c$, "setModelClickability", function () { for (var i = this.atomCount; --i >= 0; ) { var atom = this.atoms[i]; if ((atom.getShapeVisibilityFlags () & this.myVisibilityFlag) == 0 || this.modelSet.isAtomHidden (i)) continue; atom.setClickable (this.myVisibilityFlag); } }); Clazz.overrideMethod (c$, "getShapeState", function () { var dotsConvexMaps = this.ec.getDotsConvexMaps (); if (dotsConvexMaps == null || this.ec.getDotsConvexMax () == 0) return ""; var s = new org.jmol.util.StringXBuilder (); var temp = new java.util.Hashtable (); var atomCount = this.viewer.getAtomCount (); var type = (this.isSurface ? "geoSurface " : "dots "); for (var i = 0; i < atomCount; i++) { if (!this.bsOn.get (i) || dotsConvexMaps[i] == null) continue; if (this.bsColixSet != null && this.bsColixSet.get (i)) org.jmol.shape.Shape.setStateInfo (temp, i, this.getColorCommand (type, this.paletteIDs[i], this.colixes[i])); var bs = dotsConvexMaps[i]; if (!bs.isEmpty ()) { var r = this.ec.getAppropriateRadius (i); org.jmol.shape.Shape.appendCmd (s, type + i + " radius " + r + " " + org.jmol.util.Escape.escape (bs)); }} s.append (org.jmol.shape.Shape.getShapeCommands (temp, null)); return s.toString (); }); Clazz.defineStatics (c$, "SURFACE_DISTANCE_FOR_CALCULATION", 10, "MAX_LEVEL", 3); });
ksripathi/edx-demo-course
static/jsmol/j2s/org/jmol/shapespecial/Dots.js
JavaScript
agpl-3.0
7,637
/* * * * (c) 2010-2020 Torstein Honsi * * License: www.highcharts.com/license * * !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!! * * */ 'use strict'; import H from './Globals.js'; import Point from './Point.js'; import U from './Utilities.js'; var seriesType = U.seriesType; var seriesTypes = H.seriesTypes; /** * The ohlc series type. * * @private * @class * @name Highcharts.seriesTypes.ohlc * * @augments Highcharts.Series */ seriesType('ohlc', 'column' /** * An OHLC chart is a style of financial chart used to describe price * movements over time. It displays open, high, low and close values per * data point. * * @sample stock/demo/ohlc/ * OHLC chart * * @extends plotOptions.column * @excluding borderColor, borderRadius, borderWidth, crisp, stacking, * stack * @product highstock * @optionparent plotOptions.ohlc */ , { /** * The approximate pixel width of each group. If for example a series * with 30 points is displayed over a 600 pixel wide plot area, no * grouping is performed. If however the series contains so many points * that the spacing is less than the groupPixelWidth, Highcharts will * try to group it into appropriate groups so that each is more or less * two pixels wide. Defaults to `5`. * * @type {number} * @default 5 * @product highstock * @apioption plotOptions.ohlc.dataGrouping.groupPixelWidth */ /** * The pixel width of the line/border. Defaults to `1`. * * @sample {highstock} stock/plotoptions/ohlc-linewidth/ * A greater line width * * @type {number} * @default 1 * @product highstock * * @private */ lineWidth: 1, tooltip: { pointFormat: '<span style="color:{point.color}">\u25CF</span> ' + '<b> {series.name}</b><br/>' + 'Open: {point.open}<br/>' + 'High: {point.high}<br/>' + 'Low: {point.low}<br/>' + 'Close: {point.close}<br/>' }, threshold: null, states: { /** * @extends plotOptions.column.states.hover * @product highstock */ hover: { /** * The pixel width of the line representing the OHLC point. * * @type {number} * @default 3 * @product highstock */ lineWidth: 3 } }, /** * Determines which one of `open`, `high`, `low`, `close` values should * be represented as `point.y`, which is later used to set dataLabel * position and [compare](#plotOptions.series.compare). * * @sample {highstock} stock/plotoptions/ohlc-pointvalkey/ * Possible values * * @type {string} * @default close * @validvalue ["open", "high", "low", "close"] * @product highstock * @apioption plotOptions.ohlc.pointValKey */ /** * @default close * @apioption plotOptions.ohlc.colorKey */ /** * Line color for up points. * * @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject} * @product highstock * @apioption plotOptions.ohlc.upColor */ stickyTracking: true }, /** * @lends Highcharts.seriesTypes.ohlc */ { /* eslint-disable valid-jsdoc */ directTouch: false, pointArrayMap: ['open', 'high', 'low', 'close'], toYData: function (point) { // return a plain array for speedy calculation return [point.open, point.high, point.low, point.close]; }, pointValKey: 'close', pointAttrToOptions: { stroke: 'color', 'stroke-width': 'lineWidth' }, /** * @private * @function Highcarts.seriesTypes.ohlc#init * @return {void} */ init: function () { seriesTypes.column.prototype.init.apply(this, arguments); this.options.stacking = void 0; // #8817 }, /** * Postprocess mapping between options and SVG attributes * * @private * @function Highcharts.seriesTypes.ohlc#pointAttribs * @param {Highcharts.OHLCPoint} point * @param {string} state * @return {Highcharts.SVGAttributes} */ pointAttribs: function (point, state) { var attribs = seriesTypes.column.prototype.pointAttribs.call(this, point, state), options = this.options; delete attribs.fill; if (!point.options.color && options.upColor && point.open < point.close) { attribs.stroke = options.upColor; } return attribs; }, /** * Translate data points from raw values x and y to plotX and plotY * * @private * @function Highcharts.seriesTypes.ohlc#translate * @return {void} */ translate: function () { var series = this, yAxis = series.yAxis, hasModifyValue = !!series.modifyValue, translated = [ 'plotOpen', 'plotHigh', 'plotLow', 'plotClose', 'yBottom' ]; // translate OHLC for seriesTypes.column.prototype.translate.apply(series); // Do the translation series.points.forEach(function (point) { [point.open, point.high, point.low, point.close, point.low] .forEach(function (value, i) { if (value !== null) { if (hasModifyValue) { value = series.modifyValue(value); } point[translated[i]] = yAxis.toPixels(value, true); } }); // Align the tooltip to the high value to avoid covering the // point point.tooltipPos[1] = point.plotHigh + yAxis.pos - series.chart.plotTop; }); }, /** * Draw the data points * * @private * @function Highcharts.seriesTypes.ohlc#drawPoints * @return {void} */ drawPoints: function () { var series = this, points = series.points, chart = series.chart, /** * Extend vertical stem to open and close values. */ extendStem = function (path, halfStrokeWidth, openOrClose) { var start = path[0]; var end = path[1]; // We don't need to worry about crisp - openOrClose value // is already crisped and halfStrokeWidth should remove it. if (typeof start[2] === 'number') { start[2] = Math.max(openOrClose + halfStrokeWidth, start[2]); } if (typeof end[2] === 'number') { end[2] = Math.min(openOrClose - halfStrokeWidth, end[2]); } }; points.forEach(function (point) { var plotOpen, plotClose, crispCorr, halfWidth, path, graphic = point.graphic, crispX, isNew = !graphic, strokeWidth; if (typeof point.plotY !== 'undefined') { // Create and/or update the graphic if (!graphic) { point.graphic = graphic = chart.renderer.path() .add(series.group); } if (!chart.styledMode) { graphic.attr(series.pointAttribs(point, (point.selected && 'select'))); // #3897 } // crisp vector coordinates strokeWidth = graphic.strokeWidth(); crispCorr = (strokeWidth % 2) / 2; // #2596: crispX = Math.round(point.plotX) - crispCorr; halfWidth = Math.round(point.shapeArgs.width / 2); // the vertical stem path = [ ['M', crispX, Math.round(point.yBottom)], ['L', crispX, Math.round(point.plotHigh)] ]; // open if (point.open !== null) { plotOpen = Math.round(point.plotOpen) + crispCorr; path.push(['M', crispX, plotOpen], ['L', crispX - halfWidth, plotOpen]); extendStem(path, strokeWidth / 2, plotOpen); } // close if (point.close !== null) { plotClose = Math.round(point.plotClose) + crispCorr; path.push(['M', crispX, plotClose], ['L', crispX + halfWidth, plotClose]); extendStem(path, strokeWidth / 2, plotClose); } graphic[isNew ? 'attr' : 'animate']({ d: path }) .addClass(point.getClassName(), true); } }); }, animate: null // Disable animation /* eslint-enable valid-jsdoc */ }, /** * @lends Highcharts.seriesTypes.ohlc.prototype.pointClass.prototype */ { /* eslint-disable valid-jsdoc */ /** * Extend the parent method by adding up or down to the class name. * @private * @function Highcharts.seriesTypes.ohlc#getClassName * @return {string} */ getClassName: function () { return Point.prototype.getClassName.call(this) + (this.open < this.close ? ' highcharts-point-up' : ' highcharts-point-down'); } /* eslint-enable valid-jsdoc */ }); /** * A `ohlc` series. If the [type](#series.ohlc.type) option is not * specified, it is inherited from [chart.type](#chart.type). * * @extends series,plotOptions.ohlc * @excluding dataParser, dataURL * @product highstock * @apioption series.ohlc */ /** * An array of data points for the series. For the `ohlc` series type, * points can be given in the following ways: * * 1. An array of arrays with 5 or 4 values. In this case, the values correspond * to `x,open,high,low,close`. If the first value is a string, it is applied * as the name of the point, and the `x` value is inferred. The `x` value can * also be omitted, in which case the inner arrays should be of length 4\. * Then the `x` value is automatically calculated, either starting at 0 and * incremented by 1, or from `pointStart` and `pointInterval` given in the * series options. * ```js * data: [ * [0, 6, 5, 6, 7], * [1, 9, 4, 8, 2], * [2, 6, 3, 4, 10] * ] * ``` * * 2. An array of objects with named values. The following snippet shows only a * few settings, see the complete options set below. If the total number of * data points exceeds the series' * [turboThreshold](#series.ohlc.turboThreshold), this option is not * available. * ```js * data: [{ * x: 1, * open: 3, * high: 4, * low: 5, * close: 2, * name: "Point2", * color: "#00FF00" * }, { * x: 1, * open: 4, * high: 3, * low: 6, * close: 7, * name: "Point1", * color: "#FF00FF" * }] * ``` * * @type {Array<Array<(number|string),number,number,number>|Array<(number|string),number,number,number,number>|*>} * @extends series.arearange.data * @excluding y, marker * @product highstock * @apioption series.ohlc.data */ /** * The closing value of each data point. * * @type {number} * @product highstock * @apioption series.ohlc.data.close */ /** * The opening value of each data point. * * @type {number} * @product highstock * @apioption series.ohlc.data.open */ ''; // adds doclets above to transpilat
burki/jewish-history-online
web/vendor/highcharts/es-modules/parts/OHLCSeries.js
JavaScript
agpl-3.0
11,563
/*-------------------------------------------------------------------- Copyright (c) 2011 Local Projects. All rights reserved. Licensed under the Affero GNU GPL v3, see LICENSE for more details. --------------------------------------------------------------------*/ tc.gam.widgetVisibilityHandler = function(options) { var self = { currentHash: window.location.hash, previousHash: null }; self._setHash = function(hash) { if (hash === self.currentHash) { tc.jQ(window).trigger('hashchange'); } else { //This will trigger the 'hashchange' event because the hash is different window.location.hash = hash; } }; self._getHash = function() { return window.location.hash.substring(1, window.location.hash.length); }; self._goHome = function() { self._setHash('show,home'); }; self._triggerWidgetVisibilityEvent = function(action, widget, id) { tc.jQ(tc).trigger(action + '-project-widget', [widget, id]); }; self._onHashChange = function(event) { var action, widget; self.previousHash = self.currentHash; self.currentHash = self._getHash(); // For project-home hash, fire goHome. if (!self.currentHash || self.currentHash === 'project-home') { self._goHome(); } else { action = self.currentHash.split(',')[0]; widget = self.currentHash.split(',')[1]; id = self.currentHash.split(',')[2]; } tc.util.log('&&& hashchange: ' + action + ', ' + widget); self._triggerWidgetVisibilityEvent(action, widget, id); }; var bindEvents = function() { tc.jQ(window).bind('hashchange', self._onHashChange); }; var init = function() { bindEvents(); if (self.currentHash) { self._setHash(self.currentHash); } else { self._goHome(); } }; init(); return self; };
localprojects/Change-By-Us
static/js/tc.gam.widget-visibility-handler.js
JavaScript
agpl-3.0
2,065
{ "translatorID": "cd587058-6125-4b33-a876-8c6aae48b5e8", "label": "WHO", "creator": "Mario Trojan, Philipp Zumstein", "target": "^http://apps\\.who\\.int/iris/", "minVersion": "3.0", "maxVersion": "", "priority": 100, "inRepository": true, "translatorType": 4, "browserSupport": "gcsibv", "lastUpdated": "2018-09-02 14:34:27" } /* ***** BEGIN LICENSE BLOCK ***** Copyright © 2018 Mario Trojan This file is part of Zotero. Zotero is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Zotero is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Zotero. If not, see <http://www.gnu.org/licenses/>. ***** END LICENSE BLOCK ***** */ // attr()/text() v2 function attr(docOrElem,selector,attr,index){var elem=index?docOrElem.querySelectorAll(selector).item(index):docOrElem.querySelector(selector);return elem?elem.getAttribute(attr):null;} function text(docOrElem,selector,index){var elem=index?docOrElem.querySelectorAll(selector).item(index):docOrElem.querySelector(selector);return elem?elem.textContent:null;} function detectWeb(doc, url) { if (url.includes("/handle/") && text(doc, 'div.item-summary-view-metadata')) { var type = attr(doc, 'meta[name="DC.type"]', 'content'); //Z.debug(type); if (type && type.includes("articles")) { return "journalArticle"; } if (type && (type.includes("Book") || type.includes("Publications"))) { return "book"; } return "report"; } else if (getSearchResults(doc, true)) { return "multiple"; } } function getSearchResults(doc, checkOnly) { var items = {}; var found = false; var rows = doc.querySelectorAll('h4.artifact-title>a'); for (let i=0; i<rows.length; i++) { let href = rows[i].href; var title = rows[i].textContent; if (!href || !title) continue; if (checkOnly) return true; found = true; items[href] = title; } return found ? items : false; } function doWeb(doc, url) { if (detectWeb(doc, url) == "multiple") { Zotero.selectItems(getSearchResults(doc, false), function (items) { if (!items) { return true; } var articles = []; for (var i in items) { articles.push(i); } ZU.processDocuments(articles, scrape); }); } else { scrape(doc, url); } } function scrape(doc, url) { // copy meta tags in body to head var head = doc.getElementsByTagName('head'); var metasInBody = ZU.xpath(doc, '//body/meta'); for (let meta of metasInBody) { head[0].append(meta); } var type = detectWeb(doc, url); var translator = Zotero.loadTranslator('web'); // Embedded Metadata translator.setTranslator('951c027d-74ac-47d4-a107-9c3069ab7b48'); translator.setHandler('itemDone', function (obj, item) { if (item.publisher && !item.place && item.publisher.includes(' : ')) { let placePublisher = item.publisher.split(' : '); item.place = placePublisher[0]; item.publisher = placePublisher[1]; } var firstAuthor = attr(doc, 'meta[name="DC.creator"]', 'content'); if (firstAuthor && !firstAuthor.includes(',')) { item.creators[0] = { "lastName": firstAuthor, "creatorType": "author", "fieldMode": true }; } var descriptions = doc.querySelectorAll('meta[name="DC.description"]'); // DC.description doesn't actually contain other useful content, // except possibly the number of pages for (let description of descriptions) { var numPages = description.content.match(/(([lxiv]+,\s*)?\d+)\s*p/); if (numPages) { if (ZU.fieldIsValidForType("numPages", item.itemType)) { item.numPages = numPages[1]; } else if (!item.extra) { item.extra = "number-of-pages: " + numPages[1]; } else { item.extra += "\nnumber-of-pages: " + numPages[1]; } delete item.abstractNote; } } item.complete(); }); translator.getTranslatorObject(function(trans) { trans.itemType = type; trans.doWeb(doc, url); }); } /** BEGIN TEST CASES **/ var testCases = [ { "type": "web", "url": "http://apps.who.int/iris/handle/10665/70863?locale=ar", "items": [ { "itemType": "report", "title": "Consensus document on the epidemiology of severe acute respiratory syndrome (SARS)", "creators": [ { "lastName": "World Health Organization", "creatorType": "author", "fieldMode": true } ], "date": "2003", "extra": "number-of-pages: 46", "institution": "World Health Organization", "language": "en", "libraryCatalog": "apps.who.int", "place": "Geneva", "reportNumber": "WHO/CDS/CSR/GAR/2003.11", "url": "http://apps.who.int/iris/handle/10665/70863", "attachments": [ { "title": "Full Text PDF", "mimeType": "application/pdf" }, { "title": "Snapshot" } ], "tags": [ { "tag": "Communicable Diseases and their Control" }, { "tag": "Disease outbreaks" }, { "tag": "Epidemiologic surveillance" }, { "tag": "Severe acute respiratory syndrome" } ], "notes": [], "seeAlso": [] } ] }, { "type": "web", "url": "http://apps.who.int/iris/handle/10665/272081", "items": [ { "itemType": "journalArticle", "title": "Providing oxygen to children in hospitals: a realist review", "creators": [ { "firstName": "Hamish", "lastName": "Graham", "creatorType": "author" }, { "firstName": "Shidan", "lastName": "Tosif", "creatorType": "author" }, { "firstName": "Amy", "lastName": "Gray", "creatorType": "author" }, { "firstName": "Shamim", "lastName": "Qazi", "creatorType": "author" }, { "firstName": "Harry", "lastName": "Campbell", "creatorType": "author" }, { "firstName": "David", "lastName": "Peel", "creatorType": "author" }, { "firstName": "Barbara", "lastName": "McPake", "creatorType": "author" }, { "firstName": "Trevor", "lastName": "Duke", "creatorType": "author" } ], "date": "2017-4-01", "DOI": "10.2471/BLT.16.186676", "ISSN": "0042-9686", "abstractNote": "288", "extra": "PMID: 28479624", "issue": "4", "language": "en", "libraryCatalog": "apps.who.int", "pages": "288-302", "publicationTitle": "Bulletin of the World Health Organization", "rights": "http://creativecommons.org/licenses/by/3.0/igo/legalcode", "shortTitle": "Providing oxygen to children in hospitals", "url": "http://apps.who.int/iris/handle/10665/272081", "volume": "95", "attachments": [ { "title": "Full Text PDF", "mimeType": "application/pdf" }, { "title": "Snapshot" }, { "title": "PubMed entry", "mimeType": "text/html", "snapshot": false } ], "tags": [ { "tag": "Systematic Reviews" } ], "notes": [], "seeAlso": [] } ] }, { "type": "web", "url": "http://apps.who.int/iris/handle/10665/273678", "items": [ { "itemType": "book", "title": "Сборник руководящих принципов и стандартов ВОЗ: обеспечение оптимального оказания медицинских услуг пациентам с туберкулезом", "creators": [ { "lastName": "Всемирная организация здравоохранения", "creatorType": "author", "fieldMode": true } ], "date": "2018", "ISBN": "9789244514108", "language": "ru", "libraryCatalog": "apps.who.int", "numPages": "47", "publisher": "Всемирная организация здравоохранения", "rights": "CC BY-NC-SA 3.0 IGO", "shortTitle": "Сборник руководящих принципов и стандартов ВОЗ", "url": "http://apps.who.int/iris/handle/10665/273678", "attachments": [ { "title": "Full Text PDF", "mimeType": "application/pdf" }, { "title": "Snapshot" } ], "tags": [ { "tag": "Delivery of Health Care" }, { "tag": "Disease Management" }, { "tag": "Guideline" }, { "tag": "Infection Control" }, { "tag": "Multidrug-Resistant" }, { "tag": "Patient Care" }, { "tag": "Reference Standards" }, { "tag": "Tuberculosis" } ], "notes": [], "seeAlso": [] } ] }, { "type": "web", "url": "http://apps.who.int/iris/handle/10665/165097", "items": "multiple" }, { "type": "web", "url": "http://apps.who.int/iris/discover?query=acupuncture", "items": "multiple" } ]; /** END TEST CASES **/
ZotPlus/zotero-better-bibtex
test/fixtures/profile/zotero/zotero/translators/WHO.js
JavaScript
unlicense
9,219
'use strict'; angular.module('mgcrea.ngStrap.typeahead', ['mgcrea.ngStrap.tooltip', 'mgcrea.ngStrap.helpers.parseOptions']) .provider('$typeahead', function() { var defaults = this.defaults = { animation: 'am-fade', prefixClass: 'typeahead', prefixEvent: '$typeahead', placement: 'bottom-left', template: 'typeahead/typeahead.tpl.html', trigger: 'focus', container: false, keyboard: true, html: false, delay: 0, minLength: 1, filter: 'filter', limit: 6 }; this.$get = function($window, $rootScope, $tooltip) { var bodyEl = angular.element($window.document.body); function TypeaheadFactory(element, controller, config) { var $typeahead = {}; // Common vars var options = angular.extend({}, defaults, config); $typeahead = $tooltip(element, options); var parentScope = config.scope; var scope = $typeahead.$scope; scope.$resetMatches = function(){ scope.$matches = []; scope.$activeIndex = 0; }; scope.$resetMatches(); scope.$activate = function(index) { scope.$$postDigest(function() { $typeahead.activate(index); }); }; scope.$select = function(index, evt) { scope.$$postDigest(function() { $typeahead.select(index); }); }; scope.$isVisible = function() { return $typeahead.$isVisible(); }; // Public methods $typeahead.update = function(matches) { scope.$matches = matches; if(scope.$activeIndex >= matches.length) { scope.$activeIndex = 0; } }; $typeahead.activate = function(index) { scope.$activeIndex = index; }; $typeahead.select = function(index) { var value = scope.$matches[index].value; controller.$setViewValue(value); controller.$render(); scope.$resetMatches(); if(parentScope) parentScope.$digest(); // Emit event scope.$emit(options.prefixEvent + '.select', value, index); }; // Protected methods $typeahead.$isVisible = function() { if(!options.minLength || !controller) { return !!scope.$matches.length; } // minLength support return scope.$matches.length && angular.isString(controller.$viewValue) && controller.$viewValue.length >= options.minLength; }; $typeahead.$getIndex = function(value) { var l = scope.$matches.length, i = l; if(!l) return; for(i = l; i--;) { if(scope.$matches[i].value === value) break; } if(i < 0) return; return i; }; $typeahead.$onMouseDown = function(evt) { // Prevent blur on mousedown evt.preventDefault(); evt.stopPropagation(); }; $typeahead.$onKeyDown = function(evt) { if(!/(38|40|13)/.test(evt.keyCode)) return; // Let ngSubmit pass if the typeahead tip is hidden if($typeahead.$isVisible()) { evt.preventDefault(); evt.stopPropagation(); } // Select with enter if(evt.keyCode === 13 && scope.$matches.length) { $typeahead.select(scope.$activeIndex); } // Navigate with keyboard else if(evt.keyCode === 38 && scope.$activeIndex > 0) scope.$activeIndex--; else if(evt.keyCode === 40 && scope.$activeIndex < scope.$matches.length - 1) scope.$activeIndex++; else if(angular.isUndefined(scope.$activeIndex)) scope.$activeIndex = 0; scope.$digest(); }; // Overrides var show = $typeahead.show; $typeahead.show = function() { show(); setTimeout(function() { $typeahead.$element.on('mousedown', $typeahead.$onMouseDown); if(options.keyboard) { element.on('keydown', $typeahead.$onKeyDown); } }); }; var hide = $typeahead.hide; $typeahead.hide = function() { $typeahead.$element.off('mousedown', $typeahead.$onMouseDown); if(options.keyboard) { element.off('keydown', $typeahead.$onKeyDown); } hide(); }; return $typeahead; } TypeaheadFactory.defaults = defaults; return TypeaheadFactory; }; }) .directive('bsTypeahead', function($window, $parse, $q, $typeahead, $parseOptions) { var defaults = $typeahead.defaults; return { restrict: 'EAC', require: 'ngModel', link: function postLink(scope, element, attr, controller) { // Directive options var options = {scope: scope}; angular.forEach(['placement', 'container', 'delay', 'trigger', 'keyboard', 'html', 'animation', 'template', 'filter', 'limit', 'minLength', 'watchOptions', 'selectMode'], function(key) { if(angular.isDefined(attr[key])) options[key] = attr[key]; }); // Build proper ngOptions var filter = options.filter || defaults.filter; var limit = options.limit || defaults.limit; var ngOptions = attr.ngOptions; if(filter) ngOptions += ' | ' + filter + ':$viewValue'; if(limit) ngOptions += ' | limitTo:' + limit; var parsedOptions = $parseOptions(ngOptions); // Initialize typeahead var typeahead = $typeahead(element, controller, options); // Watch options on demand if(options.watchOptions) { // Watch ngOptions values before filtering for changes, drop function calls var watchedOptions = parsedOptions.$match[7].replace(/\|.+/, '').replace(/\(.*\)/g, '').trim(); scope.$watch(watchedOptions, function (newValue, oldValue) { // console.warn('scope.$watch(%s)', watchedOptions, newValue, oldValue); parsedOptions.valuesFn(scope, controller).then(function (values) { typeahead.update(values); controller.$render(); }); }, true); } // Watch model for changes scope.$watch(attr.ngModel, function(newValue, oldValue) { // console.warn('$watch', element.attr('ng-model'), newValue); scope.$modelValue = newValue; // Publish modelValue on scope for custom templates parsedOptions.valuesFn(scope, controller) .then(function(values) { // Prevent input with no future prospect if selectMode is truthy // @TODO test selectMode if(options.selectMode && !values.length && newValue.length > 0) { controller.$setViewValue(controller.$viewValue.substring(0, controller.$viewValue.length - 1)); return; } if(values.length > limit) values = values.slice(0, limit); var isVisible = typeahead.$isVisible(); isVisible && typeahead.update(values); // Do not re-queue an update if a correct value has been selected if(values.length === 1 && values[0].value === newValue) return; !isVisible && typeahead.update(values); // Queue a new rendering that will leverage collection loading controller.$render(); }); }); // Model rendering in view controller.$render = function () { // console.warn('$render', element.attr('ng-model'), 'controller.$modelValue', typeof controller.$modelValue, controller.$modelValue, 'controller.$viewValue', typeof controller.$viewValue, controller.$viewValue); if(controller.$isEmpty(controller.$viewValue)) return element.val(''); var index = typeahead.$getIndex(controller.$modelValue); var selected = angular.isDefined(index) ? typeahead.$scope.$matches[index].label : controller.$viewValue; selected = angular.isObject(selected) ? selected.label : selected; element.val(selected.replace(/<(?:.|\n)*?>/gm, '').trim()); }; // Garbage collection scope.$on('$destroy', function() { if (typeahead) typeahead.destroy(); options = null; typeahead = null; }); } }; });
anirvann/testApp
vendor/angular-strap/src/typeahead/typeahead.js
JavaScript
unlicense
8,390
///<reference path="app.js" /> define(['Dexie', 'Dexie.Observable', './console'], function (Dexie, DexieObservable, console) { // Declare Dexie instance and explicitely apply the addon: var db = new Dexie("appdb2", { addons: [DexieObservable] }); // Define database schema db.version(1).stores({ contacts: '++id,first,last' }); // Populate ground data db.on('populate', function () { console.log("Populating data first time"); // Populate a contact db.contacts.add({ first: 'Arnold', last: 'Fitzgerald' }); }); // Open database db.open(); return db; });
YuriSolovyov/Dexie.js
samples/requirejs-with-addons/scripts/db.js
JavaScript
apache-2.0
643
/*! * Copyright 2014 Apereo Foundation (AF) Licensed under the * Educational Community License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may * obtain a copy of the License at * * http://opensource.org/licenses/ECL-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an "AS IS" * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing * permissions and limitations under the License. */ define(['jquery', 'oae.core'], function ($, oae) { return function (uid) { // The widget container var $rootel = $('#' + uid); // Holds the current state of the user profile as it is updated var profile = _.extend({}, oae.data.me); // Holds an email address that is pending verification from the user, if // applicable var unverifiedEmail = null; /** * Determine if the current profile has a valid display name * * @return {Boolean} Whether or not the profile has a valid display name */ var isValidDisplayName = function() { return oae.api.util.validation().isValidDisplayName(profile.displayName); }; /** * Determine if the current profile has a valid email * * @return {Boolean} Whether or not the profile has a valid email */ var isValidEmail = function() { return oae.api.util.validation().isValidEmail(profile.email); }; /** * Determine if the current profile is valid, such that it would allow a user to dismiss the * user profile modal * * @return {Boolean} Whether or not the profile is valid in its current state */ var isValidProfile = function() { return (isValidEmail() && isValidDisplayName()); }; /** * Show the main panel */ var showMainPanel = function() { $('#editprofile-panel-email-container').hide(); $('#editprofile-panel-main-container').show(); }; /** * Show the email panel */ var showEmailPanel = function() { $('#editprofile-panel-main-container').hide(); $('#editprofile-panel-email-container').show(); }; /** * Show the appropriate panel based on the user's profile state */ var showDefaultPanel = function() { // Initialize the email verification status oae.api.user.getEmailVerificationStatus(oae.data.me.id, function(err, email) { // Ignore issues checking for a pending email verification, as there being no // pending verification is the 99.999% use-case and we wouldn't want to annoy // uninterested users with an error notification or anything unverifiedEmail = email; if (isValidDisplayName() && !isValidEmail() && unverifiedEmail) { // If the user profile is awaiting a verified email, but all // the other information is accurate, we take them directly // to the panel that indicates they need to verify their // email renderEditProfileEmailPanel(); } else { renderEditProfileMainPanel(); } }); }; /** * Render the edit profile "main" panel with validation and switch the current modal view to * the "main" panel */ var renderEditProfileMainPanel = function() { // If the display name is not valid, clear it to inform the template that the user // has no real display name if (!isValidDisplayName()) { profile.displayName = null; // Profiles with invalid display names will have had visibility set to private, so we // reset it to the tenant's default visibility // @see https://github.com/oaeproject/3akai-ux/pull/4100 var tenantVisibility = oae.api.config.getValue('oae-principals', 'user', 'visibility'); profile.visibility = tenantVisibility; } // Render the form elements oae.api.util.template().render($('#editprofile-panel-main-template', $rootel), { 'isValidProfile': isValidProfile(), 'profile': profile, 'unverifiedEmail': unverifiedEmail }, $('#editprofile-panel-main-container', $rootel)); // Detect changes in the form and enable the submit button $('#editprofile-form', $rootel).on(oae.api.util.getFormChangeEventNames(), function() { $('#editprofile-panel-main-container button[type="submit"]', $rootel).prop('disabled', false); }); // Initialize jQuery validate on the form var validateOpts = { 'submitHandler': editProfile, 'methods': { 'displayname': { 'method': oae.api.util.validation().isValidDisplayName, 'text': oae.api.i18n.translate('__MSG__PLEASE_ENTER_A_VALID_NAME__') } } }; oae.api.util.validation().validate($('#editprofile-form', $rootel), validateOpts); // Switch the view to the main panel showMainPanel(); }; /** * Render the edit profile "email" panel that instructs the user how to proceed with * verifying their email. It will also switch the view to the "email" panel. */ var renderEditProfileEmailPanel = function() { // Render the email verification instruction template oae.api.util.template().render($('#editprofile-panel-email-template', $rootel), { 'isValidProfile': isValidProfile(), 'profile': profile, 'unverifiedEmail': unverifiedEmail }, $('#editprofile-panel-email-container', $rootel)); // Switch the view to the email panel showEmailPanel(); }; /** * Perform the edit profile action */ var editProfile = function() { // Disable the form $('#editprofile-form *', $rootel).prop('disabled', true); var newDisplayName = $.trim($('#editprofile-name', $rootel).val()); var newEmail = $.trim($('#editprofile-email', $rootel).val()).toLowerCase(); var newVisibility = $('.oae-large-options-container input[type="radio"]:checked', $rootel).val(); var params = { 'displayName': newDisplayName, 'email': newEmail, 'visibility': newVisibility }; // Determine if this update constitutes a change in email. If so we will need to notify // the user that the new email is pending verification var isEmailChange = (newEmail !== oae.data.me.email); oae.api.user.updateUser(params, function (err, data) { if (!err) { // Update the user profile in state profile = data; // Notify the rest of the UI widgets that the profile has been updated $(document).trigger('oae.editprofile.done', data); if (!isEmailChange) { // If the update succeeded and didn't have an email change, close the modal // while showing a notification closeModal(); oae.api.util.notification( oae.api.i18n.translate('__MSG__PROFILE_EDITED__'), oae.api.i18n.translate('__MSG__PROFILE_DETAILS_EDIT_SUCCESS__', 'editprofile')); } else { // Since the email is updated, a verification email will be sent. We should // tell the user that they must validate their email address from their // email inbox unverifiedEmail = newEmail; renderEditProfileEmailPanel(); } } else { // If the update failed, enable the form and show an error notification oae.api.util.notification( oae.api.i18n.translate('__MSG__PROFILE_NOT_EDITED__'), oae.api.i18n.translate('__MSG__PROFILE_DETAILS_EDIT_FAIL__', 'editprofile'), 'error'); // Enable the form $('#editprofile-form *', $rootel).prop('disabled', false); } }); // Avoid default form submit behavior return false; }; /** * Reset the widget to its original state when the modal dialog is opened and closed. * Ideally this would only be necessary when the modal is hidden, but IE10+ fires `input` * events while Bootstrap is rendering the modal, and those events can "undo" parts of the * reset. Hooking into the `shown` event provides the chance to compensate. */ var setUpReset = function() { $('#editprofile-modal', $rootel).on('shown.bs.modal', showDefaultPanel); $('#editprofile-modal', $rootel).on('hidden.bs.modal', function (evt) { // Reset the form var $form = $('#editprofile-form', $rootel); $form[0].reset(); oae.api.util.validation().clear($form); // Enable the form $('#editprofile-form *', $rootel).prop('disabled', false); $('#editprofile-form button[type="submit"]', $rootel).prop('disabled', true); showMainPanel(); }); }; /** * Apply the listeners to the document that will launch the editprofile modal */ var setUpModalListeners = function() { $(document).on('click', '.oae-trigger-editprofile', showModal); $(document).on('oae.trigger.editprofile', showModal); }; /** * Show the edit profile modal and render the appropriate panel */ var showModal = function() { $('#editprofile-modal', $rootel).modal({ 'backdrop': 'static' }); showDefaultPanel(); }; /** * Close the edit profile modal */ var closeModal = function() { $('#editprofile-modal', $rootel).modal('hide'); if (oae.data.me.needsToAcceptTC) { // It is possible that we entered the edit profile modal to // clean up our user profile before accepting the terms and // conditions (see `oae.api.js` function `setupPreUseActions`). // Therefore we need to ensure we segue to the terms and // conditions widget after we close the editprofile modal oae.api.widget.insertWidget('termsandconditions', null, null, true); } }; /** * Bind all the action listeners needed for the user to interact with the "main" panel in * the edit profile modal */ var bindEditProfileMainPanelListeners = function() { $('#editprofile-modal', $rootel).on('shown.bs.modal', function() { // Set focus to the display name field $('#editprofile-name', $rootel).focus(); }); // Catch changes in the visibility radio group $rootel.on('change', '#editprofile-panel-main-container .oae-large-options-container input[type="radio"]', function() { $('.oae-large-options-container label', $rootel).removeClass('checked'); $(this).parents('label').addClass('checked'); }); // When the "Resend Verification" button is clicked, resend the email verification $rootel.on('click', '#editprofile-email-verification .editprofile-email-verification-action button', function() { // Disable all actions in the modal $('#editprofile-form *', $rootel).prop('disabled', true); oae.api.user.resendEmailToken(oae.data.me.id, function(err) { if (!err) { // If the token resent successfully show a notification oae.api.util.notification( oae.api.i18n.translate('__MSG__VERIFICATION_EMAIL_SENT__', 'editprofile'), oae.api.i18n.translate('__MSG__A_VERIFICATION_EMAIL_HAS_BEEN_SENT_TO_UNVERIFIED_EMAIL__', 'editprofile', { 'unverifiedEmail': unverifiedEmail })); } else { // If the token failed to resend, show a notification oae.api.util.notification( oae.api.i18n.translate('__MSG__VERIFICATION_EMAIL_FAILED__', 'editprofile'), oae.api.i18n.translate('__MSG__A_VERIFICATION_EMAIL_FAILED_TO_BE_SENT_TO_UNVERIFIED_EMAIL__', 'editprofile', { 'unverifiedEmail': unverifiedEmail }), 'error'); } // Re-enable the form $('#editprofile-form *', $rootel).prop('disabled', false); }); }); // When the "Cancel Verification" button is clicked, delete the pending email verification // and close the container that indicates there is a pending verification $rootel.on('click', '#editprofile-email-verification .editprofile-email-verification-cancel button', function(evt) { // Allow the modal to be saved now $('#editprofile-panel-main-container button[type="submit"]', $rootel).prop('disabled', false); oae.api.user.deletePendingEmailVerification(function(err) { if (!err) { unverifiedEmail = null; // If cancelling succeeded, simply remove the email verification panel $('#editprofile-email-verification', $rootel).slideUp(); } else { // If the token failed to resend, show a notification oae.api.util.notification( oae.api.i18n.translate('__MSG__CANCEL_EMAIL_VERIFICATION_FAILED__', 'editprofile'), oae.api.i18n.translate('__MSG__AN_ERROR_OCCURRED_WHILE_CANCELLING_THE_EMAIL_VERIFICATION__', 'editprofile'), 'error'); } }); evt.preventDefault(); }); }; /** * Bind all the action listeners needed for the user to interact with the "email" panel in * the edit profile modal */ var bindEditProfileEmailPanelListeners = function() { // When "Done" is clicked, close the modal $rootel.on('click', '#editprofile-panel-email-container .modal-footer button.btn-primary', function() { closeModal(); }); // When the user chooses to go back, re-render and enable the main panel $rootel.on('click', '#editprofile-panel-email-container .modal-footer button.btn-link', function() { renderEditProfileMainPanel(); }); }; setUpReset(); setUpModalListeners(); bindEditProfileMainPanelListeners(); bindEditProfileEmailPanelListeners(); }; });
nicolaasmatthijs/3akai-ux
node_modules/oae-core/editprofile/js/editprofile.js
JavaScript
apache-2.0
16,154
if (!this["output"]) output = print; var passed = 0; var failed = 0; function is(got, expected, msg) { if (got == expected) { output("OK: " + msg); ++passed; } else { output("FAIL: " + msg); output("Expected |" + expected + "|"); output(" Got |" + got + "|"); ++failed; } } function complete() { output("\nTests Complete"); output("--------------"); output("Passed: " + passed); output("Failed: " + failed); output("\n"); } // // test our internal functions // function test_isObjectOrArray() { is(isObjectOrArray({}), true, "isObjectOrArray detects an object"); is(isObjectOrArray([]), true, "isObjectOrArray detects an array"); is(isObjectOrArray("foo"), false, "isObjectOrArray shouldn't detect string"); is(isObjectOrArray(4), false, "isObjectOrArray shouldn't detect integer"); is(isObjectOrArray(5.5), false, "isObjectOrArray shouldn't detect float"); is(isObjectOrArray(undefined), false, "isObjectOrArray shouldn't detect undefined"); is(isObjectOrArray(null), false, "isObjectOrArray shouldn't detect null"); } function test_identifySuspects() { var suspects = identifySuspects({"a": 1, "b": 2, "c": 3, "d": "hmm"}, {"a": 1, "b": 2, "c": 3, "d": "hmm"}); is(suspects.length, 0, "shouldn't be any suspects for matching primitives"); suspects = identifySuspects({"a": 1, "b": 2, "c": 3, "d": "hmm"}, {"a": 1, "b": 3, "c": 3, "d": "hmm"}); is(suspects.length, 1, "should detect edited primitives"); suspects = identifySuspects({"a": 1, "b": {}, "c": 3, "d": "hmm"}, {"a": 1, "b": {}, "c": 3, "d": "hmm"}); is(suspects.length, 1, "should detect matching objects"); suspects = identifySuspects({"a": 1, "b": 2, "c": 3, "d": "hmm"}, {"a": "1", "b": 2, "c": 3, "d": "hmm"}); is(suspects.length, 1, "should detect primitive type change"); suspects = identifySuspects({"a": 1, "b": 2, "c": 3, "d": "hmmm"}, {"a": 1, "b": 2, "c": 3, "d": "hmm"}); is(suspects.length, 1, "should detect string edit"); suspects = identifySuspects({"xxx": 1, "b": 2, "c": 3, "d": "hmm"}, {"yyy": 1, "b": 2, "c": 3, "d": "hmm"}); is(suspects.length, 2, "should detect differing keys"); suspects = identifySuspects({"0": 1, "b": 2, "c": 3, "d": "hmm"}, {0: 1, "b": 2, "c": 3, "d": "hmm"}); is(suspects.length, 0, "should not detect key type changes"); } function test_created() { var record = created(["foo"], {}); is(record.length, 1, "created empty object is length 1"); record = created(["foo"], 1); is(record.length, 1, "created primitive is length 1"); record = created(["foo"], {"bar":"baz"}); is(record.length, 2, "created populated object is length 2"); record = created(["foo"], {"bar":"baz", "qux":"baz"}); is(record.length, 3, "created populated object is length 3"); is(record[0].action, "create", "create action is correct"); is(record[0].path.length, 1, "creation paths in preorder"); is(record[1].path.length, 2, "creation paths in preorder"); is(record[1].value, "baz", "create has correct value"); is(record[2].path.length, 2, "creation paths in preorder"); is(record[2].value, "baz", "create has correct value"); } function test_removed() { var record = removed(["foo"], {}); is(record.length, 1, "removed empty object is length 1"); record = removed(["foo"], 1); is(record.length, 1, "removed primitive is length 1"); record = removed(["foo"], {"bar":"baz"}); is(record.length, 2, "removed populated object is length 2"); record = removed(["foo"], {"bar":"baz", "qux":"baz"}); is(record.length, 3, "removed populated object is length 3"); is(record[0].action, "remove", "remove action is correct"); is(record[0].path.length, 2, "removal paths in postorder"); is(record[1].path.length, 2, "removal paths in postorder"); is(record[2].path.length, 1, "removal paths in postorder"); } function test_edited() { var record = edited(["foo"], 5, 3); is(record.length, 1, "primitive edit is length 1"); is(record[0].action, "edit", "edit action is correct"); is(record[0].value, 3, "edit has correct value"); is(record[0].path.length, 1, "edit path is correct"); record = edited(["foo"], {"bar": "baz"}, 3); is(record.length, 2, "obj2primitive contains removals"); is(record[0].action, "edit", "edits precede removals"); is(record[1].action, "remove", "remove action is there"); record = edited(["foo"], 3, {"bar": "baz"}); is(record.length, 2, "primitive2object contains creations"); is(record[0].action, "edit", "edits precede creations"); is(record[1].action, "create", "create action is there"); }; // A snapshot, followed by four non-conflicting replicas var snap = { "foo": 1, "bar": 1, "baz": 1, "qux": 1 } var replica1 = { "foo": 0, "bar": 1, "baz": 1, "qux": 1 } var replica2 = { "foo": 1, "bar": 0, "baz": 1, "qux": 1 } var replica3 = { "foo": 1, "bar": 1, "baz": 0, "qux": 1 } var replica4 = { "foo": 1, "bar": 1, "baz": 1, "qux": 0 } function test_detectUpdates() { function checkReplica(name, replica) { var updateList = detectUpdates(snap, replica); is(updateList.length, 1, name + " has correct number of updates"); is(updateList[0].action, "edit", name + " should have an edit"); is(updateList[0].value, 0, name + " should have value 0"); } checkReplica("replica1", replica1); checkReplica("replica2", replica2); checkReplica("replica3", replica3); checkReplica("replica4", replica4); } function test_orderUpdates() { } function test_Command() { var x = new Command("edit", ["foo"], 5); var y = new Command("edit", ["foo"], 5); is(x instanceof Command, true, "instanceof"); is(x.equals(y), true, "equals method of Command works"); x.value = "5"; y.value = 5; is(x.equals(y), false, "equals method of Command detects type changes"); x.value = {}; y.value = {}; is(x.equals(y), true, "equals method of Command matches {} values"); x.value = []; y.value = []; is(x.equals(y), true, "equals method of Command matches [] values"); x.value = "5"; y.value = []; is(x.equals(y), false, "equals method of Command detects obj vs. primitive"); var z = new Command("edit", ["foo","bar"], 5); is(x.isParentOf(z), true, "check for parents"); } function test_commandInList() { var x = new Command("edit", ["foo"], 5); var y = new Command("remove", ["bar"]); var commandList = [new Command("edit", ["foo"], 5), new Command("remove", ["bar"])]; is(commandInList(x, commandList), true, "commandInList matches identical"); is(commandInList(y, commandList), true, "commandInList matches removes"); is(commandInList(new Command("edit", ["foo"], "bar"), [new Command("edit", ["foo"], "bar")]), true, "edits match"); is(commandInList(new Command("edit", ["foo"], 6), commandList), false, "commandInList fails differing values"); } function test_doesConflict() { var x = new Command("edit", ["foo"], 1); var y = new Command("edit", ["foo"], 2); is(doesConflict(x, y), true, "doesConflict finds identical paths with different values"); y.path = ["bar"]; is(doesConflict(x, y), false, "doesConflict ignores mismatched paths"); var a = new Command("remove", ["foo"]); var b = new Command("edit", ["foo","bar"], 42); is(doesConflict(a, b), true, "doesConflict catches edit under remove"); is(doesConflict(b, a), true, "doesConflict catches edit under remove"); } function test_applyCommand() { var c = new Command("edit", ["foo"], "bar"); var target = {foo: "qux"}; applyCommand(target, c); is(target.foo, "bar", "applying edit commands works"); } function test_reconcileWithNoConflicts() { var syncdata = reconcile([detectUpdates(snap, replica1), detectUpdates(snap, replica2), detectUpdates(snap, replica3), detectUpdates(snap, replica4)]); is(syncdata.propagations.length, 4, "correct number of propogation arrays"); is(syncdata.propagations[0].length, 3, "correct number of commands to exec"); is(syncdata.propagations[0][0].action, "edit", "is it an edit?"); applyCommands(replica1, syncdata.propagations[0]); applyCommands(replica2, syncdata.propagations[1]); applyCommands(replica3, syncdata.propagations[2]); applyCommands(replica4, syncdata.propagations[3]); forEach([replica1, replica2, replica3, replica4], function (replica) { is(replica.foo, 0, "replica.foo is zero"); is(replica.baz, 0, "replica.bar is zero"); is(replica.bar, 0, "replica.baz is zero"); is(replica.qux, 0, "replica.qux is zero"); } ); } function pathToArray(path) { return path == "/" ? [] : path.split("/").slice(1); } function commandFromArray(key, array) { var c = array.filter( function(c) { return ("/" + c.path.join("/")) == key; } ); return c[0]; } function checkUpdate(list, path, expectAction, expectValue) { var x = commandFromArray(path, list); is(x.action, expectAction, path + " action"); if (isObjectOrArray(expectValue)) is(x.value.constructor, expectValue.constructor, path + " value"); else is(x.value, expectValue, path + " value"); is(arrayEqual(x.path, pathToArray(path)), true, path + " path"); } function checkSync(obj1, obj2, path, value) { field1 = pathToReference(obj1, pathToArray(path)); field2 = pathToReference(obj2, pathToArray(path)); is(field1, field2, path + " in sync"); is(field1, value, path + " correct value"); } // the README examples var snapshotJSON = { "x": 42, "a": 1, "b": { "c": 2, "d": { "e": 3, "f": 4 }, "g": 5 }, "h": 6.6, "i": [7, 8, 9], "j": 10, "k": { "m": 11 }, "n": 66, } var currentJSON = { "x": 43, /* edited */ "a": 1, "new": 11, /* created */ "b": { "c": 2, "new2": 22, /* created */ "d": { "e": 3, /*"f": 4*/ /* removed */ }, "g": 55, /* edited */ }, /* "h": 6.6, */ /* removed */ "i": [7, 8, 9, 99], /* added array element */ "j": 10, "k": 42, /* replaced object with primitive */ "n": { "new3": 77 }, /* replaced primitive with object */ } function test_complexReconcileWithNoConflicts() { var updates = detectUpdates(snapshotJSON, currentJSON); is(updates.length, 11, "detect correct number of updates"); checkUpdate(updates, "/x", "edit", 43); checkUpdate(updates, "/new", "create", 11); checkUpdate(updates, "/b/new2", "create", 22); checkUpdate(updates, "/b/d/f", "remove", undefined); checkUpdate(updates, "/b/g", "edit", 55); checkUpdate(updates, "/h", "remove", undefined); checkUpdate(updates, "/i/3", "create", 99); checkUpdate(updates, "/k/m", "remove", undefined); checkUpdate(updates, "/k", "edit", 42); checkUpdate(updates, "/n", "edit", {}); checkUpdate(updates, "/n/new3", "create", 77); // now we check against an object that contains edits to other // fields, or identical edits. var otherJSON = { "x": 43, /* edited to the same value */ "a": 100, /* non-conflicting edit */ "new": 11, /* created to the same value */ "b": { /*"c": 2,*/ /* non-conflicting remove */ "d": { "e": 3, /*"f": 4*/ /* removed same value */ }, "g": 5, /* didn't edit */ "foo": 555 /* non-conflicting create */ }, "h": 6.6, /* didn't remove */ "i": [7, 8, 9, 99], /* added same array element */ "j": 10, "k": { "m": 11 }, /* didn't touch */ "n": 66 /* didn't touch */ } var otherUpdates = detectUpdates(snapshotJSON, otherJSON); checkUpdate(otherUpdates, "/x", "edit", 43); checkUpdate(otherUpdates, "/a", "edit", 100); checkUpdate(otherUpdates, "/b/c", "remove", undefined); checkUpdate(otherUpdates, "/b/d/f", "remove", undefined); checkUpdate(otherUpdates, "/i/3", "create", 99); var syncdata = reconcile([updates, otherUpdates]); applyCommands(currentJSON, syncdata.propagations[0]); applyCommands(otherJSON, syncdata.propagations[1]); checkSync(currentJSON, otherJSON, "/x", 43); checkSync(currentJSON, otherJSON, "/a", 100); checkSync(currentJSON, otherJSON, "/new", 11); checkSync(currentJSON, otherJSON, "/b/c", undefined); checkSync(currentJSON, otherJSON, "/b/new2", 22); checkSync(currentJSON, otherJSON, "/b/d/f", undefined); checkSync(currentJSON, otherJSON, "/b/g", 55); checkSync(currentJSON, otherJSON, "/b/foo", 555); checkSync(currentJSON, otherJSON, "/h", undefined); checkSync(currentJSON, otherJSON, "/i/3", 99); checkSync(currentJSON, otherJSON, "/k", 42); checkSync(currentJSON, otherJSON, "/n/new3", 77); checkSync(currentJSON, otherJSON, "/j", 10); } function test_repeatedSyncsWithNoConflicts() { var originalJSON = {"foo": {"bar": "baz"}, "toBeRemoved":"goner", "someArray":["tobeEdited"]}; var clientJSON = {"foo": {"bar": "baz"}, "toBeRemoved":"goner", "someArray":["tobeEdited"]}; var serverJSON = {"foo": {"bar": "baz"}, "toBeRemoved":"goner", "someArray":["tobeEdited"]}; clientJSON["foo"]["clientAddition"] = "the client added this"; serverJSON["foo"]["serverAddition"] = "the server added this"; delete clientJSON["toBeRemoved"]; delete serverJSON["toBeRemoved"]; clientJSON["someArray"][0] = "been edited"; serverJSON["someArray"][0] = "been edited"; var syncdata = reconcile([detectUpdates(originalJSON, clientJSON), detectUpdates(originalJSON, serverJSON)]); applyCommands(clientJSON, syncdata.propagations[0]); applyCommands(serverJSON, syncdata.propagations[1]); is(clientJSON["foo"]["bar"] == serverJSON["foo"]["bar"], true, "unchanged fields remain"); is(serverJSON["foo"]["clientAddition"], clientJSON["foo"]["clientAddition"], "server has client addition"); is(clientJSON["foo"]["serverAddition"], serverJSON["foo"]["serverAddition"], "client has server addition"); is(clientJSON["toBeRemoved"] == undefined, true, "removed from client"); is(serverJSON["toBeRemoved"] == undefined, true, "removed from server"); is(clientJSON["someArray"][0] == serverJSON["someArray"][0], true, "identically edited array ok"); /* now all the fields are the same */ originalJSON = { "foo": {"bar":"baz", "clientAddition":"the client added this", "serverAddition":"the server added this"}, "someArray":["been edited"]} ; clientJSON["someArray"][0] = "edited again"; serverJSON["foo"]["bar"] = "edit some other field"; syncdata = reconcile([detectUpdates(originalJSON, clientJSON), detectUpdates(originalJSON, serverJSON)]); applyCommands(clientJSON, syncdata.propagations[0]); applyCommands(serverJSON, syncdata.propagations[1]); is(serverJSON["someArray"][0], "edited again", "repeated edit works"); is(serverJSON["foo"]["bar"], "edit some other field", "repeated edit works"); } function test_conflictsFromReplica() { var conflictList = conflictsFromReplica(new Command("edit", ["f"], "b"), [new Command("edit", ["f"], "b")]); is(conflictList.conflicts.length, 0, "identical commands don't conflict"); } function test_basicConflicts() { // conflicting edits var snap = {"foo":"bar"} var clientJSON = {"foo":"baz"} var serverJSON = {"foo":"qux"} var syncdata = reconcile([detectUpdates(snap, clientJSON), detectUpdates(snap, serverJSON)]); // should have zero propagations and one conflict is(syncdata.propagations[0].length, 0, "complete edit conflict should have no propagations"); is(syncdata.propagations[1].length, 0, "complete edit conflict should have no propagations"); is(syncdata.conflicts[0].length, 1, "single edit field conflicting should have one conflict"); is(syncdata.conflicts[1].length, 1, "single edit field conflicting should have one conflict"); // conflicting creates var snap = {"foo":"bar"} var clientJSON = {"foo":"bar","baz":"qux"} var serverJSON = {"foo":"bar","baz":"quux"} var syncdata = reconcile([detectUpdates(snap, clientJSON), detectUpdates(snap, serverJSON)]); // should have zero propagations and one conflict is(syncdata.propagations[0].length, 0, "complete create conflict should have no propagations"); is(syncdata.propagations[1].length, 0, "complete create conflict should have no propagations"); is(syncdata.conflicts[0].length, 1, "single create field conflicting should have one conflict"); is(syncdata.conflicts[1].length, 1, "single create field conflicting should have one conflict"); // edit that conflicts with a remove of its parent var snap = {"foo":{"bar":"baz"}, "xuq":"xuuq"} var clientJSON = {"xuq":"xuuq"} var serverJSON = {"foo":{"bar":"qux"}, "xuq":"xuuq"} var syncdata = reconcile([detectUpdates(snap, clientJSON), detectUpdates(snap, serverJSON)]); is(syncdata.propagations[0].length, 0, "complete remove conflict should have no propagations"); is(syncdata.propagations[1].length, 0, "complete remove conflict should have no propagations"); is(syncdata.conflicts[0].length, 1, "the client gets one conflict: the edit to /foo/bar"); is(syncdata.conflicts[1].length, 2, "the server gets two conflicts: both of the removals"); // edit that conflicts with an empty object var snap = {"foo":{"bar":"baz"}} var clientJSON = {} var serverJSON = {"foo":{"bar":"qux"}} var syncdata = reconcile([detectUpdates(snap, clientJSON), detectUpdates(snap, serverJSON)]); is(syncdata.propagations[0].length, 0, "complete remove conflict should have no propagations"); is(syncdata.propagations[1].length, 0, "complete remove conflict should have no propagations"); is(syncdata.conflicts[0].length, 1, "the client gets one conflict: the edit to /foo/bar"); is(syncdata.conflicts[1].length, 2, "the server gets two conflicts: both of the removals"); // hierarchical create conflict var snap = {"foo":"bar"} var clientJSON = {"foo":"bar", "baz":{"qux":"quux"}} var serverJSON = {"foo":"bar", "baz":"b"} var syncdata = reconcile([detectUpdates(snap, clientJSON), detectUpdates(snap, serverJSON)]); is(syncdata.propagations[0].length, 0, "complete remove conflict should have no propagations"); is(syncdata.propagations[1].length, 0, "complete remove conflict should have no propagations"); is(syncdata.conflicts[0].length, 1, "the client gets one conflict: creation of /baz"); is(syncdata.conflicts[1].length, 2, "the server gets two conflicts: both of the client creates"); // edited to primitive var snap = {"foo":"bar", "baz":{}} var clientJSON = {"foo":"bar", "baz":{"qux":"quux"}} var serverJSON = {"foo":"bar", "baz":"b"} var syncdata = reconcile([detectUpdates(snap, clientJSON), detectUpdates(snap, serverJSON)]); is(syncdata.propagations[0].length, 0, "complete remove conflict should have no propagations"); is(syncdata.propagations[1].length, 0, "complete remove conflict should have no propagations"); is(syncdata.conflicts[0].length, 1, "the client gets one conflict: edit of /baz"); is(syncdata.conflicts[1].length, 1, "the server gets one conflict: the creation of /baz/qux"); } function test_arrayMerging() { var snap = { "foo": [ {"a": "1"}, {"b": "2"}, {"c": "3"} ] } var clientJSON = { "foo": [ {"a": "1"}, {"b": "2"}, {"b2": "2b"}, {"c": "3"} ] } var serverJSON = { "foo": [ {"a": "1"}, {"a1": "1a"}, {"b": "2"}, {"c": "3"} ] } var syncdata = reconcile([detectUpdates(snap, clientJSON), detectUpdates(snap, serverJSON)]); // The result we end up with here is a little counter-intuitive. // The object with keys "b" and "b2" both end up being creates // underneath /foo/2. This illustrates the need to let clients // define properties that serve as identifiers. is(syncdata.propagations[0].length, 3, "move the indexes up"); is(syncdata.propagations[1].length, 1, "apply a create inside /foo/2"); is(syncdata.conflicts[0].length, 0, "no conflicts in array merging"); is(syncdata.conflicts[0].length, 0, "no conflicts in array merging"); applyCommands(clientJSON, syncdata.propagations[0]); applyCommands(serverJSON, syncdata.propagations[1]); checkSync(clientJSON, serverJSON, "/foo/0/a", "1"); checkSync(clientJSON, serverJSON, "/foo/1/a1", "1a"); checkSync(clientJSON, serverJSON, "/foo/2/b", "2"); checkSync(clientJSON, serverJSON, "/foo/2/b2", "2b"); checkSync(clientJSON, serverJSON, "/foo/3/c", "3"); } function test_arrayMergingWithIDs() { var snap = { "foo": [ {"a": "1"}, {"b": "2"}, {"c": "3"} ] } var clientJSON = { "foo": [ {"a": "1"}, {"b": "2"}, {"b2": "2b"}, {"c": "3"} ] } var serverJSON = { "foo": [ {"a": "1"}, {"a1": "1a"}, {"b": "2"}, {"c": "3"} ] } var syncdata = reconcile([detectUpdates(snap, clientJSON), detectUpdates(snap, serverJSON)]); output(syncdata.propagations[0].length + " " + syncdata.propagations[1].length) output(syncdata.conflicts[0].length + " " + syncdata.conflicts[1].length) forEach(syncdata.propagations[0], function(x) { output(x.action + " " + x.path + " = " + x.value)}) output("-----------") forEach(syncdata.propagations[1], function(x) { output(x.action + " " + x.path + " = " + x.value)}) } function test_complexConflictsMixedWithPropagations() { var snap = { "foo": { "bar": "baz", "bar2": "baz2" }, "foo2": { "hmm1": { "hmm": "yeah", "hm1": "hmmm", "hm2": "hmmmmmm" }, "foo3": { "bar3": ["hmm", "yeah", "ok"], "baz3": [ {"a": "1"}, {"b": "2"}, {"c": "3"} ] } } } var clientJSON = { "foo": { "bar": "baz1", /* conflict */ "bar2": "baz2", "fff": "ggg" /* no conflict create */ }, "foo2": { "hmm1": { "hmm": "yeah", "hm1": "hmmm", "hm2": "hmmmmmm" }, "foo3": { "bar3": ["hmm", "yeah", "ok"], "baz3": [ {"a": "1"}, {"a2": "12"}, {"b": "2"}, {"c": "3"} ] } } } var serverJSON = { "foo": { "bar": "asdfasdf", /* conflict */ "bar2": "baz2", "fff": "ggg", /* no conflict create */ "fff2": "ggg2" /* no conflict create */ }, "foo2": { "hmm1": { "hmm": "yeah", "hm1": "hmmm", "hm2": "hmmmmmm" }, "foo3": { "bar3": ["hmm", "yeah", "ok"], "baz3": [ {"a": "1"}, {"b": "2"}, {"b2": "2b"}, {"c": "3"} ] } } } } function runTests() { output("\n\nTests Starting"); output("--------------"); test_isObjectOrArray(); test_identifySuspects(); test_created(); test_removed(); test_edited(); test_detectUpdates(); test_orderUpdates(); test_Command(); test_commandInList(); test_doesConflict(); test_applyCommand(); test_reconcileWithNoConflicts(); test_complexReconcileWithNoConflicts(); test_repeatedSyncsWithNoConflicts(); test_conflictsFromReplica(); test_basicConflicts(); test_arrayMerging(); //test_arrayMergingWithIDs(); complete(); } if (this["document"]) { window.onload = runTests; } else { runTests(); }
krishnabangalore/Webinos-Platform
webinos/core/manager/synchronisation_manager/lib/json-sync-master/test.js
JavaScript
apache-2.0
24,453
/** * Copyright 2020 The AMP HTML Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS-IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import {Services} from '../../../src/services'; import {getMode} from '../../../src/mode'; import {includes} from '../../../src/string'; import {map} from '../../../src/utils/object'; import {parseExtensionUrl} from '../../../src/service/extension-script'; import {preloadFriendlyIframeEmbedExtensions} from '../../../src/friendly-iframe-embed'; import {removeElement, rootNodeFor} from '../../../src/dom'; import {urls} from '../../../src/config'; /** * @typedef {{ * extensions: !Array<{extensionId: (string|undefined), extensionVersion: (string|undefined)}>, * head: !Element * }} */ export let ValidatedHeadDef; // From validator/validator-main.protoascii const ALLOWED_FONT_REGEX = new RegExp( 'https://cdn\\.materialdesignicons\\.com/' + '([0-9]+\\.?)+/css/materialdesignicons\\.min\\.css|' + 'https://cloud\\.typography\\.com/' + '[0-9]*/[0-9]*/css/fonts\\.css|' + 'https://fast\\.fonts\\.net/.*|' + 'https://fonts\\.googleapis\\.com/css2?\\?.*|' + 'https://fonts\\.googleapis\\.com/icon\\?.*|' + 'https://fonts\\.googleapis\\.com/earlyaccess/.*\\.css|' + 'https://maxcdn\\.bootstrapcdn\\.com/font-awesome/' + '([0-9]+\\.?)+/css/font-awesome\\.min\\.css(\\?.*)?|' + 'https://(use|pro)\\.fontawesome\\.com/releases/v([0-9]+\\.?)+' + '/css/[0-9a-zA-Z-]+\\.css|' + 'https://(use|pro)\\.fontawesome\\.com/[0-9a-zA-Z-]+\\.css|' + 'https://use\\.typekit\\.net/[\\w\\p{L}\\p{N}_]+\\.css' ); // If editing please also change: // extensions/amp-a4a/amp-a4a-format.md#allowed-amp-extensions-and-builtins const EXTENSION_ALLOWLIST = map({ 'amp-accordion': true, 'amp-ad-exit': true, 'amp-analytics': true, 'amp-anim': true, 'amp-animation': true, 'amp-audio': true, 'amp-bind': true, 'amp-carousel': true, 'amp-fit-text': true, 'amp-font': true, 'amp-form': true, 'amp-img': true, 'amp-layout': true, 'amp-lightbox': true, 'amp-mraid': true, 'amp-mustache': true, 'amp-pixel': true, 'amp-position-observer': true, 'amp-selector': true, 'amp-social-share': true, 'amp-video': true, }); const EXTENSION_URL_PREFIX = new RegExp( urls.cdn.replace(/\./g, '\\.') + '/v0/' ); /** * Sanitizes AMPHTML Ad head element and extracts extensions to be installed. * @param {!Window} win * @param {!Element} adElement * @param {?Element} head * @return {?ValidatedHeadDef} */ export function processHead(win, adElement, head) { if (!head || !head.firstChild) { return null; } const root = rootNodeFor(head); const htmlTag = root.documentElement; if ( !htmlTag || (!htmlTag.hasAttribute('amp4ads') && !htmlTag.hasAttribute('⚡️4ads') && !htmlTag.hasAttribute('⚡4ads')) // Unicode weirdness. ) { return null; } const urlService = Services.urlForDoc(adElement); /** @type {!Array<{extensionId: string, extensionVersion: string}>} */ const extensions = []; const fonts = []; const images = []; let element = head.firstElementChild; while (element) { // Store next element here as the following code will remove // certain elements from the detached DOM. const nextElement = element.nextElementSibling; switch (element.tagName.toUpperCase()) { case 'SCRIPT': handleScript(extensions, element); break; case 'STYLE': handleStyle(element); break; case 'LINK': handleLink(fonts, images, element); break; // Allow these without validation. case 'META': case 'TITLE': break; default: removeElement(element); break; } element = nextElement; } // Load any extensions; do not wait on their promises as this // is just to prefetch. preloadFriendlyIframeEmbedExtensions(win, extensions); // Preload any fonts. fonts.forEach((fontUrl) => Services.preconnectFor(win).preload(adElement.getAmpDoc(), fontUrl) ); // Preload any AMP images. images.forEach( (imageUrl) => urlService.isSecure(imageUrl) && Services.preconnectFor(win).preload(adElement.getAmpDoc(), imageUrl) ); return { extensions, head, }; } /** * Allows json scripts and allowlisted amp elements while removing others. * @param {!Array<{extensionId: string, extensionVersion: string}>} extensions * @param {!Element} script */ function handleScript(extensions, script) { if (script.type === 'application/json') { return; } const {src} = script; const isTesting = getMode().test || getMode().localDev; if ( EXTENSION_URL_PREFIX.test(src) || // Integration tests point to local files. (isTesting && includes(src, '/dist/')) ) { const extensionInfo = parseExtensionUrl(src); if (extensionInfo && EXTENSION_ALLOWLIST[extensionInfo.extensionId]) { extensions.push(extensionInfo); } } removeElement(script); } /** * Collect links that are from allowed font providers or used for image * preloading. Remove other <link> elements. * @param {!Array<string>} fonts * @param {!Array<string>} images * @param {!Element} link */ function handleLink(fonts, images, link) { const {href, as, rel} = link; if (rel === 'preload' && as === 'image') { images.push(href); return; } if (rel === 'stylesheet' && ALLOWED_FONT_REGEX.test(href)) { fonts.push(href); return; } removeElement(link); } /** * Remove any non `amp-custom` or `amp-keyframe` styles. * @param {!Element} style */ function handleStyle(style) { if ( style.hasAttribute('amp-custom') || style.hasAttribute('amp-keyframes') || style.hasAttribute('amp4ads-boilerplate') ) { return; } removeElement(style); }
lannka/amphtml
extensions/amp-a4a/0.1/head-validation.js
JavaScript
apache-2.0
6,308
'use strict'; module.exports = function (math) { var util = require('../../util/index'), BigNumber = math.type.BigNumber, collection = require('../../type/collection'), isNumber = util.number.isNumber, isBoolean = util['boolean'].isBoolean, isInteger = util.number.isInteger, isCollection = collection.isCollection; /** * Compute the factorial of a value * * Factorial only supports an integer value as argument. * For matrices, the function is evaluated element wise. * * Syntax: * * math.factorial(n) * * Examples: * * math.factorial(5); // returns 120 * math.factorial(3); // returns 6 * * See also: * * combinations, permutations * * @param {Number | BigNumber | Array | Matrix} n An integer number * @return {Number | BigNumber | Array | Matrix} The factorial of `n` */ math.factorial = function factorial (n) { var value, res; if (arguments.length != 1) { throw new math.error.ArgumentsError('factorial', arguments.length, 1); } if (isNumber(n)) { if (!isInteger(n) || n < 0) { throw new TypeError('Positive integer value expected in function factorial'); } value = n - 1; res = n; while (value > 1) { res *= value; value--; } if (res == 0) { res = 1; // 0! is per definition 1 } return res; } if (n instanceof BigNumber) { if (!(isPositiveInteger(n))) { throw new TypeError('Positive integer value expected in function factorial'); } var one = new BigNumber(1); value = n.minus(one); res = n; while (value.gt(one)) { res = res.times(value); value = value.minus(one); } if (res.equals(0)) { res = one; // 0! is per definition 1 } return res; } if (isBoolean(n)) { return 1; // factorial(1) = 1, factorial(0) = 1 } if (isCollection(n)) { return collection.deepMap(n, factorial); } throw new math.error.UnsupportedTypeError('factorial', math['typeof'](n)); }; /** * Test whether BigNumber n is a positive integer * @param {BigNumber} n * @returns {boolean} isPositiveInteger */ var isPositiveInteger = function(n) { return n.isInteger() && n.gte(0); }; };
wyom/mathjs
lib/function/probability/factorial.js
JavaScript
apache-2.0
2,388
/* * author: the5fire * blog: the5fire.com * date: 2014-03-16 * */ $(function(){ WEB_SOCKET_SWF_LOCATION = "/static/WebSocketMain.swf"; WEB_SOCKET_DEBUG = true; var socket = io.connect(); socket.on('connect', function(){ console.log('connected'); }); $(window).bind("beforeunload", function() { socket.disconnect(); }); var User = Backbone.Model.extend({ urlRoot: '/user', }); var Topic = Backbone.Model.extend({ urlRoot: '/topic', }); var Message = Backbone.Model.extend({ urlRoot: '/message', sync: function(method, model, options) { if (method === 'create') { socket.emit('message', model.attributes); // 错误处理没做 $('#comment').val(''); } else { return Backbone.sync(method, model, options); }; }, }); var Topics = Backbone.Collection.extend({ url: '/topic', model: Topic, }); var Messages = Backbone.Collection.extend({ url: '/message', model: Message, }); var topics = new Topics; var TopicView = Backbone.View.extend({ tagName: "div class='column'", templ: _.template($('#topic-template').html()), // 渲染列表页模板 render: function() { $(this.el).html(this.templ(this.model.toJSON())); return this; }, }); var messages = new Messages; var MessageView = Backbone.View.extend({ tagName: "div class='comment'", templ: _.template($('#message-template').html()), // 渲染列表页模板 render: function() { $(this.el).html(this.templ(this.model.toJSON())); return this; }, }); var AppView = Backbone.View.extend({ el: "#main", topic_list: $("#topic_list"), topic_section: $("#topic_section"), message_section: $("#message_section"), message_list: $("#message_list"), message_head: $("#message_head"), events: { 'click .submit': 'saveMessage', 'click .submit_topic': 'saveTopic', 'keypress #comment': 'saveMessageEvent', }, initialize: function() { _.bindAll(this, 'addTopic', 'addMessage'); topics.bind('add', this.addTopic); // 定义消息列表池,每个topic有自己的message collection // 这样保证每个主题下得消息不冲突 this.message_pool = {}; this.socket = null; this.message_list_div = document.getElementById('message_list'); }, addTopic: function(topic) { var view = new TopicView({model: topic}); this.topic_list.append(view.render().el); }, addMessage: function(message) { var view = new MessageView({model: message}); this.message_list.append(view.render().el); self.message_list.scrollTop(self.message_list_div.scrollHeight); }, saveMessageEvent: function(evt) { if (evt.keyCode == 13) { this.saveMessage(evt); } }, saveMessage: function(evt) { var comment_box = $('#comment') var content = comment_box.val(); if (content == '') { alert('内容不能为空'); return false; } var topic_id = comment_box.attr('topic_id'); var message = new Message({ content: content, topic_id: topic_id, }); var messages = this.message_pool[topic_id]; message.save(); // 依赖上面对sync的重载 }, saveTopic: function(evt) { var topic_title = $('#topic_title'); if (topic_title.val() == '') { alert('主题不能为空!'); return false } var topic = new Topic({ title: topic_title.val(), }); self = this; topic.save(null, { success: function(model, response, options){ topics.add(response); topic_title.val(''); }, error: function(model, resp, options) { alert(resp.responseText); } }); }, showTopic: function(){ topics.fetch(); this.topic_section.show(); this.message_section.hide(); this.message_list.html(''); this.goOut() }, goOut: function(){ // 退出房间 socket.emit('go_out'); socket.removeAllListeners('message'); }, initMessage: function(topic_id) { var messages = new Messages; messages.bind('add', this.addMessage); this.message_pool[topic_id] = messages; }, showMessage: function(topic_id) { this.initMessage(topic_id); this.message_section.show(); this.topic_section.hide(); this.showMessageHead(topic_id); $('#comment').attr('topic_id', topic_id); var messages = this.message_pool[topic_id]; // 进入房间 socket.emit('topic', topic_id); // 监听message事件,添加对话到messages中 socket.on('message', function(response) { messages.add(response); }); messages.fetch({ data: {topic_id: topic_id}, success: function(resp) { self.message_list.scrollTop(self.message_list_div.scrollHeight) }, error: function(model, resp, options) { alert(resp.responseText); } }); }, showMessageHead: function(topic_id) { var topic = new Topic({id: topic_id}); self = this; topic.fetch({ success: function(resp, model, options){ self.message_head.html(model.title); }, error: function(model, resp, options) { alert(resp.responseText); } }); }, }); var LoginView = Backbone.View.extend({ el: "#login", wrapper: $('#wrapper'), events: { 'keypress #login_pwd': 'loginEvent', 'click .login_submit': 'login', 'keypress #reg_pwd_repeat': 'registeEvent', 'click .registe_submit': 'registe', }, hide: function() { this.wrapper.hide(); }, show: function() { this.wrapper.show(); }, loginEvent: function(evt) { if (evt.keyCode == 13) { this.login(evt); } }, login: function(evt){ var username_input = $('#login_username'); var pwd_input = $('#login_pwd'); var u = new User({ username: username_input.val(), password: pwd_input.val(), }); u.save(null, { url: '/login', success: function(model, resp, options){ g_user = resp; // 跳转到index appRouter.navigate('index', {trigger: true}); }, error: function(model, resp, options) { alert(resp.responseText); } }); }, registeEvent: function(evt) { if (evt.keyCode == 13) { this.registe(evt); } }, registe: function(evt){ var reg_username_input = $('#reg_username'); var reg_pwd_input = $('#reg_pwd'); var reg_pwd_repeat_input = $('#reg_pwd_repeat'); var u = new User({ username: reg_username_input.val(), password: reg_pwd_input.val(), password_repeat: reg_pwd_repeat_input.val(), }); u.save(null, { success: function(model, resp, options){ g_user = resp; // 跳转到index appRouter.navigate('index', {trigger: true}); }, error: function(model, resp, options) { alert(resp.responseText); } }); }, }); var UserView = Backbone.View.extend({ el: "#user_info", username: $('#username'), show: function(username) { this.username.html(username); this.$el.show(); }, }); var AppRouter = Backbone.Router.extend({ routes: { "login": "login", "index": "index", "topic/:id" : "topic", }, initialize: function(){ // 初始化项目, 显示首页 this.appView = new AppView(); this.loginView = new LoginView(); this.userView = new UserView(); this.indexFlag = false; }, login: function(){ this.loginView.show(); }, index: function(){ if (g_user && g_user.id != undefined) { this.appView.showTopic(); this.userView.show(g_user.username); this.loginView.hide(); this.indexFlag = true; // 标志已经到达主页了 } }, topic: function(topic_id) { if (g_user && g_user.id != undefined) { this.appView.showMessage(topic_id); this.userView.show(g_user.username); this.loginView.hide(); this.indexFlag = true; // 标志已经到达主页了 } }, }); var appRouter = new AppRouter(); var g_user = new User; g_user.fetch({ success: function(model, resp, options){ g_user = resp; Backbone.history.start({pustState: true}); if(g_user === null || g_user.id === undefined) { // 跳转到登录页面 appRouter.navigate('login', {trigger: true}); } else if (appRouter.indexFlag == false){ // 跳转到首页 appRouter.navigate('index', {trigger: true}); } }, error: function(model, resp, options) { alert(resp.responseText); } }); // 获取当前用户 });
yhbyun/wechat-1
src/static/js/chat.js
JavaScript
apache-2.0
10,736
/* */ "format cjs"; /** * Determines whether two sequences are equal by comparing the elements pairwise using a specified equality comparer. * * @example * var res = res = source.sequenceEqual([1,2,3]); * var res = res = source.sequenceEqual([{ value: 42 }], function (x, y) { return x.value === y.value; }); * 3 - res = source.sequenceEqual(Rx.Observable.returnValue(42)); * 4 - res = source.sequenceEqual(Rx.Observable.returnValue({ value: 42 }), function (x, y) { return x.value === y.value; }); * @param {Observable} second Second observable sequence or array to compare. * @param {Function} [comparer] Comparer used to compare elements of both sequences. * @returns {Observable} An observable sequence that contains a single element which indicates whether both sequences are of equal length and their corresponding elements are equal according to the specified equality comparer. */ observableProto.sequenceEqual = function (second, comparer) { var first = this; comparer || (comparer = defaultComparer); return new AnonymousObservable(function (o) { var donel = false, doner = false, ql = [], qr = []; var subscription1 = first.subscribe(function (x) { var equal, v; if (qr.length > 0) { v = qr.shift(); try { equal = comparer(v, x); } catch (e) { o.onError(e); return; } if (!equal) { o.onNext(false); o.onCompleted(); } } else if (doner) { o.onNext(false); o.onCompleted(); } else { ql.push(x); } }, function(e) { o.onError(e); }, function () { donel = true; if (ql.length === 0) { if (qr.length > 0) { o.onNext(false); o.onCompleted(); } else if (doner) { o.onNext(true); o.onCompleted(); } } }); (isArrayLike(second) || isIterable(second)) && (second = observableFrom(second)); isPromise(second) && (second = observableFromPromise(second)); var subscription2 = second.subscribe(function (x) { var equal; if (ql.length > 0) { var v = ql.shift(); try { equal = comparer(v, x); } catch (exception) { o.onError(exception); return; } if (!equal) { o.onNext(false); o.onCompleted(); } } else if (donel) { o.onNext(false); o.onCompleted(); } else { qr.push(x); } }, function(e) { o.onError(e); }, function () { doner = true; if (qr.length === 0) { if (ql.length > 0) { o.onNext(false); o.onCompleted(); } else if (donel) { o.onNext(true); o.onCompleted(); } } }); return new CompositeDisposable(subscription1, subscription2); }, first); };
cfraz89/moonrock-js-starter
jspm_packages/npm/[email protected]/src/core/linq/observable/sequenceequal.js
JavaScript
apache-2.0
3,046
function getUrlVars() { var vars = [], hash; var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&'); for (var i = 0; i < hashes.length; i++) { hash = hashes[i].split('='); vars.push(hash[0]); vars[hash[0]] = hash[1]; } return vars; }
SreejithNS/com.sreejithn
www/js/geturi.js
JavaScript
apache-2.0
312
export const CREATE_COURSE = 'CREATE_COURSE';
bluSCALE4/react-hello-world
src/actions/actionTypes.js
JavaScript
apache-2.0
46
/*** Wrapper/Helper Class for datagrid based on jQuery Datatable Plugin ***/ var Datatable = function () { var tableOptions; // main options var dataTable; // datatable object var table; // actual table jquery object var tableContainer; // actual table container object var tableWrapper; // actual table wrapper jquery object var tableInitialized = false; var ajaxParams = {}; // set filter mode var countSelectedRecords = function() { var selected = $('tbody > tr > td:nth-child(1) input[type="checkbox"]:checked', table).size(); var text = tableOptions.dataTable.oLanguage.sGroupActions; if (selected > 0) { $('.table-group-actions > span', tableWrapper).text(text.replace("_TOTAL_", selected)); } else { $('.table-group-actions > span', tableWrapper).text(""); } } return { //main function to initiate the module init: function (options) { if (!$().dataTable) { return; } var the = this; // default settings options = $.extend(true, { src: "", // actual table filterApplyAction: "filter", filterCancelAction: "filter_cancel", resetGroupActionInputOnSuccess: true, dataTable: { "sDom" : "<'row'<'col-md-8 col-sm-12'pli><'col-md-4 col-sm-12'<'table-group-actions pull-right'>>r><'table-scrollable't><'row'<'col-md-8 col-sm-12'pli><'col-md-4 col-sm-12'>r>>", // datatable layout "aLengthMenu": [ // set available records per page [10, 25, 50, 100, -1], [10, 25, 50, 100, "All"] ], "iDisplayLength": 10, // default records per page "oLanguage": { // language settings "sProcessing": '<img src="' + Metronic.getGlobalImgPath() + 'loading-spinner-grey.gif"/><span>&nbsp;&nbsp;Loading...</span>', "sLengthMenu": "<span class='seperator'>|</span>View _MENU_ records", "sInfo": "<span class='seperator'>|</span>Found total _TOTAL_ records", "sInfoEmpty": "No records found to show", "sGroupActions": "_TOTAL_ records selected: ", "sAjaxRequestGeneralError": "Could not complete request. Please check your internet connection", "sEmptyTable": "No data available in table", "sZeroRecords": "No matching records found", "oPaginate": { "sPrevious": "Prev", "sNext": "Next", "sPage": "Page", "sPageOf": "of" } }, "aoColumnDefs" : [{ // define columns sorting options(by default all columns are sortable extept the first checkbox column) 'bSortable' : false, 'aTargets' : [ 0 ] }], "bAutoWidth": false, // disable fixed width and enable fluid table "bSortCellsTop": true, // make sortable only the first row in thead "sPaginationType": "bootstrap_extended", // pagination type(bootstrap, bootstrap_full_number or bootstrap_extended) "bProcessing": true, // enable/disable display message box on record load "bServerSide": true, // enable/disable server side ajax loading "sAjaxSource": "", // define ajax source URL "sServerMethod": "POST", // handle ajax request "fnServerData": function ( sSource, aoData, fnCallback, oSettings ) { oSettings.jqXHR = $.ajax( { "dataType": 'json', "type": "POST", "url": sSource, "data": aoData, "success": function(res, textStatus, jqXHR) { if (res.sMessage) { Metronic.alert({type: (res.sStatus == 'OK' ? 'success' : 'danger'), icon: (res.sStatus == 'OK' ? 'check' : 'warning'), message: res.sMessage, container: tableWrapper, place: 'prepend'}); } if (res.sStatus) { if (tableOptions.resetGroupActionInputOnSuccess) { $('.table-group-action-input', tableWrapper).val(""); } } if ($('.group-checkable', table).size() === 1) { $('.group-checkable', table).attr("checked", false); $.uniform.update($('.group-checkable', table)); } if (tableOptions.onSuccess) { tableOptions.onSuccess.call(undefined, the); } fnCallback(res, textStatus, jqXHR); }, "error": function() { if (tableOptions.onError) { tableOptions.onError.call(undefined, the); } Metronic.alert({type: 'danger', icon: 'warning', message: tableOptions.dataTable.oLanguage.sAjaxRequestGeneralError, container: tableWrapper, place: 'prepend'}); $('.dataTables_processing', tableWrapper).remove(); } } ); }, // pass additional parameter "fnServerParams": function ( aoData ) { //here can be added an external ajax request parameters. $.each(ajaxParams, function( key, value ) { aoData.push({"name" : key, "value": value}); }); }, "fnDrawCallback": function( oSettings ) { // run some code on table redraw if (tableInitialized === false) { // check if table has been initialized tableInitialized = true; // set table initialized table.show(); // display table } Metronic.initUniform($('input[type="checkbox"]', table)); // reinitialize uniform checkboxes on each table reload countSelectedRecords(); // reset selected records indicator } } }, options); tableOptions = options; // create table's jquery object table = $(options.src); tableContainer = table.parents(".table-container"); // apply the special class that used to restyle the default datatable $.fn.dataTableExt.oStdClasses.sWrapper = $.fn.dataTableExt.oStdClasses.sWrapper + " dataTables_extended_wrapper"; // initialize a datatable dataTable = table.dataTable(options.dataTable); tableWrapper = table.parents('.dataTables_wrapper'); // modify table per page dropdown input by appliying some classes $('.dataTables_length select', tableWrapper).addClass("form-control input-xsmall input-sm"); // build table group actions panel if ($('.table-actions-wrapper', tableContainer).size() === 1) { $('.table-group-actions', tableWrapper).html($('.table-actions-wrapper', tableContainer).html()); // place the panel inside the wrapper $('.table-actions-wrapper', tableContainer).remove(); // remove the template container } // handle group checkboxes check/uncheck $('.group-checkable', table).change(function () { var set = $('tbody > tr > td:nth-child(1) input[type="checkbox"]', table); var checked = $(this).is(":checked"); $(set).each(function () { $(this).attr("checked", checked); }); $.uniform.update(set); countSelectedRecords(); }); // handle row's checkbox click table.on('change', 'tbody > tr > td:nth-child(1) input[type="checkbox"]', function(){ countSelectedRecords(); }); // handle filter submit button click table.on('click', '.filter-submit', function(e){ e.preventDefault(); the.setAjaxParam("sAction", tableOptions.filterApplyAction); // get all typeable inputs $('textarea.form-filter, select.form-filter, input.form-filter:not([type="radio"],[type="checkbox"])', table).each(function(){ the.setAjaxParam($(this).attr("name"), $(this).val()); }); // get all checkable inputs $('input.form-filter[type="checkbox"]:checked, input.form-filter[type="radio"]:checked', table).each(function(){ the.setAjaxParam($(this).attr("name"), $(this).val()); }); dataTable.fnDraw(); }); // handle filter cancel button click table.on('click', '.filter-cancel', function(e){ e.preventDefault(); $('textarea.form-filter, select.form-filter, input.form-filter', table).each(function(){ $(this).val(""); }); $('input.form-filter[type="checkbox"]', table).each(function(){ $(this).attr("checked", false); }); the.clearAjaxParams(); the.setAjaxParam("sAction", tableOptions.filterCancelAction); dataTable.fnDraw(); }); }, getSelectedRowsCount: function() { return $('tbody > tr > td:nth-child(1) input[type="checkbox"]:checked', table).size(); }, getSelectedRows: function() { var rows = []; $('tbody > tr > td:nth-child(1) input[type="checkbox"]:checked', table).each(function(){ rows.push({name: $(this).attr("name"), value: $(this).val()}); }); return rows; }, addAjaxParam: function(name, value) { ajaxParams[name] = value; }, setAjaxParam: function(name, value) { ajaxParams[name] = value; }, clearAjaxParams: function(name, value) { ajaxParams = []; }, getDataTable: function() { return dataTable; }, getTableWrapper: function() { return tableWrapper; }, gettableContainer: function() { return tableContainer; }, getTable: function() { return table; } }; };
zeickan/Infected-Engine
static/global/scripts/datatable.js
JavaScript
apache-2.0
11,607
Ext.data.ArrayReader=Ext.extend(Ext.data.JsonReader,{readRecords:function(c){var b=this.meta?this.meta.id:null;var h=this.recordType,q=h.prototype.fields;var e=[];var s=c;for(var m=0;m<s.length;m++){var d=s[m];var u={};var a=((b||b===0)&&d[b]!==undefined&&d[b]!==""?d[b]:null);for(var l=0,w=q.length;l<w;l++){var r=q.items[l];var g=r.mapping!==undefined&&r.mapping!==null?r.mapping:l;var t=d[g]!==undefined?d[g]:r.defaultValue;t=r.convert(t,d);u[r.name]=t}var p=new h(u,a);p.json=d;e[e.length]=p}return{records:e,totalRecords:e.length}}});
Ariah-Group/Continuity
src/main/webapp/javascripts/ext/build/data/ArrayReader-min.js
JavaScript
apache-2.0
539
/** * @file * <a href="https://travis-ci.org/Xotic750/has-to-string-tag-x" * title="Travis status"> * <img * src="https://travis-ci.org/Xotic750/has-to-string-tag-x.svg?branch=master" * alt="Travis status" height="18"> * </a> * <a href="https://david-dm.org/Xotic750/has-to-string-tag-x" * title="Dependency status"> * <img src="https://david-dm.org/Xotic750/has-to-string-tag-x.svg" * alt="Dependency status" height="18"/> * </a> * <a * href="https://david-dm.org/Xotic750/has-to-string-tag-x#info=devDependencies" * title="devDependency status"> * <img src="https://david-dm.org/Xotic750/has-to-string-tag-x/dev-status.svg" * alt="devDependency status" height="18"/> * </a> * <a href="https://badge.fury.io/js/has-to-string-tag-x" title="npm version"> * <img src="https://badge.fury.io/js/has-to-string-tag-x.svg" * alt="npm version" height="18"> * </a> * * hasToStringTag tests if @@toStringTag is supported. `true` if supported. * * <h2>ECMAScript compatibility shims for legacy JavaScript engines</h2> * `es5-shim.js` monkey-patches a JavaScript context to contain all EcmaScript 5 * methods that can be faithfully emulated with a legacy JavaScript engine. * * `es5-sham.js` monkey-patches other ES5 methods as closely as possible. * For these methods, as closely as possible to ES5 is not very close. * Many of these shams are intended only to allow code to be written to ES5 * without causing run-time errors in older engines. In many cases, * this means that these shams cause many ES5 methods to silently fail. * Decide carefully whether this is what you want. Note: es5-sham.js requires * es5-shim.js to be able to work properly. * * `json3.js` monkey-patches the EcmaScript 5 JSON implimentation faithfully. * * `es6.shim.js` provides compatibility shims so that legacy JavaScript engines * behave as closely as possible to ECMAScript 6 (Harmony). * * @version 1.1.0 * @author Xotic750 <[email protected]> * @copyright Xotic750 * @license {@link <https://opensource.org/licenses/MIT> MIT} * @module has-to-string-tag-x */ /* jslint maxlen:80, es6:true, white:true */ /* jshint bitwise:true, camelcase:true, curly:true, eqeqeq:true, forin:true, freeze:true, futurehostile:true, latedef:true, newcap:true, nocomma:true, nonbsp:true, singleGroups:true, strict:true, undef:true, unused:true, es3:false, esnext:true, plusplus:true, maxparams:1, maxdepth:1, maxstatements:3, maxcomplexity:2 */ /* eslint strict: 1, max-statements: 1 */ /* global module */ ;(function () { // eslint-disable-line no-extra-semi 'use strict'; /** * Indicates if `Symbol.toStringTag`exists and is the correct type. * `true`, if it exists and is the correct type, otherwise `false`. * * @type boolean */ module.exports = require('has-symbol-support-x') && typeof Symbol.toStringTag === 'symbol'; }());
BluelabUnifor/sunny-messeger
node_modules/watson-developer-cloud/node_modules/buffer-from/node_modules/is-array-buffer-x/node_modules/has-to-string-tag-x/index.js
JavaScript
apache-2.0
2,875
// Copyright (C) 2016 the V8 project authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- esid: sec-html-like-comments description: SingleLineHTMLOpenComment info: | Comment :: MultiLineComment SingleLineComment SingleLineHTMLOpenComment SingleLineHTMLCloseComment SingleLineDelimitedComment SingleLineHTMLOpenComment :: <!--SingleLineCommentCharsopt negative: phase: runtime type: Test262Error ---*/ var counter = 0; <!-- counter += 1; <!--the comment extends to these characters counter += 1; counter += 1;<!--the comment extends to these characters counter += 1; var x = 0; x = -1 <!--x; // Because this test concerns the interpretation of non-executable character // sequences within ECMAScript source code, special care must be taken to // ensure that executable code is evaluated as expected. // // Express the intended behavior by intentionally throwing an error; this // guarantees that test runners will only consider the test "passing" if // executable sequences are correctly interpreted as such. if (counter === 4 && x === -1) { throw new Test262Error(); }
sebastienros/jint
Jint.Tests.Test262/test/annexB/language/comments/single-line-html-open.js
JavaScript
bsd-2-clause
1,179
// Copyright (C) 2016 the V8 project authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- esid: sec-%typedarray%.prototype.copywithin description: > Set values with out of bounds negative target argument. info: | 22.2.3.5 %TypedArray%.prototype.copyWithin (target, start [ , end ] ) %TypedArray%.prototype.copyWithin is a distinct function that implements the same algorithm as Array.prototype.copyWithin as defined in 22.1.3.3 except that the this object's [[ArrayLength]] internal slot is accessed in place of performing a [[Get]] of "length" and the actual copying of values in step 12 must be performed in a manner that preserves the bit-level encoding of the source data. ... 22.1.3.3 Array.prototype.copyWithin (target, start [ , end ] ) ... 4. If relativeTarget < 0, let to be max((len + relativeTarget), 0); else let to be min(relativeTarget, len). ... includes: [compareArray.js, testBigIntTypedArray.js] features: [BigInt, TypedArray] ---*/ testWithBigIntTypedArrayConstructors(function(TA) { assert( compareArray( new TA([0n, 1n, 2n, 3n]).copyWithin(-10, 0), [0n, 1n, 2n, 3n] ), '[0, 1, 2, 3].copyWithin(-10, 0) -> [0, 1, 2, 3]' ); assert( compareArray( new TA([1n, 2n, 3n, 4n, 5n]).copyWithin(-Infinity, 0), [1n, 2n, 3n, 4n, 5n] ), '[1, 2, 3, 4, 5].copyWithin(-Infinity, 0) -> [1, 2, 3, 4, 5]' ); assert( compareArray( new TA([0n, 1n, 2n, 3n, 4n]).copyWithin(-10, 2), [2n, 3n, 4n, 3n, 4n] ), '[0, 1, 2, 3, 4].copyWithin(-10, 2) -> [2, 3, 4, 3, 4]' ); assert( compareArray( new TA([1n, 2n, 3n, 4n, 5n]).copyWithin(-Infinity, 2), [3n, 4n, 5n, 4n, 5n] ), '[1, 2, 3, 4, 5].copyWithin(-Infinity, 2) -> [3, 4, 5, 4, 5]' ); });
sebastienros/jint
Jint.Tests.Test262/test/built-ins/TypedArray/prototype/copyWithin/BigInt/negative-out-of-bounds-target.js
JavaScript
bsd-2-clause
1,835
// Copyright (c) 2012 Ecma International. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- es5id: 15.2.3.6-3-114 description: > Object.defineProperty - 'configurable' property in 'Attributes' is a Boolean object (8.10.5 step 4.b) ---*/ var obj = {}; Object.defineProperty(obj, "property", { configurable: new Boolean(true) }); var beforeDeleted = obj.hasOwnProperty("property"); delete obj.property; var afterDeleted = obj.hasOwnProperty("property"); assert.sameValue(beforeDeleted, true, 'beforeDeleted'); assert.sameValue(afterDeleted, false, 'afterDeleted');
sebastienros/jint
Jint.Tests.Test262/test/built-ins/Object/defineProperty/15.2.3.6-3-114.js
JavaScript
bsd-2-clause
629
// Copyright (c) 2012 Ecma International. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- es5id: 15.2.3.3-2-25 description: > Object.getOwnPropertyDescriptor - argument 'P' is a number that converts to a string (value is 1e-7) ---*/ var obj = { "1e-7": 1 }; var desc = Object.getOwnPropertyDescriptor(obj, 1e-7); assert.sameValue(desc.value, 1, 'desc.value');
sebastienros/jint
Jint.Tests.Test262/test/built-ins/Object/getOwnPropertyDescriptor/15.2.3.3-2-25.js
JavaScript
bsd-2-clause
425
/** * License and Terms of Use * * Copyright (c) 2011 SignpostMarv * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ (function(window, undefined){ var Array = window['Array'], EventTarget = window['EventTarget'], mapapi = window['mapapi'], gridPoint = mapapi['gridPoint'], bounds = mapapi['bounds'], ctype_digit = mapapi['utils']['ctype_digit'] ; if(mapapi == undefined){ throw 'mapapi.js is not loaded.'; }else if(EventTarget == undefined){ throw 'EventTarget is not loaded'; } function extend(a,b){ a.prototype = new b; a.prototype['constructor'] = a; } function shape(options){ EventTarget['call'](this); this['opts'] = {}; for(var i in this['defaultOpts']){ this['opts'][i] = this['defaultOpts'][i]; } if(options != undefined){ this['options'](options); } } extend(shape, EventTarget); shape.prototype['defaultOpts'] = {'fillStyle':'rgba(255,255,255,0.5)', 'strokeStyle':'rgb(255,255,255)', 'lineWidth':0}; shape.prototype['options'] = function(options){ options = options || {}; for(var i in options){ this['opts'] = options[i]; } } shape.prototype['withinShape'] = function(pos){ if(pos instanceof gridPoint){ return true; } return false; } shape.prototype['coords'] = function(value){ if(value != undefined){ this['options']({'coords':value}); } var coords = this['opts']['coords'] ; return coords != undefined ? coords : []; } shape.prototype['clickable'] = function(value){ if(value != undefined){ this['options']({'clickable':!!value}); } var clickable = this['opts']['clickable']; ; return clickable != undefined ? clickable : false; } shape.prototype['strokeStyle'] = function(value){ if(typeof value == 'string'){ this['options']({'strokeStyle':value}); } return this['opts']['strokeStyle']; } shape.prototype['lineWidth'] = function(value){ if(typeof value == 'number'){ this['options']({'lineWidth':Math.max(0,value)}); } return Math.max(0, this['opts']['lineWidth']); } shape.prototype['intersects'] = function(value){ if(value instanceof bounds && this['bounds'] instanceof bounds){ return this['bounds']['intersects'](value); } return false; } mapapi['shape'] = shape; function shapeManager(){ Array['call'](this); } extend(shapeManager, Array); shapeManager.prototype['push'] = function(){ for(var i=0;i<arguments['length'];++i){ if(!(arguments[i] instanceof shape)){ throw 'Arguments of mapapi.shapeManager::push() should be instances of mapapi.shape'; } } Array.prototype['push']['apply'](this, arguments); } shapeManager.prototype['intersects'] = function(value){ if(value instanceof bounds){ var shpmngr = new this['constructor'] ; for(var i=0;i<this['length'];++i){ if(this[i]['intersects'](value)){ shpmngr['push'](this[i]); } } return shpmngr; }else{ throw 'Intersection argument must be an instance of mapapi.bounds'; } } shapeManager.prototype['click'] = function(value){ var value = gridPoint['fuzzy'](value), ret ; for(var i=0;i<this['length'];++i){ if(this[i]['clickable']() && this[i]['withinShape'](value)){ ret = this[i]['fire']('click',{'pos':value}); if(ret != undefined && ret == false){ break; } } } } mapapi['shapeManager'] = shapeManager; function poly(options){ shape['call'](this, options); } extend(poly, shape); poly.prototype['options'] = function(options){ var options = options || {}, coords = options['coords'], fillStyle = options['fillStyle'], strokeStyle = options['strokeStyle'], lineWidth = options['lineWidth'] ; if(options['coords'] != undefined){ if(coords instanceof Array){ for(var i=0;i<coords['length'];++i){ coords[i] = gridPoint['fuzzy'](coords[i]); } var swx = coords[0]['x'], swy = coords[0]['y'], nex = coords[0]['x'], ney = coords[0]['y'] ; for(var i=1;i<coords['length'];++i){ swx = (coords[i]['x'] < swx) ? coords[i]['x'] : swx; swy = (coords[i]['y'] < swy) ? coords[i]['y'] : swy; nex = (coords[i]['x'] > nex) ? coords[i]['x'] : nex; ney = (coords[i]['y'] > ney) ? coords[i]['y'] : ney; } this['bounds'] = new bounds(new gridPoint(swx, swy), new gridPoint(nex, ney)); this['opts']['coords'] = coords; this['fire']('changedcoords'); }else{ throw 'coords must be array'; } } if(typeof fillStyle == 'string'){ var diff = this['opts']['fillStyle'] != fillStyle; this['opts']['fillStyle'] = fillStyle; if(diff){ this['fire']('changedfillstyle'); } } if(typeof strokeStyle == 'string'){ var diff = this['opts']['strokeStyle'] != strokeStyle; this['opts']['strokeStyle'] = strokeStyle; if(diff){ this['fire']('changedstrokestyle'); } } if(typeof lineWidth == 'number'){ var diff = this['opts']['lineWidth'] != Math.max(0,lineWidth); this['opts']['lineWidth'] = Math.max(0,lineWidth); if(diff){ this['fire']('changedlinewidth'); } } if(options['clickable'] != undefined){ this['opts']['clickable'] = !!options['clickable']; } } poly.prototype['fillStyle'] = function(value){ if(value != undefined){ this['options']({'fillStyle':value}); } return this['opts']['fillStyle']; } shape['polygon'] = poly; function rectangle(options){ poly['call'](this, options); } extend(rectangle, poly); rectangle.prototype['options'] = function(options){ var options = options || {}, coords = options['coords'] ; if(coords != undefined){ if(coords instanceof Array){ if(coords['length'] == 2){ for(var i=0;i<coords['length'];++i){ coords[i] = gridPoint['fuzzy'](coords[i]); } var sw = coords[0], ne = coords[1], foo,bar ; if(ne['y'] > sw['y']){ foo = new gridPoint(ne['x'], sw['y']); bar = new gridPoint(sw['x'], ne['y']); ne = foo; sw = bar; } if(sw['x'] > ne['x']){ foo = new gridPoint(ne['x'], sw['y']); bar = new gridPoint(sw['x'], ne['y']); sw = foo; ne = bar; } options['coords'] = [sw, ne]; }else{ throw 'When supplying mapapi.shape.rectangle::options with an Array for the coordinates, there should only be two entries'; } }else{ throw 'something other than array was given to mapapi.shape.rectangle::options'; } } poly.prototype['options']['call'](this, options); } rectangle.prototype['withinShape'] = function(value){ if(value == undefined){ throw 'Must specify an instance of mapapi.gridPoint'; }else if(!(this['bounds'] instanceof bounds)){ throw 'Coordinates not set'; } value = gridPoint['fuzzy'](value); return this['bounds']['isWithin'](value); } shape['rectangle'] = rectangle; function square(options){ rectangle['call'](this, options); } extend(square, rectangle); square.prototype['options'] = function(options){ options = options || {}; var coords = options['coords'] ; if(coords instanceof Array && coords['length'] <= 2){ var sw = coords[0], ne = coords[1] ; if(Math.abs(ne['x'] - sw['x']) != Math.abs(ne['y'] - sw['y'])){ throw 'coordinates should form a square'; } } rectangle.prototype['options']['call'](this, options); } shape['square'] = square; function line(options){ shape['call'](this, options); } extend(line, shape); line.prototype['defaultOpts'] = {'strokeStyle':'rgb(255,255,255)', 'lineWidth':1}; line.prototype['options'] = function(options){ var options = options || {}, coords = options['coords'], strokeStyle = options['strokeStyle'], lineWidth = options['lineWidth'] ; if(options['coords'] != undefined){ if(coords instanceof Array){ if(coords['length'] >= 2){ for(var i=0;i<coords['length'];++i){ coords[i] = gridPoint['fuzzy'](coords[i]); } this['opts']['coords'] = coords; this['fire']('changedcoords'); }else{ throw 'mapapi.shape.line requires two or more coordinates'; } }else{ throw 'mapapi.shape.line requires coordinates be passed as an array'; } } if(typeof strokeStyle == 'string'){ var diff = this['opts']['strokeStyle'] != strokeStyle; this['opts']['strokeStyle'] = strokeStyle; if(diff){ this['fire']('changedstrokestyle'); } } if(ctype_digit(lineWidth)){ lineWidth = Math.max(0,lineWidth * 1); var diff = this['opts']['lineWidth'] != lineWidth; this['opts']['lineWidth'] = lineWidth; if(diff){ this['fire']('changedlinewidth'); } } if(options['clickable'] != undefined){ this['opts']['clickable'] = !!options['clickable']; } } line.prototype['intersects'] = function(value){ if(value instanceof bounds){ var coords = this['coords']() ; for(var i=0;i<coords['length'];++i){ if(value['isWithin'](coords[i])){ return true; } } } return false; } shape['line'] = line; function circle(options){ shape['call'](this, options); } extend(circle, shape); circle.prototype['options'] = function(options){ var opts = this['opts'], options = options || {}, coords = options['coords'], radius = options['radius'], strokeStyle = options['strokeStyle'], lineWidth = options['lineWidth'], diffPos=false,diffRadius=false,diff ; if(coords != undefined){ coords[0] = gridPoint['fuzzy'](coords[0]); diffPos = opts['coords'] == undefined || !pos['equals'](opts['coords'][0]); opts['coords'] = [coords[0]]; } if(radius != undefined){ if(typeof radius != 'number'){ throw 'radius should be specified as a number'; }else if(radius <= 0){ throw 'radius should be greater than zero'; } diffRadius = radius != opts['radius']; opts['radius'] = radius; } if(diffPos || diffRadius){ this['fire']('changedcoords'); } if(typeof fillStyle == 'string'){ var diff = this['opts']['fillStyle'] != fillStyle; this['opts']['fillStyle'] = fillStyle; if(diff){ this['fire']('changedfillstyle'); } } if(typeof strokeStyle == 'string'){ var diff = this['opts']['strokeStyle'] != strokeStyle; this['opts']['strokeStyle'] = strokeStyle; if(diff){ this['fire']('changedstrokestyle'); } } if(typeof lineWidth == 'number'){ var diff = this['opts']['lineWidth'] != Math.max(0,lineWidth); this['opts']['lineWidth'] = Math.max(0,lineWidth); if(diff){ this['fire']('changedlinewidth'); } } if(options['clickable'] != undefined){ this['opts']['clickable'] = !!options['clickable']; } } circle.prototype['radius'] = function(value){ if(value != undefined){ this['options']({'radius':value}); } return this['opts']['radius']; } circle.prototype['fillStyle'] = function(value){ if(value != undefined){ this['options']({'fillStyle':value}); } return this['opts']['fillStyle']; } circle.prototype['withinShape'] = function(pos){ pos = gridPoint['fuzzy'](pos); return (this['coords']()[0] instanceof gridPoint && typeof this['radius']() == 'number') && (this['coords']()[0]['distance'](pos) <= this['radius']()); } circle.prototype['intersects'] = function(value){ if(value instanceof bounds && this['coords']()[0] instanceof gridPoint){ if(value['isWithin'](this['coords']()[0])){ return true; }else if(typeof this['radius']() == 'number'){ var sw = value['sw'], ne = value['ne'], distanceTests = [sw,ne,{'x':sw['x'], 'y':ne['y']}, {'x':ne['x'], 'y':sw['y']}] ; for(var i=0;i<distanceTests.length;++i){ if(this['withinShape'](distanceTests[i])){ return true; } } } } return false; } shape['circle'] = circle; })(window);
aurora-sim/Aurora-WebUI
www/worldmap/javascripts/mapapi.shape.js
JavaScript
bsd-3-clause
12,790
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @format * @flow strict-local */ 'use strict'; import type {Node} from 'React'; import {ActivityIndicator, StyleSheet, View} from 'react-native'; import React, {Component} from 'react'; type State = {|animating: boolean|}; type Props = $ReadOnly<{||}>; type Timer = TimeoutID; class ToggleAnimatingActivityIndicator extends Component<Props, State> { _timer: Timer; constructor(props: Props) { super(props); this.state = { animating: true, }; } componentDidMount() { this.setToggleTimeout(); } componentWillUnmount() { clearTimeout(this._timer); } setToggleTimeout() { this._timer = setTimeout(() => { this.setState({animating: !this.state.animating}); this.setToggleTimeout(); }, 2000); } render(): Node { return ( <ActivityIndicator animating={this.state.animating} style={[styles.centering, {height: 80}]} size="large" /> ); } } const styles = StyleSheet.create({ centering: { alignItems: 'center', justifyContent: 'center', padding: 8, }, gray: { backgroundColor: '#cccccc', }, horizontal: { flexDirection: 'row', justifyContent: 'space-around', padding: 8, }, }); exports.displayName = (undefined: ?string); exports.category = 'UI'; exports.framework = 'React'; exports.title = 'ActivityIndicator'; exports.documentationURL = 'https://reactnative.dev/docs/activityindicator'; exports.description = 'Animated loading indicators.'; exports.examples = [ { title: 'Default (small, white)', render(): Node { return ( <ActivityIndicator style={[styles.centering, styles.gray]} color="white" /> ); }, }, { title: 'Gray', render(): Node { return ( <View> <ActivityIndicator style={[styles.centering]} /> <ActivityIndicator style={[styles.centering, styles.gray]} /> </View> ); }, }, { title: 'Custom colors', render(): Node { return ( <View style={styles.horizontal}> <ActivityIndicator color="#0000ff" /> <ActivityIndicator color="#aa00aa" /> <ActivityIndicator color="#aa3300" /> <ActivityIndicator color="#00aa00" /> </View> ); }, }, { title: 'Large', render(): Node { return ( <ActivityIndicator style={[styles.centering, styles.gray]} size="large" color="white" /> ); }, }, { title: 'Large, custom colors', render(): Node { return ( <View style={styles.horizontal}> <ActivityIndicator size="large" color="#0000ff" /> <ActivityIndicator size="large" color="#aa00aa" /> <ActivityIndicator size="large" color="#aa3300" /> <ActivityIndicator size="large" color="#00aa00" /> </View> ); }, }, { title: 'Start/stop', render(): Node { return <ToggleAnimatingActivityIndicator />; }, }, { title: 'Custom size', render(): Node { return ( <ActivityIndicator style={[styles.centering, {transform: [{scale: 1.5}]}]} size="large" /> ); }, }, { platform: 'android', title: 'Custom size (size: 75)', render(): Node { return <ActivityIndicator style={styles.centering} size={75} />; }, }, ];
hoangpham95/react-native
packages/rn-tester/js/examples/ActivityIndicator/ActivityIndicatorExample.js
JavaScript
bsd-3-clause
3,613
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @providesModule takeSnapshot * @flow */ 'use strict'; const UIManager = require('UIManager'); const findNumericNodeHandle = require('findNumericNodeHandle'); /** * Capture an image of the screen, window or an individual view. The image * will be stored in a temporary file that will only exist for as long as the * app is running. * * The `view` argument can be the literal string `window` if you want to * capture the entire window, or it can be a reference to a specific * React Native component. * * The `options` argument may include: * - width/height (number) - the width and height of the image to capture. * - format (string) - either 'png' or 'jpeg'. Defaults to 'png'. * - quality (number) - the quality when using jpeg. 0.0 - 1.0 (default). * * Returns a Promise. * @platform ios */ function takeSnapshot( view?: 'window' | React$Element<any> | number, options?: { width?: number, height?: number, format?: 'png' | 'jpeg', quality?: number, }, ): Promise<any> { if (typeof view !== 'number' && view !== 'window') { view = findNumericNodeHandle(view) || 'window'; } // Call the hidden '__takeSnapshot' method; the main one throws an error to // prevent accidental backwards-incompatible usage. return UIManager.__takeSnapshot(view, options); } module.exports = takeSnapshot;
yangshun/react
src/renderers/native/takeSnapshot.js
JavaScript
bsd-3-clause
1,528
(function($, window, document) { var pluginName = 'fatNav', defaults = {}; function Plugin(options) { this.settings = $.extend({}, defaults, options); this._defaults = defaults; this._name = pluginName; this.init(); } $.extend(Plugin.prototype, { init: function() { var self = this; var $nav = this.$nav = $('.fat-nav'); var $hamburger = this.$hamburger = $('<a href="javascript:void(0)" class="hamburger"><div class="hamburger__icon"></div></a>'); this._bodyOverflow = $('body').css('overflow'); // Hack to prevent mobile safari scrolling the whole body when nav is open if (navigator.userAgent.match(/(iPad|iPhone|iPod)/g)) { $nav.children().css({ 'height': '110%', 'transform': 'translateY(-5%)' }); } $('body').append($hamburger); $().add($hamburger).add($nav.find('a')).on('click', function(e) { self.toggleNav(); }); }, toggleNav: function() { var self = this; this.$nav.fadeToggle(400); self.toggleBodyOverflow(); $().add(this.$hamburger).add(this.$nav).toggleClass('active'); }, toggleBodyOverflow: function() { var self = this; var $body = $('body'); $body.toggleClass('no-scroll'); var isNavOpen = $body.hasClass('no-scroll'); // $body.width($body.width()); $body.css('overflow', isNavOpen ? 'hidden' : self._bodyOverflow); } }); if (typeof $[pluginName] === 'undefined') { $[pluginName] = function(options) { return new Plugin(this, options); }; } }(jQuery, window, document));
wangrunxinyes/sby
frontend/plugin/include/extensions/fullscren.choices/src/js/jquery.fatNav.js
JavaScript
bsd-3-clause
2,044
// package metadata file for Meteor.js 'use strict'; var packageName = 'gromo:jquery.scrollbar'; // https://atmospherejs.com/mediatainment/switchery var where = 'client'; // where to install: 'client' or 'server'. For both, pass nothing. Package.describe({ name: packageName, version: '0.2.10', // Brief, one-line summary of the package. summary: 'Cross-browser CSS customizable scrollbar with advanced features.', // URL to the Git repository containing the source code for this package. git: '[email protected]:gromo/jquery.scrollbar.git' }); Package.onUse(function (api) { api.versionsFrom(['[email protected]', '[email protected]']); api.use('jquery', where); api.addFiles(['jquery.scrollbar.js', 'jquery.scrollbar.css'], where); }); Package.onTest(function (api) { api.use([packageName, 'sanjo:jasmine'], where); api.use(['webapp','tinytest'], where); api.addFiles('meteor/tests.js', where); // testing specific files });
aivankovich/zo
vendor/jquery.scrollbar/package.js
JavaScript
bsd-3-clause
964
Prism.languages.j={comment:{pattern:/\bNB\..*/,greedy:!0},string:{pattern:/'(?:''|[^'\r\n])*'/,greedy:!0},keyword:/\b(?:(?:CR|LF|adverb|conjunction|def|define|dyad|monad|noun|verb)\b|(?:assert|break|case|catch[dt]?|continue|do|else|elseif|end|fcase|for|for_\w+|goto_\w+|if|label_\w+|return|select|throw|try|while|whilst)\.)/,verb:{pattern:/(?!\^:|;\.|[=!][.:])(?:\{(?:\.|::?)?|p(?:\.\.?|:)|[=!\]]|[<>+*\-%$|,#][.:]?|[?^]\.?|[;\[]:?|[~}"i][.:]|[ACeEIjLor]\.|(?:[_\/\\qsux]|_?\d):)/,alias:"keyword"},number:/\b_?(?:(?!\d:)\d+(?:\.\d+)?(?:(?:ad|ar|[ejpx])_?\d+(?:\.\d+)?)*(?:b_?[\da-z]+(?:\.[\da-z]+)?)?|_\b(?!\.))/,adverb:{pattern:/[~}]|[\/\\]\.?|[bfM]\.|t[.:]/,alias:"builtin"},operator:/[=a][.:]|_\./,conjunction:{pattern:/&(?:\.:?|:)?|[.:@][.:]?|[!D][.:]|[;dHT]\.|`:?|[\^LS]:|"/,alias:"variable"},punctuation:/[()]/};
netbek/chrys
demo/vendor/prismjs/components/prism-j.min.js
JavaScript
bsd-3-clause
818
/* * zClip :: jQuery ZeroClipboard v1.1.1 * http://steamdev.com/zclip * * Copyright 2011, SteamDev * Released under the MIT license. * http://www.opensource.org/licenses/mit-license.php * * Date: Wed Jun 01, 2011 */ (function ($) { $.fn.zclip = function (params) { if (typeof params == "object" && !params.length) { var settings = $.extend({ path: 'ZeroClipboard.swf', copy: null, beforeCopy: null, afterCopy: null, clickAfter: true, setHandCursor: true, setCSSEffects: true }, params); return this.each(function () { var o = $(this); if (o.is(':visible') && (typeof settings.copy == 'string' || $.isFunction(settings.copy))) { ZeroClipboard.setMoviePath(settings.path); var clip = new ZeroClipboard.Client(); if($.isFunction(settings.copy)){ o.bind('zClip_copy',settings.copy); } if($.isFunction(settings.beforeCopy)){ o.bind('zClip_beforeCopy',settings.beforeCopy); } if($.isFunction(settings.afterCopy)){ o.bind('zClip_afterCopy',settings.afterCopy); } clip.setHandCursor(settings.setHandCursor); clip.setCSSEffects(settings.setCSSEffects); clip.addEventListener('mouseOver', function (client) { o.trigger('mouseenter'); }); clip.addEventListener('mouseOut', function (client) { o.trigger('mouseleave'); }); clip.addEventListener('mouseDown', function (client) { o.trigger('mousedown'); if(!$.isFunction(settings.copy)){ clip.setText(settings.copy); } else { clip.setText(o.triggerHandler('zClip_copy')); } if ($.isFunction(settings.beforeCopy)) { o.trigger('zClip_beforeCopy'); } }); clip.addEventListener('complete', function (client, text) { if ($.isFunction(settings.afterCopy)) { o.trigger('zClip_afterCopy'); } else { if (text.length > 500) { text = text.substr(0, 500) + "...\n\n(" + (text.length - 500) + " characters not shown)"; } o.removeClass('hover'); alert("Copied text to clipboard:\n\n " + text); } if (settings.clickAfter) { o.trigger('click'); } }); clip.glue(o[0], o.parent()[0]); $(window).bind('load resize',function(){clip.reposition();}); } }); } else if (typeof params == "string") { return this.each(function () { var o = $(this); params = params.toLowerCase(); var zclipId = o.data('zclipId'); var clipElm = $('#' + zclipId + '.zclip'); if (params == "remove") { clipElm.remove(); o.removeClass('active hover'); } else if (params == "hide") { clipElm.hide(); o.removeClass('active hover'); } else if (params == "show") { clipElm.show(); } }); } } })(jQuery); // ZeroClipboard // Simple Set Clipboard System // Author: Joseph Huckaby var ZeroClipboard = { version: "1.0.7", clients: {}, // registered upload clients on page, indexed by id moviePath: 'ZeroClipboard.swf', // URL to movie nextId: 1, // ID of next movie $: function (thingy) { // simple DOM lookup utility function if (typeof(thingy) == 'string') thingy = document.getElementById(thingy); if (!thingy.addClass) { // extend element with a few useful methods thingy.hide = function () { this.style.display = 'none'; }; thingy.show = function () { this.style.display = ''; }; thingy.addClass = function (name) { this.removeClass(name); this.className += ' ' + name; }; thingy.removeClass = function (name) { var classes = this.className.split(/\s+/); var idx = -1; for (var k = 0; k < classes.length; k++) { if (classes[k] == name) { idx = k; k = classes.length; } } if (idx > -1) { classes.splice(idx, 1); this.className = classes.join(' '); } return this; }; thingy.hasClass = function (name) { return !!this.className.match(new RegExp("\\s*" + name + "\\s*")); }; } return thingy; }, setMoviePath: function (path) { // set path to ZeroClipboard.swf this.moviePath = path; }, dispatch: function (id, eventName, args) { // receive event from flash movie, send to client var client = this.clients[id]; if (client) { client.receiveEvent(eventName, args); } }, register: function (id, client) { // register new client to receive events this.clients[id] = client; }, getDOMObjectPosition: function (obj, stopObj) { // get absolute coordinates for dom element var info = { left: 0, top: 0, width: obj.width ? obj.width : obj.offsetWidth, height: obj.height ? obj.height : obj.offsetHeight }; if (obj && (obj != stopObj)) { info.left += obj.offsetLeft; info.top += obj.offsetTop; } return info; }, Client: function (elem) { // constructor for new simple upload client this.handlers = {}; // unique ID this.id = ZeroClipboard.nextId++; this.movieId = 'ZeroClipboardMovie_' + this.id; // register client with singleton to receive flash events ZeroClipboard.register(this.id, this); // create movie if (elem) this.glue(elem); } }; ZeroClipboard.Client.prototype = { id: 0, // unique ID for us ready: false, // whether movie is ready to receive events or not movie: null, // reference to movie object clipText: '', // text to copy to clipboard handCursorEnabled: true, // whether to show hand cursor, or default pointer cursor cssEffects: true, // enable CSS mouse effects on dom container handlers: null, // user event handlers glue: function (elem, appendElem, stylesToAdd) { // glue to DOM element // elem can be ID or actual DOM element object this.domElement = ZeroClipboard.$(elem); // float just above object, or zIndex 99 if dom element isn't set var zIndex = 99; if (this.domElement.style.zIndex) { zIndex = parseInt(this.domElement.style.zIndex, 10) + 1; } if (typeof(appendElem) == 'string') { appendElem = ZeroClipboard.$(appendElem); } else if (typeof(appendElem) == 'undefined') { appendElem = document.getElementsByTagName('body')[0]; } // find X/Y position of domElement var box = ZeroClipboard.getDOMObjectPosition(this.domElement, appendElem); // create floating DIV above element this.div = document.createElement('div'); this.div.className = "zclip"; this.div.id = "zclip-" + this.movieId; $(this.domElement).data('zclipId', 'zclip-' + this.movieId); var style = this.div.style; style.position = 'absolute'; style.left = '' + box.left + 'px'; style.top = '' + box.top + 'px'; style.width = '' + box.width + 'px'; style.height = '' + box.height + 'px'; style.zIndex = zIndex; if (typeof(stylesToAdd) == 'object') { for (addedStyle in stylesToAdd) { style[addedStyle] = stylesToAdd[addedStyle]; } } // style.backgroundColor = '#f00'; // debug appendElem.appendChild(this.div); this.div.innerHTML = this.getHTML(box.width, box.height); }, getHTML: function (width, height) { // return HTML for movie var html = ''; var flashvars = 'id=' + this.id + '&width=' + width + '&height=' + height; if (navigator.userAgent.match(/MSIE/)) { // IE gets an OBJECT tag var protocol = location.href.match(/^https/i) ? 'https://' : 'http://'; html += '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="' + protocol + 'download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="' + width + '" height="' + height + '" id="' + this.movieId + '" align="middle"><param name="allowScriptAccess" value="always" /><param name="allowFullScreen" value="false" /><param name="movie" value="' + ZeroClipboard.moviePath + '" /><param name="loop" value="false" /><param name="menu" value="false" /><param name="quality" value="best" /><param name="bgcolor" value="#ffffff" /><param name="flashvars" value="' + flashvars + '"/><param name="wmode" value="transparent"/></object>'; } else { // all other browsers get an EMBED tag html += '<embed id="' + this.movieId + '" src="' + ZeroClipboard.moviePath + '" loop="false" menu="false" quality="best" bgcolor="#ffffff" width="' + width + '" height="' + height + '" name="' + this.movieId + '" align="middle" allowScriptAccess="always" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" flashvars="' + flashvars + '" wmode="transparent" />'; } return html; }, hide: function () { // temporarily hide floater offscreen if (this.div) { this.div.style.left = '-2000px'; } }, show: function () { // show ourselves after a call to hide() this.reposition(); }, destroy: function () { // destroy control and floater if (this.domElement && this.div) { this.hide(); this.div.innerHTML = ''; var body = document.getElementsByTagName('body')[0]; try { body.removeChild(this.div); } catch (e) {; } this.domElement = null; this.div = null; } }, reposition: function (elem) { // reposition our floating div, optionally to new container // warning: container CANNOT change size, only position if (elem) { this.domElement = ZeroClipboard.$(elem); if (!this.domElement) this.hide(); } if (this.domElement && this.div) { var box = ZeroClipboard.getDOMObjectPosition(this.domElement); var style = this.div.style; style.left = '' + box.left + 'px'; style.top = '' + box.top + 'px'; } }, setText: function (newText) { // set text to be copied to clipboard this.clipText = newText; if (this.ready) { this.movie.setText(newText); } }, addEventListener: function (eventName, func) { // add user event listener for event // event types: load, queueStart, fileStart, fileComplete, queueComplete, progress, error, cancel eventName = eventName.toString().toLowerCase().replace(/^on/, ''); if (!this.handlers[eventName]) { this.handlers[eventName] = []; } this.handlers[eventName].push(func); }, setHandCursor: function (enabled) { // enable hand cursor (true), or default arrow cursor (false) this.handCursorEnabled = enabled; if (this.ready) { this.movie.setHandCursor(enabled); } }, setCSSEffects: function (enabled) { // enable or disable CSS effects on DOM container this.cssEffects = !! enabled; }, receiveEvent: function (eventName, args) { // receive event from flash eventName = eventName.toString().toLowerCase().replace(/^on/, ''); // special behavior for certain events switch (eventName) { case 'load': // movie claims it is ready, but in IE this isn't always the case... // bug fix: Cannot extend EMBED DOM elements in Firefox, must use traditional function this.movie = document.getElementById(this.movieId); if (!this.movie) { var self = this; setTimeout(function () { self.receiveEvent('load', null); }, 1); return; } // firefox on pc needs a "kick" in order to set these in certain cases if (!this.ready && navigator.userAgent.match(/Firefox/) && navigator.userAgent.match(/Windows/)) { var self = this; setTimeout(function () { self.receiveEvent('load', null); }, 100); this.ready = true; return; } this.ready = true; try { this.movie.setText(this.clipText); } catch (e) {} try { this.movie.setHandCursor(this.handCursorEnabled); } catch (e) {} break; case 'mouseover': if (this.domElement && this.cssEffects) { this.domElement.addClass('hover'); if (this.recoverActive) { this.domElement.addClass('active'); } } break; case 'mouseout': if (this.domElement && this.cssEffects) { this.recoverActive = false; if (this.domElement.hasClass('active')) { this.domElement.removeClass('active'); this.recoverActive = true; } this.domElement.removeClass('hover'); } break; case 'mousedown': if (this.domElement && this.cssEffects) { this.domElement.addClass('active'); } break; case 'mouseup': if (this.domElement && this.cssEffects) { this.domElement.removeClass('active'); this.recoverActive = false; } break; } // switch eventName if (this.handlers[eventName]) { for (var idx = 0, len = this.handlers[eventName].length; idx < len; idx++) { var func = this.handlers[eventName][idx]; if (typeof(func) == 'function') { // actual function reference func(this, args); } else if ((typeof(func) == 'object') && (func.length == 2)) { // PHP style object + method, i.e. [myObject, 'myMethod'] func[0][func[1]](this, args); } else if (typeof(func) == 'string') { // name of function window[func](this, args); } } // foreach event handler defined } // user defined handler for event } };
xantage/code
vilya/static/js/lib/jquery.zclip.js
JavaScript
bsd-3-clause
16,750
var clientid = '4c3b2c1b-364c-4ceb-9416-8371dd4ebe3a'; if (/^#access_token=/.test(location.hash)) { location.assign('/Home/index?auto=1&ss=0' + '&cors=1' + '&client_id=' + clientid+ '&origins=https://webdir.online.lync.com/autodiscover/autodiscoverservice.svc/root'); } $('.loginForm').submit(function (event) { event.preventDefault(); if (location.hash == '') { location.assign('https://login.windows.net/common/oauth2/authorize?response_type=token' + '&client_id=' + clientid+ '&redirect_uri=http://healthcarenocc.azurewebsites.net/' + '&resource=https://webdir.online.lync.com'); } });
unixcbt/demos
LamnaHealthCare-Patient/obj/Release/Package/PackageTmp/Scripts/onlinesignin.js
JavaScript
bsd-3-clause
698
var vows = require('vows'), assert = require('assert'), path = require('path'), fs = require('fs'), exec = require('child_process').exec, base = path.join(__dirname, 'assets/badmodule/'), buildBase = path.join(base, 'build'), srcBase = path.join(base, 'src/foo'), rimraf = require('rimraf'); var tests = { 'clean build': { topic: function() { rimraf(path.join(buildBase, 'foo'), this.callback); }, 'should not have build dir and': { topic: function() { var self = this; fs.stat(path.join(buildBase, 'foo'), function(err) { self.callback(null, err); }); }, 'should not have build/foo': function(foo, err) { assert.isNotNull(err); assert.equal(err.code, 'ENOENT'); }, 'should build foo and': { topic: function() { var self = this, child; process.chdir(path.resolve(base, srcBase)); child = exec('../../../../../bin/shifter --no-global-config', function (error, stdout, stderr) { self.callback(null, { error: error, stderr: stderr }); }); }, 'should fail with an error code 1': function (topic) { assert.equal(topic.error.code, 1); }, 'should fail with an error message': function(topic) { assert.isNotNull(topic.stderr); } } } } }; vows.describe('building badmodule with UglifyJS via command line').addBatch(tests).export(module);
wf2/shifter
tests/14-builder-uglify-badmodule-cmd.js
JavaScript
bsd-3-clause
1,833
/* jshint multistr:true */ /* jshint -W040 */ 'use strict'; var envify = require('envify/custom'); var es3ify = require('es3ify'); var grunt = require('grunt'); var UglifyJS = require('uglify-js'); var uglifyify = require('uglifyify'); var derequire = require('derequire'); var collapser = require('bundle-collapser/plugin'); var SIMPLE_TEMPLATE = '/**\n\ * @PACKAGE@ v@VERSION@\n\ */'; var LICENSE_TEMPLATE = '/**\n\ * @PACKAGE@ v@VERSION@\n\ *\n\ * Copyright 2013-2014, Facebook, Inc.\n\ * All rights reserved.\n\ *\n\ * This source code is licensed under the BSD-style license found in the\n\ * LICENSE file in the root directory of this source tree. An additional grant\n\ * of patent rights can be found in the PATENTS file in the same directory.\n\ *\n\ */'; function minify(src) { return UglifyJS.minify(src, { fromString: true }).code; } // TODO: move this out to another build step maybe. function bannerify(src) { var version = grunt.config.data.pkg.version; var packageName = this.data.packageName || this.data.standalone; return LICENSE_TEMPLATE.replace('@PACKAGE@', packageName) .replace('@VERSION@', version) + '\n' + src; } function simpleBannerify(src) { var version = grunt.config.data.pkg.version; var packageName = this.data.packageName || this.data.standalone; return SIMPLE_TEMPLATE.replace('@PACKAGE@', packageName) .replace('@VERSION@', version) + '\n' + src; } // Our basic config which we'll add to to make our other builds var basic = { entries: [ './build/modules/React.js' ], outfile: './build/react.js', debug: false, standalone: 'React', transforms: [envify({NODE_ENV: 'development'})], plugins: [collapser], after: [es3ify.transform, derequire, simpleBannerify] }; var min = { entries: [ './build/modules/React.js' ], outfile: './build/react.min.js', debug: false, standalone: 'React', transforms: [envify({NODE_ENV: 'production'}), uglifyify], plugins: [collapser], after: [es3ify.transform, derequire, minify, bannerify] }; var transformer = { entries:[ './vendor/browser-transforms.js' ], outfile: './build/JSXTransformer.js', debug: false, standalone: 'JSXTransformer', transforms: [], plugins: [collapser], after: [es3ify.transform, derequire, simpleBannerify] }; var addons = { entries: [ './build/modules/ReactWithAddons.js' ], outfile: './build/react-with-addons.js', debug: false, standalone: 'React', packageName: 'React (with addons)', transforms: [envify({NODE_ENV: 'development'})], plugins: [collapser], after: [es3ify.transform, derequire, simpleBannerify] }; var addonsMin = { entries: [ './build/modules/ReactWithAddons.js' ], outfile: './build/react-with-addons.min.js', debug: false, standalone: 'React', packageName: 'React (with addons)', transforms: [envify({NODE_ENV: 'production'}), uglifyify], plugins: [collapser], after: [es3ify.transform, derequire, minify, bannerify] }; var withCodeCoverageLogging = { entries: [ './build/modules/React.js' ], outfile: './build/react.js', debug: true, standalone: 'React', transforms: [ envify({NODE_ENV: 'development'}), require('coverify') ], plugins: [collapser] }; module.exports = { basic: basic, min: min, transformer: transformer, addons: addons, addonsMin: addonsMin, withCodeCoverageLogging: withCodeCoverageLogging };
kchia/react
grunt/config/browserify.js
JavaScript
bsd-3-clause
3,473
(function ($) { $.Redactor.opts.langs['ua'] = { html: 'Код', video: 'Відео', image: 'Зображення', table: 'Таблиця', link: 'Посилання', link_insert: 'Вставити посилання ...', link_edit: 'Edit link', unlink: 'Видалити посилання', formatting: 'Стилі', paragraph: 'Звичайний текст', quote: 'Цитата', code: 'Код', header1: 'Заголовок 1', header2: 'Заголовок 2', header3: 'Заголовок 3', header4: 'Заголовок 4', bold: 'Жирний', italic: 'Похилий', fontcolor: 'Колір тексту', backcolor: 'Заливка тексту', unorderedlist: 'Звичайний список', orderedlist: 'Нумерований список', outdent: 'Зменшити відступ', indent: 'Збільшити відступ', cancel: 'Скасувати', insert: 'Вставити', save: 'Зберегти', _delete: 'Видалити', insert_table: 'Вставити таблицю', insert_row_above: 'Додати рядок зверху', insert_row_below: 'Додати рядок знизу', insert_column_left: 'Додати стовпець ліворуч', insert_column_right: 'Додати стовпець праворуч', delete_column: 'Видалити стовпець', delete_row: 'Видалити рядок', delete_table: 'Видалити таблицю', rows: 'Рядки', columns: 'Стовпці', add_head: 'Додати заголовок', delete_head: 'Видалити заголовок', title: 'Підказка', image_view: 'Завантажити зображення', image_position: 'Обтікання текстом', none: 'ні', left: 'ліворуч', right: 'праворуч', image_web_link: 'Посилання на зображення', text: 'Текст', mailto: 'Ел. пошта', web: 'URL', video_html_code: 'Код відео ролика', file: 'Файл', upload: 'Завантажити', download: 'Завантажити', choose: 'Вибрати', or_choose: 'Або виберіть', drop_file_here: 'Перетягніть файл сюди', align_left: 'По лівому краю', align_center: 'По центру', align_right: 'По правому краю', align_justify: 'Вирівняти текст по ширині', horizontalrule: 'Горизонтальная лінійка', fullscreen: 'На весь екран', deleted: 'Закреслений', anchor: 'Anchor', link_new_tab: 'Open link in new tab', underline: 'Underline', alignment: 'Alignment', filename: 'Name (optional)' }; })( jQuery );
elearninglondon/ematrix_2015
themes/third_party/editor/redactor/lang/ua.js
JavaScript
mit
2,697
// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors // MIT License. See license.txt $.extend(frappe.model, { docinfo: {}, sync: function(r) { /* docs: extract docs, docinfo (attachments, comments, assignments) from incoming request and set in `locals` and `frappe.model.docinfo` */ var isPlain; if(!r.docs && !r.docinfo) r = {docs:r}; isPlain = $.isPlainObject(r.docs); if(isPlain) r.docs = [r.docs]; if(r.docs) { var last_parent_name = null; for(var i=0, l=r.docs.length; i<l; i++) { var d = r.docs[i]; frappe.model.add_to_locals(d); d.__last_sync_on = new Date(); if(d.doctype==="DocType") { frappe.meta.sync(d); } if(cur_frm && cur_frm.doctype==d.doctype && cur_frm.docname==d.name) { cur_frm.doc = d; } if(d.localname) { frappe.model.new_names[d.localname] = d.name; $(document).trigger('rename', [d.doctype, d.localname, d.name]); delete locals[d.doctype][d.localname]; // update docinfo to new dict keys if(i===0) { frappe.model.docinfo[d.doctype][d.name] = frappe.model.docinfo[d.doctype][d.localname]; frappe.model.docinfo[d.doctype][d.localname] = undefined; } } } if(cur_frm && isPlain) cur_frm.dirty(); } // set docinfo (comments, assign, attachments) if(r.docinfo) { if(r.docs) { var doc = r.docs[0]; } else { if(cur_frm) var doc = cur_frm.doc; } if(doc) { if(!frappe.model.docinfo[doc.doctype]) frappe.model.docinfo[doc.doctype] = {}; frappe.model.docinfo[doc.doctype][doc.name] = r.docinfo; } } return r.docs; }, add_to_locals: function(doc) { if(!locals[doc.doctype]) locals[doc.doctype] = {}; if(!doc.name && doc.__islocal) { // get name (local if required) if(!doc.parentfield) frappe.model.clear_doc(doc); doc.name = frappe.model.get_new_name(doc.doctype); if(!doc.parentfield) frappe.provide("frappe.model.docinfo." + doc.doctype + "." + doc.name); } locals[doc.doctype][doc.name] = doc; // add child docs to locals if(!doc.parentfield) { for(var i in doc) { var value = doc[i]; if($.isArray(value)) { for (var x=0, y=value.length; x < y; x++) { var d = value[x]; if(!d.parent) d.parent = doc.name; frappe.model.add_to_locals(d); } } } } } });
bcornwellmott/frappe
frappe/public/js/frappe/model/sync.js
JavaScript
mit
2,359
export const INCREMENT_COUNTER = 'INCREMENT_COUNTER' export const DECREMENT_COUNTER = 'DECREMENT_COUNTER'
niqdev/react-redux-bootstrap4
src/modules/counter/CounterActionTypes.js
JavaScript
mit
106
var expect = require('chai').expect; var runner = require('../runner'); describe('nasm runner', function() { describe('.run', function() { it('should handle basic code evaluation (no libc)', function(done) { runner.run({ language: 'nasm', code: [ ' global _start', ' section .text', '_start:', ' mov rax, 1', ' mov rdi, 1', ' mov rsi, message', ' mov rdx, 25', ' syscall', ' mov eax, 60', ' xor rdi, rdi', ' syscall', 'message:', 'db "Hello, Netwide Assembler!", 25' ].join('\n') }, function(buffer) { expect(buffer.stdout).to.equal('Hello, Netwide Assembler!'); done(); }); }); it('should handle basic code evaluation (with libc)', function(done) { runner.run({ language: 'nasm', code: [ ' global main', ' extern puts', ' section .text', 'main:', ' mov rdi, message', ' call puts', ' ret', 'message:', 'db "Netwide Assembler together with LIBC! Let\'s Port Codewars From Rails to THIS! \\m/", 0' ].join('\n') }, function(buffer) { expect(buffer.stdout).to.equal('Netwide Assembler together with LIBC! Let\'s Port Codewars From Rails to THIS! \\m/\n'); done(); }); }); }); });
Codewars/codewars-runner
test/runners/nasm_spec.js
JavaScript
mit
1,513
/** * error handling middleware loosely based off of the connect/errorHandler code. This handler chooses * to render errors using Jade / Express instead of the manual templating used by the connect middleware * sample. This may or may not be a good idea :-) * @param options {object} array of options **/ exports = module.exports = function errorHandler(options) { options = options || {}; // defaults var showStack = options.showStack || options.stack , showMessage = options.showMessage || options.message , dumpExceptions = options.dumpExceptions || options.dump , formatUrl = options.formatUrl; return function errorHandler(err, req, res, next) { res.statusCode = 500; if(dumpExceptions) console.error(err.stack); var app = res.app; if(err instanceof exports.NotFound) { res.render('errors/404', { locals: { title: '404 - Not Found' }, status: 404 }); } else { res.render('errors/500', { locals: { title: 'The Server Encountered an Error' , error: showStack ? err : undefined }, status: 500 }); } }; }; exports.NotFound = function(msg) { this.name = 'NotFound'; Error.call(this, msg); Error.captureStackTrace(this, arguments.callee); }
brendan1mcmanus/PennApps-Fall-2015
middleware/errorHandler.js
JavaScript
mit
1,381
// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. if (!process.versions.openssl) { console.error('Skipping because node compiled without OpenSSL.'); process.exit(0); } var common = require('../common'); var assert = require('assert'); var fs = require('fs'); var tls = require('tls'); var key = fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'); var cert = fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem'); tls.createServer({ key: key, cert: cert }, function(conn) { conn.end(); this.close(); }).listen(0, function() { var options = { port: this.address().port, rejectUnauthorized: true }; tls.connect(options).on('error', common.mustCall(function(err) { assert.equal(err.code, 'UNABLE_TO_VERIFY_LEAF_SIGNATURE'); assert.equal(err.message, 'unable to verify the first certificate'); this.destroy(); })); });
ptmt/flow-declarations
test/node/test-tls-friendly-error-message.js
JavaScript
mit
1,945
Kanboard.App = function() { this.controllers = {}; }; Kanboard.App.prototype.get = function(controller) { return this.controllers[controller]; }; Kanboard.App.prototype.execute = function() { for (var className in Kanboard) { if (className !== "App") { var controller = new Kanboard[className](this); this.controllers[className] = controller; if (typeof controller.execute === "function") { controller.execute(); } if (typeof controller.listen === "function") { controller.listen(); } if (typeof controller.focus === "function") { controller.focus(); } } } this.focus(); this.datePicker(); this.autoComplete(); this.tagAutoComplete(); }; Kanboard.App.prototype.focus = function() { // Auto-select input fields $(document).on('focus', '.auto-select', function() { $(this).select(); }); // Workaround for chrome $(document).on('mouseup', '.auto-select', function(e) { e.preventDefault(); }); }; Kanboard.App.prototype.datePicker = function() { var bodyElement = $("body"); var dateFormat = bodyElement.data("js-date-format"); var timeFormat = bodyElement.data("js-time-format"); var lang = bodyElement.data("js-lang"); $.datepicker.setDefaults($.datepicker.regional[lang]); $.timepicker.setDefaults($.timepicker.regional[lang]); // Datepicker $(".form-date").datepicker({ showOtherMonths: true, selectOtherMonths: true, dateFormat: dateFormat, constrainInput: false }); // Datetime picker $(".form-datetime").datetimepicker({ dateFormat: dateFormat, timeFormat: timeFormat, constrainInput: false }); }; Kanboard.App.prototype.tagAutoComplete = function() { $(".tag-autocomplete").select2({ tags: true }); }; Kanboard.App.prototype.autoComplete = function() { $(".autocomplete").each(function() { var input = $(this); var field = input.data("dst-field"); var extraFields = input.data("dst-extra-fields"); if ($('#form-' + field).val() === '') { input.parent().find("button[type=submit]").attr('disabled','disabled'); } input.autocomplete({ source: input.data("search-url"), minLength: 1, select: function(event, ui) { $("input[name=" + field + "]").val(ui.item.id); if (extraFields) { var fields = extraFields.split(','); for (var i = 0; i < fields.length; i++) { var fieldName = fields[i].trim(); $("input[name=" + fieldName + "]").val(ui.item[fieldName]); } } input.parent().find("button[type=submit]").removeAttr('disabled'); } }); }); }; Kanboard.App.prototype.hasId = function(id) { return !!document.getElementById(id); }; Kanboard.App.prototype.showLoadingIcon = function() { $("body").append('<span id="app-loading-icon">&nbsp;<i class="fa fa-spinner fa-spin"></i></span>'); }; Kanboard.App.prototype.hideLoadingIcon = function() { $("#app-loading-icon").remove(); };
fguillot/kanboard
assets/js/src/App.js
JavaScript
mit
3,355
/* * Should * Copyright(c) 2010-2014 TJ Holowaychuk <[email protected]> * MIT Licensed */ module.exports = function(should, Assertion) { /** * Assert given object is NaN * @name NaN * @memberOf Assertion * @category assertion numbers * @example * * (10).should.not.be.NaN(); * NaN.should.be.NaN(); */ Assertion.add('NaN', function() { this.params = { operator: 'to be NaN' }; this.assert(this.obj !== this.obj); }); /** * Assert given object is not finite (positive or negative) * * @name Infinity * @memberOf Assertion * @category assertion numbers * @example * * (10).should.not.be.Infinity(); * NaN.should.not.be.Infinity(); */ Assertion.add('Infinity', function() { this.params = { operator: 'to be Infinity' }; this.is.a.Number() .and.not.a.NaN() .and.assert(!isFinite(this.obj)); }); /** * Assert given number between `start` and `finish` or equal one of them. * * @name within * @memberOf Assertion * @category assertion numbers * @param {number} start Start number * @param {number} finish Finish number * @param {string} [description] Optional message * @example * * (10).should.be.within(0, 20); */ Assertion.add('within', function(start, finish, description) { this.params = { operator: 'to be within ' + start + '..' + finish, message: description }; this.assert(this.obj >= start && this.obj <= finish); }); /** * Assert given number near some other `value` within `delta` * * @name approximately * @memberOf Assertion * @category assertion numbers * @param {number} value Center number * @param {number} delta Radius * @param {string} [description] Optional message * @example * * (9.99).should.be.approximately(10, 0.1); */ Assertion.add('approximately', function(value, delta, description) { this.params = { operator: 'to be approximately ' + value + " ±" + delta, message: description }; this.assert(Math.abs(this.obj - value) <= delta); }); /** * Assert given number above `n`. * * @name above * @alias Assertion#greaterThan * @memberOf Assertion * @category assertion numbers * @param {number} n Margin number * @param {string} [description] Optional message * @example * * (10).should.be.above(0); */ Assertion.add('above', function(n, description) { this.params = { operator: 'to be above ' + n, message: description }; this.assert(this.obj > n); }); /** * Assert given number below `n`. * * @name below * @alias Assertion#lessThan * @memberOf Assertion * @category assertion numbers * @param {number} n Margin number * @param {string} [description] Optional message * @example * * (0).should.be.below(10); */ Assertion.add('below', function(n, description) { this.params = { operator: 'to be below ' + n, message: description }; this.assert(this.obj < n); }); Assertion.alias('above', 'greaterThan'); Assertion.alias('below', 'lessThan'); };
XuanyuZhao1984/MeanJS_train1
node_modules/should/lib/ext/number.js
JavaScript
mit
3,086
'use strict'; var APPLICATION_JSON = 'application/json'; var CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': APPLICATION_JSON + ';charset=utf-8'}; var JSON_START = /^\[|^\{(?!\{)/; var JSON_ENDS = { '[': /]$/, '{': /}$/ }; var JSON_PROTECTION_PREFIX = /^\)\]\}',?\n/; var $httpMinErr = minErr('$http'); var $httpMinErrLegacyFn = function(method) { return function() { throw $httpMinErr('legacy', 'The method `{0}` on the promise returned from `$http` has been disabled.', method); }; }; function serializeValue(v) { if (isObject(v)) { return isDate(v) ? v.toISOString() : toJson(v); } return v; } function $HttpParamSerializerProvider() { /** * @ngdoc service * @name $httpParamSerializer * @description * * Default {@link $http `$http`} params serializer that converts objects to strings * according to the following rules: * * * `{'foo': 'bar'}` results in `foo=bar` * * `{'foo': Date.now()}` results in `foo=2015-04-01T09%3A50%3A49.262Z` (`toISOString()` and encoded representation of a Date object) * * `{'foo': ['bar', 'baz']}` results in `foo=bar&foo=baz` (repeated key for each array element) * * `{'foo': {'bar':'baz'}}` results in `foo=%7B%22bar%22%3A%22baz%22%7D"` (stringified and encoded representation of an object) * * Note that serializer will sort the request parameters alphabetically. * */ this.$get = function() { return function ngParamSerializer(params) { if (!params) return ''; var parts = []; forEachSorted(params, function(value, key) { if (value === null || isUndefined(value)) return; if (isArray(value)) { forEach(value, function(v, k) { parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(v))); }); } else { parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(value))); } }); return parts.join('&'); }; }; } function $HttpParamSerializerJQLikeProvider() { /** * @ngdoc service * @name $httpParamSerializerJQLike * @description * * Alternative {@link $http `$http`} params serializer that follows * jQuery's [`param()`](http://api.jquery.com/jquery.param/) method logic. * The serializer will also sort the params alphabetically. * * To use it for serializing `$http` request parameters, set it as the `paramSerializer` property: * * ```js * $http({ * url: myUrl, * method: 'GET', * params: myParams, * paramSerializer: '$httpParamSerializerJQLike' * }); * ``` * * It is also possible to set it as the default `paramSerializer` in the * {@link $httpProvider#defaults `$httpProvider`}. * * Additionally, you can inject the serializer and use it explicitly, for example to serialize * form data for submission: * * ```js * .controller(function($http, $httpParamSerializerJQLike) { * //... * * $http({ * url: myUrl, * method: 'POST', * data: $httpParamSerializerJQLike(myData), * headers: { * 'Content-Type': 'application/x-www-form-urlencoded' * } * }); * * }); * ``` * * */ this.$get = function() { return function jQueryLikeParamSerializer(params) { if (!params) return ''; var parts = []; serialize(params, '', true); return parts.join('&'); function serialize(toSerialize, prefix, topLevel) { if (toSerialize === null || isUndefined(toSerialize)) return; if (isArray(toSerialize)) { forEach(toSerialize, function(value, index) { serialize(value, prefix + '[' + (isObject(value) ? index : '') + ']'); }); } else if (isObject(toSerialize) && !isDate(toSerialize)) { forEachSorted(toSerialize, function(value, key) { serialize(value, prefix + (topLevel ? '' : '[') + key + (topLevel ? '' : ']')); }); } else { parts.push(encodeUriQuery(prefix) + '=' + encodeUriQuery(serializeValue(toSerialize))); } } }; }; } function defaultHttpResponseTransform(data, headers) { if (isString(data)) { // Strip json vulnerability protection prefix and trim whitespace var tempData = data.replace(JSON_PROTECTION_PREFIX, '').trim(); if (tempData) { var contentType = headers('Content-Type'); if ((contentType && (contentType.indexOf(APPLICATION_JSON) === 0)) || isJsonLike(tempData)) { data = fromJson(tempData); } } } return data; } function isJsonLike(str) { var jsonStart = str.match(JSON_START); return jsonStart && JSON_ENDS[jsonStart[0]].test(str); } /** * Parse headers into key value object * * @param {string} headers Raw headers as a string * @returns {Object} Parsed headers as key value object */ function parseHeaders(headers) { var parsed = createMap(), i; function fillInParsed(key, val) { if (key) { parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val; } } if (isString(headers)) { forEach(headers.split('\n'), function(line) { i = line.indexOf(':'); fillInParsed(lowercase(trim(line.substr(0, i))), trim(line.substr(i + 1))); }); } else if (isObject(headers)) { forEach(headers, function(headerVal, headerKey) { fillInParsed(lowercase(headerKey), trim(headerVal)); }); } return parsed; } /** * Returns a function that provides access to parsed headers. * * Headers are lazy parsed when first requested. * @see parseHeaders * * @param {(string|Object)} headers Headers to provide access to. * @returns {function(string=)} Returns a getter function which if called with: * * - if called with single an argument returns a single header value or null * - if called with no arguments returns an object containing all headers. */ function headersGetter(headers) { var headersObj; return function(name) { if (!headersObj) headersObj = parseHeaders(headers); if (name) { var value = headersObj[lowercase(name)]; if (value === void 0) { value = null; } return value; } return headersObj; }; } /** * Chain all given functions * * This function is used for both request and response transforming * * @param {*} data Data to transform. * @param {function(string=)} headers HTTP headers getter fn. * @param {number} status HTTP status code of the response. * @param {(Function|Array.<Function>)} fns Function or an array of functions. * @returns {*} Transformed data. */ function transformData(data, headers, status, fns) { if (isFunction(fns)) { return fns(data, headers, status); } forEach(fns, function(fn) { data = fn(data, headers, status); }); return data; } function isSuccess(status) { return 200 <= status && status < 300; } /** * @ngdoc provider * @name $httpProvider * @description * Use `$httpProvider` to change the default behavior of the {@link ng.$http $http} service. * */ function $HttpProvider() { /** * @ngdoc property * @name $httpProvider#defaults * @description * * Object containing default values for all {@link ng.$http $http} requests. * * - **`defaults.cache`** - {Object} - an object built with {@link ng.$cacheFactory `$cacheFactory`} * that will provide the cache for all requests who set their `cache` property to `true`. * If you set the `defaults.cache = false` then only requests that specify their own custom * cache object will be cached. See {@link $http#caching $http Caching} for more information. * * - **`defaults.xsrfCookieName`** - {string} - Name of cookie containing the XSRF token. * Defaults value is `'XSRF-TOKEN'`. * * - **`defaults.xsrfHeaderName`** - {string} - Name of HTTP header to populate with the * XSRF token. Defaults value is `'X-XSRF-TOKEN'`. * * - **`defaults.headers`** - {Object} - Default headers for all $http requests. * Refer to {@link ng.$http#setting-http-headers $http} for documentation on * setting default headers. * - **`defaults.headers.common`** * - **`defaults.headers.post`** * - **`defaults.headers.put`** * - **`defaults.headers.patch`** * * * - **`defaults.paramSerializer`** - `{string|function(Object<string,string>):string}` - A function * used to the prepare string representation of request parameters (specified as an object). * If specified as string, it is interpreted as a function registered with the {@link auto.$injector $injector}. * Defaults to {@link ng.$httpParamSerializer $httpParamSerializer}. * **/ var defaults = this.defaults = { // transform incoming response data transformResponse: [defaultHttpResponseTransform], // transform outgoing request data transformRequest: [function(d) { return isObject(d) && !isFile(d) && !isBlob(d) && !isFormData(d) ? toJson(d) : d; }], // default headers headers: { common: { 'Accept': 'application/json, text/plain, */*' }, post: shallowCopy(CONTENT_TYPE_APPLICATION_JSON), put: shallowCopy(CONTENT_TYPE_APPLICATION_JSON), patch: shallowCopy(CONTENT_TYPE_APPLICATION_JSON) }, xsrfCookieName: 'XSRF-TOKEN', xsrfHeaderName: 'X-XSRF-TOKEN', paramSerializer: '$httpParamSerializer' }; var useApplyAsync = false; /** * @ngdoc method * @name $httpProvider#useApplyAsync * @description * * Configure $http service to combine processing of multiple http responses received at around * the same time via {@link ng.$rootScope.Scope#$applyAsync $rootScope.$applyAsync}. This can result in * significant performance improvement for bigger applications that make many HTTP requests * concurrently (common during application bootstrap). * * Defaults to false. If no value is specified, returns the current configured value. * * @param {boolean=} value If true, when requests are loaded, they will schedule a deferred * "apply" on the next tick, giving time for subsequent requests in a roughly ~10ms window * to load and share the same digest cycle. * * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining. * otherwise, returns the current configured value. **/ this.useApplyAsync = function(value) { if (isDefined(value)) { useApplyAsync = !!value; return this; } return useApplyAsync; }; var useLegacyPromise = true; /** * @ngdoc method * @name $httpProvider#useLegacyPromiseExtensions * @description * * Configure `$http` service to return promises without the shorthand methods `success` and `error`. * This should be used to make sure that applications work without these methods. * * Defaults to true. If no value is specified, returns the current configured value. * * @param {boolean=} value If true, `$http` will return a promise with the deprecated legacy `success` and `error` methods. * * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining. * otherwise, returns the current configured value. **/ this.useLegacyPromiseExtensions = function(value) { if (isDefined(value)) { useLegacyPromise = !!value; return this; } return useLegacyPromise; }; /** * @ngdoc property * @name $httpProvider#interceptors * @description * * Array containing service factories for all synchronous or asynchronous {@link ng.$http $http} * pre-processing of request or postprocessing of responses. * * These service factories are ordered by request, i.e. they are applied in the same order as the * array, on request, but reverse order, on response. * * {@link ng.$http#interceptors Interceptors detailed info} **/ var interceptorFactories = this.interceptors = []; this.$get = ['$httpBackend', '$$cookieReader', '$cacheFactory', '$rootScope', '$q', '$injector', function($httpBackend, $$cookieReader, $cacheFactory, $rootScope, $q, $injector) { var defaultCache = $cacheFactory('$http'); /** * Make sure that default param serializer is exposed as a function */ defaults.paramSerializer = isString(defaults.paramSerializer) ? $injector.get(defaults.paramSerializer) : defaults.paramSerializer; /** * Interceptors stored in reverse order. Inner interceptors before outer interceptors. * The reversal is needed so that we can build up the interception chain around the * server request. */ var reversedInterceptors = []; forEach(interceptorFactories, function(interceptorFactory) { reversedInterceptors.unshift(isString(interceptorFactory) ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory)); }); /** * @ngdoc service * @kind function * @name $http * @requires ng.$httpBackend * @requires $cacheFactory * @requires $rootScope * @requires $q * @requires $injector * * @description * The `$http` service is a core Angular service that facilitates communication with the remote * HTTP servers via the browser's [XMLHttpRequest](https://developer.mozilla.org/en/xmlhttprequest) * object or via [JSONP](http://en.wikipedia.org/wiki/JSONP). * * For unit testing applications that use `$http` service, see * {@link ngMock.$httpBackend $httpBackend mock}. * * For a higher level of abstraction, please check out the {@link ngResource.$resource * $resource} service. * * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by * the $q service. While for simple usage patterns this doesn't matter much, for advanced usage * it is important to familiarize yourself with these APIs and the guarantees they provide. * * * ## General usage * The `$http` service is a function which takes a single argument — a {@link $http#usage configuration object} — * that is used to generate an HTTP request and returns a {@link ng.$q promise}. * * ```js * // Simple GET request example: * $http({ * method: 'GET', * url: '/someUrl' * }).then(function successCallback(response) { * // this callback will be called asynchronously * // when the response is available * }, function errorCallback(response) { * // called asynchronously if an error occurs * // or server returns response with an error status. * }); * ``` * * The response object has these properties: * * - **data** – `{string|Object}` – The response body transformed with the transform * functions. * - **status** – `{number}` – HTTP status code of the response. * - **headers** – `{function([headerName])}` – Header getter function. * - **config** – `{Object}` – The configuration object that was used to generate the request. * - **statusText** – `{string}` – HTTP status text of the response. * * A response status code between 200 and 299 is considered a success status and * will result in the success callback being called. Note that if the response is a redirect, * XMLHttpRequest will transparently follow it, meaning that the error callback will not be * called for such responses. * * * ## Shortcut methods * * Shortcut methods are also available. All shortcut methods require passing in the URL, and * request data must be passed in for POST/PUT requests. An optional config can be passed as the * last argument. * * ```js * $http.get('/someUrl', config).then(successCallback, errorCallback); * $http.post('/someUrl', data, config).then(successCallback, errorCallback); * ``` * * Complete list of shortcut methods: * * - {@link ng.$http#get $http.get} * - {@link ng.$http#head $http.head} * - {@link ng.$http#post $http.post} * - {@link ng.$http#put $http.put} * - {@link ng.$http#delete $http.delete} * - {@link ng.$http#jsonp $http.jsonp} * - {@link ng.$http#patch $http.patch} * * * ## Writing Unit Tests that use $http * When unit testing (using {@link ngMock ngMock}), it is necessary to call * {@link ngMock.$httpBackend#flush $httpBackend.flush()} to flush each pending * request using trained responses. * * ``` * $httpBackend.expectGET(...); * $http.get(...); * $httpBackend.flush(); * ``` * * ## Deprecation Notice * <div class="alert alert-danger"> * The `$http` legacy promise methods `success` and `error` have been deprecated. * Use the standard `then` method instead. * If {@link $httpProvider#useLegacyPromiseExtensions `$httpProvider.useLegacyPromiseExtensions`} is set to * `false` then these methods will throw {@link $http:legacy `$http/legacy`} error. * </div> * * ## Setting HTTP Headers * * The $http service will automatically add certain HTTP headers to all requests. These defaults * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration * object, which currently contains this default configuration: * * - `$httpProvider.defaults.headers.common` (headers that are common for all requests): * - `Accept: application/json, text/plain, * / *` * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests) * - `Content-Type: application/json` * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests) * - `Content-Type: application/json` * * To add or overwrite these defaults, simply add or remove a property from these configuration * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object * with the lowercased HTTP method name as the key, e.g. * `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }`. * * The defaults can also be set at runtime via the `$http.defaults` object in the same * fashion. For example: * * ``` * module.run(function($http) { * $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w' * }); * ``` * * In addition, you can supply a `headers` property in the config object passed when * calling `$http(config)`, which overrides the defaults without changing them globally. * * To explicitly remove a header automatically added via $httpProvider.defaults.headers on a per request basis, * Use the `headers` property, setting the desired header to `undefined`. For example: * * ```js * var req = { * method: 'POST', * url: 'http://example.com', * headers: { * 'Content-Type': undefined * }, * data: { test: 'test' } * } * * $http(req).then(function(){...}, function(){...}); * ``` * * ## Transforming Requests and Responses * * Both requests and responses can be transformed using transformation functions: `transformRequest` * and `transformResponse`. These properties can be a single function that returns * the transformed value (`function(data, headersGetter, status)`) or an array of such transformation functions, * which allows you to `push` or `unshift` a new transformation function into the transformation chain. * * ### Default Transformations * * The `$httpProvider` provider and `$http` service expose `defaults.transformRequest` and * `defaults.transformResponse` properties. If a request does not provide its own transformations * then these will be applied. * * You can augment or replace the default transformations by modifying these properties by adding to or * replacing the array. * * Angular provides the following default transformations: * * Request transformations (`$httpProvider.defaults.transformRequest` and `$http.defaults.transformRequest`): * * - If the `data` property of the request configuration object contains an object, serialize it * into JSON format. * * Response transformations (`$httpProvider.defaults.transformResponse` and `$http.defaults.transformResponse`): * * - If XSRF prefix is detected, strip it (see Security Considerations section below). * - If JSON response is detected, deserialize it using a JSON parser. * * * ### Overriding the Default Transformations Per Request * * If you wish override the request/response transformations only for a single request then provide * `transformRequest` and/or `transformResponse` properties on the configuration object passed * into `$http`. * * Note that if you provide these properties on the config object the default transformations will be * overwritten. If you wish to augment the default transformations then you must include them in your * local transformation array. * * The following code demonstrates adding a new response transformation to be run after the default response * transformations have been run. * * ```js * function appendTransform(defaults, transform) { * * // We can't guarantee that the default transformation is an array * defaults = angular.isArray(defaults) ? defaults : [defaults]; * * // Append the new transformation to the defaults * return defaults.concat(transform); * } * * $http({ * url: '...', * method: 'GET', * transformResponse: appendTransform($http.defaults.transformResponse, function(value) { * return doTransform(value); * }) * }); * ``` * * * ## Caching * * To enable caching, set the request configuration `cache` property to `true` (to use default * cache) or to a custom cache object (built with {@link ng.$cacheFactory `$cacheFactory`}). * When the cache is enabled, `$http` stores the response from the server in the specified * cache. The next time the same request is made, the response is served from the cache without * sending a request to the server. * * Note that even if the response is served from cache, delivery of the data is asynchronous in * the same way that real requests are. * * If there are multiple GET requests for the same URL that should be cached using the same * cache, but the cache is not populated yet, only one request to the server will be made and * the remaining requests will be fulfilled using the response from the first request. * * You can change the default cache to a new object (built with * {@link ng.$cacheFactory `$cacheFactory`}) by updating the * {@link ng.$http#defaults `$http.defaults.cache`} property. All requests who set * their `cache` property to `true` will now use this cache object. * * If you set the default cache to `false` then only requests that specify their own custom * cache object will be cached. * * ## Interceptors * * Before you start creating interceptors, be sure to understand the * {@link ng.$q $q and deferred/promise APIs}. * * For purposes of global error handling, authentication, or any kind of synchronous or * asynchronous pre-processing of request or postprocessing of responses, it is desirable to be * able to intercept requests before they are handed to the server and * responses before they are handed over to the application code that * initiated these requests. The interceptors leverage the {@link ng.$q * promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing. * * The interceptors are service factories that are registered with the `$httpProvider` by * adding them to the `$httpProvider.interceptors` array. The factory is called and * injected with dependencies (if specified) and returns the interceptor. * * There are two kinds of interceptors (and two kinds of rejection interceptors): * * * `request`: interceptors get called with a http {@link $http#usage config} object. The function is free to * modify the `config` object or create a new one. The function needs to return the `config` * object directly, or a promise containing the `config` or a new `config` object. * * `requestError`: interceptor gets called when a previous interceptor threw an error or * resolved with a rejection. * * `response`: interceptors get called with http `response` object. The function is free to * modify the `response` object or create a new one. The function needs to return the `response` * object directly, or as a promise containing the `response` or a new `response` object. * * `responseError`: interceptor gets called when a previous interceptor threw an error or * resolved with a rejection. * * * ```js * // register the interceptor as a service * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) { * return { * // optional method * 'request': function(config) { * // do something on success * return config; * }, * * // optional method * 'requestError': function(rejection) { * // do something on error * if (canRecover(rejection)) { * return responseOrNewPromise * } * return $q.reject(rejection); * }, * * * * // optional method * 'response': function(response) { * // do something on success * return response; * }, * * // optional method * 'responseError': function(rejection) { * // do something on error * if (canRecover(rejection)) { * return responseOrNewPromise * } * return $q.reject(rejection); * } * }; * }); * * $httpProvider.interceptors.push('myHttpInterceptor'); * * * // alternatively, register the interceptor via an anonymous factory * $httpProvider.interceptors.push(function($q, dependency1, dependency2) { * return { * 'request': function(config) { * // same as above * }, * * 'response': function(response) { * // same as above * } * }; * }); * ``` * * ## Security Considerations * * When designing web applications, consider security threats from: * * - [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx) * - [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) * * Both server and the client must cooperate in order to eliminate these threats. Angular comes * pre-configured with strategies that address these issues, but for this to work backend server * cooperation is required. * * ### JSON Vulnerability Protection * * A [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx) * allows third party website to turn your JSON resource URL into * [JSONP](http://en.wikipedia.org/wiki/JSONP) request under some conditions. To * counter this your server can prefix all JSON requests with following string `")]}',\n"`. * Angular will automatically strip the prefix before processing it as JSON. * * For example if your server needs to return: * ```js * ['one','two'] * ``` * * which is vulnerable to attack, your server can return: * ```js * )]}', * ['one','two'] * ``` * * Angular will strip the prefix, before processing the JSON. * * * ### Cross Site Request Forgery (XSRF) Protection * * [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) is a technique by which * an unauthorized site can gain your user's private data. Angular provides a mechanism * to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie * (by default, `XSRF-TOKEN`) and sets it as an HTTP header (`X-XSRF-TOKEN`). Since only * JavaScript that runs on your domain could read the cookie, your server can be assured that * the XHR came from JavaScript running on your domain. The header will not be set for * cross-domain requests. * * To take advantage of this, your server needs to set a token in a JavaScript readable session * cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure * that only JavaScript running on your domain could have sent the request. The token must be * unique for each user and must be verifiable by the server (to prevent the JavaScript from * making up its own tokens). We recommend that the token is a digest of your site's * authentication cookie with a [salt](https://en.wikipedia.org/wiki/Salt_(cryptography&#41;) * for added security. * * The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName * properties of either $httpProvider.defaults at config-time, $http.defaults at run-time, * or the per-request config object. * * In order to prevent collisions in environments where multiple Angular apps share the * same domain or subdomain, we recommend that each application uses unique cookie name. * * @param {object} config Object describing the request to be made and how it should be * processed. The object has following properties: * * - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc) * - **url** – `{string}` – Absolute or relative URL of the resource that is being requested. * - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be serialized * with the `paramSerializer` and appended as GET parameters. * - **data** – `{string|Object}` – Data to be sent as the request message data. * - **headers** – `{Object}` – Map of strings or functions which return strings representing * HTTP headers to send to the server. If the return value of a function is null, the * header will not be sent. Functions accept a config object as an argument. * - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token. * - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token. * - **transformRequest** – * `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` – * transform function or an array of such functions. The transform function takes the http * request body and headers and returns its transformed (typically serialized) version. * See {@link ng.$http#overriding-the-default-transformations-per-request * Overriding the Default Transformations} * - **transformResponse** – * `{function(data, headersGetter, status)|Array.<function(data, headersGetter, status)>}` – * transform function or an array of such functions. The transform function takes the http * response body, headers and status and returns its transformed (typically deserialized) version. * See {@link ng.$http#overriding-the-default-transformations-per-request * Overriding the Default TransformationjqLiks} * - **paramSerializer** - `{string|function(Object<string,string>):string}` - A function used to * prepare the string representation of request parameters (specified as an object). * If specified as string, it is interpreted as function registered with the * {@link $injector $injector}, which means you can create your own serializer * by registering it as a {@link auto.$provide#service service}. * The default serializer is the {@link $httpParamSerializer $httpParamSerializer}; * alternatively, you can use the {@link $httpParamSerializerJQLike $httpParamSerializerJQLike} * - **cache** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the * GET request, otherwise if a cache instance built with * {@link ng.$cacheFactory $cacheFactory}, this cache will be used for * caching. * - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise} * that should abort the request when resolved. * - **withCredentials** - `{boolean}` - whether to set the `withCredentials` flag on the * XHR object. See [requests with credentials](https://developer.mozilla.org/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials) * for more information. * - **responseType** - `{string}` - see * [XMLHttpRequest.responseType](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#xmlhttprequest-responsetype). * * @returns {HttpPromise} Returns a {@link ng.$q `Promise}` that will be resolved to a response object * when the request succeeds or fails. * * * @property {Array.<Object>} pendingRequests Array of config objects for currently pending * requests. This is primarily meant to be used for debugging purposes. * * * @example <example module="httpExample"> <file name="index.html"> <div ng-controller="FetchController"> <select ng-model="method" aria-label="Request method"> <option>GET</option> <option>JSONP</option> </select> <input type="text" ng-model="url" size="80" aria-label="URL" /> <button id="fetchbtn" ng-click="fetch()">fetch</button><br> <button id="samplegetbtn" ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button> <button id="samplejsonpbtn" ng-click="updateModel('JSONP', 'https://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')"> Sample JSONP </button> <button id="invalidjsonpbtn" ng-click="updateModel('JSONP', 'https://angularjs.org/doesntexist&callback=JSON_CALLBACK')"> Invalid JSONP </button> <pre>http status code: {{status}}</pre> <pre>http response data: {{data}}</pre> </div> </file> <file name="script.js"> angular.module('httpExample', []) .controller('FetchController', ['$scope', '$http', '$templateCache', function($scope, $http, $templateCache) { $scope.method = 'GET'; $scope.url = 'http-hello.html'; $scope.fetch = function() { $scope.code = null; $scope.response = null; $http({method: $scope.method, url: $scope.url, cache: $templateCache}). then(function(response) { $scope.status = response.status; $scope.data = response.data; }, function(response) { $scope.data = response.data || "Request failed"; $scope.status = response.status; }); }; $scope.updateModel = function(method, url) { $scope.method = method; $scope.url = url; }; }]); </file> <file name="http-hello.html"> Hello, $http! </file> <file name="protractor.js" type="protractor"> var status = element(by.binding('status')); var data = element(by.binding('data')); var fetchBtn = element(by.id('fetchbtn')); var sampleGetBtn = element(by.id('samplegetbtn')); var sampleJsonpBtn = element(by.id('samplejsonpbtn')); var invalidJsonpBtn = element(by.id('invalidjsonpbtn')); it('should make an xhr GET request', function() { sampleGetBtn.click(); fetchBtn.click(); expect(status.getText()).toMatch('200'); expect(data.getText()).toMatch(/Hello, \$http!/); }); // Commented out due to flakes. See https://github.com/angular/angular.js/issues/9185 // it('should make a JSONP request to angularjs.org', function() { // sampleJsonpBtn.click(); // fetchBtn.click(); // expect(status.getText()).toMatch('200'); // expect(data.getText()).toMatch(/Super Hero!/); // }); it('should make JSONP request to invalid URL and invoke the error handler', function() { invalidJsonpBtn.click(); fetchBtn.click(); expect(status.getText()).toMatch('0'); expect(data.getText()).toMatch('Request failed'); }); </file> </example> */ function $http(requestConfig) { if (!isObject(requestConfig)) { throw minErr('$http')('badreq', 'Http request configuration must be an object. Received: {0}', requestConfig); } var config = extend({ method: 'get', transformRequest: defaults.transformRequest, transformResponse: defaults.transformResponse, paramSerializer: defaults.paramSerializer }, requestConfig); config.headers = mergeHeaders(requestConfig); config.method = uppercase(config.method); config.paramSerializer = isString(config.paramSerializer) ? $injector.get(config.paramSerializer) : config.paramSerializer; var serverRequest = function(config) { var headers = config.headers; var reqData = transformData(config.data, headersGetter(headers), undefined, config.transformRequest); // strip content-type if data is undefined if (isUndefined(reqData)) { forEach(headers, function(value, header) { if (lowercase(header) === 'content-type') { delete headers[header]; } }); } if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) { config.withCredentials = defaults.withCredentials; } // send request return sendReq(config, reqData).then(transformResponse, transformResponse); }; var chain = [serverRequest, undefined]; var promise = $q.when(config); // apply interceptors forEach(reversedInterceptors, function(interceptor) { if (interceptor.request || interceptor.requestError) { chain.unshift(interceptor.request, interceptor.requestError); } if (interceptor.response || interceptor.responseError) { chain.push(interceptor.response, interceptor.responseError); } }); while (chain.length) { var thenFn = chain.shift(); var rejectFn = chain.shift(); promise = promise.then(thenFn, rejectFn); } if (useLegacyPromise) { promise.success = function(fn) { assertArgFn(fn, 'fn'); promise.then(function(response) { fn(response.data, response.status, response.headers, config); }); return promise; }; promise.error = function(fn) { assertArgFn(fn, 'fn'); promise.then(null, function(response) { fn(response.data, response.status, response.headers, config); }); return promise; }; } else { promise.success = $httpMinErrLegacyFn('success'); promise.error = $httpMinErrLegacyFn('error'); } return promise; function transformResponse(response) { // make a copy since the response must be cacheable var resp = extend({}, response); resp.data = transformData(response.data, response.headers, response.status, config.transformResponse); return (isSuccess(response.status)) ? resp : $q.reject(resp); } function executeHeaderFns(headers, config) { var headerContent, processedHeaders = {}; forEach(headers, function(headerFn, header) { if (isFunction(headerFn)) { headerContent = headerFn(config); if (headerContent != null) { processedHeaders[header] = headerContent; } } else { processedHeaders[header] = headerFn; } }); return processedHeaders; } function mergeHeaders(config) { var defHeaders = defaults.headers, reqHeaders = extend({}, config.headers), defHeaderName, lowercaseDefHeaderName, reqHeaderName; defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]); // using for-in instead of forEach to avoid unecessary iteration after header has been found defaultHeadersIteration: for (defHeaderName in defHeaders) { lowercaseDefHeaderName = lowercase(defHeaderName); for (reqHeaderName in reqHeaders) { if (lowercase(reqHeaderName) === lowercaseDefHeaderName) { continue defaultHeadersIteration; } } reqHeaders[defHeaderName] = defHeaders[defHeaderName]; } // execute if header value is a function for merged headers return executeHeaderFns(reqHeaders, shallowCopy(config)); } } $http.pendingRequests = []; /** * @ngdoc method * @name $http#get * * @description * Shortcut method to perform `GET` request. * * @param {string} url Relative or absolute URL specifying the destination of the request * @param {Object=} config Optional configuration object * @returns {HttpPromise} Future object */ /** * @ngdoc method * @name $http#delete * * @description * Shortcut method to perform `DELETE` request. * * @param {string} url Relative or absolute URL specifying the destination of the request * @param {Object=} config Optional configuration object * @returns {HttpPromise} Future object */ /** * @ngdoc method * @name $http#head * * @description * Shortcut method to perform `HEAD` request. * * @param {string} url Relative or absolute URL specifying the destination of the request * @param {Object=} config Optional configuration object * @returns {HttpPromise} Future object */ /** * @ngdoc method * @name $http#jsonp * * @description * Shortcut method to perform `JSONP` request. * * @param {string} url Relative or absolute URL specifying the destination of the request. * The name of the callback should be the string `JSON_CALLBACK`. * @param {Object=} config Optional configuration object * @returns {HttpPromise} Future object */ createShortMethods('get', 'delete', 'head', 'jsonp'); /** * @ngdoc method * @name $http#post * * @description * Shortcut method to perform `POST` request. * * @param {string} url Relative or absolute URL specifying the destination of the request * @param {*} data Request content * @param {Object=} config Optional configuration object * @returns {HttpPromise} Future object */ /** * @ngdoc method * @name $http#put * * @description * Shortcut method to perform `PUT` request. * * @param {string} url Relative or absolute URL specifying the destination of the request * @param {*} data Request content * @param {Object=} config Optional configuration object * @returns {HttpPromise} Future object */ /** * @ngdoc method * @name $http#patch * * @description * Shortcut method to perform `PATCH` request. * * @param {string} url Relative or absolute URL specifying the destination of the request * @param {*} data Request content * @param {Object=} config Optional configuration object * @returns {HttpPromise} Future object */ createShortMethodsWithData('post', 'put', 'patch'); /** * @ngdoc property * @name $http#defaults * * @description * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of * default headers, withCredentials as well as request and response transformations. * * See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above. */ $http.defaults = defaults; return $http; function createShortMethods(names) { forEach(arguments, function(name) { $http[name] = function(url, config) { return $http(extend({}, config || {}, { method: name, url: url })); }; }); } function createShortMethodsWithData(name) { forEach(arguments, function(name) { $http[name] = function(url, data, config) { return $http(extend({}, config || {}, { method: name, url: url, data: data })); }; }); } /** * Makes the request. * * !!! ACCESSES CLOSURE VARS: * $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests */ function sendReq(config, reqData) { var deferred = $q.defer(), promise = deferred.promise, cache, cachedResp, reqHeaders = config.headers, url = buildUrl(config.url, config.paramSerializer(config.params)); $http.pendingRequests.push(config); promise.then(removePendingReq, removePendingReq); if ((config.cache || defaults.cache) && config.cache !== false && (config.method === 'GET' || config.method === 'JSONP')) { cache = isObject(config.cache) ? config.cache : isObject(defaults.cache) ? defaults.cache : defaultCache; } if (cache) { cachedResp = cache.get(url); if (isDefined(cachedResp)) { if (isPromiseLike(cachedResp)) { // cached request has already been sent, but there is no response yet cachedResp.then(resolvePromiseWithResult, resolvePromiseWithResult); } else { // serving from cache if (isArray(cachedResp)) { resolvePromise(cachedResp[1], cachedResp[0], shallowCopy(cachedResp[2]), cachedResp[3]); } else { resolvePromise(cachedResp, 200, {}, 'OK'); } } } else { // put the promise for the non-transformed response into cache as a placeholder cache.put(url, promise); } } // if we won't have the response in cache, set the xsrf headers and // send the request to the backend if (isUndefined(cachedResp)) { var xsrfValue = urlIsSameOrigin(config.url) ? $$cookieReader()[config.xsrfCookieName || defaults.xsrfCookieName] : undefined; if (xsrfValue) { reqHeaders[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue; } $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout, config.withCredentials, config.responseType); } return promise; /** * Callback registered to $httpBackend(): * - caches the response if desired * - resolves the raw $http promise * - calls $apply */ function done(status, response, headersString, statusText) { if (cache) { if (isSuccess(status)) { cache.put(url, [status, response, parseHeaders(headersString), statusText]); } else { // remove promise from the cache cache.remove(url); } } function resolveHttpPromise() { resolvePromise(response, status, headersString, statusText); } if (useApplyAsync) { $rootScope.$applyAsync(resolveHttpPromise); } else { resolveHttpPromise(); if (!$rootScope.$$phase) $rootScope.$apply(); } } /** * Resolves the raw $http promise. */ function resolvePromise(response, status, headers, statusText) { //status: HTTP response status code, 0, -1 (aborted by timeout / promise) status = status >= -1 ? status : 0; (isSuccess(status) ? deferred.resolve : deferred.reject)({ data: response, status: status, headers: headersGetter(headers), config: config, statusText: statusText }); } function resolvePromiseWithResult(result) { resolvePromise(result.data, result.status, shallowCopy(result.headers()), result.statusText); } function removePendingReq() { var idx = $http.pendingRequests.indexOf(config); if (idx !== -1) $http.pendingRequests.splice(idx, 1); } } function buildUrl(url, serializedParams) { if (serializedParams.length > 0) { url += ((url.indexOf('?') == -1) ? '?' : '&') + serializedParams; } return url; } }]; }
evil-wolf/angular.js
src/ng/http.js
JavaScript
mit
49,570
import { run } from '@ember/runloop'; import { guidFor, setName } from 'ember-utils'; import { context } from 'ember-environment'; import EmberObject from '../../../lib/system/object'; import Namespace from '../../../lib/system/namespace'; import { moduleFor, AbstractTestCase } from 'internal-test-helpers'; let originalLookup = context.lookup; let lookup; moduleFor( 'system/object/toString', class extends AbstractTestCase { beforeEach() { context.lookup = lookup = {}; } afterEach() { context.lookup = originalLookup; } ['@test toString() returns the same value if called twice'](assert) { let Foo = Namespace.create(); Foo.toString = function() { return 'Foo'; }; Foo.Bar = EmberObject.extend(); assert.equal(Foo.Bar.toString(), 'Foo.Bar'); assert.equal(Foo.Bar.toString(), 'Foo.Bar'); let obj = Foo.Bar.create(); assert.equal(obj.toString(), '<Foo.Bar:' + guidFor(obj) + '>'); assert.equal(obj.toString(), '<Foo.Bar:' + guidFor(obj) + '>'); assert.equal(Foo.Bar.toString(), 'Foo.Bar'); run(Foo, 'destroy'); } ['@test toString on a class returns a useful value when nested in a namespace'](assert) { let obj; let Foo = Namespace.create(); Foo.toString = function() { return 'Foo'; }; Foo.Bar = EmberObject.extend(); assert.equal(Foo.Bar.toString(), 'Foo.Bar'); obj = Foo.Bar.create(); assert.equal(obj.toString(), '<Foo.Bar:' + guidFor(obj) + '>'); Foo.Baz = Foo.Bar.extend(); assert.equal(Foo.Baz.toString(), 'Foo.Baz'); obj = Foo.Baz.create(); assert.equal(obj.toString(), '<Foo.Baz:' + guidFor(obj) + '>'); obj = Foo.Bar.create(); assert.equal(obj.toString(), '<Foo.Bar:' + guidFor(obj) + '>'); run(Foo, 'destroy'); } ['@test toString on a namespace finds the namespace in lookup'](assert) { let Foo = (lookup.Foo = Namespace.create()); assert.equal(Foo.toString(), 'Foo'); run(Foo, 'destroy'); } ['@test toString on a namespace finds the namespace in lookup'](assert) { let Foo = (lookup.Foo = Namespace.create()); let obj; Foo.Bar = EmberObject.extend(); assert.equal(Foo.Bar.toString(), 'Foo.Bar'); obj = Foo.Bar.create(); assert.equal(obj.toString(), '<Foo.Bar:' + guidFor(obj) + '>'); run(Foo, 'destroy'); } ['@test toString on a namespace falls back to modulePrefix, if defined'](assert) { let Foo = Namespace.create({ modulePrefix: 'foo' }); assert.equal(Foo.toString(), 'foo'); run(Foo, 'destroy'); } ['@test toString includes toStringExtension if defined'](assert) { let Foo = EmberObject.extend({ toStringExtension() { return 'fooey'; }, }); let foo = Foo.create(); let Bar = EmberObject.extend({}); let bar = Bar.create(); // simulate these classes being defined on a Namespace setName(Foo, 'Foo'); setName(Bar, 'Bar'); assert.equal( bar.toString(), '<Bar:' + guidFor(bar) + '>', 'does not include toStringExtension part' ); assert.equal( foo.toString(), '<Foo:' + guidFor(foo) + ':fooey>', 'Includes toStringExtension result' ); } } );
csantero/ember.js
packages/ember-runtime/tests/system/object/toString_test.js
JavaScript
mit
3,366
define(["../core","../manipulation"],function(e){function t(t,n){var o,a=e(n.createElement(t)).appendTo(n.body),d=window.getDefaultComputedStyle&&(o=window.getDefaultComputedStyle(a[0]))?o.display:e.css(a[0],"display");return a.detach(),d}function n(n){var d=document,r=a[n];return r||(r=t(n,d),"none"!==r&&r||(o=(o||e("<iframe frameborder='0' width='0' height='0'/>")).appendTo(d.documentElement),d=o[0].contentDocument,d.write(),d.close(),r=t(n,d),o.detach()),a[n]=r),r}var o,a={};return n});
dandenney/dandenney.com
build/assets/javascripts/vendor/jquery/src/css/defaultDisplay.js
JavaScript
mit
494
#!/usr/bin/env node 'use strict'; var fs = require('fs'), path = require('path'), exec = require('child_process').exec, chalk = require('chalk'), Table = require('cli-table'); var fileNames = [ 'abc', 'amazon', //'eloquentjavascript', //'es6-draft', 'es6-table', 'google', 'html-minifier', 'msn', 'newyorktimes', 'stackoverflow', 'wikipedia', 'es6' ]; fileNames = fileNames.sort().reverse(); var table = new Table({ head: ['File', 'Before', 'After', 'Savings', 'Time'], colWidths: [20, 25, 25, 20, 20] }); function toKb(size) { return (size / 1024).toFixed(2); } function redSize(size) { return chalk.red.bold(size) + chalk.white(' (' + toKb(size) + ' KB)'); } function greenSize(size) { return chalk.green.bold(size) + chalk.white(' (' + toKb(size) + ' KB)'); } function blueSavings(oldSize, newSize) { var savingsPercent = (1 - newSize / oldSize) * 100; var savings = (oldSize - newSize) / 1024; return chalk.cyan.bold(savingsPercent.toFixed(2)) + chalk.white('% (' + savings.toFixed(2) + ' KB)'); } function blueTime(time) { return chalk.cyan.bold(time) + chalk.white(' ms'); } function test(fileName, done) { if (!fileName) { console.log('\n' + table.toString()); return; } console.log('Processing...', fileName); var filePath = path.join('benchmarks/', fileName + '.html'); var minifiedFilePath = path.join('benchmarks/generated/', fileName + '.min.html'); var gzFilePath = path.join('benchmarks/generated/', fileName + '.html.gz'); var gzMinifiedFilePath = path.join('benchmarks/generated/', fileName + '.min.html.gz'); var command = path.normalize('./cli.js') + ' ' + filePath + ' -c benchmark.conf' + ' -o ' + minifiedFilePath; // Open and read the size of the original input fs.stat(filePath, function (err, stats) { if (err) { throw new Error('There was an error reading ' + filePath); } var originalSize = stats.size; exec('gzip --keep --force --best --stdout ' + filePath + ' > ' + gzFilePath, function () { // Open and read the size of the gzipped original fs.stat(gzFilePath, function (err, stats) { if (err) { throw new Error('There was an error reading ' + gzFilePath); } var gzOriginalSize = stats.size; // Begin timing after gzipped fixtures have been created var startTime = new Date(); exec('node ' + command, function () { // Open and read the size of the minified output fs.stat(minifiedFilePath, function (err, stats) { if (err) { throw new Error('There was an error reading ' + minifiedFilePath); } var minifiedSize = stats.size; var minifiedTime = new Date() - startTime; // Gzip the minified output exec('gzip --keep --force --best --stdout ' + minifiedFilePath + ' > ' + gzMinifiedFilePath, function () { // Open and read the size of the minified+gzipped output fs.stat(gzMinifiedFilePath, function (err, stats) { if (err) { throw new Error('There was an error reading ' + gzMinifiedFilePath); } var gzMinifiedSize = stats.size; var gzMinifiedTime = new Date() - startTime; table.push([ [fileName, '+ gzipped'].join('\n'), [redSize(originalSize), redSize(gzOriginalSize)].join('\n'), [greenSize(minifiedSize), greenSize(gzMinifiedSize)].join('\n'), [blueSavings(originalSize, minifiedSize), blueSavings(gzOriginalSize, gzMinifiedSize)].join('\n'), [blueTime(minifiedTime), blueTime(gzMinifiedTime)].join('\n') ]); done(); }); }); }); }); }); }); }); } (function run() { test(fileNames.pop(), run); })();
psychoss/html-minifier
benchmark.js
JavaScript
mit
3,946
steal('can/util', 'can/observe', function(can) { // ** - 'this' will be the deepest item changed // * - 'this' will be any changes within *, but * will be the // this returned // tells if the parts part of a delegate matches the broken up props of the event // gives the prop to use as 'this' // - parts - the attribute name of the delegate split in parts ['foo','*'] // - props - the split props of the event that happened ['foo','bar','0'] // - returns - the attribute to delegate too ('foo.bar'), or null if not a match var matches = function(parts, props){ //check props parts are the same or var len = parts.length, i =0, // keeps the matched props we will use matchedProps = [], prop; // if the event matches for(i; i< len; i++){ prop = props[i] // if no more props (but we should be matching them) // return null if( typeof prop !== 'string' ) { return null; } else // if we have a "**", match everything if( parts[i] == "**" ) { return props.join("."); } else // a match, but we want to delegate to "*" if (parts[i] == "*"){ // only do this if there is nothing after ... matchedProps.push(prop); } else if( prop === parts[i] ) { matchedProps.push(prop); } else { return null; } } return matchedProps.join("."); }, // gets a change event and tries to figure out which // delegates to call delegate = function(event, prop, how, newVal, oldVal){ // pre-split properties to save some regexp time var props = prop.split("."), delegates = (this._observe_delegates || []).slice(0), delegate, attr, matchedAttr, hasMatch, valuesEqual; event.attr = prop; event.lastAttr = props[props.length -1 ]; // for each delegate for(var i =0; delegate = delegates[i++];){ // if there is a batchNum, this means that this // event is part of a series of events caused by a single // attrs call. We don't want to issue the same event // multiple times // setting the batchNum happens later if((event.batchNum && delegate.batchNum === event.batchNum) || delegate.undelegated ){ continue; } // reset match and values tests hasMatch = undefined; valuesEqual = true; // for each attr in a delegate for(var a =0 ; a < delegate.attrs.length; a++){ attr = delegate.attrs[a]; // check if it is a match if(matchedAttr = matches(attr.parts, props)){ hasMatch = matchedAttr; } // if it has a value, make sure it's the right value // if it's set, we should probably check that it has a // value no matter what if(attr.value && valuesEqual /* || delegate.hasValues */){ valuesEqual = attr.value === ""+this.attr(attr.attr) } else if (valuesEqual && delegate.attrs.length > 1){ // if there are multiple attributes, each has to at // least have some value valuesEqual = this.attr(attr.attr) !== undefined } } // if there is a match and valuesEqual ... call back if(hasMatch && valuesEqual) { // how to get to the changed property from the delegate var from = prop.replace(hasMatch+".",""); // if this event is part of a batch, set it on the delegate // to only send one event if(event.batchNum ){ delegate.batchNum = event.batchNum } // if we listen to change, fire those with the same attrs // TODO: the attrs should probably be using from if( delegate.event === 'change' ){ arguments[1] = from; event.curAttr = hasMatch; delegate.callback.apply(this.attr(hasMatch), can.makeArray( arguments)); } else if(delegate.event === how ){ // if it's a match, callback with the location of the match delegate.callback.apply(this.attr(hasMatch), [event,newVal, oldVal, from]); } else if(delegate.event === 'set' && how == 'add' ) { // if we are listening to set, we should also listen to add delegate.callback.apply(this.attr(hasMatch), [event,newVal, oldVal, from]); } } } }; can.extend(can.Observe.prototype,{ /** * @function can.Observe.prototype.delegate * @parent can.Observe.delegate * @plugin can/observe/delegate * * `delegate( selector, event, handler(ev,newVal,oldVal,from) )` listen for changes * in a child attribute from the parent. The child attribute * does not have to exist. * * * // create an observable * var observe = can.Observe({ * foo : { * bar : "Hello World" * } * }) * * //listen to changes on a property * observe.delegate("foo.bar","change", function(ev, prop, how, newVal, oldVal){ * // foo.bar has been added, set, or removed * this //-> * }); * * // change the property * observe.attr('foo.bar',"Goodbye Cruel World") * * ## Types of events * * Delegate lets you listen to add, set, remove, and change events on property. * * __add__ * * An add event is fired when a new property has been added. * * var o = new can.Control({}); * o.delegate("name","add", function(ev, value){ * // called once * can.$('#name').show() * }) * o.attr('name',"Justin") * o.attr('name',"Brian"); * * Listening to add events is useful for 'setup' functionality (in this case * showing the <code>#name</code> element. * * __set__ * * Set events are fired when a property takes on a new value. set events are * always fired after an add. * * o.delegate("name","set", function(ev, value){ * // called twice * can.$('#name').text(value) * }) * o.attr('name',"Justin") * o.attr('name',"Brian"); * * __remove__ * * Remove events are fired after a property is removed. * * o.delegate("name","remove", function(ev){ * // called once * $('#name').text(value) * }) * o.attr('name',"Justin"); * o.removeAttr('name'); * * ## Wildcards - matching multiple properties * * Sometimes, you want to know when any property within some part * of an observe has changed. Delegate lets you use wildcards to * match any property name. The following listens for any change * on an attribute of the params attribute: * * var o = can.Control({ * options : { * limit : 100, * offset: 0, * params : { * parentId: 5 * } * } * }) * o.delegate('options.*','change', function(){ * alert('1'); * }) * o.delegate('options.**','change', function(){ * alert('2'); * }) * * // alerts 1 * // alerts 2 * o.attr('options.offset',100) * * // alerts 2 * o.attr('options.params.parentId',6); * * Using a single wildcard (<code>*</code>) matches single level * properties. Using a double wildcard (<code>**</code>) matches * any deep property. * * ## Listening on multiple properties and values * * Delegate lets you listen on multiple values at once. The following listens * for first and last name changes: * * var o = new can.Observe({ * name : {first: "Justin", last: "Meyer"} * }) * * o.bind("name.first,name.last", * "set", * function(ev,newVal,oldVal,from){ * * }) * * ## Listening when properties are a particular value * * Delegate lets you listen when a property is __set__ to a specific value: * * var o = new can.Observe({ * name : "Justin" * }) * * o.bind("name=Brian", * "set", * function(ev,newVal,oldVal,from){ * * }) * * @param {String} selector The attributes you want to listen for changes in. * * Selector should be the property or * property names of the element you are searching. Examples: * * "name" - listens to the "name" property changing * "name, address" - listens to "name" or "address" changing * "name address" - listens to "name" or "address" changing * "address.*" - listens to property directly in address * "address.**" - listens to any property change in address * "foo=bar" - listens when foo is "bar" * * @param {String} event The event name. One of ("set","add","remove","change") * @param {Function} handler(ev,newVal,oldVal,prop) The callback handler * called with: * * - newVal - the new value set on the observe * - oldVal - the old value set on the observe * - prop - the prop name that was changed * * @return {jQuery.Delegate} the delegate for chaining */ delegate : function(selector, event, handler){ selector = can.trim(selector); var delegates = this._observe_delegates || (this._observe_delegates = []), attrs = []; // split selector by spaces selector.replace(/([^\s=]+)=?([^\s]+)?/g, function(whole, attr, value){ attrs.push({ // the attribute name attr: attr, // the attribute's pre-split names (for speed) parts: attr.split('.'), // the value associated with this prop value: value }) }); // delegates has pre-processed info about the event delegates.push({ // the attrs name for unbinding selector : selector, // an object of attribute names and values {type: 'recipe',id: undefined} // undefined means a value was not defined attrs : attrs, callback : handler, event: event }); if(delegates.length === 1){ this.bind("change",delegate) } return this; }, /** * @function can.Observe.prototype.undelegate * @parent can.Observe.delegate * * `undelegate( selector, event, handler )` removes a delegated event handler from an observe. * * observe.undelegate("name","set", handler ) * * @param {String} selector the attribute name of the object you want to undelegate from. * @param {String} event the event name * @param {Function} handler the callback handler * @return {jQuery.Delegate} the delegate for chaining */ undelegate : function(selector, event, handler){ selector = can.trim(selector); var i =0, delegates = this._observe_delegates || [], delegateOb; if(selector){ while(i < delegates.length){ delegateOb = delegates[i]; if( delegateOb.callback === handler || (!handler && delegateOb.selector === selector) ){ delegateOb.undelegated = true; delegates.splice(i,1) } else { i++; } } } else { // remove all delegates delegates = []; } if(!delegates.length){ //can.removeData(this, "_observe_delegates"); this.unbind("change",delegate) } return this; } }); // add helpers for testing .. can.Observe.prototype.delegate.matches = matches; return can.Observe; })
SpredfastLegacy/canjs
observe/delegate/delegate.js
JavaScript
mit
11,161
var name = "Wanderer"; var collection_type = 0; var is_secret = 0; var desc = "Visited 503 new locations."; var status_text = "Gosh, where HAVEN'T you traveled? Your peregrinations have earned you this footworn-but-carefree Wanderer badge."; var last_published = 1348803094; var is_shareworthy = 1; var url = "wanderer"; var category = "exploring"; var url_swf = "\/c2.glitch.bz\/achievements\/2011-09-18\/wanderer_1316414516.swf"; var url_img_180 = "\/c2.glitch.bz\/achievements\/2011-09-18\/wanderer_1316414516_180.png"; var url_img_60 = "\/c2.glitch.bz\/achievements\/2011-09-18\/wanderer_1316414516_60.png"; var url_img_40 = "\/c2.glitch.bz\/achievements\/2011-09-18\/wanderer_1316414516_40.png"; function on_apply(pc){ } var conditions = { 8 : { type : "group_count", group : "locations_visited", value : "503" }, }; function onComplete(pc){ // generated from rewards var multiplier = pc.buffs_has('gift_of_gab') ? 1.2 : pc.buffs_has('silvertongue') ? 1.05 : 1.0; multiplier += pc.imagination_get_achievement_modifier(); if (/completist/i.exec(this.name)) { var level = pc.stats_get_level(); if (level > 4) { multiplier *= (pc.stats_get_level()/4); } } pc.stats_add_xp(round_to_5(1000 * multiplier), true); pc.stats_add_favor_points("lem", round_to_5(200 * multiplier)); if(pc.buffs_has('gift_of_gab')) { pc.buffs_remove('gift_of_gab'); } else if(pc.buffs_has('silvertongue')) { pc.buffs_remove('silvertongue'); } } var rewards = { "xp" : 1000, "favor" : { "giant" : "lem", "points" : 200 } }; // generated ok (NO DATE)
yelworc/eleven-gsjs
achievements/wanderer.js
JavaScript
mit
1,587
export default class ModelAccessor { constructor() { this.value = 10 } get highCount() { return this.value + 100 } set highCount(v) { this.value = v - 100 } get doubleHigh() { return this.highCount * 2 } incr() { this.value++ } }
nekronos/fuselibs-public
Source/Fuse.Models/Tests/UX/Accessor.js
JavaScript
mit
255
import { Template } from 'meteor/templating'; Template.messageAction.helpers({ isButton() { return this.type === 'button'; }, areButtonsHorizontal() { return Template.parentData(1).button_alignment === 'horizontal'; }, jsActionButtonClassname(processingType) { return `js-actionButton-${ processingType || 'sendMessage' }`; }, });
4thParty/Rocket.Chat
app/message-action/client/messageAction.js
JavaScript
mit
344
import fs from 'fs'; import url from 'url'; import path from 'path'; import mime from 'mime-types'; import gulp from 'gulp'; import createServerTask from './tasks/server'; import consoleArguments from './console-arguments'; import { adminBundle } from './admin-bundle.tasks'; import { dashboardBundle } from './dashboard-bundle.tasks'; import { mediaBundle } from './media-bundle.tasks'; import { translatorBundle } from './translator-bundle.tasks'; const BUNDLES = [adminBundle, dashboardBundle, mediaBundle, translatorBundle]; const writeToResponse = (req, res, bundlePaths) => { const formattedUrl = url.parse(req.url); for (const bundlePath of bundlePaths) { const filePath = path.normalize(bundlePath + formattedUrl.pathname); try { const stat = fs.statSync(filePath); if (stat && stat.isFile()) { const rstream = fs.createReadStream(filePath); const extension = path.extname(filePath); const contentType = mime.lookup(extension); res.writeHead(200, { 'Content-Type': contentType, 'Content-Length': stat.size }); rstream.pipe(res); return; } } catch (e) { // Does not exist } } return new Error(`Local file for ${req.url} not found`); }; const handleRequest = (req, res, next) => { if (writeToResponse(req, res, BUNDLES.map(item => item.config.distPath))) { // Nothing we can write to the stream, fallback to the default behavior return next(); }; }; const startLocalTask = createServerTask({ config: { ui: false, ghostMode: false, open: false, reloadOnRestart: true, notify: true, proxy: { target: consoleArguments.backendProxy }, middleware: BUNDLES.map(bundle => { return { route: bundle.config.publicPath, handle: handleRequest } }) } }); export const buildOnChange = (done) => { for (const bundle of BUNDLES) { const srcPath = bundle.config.srcPath; const jsAssets = srcPath + 'js/**/!(*.spec).js'; gulp.watch(jsAssets, bundle.tasks.scripts); if (bundle.tasks.bundle) { const jsNextAssets = srcPath + 'jsnext/**/!(*.spec).js'; gulp.watch(jsNextAssets, bundle.tasks.bundle); } const styleAssets = srcPath + 'scss/**/*.scss'; gulp.watch(styleAssets, bundle.tasks.cssOptimized); if (bundle.tasks.cssNextOptimized) { const styleNextAssets = srcPath + 'scssnext/**/*.scss'; gulp.watch(styleNextAssets, bundle.tasks.cssNextOptimized); } } done(); }; export function testOnChange(done) { for (const bundle of BUNDLES) { if (bundle.tasks.eslint) { const srcPath = bundle.config.srcPath; gulp.watch(`${srcPath}jsnext/**/*.js`, bundle.tasks.eslint); } if (bundle.tasks.stylelint) { const srcPath = bundle.config.srcPath; gulp.watch(`${srcPath}scssnext/**/*.scss`, bundle.tasks.stylelint); } } done(); } export default startLocalTask;
Kunstmaan/KunstmaanBundlesCMS
groundcontrol/start-local.task.js
JavaScript
mit
3,206
'use strict'; describe('Service: Initiatives', function () { // instantiate service var Initiatives, Timeout, cfg, $httpBackend, $rootScope, tPromise; // load the service's module beforeEach(module('sumaAnalysis')); beforeEach(inject(function (_$rootScope_, _$httpBackend_, _initiatives_, $q, $timeout) { $rootScope = _$rootScope_; $httpBackend = _$httpBackend_; Initiatives = _initiatives_; tPromise = $q.defer(); Timeout = $timeout; cfg = { timeoutPromise: tPromise, timeout: 180000 }; })); it('should make an AJAX call', function (done) { $httpBackend.whenGET('lib/php/initiatives.php') .respond([{}, {}]); Initiatives.get(cfg).then(function (result) { expect(result.length).to.equal(2); done(); }); $httpBackend.flush(); }); it('should respond with error message on failure', function (done) { $httpBackend.whenGET('lib/php/initiatives.php') .respond(500, {message: 'Error'}); Initiatives.get(cfg).then(function (result) { }, function (result) { expect(result).to.deep.equal({ message: 'Error', code: 500 }); done(); }); $httpBackend.flush(); }); it('should return error with promiseTimeout true on aborted http request', function (done) { // simulate aborted request $httpBackend.whenGET('lib/php/initiatives.php') .respond(0, {message: 'Error'}); Initiatives.get(cfg).then(function (result) { }, function (result) { expect(result).to.deep.equal({ message: 'Initiatives.get Timeout', code: 0, promiseTimeout: true }); done(); }); $httpBackend.flush(); }); it('should return error without promiseTimeout on http timeout', function (done) { $httpBackend.whenGET('lib/php/initiatives.php') .respond([{}, {}]); Initiatives.get(cfg).then(function (result) { }, function (result) { expect(result).to.deep.equal({ message: 'Initiatives.get Timeout', code: 0 }); done(); }); Timeout.flush(); }); });
cazzerson/Suma
analysis/test/js/spec/services/initiatives.js
JavaScript
mit
2,143
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; /* Tabulator v4.0.2 (c) Oliver Folkerd */ var HtmlTableImport = function HtmlTableImport(table) { this.table = table; //hold Tabulator object this.fieldIndex = []; this.hasIndex = false; }; HtmlTableImport.prototype.parseTable = function () { var self = this, element = self.table.element, options = self.table.options, columns = options.columns, headers = element.getElementsByTagName("th"), rows = element.getElementsByTagName("tbody")[0].getElementsByTagName("tr"), data = [], newTable; self.hasIndex = false; self.table.options.htmlImporting.call(this.table); //check for tablator inline options self._extractOptions(element, options); if (headers.length) { self._extractHeaders(headers, rows); } else { self._generateBlankHeaders(headers, rows); } //iterate through table rows and build data set for (var index = 0; index < rows.length; index++) { var row = rows[index], cells = row.getElementsByTagName("td"), item = {}; //create index if the dont exist in table if (!self.hasIndex) { item[options.index] = index; } for (var i = 0; i < cells.length; i++) { var cell = cells[i]; if (typeof this.fieldIndex[i] !== "undefined") { item[this.fieldIndex[i]] = cell.innerHTML; } } //add row data to item data.push(item); } //create new element var newElement = document.createElement("div"); //transfer attributes to new element var attributes = element.attributes; // loop through attributes and apply them on div for (var i in attributes) { if (_typeof(attributes[i]) == "object") { newElement.setAttribute(attributes[i].name, attributes[i].value); } } // replace table with div element element.parentNode.replaceChild(newElement, element); options.data = data; self.table.options.htmlImported.call(this.table); // // newElement.tabulator(options); this.table.element = newElement; }; //extract tabluator attribute options HtmlTableImport.prototype._extractOptions = function (element, options) { var attributes = element.attributes; for (var index in attributes) { var attrib = attributes[index]; var name; if ((typeof attrib === "undefined" ? "undefined" : _typeof(attrib)) == "object" && attrib.name && attrib.name.indexOf("tabulator-") === 0) { name = attrib.name.replace("tabulator-", ""); for (var key in options) { if (key.toLowerCase() == name) { options[key] = this._attribValue(attrib.value); } } } } }; //get value of attribute HtmlTableImport.prototype._attribValue = function (value) { if (value === "true") { return true; } if (value === "false") { return false; } return value; }; //find column if it has already been defined HtmlTableImport.prototype._findCol = function (title) { var match = this.table.options.columns.find(function (column) { return column.title === title; }); return match || false; }; //extract column from headers HtmlTableImport.prototype._extractHeaders = function (headers, rows) { for (var index = 0; index < headers.length; index++) { var header = headers[index], exists = false, col = this._findCol(header.textContent), width, attributes; if (col) { exists = true; } else { col = { title: header.textContent.trim() }; } if (!col.field) { col.field = header.textContent.trim().toLowerCase().replace(" ", "_"); } width = header.getAttribute("width"); if (width && !col.width) { col.width = width; } //check for tablator inline options attributes = header.attributes; // //check for tablator inline options this._extractOptions(header, col); for (var i in attributes) { var attrib = attributes[i], name; if ((typeof attrib === "undefined" ? "undefined" : _typeof(attrib)) == "object" && attrib.name && attrib.name.indexOf("tabulator-") === 0) { name = attrib.name.replace("tabulator-", ""); col[name] = this._attribValue(attrib.value); } } this.fieldIndex[index] = col.field; if (col.field == this.table.options.index) { this.hasIndex = true; } if (!exists) { this.table.options.columns.push(col); } } }; //generate blank headers HtmlTableImport.prototype._generateBlankHeaders = function (headers, rows) { for (var index = 0; index < headers.length; index++) { var header = headers[index], col = { title: "", field: "col" + index }; this.fieldIndex[index] = col.field; var width = header.getAttribute("width"); if (width) { col.width = width; } this.table.options.columns.push(col); } }; Tabulator.prototype.registerModule("htmlTableImport", HtmlTableImport);
joeyparrish/cdnjs
ajax/libs/tabulator/4.0.2/js/modules/html_table_import.js
JavaScript
mit
4,916
//------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. //------------------------------------------------------------------------------------------------------- function DumpArray(a) { var undef_start = -1; for (var i = 0; i < a.length; i++) { if (a[i] == undefined) { if (undef_start == -1) { undef_start = i; } } else { if (undef_start != -1) { WScript.Echo(undef_start + "-" + (i-1) + " = undefined"); undef_start = -1; } WScript.Echo(i + " = " + a[i]); } } } DumpArray([]); DumpArray([ 0 ]); DumpArray([ 0, 1, 2, 3, 4, 5, 6 ,7 ,8, 9]); DumpArray([,,,0,,,1,,,2,,,3,,,4,,,5,,,6,,,7,,,8,,,9,,,]); var s0 = ""; for (var i = 0; i < 100; i++) { s0 += ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,"; } DumpArray(eval("[" + s0 + "1]")); var s1 = ""; for (var i = 0; i < 30; i++) { s1 += s0; } DumpArray(eval("[" + s1 + "1]")); var s2 = ""; for (var i = 0; i < 10; i++) { s2 += s1; } DumpArray(eval("[" + s2 + "1]"));
arunetm/ChakraCore_0114
test/Array/array_init.js
JavaScript
mit
1,438
$_L(["$wt.widgets.Layout"],"$wt.layout.FillLayout",["$wt.graphics.Point","$wt.layout.FillData"],function(){ c$=$_C(function(){ this.type=256; this.marginWidth=0; this.marginHeight=0; this.spacing=0; $_Z(this,arguments); },$wt.layout,"FillLayout",$wt.widgets.Layout); $_K(c$, function(){ $_R(this,$wt.layout.FillLayout,[]); }); $_K(c$, function(type){ $_R(this,$wt.layout.FillLayout,[]); this.type=type; },"~N"); $_V(c$,"computeSize", function(composite,wHint,hHint,flushCache){ var children=composite.getChildren(); var count=children.length; var maxWidth=0; var maxHeight=0; for(var i=0;i<count;i++){ var child=children[i]; var w=wHint; var h=hHint; if(count>0){ if(this.type==256&&wHint!=-1){ w=Math.max(0,Math.floor((wHint-(count-1)*this.spacing)/count)); }if(this.type==512&&hHint!=-1){ h=Math.max(0,Math.floor((hHint-(count-1)*this.spacing)/count)); }}var size=this.computeChildSize(child,w,h,flushCache); maxWidth=Math.max(maxWidth,size.x); maxHeight=Math.max(maxHeight,size.y); } var width=0; var height=0; if(this.type==256){ width=count*maxWidth; if(count!=0)width+=(count-1)*this.spacing; height=maxHeight; }else{ width=maxWidth; height=count*maxHeight; if(count!=0)height+=(count-1)*this.spacing; }width+=this.marginWidth*2; height+=this.marginHeight*2; if(wHint!=-1)width=wHint; if(hHint!=-1)height=hHint; return new $wt.graphics.Point(width,height); },"$wt.widgets.Composite,~N,~N,~B"); $_M(c$,"computeChildSize", function(control,wHint,hHint,flushCache){ var data=control.getLayoutData(); if(data==null){ data=new $wt.layout.FillData(); control.setLayoutData(data); }var size=null; if(wHint==-1&&hHint==-1){ size=data.computeSize(control,wHint,hHint,flushCache); }else{ var trimX; var trimY; if($_O(control,$wt.widgets.Scrollable)){ var rect=(control).computeTrim(0,0,0,0); trimX=rect.width; trimY=rect.height; }else{ trimX=trimY=control.getBorderWidth()*2; }var w=wHint==-1?wHint:Math.max(0,wHint-trimX); var h=hHint==-1?hHint:Math.max(0,hHint-trimY); size=data.computeSize(control,w,h,flushCache); }return size; },"$wt.widgets.Control,~N,~N,~B"); $_V(c$,"flushCache", function(control){ var data=control.getLayoutData(); if(data!=null)(data).flushCache(); return true; },"$wt.widgets.Control"); $_M(c$,"getName", function(){ var string=this.getClass().getName(); var index=string.lastIndexOf('.'); if(index==-1)return string; return string.substring(index+1,string.length); }); $_V(c$,"layout", function(composite,flushCache){ var rect=composite.getClientArea(); var children=composite.getChildren(); var count=children.length; if(count==0)return; var width=rect.width-this.marginWidth*2; var height=rect.height-this.marginHeight*2; if(this.type==256){ width-=(count-1)*this.spacing; var x=rect.x+this.marginWidth; var extra=width%count; var y=rect.y+this.marginHeight; var cellWidth=Math.floor(width/count); for(var i=0;i<count;i++){ var child=children[i]; var childWidth=cellWidth; if(i==0){ childWidth+=Math.floor(extra/2); }else{ if(i==count-1)childWidth+=Math.floor((extra+1)/2); }child.setBounds(x,y,childWidth,height); x+=childWidth+this.spacing; } }else{ height-=(count-1)*this.spacing; var x=rect.x+this.marginWidth; var cellHeight=Math.floor(height/count); var y=rect.y+this.marginHeight; var extra=height%count; for(var i=0;i<count;i++){ var child=children[i]; var childHeight=cellHeight; if(i==0){ childHeight+=Math.floor(extra/2); }else{ if(i==count-1)childHeight+=Math.floor((extra+1)/2); }child.setBounds(x,y,width,childHeight); y+=childHeight+this.spacing; } }},"$wt.widgets.Composite,~B"); $_V(c$,"toString", function(){ var string=this.getName()+"{"; string+="type="+((this.type==512)?"SWT.VERTICAL":"SWT.HORIZONTAL")+" "; if(this.marginWidth!=0)string+="marginWidth="+this.marginWidth+" "; if(this.marginHeight!=0)string+="marginHeight="+this.marginHeight+" "; if(this.spacing!=0)string+="spacing="+this.spacing+" "; string=string.trim(); string+="}"; return string; }); });
01org/mayloon-portingtool
sources/net.sf.j2s.lib/j2slib/org/eclipse/swt/layout/FillLayout.js
JavaScript
epl-1.0
4,054
var path = require("path"); module.exports = { entry: "./public/App.js", output: { filename: "bundle.js", path: path.resolve(__dirname, "public") } };
generalelectrix/wiggles
view/webpack.config.js
JavaScript
gpl-2.0
179
$(document).ready(function(){ // removing some column headers when there is at least one product if ( $('#lines tbody tr.product').length > 0 ) { $('#lines').addClass('with-product'); $('body').addClass('with-product'); } if ( $('#lines tbody tr.ticket').length > 0 ) { $('#lines').addClass('with-ticket'); $('body').addClass('with-ticket'); } window.print(); // update the parent window's content if ( window.opener != undefined && typeof window.opener.li === 'object' ) window.opener.li.initContent(); // print again if ( $('#options #print-again').length > 0 ) window.location = $('#options #print-again a').prop('href'); // close if ( $('#options #close').length > 0 && $('#options #print-again').length == 0 ) window.close(); });
Fabrice-li/e-venement
web/js/print-tickets.js
JavaScript
gpl-2.0
803
/* Implement Github like autocomplete mentions http://ichord.github.com/At.js Copyright (c) 2013 [email protected] Licensed under the MIT license. */ /* 本插件操作 textarea 或者 input 内的插入符 只实现了获得插入符在文本框中的位置,我设置 插入符的位置. */ /** * -------------------- * Vanilla Forums NOTE: * -------------------- * * This file has been highly modified to work with iframes, as well * as custom username handling with quotation marks and spaces for Vanilla. * Do not just replace with a more current version. At the time of * development there was no support for iframes, or spaces in names. * This may have changed, so if you do decide to upgrade this library, * you're going to have to update the code that uses this library as well. * It's all wrapped up in a function called `atCompleteInit`. */ (function() { (function(factory) { if (typeof define === 'function' && define.amd) { return define(['jquery'], factory); } else { return factory(window.jQuery); } })(function($) { "use strict"; ////var EditableCaret, InputCaret, Mirror, Utils, methods, pluginName; var EditableCaret, InputCaret, Mirror, Utils, methods, pluginName, cWin; pluginName = 'caret'; EditableCaret = (function() { function EditableCaret($inputor) { this.$inputor = $inputor; this.domInputor = this.$inputor[0]; } EditableCaret.prototype.setPos = function(pos) { return this.domInputor; }; EditableCaret.prototype.getIEPosition = function() { return $.noop(); }; EditableCaret.prototype.getPosition = function() { return $.noop(); }; EditableCaret.prototype.getOldIEPos = function() { var preCaretTextRange, textRange; textRange = document.selection.createRange(); preCaretTextRange = document.body.createTextRange(); preCaretTextRange.moveToElementText(this.domInputor); preCaretTextRange.setEndPoint("EndToEnd", textRange); return preCaretTextRange.text.length; }; EditableCaret.prototype.getPos = function() { var clonedRange, pos, range; if (range = this.range()) { clonedRange = range.cloneRange(); clonedRange.selectNodeContents(this.domInputor); clonedRange.setEnd(range.endContainer, range.endOffset); pos = clonedRange.toString().length; clonedRange.detach(); return pos; } else if (document.selection) { return this.getOldIEPos(); } }; EditableCaret.prototype.getOldIEOffset = function() { var range, rect; range = document.selection.createRange().duplicate(); range.moveStart("character", -1); rect = range.getBoundingClientRect(); return { height: rect.bottom - rect.top, left: rect.left, top: rect.top }; }; EditableCaret.prototype.getOffset = function(pos) { var clonedRange, offset, range, rect; offset = null; ////if (window.getSelection && (range = this.range())) { if (cWin.getSelection && (range = this.range())) { if (range.endOffset - 1 < 0) { return null; } clonedRange = range.cloneRange(); clonedRange.setStart(range.endContainer, range.endOffset - 1); clonedRange.setEnd(range.endContainer, range.endOffset); rect = clonedRange.getBoundingClientRect(); offset = { height: rect.height, left: rect.left + rect.width, top: rect.top }; clonedRange.detach(); offset; } else if (document.selection) { this.getOldIEOffset(); } return Utils.adjustOffset(offset, this.$inputor); }; EditableCaret.prototype.range = function() { var sel; ////if (!window.getSelection) { if (!cWin.getSelection) { return; } ////sel = window.getSelection(); sel = cWin.getSelection(); if (sel.rangeCount > 0) { return sel.getRangeAt(0); } else { return null; } }; return EditableCaret; })(); InputCaret = (function() { function InputCaret($inputor) { this.$inputor = $inputor; this.domInputor = this.$inputor[0]; } InputCaret.prototype.getIEPos = function() { var endRange, inputor, len, normalizedValue, pos, range, textInputRange; inputor = this.domInputor; range = document.selection.createRange(); pos = 0; if (range && range.parentElement() === inputor) { normalizedValue = inputor.value.replace(/\r\n/g, "\n"); len = normalizedValue.length; textInputRange = inputor.createTextRange(); textInputRange.moveToBookmark(range.getBookmark()); endRange = inputor.createTextRange(); endRange.collapse(false); if (textInputRange.compareEndPoints("StartToEnd", endRange) > -1) { pos = len; } else { pos = -textInputRange.moveStart("character", -len); } } return pos; }; InputCaret.prototype.getPos = function() { if (document.selection) { return this.getIEPos(); } else { return this.domInputor.selectionStart; } }; InputCaret.prototype.setPos = function(pos) { var inputor, range; inputor = this.domInputor; if (document.selection) { range = inputor.createTextRange(); range.move("character", pos); range.select(); } else if (inputor.setSelectionRange) { inputor.setSelectionRange(pos, pos); } return inputor; }; InputCaret.prototype.getIEOffset = function(pos) { var h, range, textRange, x, y; textRange = this.domInputor.createTextRange(); if (pos) { textRange.move('character', pos); } else { range = document.selection.createRange(); textRange.moveToBookmark(range.getBookmark()); } x = textRange.boundingLeft; y = textRange.boundingTop; h = textRange.boundingHeight; return { left: x, top: y, height: h }; }; InputCaret.prototype.getOffset = function(pos) { var $inputor, offset, position; $inputor = this.$inputor; if (document.selection) { return Utils.adjustOffset(this.getIEOffset(pos), $inputor); } else { offset = $inputor.offset(); position = this.getPosition(pos); return offset = { left: offset.left + position.left, top: offset.top + position.top, height: position.height }; } }; InputCaret.prototype.getPosition = function(pos) { var $inputor, at_rect, format, html, mirror, start_range; $inputor = this.$inputor; format = function(value) { return value.replace(/</g, '&lt').replace(/>/g, '&gt').replace(/`/g, '&#96').replace(/"/g, '&quot').replace(/\r\n|\r|\n/g, "<br />"); }; if (pos === void 0) { pos = this.getPos(); } start_range = $inputor.val().slice(0, pos); html = "<span>" + format(start_range) + "</span>"; html += "<span id='caret'>|</span>"; mirror = new Mirror($inputor); return at_rect = mirror.create(html).rect(); }; InputCaret.prototype.getIEPosition = function(pos) { var h, inputorOffset, offset, x, y; offset = this.getIEOffset(pos); inputorOffset = this.$inputor.offset(); x = offset.left - inputorOffset.left; y = offset.top - inputorOffset.top; h = offset.height; return { left: x, top: y, height: h }; }; return InputCaret; })(); Mirror = (function() { Mirror.prototype.css_attr = ["overflowY", "height", "width", "paddingTop", "paddingLeft", "paddingRight", "paddingBottom", "marginTop", "marginLeft", "marginRight", "marginBottom", "fontFamily", "borderStyle", "borderWidth", "wordWrap", "fontSize", "lineHeight", "overflowX", "text-align"]; function Mirror($inputor) { this.$inputor = $inputor; } Mirror.prototype.mirrorCss = function() { var css, _this = this; css = { position: 'absolute', left: -9999, top: 0, zIndex: -20000, 'white-space': 'pre-wrap' }; $.each(this.css_attr, function(i, p) { return css[p] = _this.$inputor.css(p); }); return css; }; Mirror.prototype.create = function(html) { this.$mirror = $('<div></div>'); this.$mirror.css(this.mirrorCss()); this.$mirror.html(html); this.$inputor.after(this.$mirror); return this; }; Mirror.prototype.rect = function() { var $flag, pos, rect; $flag = this.$mirror.find("#caret"); pos = $flag.position(); rect = { left: pos.left, top: pos.top, height: $flag.height() }; this.$mirror.remove(); return rect; }; return Mirror; })(); Utils = { adjustOffset: function(offset, $inputor) { if (!offset) { return; } offset.top += $(window).scrollTop() + $inputor.scrollTop(); offset.left += +$(window).scrollLeft() + $inputor.scrollLeft(); return offset; }, contentEditable: function($inputor) { return !!($inputor[0].contentEditable && $inputor[0].contentEditable === 'true'); } }; methods = { pos: function(pos) { if (pos) { return this.setPos(pos); } else { return this.getPos(); } }, position: function(pos) { if (document.selection) { return this.getIEPosition(pos); } else { return this.getPosition(pos); } }, offset: function(pos) { return this.getOffset(pos); } }; ////$.fn.caret = function(method) { $.fn.caret = function(method, aWin) { var caret; //// cWin = aWin; caret = Utils.contentEditable(this) ? new EditableCaret(this) : new InputCaret(this); if (methods[method]) { ////return methods[method].apply(caret, Array.prototype.slice.call(arguments, 1)); ///////return methods[method].apply(caret, Array.prototype.slice.call(arguments, method == 'pos' ? 2 : 1)); return methods[method].apply(caret, Array.prototype.slice.call(arguments, 2)); } else { return $.error("Method " + method + " does not exist on jQuery.caret"); } }; $.fn.caret.EditableCaret = EditableCaret; $.fn.caret.InputCaret = InputCaret; $.fn.caret.Utils = Utils; return $.fn.caret.apis = methods; }); }).call(this); /* Implement Github like autocomplete mentions http://ichord.github.com/At.js Copyright (c) 2013 [email protected] Licensed under the MIT license. */ (function() { var __slice = [].slice; (function(factory) { if (typeof define === 'function' && define.amd) { return define(['jquery'], factory); } else { return factory(window.jQuery); } })(function($) { var $CONTAINER, Api, App, Atwho, Controller, DEFAULT_CALLBACKS, KEY_CODE, Model, View; App = (function() { function App(inputor) { this.current_flag = null; this.controllers = {}; this.$inputor = $(inputor); this.listen(); } App.prototype.controller = function(at) { return this.controllers[at || this.current_flag]; }; App.prototype.set_context_for = function(at) { this.current_flag = at; return this; }; App.prototype.reg = function(flag, setting) { var controller, _base; controller = (_base = this.controllers)[flag] || (_base[flag] = new Controller(this, flag)); if (setting.alias) { this.controllers[setting.alias] = controller; } controller.init(setting); return this; }; App.prototype.listen = function() { var _this = this; return this.$inputor.on('keyup.atwho', function(e) { return _this.on_keyup(e); }).on('keydown.atwho', function(e) { return _this.on_keydown(e); }).on('scroll.atwho', function(e) { var _ref; return (_ref = _this.controller()) != null ? _ref.view.hide() : void 0; }).on('blur.atwho', function(e) { var c; if (c = _this.controller()) { return c.view.hide(c.get_opt("display_timeout")); } }); }; App.prototype.dispatch = function() { var _this = this; return $.map(this.controllers, function(c) { if (c.look_up()) { return _this.set_context_for(c.at); } }); }; App.prototype.on_keyup = function(e) { var _ref; switch (e.keyCode) { case KEY_CODE.ESC: case KEY_CODE.TAB: case KEY_CODE.ENTER: e.preventDefault(); if ((_ref = this.controller()) != null) { _ref.view.hide(); } break; case KEY_CODE.DOWN: case KEY_CODE.UP: $.noop(); break; default: this.dispatch(); } }; App.prototype.on_keydown = function(e) { var view, _ref; view = (_ref = this.controller()) != null ? _ref.view : void 0; if (!(view && view.visible())) { return; } switch (e.keyCode) { case KEY_CODE.ESC: e.preventDefault(); view.hide(); break; case KEY_CODE.UP: e.preventDefault(); view.prev(); break; case KEY_CODE.DOWN: e.preventDefault(); view.next(); break; case KEY_CODE.TAB: case KEY_CODE.ENTER: if (!view.visible()) { return; } view.choose(e); break; default: $.noop(); } }; return App; })(); Controller = (function() { var uuid, _uuid; _uuid = 0; uuid = function() { return _uuid += 1; }; function Controller(app, at) { this.app = app; this.at = at; this.$inputor = this.app.$inputor; this.id = this.$inputor[0].id || uuid(); this.setting = null; this.query = null; this.pos = 0; this.cur_rect = null; this.range = null; $CONTAINER.append(this.$el = $("<div id='atwho-ground-" + this.id + "'></div>")); this.model = new Model(this); this.view = new View(this); } Controller.prototype.init = function(setting) { this.setting = $.extend({}, this.setting || $.fn.atwho["default"], setting); this.view.init(); return this.model.reload(this.setting.data); }; Controller.prototype.call_default = function() { var args, func_name; func_name = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : []; try { return DEFAULT_CALLBACKS[func_name].apply(this, args); } catch (error) { return $.error("" + error + " Or maybe At.js doesn't have function " + func_name); } }; Controller.prototype.trigger = function(name, data) { var alias, event_name; data.push(this); alias = this.get_opt('alias'); event_name = alias ? "" + name + "-" + alias + ".atwho" : "" + name + ".atwho"; return this.$inputor.trigger(event_name, data); }; Controller.prototype.callbacks = function(func_name) { return this.get_opt("callbacks")[func_name] || DEFAULT_CALLBACKS[func_name]; }; Controller.prototype.get_opt = function(at, default_value) { try { return this.setting[at]; } catch (e) { return null; } }; Controller.prototype.content = function() { var result = { content: null, offset: 0 }; if (this.$inputor.is('textarea, input')) { result.content = this.$inputor.val(); } else { var textNode = $(document.createElement('div')); var html = this.$inputor.html(); var breaks = /<br(\s+)?(\/)?>/g; result.offset = html.match(breaks) ? html.match(breaks).length : 0; textNode.html(html.replace(breaks, "\n")); result.content = textNode.text(); } return result; }; Controller.prototype.catch_query = function() { var caret_pos, contents, end, query, start, subtext; contents = this.content(); ////caret_pos = this.$inputor.caret('pos'); caret_pos = this.$inputor.caret('pos', this.setting.cWindow) + contents.offset; subtext = contents.content.slice(0, caret_pos); query = this.callbacks("matcher").call(this, this.at, subtext, this.get_opt('start_with_space')); if (typeof query === "string" && query.length <= this.get_opt('max_len', 20)) { start = caret_pos - query.length; end = start + query.length; this.pos = start; query = { 'text': query.toLowerCase(), 'head_pos': start, 'end_pos': end }; this.trigger("matched", [this.at, query.text]); } else { this.view.hide(); } return this.query = query; }; Controller.prototype.rect = function() { var c, scale_bottom; /////if (!(c = this.$inputor.caret('offset', this.pos - 1))) { if (!(c = this.$inputor.caret('offset', this.setting.cWindow, this.pos - 1))) { return; } if (this.$inputor.attr('contentEditable') === 'true') { c = (this.cur_rect || (this.cur_rect = c)) || c; } scale_bottom = document.selection ? 0 : 2; return { left: c.left, top: c.top, bottom: c.top + c.height + scale_bottom }; }; Controller.prototype.reset_rect = function() { if (this.$inputor.attr('contentEditable') === 'true') { return this.cur_rect = null; } }; Controller.prototype.mark_range = function() { return this.range = this.get_range() || this.get_ie_range(); }; Controller.prototype.clear_range = function() { return this.range = null; }; Controller.prototype.get_range = function() { ////return this.range || (window.getSelection ? window.getSelection().getRangeAt(0) : void 0); var thisWin = this.setting.cWindow; //////return this.range || (thisWin.getSelection ? thisWin.getSelection().getRangeAt(0) : void 0); return thisWin.getSelection ? thisWin.getSelection().getRangeAt(0) : (this.range || void 0); }; Controller.prototype.get_ie_range = function() { return this.range || (document.selection ? document.selection.createRange() : void 0); }; Controller.prototype.insert_content_for = function($li) { var data, data_value, tpl; data_value = $li.data('value'); tpl = this.get_opt('insert_tpl'); if (this.$inputor.is('textarea, input') || !tpl) { return data_value; } data = $.extend({}, $li.data('item-data'), { 'atwho-data-value': data_value, 'atwho-at': this.at }); return this.callbacks("tpl_eval").call(this, tpl, data); }; Controller.prototype.insert = function(content, $li) { ////var $inputor, $insert_node, class_name, content_node, insert_node, pos, range, sel, source, start_str, text; //////////var $inputor, $insert_node, class_name, content_node, insert_node, pos, range, sel, source, start_str, text, thisWin; var $inputor, $insert_node, class_name, content_editable, content_node, insert_node, pos, range, sel, source, start_str, text; $inputor = this.$inputor; if ($inputor.attr('contentEditable') === 'true') { ////////// content_editable = '' + /firefox/i.test(navigator.userAgent); //class_name = "atwho-view-flag atwho-view-flag-" + (this.get_opt('alias') || this.at); class_name = "vanilla-mention-" + (this.get_opt('alias') || this.at); //////////content_node = "" + content + "<span contenteditable='false'>&nbsp;<span>"; //////////insert_node = "<span contenteditable='false' class='" + class_name + "'>" + content_node + "</span>"; //content_node = ("" + content + "<span contenteditable='") + content_editable + "'>&nbsp;<span>"; content_node = "" + content + "&nbsp;"; //content_node = "" + content; //insert_node = "<span contenteditable='" + content_editable + ("' class='" + class_name + "'>" + content_node + "</span>"); insert_node = '<span class="' + class_name + '">' + content_node + '</span>'; $insert_node = $(insert_node).data('atwho-data-item', $li.data('item-data')); if (document.selection) { $insert_node = $("<span contenteditable='true'></span>").html($insert_node); } } if ($inputor.is('textarea, input')) { content = '' + content; source = $inputor.val(); start_str = source.slice(0, Math.max(this.query.head_pos - this.at.length, 0)); text = "" + start_str + content + " " + (source.slice(this.query['end_pos'] || 0)); $inputor.val(text); ////$inputor.caret('pos', start_str.length + content.length + 1); $inputor.caret('pos', this.setting.cWindow, start_str.length + content.length + 1); } else if (range = this.get_range()) { //// thisWin = this.setting.cWindow; pos = range.startOffset - (this.query.end_pos - this.query.head_pos) - this.at.length; range.setStart(range.endContainer, Math.max(pos, 0)); range.setEnd(range.endContainer, range.endOffset); range.deleteContents(); range.insertNode(document.createTextNode(content + " ")); //range.insertNode($insert_node[0]); range.collapse(false); ////sel = window.getSelection(); sel = thisWin.getSelection(); sel.removeAllRanges(); sel.addRange(range); } else if (range = this.get_ie_range()) { range.moveStart('character', this.query.end_pos - this.query.head_pos - this.at.length); /////// range.pasteHTML($insert_node[0]); range.collapse(false); range.select(); } $inputor.focus(); return $inputor.change(); }; Controller.prototype.render_view = function(data) { var search_key; search_key = this.get_opt("search_key"); data = this.callbacks("sorter").call(this, this.query.text, data.slice(0, 1001), search_key); return this.view.render(data.slice(0, this.get_opt('limit'))); }; Controller.prototype.look_up = function() { var query, _callback; if (!(query = this.catch_query())) { return; } _callback = function(data) { if (data && data.length > 0) { return this.render_view(data); } else { return this.view.hide(); } }; this.model.query(query.text, $.proxy(_callback, this)); return query; }; return Controller; })(); Model = (function() { var _storage; _storage = {}; function Model(context) { this.context = context; this.at = this.context.at; } Model.prototype.saved = function() { return this.fetch() > 0; }; Model.prototype.query = function(query, callback) { var data, search_key, _ref; data = this.fetch(); search_key = this.context.get_opt("search_key"); callback(data = this.context.callbacks('filter').call(this.context, query, data, search_key)); if (!(data && data.length > 0)) { return (_ref = this.context.callbacks('remote_filter')) != null ? _ref.call(this.context, query, callback) : void 0; } }; Model.prototype.fetch = function() { return _storage[this.at] || []; }; Model.prototype.save = function(data) { return _storage[this.at] = this.context.callbacks("before_save").call(this.context, data || []); }; Model.prototype.load = function(data) { if (!(this.saved() || !data)) { return this._load(data); } }; Model.prototype.reload = function(data) { return this._load(data); }; Model.prototype._load = function(data) { var _this = this; if (typeof data === "string") { return $.ajax(data, { dataType: "json" }).done(function(data) { return _this.save(data); }); } else { return this.save(data); } }; return Model; })(); View = (function() { function View(context) { this.context = context; this.$el = $("<div class='atwho-view'><ul class='atwho-view-ul'></ul></div>"); this.timeout_id = null; this.context.$el.append(this.$el); this.bind_event(); } View.prototype.init = function() { var id; id = this.context.get_opt("alias") || this.context.at.charCodeAt(0); return this.$el.attr({ 'id': "at-view-" + id }); }; View.prototype.bind_event = function() { var $menu, _this = this; $menu = this.$el.find('ul'); $menu.on('mouseenter.atwho-view', 'li', function(e) { $menu.find('.cur').removeClass('cur'); return $(e.currentTarget).addClass('cur'); }).on('click', function(e) { _this.choose(e); return e.preventDefault(); }); return this.$el.on('mouseenter.atwho-view', 'ul', function(e) { return _this.context.mark_range(); }).on('mouseleave.atwho-view', 'ul', function(e) { return _this.context.clear_range(); }); }; View.prototype.visible = function() { return this.$el.is(":visible"); }; View.prototype.choose = function(event) { var $li, content; if (($li = this.$el.find(".cur")).length) { event.preventDefault(); content = this.context.insert_content_for($li); this.context.insert(this.context.callbacks("before_insert").call(this.context, content, $li), $li); this.context.trigger("inserted", [$li]); return this.hide(); } }; View.prototype.reposition = function(rect) { ////var offset; ////if (rect.bottom + this.$el.height() - $(window).scrollTop() > $(window).height()) { var offset; //// // Make sure the non-iframe version still references window. var thisWin = (this.context.setting.cWindow) ? null : window; if (rect.bottom + this.$el.height() - $(thisWin).scrollTop() > $(thisWin).height()) { rect.bottom = rect.top - this.$el.height(); } offset = { left: rect.left, top: rect.bottom }; this.$el.offset(offset); return this.context.trigger("reposition", [offset]); }; View.prototype.next = function() { var cur, next; cur = this.$el.find('.cur').removeClass('cur'); next = cur.next(); if (!next.length) { next = this.$el.find('li:first'); } return next.addClass('cur'); }; View.prototype.prev = function() { var cur, prev; cur = this.$el.find('.cur').removeClass('cur'); prev = cur.prev(); if (!prev.length) { prev = this.$el.find('li:last'); } return prev.addClass('cur'); }; View.prototype.show = function() { var rect; if (!this.visible()) { this.$el.show(); } if (rect = this.context.rect()) { return this.reposition(rect); } }; View.prototype.hide = function(time) { var callback, _this = this; if (isNaN(time && this.visible())) { this.context.reset_rect(); return this.$el.hide(); } else { callback = function() { return _this.hide(); }; clearTimeout(this.timeout_id); return this.timeout_id = setTimeout(callback, time); } }; View.prototype.render = function(list) { var $li, $ul, item, li, tpl, _i, _len; if (!$.isArray(list || list.length <= 0)) { this.hide(); return; } this.$el.find('ul').empty(); $ul = this.$el.find('ul'); tpl = this.context.get_opt('tpl'); for (_i = 0, _len = list.length; _i < _len; _i++) { item = list[_i]; item = $.extend({}, item, { 'atwho-at': this.context.at }); li = this.context.callbacks("tpl_eval").call(this.context, tpl, item); $li = $(this.context.callbacks("highlighter").call(this.context, li, this.context.query.text)); $li.data("item-data", item); $ul.append($li); } this.show(); return $ul.find("li:first").addClass("cur"); }; return View; })(); KEY_CODE = { DOWN: 40, UP: 38, ESC: 27, TAB: 9, ENTER: 13 }; DEFAULT_CALLBACKS = { before_save: function(data) { var item, _i, _len, _results; if (!$.isArray(data)) { return data; } _results = []; for (_i = 0, _len = data.length; _i < _len; _i++) { item = data[_i]; if ($.isPlainObject(item)) { _results.push(item); } else { _results.push({ name: item }); } } return _results; }, matcher: function(flag, subtext, should_start_with_space) { var match, regexp; flag = flag.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); if (should_start_with_space) { flag = '(?:^|\\s)' + flag; } regexp = new RegExp(flag + '([A-Za-z0-9_\+\-]*)$|' + flag + '([^\\x00-\\xff]*)$', 'gi'); match = regexp.exec(subtext); if (match) { return match[2] || match[1]; } else { return null; } }, filter: function(query, data, search_key) { var item, _i, _len, _results; _results = []; for (_i = 0, _len = data.length; _i < _len; _i++) { item = data[_i]; if (~item[search_key].toLowerCase().indexOf(query)) { _results.push(item); } } return _results; }, remote_filter: null, sorter: function(query, items, search_key) { var item, _i, _len, _results; if (!query) { return items; } _results = []; for (_i = 0, _len = items.length; _i < _len; _i++) { item = items[_i]; item.atwho_order = item[search_key].toLowerCase().indexOf(query); if (item.atwho_order > -1) { _results.push(item); } } return _results.sort(function(a, b) { return a.atwho_order - b.atwho_order; }); }, tpl_eval: function(tpl, map) { try { return tpl.replace(/\$\{([^\}]*)\}/g, function(tag, key, pos) { return map[key]; }); } catch (error) { return ""; } }, highlighter: function(li, query) { var regexp; if (!query) { return li; } regexp = new RegExp(">\\s*(\\w*)(" + query.replace("+", "\\+") + ")(\\w*)\\s*<", 'ig'); return li.replace(regexp, function(str, $1, $2, $3) { return '> ' + $1 + '<strong>' + $2 + '</strong>' + $3 + ' <'; }); }, before_insert: function(value, $li) { return value; } }; Api = { load: function(at, data) { var c; if (c = this.controller(at)) { return c.model.load(data); } }, getInsertedItemsWithIDs: function(at) { var c, ids, items; if (!(c = this.controller(at))) { return [null, null]; } if (at) { at = "-" + (c.get_opt('alias') || c.at); } ids = []; items = $.map(this.$inputor.find("span.atwho-view-flag" + (at || "")), function(item) { var data; data = $(item).data('atwho-data-item'); if (ids.indexOf(data.id) > -1) { return; } if (data.id) { ids.push = data.id; } return data; }); return [ids, items]; }, getInsertedItems: function(at) { return Api.getInsertedItemsWithIDs.apply(this, [at])[1]; }, getInsertedIDs: function(at) { return Api.getInsertedItemsWithIDs.apply(this, [at])[0]; }, run: function() { return this.dispatch(); } }; Atwho = { init: function(options) { var $this, app; app = ($this = $(this)).data("atwho"); if (!app) { $this.data('atwho', (app = new App(this))); } app.reg(options.at, options); return this; } }; $CONTAINER = $("<div id='atwho-container'></div>"); $.fn.atwho = function(method) { var result, _args; _args = arguments; $('body').append($CONTAINER); result = null; this.filter('textarea, input, [contenteditable=true]').each(function() { //console.log('at inloop'); //console.log(this); var app; if (typeof method === 'object' || !method) { return Atwho.init.apply(this, _args); } else if (Api[method]) { if (app = $(this).data('atwho')) { return result = Api[method].apply(app, Array.prototype.slice.call(_args, 1)); } } else { return $.error("Method " + method + " does not exist on jQuery.caret"); } }); return result || this; }; return $.fn.atwho["default"] = { at: void 0, alias: void 0, data: null, tpl: "<li data-value='${atwho-at}${name}'>${name}</li>", insert_tpl: "<span>${atwho-data-value}</span>", callbacks: DEFAULT_CALLBACKS, search_key: "name", start_with_space: true, limit: 5, max_len: 20, display_timeout: 300, //// cWindow: window }; }); }).call(this);
rwmcoder/Vanilla
js/library/jquery.atwho.js
JavaScript
gpl-2.0
35,430
'use strict'; const common = require('../common.js'); const bench = common.createBenchmark(main, { pieces: [1, 4, 16], pieceSize: [1, 16, 256], withTotalLength: [0, 1], n: [1024] }); function main(conf) { const n = +conf.n; const size = +conf.pieceSize; const pieces = +conf.pieces; const list = new Array(pieces); list.fill(Buffer.allocUnsafe(size)); const totalLength = conf.withTotalLength ? pieces * size : undefined; bench.start(); for (var i = 0; i < n * 1024; i++) { Buffer.concat(list, totalLength); } bench.end(n); }
domino-team/openwrt-cc
package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/benchmark/buffers/buffer-concat.js
JavaScript
gpl-2.0
563
function test() { return (function foo(){}).name === 'foo' && (function(){}).name === ''; } if (!test()) throw new Error("Test failed");
Debian/openjfx
modules/web/src/main/native/Source/JavaScriptCore/tests/es6/function_name_property_function_expressions.js
JavaScript
gpl-2.0
153
FD40.ready(function($) { var jQuery = $;// Catalan jQuery.timeago.settings.strings = { prefixAgo: "fa", prefixFromNow: "d'aqui a", suffixAgo: null, suffixFromNow: null, seconds: "menys d'1 minut", minute: "1 minut", minutes: "uns %d minuts", hour: "1 hora", hours: "unes %d hores", day: "1 dia", days: "%d dies", month: "aproximadament un mes", months: "%d mesos", year: "aproximadament un any", years: "%d anys" }; });
BetterBetterBetter/WheresWalden
media/foundry/4.0/scripts/timeago/ca.js
JavaScript
gpl-2.0
450
/* * JCE Editor 2.2.4 * @package JCE * @url http://www.joomlacontenteditor.net * @copyright Copyright (C) 2006 - 2012 Ryan Demmer. All rights reserved * @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html * @date 16 July 2012 * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * NOTE : Javascript files have been compressed for speed and can be uncompressed using http://jsbeautifier.org/ */ tinyMCEPopup.requireLangPack();var ColorPicker={settings:{},init:function(){var self=this,ed=tinyMCEPopup.editor,color=tinyMCEPopup.getWindowArg('input_color')||'#FFFFFF';$('#tmp_color').val(color).colorpicker($.extend(this.settings,{dialog:false,insert:function(){return ColorPicker.insert();},close:function(){return tinyMCEPopup.close();}}));$('button#insert').button({icons:{primary:'ui-icon-check'}});$('#jce').css('display','block');},insert:function(){var color=$("#colorpicker_color").val(),f=tinyMCEPopup.getWindowArg('func');tinyMCEPopup.restoreSelection();if(f) f(color);tinyMCEPopup.close();}};tinyMCEPopup.onInit.add(ColorPicker.init,ColorPicker);
ArtificialEX/jwexport
components/com_jce/editor/tiny_mce/themes/advanced/js/colorpicker.js
JavaScript
gpl-2.0
1,641
/** * @file Visual mapping. */ define(function (require) { var zrUtil = require('zrender/core/util'); var zrColor = require('zrender/tool/color'); var linearMap = require('../util/number').linearMap; var each = zrUtil.each; var isObject = zrUtil.isObject; var CATEGORY_DEFAULT_VISUAL_INDEX = -1; /** * @param {Object} option * @param {string} [option.type] See visualHandlers. * @param {string} [option.mappingMethod] 'linear' or 'piecewise' or 'category' or 'fixed' * @param {Array.<number>=} [option.dataExtent] [minExtent, maxExtent], * required when mappingMethod is 'linear' * @param {Array.<Object>=} [option.pieceList] [ * {value: someValue}, * {interval: [min1, max1], visual: {...}}, * {interval: [min2, max2]} * ], * required when mappingMethod is 'piecewise'. * Visual for only each piece can be specified. * @param {Array.<string|Object>=} [option.categories] ['cate1', 'cate2'] * required when mappingMethod is 'category'. * If no option.categories, categories is set * as [0, 1, 2, ...]. * @param {boolean} [option.loop=false] Whether loop mapping when mappingMethod is 'category'. * @param {(Array|Object|*)} [option.visual] Visual data. * when mappingMethod is 'category', * visual data can be array or object * (like: {cate1: '#222', none: '#fff'}) * or primary types (which represents * defualt category visual), otherwise visual * can be array or primary (which will be * normalized to array). * */ var VisualMapping = function (option) { var mappingMethod = option.mappingMethod; var visualType = option.type; /** * @readOnly * @type {Object} */ var thisOption = this.option = zrUtil.clone(option); /** * @readOnly * @type {string} */ this.type = visualType; /** * @readOnly * @type {string} */ this.mappingMethod = mappingMethod; /** * @private * @type {Function} */ this._normalizeData = normalizers[mappingMethod]; var visualHandler = visualHandlers[visualType]; /** * @public * @type {Function} */ this.applyVisual = visualHandler.applyVisual; /** * @public * @type {Function} */ this.getColorMapper = visualHandler.getColorMapper; /** * @private * @type {Function} */ this._doMap = visualHandler._doMap[mappingMethod]; if (mappingMethod === 'piecewise') { normalizeVisualRange(thisOption); preprocessForPiecewise(thisOption); } else if (mappingMethod === 'category') { thisOption.categories ? preprocessForSpecifiedCategory(thisOption) // categories is ordinal when thisOption.categories not specified, // which need no more preprocess except normalize visual. : normalizeVisualRange(thisOption, true); } else { // mappingMethod === 'linear' or 'fixed' zrUtil.assert(mappingMethod !== 'linear' || thisOption.dataExtent); normalizeVisualRange(thisOption); } }; VisualMapping.prototype = { constructor: VisualMapping, mapValueToVisual: function (value) { var normalized = this._normalizeData(value); return this._doMap(normalized, value); }, getNormalizer: function () { return zrUtil.bind(this._normalizeData, this); } }; var visualHandlers = VisualMapping.visualHandlers = { color: { applyVisual: makeApplyVisual('color'), /** * Create a mapper function * @return {Function} */ getColorMapper: function () { var thisOption = this.option; return zrUtil.bind( thisOption.mappingMethod === 'category' ? function (value, isNormalized) { !isNormalized && (value = this._normalizeData(value)); return doMapCategory.call(this, value); } : function (value, isNormalized, out) { // If output rgb array // which will be much faster and useful in pixel manipulation var returnRGBArray = !!out; !isNormalized && (value = this._normalizeData(value)); out = zrColor.fastMapToColor(value, thisOption.parsedVisual, out); return returnRGBArray ? out : zrColor.stringify(out, 'rgba'); }, this ); }, _doMap: { linear: function (normalized) { return zrColor.stringify( zrColor.fastMapToColor(normalized, this.option.parsedVisual), 'rgba' ); }, category: doMapCategory, piecewise: function (normalized, value) { var result = getSpecifiedVisual.call(this, value); if (result == null) { result = zrColor.stringify( zrColor.fastMapToColor(normalized, this.option.parsedVisual), 'rgba' ); } return result; }, fixed: doMapFixed } }, colorHue: makePartialColorVisualHandler(function (color, value) { return zrColor.modifyHSL(color, value); }), colorSaturation: makePartialColorVisualHandler(function (color, value) { return zrColor.modifyHSL(color, null, value); }), colorLightness: makePartialColorVisualHandler(function (color, value) { return zrColor.modifyHSL(color, null, null, value); }), colorAlpha: makePartialColorVisualHandler(function (color, value) { return zrColor.modifyAlpha(color, value); }), opacity: { applyVisual: makeApplyVisual('opacity'), _doMap: makeDoMap([0, 1]) }, symbol: { applyVisual: function (value, getter, setter) { var symbolCfg = this.mapValueToVisual(value); if (zrUtil.isString(symbolCfg)) { setter('symbol', symbolCfg); } else if (isObject(symbolCfg)) { for (var name in symbolCfg) { if (symbolCfg.hasOwnProperty(name)) { setter(name, symbolCfg[name]); } } } }, _doMap: { linear: doMapToArray, category: doMapCategory, piecewise: function (normalized, value) { var result = getSpecifiedVisual.call(this, value); if (result == null) { result = doMapToArray.call(this, normalized); } return result; }, fixed: doMapFixed } }, symbolSize: { applyVisual: makeApplyVisual('symbolSize'), _doMap: makeDoMap([0, 1]) } }; function preprocessForPiecewise(thisOption) { var pieceList = thisOption.pieceList; thisOption.hasSpecialVisual = false; zrUtil.each(pieceList, function (piece, index) { piece.originIndex = index; // piece.visual is "result visual value" but not // a visual range, so it does not need to be normalized. if (piece.visual != null) { thisOption.hasSpecialVisual = true; } }); } function preprocessForSpecifiedCategory(thisOption) { // Hash categories. var categories = thisOption.categories; var visual = thisOption.visual; var categoryMap = thisOption.categoryMap = {}; each(categories, function (cate, index) { categoryMap[cate] = index; }); // Process visual map input. if (!zrUtil.isArray(visual)) { var visualArr = []; if (zrUtil.isObject(visual)) { each(visual, function (v, cate) { var index = categoryMap[cate]; visualArr[index != null ? index : CATEGORY_DEFAULT_VISUAL_INDEX] = v; }); } else { // Is primary type, represents default visual. visualArr[CATEGORY_DEFAULT_VISUAL_INDEX] = visual; } visual = setVisualToOption(thisOption, visualArr); } // Remove categories that has no visual, // then we can mapping them to CATEGORY_DEFAULT_VISUAL_INDEX. for (var i = categories.length - 1; i >= 0; i--) { if (visual[i] == null) { delete categoryMap[categories[i]]; categories.pop(); } } } function normalizeVisualRange(thisOption, isCategory) { var visual = thisOption.visual; var visualArr = []; if (zrUtil.isObject(visual)) { each(visual, function (v) { visualArr.push(v); }); } else if (visual != null) { visualArr.push(visual); } var doNotNeedPair = {color: 1, symbol: 1}; if (!isCategory && visualArr.length === 1 && !doNotNeedPair.hasOwnProperty(thisOption.type) ) { // Do not care visualArr.length === 0, which is illegal. visualArr[1] = visualArr[0]; } setVisualToOption(thisOption, visualArr); } function makePartialColorVisualHandler(applyValue) { return { applyVisual: function (value, getter, setter) { value = this.mapValueToVisual(value); // Must not be array value setter('color', applyValue(getter('color'), value)); }, _doMap: makeDoMap([0, 1]) }; } function doMapToArray(normalized) { var visual = this.option.visual; return visual[ Math.round(linearMap(normalized, [0, 1], [0, visual.length - 1], true)) ] || {}; } function makeApplyVisual(visualType) { return function (value, getter, setter) { setter(visualType, this.mapValueToVisual(value)); }; } function doMapCategory(normalized) { var visual = this.option.visual; return visual[ (this.option.loop && normalized !== CATEGORY_DEFAULT_VISUAL_INDEX) ? normalized % visual.length : normalized ]; } function doMapFixed() { return this.option.visual[0]; } function makeDoMap(sourceExtent) { return { linear: function (normalized) { return linearMap(normalized, sourceExtent, this.option.visual, true); }, category: doMapCategory, piecewise: function (normalized, value) { var result = getSpecifiedVisual.call(this, value); if (result == null) { result = linearMap(normalized, sourceExtent, this.option.visual, true); } return result; }, fixed: doMapFixed }; } function getSpecifiedVisual(value) { var thisOption = this.option; var pieceList = thisOption.pieceList; if (thisOption.hasSpecialVisual) { var pieceIndex = VisualMapping.findPieceIndex(value, pieceList); var piece = pieceList[pieceIndex]; if (piece && piece.visual) { return piece.visual[this.type]; } } } function setVisualToOption(thisOption, visualArr) { thisOption.visual = visualArr; if (thisOption.type === 'color') { thisOption.parsedVisual = zrUtil.map(visualArr, function (item) { return zrColor.parse(item); }); } return visualArr; } /** * Normalizers by mapping methods. */ var normalizers = { linear: function (value) { return linearMap(value, this.option.dataExtent, [0, 1], true); }, piecewise: function (value) { var pieceList = this.option.pieceList; var pieceIndex = VisualMapping.findPieceIndex(value, pieceList, true); if (pieceIndex != null) { return linearMap(pieceIndex, [0, pieceList.length - 1], [0, 1], true); } }, category: function (value) { var index = this.option.categories ? this.option.categoryMap[value] : value; // ordinal return index == null ? CATEGORY_DEFAULT_VISUAL_INDEX : index; }, fixed: zrUtil.noop }; /** * List available visual types. * * @public * @return {Array.<string>} */ VisualMapping.listVisualTypes = function () { var visualTypes = []; zrUtil.each(visualHandlers, function (handler, key) { visualTypes.push(key); }); return visualTypes; }; /** * @public */ VisualMapping.addVisualHandler = function (name, handler) { visualHandlers[name] = handler; }; /** * @public */ VisualMapping.isValidType = function (visualType) { return visualHandlers.hasOwnProperty(visualType); }; /** * Convinent method. * Visual can be Object or Array or primary type. * * @public */ VisualMapping.eachVisual = function (visual, callback, context) { if (zrUtil.isObject(visual)) { zrUtil.each(visual, callback, context); } else { callback.call(context, visual); } }; VisualMapping.mapVisual = function (visual, callback, context) { var isPrimary; var newVisual = zrUtil.isArray(visual) ? [] : zrUtil.isObject(visual) ? {} : (isPrimary = true, null); VisualMapping.eachVisual(visual, function (v, key) { var newVal = callback.call(context, v, key); isPrimary ? (newVisual = newVal) : (newVisual[key] = newVal); }); return newVisual; }; /** * @public * @param {Object} obj * @return {Oject} new object containers visual values. * If no visuals, return null. */ VisualMapping.retrieveVisuals = function (obj) { var ret = {}; var hasVisual; obj && each(visualHandlers, function (h, visualType) { if (obj.hasOwnProperty(visualType)) { ret[visualType] = obj[visualType]; hasVisual = true; } }); return hasVisual ? ret : null; }; /** * Give order to visual types, considering colorSaturation, colorAlpha depends on color. * * @public * @param {(Object|Array)} visualTypes If Object, like: {color: ..., colorSaturation: ...} * IF Array, like: ['color', 'symbol', 'colorSaturation'] * @return {Array.<string>} Sorted visual types. */ VisualMapping.prepareVisualTypes = function (visualTypes) { if (isObject(visualTypes)) { var types = []; each(visualTypes, function (item, type) { types.push(type); }); visualTypes = types; } else if (zrUtil.isArray(visualTypes)) { visualTypes = visualTypes.slice(); } else { return []; } visualTypes.sort(function (type1, type2) { // color should be front of colorSaturation, colorAlpha, ... // symbol and symbolSize do not matter. return (type2 === 'color' && type1 !== 'color' && type1.indexOf('color') === 0) ? 1 : -1; }); return visualTypes; }; /** * 'color', 'colorSaturation', 'colorAlpha', ... are depends on 'color'. * Other visuals are only depends on themself. * * @public * @param {string} visualType1 * @param {string} visualType2 * @return {boolean} */ VisualMapping.dependsOn = function (visualType1, visualType2) { return visualType2 === 'color' ? !!(visualType1 && visualType1.indexOf(visualType2) === 0) : visualType1 === visualType2; }; /** * @param {number} value * @param {Array.<Object>} pieceList [{value: ..., interval: [min, max]}, ...] * Always from small to big. * @param {boolean} [findClosestWhenOutside=false] * @return {number} index */ VisualMapping.findPieceIndex = function (value, pieceList, findClosestWhenOutside) { var possibleI; var abs = Infinity; // value has the higher priority. for (var i = 0, len = pieceList.length; i < len; i++) { var pieceValue = pieceList[i].value; if (pieceValue != null) { if (pieceValue === value // FIXME // It is supposed to compare value according to value type of dimension, // but currently value type can exactly be string or number. // Compromise for numeric-like string (like '12'), especially // in the case that visualMap.categories is ['22', '33']. || (typeof pieceValue === 'string' && pieceValue === value + '') ) { return i; } findClosestWhenOutside && updatePossible(pieceValue, i); } } for (var i = 0, len = pieceList.length; i < len; i++) { var piece = pieceList[i]; var interval = piece.interval; var close = piece.close; if (interval) { if (interval[0] === -Infinity) { if (littleThan(close[1], value, interval[1])) { return i; } } else if (interval[1] === Infinity) { if (littleThan(close[0], interval[0], value)) { return i; } } else if ( littleThan(close[0], interval[0], value) && littleThan(close[1], value, interval[1]) ) { return i; } findClosestWhenOutside && updatePossible(interval[0], i); findClosestWhenOutside && updatePossible(interval[1], i); } } if (findClosestWhenOutside) { return value === Infinity ? pieceList.length - 1 : value === -Infinity ? 0 : possibleI; } function updatePossible(val, index) { var newAbs = Math.abs(val - value); if (newAbs < abs) { abs = newAbs; possibleI = index; } } }; function littleThan(close, a, b) { return close ? a <= b : a < b; } return VisualMapping; });
mo-norant/FinHeartBel
website/node_modules/echarts/src/visual/VisualMapping.js
JavaScript
gpl-3.0
20,627
var express = require('express') var app = module.exports = express() app.get('/404', require('lib/site/layout')) app.get('*', function (req, res) { res.redirect('/404') })
democracy-os-fr/democracyos
lib/site/error-pages/not-found/index.js
JavaScript
gpl-3.0
176
// Set iterators produces entries in the order they were inserted. var set = Set(); var i; for (i = 7; i !== 1; i = i * 7 % 1117) set.add(i); assertEq(set.size, 557); i = 7; for (var v of set) { assertEq(v, i); i = i * 7 % 1117; } assertEq(i, 1);
SlateScience/MozillaJS
js/src/jit-test/tests/collections/Set-iterator-order.js
JavaScript
mpl-2.0
261
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ exports.FLACDemuxer = require('./src/demuxer'); exports.FLACDecoder = require('./src/decoder'); require('./src/ogg'); },{"./src/decoder":2,"./src/demuxer":3,"./src/ogg":4}],2:[function(require,module,exports){ /* * FLAC.js - Free Lossless Audio Codec decoder in JavaScript * Original C version from FFmpeg (c) 2003 Alex Beregszaszi * JavaScript port by Devon Govett and Jens Nockert of Official.fm Labs * * Licensed under the same terms as the original. The original * license follows. * * FLAC.js is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FLAC.js is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ var AV = (window.AV); var FLACDecoder = AV.Decoder.extend(function() { AV.Decoder.register('flac', this); this.prototype.setCookie = function(cookie) { this.cookie = cookie; // initialize arrays this.decoded = []; for (var i = 0; i < this.format.channelsPerFrame; i++) { this.decoded[i] = new Int32Array(cookie.maxBlockSize); } }; const BLOCK_SIZES = new Int16Array([ 0, 192, 576 << 0, 576 << 1, 576 << 2, 576 << 3, 0, 0, 256 << 0, 256 << 1, 256 << 2, 256 << 3, 256 << 4, 256 << 5, 256 << 6, 256 << 7 ]); const SAMPLE_RATES = new Int32Array([ 0, 88200, 176400, 192000, 8000, 16000, 22050, 24000, 32000, 44100, 48000, 96000, 0, 0, 0, 0 ]); const SAMPLE_SIZES = new Int8Array([ 0, 8, 12, 0, 16, 20, 24, 0 ]); const MAX_CHANNELS = 8, CHMODE_INDEPENDENT = 0, CHMODE_LEFT_SIDE = 8, CHMODE_RIGHT_SIDE = 9, CHMODE_MID_SIDE = 10; this.prototype.readChunk = function() { var stream = this.bitstream; if (!stream.available(32)) return; // frame sync code if ((stream.read(15) & 0x7FFF) !== 0x7FFC) throw new Error('Invalid sync code'); var isVarSize = stream.read(1), // variable block size stream code bsCode = stream.read(4), // block size srCode = stream.read(4), // sample rate code chMode = stream.read(4), // channel mode bpsCode = stream.read(3); // bits per sample stream.advance(1); // reserved bit // channels this.chMode = chMode; var channels; if (chMode < MAX_CHANNELS) { channels = chMode + 1; this.chMode = CHMODE_INDEPENDENT; } else if (chMode <= CHMODE_MID_SIDE) { channels = 2; } else { throw new Error('Invalid channel mode'); } if (channels !== this.format.channelsPerFrame) throw new Error('Switching channel layout mid-stream not supported.'); // bits per sample if (bpsCode === 3 || bpsCode === 7) throw new Error('Invalid sample size code'); this.bps = SAMPLE_SIZES[bpsCode]; if (this.bps !== this.format.bitsPerChannel) throw new Error('Switching bits per sample mid-stream not supported.'); var sampleShift, is32; if (this.bps > 16) { sampleShift = 32 - this.bps; is32 = true; } else { sampleShift = 16 - this.bps; is32 = false; } // sample number or frame number // see http://www.hydrogenaudio.org/forums/index.php?s=ea7085ffe6d57132c36e6105c0d434c9&showtopic=88390&pid=754269&st=0&#entry754269 var ones = 0; while (stream.read(1) === 1) ones++; var frame_or_sample_num = stream.read(7 - ones); for (; ones > 1; ones--) { stream.advance(2); // == 2 frame_or_sample_num = (frame_or_sample_num << 6) | stream.read(6); } // block size if (bsCode === 0) throw new Error('Reserved blocksize code'); else if (bsCode === 6) this.blockSize = stream.read(8) + 1; else if (bsCode === 7) this.blockSize = stream.read(16) + 1; else this.blockSize = BLOCK_SIZES[bsCode]; // sample rate var sampleRate; if (srCode < 12) sampleRate = SAMPLE_RATES[srCode]; else if (srCode === 12) sampleRate = stream.read(8) * 1000; else if (srCode === 13) sampleRate = stream.read(16); else if (srCode === 14) sampleRate = stream.read(16) * 10; else throw new Error('Invalid sample rate code'); stream.advance(8); // skip CRC check // subframes for (var i = 0; i < channels; i++) this.decodeSubframe(i); stream.align(); stream.advance(16); // skip CRC frame footer var output = new ArrayBuffer(this.blockSize * channels * this.bps / 8), buf = is32 ? new Int32Array(output) : new Int16Array(output), blockSize = this.blockSize, decoded = this.decoded, j = 0; switch (this.chMode) { case CHMODE_INDEPENDENT: for (var k = 0; k < blockSize; k++) { for (var i = 0; i < channels; i++) { buf[j++] = decoded[i][k] << sampleShift; } } break; case CHMODE_LEFT_SIDE: for (var i = 0; i < blockSize; i++) { var left = decoded[0][i], right = decoded[1][i]; buf[j++] = left << sampleShift; buf[j++] = (left - right) << sampleShift; } break; case CHMODE_RIGHT_SIDE: for (var i = 0; i < blockSize; i++) { var left = decoded[0][i], right = decoded[1][i]; buf[j++] = (left + right) << sampleShift; buf[j++] = right << sampleShift; } break; case CHMODE_MID_SIDE: for (var i = 0; i < blockSize; i++) { var left = decoded[0][i], right = decoded[1][i]; left -= right >> 1; buf[j++] = (left + right) << sampleShift; buf[j++] = left << sampleShift; } break; } return buf; }; this.prototype.decodeSubframe = function(channel) { var wasted = 0, stream = this.bitstream, blockSize = this.blockSize, decoded = this.decoded; this.curr_bps = this.bps; if (channel === 0) { if (this.chMode === CHMODE_RIGHT_SIDE) this.curr_bps++; } else { if (this.chMode === CHMODE_LEFT_SIDE || this.chMode === CHMODE_MID_SIDE) this.curr_bps++; } if (stream.read(1)) throw new Error("Invalid subframe padding"); var type = stream.read(6); if (stream.read(1)) { wasted = 1; while (!stream.read(1)) wasted++; this.curr_bps -= wasted; } if (this.curr_bps > 32) throw new Error("decorrelated bit depth > 32 (" + this.curr_bps + ")"); if (type === 0) { var tmp = stream.read(this.curr_bps, true); for (var i = 0; i < blockSize; i++) decoded[channel][i] = tmp; } else if (type === 1) { var bps = this.curr_bps; for (var i = 0; i < blockSize; i++) decoded[channel][i] = stream.read(bps, true); } else if ((type >= 8) && (type <= 12)) { this.decode_subframe_fixed(channel, type & ~0x8); } else if (type >= 32) { this.decode_subframe_lpc(channel, (type & ~0x20) + 1); } else { throw new Error("Invalid coding type"); } if (wasted) { for (var i = 0; i < blockSize; i++) decoded[channel][i] <<= wasted; } }; this.prototype.decode_subframe_fixed = function(channel, predictor_order) { var decoded = this.decoded[channel], stream = this.bitstream, bps = this.curr_bps; // warm up samples for (var i = 0; i < predictor_order; i++) decoded[i] = stream.read(bps, true); this.decode_residuals(channel, predictor_order); var a = 0, b = 0, c = 0, d = 0; if (predictor_order > 0) a = decoded[predictor_order - 1]; if (predictor_order > 1) b = a - decoded[predictor_order - 2]; if (predictor_order > 2) c = b - decoded[predictor_order - 2] + decoded[predictor_order - 3]; if (predictor_order > 3) d = c - decoded[predictor_order - 2] + 2 * decoded[predictor_order - 3] - decoded[predictor_order - 4]; switch (predictor_order) { case 0: break; case 1: case 2: case 3: case 4: var abcd = new Int32Array([a, b, c, d]), blockSize = this.blockSize; for (var i = predictor_order; i < blockSize; i++) { abcd[predictor_order - 1] += decoded[i]; for (var j = predictor_order - 2; j >= 0; j--) { abcd[j] += abcd[j + 1]; } decoded[i] = abcd[0]; } break; default: throw new Error("Invalid Predictor Order " + predictor_order); } }; this.prototype.decode_subframe_lpc = function(channel, predictor_order) { var stream = this.bitstream, decoded = this.decoded[channel], bps = this.curr_bps, blockSize = this.blockSize; // warm up samples for (var i = 0; i < predictor_order; i++) { decoded[i] = stream.read(bps, true); } var coeff_prec = stream.read(4) + 1; if (coeff_prec === 16) throw new Error("Invalid coefficient precision"); var qlevel = stream.read(5, true); if (qlevel < 0) throw new Error("Negative qlevel, maybe buggy stream"); var coeffs = new Int32Array(32); for (var i = 0; i < predictor_order; i++) { coeffs[i] = stream.read(coeff_prec, true); } this.decode_residuals(channel, predictor_order); if (this.bps > 16) throw new Error("no 64-bit integers in JS, could probably use doubles though"); for (var i = predictor_order; i < blockSize - 1; i += 2) { var d = decoded[i - predictor_order], s0 = 0, s1 = 0, c; for (var j = predictor_order - 1; j > 0; j--) { c = coeffs[j]; s0 += c * d; d = decoded[i - j]; s1 += c * d; } c = coeffs[0]; s0 += c * d; d = decoded[i] += (s0 >> qlevel); s1 += c * d; decoded[i + 1] += (s1 >> qlevel); } if (i < blockSize) { var sum = 0; for (var j = 0; j < predictor_order; j++) sum += coeffs[j] * decoded[i - j - 1]; decoded[i] += (sum >> qlevel); } }; const INT_MAX = 32767; this.prototype.decode_residuals = function(channel, predictor_order) { var stream = this.bitstream, method_type = stream.read(2); if (method_type > 1) throw new Error('Illegal residual coding method ' + method_type); var rice_order = stream.read(4), samples = (this.blockSize >>> rice_order); if (predictor_order > samples) throw new Error('Invalid predictor order ' + predictor_order + ' > ' + samples); var decoded = this.decoded[channel], sample = predictor_order, i = predictor_order; for (var partition = 0; partition < (1 << rice_order); partition++) { var tmp = stream.read(method_type === 0 ? 4 : 5); if (tmp === (method_type === 0 ? 15 : 31)) { tmp = stream.read(5); for (; i < samples; i++) decoded[sample++] = stream.read(tmp, true); } else { for (; i < samples; i++) decoded[sample++] = this.golomb(tmp, INT_MAX, 0); } i = 0; } }; const MIN_CACHE_BITS = 25; this.prototype.golomb = function(k, limit, esc_len) { var data = this.bitstream, offset = data.bitPosition, buf = data.peek(32 - offset) << offset, v = 0; var log = 31 - clz(buf | 1); // log2(buf) if (log - k >= 32 - MIN_CACHE_BITS && 32 - log < limit) { buf >>>= log - k; buf += (30 - log) << k; data.advance(32 + k - log); v = buf; } else { for (var i = 0; data.read(1) === 0; i++) buf = data.peek(32 - offset) << offset; if (i < limit - 1) { if (k) buf = data.read(k); else buf = 0; v = buf + (i << k); } else if (i === limit - 1) { buf = data.read(esc_len); v = buf + 1; } else { v = -1; } } return (v >> 1) ^ -(v & 1); }; // Should be in the damned standard library... function clz(input) { var output = 0, curbyte = 0; while(true) { // emulate goto in JS using the break statement :D curbyte = input >>> 24; if (curbyte) break; output += 8; curbyte = input >>> 16; if (curbyte & 0xff) break; output += 8; curbyte = input >>> 8; if (curbyte & 0xff) break; output += 8; curbyte = input; if (curbyte & 0xff) break; output += 8; return output; } if (!(curbyte & 0xf0)) output += 4; else curbyte >>>= 4; if (curbyte & 0x8) return output; if (curbyte & 0x4) return output + 1; if (curbyte & 0x2) return output + 2; if (curbyte & 0x1) return output + 3; // shouldn't get here return output + 4; } }); module.exports = FLACDecoder; },{}],3:[function(require,module,exports){ /* * FLAC.js - Free Lossless Audio Codec decoder in JavaScript * By Devon Govett and Jens Nockert of Official.fm Labs * * FLAC.js is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FLAC.js is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ var AV = (window.AV); var FLACDemuxer = AV.Demuxer.extend(function() { AV.Demuxer.register(this); this.probe = function(buffer) { return buffer.peekString(0, 4) === 'fLaC'; } const STREAMINFO = 0, PADDING = 1, APPLICATION = 2, SEEKTABLE = 3, VORBIS_COMMENT = 4, CUESHEET = 5, PICTURE = 6, INVALID = 127, STREAMINFO_SIZE = 34; this.prototype.readChunk = function() { var stream = this.stream; if (!this.readHeader && stream.available(4)) { if (stream.readString(4) !== 'fLaC') return this.emit('error', 'Invalid FLAC file.'); this.readHeader = true; } while (stream.available(1) && !this.last) { if (!this.readBlockHeaders) { var tmp = stream.readUInt8(); this.last = (tmp & 0x80) === 0x80, this.type = tmp & 0x7F, this.size = stream.readUInt24(); } if (!this.foundStreamInfo && this.type !== STREAMINFO) return this.emit('error', 'STREAMINFO must be the first block'); if (!stream.available(this.size)) return; switch (this.type) { case STREAMINFO: if (this.foundStreamInfo) return this.emit('error', 'STREAMINFO can only occur once.'); if (this.size !== STREAMINFO_SIZE) return this.emit('error', 'STREAMINFO size is wrong.'); this.foundStreamInfo = true; var bitstream = new AV.Bitstream(stream); var cookie = { minBlockSize: bitstream.read(16), maxBlockSize: bitstream.read(16), minFrameSize: bitstream.read(24), maxFrameSize: bitstream.read(24) }; this.format = { formatID: 'flac', sampleRate: bitstream.read(20), channelsPerFrame: bitstream.read(3) + 1, bitsPerChannel: bitstream.read(5) + 1 }; this.emit('format', this.format); this.emit('cookie', cookie); var sampleCount = bitstream.read(36); this.emit('duration', sampleCount / this.format.sampleRate * 1000 | 0); stream.advance(16); // skip MD5 hashes this.readBlockHeaders = false; break; /* I am only looking at the least significant 32 bits of sample number and offset data This is more than sufficient for the longest flac file I have (~50 mins 2-channel 16-bit 44.1k which uses about 7.5% of the UInt32 space for the largest offset) Can certainly be improved by storing sample numbers and offests as doubles, but would require additional overriding of the searchTimestamp and seek functions (possibly more?) Also the flac faq suggests it would be possible to find frame lengths and thus create seek points on the fly via decoding but I assume this would be slow I may look into these thigns though as my project progresses */ case SEEKTABLE: for(var s=0; s<this.size/18; s++) { if(stream.peekUInt32(0) == 0xFFFFFFFF && stream.peekUInt32(1) == 0xFFFFFFFF) { //placeholder, ignore stream.advance(18); } else { if(stream.readUInt32() > 0) { this.emit('error', 'Seek points with sample number >UInt32 not supported'); } var samplenum = stream.readUInt32(); if(stream.readUInt32() > 0) { this.emit('error', 'Seek points with stream offset >UInt32 not supported'); } var offset = stream.readUInt32(); stream.advance(2); this.addSeekPoint(offset, samplenum); } } break; case VORBIS_COMMENT: // see http://www.xiph.org/vorbis/doc/v-comment.html this.metadata || (this.metadata = {}); var len = stream.readUInt32(true); this.metadata.vendor = stream.readString(len); var length = stream.readUInt32(true); for (var i = 0; i < length; i++) { len = stream.readUInt32(true); var str = stream.readString(len, 'utf8'), idx = str.indexOf('='); this.metadata[str.slice(0, idx).toLowerCase()] = str.slice(idx + 1); } // TODO: standardize field names across formats break; case PICTURE: var type = stream.readUInt32(); if (type !== 3) { // make sure this is album art (type 3) stream.advance(this.size - 4); } else { var mimeLen = stream.readUInt32(), mime = stream.readString(mimeLen), descLen = stream.readUInt32(), description = stream.readString(descLen), width = stream.readUInt32(), height = stream.readUInt32(), depth = stream.readUInt32(), colors = stream.readUInt32(), length = stream.readUInt32(), picture = stream.readBuffer(length); this.metadata || (this.metadata = {}); this.metadata.coverArt = picture; } // does anyone want the rest of the info? break; default: stream.advance(this.size); this.readBlockHeaders = false; } if (this.last && this.metadata) this.emit('metadata', this.metadata); } while (stream.available(1) && this.last) { var buffer = stream.readSingleBuffer(stream.remainingBytes()); this.emit('data', buffer); } } }); module.exports = FLACDemuxer; },{}],4:[function(require,module,exports){ // if ogg.js exists, register a plugin try { var OggDemuxer = (window.AV.OggDemuxer); } catch (e) {}; if (!OggDemuxer) return; OggDemuxer.plugins.push({ magic: "\177FLAC", init: function() { this.list = new AV.BufferList(); this.stream = new AV.Stream(this.list); }, readHeaders: function(packet) { var stream = this.stream; this.list.append(new AV.Buffer(packet)); stream.advance(5); // magic if (stream.readUInt8() != 1) throw new Error('Unsupported FLAC version'); stream.advance(3); if (stream.peekString(0, 4) != 'fLaC') throw new Error('Not flac'); this.flac = AV.Demuxer.find(stream.peekSingleBuffer(0, stream.remainingBytes())); if (!this.flac) throw new Error('Flac demuxer not found'); this.flac.prototype.readChunk.call(this); return true; }, readPacket: function(packet) { this.list.append(new AV.Buffer(packet)); this.flac.prototype.readChunk.call(this); } }); },{}]},{},[1]) //# sourceMappingURL=flac.js.map
systems-rebooter/music
js/vendor/aurora/flac.js
JavaScript
agpl-3.0
25,523
/* * /MathJax/localization/br/br.js * * Copyright (c) 2009-2015 The MathJax Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ MathJax.Localization.addTranslation( "br", null, { menuTitle: "brezhoneg", version: "2.5.0", isLoaded: true, domains: { _: { version: "2.5.0", isLoaded: true, strings: { MathProcessingError: "Fazi o treta\u00F1 ar formulenn", MathError: "Fazi er formulenn", LoadFile: "O karga\u00F1 %1", Loading: "O karga\u00F1", LoadFailed: "N'eus ket bet gallet karga\u00F1 %1", ProcessMath: "Treta\u00F1 ar formulenno\u00F9 : %1%%", Processing: "O treta\u00F1", TypesetMath: "Aoza\u00F1 formulenno\u00F9 : %1%%", Typesetting: "Aoza\u00F1", MathJaxNotSupported: "Ne c'hall ket ho merdeer ober gant MathJax" } }, FontWarnings: {}, "HTML-CSS": {}, HelpDialog: {}, MathML: {}, MathMenu: {}, TeX: {} }, plural: function( a ) { if (a % 10 === 1 && !(a % 100 === 11 || a % 100 === 71 || a % 100 === 91)) { return 1 } if (a % 10 === 2 && !(a % 100 === 12 || a % 100 === 72 || a % 100 === 92)) { return 2 } if ((a % 10 === 3 || a % 10 === 4 || a % 10 === 9) && !(10 <= a % 100 && a % 100 <= 19 || 70 <= a % 100 && a % 100 <= 79 || 90 <= a % 100 && a % 100 <= 99)) { return 3 } if (a !== 0 && a % 1000000 === 0) { return 4 } return 5 }, number: function( a ) { return a } } ); MathJax.Ajax.loadComplete( "[MathJax]/localization/br/br.js" );
hannesk001/SPHERE-Framework
Library/MathJax/2.5.0/localization/br/br.js
JavaScript
agpl-3.0
2,278
/* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is the Places Command Controller. * * The Initial Developer of the Original Code is Google Inc. * * Portions created by the Initial Developer are Copyright (C) 2005 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Sungjoon Steve Won <[email protected]> (Original Author) * Asaf Romano <[email protected]> * Marco Bonarco <[email protected]> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ let Ci = Components.interfaces; let Cc = Components.classes; let Cr = Components.results; const LOAD_IN_SIDEBAR_ANNO = "bookmarkProperties/loadInSidebar"; const DESCRIPTION_ANNO = "bookmarkProperties/description"; const GUID_ANNO = "placesInternal/GUID"; const CLASS_ID = Components.ID("c0844a84-5a12-4808-80a8-809cb002bb4f"); const CONTRACT_ID = "@mozilla.org/browser/placesTransactionsService;1"; Components.utils.import("resource://gre/modules/XPCOMUtils.jsm"); __defineGetter__("PlacesUtils", function() { delete this.PlacesUtils var tmpScope = {}; Components.utils.import("resource://gre/modules/utils.js", tmpScope); return this.PlacesUtils = tmpScope.PlacesUtils; }); // The minimum amount of transactions we should tell our observers to begin // batching (rather than letting them do incremental drawing). const MIN_TRANSACTIONS_FOR_BATCH = 5; function placesTransactionsService() { this.mTransactionManager = Cc["@mozilla.org/transactionmanager;1"]. createInstance(Ci.nsITransactionManager); } placesTransactionsService.prototype = { classDescription: "Places Transaction Manager", classID: CLASS_ID, contractID: CONTRACT_ID, QueryInterface: XPCOMUtils.generateQI([Ci.nsIPlacesTransactionsService, Ci.nsITransactionManager]), aggregateTransactions: function placesTxn_aggregateTransactions(aName, aTransactions) { return new placesAggregateTransactions(aName, aTransactions); }, createFolder: function placesTxn_createFolder(aName, aContainer, aIndex, aAnnotations, aChildItemsTransactions) { return new placesCreateFolderTransactions(aName, aContainer, aIndex, aAnnotations, aChildItemsTransactions); }, createItem: function placesTxn_createItem(aURI, aContainer, aIndex, aTitle, aKeyword, aAnnotations, aChildTransactions) { return new placesCreateItemTransactions(aURI, aContainer, aIndex, aTitle, aKeyword, aAnnotations, aChildTransactions); }, createSeparator: function placesTxn_createSeparator(aContainer, aIndex) { return new placesCreateSeparatorTransactions(aContainer, aIndex); }, createLivemark: function placesTxn_createLivemark(aFeedURI, aSiteURI, aName, aContainer, aIndex, aAnnotations) { return new placesCreateLivemarkTransactions(aFeedURI, aSiteURI, aName, aContainer, aIndex, aAnnotations); }, moveItem: function placesTxn_moveItem(aItemId, aNewContainer, aNewIndex) { return new placesMoveItemTransactions(aItemId, aNewContainer, aNewIndex); }, removeItem: function placesTxn_removeItem(aItemId) { if (aItemId == PlacesUtils.tagsFolderId || aItemId == PlacesUtils.placesRootId || aItemId == PlacesUtils.bookmarksMenuFolderId || aItemId == PlacesUtils.toolbarFolderId) throw Cr.NS_ERROR_INVALID_ARG; // if the item lives within a tag container, use the tagging transactions var parent = PlacesUtils.bookmarks.getFolderIdForItem(aItemId); var grandparent = PlacesUtils.bookmarks.getFolderIdForItem(parent); if (grandparent == PlacesUtils.tagsFolderId) { var uri = PlacesUtils.bookmarks.getBookmarkURI(aItemId); return this.untagURI(uri, [parent]); } // if the item is a livemark container we will not save its children and // will use createLivemark to undo. if (PlacesUtils.itemIsLivemark(aItemId)) return new placesRemoveLivemarkTransaction(aItemId); return new placesRemoveItemTransaction(aItemId); }, editItemTitle: function placesTxn_editItemTitle(aItemId, aNewTitle) { return new placesEditItemTitleTransactions(aItemId, aNewTitle); }, editBookmarkURI: function placesTxn_editBookmarkURI(aItemId, aNewURI) { return new placesEditBookmarkURITransactions(aItemId, aNewURI); }, setItemAnnotation: function placesTxn_setItemAnnotation(aItemId, aAnnotationObject) { return new placesSetItemAnnotationTransactions(aItemId, aAnnotationObject); }, setPageAnnotation: function placesTxn_setPageAnnotation(aURI, aAnnotationObject) { return new placesSetPageAnnotationTransactions(aURI, aAnnotationObject); }, setLoadInSidebar: function placesTxn_setLoadInSidebar(aItemId, aLoadInSidebar) { var annoObj = { name: LOAD_IN_SIDEBAR_ANNO, type: Ci.nsIAnnotationService.TYPE_INT32, flags: 0, value: aLoadInSidebar, expires: Ci.nsIAnnotationService.EXPIRE_NEVER }; return this.setItemAnnotation(aItemId, annoObj); }, editItemDescription: function placesTxn_editItemDescription(aItemId, aDescription) { var annoObj = { name: DESCRIPTION_ANNO, type: Ci.nsIAnnotationService.TYPE_STRING, flags: 0, value: aDescription, expires: Ci.nsIAnnotationService.EXPIRE_NEVER }; return this.setItemAnnotation(aItemId, annoObj); }, editBookmarkKeyword: function placesTxn_editBookmarkKeyword(aItemId, aNewKeyword) { return new placesEditBookmarkKeywordTransactions(aItemId, aNewKeyword); }, editBookmarkPostData: function placesTxn_editBookmarkPostdata(aItemId, aPostData) { return new placesEditBookmarkPostDataTransactions(aItemId, aPostData); }, editLivemarkSiteURI: function placesTxn_editLivemarkSiteURI(aLivemarkId, aSiteURI) { return new placesEditLivemarkSiteURITransactions(aLivemarkId, aSiteURI); }, editLivemarkFeedURI: function placesTxn_editLivemarkFeedURI(aLivemarkId, aFeedURI) { return new placesEditLivemarkFeedURITransactions(aLivemarkId, aFeedURI); }, editBookmarkMicrosummary: function placesTxn_editBookmarkMicrosummary(aItemId, aNewMicrosummary) { return new placesEditBookmarkMicrosummaryTransactions(aItemId, aNewMicrosummary); }, editItemDateAdded: function placesTxn_editItemDateAdded(aItemId, aNewDateAdded) { return new placesEditItemDateAddedTransaction(aItemId, aNewDateAdded); }, editItemLastModified: function placesTxn_editItemLastModified(aItemId, aNewLastModified) { return new placesEditItemLastModifiedTransaction(aItemId, aNewLastModified); }, sortFolderByName: function placesTxn_sortFolderByName(aFolderId) { return new placesSortFolderByNameTransactions(aFolderId); }, tagURI: function placesTxn_tagURI(aURI, aTags) { return new placesTagURITransaction(aURI, aTags); }, untagURI: function placesTxn_untagURI(aURI, aTags) { return new placesUntagURITransaction(aURI, aTags); }, // Update commands in the undo group of the active window // commands in inactive windows will are updated on-focus _updateCommands: function placesTxn__updateCommands() { var wm = Cc["@mozilla.org/appshell/window-mediator;1"]. getService(Ci.nsIWindowMediator); var win = wm.getMostRecentWindow(null); if (win) win.updateCommands("undo"); }, // nsITransactionManager beginBatch: function() { this.mTransactionManager.beginBatch(); // A no-op transaction is pushed to the stack, in order to make safe and // easy to implement "Undo" an unknown number of transactions (including 0), // "above" beginBatch and endBatch. Otherwise,implementing Undo that way // head to dataloss: for example, if no changes were done in the // edit-item panel, the last transaction on the undo stack would be the // initial createItem transaction, or even worse, the batched editing of // some other item. // DO NOT MOVE this to the window scope, that would leak (bug 490068)! this.doTransaction({ doTransaction: function() { }, undoTransaction: function() { }, redoTransaction: function() { }, isTransient: false, merge: function() { return false; } }); }, endBatch: function() this.mTransactionManager.endBatch(), doTransaction: function placesTxn_doTransaction(txn) { this.mTransactionManager.doTransaction(txn); this._updateCommands(); }, undoTransaction: function placesTxn_undoTransaction() { this.mTransactionManager.undoTransaction(); this._updateCommands(); }, redoTransaction: function placesTxn_redoTransaction() { this.mTransactionManager.redoTransaction(); this._updateCommands(); }, clear: function() this.mTransactionManager.clear(), get numberOfUndoItems() { return this.mTransactionManager.numberOfUndoItems; }, get numberOfRedoItems() { return this.mTransactionManager.numberOfRedoItems; }, get maxTransactionCount() { return this.mTransactionManager.maxTransactionCount; }, set maxTransactionCount(val) { return this.mTransactionManager.maxTransactionCount = val; }, peekUndoStack: function() this.mTransactionManager.peekUndoStack(), peekRedoStack: function() this.mTransactionManager.peekRedoStack(), getUndoStack: function() this.mTransactionManager.getUndoStack(), getRedoStack: function() this.mTransactionManager.getRedoStack(), AddListener: function(l) this.mTransactionManager.AddListener(l), RemoveListener: function(l) this.mTransactionManager.RemoveListener(l) }; /** * Method and utility stubs for Places Edit Transactions */ function placesBaseTransaction() { } placesBaseTransaction.prototype = { // for child-transactions get wrappedJSObject() { return this; }, // nsITransaction redoTransaction: function PBT_redoTransaction() { throw Cr.NS_ERROR_NOT_IMPLEMENTED; }, get isTransient() { return false; }, merge: function mergeFunc(transaction) { return false; }, // nsISupports QueryInterface: XPCOMUtils.generateQI([Ci.nsITransaction]), }; function placesAggregateTransactions(name, transactions) { this._transactions = transactions; this._name = name; this.container = -1; this.redoTransaction = this.doTransaction; // Check child transactions number. We will batch if we have more than // MIN_TRANSACTIONS_FOR_BATCH total number of transactions. var countTransactions = function(aTransactions, aTxnCount) { for (let i = 0; i < aTransactions.length && aTxnCount < MIN_TRANSACTIONS_FOR_BATCH; i++, aTxnCount++) { let txn = aTransactions[i].wrappedJSObject; if (txn && txn.childTransactions && txn.childTransactions.length) aTxnCount = countTransactions(txn.childTransactions, aTxnCount); } return aTxnCount; } var txnCount = countTransactions(transactions, 0); this._useBatch = txnCount >= MIN_TRANSACTIONS_FOR_BATCH; } placesAggregateTransactions.prototype = { __proto__: placesBaseTransaction.prototype, doTransaction: function PAT_doTransaction() { if (this._useBatch) { var callback = { _self: this, runBatched: function() { this._self.commit(false); } }; PlacesUtils.bookmarks.runInBatchMode(callback, null); } else this.commit(false); }, undoTransaction: function PAT_undoTransaction() { if (this._useBatch) { var callback = { _self: this, runBatched: function() { this._self.commit(true); } }; PlacesUtils.bookmarks.runInBatchMode(callback, null); } else this.commit(true); }, commit: function PAT_commit(aUndo) { // Use a copy of the transactions array, so we won't reverse the original // one on undoing. var transactions = this._transactions.slice(0); if (aUndo) transactions.reverse(); for (var i = 0; i < transactions.length; i++) { var txn = transactions[i]; if (this.container > -1) txn.wrappedJSObject.container = this.container; if (aUndo) txn.undoTransaction(); else txn.doTransaction(); } } }; function placesCreateFolderTransactions(aName, aContainer, aIndex, aAnnotations, aChildItemsTransactions) { this._name = aName; this._container = aContainer; this._index = typeof(aIndex) == "number" ? aIndex : -1; this._annotations = aAnnotations; this._id = null; this.childTransactions = aChildItemsTransactions || []; this.redoTransaction = this.doTransaction; } placesCreateFolderTransactions.prototype = { __proto__: placesBaseTransaction.prototype, // childItemsTransaction support get container() { return this._container; }, set container(val) { return this._container = val; }, doTransaction: function PCFT_doTransaction() { this._id = PlacesUtils.bookmarks.createFolder(this._container, this._name, this._index); if (this._annotations && this._annotations.length > 0) PlacesUtils.setAnnotationsForItem(this._id, this._annotations); if (this.childTransactions.length) { // Set the new container id into child transactions. for (var i = 0; i < this.childTransactions.length; ++i) { this.childTransactions[i].wrappedJSObject.container = this._id; } let aggregateTxn = new placesAggregateTransactions("Create folder childTxn", this.childTransactions); aggregateTxn.doTransaction(); } if (this._GUID) PlacesUtils.bookmarks.setItemGUID(this._id, this._GUID); }, undoTransaction: function PCFT_undoTransaction() { if (this.childTransactions.length) { let aggregateTxn = new placesAggregateTransactions("Create folder childTxn", this.childTransactions); aggregateTxn.undoTransaction(); } // If a GUID exists for this item, preserve it before removing the item. if (PlacesUtils.annotations.itemHasAnnotation(this._id, GUID_ANNO)) this._GUID = PlacesUtils.bookmarks.getItemGUID(this._id); // Remove item only after all child transactions have been reverted. PlacesUtils.bookmarks.removeItem(this._id); } }; function placesCreateItemTransactions(aURI, aContainer, aIndex, aTitle, aKeyword, aAnnotations, aChildTransactions) { this._uri = aURI; this._container = aContainer; this._index = typeof(aIndex) == "number" ? aIndex : -1; this._title = aTitle; this._keyword = aKeyword; this._annotations = aAnnotations; this.childTransactions = aChildTransactions || []; this.redoTransaction = this.doTransaction; } placesCreateItemTransactions.prototype = { __proto__: placesBaseTransaction.prototype, // childItemsTransactions support for the create-folder transaction get container() { return this._container; }, set container(val) { return this._container = val; }, doTransaction: function PCIT_doTransaction() { this._id = PlacesUtils.bookmarks.insertBookmark(this.container, this._uri, this._index, this._title); if (this._keyword) PlacesUtils.bookmarks.setKeywordForBookmark(this._id, this._keyword); if (this._annotations && this._annotations.length > 0) PlacesUtils.setAnnotationsForItem(this._id, this._annotations); if (this.childTransactions.length) { // Set the new item id into child transactions. for (var i = 0; i < this.childTransactions.length; ++i) { this.childTransactions[i].wrappedJSObject.id = this._id; } let aggregateTxn = new placesAggregateTransactions("Create item childTxn", this.childTransactions); aggregateTxn.doTransaction(); } if (this._GUID) PlacesUtils.bookmarks.setItemGUID(this._id, this._GUID); }, undoTransaction: function PCIT_undoTransaction() { if (this.childTransactions.length) { // Undo transactions should always be done in reverse order. let aggregateTxn = new placesAggregateTransactions("Create item childTxn", this.childTransactions); aggregateTxn.undoTransaction(); } // If a GUID exists for this item, preserve it before removing the item. if (PlacesUtils.annotations.itemHasAnnotation(this._id, GUID_ANNO)) this._GUID = PlacesUtils.bookmarks.getItemGUID(this._id); // Remove item only after all child transactions have been reverted. PlacesUtils.bookmarks.removeItem(this._id); } }; function placesCreateSeparatorTransactions(aContainer, aIndex) { this._container = aContainer; this._index = typeof(aIndex) == "number" ? aIndex : -1; this._id = null; this.redoTransaction = this.doTransaction; } placesCreateSeparatorTransactions.prototype = { __proto__: placesBaseTransaction.prototype, // childItemsTransaction support get container() { return this._container; }, set container(val) { return this._container = val; }, doTransaction: function PCST_doTransaction() { this._id = PlacesUtils.bookmarks .insertSeparator(this.container, this._index); if (this._GUID) PlacesUtils.bookmarks.setItemGUID(this._id, this._GUID); }, undoTransaction: function PCST_undoTransaction() { // If a GUID exists for this item, preserve it before removing the item. if (PlacesUtils.annotations.itemHasAnnotation(this._id, GUID_ANNO)) this._GUID = PlacesUtils.bookmarks.getItemGUID(this._id); PlacesUtils.bookmarks.removeItem(this._id); } }; function placesCreateLivemarkTransactions(aFeedURI, aSiteURI, aName, aContainer, aIndex, aAnnotations) { this.redoTransaction = this.doTransaction; this._feedURI = aFeedURI; this._siteURI = aSiteURI; this._name = aName; this._container = aContainer; this._index = typeof(aIndex) == "number" ? aIndex : -1; this._annotations = aAnnotations; } placesCreateLivemarkTransactions.prototype = { __proto__: placesBaseTransaction.prototype, // childItemsTransaction support get container() { return this._container; }, set container(val) { return this._container = val; }, doTransaction: function PCLT_doTransaction() { this._id = PlacesUtils.livemarks.createLivemark(this._container, this._name, this._siteURI, this._feedURI, this._index); if (this._annotations && this._annotations.length > 0) PlacesUtils.setAnnotationsForItem(this._id, this._annotations); if (this._GUID) PlacesUtils.bookmarks.setItemGUID(this._id, this._GUID); }, undoTransaction: function PCLT_undoTransaction() { // If a GUID exists for this item, preserve it before removing the item. if (PlacesUtils.annotations.itemHasAnnotation(this._id, GUID_ANNO)) this._GUID = PlacesUtils.bookmarks.getItemGUID(this._id); PlacesUtils.bookmarks.removeItem(this._id); } }; function placesRemoveLivemarkTransaction(aFolderId) { this.redoTransaction = this.doTransaction; this._id = aFolderId; this._title = PlacesUtils.bookmarks.getItemTitle(this._id); this._container = PlacesUtils.bookmarks.getFolderIdForItem(this._id); var annos = PlacesUtils.getAnnotationsForItem(this._id); // Exclude livemark service annotations, those will be recreated automatically var annosToExclude = ["livemark/feedURI", "livemark/siteURI", "livemark/expiration", "livemark/loadfailed", "livemark/loading"]; this._annotations = annos.filter(function(aValue, aIndex, aArray) { return annosToExclude.indexOf(aValue.name) == -1; }); this._feedURI = PlacesUtils.livemarks.getFeedURI(this._id); this._siteURI = PlacesUtils.livemarks.getSiteURI(this._id); this._dateAdded = PlacesUtils.bookmarks.getItemDateAdded(this._id); this._lastModified = PlacesUtils.bookmarks.getItemLastModified(this._id); } placesRemoveLivemarkTransaction.prototype = { __proto__: placesBaseTransaction.prototype, doTransaction: function PRLT_doTransaction() { this._index = PlacesUtils.bookmarks.getItemIndex(this._id); PlacesUtils.bookmarks.removeItem(this._id); }, undoTransaction: function PRLT_undoTransaction() { this._id = PlacesUtils.livemarks.createLivemark(this._container, this._title, this._siteURI, this._feedURI, this._index); PlacesUtils.bookmarks.setItemDateAdded(this._id, this._dateAdded); PlacesUtils.bookmarks.setItemLastModified(this._id, this._lastModified); // Restore annotations PlacesUtils.setAnnotationsForItem(this._id, this._annotations); } }; function placesMoveItemTransactions(aItemId, aNewContainer, aNewIndex) { this._id = aItemId; this._oldContainer = PlacesUtils.bookmarks.getFolderIdForItem(this._id); this._newContainer = aNewContainer; this._newIndex = aNewIndex; this.redoTransaction = this.doTransaction; } placesMoveItemTransactions.prototype = { __proto__: placesBaseTransaction.prototype, doTransaction: function PMIT_doTransaction() { this._oldIndex = PlacesUtils.bookmarks.getItemIndex(this._id); PlacesUtils.bookmarks.moveItem(this._id, this._newContainer, this._newIndex); this._undoIndex = PlacesUtils.bookmarks.getItemIndex(this._id); }, undoTransaction: function PMIT_undoTransaction() { // moving down in the same container takes in count removal of the item // so to revert positions we must move to oldIndex + 1 if (this._newContainer == this._oldContainer && this._oldIndex > this._undoIndex) PlacesUtils.bookmarks.moveItem(this._id, this._oldContainer, this._oldIndex + 1); else PlacesUtils.bookmarks.moveItem(this._id, this._oldContainer, this._oldIndex); } }; function placesRemoveItemTransaction(aItemId) { this.redoTransaction = this.doTransaction; this._id = aItemId; this._itemType = PlacesUtils.bookmarks.getItemType(this._id); if (this._itemType == Ci.nsINavBookmarksService.TYPE_FOLDER) { this.childTransactions = this._getFolderContentsTransactions(); // Remove this folder itself. let txn = PlacesUtils.bookmarks.getRemoveFolderTransaction(this._id); this.childTransactions.push(txn); } else if (this._itemType == Ci.nsINavBookmarksService.TYPE_BOOKMARK) { this._uri = PlacesUtils.bookmarks.getBookmarkURI(this._id); this._keyword = PlacesUtils.bookmarks.getKeywordForBookmark(this._id); } if (this._itemType != Ci.nsINavBookmarksService.TYPE_SEPARATOR) this._title = PlacesUtils.bookmarks.getItemTitle(this._id); this._oldContainer = PlacesUtils.bookmarks.getFolderIdForItem(this._id); this._annotations = PlacesUtils.getAnnotationsForItem(this._id); this._dateAdded = PlacesUtils.bookmarks.getItemDateAdded(this._id); this._lastModified = PlacesUtils.bookmarks.getItemLastModified(this._id); } placesRemoveItemTransaction.prototype = { __proto__: placesBaseTransaction.prototype, doTransaction: function PRIT_doTransaction() { this._oldIndex = PlacesUtils.bookmarks.getItemIndex(this._id); if (this._itemType == Ci.nsINavBookmarksService.TYPE_FOLDER) { let aggregateTxn = new placesAggregateTransactions("Remove item childTxn", this.childTransactions); aggregateTxn.doTransaction(); } else { PlacesUtils.bookmarks.removeItem(this._id); if (this._uri) { // if this was the last bookmark (excluding tag-items and livemark // children, see getMostRecentBookmarkForURI) for the bookmark's url, // remove the url from tag containers as well. if (PlacesUtils.getMostRecentBookmarkForURI(this._uri) == -1) { this._tags = PlacesUtils.tagging.getTagsForURI(this._uri, {}); PlacesUtils.tagging.untagURI(this._uri, this._tags); } } } }, undoTransaction: function PRIT_undoTransaction() { if (this._itemType == Ci.nsINavBookmarksService.TYPE_BOOKMARK) { this._id = PlacesUtils.bookmarks.insertBookmark(this._oldContainer, this._uri, this._oldIndex, this._title); if (this._tags && this._tags.length > 0) PlacesUtils.tagging.tagURI(this._uri, this._tags); if (this._keyword) PlacesUtils.bookmarks.setKeywordForBookmark(this._id, this._keyword); } else if (this._itemType == Ci.nsINavBookmarksService.TYPE_FOLDER) { let aggregateTxn = new placesAggregateTransactions("Remove item childTxn", this.childTransactions); aggregateTxn.undoTransaction(); } else // TYPE_SEPARATOR this._id = PlacesUtils.bookmarks.insertSeparator(this._oldContainer, this._oldIndex); if (this._annotations.length > 0) PlacesUtils.setAnnotationsForItem(this._id, this._annotations); PlacesUtils.bookmarks.setItemDateAdded(this._id, this._dateAdded); PlacesUtils.bookmarks.setItemLastModified(this._id, this._lastModified); }, /** * Returns a flat, ordered list of transactions for a depth-first recreation * of items within this folder. */ _getFolderContentsTransactions: function PRIT__getFolderContentsTransactions() { var transactions = []; var contents = PlacesUtils.getFolderContents(this._id, false, false).root; for (var i = 0; i < contents.childCount; ++i) { let txn = new placesRemoveItemTransaction(contents.getChild(i).itemId); transactions.push(txn); } contents.containerOpen = false; // Reverse transactions to preserve parent-child relationship. return transactions.reverse(); } }; function placesEditItemTitleTransactions(id, newTitle) { this._id = id; this._newTitle = newTitle; this._oldTitle = ""; this.redoTransaction = this.doTransaction; } placesEditItemTitleTransactions.prototype = { __proto__: placesBaseTransaction.prototype, doTransaction: function PEITT_doTransaction() { this._oldTitle = PlacesUtils.bookmarks.getItemTitle(this._id); PlacesUtils.bookmarks.setItemTitle(this._id, this._newTitle); }, undoTransaction: function PEITT_undoTransaction() { PlacesUtils.bookmarks.setItemTitle(this._id, this._oldTitle); } }; function placesEditBookmarkURITransactions(aBookmarkId, aNewURI) { this._id = aBookmarkId; this._newURI = aNewURI; this.redoTransaction = this.doTransaction; } placesEditBookmarkURITransactions.prototype = { __proto__: placesBaseTransaction.prototype, doTransaction: function PEBUT_doTransaction() { this._oldURI = PlacesUtils.bookmarks.getBookmarkURI(this._id); PlacesUtils.bookmarks.changeBookmarkURI(this._id, this._newURI); // move tags from old URI to new URI this._tags = PlacesUtils.tagging.getTagsForURI(this._oldURI, {}); if (this._tags.length != 0) { // only untag the old URI if this is the only bookmark if (PlacesUtils.getBookmarksForURI(this._oldURI, {}).length == 0) PlacesUtils.tagging.untagURI(this._oldURI, this._tags); PlacesUtils.tagging.tagURI(this._newURI, this._tags); } }, undoTransaction: function PEBUT_undoTransaction() { PlacesUtils.bookmarks.changeBookmarkURI(this._id, this._oldURI); // move tags from new URI to old URI if (this._tags.length != 0) { // only untag the new URI if this is the only bookmark if (PlacesUtils.getBookmarksForURI(this._newURI, {}).length == 0) PlacesUtils.tagging.untagURI(this._newURI, this._tags); PlacesUtils.tagging.tagURI(this._oldURI, this._tags); } } }; function placesSetItemAnnotationTransactions(aItemId, aAnnotationObject) { this.id = aItemId; this._anno = aAnnotationObject; // create an empty old anno this._oldAnno = { name: this._anno.name, type: Ci.nsIAnnotationService.TYPE_STRING, flags: 0, value: null, expires: Ci.nsIAnnotationService.EXPIRE_NEVER }; this.redoTransaction = this.doTransaction; } placesSetItemAnnotationTransactions.prototype = { __proto__: placesBaseTransaction.prototype, doTransaction: function PSIAT_doTransaction() { // Since this can be used as a child transaction this.id will be known // only at this point, after the external caller has set it. if (PlacesUtils.annotations.itemHasAnnotation(this.id, this._anno.name)) { // Save the old annotation if it is set. var flags = {}, expires = {}, mimeType = {}, type = {}; PlacesUtils.annotations.getItemAnnotationInfo(this.id, this._anno.name, flags, expires, mimeType, type); this._oldAnno.flags = flags.value; this._oldAnno.expires = expires.value; this._oldAnno.mimeType = mimeType.value; this._oldAnno.type = type.value; this._oldAnno.value = PlacesUtils.annotations .getItemAnnotation(this.id, this._anno.name); } PlacesUtils.setAnnotationsForItem(this.id, [this._anno]); }, undoTransaction: function PSIAT_undoTransaction() { PlacesUtils.setAnnotationsForItem(this.id, [this._oldAnno]); } }; function placesSetPageAnnotationTransactions(aURI, aAnnotationObject) { this._uri = aURI; this._anno = aAnnotationObject; // create an empty old anno this._oldAnno = { name: this._anno.name, type: Ci.nsIAnnotationService.TYPE_STRING, flags: 0, value: null, expires: Ci.nsIAnnotationService.EXPIRE_NEVER }; if (PlacesUtils.annotations.pageHasAnnotation(this._uri, this._anno.name)) { // fill the old anno if it is set var flags = {}, expires = {}, mimeType = {}, type = {}; PlacesUtils.annotations.getPageAnnotationInfo(this._uri, this._anno.name, flags, expires, mimeType, type); this._oldAnno.flags = flags.value; this._oldAnno.expires = expires.value; this._oldAnno.mimeType = mimeType.value; this._oldAnno.type = type.value; this._oldAnno.value = PlacesUtils.annotations .getPageAnnotation(this._uri, this._anno.name); } this.redoTransaction = this.doTransaction; } placesSetPageAnnotationTransactions.prototype = { __proto__: placesBaseTransaction.prototype, doTransaction: function PSPAT_doTransaction() { PlacesUtils.setAnnotationsForURI(this._uri, [this._anno]); }, undoTransaction: function PSPAT_undoTransaction() { PlacesUtils.setAnnotationsForURI(this._uri, [this._oldAnno]); } }; function placesEditBookmarkKeywordTransactions(id, newKeyword) { this.id = id; this._newKeyword = newKeyword; this._oldKeyword = ""; this.redoTransaction = this.doTransaction; } placesEditBookmarkKeywordTransactions.prototype = { __proto__: placesBaseTransaction.prototype, doTransaction: function PEBKT_doTransaction() { this._oldKeyword = PlacesUtils.bookmarks.getKeywordForBookmark(this.id); PlacesUtils.bookmarks.setKeywordForBookmark(this.id, this._newKeyword); }, undoTransaction: function PEBKT_undoTransaction() { PlacesUtils.bookmarks.setKeywordForBookmark(this.id, this._oldKeyword); } }; function placesEditBookmarkPostDataTransactions(aItemId, aPostData) { this.id = aItemId; this._newPostData = aPostData; this._oldPostData = null; this.redoTransaction = this.doTransaction; } placesEditBookmarkPostDataTransactions.prototype = { __proto__: placesBaseTransaction.prototype, doTransaction: function PEUPDT_doTransaction() { this._oldPostData = PlacesUtils.getPostDataForBookmark(this.id); PlacesUtils.setPostDataForBookmark(this.id, this._newPostData); }, undoTransaction: function PEUPDT_undoTransaction() { PlacesUtils.setPostDataForBookmark(this.id, this._oldPostData); } }; function placesEditLivemarkSiteURITransactions(folderId, uri) { this._folderId = folderId; this._newURI = uri; this._oldURI = null; this.redoTransaction = this.doTransaction; } placesEditLivemarkSiteURITransactions.prototype = { __proto__: placesBaseTransaction.prototype, doTransaction: function PELSUT_doTransaction() { this._oldURI = PlacesUtils.livemarks.getSiteURI(this._folderId); PlacesUtils.livemarks.setSiteURI(this._folderId, this._newURI); }, undoTransaction: function PELSUT_undoTransaction() { PlacesUtils.livemarks.setSiteURI(this._folderId, this._oldURI); } }; function placesEditLivemarkFeedURITransactions(folderId, uri) { this._folderId = folderId; this._newURI = uri; this._oldURI = null; this.redoTransaction = this.doTransaction; } placesEditLivemarkFeedURITransactions.prototype = { __proto__: placesBaseTransaction.prototype, doTransaction: function PELFUT_doTransaction() { this._oldURI = PlacesUtils.livemarks.getFeedURI(this._folderId); PlacesUtils.livemarks.setFeedURI(this._folderId, this._newURI); PlacesUtils.livemarks.reloadLivemarkFolder(this._folderId); }, undoTransaction: function PELFUT_undoTransaction() { PlacesUtils.livemarks.setFeedURI(this._folderId, this._oldURI); PlacesUtils.livemarks.reloadLivemarkFolder(this._folderId); } }; function placesEditBookmarkMicrosummaryTransactions(aItemId, newMicrosummary) { this.id = aItemId; this._mss = Cc["@mozilla.org/microsummary/service;1"]. getService(Ci.nsIMicrosummaryService); this._newMicrosummary = newMicrosummary; this._oldMicrosummary = null; this.redoTransaction = this.doTransaction; } placesEditBookmarkMicrosummaryTransactions.prototype = { __proto__: placesBaseTransaction.prototype, doTransaction: function PEBMT_doTransaction() { this._oldMicrosummary = this._mss.getMicrosummary(this.id); if (this._newMicrosummary) this._mss.setMicrosummary(this.id, this._newMicrosummary); else this._mss.removeMicrosummary(this.id); }, undoTransaction: function PEBMT_undoTransaction() { if (this._oldMicrosummary) this._mss.setMicrosummary(this.id, this._oldMicrosummary); else this._mss.removeMicrosummary(this.id); } }; function placesEditItemDateAddedTransaction(id, newDateAdded) { this.id = id; this._newDateAdded = newDateAdded; this._oldDateAdded = null; this.redoTransaction = this.doTransaction; } placesEditItemDateAddedTransaction.prototype = { __proto__: placesBaseTransaction.prototype, // to support folders as well get container() { return this.id; }, set container(val) { return this.id = val; }, doTransaction: function PEIDA_doTransaction() { this._oldDateAdded = PlacesUtils.bookmarks.getItemDateAdded(this.id); PlacesUtils.bookmarks.setItemDateAdded(this.id, this._newDateAdded); }, undoTransaction: function PEIDA_undoTransaction() { PlacesUtils.bookmarks.setItemDateAdded(this.id, this._oldDateAdded); } }; function placesEditItemLastModifiedTransaction(id, newLastModified) { this.id = id; this._newLastModified = newLastModified; this._oldLastModified = null; this.redoTransaction = this.doTransaction; } placesEditItemLastModifiedTransaction.prototype = { __proto__: placesBaseTransaction.prototype, // to support folders as well get container() { return this.id; }, set container(val) { return this.id = val; }, doTransaction: function PEILM_doTransaction() { this._oldLastModified = PlacesUtils.bookmarks.getItemLastModified(this.id); PlacesUtils.bookmarks.setItemLastModified(this.id, this._newLastModified); }, undoTransaction: function PEILM_undoTransaction() { PlacesUtils.bookmarks.setItemLastModified(this.id, this._oldLastModified); } }; function placesSortFolderByNameTransactions(aFolderId) { this._folderId = aFolderId; this._oldOrder = null, this.redoTransaction = this.doTransaction; } placesSortFolderByNameTransactions.prototype = { __proto__: placesBaseTransaction.prototype, doTransaction: function PSSFBN_doTransaction() { this._oldOrder = []; var contents = PlacesUtils.getFolderContents(this._folderId, false, false).root; var count = contents.childCount; // sort between separators var newOrder = []; var preSep = []; // temporary array for sorting each group of items var sortingMethod = function (a, b) { if (PlacesUtils.nodeIsContainer(a) && !PlacesUtils.nodeIsContainer(b)) return -1; if (!PlacesUtils.nodeIsContainer(a) && PlacesUtils.nodeIsContainer(b)) return 1; return a.title.localeCompare(b.title); }; for (var i = 0; i < count; ++i) { var item = contents.getChild(i); this._oldOrder[item.itemId] = i; if (PlacesUtils.nodeIsSeparator(item)) { if (preSep.length > 0) { preSep.sort(sortingMethod); newOrder = newOrder.concat(preSep); preSep.splice(0); } newOrder.push(item); } else preSep.push(item); } contents.containerOpen = false; if (preSep.length > 0) { preSep.sort(sortingMethod); newOrder = newOrder.concat(preSep); } // set the nex indexes var callback = { runBatched: function() { for (var i = 0; i < newOrder.length; ++i) { PlacesUtils.bookmarks.setItemIndex(newOrder[i].itemId, i); } } }; PlacesUtils.bookmarks.runInBatchMode(callback, null); }, undoTransaction: function PSSFBN_undoTransaction() { var callback = { _self: this, runBatched: function() { for (item in this._self._oldOrder) PlacesUtils.bookmarks.setItemIndex(item, this._self._oldOrder[item]); } }; PlacesUtils.bookmarks.runInBatchMode(callback, null); } }; function placesTagURITransaction(aURI, aTags) { this._uri = aURI; this._tags = aTags; this._unfiledItemId = -1; this.redoTransaction = this.doTransaction; } placesTagURITransaction.prototype = { __proto__: placesBaseTransaction.prototype, doTransaction: function PTU_doTransaction() { if (PlacesUtils.getMostRecentBookmarkForURI(this._uri) == -1) { // Force an unfiled bookmark first this._unfiledItemId = PlacesUtils.bookmarks .insertBookmark(PlacesUtils.unfiledBookmarksFolderId, this._uri, PlacesUtils.bookmarks.DEFAULT_INDEX, PlacesUtils.history.getPageTitle(this._uri)); if (this._GUID) PlacesUtils.bookmarks.setItemGUID(this._unfiledItemId, this._GUID); } PlacesUtils.tagging.tagURI(this._uri, this._tags); }, undoTransaction: function PTU_undoTransaction() { if (this._unfiledItemId != -1) { // If a GUID exists for this item, preserve it before removing the item. if (PlacesUtils.annotations.itemHasAnnotation(this._unfiledItemId, GUID_ANNO)) { this._GUID = PlacesUtils.bookmarks.getItemGUID(this._unfiledItemId); } PlacesUtils.bookmarks.removeItem(this._unfiledItemId); this._unfiledItemId = -1; } PlacesUtils.tagging.untagURI(this._uri, this._tags); } }; function placesUntagURITransaction(aURI, aTags) { this._uri = aURI; if (aTags) { // Within this transaction, we cannot rely on tags given by itemId // since the tag containers may be gone after we call untagURI. // Thus, we convert each tag given by its itemId to name. this._tags = aTags; for (var i=0; i < aTags.length; i++) { if (typeof(this._tags[i]) == "number") this._tags[i] = PlacesUtils.bookmarks.getItemTitle(this._tags[i]); } } else this._tags = PlacesUtils.tagging.getTagsForURI(this._uri, {}); this.redoTransaction = this.doTransaction; } placesUntagURITransaction.prototype = { __proto__: placesBaseTransaction.prototype, doTransaction: function PUTU_doTransaction() { PlacesUtils.tagging.untagURI(this._uri, this._tags); }, undoTransaction: function PUTU_undoTransaction() { PlacesUtils.tagging.tagURI(this._uri, this._tags); } }; function NSGetModule(aCompMgr, aFileSpec) { return XPCOMUtils.generateModule([placesTransactionsService]); }
csinitiative/trisano
webapp/features/support/firefox-36/components/nsPlacesTransactionsService.js
JavaScript
agpl-3.0
42,772
/* YUI 3.11.0 (build d549e5c) Copyright 2013 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ YUI.add('tree-openable', function (Y, NAME) { /*jshint expr:true, onevar:false */ /** Extension for `Tree` that adds the concept of open/closed state for nodes. @module tree @submodule tree-openable @main tree-openable **/ /** Extension for `Tree` that adds the concept of open/closed state for nodes. @class Tree.Openable @constructor @extensionfor Tree **/ /** Fired when a node is closed. @event close @param {Tree.Node} node Node being closed. @param {String} src Source of the event. @preventable _defCloseFn **/ var EVT_CLOSE = 'close'; /** Fired when a node is opened. @event open @param {Tree.Node} node Node being opened. @param {String} src Source of the event. @preventable _defOpenFn **/ var EVT_OPEN = 'open'; function Openable() {} Openable.prototype = { // -- Lifecycle ------------------------------------------------------------ initializer: function () { this.nodeExtensions = this.nodeExtensions.concat(Y.Tree.Node.Openable); }, // -- Public Methods ------------------------------------------------------- /** Closes the specified node if it isn't already closed. @method closeNode @param {Tree.Node} node Node to close. @param {Object} [options] Options. @param {Boolean} [options.silent=false] If `true`, the `close` event will be suppressed. @param {String} [options.src] Source of the change, to be passed along to the event facade of the resulting event. This can be used to distinguish between changes triggered by a user and changes triggered programmatically, for example. @chainable **/ closeNode: function (node, options) { if (node.canHaveChildren && node.isOpen()) { this._fireTreeEvent(EVT_CLOSE, { node: node, src : options && options.src }, { defaultFn: this._defCloseFn, silent : options && options.silent }); } return this; }, /** Opens the specified node if it isn't already open. @method openNode @param {Tree.Node} node Node to open. @param {Object} [options] Options. @param {Boolean} [options.silent=false] If `true`, the `open` event will be suppressed. @param {String} [options.src] Source of the change, to be passed along to the event facade of the resulting event. This can be used to distinguish between changes triggered by a user and changes triggered programmatically, for example. @chainable **/ openNode: function (node, options) { if (node.canHaveChildren && !node.isOpen()) { this._fireTreeEvent(EVT_OPEN, { node: node, src : options && options.src }, { defaultFn: this._defOpenFn, silent : options && options.silent }); } return this; }, /** Toggles the open/closed state of the specified node, closing it if it's currently open or opening it if it's currently closed. @method toggleOpenNode @param {Tree.Node} node Node to toggle. @param {Object} [options] Options. @param {Boolean} [options.silent=false] If `true`, events will be suppressed. @param {String} [options.src] Source of the change, to be passed along to the event facade of the resulting event. This can be used to distinguish between changes triggered by a user and changes triggered programmatically, for example. @chainable **/ toggleOpenNode: function (node, options) { return node.isOpen() ? this.closeNode(node, options) : this.openNode(node, options); }, // -- Default Event Handlers ----------------------------------------------- /** Default handler for the `close` event. @method _defCloseFn @param {EventFacade} e @protected **/ _defCloseFn: function (e) { delete e.node.state.open; }, /** Default handler for the `open` event. @method _defOpenFn @param {EventFacade} e @protected **/ _defOpenFn: function (e) { e.node.state.open = true; } }; Y.Tree.Openable = Openable; /** @module tree @submodule tree-openable **/ /** `Tree.Node` extension that adds methods useful for nodes in trees that use the `Tree.Openable` extension. @class Tree.Node.Openable @constructor @extensionfor Tree.Node **/ function NodeOpenable() {} NodeOpenable.prototype = { /** Closes this node if it's currently open. @method close @param {Object} [options] Options. @param {Boolean} [options.silent=false] If `true`, the `close` event will be suppressed. @param {String} [options.src] Source of the change, to be passed along to the event facade of the resulting event. This can be used to distinguish between changes triggered by a user and changes triggered programmatically, for example. @chainable **/ close: function (options) { this.tree.closeNode(this, options); return this; }, /** Returns `true` if this node is currently open. Note: the root node of a tree is always considered to be open. @method isOpen @return {Boolean} `true` if this node is currently open, `false` otherwise. **/ isOpen: function () { return !!this.state.open || this.isRoot(); }, /** Opens this node if it's currently closed. @method open @param {Object} [options] Options. @param {Boolean} [options.silent=false] If `true`, the `open` event will be suppressed. @param {String} [options.src] Source of the change, to be passed along to the event facade of the resulting event. This can be used to distinguish between changes triggered by a user and changes triggered programmatically, for example. @chainable **/ open: function (options) { this.tree.openNode(this, options); return this; }, /** Toggles the open/closed state of this node, closing it if it's currently open or opening it if it's currently closed. @method toggleOpen @param {Object} [options] Options. @param {Boolean} [options.silent=false] If `true`, events will be suppressed. @param {String} [options.src] Source of the change, to be passed along to the event facade of the resulting event. This can be used to distinguish between changes triggered by a user and changes triggered programmatically, for example. @chainable **/ toggleOpen: function (options) { this.tree.toggleOpenNode(this, options); return this; } }; Y.Tree.Node.Openable = NodeOpenable; }, '3.11.0', {"requires": ["tree"]});
devmix/openjst
server/commons/war/src/main/webapp/ui/lib/yui/build/tree-openable/tree-openable.js
JavaScript
agpl-3.0
7,103
/* Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'blockquote', 'af', { toolbar: 'Sitaatblok' } );
ging/vish_orange
lib/plugins/ediphy/app/assets/javascripts/lib/ckeditor/plugins/blockquote/blockquote/lang/af.js
JavaScript
agpl-3.0
219
import { expect } from 'chai'; import { spec } from 'modules/yieldoneBidAdapter.js'; import { newBidder } from 'src/adapters/bidderFactory.js'; import { deepClone } from 'src/utils.js'; const ENDPOINT = 'https://y.one.impact-ad.jp/h_bid'; const USER_SYNC_URL = 'https://y.one.impact-ad.jp/push_sync'; const VIDEO_PLAYER_URL = 'https://img.ak.impact-ad.jp/ic/pone/ivt/firstview/js/dac-video-prebid.min.js'; const DEFAULT_VIDEO_SIZE = {w: 640, h: 360}; describe('yieldoneBidAdapter', function() { const adapter = newBidder(spec); describe('isBidRequestValid', function () { let bid = { 'bidder': 'yieldone', 'params': { placementId: '36891' }, 'adUnitCode': 'adunit-code', 'sizes': [[300, 250], [336, 280]], 'bidId': '23beaa6af6cdde', 'bidderRequestId': '19c0c1efdf37e7', 'auctionId': '61466567-d482-4a16-96f0-fe5f25ffbdf1', }; it('should return true when required params found', function () { expect(spec.isBidRequestValid(bid)).to.equal(true); }); it('should return false when placementId not passed correctly', function () { bid.params.placementId = ''; expect(spec.isBidRequestValid(bid)).to.equal(false); }); it('should return false when require params are not passed', function () { let bid = Object.assign({}, bid); bid.params = {}; expect(spec.isBidRequestValid(bid)).to.equal(false); }); }); describe('buildRequests', function () { const bidderRequest = { refererInfo: { numIframes: 0, reachedTop: true, referer: 'http://example.com', stack: ['http://example.com'] } }; describe('Basic', function () { const bidRequests = [ { 'bidder': 'yieldone', 'params': {placementId: '36891'}, 'adUnitCode': 'adunit-code1', 'bidId': '23beaa6af6cdde', 'bidderRequestId': '19c0c1efdf37e7', 'auctionId': '61466567-d482-4a16-96f0-fe5f25ffbdf1', }, { 'bidder': 'yieldone', 'params': {placementId: '47919'}, 'adUnitCode': 'adunit-code2', 'bidId': '382091349b149f"', 'bidderRequestId': '"1f9c98192de251"', 'auctionId': '61466567-d482-4a16-96f0-fe5f25ffbdf1', } ]; const request = spec.buildRequests(bidRequests, bidderRequest); it('sends bid request to our endpoint via GET', function () { expect(request[0].method).to.equal('GET'); expect(request[1].method).to.equal('GET'); }); it('attaches source and version to endpoint URL as query params', function () { expect(request[0].url).to.equal(ENDPOINT); expect(request[1].url).to.equal(ENDPOINT); }); it('adUnitCode should be sent as uc parameters on any requests', function () { expect(request[0].data.uc).to.equal('adunit-code1'); expect(request[1].data.uc).to.equal('adunit-code2'); }); }); describe('Old Format', function () { const bidRequests = [ { params: {placementId: '0'}, mediaType: 'banner', sizes: [[300, 250], [336, 280]], }, { params: {placementId: '1'}, mediaType: 'banner', sizes: [[336, 280]], }, { // It doesn't actually exist. params: {placementId: '2'}, }, { params: {placementId: '3'}, mediaType: 'video', sizes: [[1280, 720], [1920, 1080]], }, { params: {placementId: '4'}, mediaType: 'video', sizes: [[1920, 1080]], }, { params: {placementId: '5'}, mediaType: 'video', }, ]; const request = spec.buildRequests(bidRequests, bidderRequest); it('parameter sz has more than one size on banner requests', function () { expect(request[0].data.sz).to.equal('300x250,336x280'); expect(request[1].data.sz).to.equal('336x280'); expect(request[2].data.sz).to.equal(''); expect(request[3].data).to.not.have.property('sz'); expect(request[4].data).to.not.have.property('sz'); expect(request[5].data).to.not.have.property('sz'); }); it('width and height should be set as separate parameters on outstream requests', function () { expect(request[0].data).to.not.have.property('w'); expect(request[1].data).to.not.have.property('w'); expect(request[2].data).to.not.have.property('w'); expect(request[3].data.w).to.equal(1280); expect(request[3].data.h).to.equal(720); expect(request[4].data.w).to.equal(1920); expect(request[4].data.h).to.equal(1080); expect(request[5].data.w).to.equal(DEFAULT_VIDEO_SIZE.w); expect(request[5].data.h).to.equal(DEFAULT_VIDEO_SIZE.h); }); }); describe('New Format', function () { const bidRequests = [ { params: {placementId: '0'}, mediaTypes: { banner: { sizes: [[300, 250], [336, 280]], }, }, }, { params: {placementId: '1'}, mediaTypes: { banner: { sizes: [[336, 280]], }, }, }, { // It doesn't actually exist. params: {placementId: '2'}, mediaTypes: { banner: { }, }, }, { params: {placementId: '3'}, mediaTypes: { video: { context: 'outstream', playerSize: [[1280, 720], [1920, 1080]], }, }, }, { params: {placementId: '4'}, mediaTypes: { video: { context: 'outstream', playerSize: [1920, 1080], }, }, }, { params: {placementId: '5'}, mediaTypes: { video: { context: 'outstream', }, }, }, ]; const request = spec.buildRequests(bidRequests, bidderRequest); it('parameter sz has more than one size on banner requests', function () { expect(request[0].data.sz).to.equal('300x250,336x280'); expect(request[1].data.sz).to.equal('336x280'); expect(request[2].data.sz).to.equal(''); expect(request[3].data).to.not.have.property('sz'); expect(request[4].data).to.not.have.property('sz'); expect(request[5].data).to.not.have.property('sz'); }); it('width and height should be set as separate parameters on outstream requests', function () { expect(request[0].data).to.not.have.property('w'); expect(request[1].data).to.not.have.property('w'); expect(request[2].data).to.not.have.property('w'); expect(request[3].data.w).to.equal(1280); expect(request[3].data.h).to.equal(720); expect(request[4].data.w).to.equal(1920); expect(request[4].data.h).to.equal(1080); expect(request[5].data.w).to.equal(DEFAULT_VIDEO_SIZE.w); expect(request[5].data.h).to.equal(DEFAULT_VIDEO_SIZE.h); }); }); describe('Multiple Format', function () { const bidRequests = [ { // It will be treated as a banner. params: { placementId: '0', }, mediaTypes: { banner: { sizes: [[300, 250], [336, 280]], }, video: { context: 'outstream', playerSize: [1920, 1080], }, }, }, { // It will be treated as a video. params: { placementId: '1', playerParams: {}, }, mediaTypes: { banner: { sizes: [[300, 250], [336, 280]], }, video: { context: 'outstream', playerSize: [1920, 1080], }, }, }, ]; const request = spec.buildRequests(bidRequests, bidderRequest); it('parameter sz has more than one size on banner requests', function () { expect(request[0].data.sz).to.equal('300x250,336x280'); expect(request[1].data).to.not.have.property('sz'); }); it('width and height should be set as separate parameters on outstream requests', function () { expect(request[0].data).to.not.have.property('w'); expect(request[1].data.w).to.equal(1920); expect(request[1].data.h).to.equal(1080); }); }); describe('FLUX Format', function () { const bidRequests = [ { // It will be treated as a banner. params: { placementId: '0', }, mediaTypes: { banner: { sizes: [[300, 250], [336, 280]], }, video: { context: 'outstream', playerSize: [[1, 1]], }, }, }, { // It will be treated as a video. params: { placementId: '1', playerParams: {}, playerSize: [1920, 1080], }, mediaTypes: { banner: { sizes: [[300, 250], [336, 280]], }, video: { context: 'outstream', playerSize: [[1, 1]], }, }, }, { // It will be treated as a video. params: { placementId: '2', playerParams: {}, }, mediaTypes: { banner: { sizes: [[300, 250], [336, 280]], }, video: { context: 'outstream', playerSize: [[1, 1]], }, }, }, ]; const request = spec.buildRequests(bidRequests, bidderRequest); it('parameter sz has more than one size on banner requests', function () { expect(request[0].data.sz).to.equal('300x250,336x280'); expect(request[1].data).to.not.have.property('sz'); expect(request[2].data).to.not.have.property('sz'); }); it('width and height should be set as separate parameters on outstream requests', function () { expect(request[0].data).to.not.have.property('w'); expect(request[1].data.w).to.equal(1920); expect(request[1].data.h).to.equal(1080); expect(request[2].data.w).to.equal(DEFAULT_VIDEO_SIZE.w); expect(request[2].data.h).to.equal(DEFAULT_VIDEO_SIZE.h); }); }); describe('LiveRampID', function () { it('dont send LiveRampID if undefined', function () { const bidRequests = [ { params: {placementId: '0'}, }, { params: {placementId: '1'}, userId: {}, }, { params: {placementId: '2'}, userId: undefined, }, ]; const request = spec.buildRequests(bidRequests, bidderRequest); expect(request[0].data).to.not.have.property('lr_env'); expect(request[1].data).to.not.have.property('lr_env'); expect(request[2].data).to.not.have.property('lr_env'); }); it('should send LiveRampID if available', function () { const bidRequests = [ { params: {placementId: '0'}, userId: {idl_env: 'idl_env_sample'}, }, ]; const request = spec.buildRequests(bidRequests, bidderRequest); expect(request[0].data.lr_env).to.equal('idl_env_sample'); }); }); describe('IMID', function () { it('dont send IMID if undefined', function () { const bidRequests = [ { params: {placementId: '0'}, }, { params: {placementId: '1'}, userId: {}, }, { params: {placementId: '2'}, userId: undefined, }, ]; const request = spec.buildRequests(bidRequests, bidderRequest); expect(request[0].data).to.not.have.property('imuid'); expect(request[1].data).to.not.have.property('imuid'); expect(request[2].data).to.not.have.property('imuid'); }); it('should send IMID if available', function () { const bidRequests = [ { params: {placementId: '0'}, userId: {imuid: 'imuid_sample'}, }, ]; const request = spec.buildRequests(bidRequests, bidderRequest); expect(request[0].data.imuid).to.equal('imuid_sample'); }); }); }); describe('interpretResponse', function () { let bidRequestBanner = [ { 'method': 'GET', 'url': 'https://y.one.impact-ad.jp/h_bid', 'data': { 'v': 'hb1', 'p': '36891', 'sz': '300x250,336x280', 'cb': 12892917383, 'r': 'http%3A%2F%2Flocalhost%3A9876%2F%3Fid%3D74552836', 'uid': '23beaa6af6cdde', 't': 'i' } } ]; let serverResponseBanner = { body: { 'adTag': '<!-- adtag -->', 'uid': '23beaa6af6cdde', 'height': 250, 'width': 300, 'cpm': 0.0536616, 'crid': '2494768', 'currency': 'JPY', 'statusMessage': 'Bid available', 'dealId': 'P1-FIX-7800-DSP-MON', 'admoain': [ 'www.example.com' ] } }; it('should get the correct bid response for banner', function () { let expectedResponse = [{ 'requestId': '23beaa6af6cdde', 'cpm': 53.6616, 'width': 300, 'height': 250, 'creativeId': '2494768', 'dealId': 'P1-FIX-7800-DSP-MON', 'currency': 'JPY', 'netRevenue': true, 'ttl': 3000, 'referrer': '', 'meta': { 'advertiserDomains': [ 'www.example.com' ] }, 'mediaType': 'banner', 'ad': '<!-- adtag -->' }]; let result = spec.interpretResponse(serverResponseBanner, bidRequestBanner[0]); expect(Object.keys(result[0])).to.deep.equal(Object.keys(expectedResponse[0])); expect(result[0].mediaType).to.equal(expectedResponse[0].mediaType); }); let serverResponseVideo = { body: { 'uid': '23beaa6af6cdde', 'height': 360, 'width': 640, 'cpm': 0.0536616, 'dealId': 'P1-FIX-766-DSP-MON', 'crid': '2494768', 'currency': 'JPY', 'statusMessage': 'Bid available', 'adm': '<!-- vast -->' } }; let bidRequestVideo = [ { 'method': 'GET', 'url': 'https://y.one.impact-ad.jp/h_bid', 'data': { 'v': 'hb1', 'p': '41993', 'w': '640', 'h': '360', 'cb': 12892917383, 'r': 'http%3A%2F%2Flocalhost%3A9876%2F%3Fid%3D74552836', 'uid': '23beaa6af6cdde', 't': 'i' } } ]; it('should get the correct bid response for video', function () { let expectedResponse = [{ 'requestId': '23beaa6af6cdde', 'cpm': 53.6616, 'width': 640, 'height': 360, 'creativeId': '2494768', 'dealId': 'P1-FIX-7800-DSP-MON', 'currency': 'JPY', 'netRevenue': true, 'ttl': 3000, 'referrer': '', 'meta': { 'advertiserDomains': [] }, 'mediaType': 'video', 'vastXml': '<!-- vast -->', 'renderer': { id: '23beaa6af6cdde', url: VIDEO_PLAYER_URL } }]; let result = spec.interpretResponse(serverResponseVideo, bidRequestVideo[0]); expect(Object.keys(result[0])).to.deep.equal(Object.keys(expectedResponse[0])); expect(result[0].mediaType).to.equal(expectedResponse[0].mediaType); expect(result[0].renderer.id).to.equal(expectedResponse[0].renderer.id); expect(result[0].renderer.url).to.equal(expectedResponse[0].renderer.url); }); it('handles empty bid response', function () { let response = { body: { 'uid': '2c0b634db95a01', 'height': 0, 'crid': '', 'statusMessage': 'Bid returned empty or error response', 'width': 0, 'cpm': 0 } }; let result = spec.interpretResponse(response, bidRequestBanner[0]); expect(result.length).to.equal(0); }); }); describe('getUserSyncs', function () { it('handles empty sync options', function () { expect(spec.getUserSyncs({})).to.be.undefined; }); it('should return a sync url if iframe syncs are enabled', function () { expect(spec.getUserSyncs({ 'iframeEnabled': true })).to.deep.equal([{ type: 'iframe', url: USER_SYNC_URL }]); }); }); });
PubWise/Prebid.js
test/spec/modules/yieldoneBidAdapter_spec.js
JavaScript
apache-2.0
16,949
$(document).ready( function() { var $roles = $(".role_change"); $roles.each( function() { var str = $(this).find("input").val(); var en_role_index = getRoleIndex(str,"EN"); var cn_role_str = indexToRole(en_role_index,"CN"); $(this).find("span").append(cn_role_str); } ); } );
tianfengjingjing/ZhuoHuaCMMOracle11g
WebRoot/js/admin/staff/viewStaffInfo.js
JavaScript
apache-2.0
367
(function () { var pigKeywordsU = pigKeywordsL = pigTypesU = pigTypesL = pigBuiltinsU = pigBuiltinsL = []; var mimeMode = CodeMirror.mimeModes['text/x-pig']; Object.keys(mimeMode.keywords).forEach( function(w) { pigKeywordsU.push(w.toUpperCase()); pigKeywordsL.push(w.toLowerCase()); }); Object.keys(mimeMode.types).forEach( function(w) { pigTypesU.push(w.toUpperCase()); pigTypesL.push(w.toLowerCase()); }); Object.keys(mimeMode.builtins).forEach( function(w) { pigBuiltinsU.push(w.toUpperCase()); pigBuiltinsL.push(w.toLowerCase()); }); function forEach(arr, f) { for (var i = 0, e = arr.length; i < e; ++i) { f(arr[i]); } } function arrayContains(arr, item) { if (!Array.prototype.indexOf) { var i = arr.length; while (i--) { if (arr[i] === item) { return true; } } return false; } return arr.indexOf(item) != -1; } function scriptHint(editor, keywords, getToken) { // Find the token at the cursor var cur = editor.getCursor(), token = getToken(editor, cur), tprop = token; // If it's not a 'word-style' token, ignore the token. if (!/^[\w$_]*$/.test(token.string)) { token = tprop = {start: cur.ch, end: cur.ch, string: "", state: token.state, type: token.string == ":" ? "pig-type" : null}; } if (!context) var context = []; context.push(tprop); completionList = getCompletions(token, context); completionList = completionList.sort(); return {list: completionList, from: {line: cur.line, ch: token.start}, to: {line: cur.line, ch: token.end}}; } function toTitleCase(str) { return str.replace(/(?:^|\s)\w/g, function(match) { return match.toUpperCase(); }); } function getCompletions(token, context) { var found = [], start = token.string; function maybeAdd(str) { if (str.indexOf(start) == 0 && !arrayContains(found, str)) found.push(str); } function gatherCompletions(obj) { if(obj == ":") { forEach(pigTypesL, maybeAdd); } else { forEach(pigBuiltinsU, maybeAdd); forEach(pigBuiltinsL, maybeAdd); forEach(pigTypesU, maybeAdd); forEach(pigTypesL, maybeAdd); forEach(pigKeywordsU, maybeAdd); forEach(pigKeywordsL, maybeAdd); } } if (context) { // If this is a property, see if it belongs to some object we can // find in the current environment. var obj = context.pop(), base; if (obj.type == "pig-word") base = obj.string; else if(obj.type == "pig-type") base = ":" + obj.string; while (base != null && context.length) base = base[context.pop().string]; if (base != null) gatherCompletions(base); } return found; } CodeMirror.registerHelper("hint", "pig", function(cm, options) { return scriptHint(cm, pigKeywordsU, function (e, cur) {return e.getTokenAt(cur);}); }); })();
radicalbit/ambari
contrib/views/pig/src/main/resources/ui/pig-web/vendor/pig-hint.js
JavaScript
apache-2.0
3,053
import {removeElement} from '#core/dom'; import {Layout_Enum, applyFillContent} from '#core/dom/layout'; import {Services} from '#service'; import {userAssert} from '#utils/log'; import {TAG as KEY_TAG} from './amp-embedly-key'; import {getIframe} from '../../../src/3p-frame'; import {listenFor} from '../../../src/iframe-helper'; /** * Component tag identifier. * @const {string} */ export const TAG = 'amp-embedly-card'; /** * Attribute name used to set api key with name * expected by embedly. * @const {string} */ const API_KEY_ATTR_NAME = 'data-card-key'; /** * Implementation of the amp-embedly-card component. * See {@link ../amp-embedly-card.md} for the spec. */ export class AmpEmbedlyCard extends AMP.BaseElement { /** @param {!AmpElement} element */ constructor(element) { super(element); /** @private {?HTMLIFrameElement} */ this.iframe_ = null; /** @private {?string} */ this.apiKey_ = null; } /** @override */ buildCallback() { userAssert( this.element.getAttribute('data-url'), 'The data-url attribute is required for <%s> %s', TAG, this.element ); const ampEmbedlyKeyElement = document.querySelector(KEY_TAG); if (ampEmbedlyKeyElement) { this.apiKey_ = ampEmbedlyKeyElement.getAttribute('value'); } } /** @override */ layoutCallback() { // Add optional paid api key attribute if provided // to remove embedly branding. if (this.apiKey_) { this.element.setAttribute(API_KEY_ATTR_NAME, this.apiKey_); } const iframe = getIframe(this.win, this.element, 'embedly'); iframe.title = this.element.title || 'Embedly card'; const opt_is3P = true; listenFor( iframe, 'embed-size', (data) => { this.forceChangeHeight(data['height']); }, opt_is3P ); applyFillContent(iframe); this.getVsync().mutate(() => { this.element.appendChild(iframe); }); this.iframe_ = iframe; return this.loadPromise(iframe); } /** @override */ unlayoutCallback() { if (this.iframe_) { removeElement(this.iframe_); this.iframe_ = null; } return true; } /** @override */ isLayoutSupported(layout) { return layout == Layout_Enum.RESPONSIVE; } /** * @param {boolean=} opt_onLayout * @override */ preconnectCallback(opt_onLayout) { Services.preconnectFor(this.win).url( this.getAmpDoc(), 'https://cdn.embedly.com', opt_onLayout ); } }
media-net/amphtml
extensions/amp-embedly-card/0.1/amp-embedly-card-impl.js
JavaScript
apache-2.0
2,517
/** * Sitespeed.io - How speedy is your site? (https://www.sitespeed.io) * Copyright (c) 2014, Peter Hedenskog, Tobias Lidskog * and other contributors * Released under the Apache 2.0 License */ 'use strict'; var util = require('../util/util'), RequestTiming = require('../requestTiming'), Stats = require('fast-stats').Stats, winston = require('winston'); var domains = {}; exports.processPage = function(pageData) { var log = winston.loggers.get('sitespeed.io'); var harData = []; if (pageData.browsertime && pageData.browsertime.har) { Array.prototype.push.apply(harData, pageData.browsertime.har); } if (pageData.webpagetest && pageData.webpagetest.har) { Array.prototype.push.apply(harData, pageData.webpagetest.har); } // Workaround to avoid issues when bt doesn't generate a har due to useProxy being set to false harData = harData.filter(function(har) { return !!har; }); var pageURL = util.getURLFromPageData(pageData); harData.forEach(function(har) { har.log.entries.forEach(function(entry) { var domain = domains[util.getHostname(entry.request.url)]; var total; if (domain) { if (entry.timings) { total = entry.timings.blocked + entry.timings.dns + entry.timings.connect + entry.timings.ssl + entry.timings .send + entry.timings.wait + entry.timings.receive; domain.blocked.add(entry.timings.blocked, entry.request.url, pageURL); domain.dns.add(entry.timings.dns, entry.request.url, pageURL); domain.connect.add(entry.timings.connect, entry.request.url, pageURL); domain.ssl.add(entry.timings.ssl, entry.request.url, pageURL); domain.send.add(entry.timings.send, entry.request.url, pageURL); domain.wait.add(entry.timings.wait, entry.request.url, pageURL); domain.receive.add(entry.timings.receive, entry.request.url, pageURL); domain.total.add(total, entry.request.url, pageURL); domain.accumulatedTime += total; } else { log.log('info', 'Missing timings in the HAR'); } } else { if (entry.timings) { total = entry.timings.blocked + entry.timings.dns + entry.timings.connect + entry.timings.ssl + entry.timings .send + entry.timings.wait + entry.timings.receive; domains[util.getHostname(entry.request.url)] = { domain: util.getHostname(entry.request.url), blocked: new RequestTiming(entry.timings.blocked, entry.request.url, pageURL), dns: new RequestTiming(entry.timings.dns, entry.request.url, pageURL), connect: new RequestTiming(entry.timings.connect, entry.request.url, pageURL), ssl: new RequestTiming(entry.timings.ssl, entry.request.url, pageURL), send: new RequestTiming(entry.timings.send, entry.request.url, pageURL), wait: new RequestTiming(entry.timings.wait, entry.request.url, pageURL), receive: new RequestTiming(entry.timings.receive, entry.request.url, pageURL), total: new RequestTiming(total, entry.request.url, pageURL), accumulatedTime: total }; } else { log.log('info', 'Missing timings in the HAR'); } } }); }); // we have HAR files with one page tested multiple times, // make sure we only get data from the first run // and we kind of add items & size for requests missing // but only for the first one var pageref = ''; // add request & size, just do it for the first run if (harData.length > 0) { harData[0].log.entries.forEach(function(entry) { if (pageref === '' || entry.pageref === pageref) { pageref = entry.pageref; var domain = domains[util.getHostname(entry.request.url)]; if (domain.count) { domain.count++; } else { domain.count = 1; } if (domain.size) { domain.size.total += entry.response.content.size; domain.size[util.getContentType(entry.response.content.mimeType)] += entry.response.content.size; } else { domain.size = { total: entry.response.content.size, css: 0, doc: 0, js: 0, image: 0, font: 0, flash: 0, unknown: 0 }; domain.size[util.getContentType(entry.response.content.mimeType)] = entry.response.content.size; } } else { // all other har files var daDomain = domains[util.getHostname(entry.request.url)]; if (!daDomain.count) { daDomain.count = 1; } if (!daDomain.size) { // this is not perfect, we will miss request in other HAR..s daDomain.size = { total: entry.response.content.size, css: 0, doc: 0, js: 0, image: 0, font: 0, flash: 0, unknown: 0 }; daDomain.size[util.getContentType(entry.response.content.mimeType)] = entry.response.content.size; } } }); } }; exports.generateResults = function() { var values = Object.keys(domains).map(function(key) { return domains[key]; }); return { id: 'domains', list: values }; }; exports.clear = function() { domains = {}; };
yesman82/sitespeed.io
lib/collectors/domains.js
JavaScript
apache-2.0
5,405