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
|
---|---|---|---|---|---|
import ruleError from './ruleError'
// Tags that have no associated components but are allowed even so
const componentLessTags = [
'mj-all',
'mj-class',
'mj-selector',
'mj-html-attribute',
]
export default function validateTag(element, { components }) {
const { tagName } = element
if (componentLessTags.includes(tagName)) return null
const Component = components[tagName]
if (!Component) {
return ruleError(
`Element ${tagName} doesn't exist or is not registered`,
element,
)
}
return null
}
| mjmlio/mjml | packages/mjml-validator/src/rules/validTag.js | JavaScript | mit | 539 |
class dximagetransform_microsoft_crblinds_1 {
constructor() {
// short bands () {get} {set}
this.bands = undefined;
// int Capabilities () {get}
this.Capabilities = undefined;
// string Direction () {get} {set}
this.Direction = undefined;
// float Duration () {get} {set}
this.Duration = undefined;
// float Progress () {get} {set}
this.Progress = undefined;
// float StepResolution () {get}
this.StepResolution = undefined;
}
}
module.exports = dximagetransform_microsoft_crblinds_1;
| mrpapercut/wscript | testfiles/COMobjects/JSclasses/DXImageTransform.Microsoft.CrBlinds.1.js | JavaScript | mit | 598 |
'use strict';
var webpack = require('webpack');
var cfg = {
entry: './src/main.jsx',
output: {
path: __dirname + '/dist',
filename: 'main.js',
},
externals: {
yaspm: 'commonjs yaspm'
},
target: process.env.NODE_ENV === 'web' ? 'web' : 'node-webkit',
module: {
loaders: [
{
test: /\.css$/,
loader: "style-loader!css-loader"
},
{
test: /\.scss$/,
loader: 'style-loader!css-loader!sass-loader?includePaths[]=' +
__dirname + '/src'
},
{
test: /\.(js|jsx)$/,
loader: 'jsx-loader?harmony'
}
]
},
plugins: [
new webpack.DefinePlugin({
'__NODEWEBKIT__': process.env.NODE_ENV === 'nodewebkit',
})
]
};
module.exports = cfg;
| cirocosta/ledmatrix | webpack.config.js | JavaScript | mit | 772 |
/**
* Created by ff on 2016/10/25.
*/
require('./style.css');
var vm = avalon.define({
$id:'map'
})
module.exports = vm; | orgrinDataOrganization/orgrinData | src/mv/map/index.js | JavaScript | mit | 123 |
'use strict';
const _ = require('lodash');
const path = require('path');
/**
* Special settings for use with serverless-offline.
*/
module.exports = {
prepareOfflineInvoke() {
// Use service packaging for compile
_.set(this.serverless, 'service.package.individually', false);
return this.serverless.pluginManager.spawn('webpack:validate').then(() => {
// Set offline location automatically if not set manually
if (!this.options.location && !_.get(this.serverless, 'service.custom.serverless-offline.location')) {
_.set(
this.serverless,
'service.custom.serverless-offline.location',
path.relative(this.serverless.config.servicePath, path.join(this.webpackOutputPath, 'service'))
);
}
return null;
});
}
};
| elastic-coders/serverless-webpack | lib/prepareOfflineInvoke.js | JavaScript | mit | 802 |
let widget = document.getElementsByClassName('markdownx-widget')[0];
let element = document.getElementsByClassName('markdownx');
let element_divs = element[0].getElementsByTagName('div');
let div_editor = element_divs[0];
let div_preview = element_divs[1];
let navbar_bar = document.getElementsByClassName('markdownx-toolbar')[0].getElementsByTagName('li');
let btn_preview = navbar_bar[0];
let btn_fullscreen = navbar_bar[1];
var turn_active = function(element) {
value = element.classname;
classval = element.getAttribute('class');
if (value.indexOf('active') >= 0) {
element.removeClass('active');
}
else {
value += 'active'
}
}
var refresh_pretty = function() {
// 每次有都需要重新渲染code
PR.prettyPrint();
};
var enable_preview = function() {
var class_btn_preview = btn_preview.getAttribute('class');
var index = class_btn_preview.indexOf('active');
if (index >= 0) {
btn_preview.setAttribute('class', '');
div_editor.setAttribute('class', 'col-md-12 child-left');
div_preview.style.display = 'none';
}
else {
btn_preview.setAttribute('class', 'active');
div_editor.setAttribute('class', 'col-md-6 child-left');
div_preview.style.display = 'block';
}
};
var enable_fullscreen = function() {
var class_btn_fullscreen = btn_fullscreen.getAttribute('class');
var index = class_btn_fullscreen.indexOf('active');
if (index >= 0) {
btn_fullscreen.setAttribute('class', '');
widget.setAttribute('class', 'markup-widget');
}
else{
btn_fullscreen.setAttribute('class', 'active');
widget.setAttribute('class', 'markup-widget fullscreen');
}
}
Object.keys(element).map(key =>
element[key].addEventListener('markdownx.update', refresh_pretty)
);
btn_preview.addEventListener('click', enable_preview);
btn_fullscreen.addEventListener('click', enable_fullscreen);
| BaskerShu/typeidea | typeidea/typeidea/themes/default/static/js/markdownx-widget.js | JavaScript | mit | 1,967 |
module.exports = {};
var app_data = {};
function initCharts()
{
$(document).ready(function() {
$.get(app_data.config.analytics_data_route, function(analytics_data) {
data = analytics_data.data;
max_val = analytics_data.highest_value;
var parseDate = d3.time.format('%Y%m%d').parse;
data.forEach(function(d) {
d.date = parseDate(d.date);
});
$('.sessions-value').html(formatAnalyticsValue((analytics_data.total_sessions).toString()));
$('.views-value').html(formatAnalyticsValue((analytics_data.total_views).toString()));
d3.select(window).on('resize', resize);
loadCharts();
}, 'json');
});
}
function loadChart(data, max_val, selector, graph_width, graph_height)
{
var margin = { top: 20, right: 0, bottom: 30, left: 50 },
width = graph_width - margin.left - margin.right,
height = graph_height - margin.top - margin.bottom;
var x = d3.time.scale().range([0, width]);
var y = d3.scale.linear().range([height, 0]);
var color = d3.scale.category10();
var x_axis = d3.svg.axis().scale(x).orient('bottom'); //.tickFormat(d3.time.format('%m/%d/%y'));
var y_axis = d3.svg.axis().scale(y).orient('left').ticks(6);
var line = d3.svg.line()
.interpolate('cardinal')
.tension(0.8)
.x(function(d) { return x(d.date); })
.y(function(d) { return y(d.val); });
var line_gridline = d3.svg.line()
.x(function(d) { return x(d[0]); })
.y(function(d) { return y(d[1]); });
var area = d3.svg.area()
.interpolate('cardinal')
.tension(0.8)
.x(function(d) { return x(d.date); })
.y0(height)
.y1(function(d) { return y(d.val); });
d3.select(selector + ' > svg').remove();
var svg = d3.select(selector).append('svg')
.attr('viewBox', '0 0 ' + graph_width + ' ' + graph_height)
.attr('perserveAspectRatio', 'xMinYMid')
.append('g')
.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
color.domain([ 'sessions', 'views' ]);
var analytics = color.domain().map(function(name) {
return {
name: name,
values: data.map(function(d) {
return {date: d.date, val: +d[name]};
})
};
});
var x_extent = d3.extent(data, function(d) { return d.date; });
x.domain(x_extent);
y.domain([
d3.min(analytics, function(c) { return 0; }),
d3.max(analytics, function(c) { return max_val; /*d3.max(c.values, function(v) { return v.val; });*/ })
]);
svg.append('g')
.attr('class', 'x axis')
.attr('transform', 'translate(0,' + height + ')')
.call(x_axis);
svg.append('g')
.attr('class', 'y axis')
.call(y_axis)
.append('text')
.style('text-anchor', 'end');
var gridline_data = [];
svg.selectAll('.y.axis .tick').each(function(data) {
var tick = d3.select(this);
var transform = d3.transform(tick.attr('transform')).translate;
if (data > 0)
{
gridline_data.push({ values: [[x_extent[0], transform[1]], [x_extent[1], transform[1]]] });
}
});
gridline_data.forEach(function(data) {
svg.append('line')
.attr('class', 'gridline')
.attr('x1', x(data.values[0][0]))
.attr('x2', x(data.values[1][0]))
.attr('y1', data.values[0][1])
.attr('y2', data.values[1][1]);
});
var analytics_line = svg.selectAll('.analytics_line')
.data(analytics)
.enter().append('g')
.attr('class', 'analytics_line');
analytics_line.append('path')
.attr('class', 'line')
.attr('d', function(d) { return line(d.values); })
.style('stroke', function(d) { return '#f2711c'; });
analytics_line.append('path')
.attr('class', 'area')
.attr('d', function(d) { return area(d.values); })
.style('fill', function(d) { return '#f2711c'; });
/*analytics.forEach(function(category) {
category.values.forEach(function(item) {
analytics_line.append('circle')
.attr('class', 'dot')
.attr('r', 4)
.attr('cx', x(item.date))
.attr('cy', y(item.val))
.style('fill', '#f2711c');
});
});*/
}
function formatAnalyticsValue(value)
{
var formatted_val = '';
var c = 1;
for (var i=value.length-1; i>=0; i--)
{
formatted_val = (c++ % 3 == 0 && i > 0 ? ' ' : '') + value.substring(i, i+1) + formatted_val;
}
return formatted_val;
}
var aspect = 4;
var chart = null;
var data = null;
var max_val = 0;
var resize_timeout = -1;
function resize()
{
if (resize_timeout != -1) clearTimeout(resize_timeout);
resize_timeout = setTimeout(function() {
resize_timeout = -1;
loadCharts();
}, 1000);
}
function loadCharts()
{
if (data == null) return;
var width = $('.analytics-graph').width();
var height = Math.max(200, $('.analytics-graph').width()/aspect); //prevents height to be smaller than 200px
loadChart(data, max_val, '.analytics-graph', width, height);
chart = $('.analytics-graph > svg');
}
module.exports.init = function(trans, config) {
app_data.trans = trans;
app_data.config = config;
$(document).ready(function() {
initCharts();
});
};
| neonbug/meexo-common | src/assets/admin_assets/js/app/src/modules/dashboard.js | JavaScript | mit | 5,037 |
const SpecReporter = require('jasmine-spec-reporter').SpecReporter;
jasmine.getEnv().clearReporters(); // remove default reporter logs
jasmine.getEnv().addReporter(new SpecReporter({ // add jasmine-spec-reporter
spec: {
displayPending: true,
},
summary: {
displayDuration: true,
}
})); | royNiladri/js-big-decimal | spec/helper/reporter.js | JavaScript | mit | 317 |
const webpack = require('atool-build/lib/webpack');
module.exports = function (webpackConfig, env) {
webpackConfig.babel.plugins.push('transform-runtime');
webpackConfig.babel.plugins.push(['import', {
libraryName: 'antd',
style: 'css' // if true, use less
}]);
// Support hmr
if (env === 'development') {
webpackConfig.devtool = '#eval';
webpackConfig.babel.plugins.push('dva-hmr');
} else {
webpackConfig.babel.plugins.push('dev-expression');
}
// Don't extract common.js and common.css
webpackConfig.plugins = webpackConfig.plugins.filter(function (plugin) {
return !(plugin instanceof webpack.optimize.CommonsChunkPlugin);
});
// Support CSS Modules
// Parse all less files as css module.
webpackConfig.module.loaders.forEach(function (loader, index) {
if (typeof loader.test === 'function' && loader.test.toString().indexOf('\\.less$') > -1) {
loader.include = /node_modules/;
loader.test = /\.less$/;
}
if (loader.test.toString() === '/\\.module\\.less$/') {
loader.exclude = /node_modules/;
loader.test = /\.less$/;
}
if (typeof loader.test === 'function' && loader.test.toString().indexOf('\\.css$') > -1) {
loader.include = /node_modules/;
loader.test = /\.css$/;
}
if (loader.test.toString() === '/\\.module\\.css$/') {
loader.exclude = /node_modules/;
loader.test = /\.css$/;
}
});
return webpackConfig;
};
| aiguanglee/dva-cnode | webpack.config.js | JavaScript | mit | 1,457 |
'use strict';
describe('Controllers Tests ', function () {
beforeEach(module('solrpressApp'));
describe('SessionsController', function () {
var $scope, SessionsService;
beforeEach(inject(function ($rootScope, $controller, Sessions) {
$scope = $rootScope.$new();
SessionsService = Sessions;
$controller('SessionsController',{$scope:$scope, Sessions:SessionsService});
}));
it('should invalidate session', function () {
//GIVEN
$scope.series = "123456789";
//SET SPY
spyOn(SessionsService, 'delete');
//WHEN
$scope.invalidate($scope.series);
//THEN
expect(SessionsService.delete).toHaveBeenCalled();
expect(SessionsService.delete).toHaveBeenCalledWith({series: "123456789"}, jasmine.any(Function), jasmine.any(Function));
//SIMULATE SUCCESS CALLBACK CALL FROM SERVICE
SessionsService.delete.calls.mostRecent().args[1]();
expect($scope.error).toBeNull();
expect($scope.success).toBe('OK');
});
});
});
| dynamicguy/solrpress | src/test/javascript/spec/app/account/sessions/sessionsControllerSpec.js | JavaScript | mit | 1,153 |
Template.registerHelper("itemTypes", function() {
return [
{label: i18n.t('choose'), value: ''},
{label: i18n.t('offer'), value: 'offer', icon: 'icon gift'},
{label: i18n.t('need'), value: 'need', icon: 'icon fire'},
{label: i18n.t('wish'), value: 'wish', icon: 'icon wizard'},
{label: i18n.t('idea'), value: 'idea', icon: 'icon cloud'}
]
})
| heaven7/wsl-items | lib/client/helpers.js | JavaScript | mit | 391 |
// --------------------------------------------------------------------------------------------------------------------
//
// cloudfront-config.js - config for AWS CloudFront
//
// Copyright (c) 2011 AppsAttic Ltd - http://www.appsattic.com/
// Written by Andrew Chilton <[email protected]>
//
// License: http://opensource.org/licenses/MIT
//
// --------------------------------------------------------------------------------------------------------------------
var data2xml = require('data2xml')({ attrProp : '@', valProp : '#', });
// --------------------------------------------------------------------------------------------------------------------
function pathDistribution(options, args) {
return '/' + this.version() + '/distribution';
}
function pathDistributionId(options, args) {
return '/' + this.version() + '/distribution/' + args.DistributionId;
}
function pathDistributionIdConfig(options, args) {
return '/' + this.version() + '/distribution/' + args.DistributionId + '/config';
}
function pathDistributionInvalidation(options, args) {
return '/' + this.version() + '/distribution/' + args.DistributionId + '/invalidation';
}
function pathDistributionInvalidationId(options, args) {
return '/' + this.version() + '/distribution/' + args.DistributionId + '/invalidation/' + args.InvalidationId;
}
function pathStreamingDistribution(options, args) {
return '/' + this.version() + '/streaming-distribution';
}
function pathStreamingDistributionId(options, args) {
return '/' + this.version() + '/streaming-distribution/' + args.DistributionId;
}
function pathStreamingDistributionIdConfig(options, args) {
return '/' + this.version() + '/streaming-distribution/' + args.DistributionId + '/config';
}
function pathOai(options, args) {
return '/' + this.version() + '/origin-access-identity/cloudfront';
}
function pathOaiId(options, args) {
return '/' + this.version() + '/origin-access-identity/cloudfront/' + args.OriginAccessId;
}
function pathOaiIdConfig(options, args) {
return '/' + this.version() + '/origin-access-identity/cloudfront/' + args.OriginAccessId + '/config';
}
function bodyDistributionConfig(options, args) {
// create the XML
var data = {
'@' : { 'xmlns' : 'http://cloudfront.amazonaws.com/doc/2010-11-01/' },
};
if ( args.S3OriginDnsName ) {
data.S3Origin = {};
data.S3Origin.DNSName = args.S3OriginDnsName;
if ( args.S3OriginOriginAccessIdentity ) {
data.S3Origin.OriginAccessIdentity = args.S3OriginOriginAccessIdentity;
}
}
if ( args.CustomOriginDnsName || args.CustomOriginOriginProtocolPolicy ) {
data.CustomOrigin = {};
if ( args.CustomOriginDnsName ) {
data.CustomOrigin.DNSName = args.CustomOriginDnsName;
}
if ( args.CustomOriginHttpPort ) {
data.CustomOrigin.HTTPPort = args.CustomOriginHttpPort;
}
if ( args.CustomOriginHttpsPort ) {
data.CustomOrigin.HTTPSPort = args.CustomOriginHttpsPort;
}
if ( args.CustomOriginOriginProtocolPolicy ) {
data.CustomOrigin.OriginProtocolPolicy = args.CustomOriginOriginProtocolPolicy;
}
}
data.CallerReference = args.CallerReference;
if ( args.Cname ) {
data.CNAME = args.Cname;
}
if ( args.Comment ) {
data.Comment = args.Comment;
}
if ( args.DefaultRootObject ) {
data.DefaultRootObject = args.DefaultRootObject;
}
data.Enabled = args.Enabled;
if ( args.PriceClass ) {
data.PriceClass = args.PriceClass;
}
if ( args.LoggingBucket ) {
data.Logging = {};
data.Logging.Bucket = args.LoggingBucket;
if ( args.LoggingPrefix ) {
data.Logging.Prefix = args.LoggingPrefix;
}
}
if ( args.TrustedSignersSelf || args.TrustedSignersAwsAccountNumber ) {
data.TrustedSigners = {};
if ( args.TrustedSignersSelf ) {
data.TrustedSigners.Self = '';
}
if ( args.TrustedSignersAwsAccountNumber ) {
data.TrustedSigners.AwsAccountNumber = args.TrustedSignersAwsAccountNumber;
}
}
if ( args.RequiredProtocolsProtocol ) {
data.RequiredProtocols = {};
data.RequiredProtocols.Protocol = args.RequiredProtocolsProtocol;
}
return data2xml('DistributionConfig', data);
}
function bodyStreamingDistributionConfig(options, args) {
// create the XML
var data = {
'@' : { 'xmlns' : 'http://cloudfront.amazonaws.com/doc/2010-11-01/' },
};
if ( args.S3OriginDnsName ) {
data.S3Origin = {};
data.S3Origin.DNSName = args.S3OriginDnsName;
if ( args.S3OriginOriginAccessIdentity ) {
data.S3Origin.OriginAccessIdentity = args.S3OriginOriginAccessIdentity;
}
}
data.CallerReference = args.CallerReference;
if ( args.Cname ) {
data.CNAME = args.Cname;
}
if ( args.Comment ) {
data.Comment = args.Comment;
}
data.Enabled = args.Enabled;
if ( args.PriceClass ) {
data.PriceClass = args.PriceClass;
}
if ( args.LoggingBucket ) {
data.Logging = {};
data.Logging.Bucket = args.LoggingBucket;
if ( args.LoggingPrefix ) {
data.Logging.Prefix = args.LoggingPrefix;
}
}
if ( args.TrustedSignersSelf || args.TrustedSignersAwsAccountNumber ) {
data.TrustedSigners = {};
if ( args.TrustedSignersSelf ) {
data.TrustedSigners.Self = '';
}
if ( args.TrustedSignersAwsAccountNumber ) {
data.TrustedSigners.AwsAccountNumber = args.TrustedSignersAwsAccountNumber;
}
}
return data2xml('StreamingDistributionConfig', data);
}
function bodyOaiConfig(options, args) {
var self = this;
var data = {
'@' : { xmlns : 'http://cloudfront.amazonaws.com/doc/2010-11-01/', },
CallerReference : args.CallerReference,
};
if ( args.Comments ) {
data.Comments = args.Comments;
}
return data2xml('CloudFrontOriginAccessIdentityConfig', data);
}
// --------------------------------------------------------------------------------------------------------------------
module.exports = {
// Operations on Distributions
CreateDistribution : {
url : 'http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/CreateDistribution.html',
method : 'POST',
path : pathDistribution,
args : {
// S3Origin Elements
DnsName : {
type : 'special',
required : false,
},
OriginAccessIdentity : {
type : 'special',
required : false,
},
// CustomOrigin elements
CustomOriginDnsName : {
type : 'special',
required : false,
},
CustomOriginHttpPort : {
type : 'special',
required : false,
},
CustomOriginHttpsPort : {
type : 'special',
required : false,
},
CustomOriginOriginProtocolPolicy : {
type : 'special',
required : false,
},
// other top level elements
CallerReference : {
type : 'special',
required : true,
},
Cname : {
type : 'special',
required : false,
},
Comment : {
type : 'special',
required : false,
},
Enabled : {
type : 'special',
required : true,
},
DefaultRootObject : {
type : 'special',
required : true,
},
// Logging Elements
LoggingBucket : {
type : 'special',
required : false,
},
LoggingPrefix : {
type : 'special',
required : false,
},
// TrustedSigners Elements
TrustedSignersSelf : {
type : 'special',
required : false,
},
TrustedSignersAwsAccountNumber : {
type : 'special',
required : false,
},
RequiredProtocols : {
type : 'special',
required : false,
},
},
body : bodyDistributionConfig,
statusCode: 201,
},
ListDistributions : {
url : 'http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/ListDistributions.html',
path : pathDistribution,
args : {
Marker : {
required : false,
type : 'param',
},
MaxItems : {
required : false,
type : 'param',
},
},
},
GetDistribution : {
url : 'http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/GetDistribution.html',
path : pathDistributionId,
args : {
DistributionId : {
required : true,
type : 'special',
},
},
},
GetDistributionConfig : {
url : 'http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/GetConfig.html',
path : pathDistributionIdConfig,
args : {
DistributionId : {
required : true,
type : 'special',
},
},
},
PutDistributionConfig : {
url : 'http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/PutConfig.html',
method : 'PUT',
path : pathDistributionIdConfig,
args : {
DistributionId : {
required : true,
type : 'special',
},
IfMatch : {
name : 'If-Match',
required : true,
type : 'header'
},
// S3Origin Elements
DnsName : {
type : 'special',
required : false,
},
OriginAccessIdentity : {
type : 'special',
required : false,
},
// CustomOrigin elements
CustomOriginDnsName : {
type : 'special',
required : false,
},
CustomOriginHttpPort : {
type : 'special',
required : false,
},
CustomOriginHttpsPort : {
type : 'special',
required : false,
},
CustomOriginOriginProtocolPolicy : {
type : 'special',
required : false,
},
// other top level elements
CallerReference : {
type : 'special',
required : true,
},
Cname : {
type : 'special',
required : false,
},
Comment : {
type : 'special',
required : false,
},
Enabled : {
type : 'special',
required : true,
},
PriceClass : {
type : 'special',
required : false,
},
DefaultRootObject : {
type : 'special',
required : true,
},
// Logging Elements
LoggingBucket : {
type : 'special',
required : false,
},
LoggingPrefix : {
type : 'special',
required : false,
},
// TrustedSigners Elements
TrustedSignersSelf : {
type : 'special',
required : false,
},
TrustedSignersAwsAccountNumber : {
type : 'special',
required : false,
},
RequiredProtocols : {
type : 'special',
required : false,
},
},
body : bodyDistributionConfig,
},
DeleteDistribution : {
url : 'http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/DeleteDistribution.html',
method : 'DELETE',
path : pathDistributionId,
args : {
DistributionId : {
required : true,
type : 'special',
},
IfMatch : {
name : 'If-Match',
required : true,
type : 'header'
},
},
statusCode : 204,
},
// Operations on Streaming Distributions
CreateStreamingDistribution : {
url : 'http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/CreateStreamingDistribution.html',
method : 'POST',
path : pathStreamingDistribution,
args : {
// S3Origin Elements
S3OriginDnsName : {
type : 'special',
required : false,
},
S3OriginOriginAccessIdentity : {
type : 'special',
required : false,
},
// other top level elements
CallerReference : {
type : 'special',
required : true,
},
Cname : {
type : 'special',
required : false,
},
Comment : {
type : 'special',
required : false,
},
Enabled : {
type : 'special',
required : true,
},
PriceClass : {
type : 'special',
required : false,
},
// Logging Elements
LoggingBucket : {
type : 'special',
required : false,
},
LoggingPrefix : {
type : 'special',
required : false,
},
// TrustedSigners Elements
TrustedSignersSelf : {
type : 'special',
required : false,
},
TrustedSignersAwsAccountNumber : {
type : 'special',
required : false,
},
},
body : bodyStreamingDistributionConfig,
},
ListStreamingDistributions : {
url : 'http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/ListStreamingDistributions.html',
path : pathStreamingDistribution,
args : {
Marker : {
required : false,
type : 'param',
},
MaxItems : {
required : false,
type : 'param',
},
},
},
GetStreamingDistribution : {
url : 'http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/GetStreamingDistribution.html',
path : pathStreamingDistributionId,
args : {
DistributionId : {
required : true,
type : 'special',
},
},
},
GetStreamingDistributionConfig : {
url : 'http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/GetStreamingDistConfig.html',
path : pathStreamingDistributionIdConfig,
args : {
DistributionId : {
required : true,
type : 'special',
},
},
},
PutStreamingDistributionConfig : {
url : 'http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/PutStreamingDistConfig.html',
method : 'PUT',
path : pathStreamingDistributionIdConfig,
args : {
DistributionId : {
required : true,
type : 'special',
},
IfMatch : {
name : 'If-Match',
required : true,
type : 'header'
},
// S3Origin Elements
DnsName : {
type : 'special',
required : false,
},
OriginAccessIdentity : {
type : 'special',
required : false,
},
// other top level elements
CallerReference : {
type : 'special',
required : true,
},
Cname : {
type : 'special',
required : false,
},
Comment : {
type : 'special',
required : false,
},
Enabled : {
type : 'special',
required : true,
},
// Logging Elements
LoggingBucket : {
type : 'special',
required : false,
},
LoggingPrefix : {
type : 'special',
required : false,
},
// TrustedSigners Elements
TrustedSignersSelf : {
type : 'special',
required : false,
},
TrustedSignersAwsAccountNumber : {
type : 'special',
required : false,
},
},
body : bodyStreamingDistributionConfig,
},
DeleteStreamingDistribution : {
url : 'http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/DeleteStreamingDistribution.html',
method : 'DELETE',
path : pathStreamingDistributionId,
args : {
DistributionId : {
required : true,
type : 'special',
},
IfMatch : {
name : 'If-Match',
required : true,
type : 'header'
},
},
statusCode : 204,
},
// Operations on Origin Access Identities
CreateOai : {
url : 'http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/CreateOAI.html',
method : 'POST',
path : pathOai,
args : {
CallerReference : {
required : true,
type : 'special',
},
Comment : {
required : false,
type : 'special',
},
},
body : bodyOaiConfig,
statusCode: 201,
},
ListOais : {
url : 'http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/ListOAIs.html',
path : pathOai,
args : {
Marker : {
required : false,
type : 'param',
},
MaxItems : {
required : false,
type : 'param',
},
},
},
GetOai : {
url : 'http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/GetOAI.html',
path : pathOaiId,
args : {
OriginAccessId : {
required : true,
type : 'special',
},
},
},
GetOaiConfig : {
url : 'http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/GetOAIConfig.html',
path : pathOaiIdConfig,
args : {
OriginAccessId : {
required : true,
type : 'special',
},
},
},
PutOaiConfig : {
url : 'http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/PutOAIConfig.html',
method : 'PUT',
path : pathOai,
args : {
OriginAccessId : {
required : true,
type : 'special',
},
CallerReference : {
required : true,
type : 'special',
},
Comment : {
required : false,
type : 'special',
},
},
body : bodyOaiConfig,
},
DeleteOai : {
url : 'http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/DeleteOAI.html',
method : 'DELETE',
path : pathOaiId,
args : {
OriginAccessId : {
required : true,
type : 'special',
},
IfMatch : {
name : 'If-Match',
required : true,
type : 'header'
},
},
statusCode : 204,
},
// Operations on Invalidations
CreateInvalidation : {
url : 'http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/CreateInvalidation.html',
method : 'POST',
path : pathDistributionInvalidation,
args : {
DistributionId : {
required : true,
type : 'special',
},
Path : {
required : true,
type : 'special',
},
CallerReference : {
required : false,
type : 'special',
},
},
body : function(options, args) {
var self = this;
var data = {
Path : args.Path,
};
if ( args.CallerReference ) {
data.CallerReference = args.CallerReference;
}
return data2xml('InvalidationBatch', data);
},
},
ListInvalidations : {
url : 'http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/ListInvalidation.html',
path : pathDistributionInvalidation,
args : {
DistributionId : {
required : true,
type : 'special',
},
Marker : {
required : false,
type : 'param',
},
MaxItems : {
required : false,
type : 'param',
},
},
},
GetInvalidation : {
url : 'http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/GetInvalidation.html',
path : pathDistributionInvalidationId,
args : {
DistributionId : {
required : true,
type : 'special',
},
Marker : {
required : false,
type : 'param',
},
MaxItems : {
required : false,
type : 'param',
},
},
},
};
// --------------------------------------------------------------------------------------------------------------------
| chilts/awssum-amazon-cloudfront | config.js | JavaScript | mit | 23,102 |
var GlobezGame = GlobezGame || {};
GlobezGame.Boot = function() {};
GlobezGame.Boot.prototype = {
preload: function() {
console.log("%cStarting Fish Vs Mines", "color:white; background:red");
this.load.image("loading", "assets/sprites/loading.png");
this.load.image("logo", "assets/sprites/logo.png");
},
create: function() {
this.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
this.scale.pageAlignHorizontally = true;
this.scale.pageAlignVertically = true;
// this.scale.setScreenSize(true);
this.physics.startSystem(Phaser.Physics.ARCADE);
this.state.start("Preload");
}
}
var GlobezGame = GlobezGame || {};
GlobezGame.Preload = function() {};
GlobezGame.Preload.prototype = {
preload: function() {
console.log("%cPreloading assets", "color:white; background:red")
var loadingBar = this.add.sprite(160, 340, "loading");
loadingBar.anchor.setTo(0.5, 0.5);
this.load.setPreloadSprite(loadingBar);
var logo = this.add.sprite(160, 240, "logo");
logo.anchor.setTo(0.5, 0.5);
this.load.image("background", "assets/sprites/background.png");
this.load.image("playbutton", "assets/sprites/playbutton.png");
this.load.image("gametitle_sealife", "assets/sprites/gametitle_sealife.png");
this.load.image("gametitle_vs", "assets/sprites/gametitle_vs.png");
this.load.image("gametitle_mines", "assets/sprites/gametitle_mines.png");
this.load.image("blackfade", "assets/sprites/blackfade.png");
this.load.image("bubble", "assets/sprites/bubble.png");
},
create: function() {
this.state.start("GameTitle");
}
}
var GlobezGame = GlobezGame || {};
GlobezGame.GameTitle = function() {
startGame = false;
};
GlobezGame.GameTitle.prototype = {
create: function() {
console.log("%cStarting game title", "color:white; background:red");
this.add.image(0, 0, "background");
//
var bubblesEmitter = this.add.emitter(160, 500, 50);
bubblesEmitter.makeParticles("bubble");
bubblesEmitter.maxParticleScale = 0.6;
bubblesEmitter.minParticleScale = 0.2;
bubblesEmitter.setYSpeed(-30, -40);
bubblesEmitter.setXSpeed(-3, 3);
bubblesEmitter.gravity = 0;
bubblesEmitter.width = 320;
bubblesEmitter.minRotation = 0;
bubblesEmitter.maxRotation = 40;
bubblesEmitter.flow(15000, 2000)
//
var gameTitleSeaLife = this.add.image(160, 70, "gametitle_sealife");
gameTitleSeaLife.anchor.setTo(0.5, 0.5);
gameTitleSeaLife.angle = (2 + Math.random() * 5) * (Math.random() > 0.5 ? 1 : -1);
var seaLifeTween = this.add.tween(gameTitleSeaLife);
seaLifeTween.to({
angle: -gameTitleSeaLife.angle
}, 5000 + Math.random() * 5000, Phaser.Easing.Linear.None, true, 0, 1000, true);
//
var gameTitleVs = this.add.image(190, 120, "gametitle_vs");
gameTitleVs.anchor.setTo(0.5, 0.5);
gameTitleVs.angle = (2 + Math.random() * 5) * (Math.random() > 0.5 ? 1 : -1);
var vsTween = this.add.tween(gameTitleVs);
vsTween.to({
angle: -gameTitleVs.angle
}, 5000 + Math.random() * 5000, Phaser.Easing.Linear.None, true, 0, 1000, true);
//
var gameTitleMines = this.add.image(160, 160, "gametitle_mines");
gameTitleMines.anchor.setTo(0.5, 0.5);
gameTitleMines.angle = (2 + Math.random() * 5) * (Math.random() > 0.5 ? 1 : -1);
var minesTween = this.add.tween(gameTitleMines);
minesTween.to({
angle: -gameTitleMines.angle
}, 5000 + Math.random() * 5000, Phaser.Easing.Linear.None, true, 0, 1000, true);
//
var playButton = this.add.button(160, 320, "playbutton", this.playTheGame, this)
playButton.anchor.setTo(0.5, 0.5);
playButton.angle = (2 + Math.random() * 5) * (Math.random() > 0.5 ? 1 : -1);
var playTween = this.add.tween(playButton);
playTween.to({
angle: -playButton.angle
}, 5000 + Math.random() * 5000, Phaser.Easing.Linear.None, true, 0, 1000, true);
//
var blackFade = this.add.sprite(0, 0, "blackfade");
var fadeTween = this.add.tween(blackFade);
fadeTween.to({
alpha: 0
}, 2000, Phaser.Easing.Cubic.Out, true);
},
playTheGame: function() {
if (!startGame) {
startGame = true
alert("Start the game!!");
}
}
}
var GlobezGame = GlobezGame || {};
GlobezGame.gameOptions = {
gameWidth: 320,
gameHeight: 480
}
GlobezGame.game = new Phaser.Game(GlobezGame.gameOptions.gameWidth, GlobezGame.gameOptions.gameHeight, Phaser.CANVAS, "");
GlobezGame.game.state.add("Boot", GlobezGame.Boot);
GlobezGame.game.state.add("Preload", GlobezGame.Preload);
GlobezGame.game.state.add("GameTitle", GlobezGame.GameTitle);
GlobezGame.game.state.start("Boot");
| jojoee/phaser-examples | games/sea-life-vs-mines/js/game.js | JavaScript | mit | 4,643 |
$("nav span").mouseenter(function(){$("nav").removeClass("closed")}),$("nav").mouseleave(function(){$("nav").addClass("closed")}),$("nav a").click(function(){var o=$(this).parent().index();console.log(o),$("html,body").animate({scrollTop:$(".section-container > section").eq(o).offset().top},500)}),$(window).scroll(function(){var o=$(window).scrollTop()+window.innerHeight,e=$(".keywords").offset().top,n=$("footer").offset().top;console.log(o-e),e>o||o>n?$(".arrow").removeClass("black"):$(".arrow").addClass("black")}),jQuery(document).ready(function(o){o(window).load(function(){o(".preloader").fadeOut("slow",function(){o(this).remove()})})}),function(){for(var o,e=function(){},n=["assert","clear","count","debug","dir","dirxml","error","exception","group","groupCollapsed","groupEnd","info","log","markTimeline","profile","profileEnd","table","time","timeEnd","timeline","timelineEnd","timeStamp","trace","warn"],i=n.length,t=window.console=window.console||{};i--;)o=n[i],t[o]||(t[o]=e)}(); | noahjl1/illicit-design | dist/js/all.min.js | JavaScript | mit | 997 |
'use strict';
describe('nothing', () => {
it('should do nothing', () => {
//
});
});
| sthuck/quick-2fa | src/index.spec.js | JavaScript | mit | 94 |
import { setData } from '@progress/kendo-angular-intl';
setData({
name: "pt-CH",
identity: {
language: "pt",
territory: "CH"
},
territory: "CH",
numbers: {
symbols: {
decimal: ",",
group: " ",
list: ";",
percentSign: "%",
plusSign: "+",
minusSign: "-",
exponential: "E",
superscriptingExponent: "×",
perMille: "‰",
infinity: "∞",
nan: "NaN",
timeSeparator: ":"
},
decimal: {
patterns: [
"n"
],
groupSize: [
3
]
},
scientific: {
patterns: [
"nEn"
],
groupSize: []
},
percent: {
patterns: [
"n%"
],
groupSize: [
3
]
},
currency: {
patterns: [
"n $"
],
groupSize: [
3
],
"unitPattern-count-one": "n $",
"unitPattern-count-other": "n $"
},
accounting: {
patterns: [
"n $",
"(n $)"
],
groupSize: [
3
]
},
currencies: {
ADP: {
displayName: "Peseta de Andorra",
"displayName-count-one": "Peseta de Andorra",
"displayName-count-other": "Pesetas de Andorra",
symbol: "ADP"
},
AED: {
displayName: "Dirham dos Emirados Árabes Unidos",
"displayName-count-one": "Dirham dos Emirados Árabes Unidos",
"displayName-count-other": "Dirhams dos Emirados Árabes Unidos",
symbol: "AED"
},
AFA: {
displayName: "Afeghani (1927–2002)",
"displayName-count-one": "Afegane do Afeganistão (AFA)",
"displayName-count-other": "Afeganes do Afeganistão (AFA)",
symbol: "AFA"
},
AFN: {
displayName: "Afegani do Afeganistão",
"displayName-count-one": "Afegani do Afeganistão",
"displayName-count-other": "Afeganis do Afeganistão",
symbol: "AFN"
},
ALK: {
displayName: "Lek Albanês (1946–1965)",
"displayName-count-one": "Lek Albanês (1946–1965)",
"displayName-count-other": "Leks Albaneses (1946–1965)"
},
ALL: {
displayName: "Lek albanês",
"displayName-count-one": "Lek albanês",
"displayName-count-other": "Leks albaneses",
symbol: "ALL"
},
AMD: {
displayName: "Dram arménio",
"displayName-count-one": "Dram arménio",
"displayName-count-other": "Drams arménios",
symbol: "AMD"
},
ANG: {
displayName: "Florim das Antilhas Holandesas",
"displayName-count-one": "Florim das Antilhas Holandesas",
"displayName-count-other": "Florins das Antilhas Holandesas",
symbol: "ANG"
},
AOA: {
displayName: "Kwanza angolano",
"displayName-count-one": "Kwanza angolano",
"displayName-count-other": "Kwanzas angolanos",
symbol: "AOA",
"symbol-alt-narrow": "Kz"
},
AOK: {
displayName: "Cuanza angolano (1977–1990)",
"displayName-count-one": "Kwanza angolano (AOK)",
"displayName-count-other": "Kwanzas angolanos (AOK)",
symbol: "AOK"
},
AON: {
displayName: "Novo cuanza angolano (1990–2000)",
"displayName-count-one": "Novo kwanza angolano (AON)",
"displayName-count-other": "Novos kwanzas angolanos (AON)",
symbol: "AON"
},
AOR: {
displayName: "Cuanza angolano reajustado (1995–1999)",
"displayName-count-one": "Kwanza angolano reajustado (AOR)",
"displayName-count-other": "Kwanzas angolanos reajustados (AOR)",
symbol: "AOR"
},
ARA: {
displayName: "Austral argentino",
"displayName-count-one": "Austral argentino",
"displayName-count-other": "Austrais argentinos",
symbol: "ARA"
},
ARL: {
displayName: "Peso lei argentino (1970–1983)",
"displayName-count-one": "Peso lei argentino (1970–1983)",
"displayName-count-other": "Pesos lei argentinos (1970–1983)",
symbol: "ARL"
},
ARM: {
displayName: "Peso argentino (1881–1970)",
"displayName-count-one": "Peso argentino (1881–1970)",
"displayName-count-other": "Pesos argentinos (1881–1970)",
symbol: "ARM"
},
ARP: {
displayName: "Peso argentino (1983–1985)",
"displayName-count-one": "Peso argentino (1983–1985)",
"displayName-count-other": "Pesos argentinos (1983–1985)",
symbol: "ARP"
},
ARS: {
displayName: "Peso argentino",
"displayName-count-one": "Peso argentino",
"displayName-count-other": "Pesos argentinos",
symbol: "ARS",
"symbol-alt-narrow": "$"
},
ATS: {
displayName: "Xelim austríaco",
"displayName-count-one": "Schilling australiano",
"displayName-count-other": "Schillings australianos",
symbol: "ATS"
},
AUD: {
displayName: "Dólar australiano",
"displayName-count-one": "Dólar australiano",
"displayName-count-other": "Dólares australianos",
symbol: "AU$",
"symbol-alt-narrow": "$"
},
AWG: {
displayName: "Florim de Aruba",
"displayName-count-one": "Florim de Aruba",
"displayName-count-other": "Florins de Aruba",
symbol: "AWG"
},
AZM: {
displayName: "Manat azerbaijano (1993–2006)",
"displayName-count-one": "Manat do Azeibaijão (1993–2006)",
"displayName-count-other": "Manats do Azeibaijão (1993–2006)",
symbol: "AZM"
},
AZN: {
displayName: "Manat do Azerbaijão",
"displayName-count-one": "Manat do Azerbaijão",
"displayName-count-other": "Manats do Azerbaijão",
symbol: "AZN"
},
BAD: {
displayName: "Dinar da Bósnia-Herzegóvina",
"displayName-count-one": "Dinar da Bósnia Herzegovina",
"displayName-count-other": "Dinares da Bósnia Herzegovina",
symbol: "BAD"
},
BAM: {
displayName: "Marco bósnio-herzegóvino conversível",
"displayName-count-one": "Marco bósnio-herzegóvino conversível",
"displayName-count-other": "Marcos bósnio-herzegóvinos conversíveis",
symbol: "BAM",
"symbol-alt-narrow": "KM"
},
BAN: {
displayName: "Novo dinar da Bósnia-Herzegovina (1994–1997)",
"displayName-count-one": "Novo dinar da Bósnia-Herzegovina",
"displayName-count-other": "Novos dinares da Bósnia-Herzegovina",
symbol: "BAN"
},
BBD: {
displayName: "Dólar barbadense",
"displayName-count-one": "Dólar barbadense",
"displayName-count-other": "Dólares barbadenses",
symbol: "BBD",
"symbol-alt-narrow": "$"
},
BDT: {
displayName: "Taka de Bangladesh",
"displayName-count-one": "Taka de Bangladesh",
"displayName-count-other": "Takas de Bangladesh",
symbol: "BDT",
"symbol-alt-narrow": "৳"
},
BEC: {
displayName: "Franco belga (convertível)",
"displayName-count-one": "Franco belga (conversível)",
"displayName-count-other": "Francos belgas (conversíveis)",
symbol: "BEC"
},
BEF: {
displayName: "Franco belga",
"displayName-count-one": "Franco belga",
"displayName-count-other": "Francos belgas",
symbol: "BEF"
},
BEL: {
displayName: "Franco belga (financeiro)",
"displayName-count-one": "Franco belga (financeiro)",
"displayName-count-other": "Francos belgas (financeiros)",
symbol: "BEL"
},
BGL: {
displayName: "Lev forte búlgaro",
"displayName-count-one": "Lev forte búlgaro",
"displayName-count-other": "Levs fortes búlgaros",
symbol: "BGL"
},
BGM: {
displayName: "Lev socialista búlgaro",
"displayName-count-one": "Lev socialista búlgaro",
"displayName-count-other": "Levs socialistas búlgaros",
symbol: "BGM"
},
BGN: {
displayName: "Lev búlgaro",
"displayName-count-one": "Lev búlgaro",
"displayName-count-other": "Levs búlgaros",
symbol: "BGN"
},
BGO: {
displayName: "Lev búlgaro (1879–1952)",
"displayName-count-one": "Lev búlgaro (1879–1952)",
"displayName-count-other": "Levs búlgaros (1879–1952)",
symbol: "BGO"
},
BHD: {
displayName: "Dinar baremita",
"displayName-count-one": "Dinar baremita",
"displayName-count-other": "Dinares baremitas",
symbol: "BHD"
},
BIF: {
displayName: "Franco burundiano",
"displayName-count-one": "Franco burundiano",
"displayName-count-other": "Francos burundianos",
symbol: "BIF"
},
BMD: {
displayName: "Dólar bermudense",
"displayName-count-one": "Dólar bermudense",
"displayName-count-other": "Dólares bermudenses",
symbol: "BMD",
"symbol-alt-narrow": "$"
},
BND: {
displayName: "Dólar bruneíno",
"displayName-count-one": "Dólar bruneíno",
"displayName-count-other": "Dólares bruneínos",
symbol: "BND",
"symbol-alt-narrow": "$"
},
BOB: {
displayName: "Boliviano",
"displayName-count-one": "Boliviano",
"displayName-count-other": "Bolivianos",
symbol: "BOB",
"symbol-alt-narrow": "Bs"
},
BOL: {
displayName: "Boliviano (1863–1963)",
"displayName-count-one": "Boliviano (1863–1963)",
"displayName-count-other": "Bolivianos (1863–1963)",
symbol: "BOL"
},
BOP: {
displayName: "Peso boliviano",
"displayName-count-one": "Peso boliviano",
"displayName-count-other": "Pesos bolivianos",
symbol: "BOP"
},
BOV: {
displayName: "Mvdol boliviano",
"displayName-count-one": "Mvdol boliviano",
"displayName-count-other": "Mvdols bolivianos",
symbol: "BOV"
},
BRB: {
displayName: "Cruzeiro novo brasileiro (1967–1986)",
"displayName-count-one": "Cruzeiro novo brasileiro (BRB)",
"displayName-count-other": "Cruzeiros novos brasileiros (BRB)",
symbol: "BRB"
},
BRC: {
displayName: "Cruzado brasileiro (1986–1989)",
"displayName-count-one": "Cruzado brasileiro",
"displayName-count-other": "Cruzados brasileiros",
symbol: "BRC"
},
BRE: {
displayName: "Cruzeiro brasileiro (1990–1993)",
"displayName-count-one": "Cruzeiro brasileiro (BRE)",
"displayName-count-other": "Cruzeiros brasileiros (BRE)",
symbol: "BRE"
},
BRL: {
displayName: "Real brasileiro",
"displayName-count-one": "Real brasileiro",
"displayName-count-other": "Reais brasileiros",
symbol: "R$",
"symbol-alt-narrow": "R$"
},
BRN: {
displayName: "Cruzado novo brasileiro (1989–1990)",
"displayName-count-one": "Cruzado novo brasileiro",
"displayName-count-other": "Cruzados novos brasileiros",
symbol: "BRN"
},
BRR: {
displayName: "Cruzeiro brasileiro (1993–1994)",
"displayName-count-one": "Cruzeiro brasileiro",
"displayName-count-other": "Cruzeiros brasileiros",
symbol: "BRR"
},
BRZ: {
displayName: "Cruzeiro brasileiro (1942–1967)",
"displayName-count-one": "Cruzeiro brasileiro antigo",
"displayName-count-other": "Cruzeiros brasileiros antigos",
symbol: "BRZ"
},
BSD: {
displayName: "Dólar das Bahamas",
"displayName-count-one": "Dólar das Bahamas",
"displayName-count-other": "Dólares das Bahamas",
symbol: "BSD",
"symbol-alt-narrow": "$"
},
BTN: {
displayName: "Ngultrum do Butão",
"displayName-count-one": "Ngultrum do Butão",
"displayName-count-other": "Ngultruns do Butão",
symbol: "BTN"
},
BUK: {
displayName: "Kyat birmanês",
"displayName-count-one": "Kyat burmês",
"displayName-count-other": "Kyats burmeses",
symbol: "BUK"
},
BWP: {
displayName: "Pula de Botswana",
"displayName-count-one": "Pula de Botswana",
"displayName-count-other": "Pulas de Botswana",
symbol: "BWP",
"symbol-alt-narrow": "P"
},
BYB: {
displayName: "Rublo novo bielorusso (1994–1999)",
"displayName-count-one": "Novo rublo bielorusso (BYB)",
"displayName-count-other": "Novos rublos bielorussos (BYB)",
symbol: "BYB"
},
BYN: {
displayName: "Rublo bielorrusso",
"displayName-count-one": "Rublo bielorrusso",
"displayName-count-other": "Rublos bielorrussos",
symbol: "BYN",
"symbol-alt-narrow": "р."
},
BYR: {
displayName: "Rublo bielorrusso (2000–2016)",
"displayName-count-one": "Rublo bielorrusso (2000–2016)",
"displayName-count-other": "Rublos bielorrussos (2000–2016)",
symbol: "BYR"
},
BZD: {
displayName: "Dólar belizense",
"displayName-count-one": "Dólar belizense",
"displayName-count-other": "Dólares belizenses",
symbol: "BZD",
"symbol-alt-narrow": "$"
},
CAD: {
displayName: "Dólar canadiano",
"displayName-count-one": "Dólar canadiano",
"displayName-count-other": "Dólares canadianos",
symbol: "CA$",
"symbol-alt-narrow": "$"
},
CDF: {
displayName: "Franco congolês",
"displayName-count-one": "Franco congolês",
"displayName-count-other": "Francos congoleses",
symbol: "CDF"
},
CHE: {
displayName: "Euro WIR",
"displayName-count-one": "Euro WIR",
"displayName-count-other": "Euros WIR",
symbol: "CHE"
},
CHF: {
displayName: "Franco suíço",
"displayName-count-one": "Franco suíço",
"displayName-count-other": "Francos suíços",
symbol: "CHF"
},
CHW: {
displayName: "Franco WIR",
"displayName-count-one": "Franco WIR",
"displayName-count-other": "Francos WIR",
symbol: "CHW"
},
CLE: {
displayName: "Escudo chileno",
"displayName-count-one": "Escudo chileno",
"displayName-count-other": "Escudos chilenos",
symbol: "CLE"
},
CLF: {
displayName: "Unidades de Fomento chilenas",
"displayName-count-one": "Unidade de fomento chilena",
"displayName-count-other": "Unidades de fomento chilenas",
symbol: "CLF"
},
CLP: {
displayName: "Peso chileno",
"displayName-count-one": "Peso chileno",
"displayName-count-other": "Pesos chilenos",
symbol: "CLP",
"symbol-alt-narrow": "$"
},
CNX: {
displayName: "Dólar do Banco Popular da China",
"displayName-count-one": "Dólar do Banco Popular da China",
"displayName-count-other": "Dólares do Banco Popular da China"
},
CNY: {
displayName: "Yuan chinês",
"displayName-count-one": "Yuan chinês",
"displayName-count-other": "Yuans chineses",
symbol: "CN¥",
"symbol-alt-narrow": "¥"
},
COP: {
displayName: "Peso colombiano",
"displayName-count-one": "Peso colombiano",
"displayName-count-other": "Pesos colombianos",
symbol: "COP",
"symbol-alt-narrow": "$"
},
COU: {
displayName: "Unidade de Valor Real",
"displayName-count-one": "Unidade de valor real",
"displayName-count-other": "Unidades de valor real",
symbol: "COU"
},
CRC: {
displayName: "Colon costa-riquenho",
"displayName-count-one": "Colon costa-riquenho",
"displayName-count-other": "Colons costa-riquenhos",
symbol: "CRC",
"symbol-alt-narrow": "₡"
},
CSD: {
displayName: "Dinar sérvio (2002–2006)",
"displayName-count-one": "Dinar antigo da Sérvia",
"displayName-count-other": "Dinares antigos da Sérvia",
symbol: "CSD"
},
CSK: {
displayName: "Coroa Forte checoslovaca",
"displayName-count-one": "Coroa forte tchecoslovaca",
"displayName-count-other": "Coroas fortes tchecoslovacas",
symbol: "CSK"
},
CUC: {
displayName: "Peso cubano conversível",
"displayName-count-one": "Peso cubano conversível",
"displayName-count-other": "Pesos cubanos conversíveis",
symbol: "CUC",
"symbol-alt-narrow": "$"
},
CUP: {
displayName: "Peso cubano",
"displayName-count-one": "Peso cubano",
"displayName-count-other": "Pesos cubanos",
symbol: "CUP",
"symbol-alt-narrow": "$"
},
CVE: {
displayName: "Escudo cabo-verdiano",
"displayName-count-one": "Escudo cabo-verdiano",
"displayName-count-other": "Escudos cabo-verdianos",
symbol: "CVE"
},
CYP: {
displayName: "Libra de Chipre",
"displayName-count-one": "Libra cipriota",
"displayName-count-other": "Libras cipriotas",
symbol: "CYP"
},
CZK: {
displayName: "Coroa checa",
"displayName-count-one": "Coroa checa",
"displayName-count-other": "Coroas checas",
symbol: "CZK",
"symbol-alt-narrow": "Kč"
},
DDM: {
displayName: "Ostmark da Alemanha Oriental",
"displayName-count-one": "Marco da Alemanha Oriental",
"displayName-count-other": "Marcos da Alemanha Oriental",
symbol: "DDM"
},
DEM: {
displayName: "Marco alemão",
"displayName-count-one": "Marco alemão",
"displayName-count-other": "Marcos alemães",
symbol: "DEM"
},
DJF: {
displayName: "Franco jibutiano",
"displayName-count-one": "Franco jibutiano",
"displayName-count-other": "Francos jibutianos",
symbol: "DJF"
},
DKK: {
displayName: "Coroa dinamarquesa",
"displayName-count-one": "Coroa dinamarquesa",
"displayName-count-other": "Coroas dinamarquesas",
symbol: "DKK",
"symbol-alt-narrow": "kr"
},
DOP: {
displayName: "Peso dominicano",
"displayName-count-one": "Peso dominicano",
"displayName-count-other": "Pesos dominicanos",
symbol: "DOP",
"symbol-alt-narrow": "$"
},
DZD: {
displayName: "Dinar argelino",
"displayName-count-one": "Dinar argelino",
"displayName-count-other": "Dinares argelinos",
symbol: "DZD"
},
ECS: {
displayName: "Sucre equatoriano",
"displayName-count-one": "Sucre equatoriano",
"displayName-count-other": "Sucres equatorianos",
symbol: "ECS"
},
ECV: {
displayName: "Unidad de Valor Constante (UVC) do Equador",
"displayName-count-one": "Unidade de valor constante equatoriana (UVC)",
"displayName-count-other": "Unidades de valor constante equatorianas (UVC)",
symbol: "ECV"
},
EEK: {
displayName: "Coroa estoniana",
"displayName-count-one": "Coroa estoniana",
"displayName-count-other": "Coroas estonianas",
symbol: "EEK"
},
EGP: {
displayName: "Libra egípcia",
"displayName-count-one": "Libra egípcia",
"displayName-count-other": "Libras egípcias",
symbol: "EGP",
"symbol-alt-narrow": "E£"
},
ERN: {
displayName: "Nakfa da Eritreia",
"displayName-count-one": "Nakfa da Eritreia",
"displayName-count-other": "Nakfas da Eritreia",
symbol: "ERN"
},
ESA: {
displayName: "Peseta espanhola (conta A)",
"displayName-count-one": "Peseta espanhola (conta A)",
"displayName-count-other": "Pesetas espanholas (conta A)",
symbol: "ESA"
},
ESB: {
displayName: "Peseta espanhola (conta conversível)",
"displayName-count-one": "Peseta espanhola (conta conversível)",
"displayName-count-other": "Pesetas espanholas (conta conversível)",
symbol: "ESB"
},
ESP: {
displayName: "Peseta espanhola",
"displayName-count-one": "Peseta espanhola",
"displayName-count-other": "Pesetas espanholas",
symbol: "ESP",
"symbol-alt-narrow": "₧"
},
ETB: {
displayName: "Birr etíope",
"displayName-count-one": "Birr etíope",
"displayName-count-other": "Birrs etíopes",
symbol: "ETB"
},
EUR: {
displayName: "Euro",
"displayName-count-one": "Euro",
"displayName-count-other": "Euros",
symbol: "€",
"symbol-alt-narrow": "€"
},
FIM: {
displayName: "Marca finlandesa",
"displayName-count-one": "Marco finlandês",
"displayName-count-other": "Marcos finlandeses",
symbol: "FIM"
},
FJD: {
displayName: "Dólar de Fiji",
"displayName-count-one": "Dólar de Fiji",
"displayName-count-other": "Dólares de Fiji",
symbol: "FJD",
"symbol-alt-narrow": "$"
},
FKP: {
displayName: "Libra das Ilhas Falkland",
"displayName-count-one": "Libra das Ilhas Falkland",
"displayName-count-other": "Libras das Ilhas Falkland",
symbol: "FKP",
"symbol-alt-narrow": "£"
},
FRF: {
displayName: "Franco francês",
"displayName-count-one": "Franco francês",
"displayName-count-other": "Francos franceses",
symbol: "FRF"
},
GBP: {
displayName: "Libra esterlina britânica",
"displayName-count-one": "Libra esterlina britânica",
"displayName-count-other": "Libras esterlinas britânicas",
symbol: "£",
"symbol-alt-narrow": "£"
},
GEK: {
displayName: "Cupom Lari georgiano",
"displayName-count-one": "Kupon larit da Geórgia",
"displayName-count-other": "Kupon larits da Geórgia",
symbol: "GEK"
},
GEL: {
displayName: "Lari georgiano",
"displayName-count-one": "Lari georgiano",
"displayName-count-other": "Laris georgianos",
symbol: "GEL",
"symbol-alt-narrow": "₾",
"symbol-alt-variant": "₾"
},
GHC: {
displayName: "Cedi de Gana (1979–2007)",
"displayName-count-one": "Cedi de Gana (1979–2007)",
"displayName-count-other": "Cedis de Gana (1979–2007)",
symbol: "GHC"
},
GHS: {
displayName: "Cedi de Gana",
"displayName-count-one": "Cedi de Gana",
"displayName-count-other": "Cedis de Gana",
symbol: "GHS"
},
GIP: {
displayName: "Libra de Gibraltar",
"displayName-count-one": "Libra de Gibraltar",
"displayName-count-other": "Libras de Gibraltar",
symbol: "GIP",
"symbol-alt-narrow": "£"
},
GMD: {
displayName: "Dalasi da Gâmbia",
"displayName-count-one": "Dalasi da Gâmbia",
"displayName-count-other": "Dalasis da Gâmbia",
symbol: "GMD"
},
GNF: {
displayName: "Franco guineense",
"displayName-count-one": "Franco guineense",
"displayName-count-other": "Francos guineenses",
symbol: "GNF",
"symbol-alt-narrow": "FG"
},
GNS: {
displayName: "Syli da Guiné",
"displayName-count-one": "Syli guineano",
"displayName-count-other": "Sylis guineanos",
symbol: "GNS"
},
GQE: {
displayName: "Ekwele da Guiné Equatorial",
"displayName-count-one": "Ekwele da Guiné Equatorial",
"displayName-count-other": "Ekweles da Guiné Equatorial",
symbol: "GQE"
},
GRD: {
displayName: "Dracma grego",
"displayName-count-one": "Dracma grego",
"displayName-count-other": "Dracmas gregos",
symbol: "GRD"
},
GTQ: {
displayName: "Quetzal da Guatemala",
"displayName-count-one": "Quetzal da Guatemala",
"displayName-count-other": "Quetzales da Guatemala",
symbol: "GTQ",
"symbol-alt-narrow": "Q"
},
GWE: {
displayName: "Escudo da Guiné Portuguesa",
"displayName-count-one": "Escudo da Guiné Portuguesa",
"displayName-count-other": "Escudos da Guinéa Portuguesa",
symbol: "GWE"
},
GWP: {
displayName: "Peso da Guiné-Bissau",
"displayName-count-one": "Peso de Guiné-Bissau",
"displayName-count-other": "Pesos de Guiné-Bissau",
symbol: "GWP"
},
GYD: {
displayName: "Dólar da Guiana",
"displayName-count-one": "Dólar da Guiana",
"displayName-count-other": "Dólares da Guiana",
symbol: "GYD",
"symbol-alt-narrow": "$"
},
HKD: {
displayName: "Dólar de Hong Kong",
"displayName-count-one": "Dólar de Hong Kong",
"displayName-count-other": "Dólares de Hong Kong",
symbol: "HK$",
"symbol-alt-narrow": "$"
},
HNL: {
displayName: "Lempira das Honduras",
"displayName-count-one": "Lempira das Honduras",
"displayName-count-other": "Lempiras das Honduras",
symbol: "HNL",
"symbol-alt-narrow": "L"
},
HRD: {
displayName: "Dinar croata",
"displayName-count-one": "Dinar croata",
"displayName-count-other": "Dinares croatas",
symbol: "HRD"
},
HRK: {
displayName: "Kuna croata",
"displayName-count-one": "Kuna croata",
"displayName-count-other": "Kunas croatas",
symbol: "HRK",
"symbol-alt-narrow": "kn"
},
HTG: {
displayName: "Gourde haitiano",
"displayName-count-one": "Gourde haitiano",
"displayName-count-other": "Gourdes haitianos",
symbol: "HTG"
},
HUF: {
displayName: "Forint húngaro",
"displayName-count-one": "Forint húngaro",
"displayName-count-other": "Forints húngaros",
symbol: "HUF",
"symbol-alt-narrow": "Ft"
},
IDR: {
displayName: "Rupia indonésia",
"displayName-count-one": "Rupia indonésia",
"displayName-count-other": "Rupias indonésias",
symbol: "IDR",
"symbol-alt-narrow": "Rp"
},
IEP: {
displayName: "Libra irlandesa",
"displayName-count-one": "Libra irlandesa",
"displayName-count-other": "Libras irlandesas",
symbol: "IEP"
},
ILP: {
displayName: "Libra israelita",
"displayName-count-one": "Libra israelita",
"displayName-count-other": "Libras israelitas",
symbol: "ILP"
},
ILR: {
displayName: "Sheqel antigo israelita",
"displayName-count-one": "Sheqel antigo israelita",
"displayName-count-other": "Sheqels antigos israelitas"
},
ILS: {
displayName: "Sheqel novo israelita",
"displayName-count-one": "Sheqel novo israelita",
"displayName-count-other": "Sheqels novos israelitas",
symbol: "₪",
"symbol-alt-narrow": "₪"
},
INR: {
displayName: "Rupia indiana",
"displayName-count-one": "Rupia indiana",
"displayName-count-other": "Rupias indianas",
symbol: "₹",
"symbol-alt-narrow": "₹"
},
IQD: {
displayName: "Dinar iraquiano",
"displayName-count-one": "Dinar iraquiano",
"displayName-count-other": "Dinares iraquianos",
symbol: "IQD"
},
IRR: {
displayName: "Rial iraniano",
"displayName-count-one": "Rial iraniano",
"displayName-count-other": "Riais iranianos",
symbol: "IRR"
},
ISJ: {
displayName: "Coroa antiga islandesa",
"displayName-count-one": "Coroa antiga islandesa",
"displayName-count-other": "Coroas antigas islandesas"
},
ISK: {
displayName: "Coroa islandesa",
"displayName-count-one": "Coroa islandesa",
"displayName-count-other": "Coroas islandesas",
symbol: "ISK",
"symbol-alt-narrow": "kr"
},
ITL: {
displayName: "Lira italiana",
"displayName-count-one": "Lira italiana",
"displayName-count-other": "Liras italianas",
symbol: "ITL"
},
JMD: {
displayName: "Dólar jamaicano",
"displayName-count-one": "Dólar jamaicano",
"displayName-count-other": "Dólares jamaicanos",
symbol: "JMD",
"symbol-alt-narrow": "$"
},
JOD: {
displayName: "Dinar jordaniano",
"displayName-count-one": "Dinar jordaniano",
"displayName-count-other": "Dinares jordanianos",
symbol: "JOD"
},
JPY: {
displayName: "Iene japonês",
"displayName-count-one": "Iene japonês",
"displayName-count-other": "Ienes japoneses",
symbol: "JP¥",
"symbol-alt-narrow": "¥"
},
KES: {
displayName: "Xelim queniano",
"displayName-count-one": "Xelim queniano",
"displayName-count-other": "Xelins quenianos",
symbol: "KES"
},
KGS: {
displayName: "Som do Quirguistão",
"displayName-count-one": "Som do Quirguistão",
"displayName-count-other": "Sons do Quirguistão",
symbol: "KGS"
},
KHR: {
displayName: "Riel cambojano",
"displayName-count-one": "Riel cambojano",
"displayName-count-other": "Rieles cambojanos",
symbol: "KHR",
"symbol-alt-narrow": "៛"
},
KMF: {
displayName: "Franco comoriano",
"displayName-count-one": "Franco comoriano",
"displayName-count-other": "Francos comorianos",
symbol: "KMF",
"symbol-alt-narrow": "CF"
},
KPW: {
displayName: "Won norte-coreano",
"displayName-count-one": "Won norte-coreano",
"displayName-count-other": "Wons norte-coreanos",
symbol: "KPW",
"symbol-alt-narrow": "₩"
},
KRH: {
displayName: "Hwan da Coreia do Sul (1953–1962)",
"displayName-count-one": "Hwan da Coreia do Sul",
"displayName-count-other": "Hwans da Coreia do Sul",
symbol: "KRH"
},
KRO: {
displayName: "Won da Coreia do Sul (1945–1953)",
"displayName-count-one": "Won antigo da Coreia do Sul",
"displayName-count-other": "Wons antigos da Coreia do Sul",
symbol: "KRO"
},
KRW: {
displayName: "Won sul-coreano",
"displayName-count-one": "Won sul-coreano",
"displayName-count-other": "Wons sul-coreanos",
symbol: "₩",
"symbol-alt-narrow": "₩"
},
KWD: {
displayName: "Dinar kuwaitiano",
"displayName-count-one": "Dinar kuwaitiano",
"displayName-count-other": "Dinares kuwaitianos",
symbol: "KWD"
},
KYD: {
displayName: "Dólar das Ilhas Caimão",
"displayName-count-one": "Dólar das Ilhas Caimão",
"displayName-count-other": "Dólares das Ilhas Caimão",
symbol: "KYD",
"symbol-alt-narrow": "$"
},
KZT: {
displayName: "Tenge do Cazaquistão",
"displayName-count-one": "Tenge do Cazaquistão",
"displayName-count-other": "Tenges do Cazaquistão",
symbol: "KZT",
"symbol-alt-narrow": "₸"
},
LAK: {
displayName: "Kip de Laos",
"displayName-count-one": "Kip de Laos",
"displayName-count-other": "Kips de Laos",
symbol: "LAK",
"symbol-alt-narrow": "₭"
},
LBP: {
displayName: "Libra libanesa",
"displayName-count-one": "Libra libanesa",
"displayName-count-other": "Libras libanesas",
symbol: "LBP",
"symbol-alt-narrow": "L£"
},
LKR: {
displayName: "Rupia do Sri Lanka",
"displayName-count-one": "Rupia do Sri Lanka",
"displayName-count-other": "Rupias do Sri Lanka",
symbol: "LKR",
"symbol-alt-narrow": "Rs"
},
LRD: {
displayName: "Dólar liberiano",
"displayName-count-one": "Dólar liberiano",
"displayName-count-other": "Dólares liberianos",
symbol: "LRD",
"symbol-alt-narrow": "$"
},
LSL: {
displayName: "Loti do Lesoto",
"displayName-count-one": "Loti do Lesoto",
"displayName-count-other": "Lotis do Lesoto",
symbol: "LSL"
},
LTL: {
displayName: "Litas da Lituânia",
"displayName-count-one": "Litas da Lituânia",
"displayName-count-other": "Litas da Lituânia",
symbol: "LTL",
"symbol-alt-narrow": "Lt"
},
LTT: {
displayName: "Talonas lituano",
"displayName-count-one": "Talonas lituanas",
"displayName-count-other": "Talonases lituanas",
symbol: "LTT"
},
LUC: {
displayName: "Franco conversível de Luxemburgo",
"displayName-count-one": "Franco conversível de Luxemburgo",
"displayName-count-other": "Francos conversíveis de Luxemburgo",
symbol: "LUC"
},
LUF: {
displayName: "Franco luxemburguês",
"displayName-count-one": "Franco de Luxemburgo",
"displayName-count-other": "Francos de Luxemburgo",
symbol: "LUF"
},
LUL: {
displayName: "Franco financeiro de Luxemburgo",
"displayName-count-one": "Franco financeiro de Luxemburgo",
"displayName-count-other": "Francos financeiros de Luxemburgo",
symbol: "LUL"
},
LVL: {
displayName: "Lats da Letónia",
"displayName-count-one": "Lats da Letónia",
"displayName-count-other": "Lats da Letónia",
symbol: "LVL",
"symbol-alt-narrow": "Ls"
},
LVR: {
displayName: "Rublo letão",
"displayName-count-one": "Rublo da Letônia",
"displayName-count-other": "Rublos da Letônia",
symbol: "LVR"
},
LYD: {
displayName: "Dinar líbio",
"displayName-count-one": "Dinar líbio",
"displayName-count-other": "Dinares líbios",
symbol: "LYD"
},
MAD: {
displayName: "Dirham marroquino",
"displayName-count-one": "Dirham marroquino",
"displayName-count-other": "Dirhams marroquinos",
symbol: "MAD"
},
MAF: {
displayName: "Franco marroquino",
"displayName-count-one": "Franco marroquino",
"displayName-count-other": "Francos marroquinos",
symbol: "MAF"
},
MCF: {
displayName: "Franco monegasco",
"displayName-count-one": "Franco monegasco",
"displayName-count-other": "Francos monegascos",
symbol: "MCF"
},
MDC: {
displayName: "Cupon moldávio",
"displayName-count-one": "Cupon moldávio",
"displayName-count-other": "Cupon moldávio",
symbol: "MDC"
},
MDL: {
displayName: "Leu moldavo",
"displayName-count-one": "Leu moldavo",
"displayName-count-other": "Lei moldavos",
symbol: "MDL"
},
MGA: {
displayName: "Ariari de Madagáscar",
"displayName-count-one": "Ariari de Madagáscar",
"displayName-count-other": "Ariaris de Madagáscar",
symbol: "MGA",
"symbol-alt-narrow": "Ar"
},
MGF: {
displayName: "Franco de Madagascar",
"displayName-count-one": "Franco de Madagascar",
"displayName-count-other": "Francos de Madagascar",
symbol: "MGF"
},
MKD: {
displayName: "Dinar macedónio",
"displayName-count-one": "Dinar macedónio",
"displayName-count-other": "Dinares macedónios",
symbol: "MKD"
},
MKN: {
displayName: "Dinar macedônio (1992–1993)",
"displayName-count-one": "Dinar macedônio (1992–1993)",
"displayName-count-other": "Dinares macedônios (1992–1993)",
symbol: "MKN"
},
MLF: {
displayName: "Franco de Mali",
"displayName-count-one": "Franco de Mali",
"displayName-count-other": "Francos de Mali",
symbol: "MLF"
},
MMK: {
displayName: "Kyat de Mianmar",
"displayName-count-one": "Kyat de Mianmar",
"displayName-count-other": "Kyats de Mianmar",
symbol: "MMK",
"symbol-alt-narrow": "K"
},
MNT: {
displayName: "Tugrik da Mongólia",
"displayName-count-one": "Tugrik da Mongólia",
"displayName-count-other": "Tugriks da Mongólia",
symbol: "MNT",
"symbol-alt-narrow": "₮"
},
MOP: {
displayName: "Pataca de Macau",
"displayName-count-one": "Pataca de Macau",
"displayName-count-other": "Patacas de Macau",
symbol: "MOP"
},
MRO: {
displayName: "Ouguiya da Mauritânia",
"displayName-count-one": "Ouguiya da Mauritânia",
"displayName-count-other": "Ouguiyas da Mauritânia",
symbol: "MRO"
},
MTL: {
displayName: "Lira maltesa",
"displayName-count-one": "Lira Maltesa",
"displayName-count-other": "Liras maltesas",
symbol: "MTL"
},
MTP: {
displayName: "Libra maltesa",
"displayName-count-one": "Libra maltesa",
"displayName-count-other": "Libras maltesas",
symbol: "MTP"
},
MUR: {
displayName: "Rupia mauriciana",
"displayName-count-one": "Rupia mauriciana",
"displayName-count-other": "Rupias mauricianas",
symbol: "MUR",
"symbol-alt-narrow": "Rs"
},
MVR: {
displayName: "Rupia das Ilhas Maldivas",
"displayName-count-one": "Rupia das Ilhas Maldivas",
"displayName-count-other": "Rupias das Ilhas Maldivas",
symbol: "MVR"
},
MWK: {
displayName: "Kwacha do Malawi",
"displayName-count-one": "Kwacha do Malawi",
"displayName-count-other": "Kwachas do Malawi",
symbol: "MWK"
},
MXN: {
displayName: "Peso mexicano",
"displayName-count-one": "Peso mexicano",
"displayName-count-other": "Pesos mexicanos",
symbol: "MX$",
"symbol-alt-narrow": "$"
},
MXP: {
displayName: "Peso Plata mexicano (1861–1992)",
"displayName-count-one": "Peso de prata mexicano (1861–1992)",
"displayName-count-other": "Pesos de prata mexicanos (1861–1992)",
symbol: "MXP"
},
MXV: {
displayName: "Unidad de Inversion (UDI) mexicana",
"displayName-count-one": "Unidade de investimento mexicana (UDI)",
"displayName-count-other": "Unidades de investimento mexicanas (UDI)",
symbol: "MXV"
},
MYR: {
displayName: "Ringgit malaio",
"displayName-count-one": "Ringgit malaio",
"displayName-count-other": "Ringgits malaios",
symbol: "MYR",
"symbol-alt-narrow": "RM"
},
MZE: {
displayName: "Escudo de Moçambique",
"displayName-count-one": "Escudo de Moçambique",
"displayName-count-other": "Escudos de Moçambique",
symbol: "MZE"
},
MZM: {
displayName: "Metical de Moçambique (1980–2006)",
"displayName-count-one": "Metical antigo de Moçambique",
"displayName-count-other": "Meticales antigos de Moçambique",
symbol: "MZM"
},
MZN: {
displayName: "Metical de Moçambique",
"displayName-count-one": "Metical de Moçambique",
"displayName-count-other": "Meticales de Moçambique",
symbol: "MZN"
},
NAD: {
displayName: "Dólar da Namíbia",
"displayName-count-one": "Dólar da Namíbia",
"displayName-count-other": "Dólares da Namíbia",
symbol: "NAD",
"symbol-alt-narrow": "$"
},
NGN: {
displayName: "Naira nigeriana",
"displayName-count-one": "Naira nigeriana",
"displayName-count-other": "Nairas nigerianas",
symbol: "NGN",
"symbol-alt-narrow": "₦"
},
NIC: {
displayName: "Córdoba nicaraguano (1988–1991)",
"displayName-count-one": "Córdoba nicaraguano (1988–1991)",
"displayName-count-other": "Córdobas nicaraguano (1988–1991)",
symbol: "NIC"
},
NIO: {
displayName: "Córdoba nicaraguano",
"displayName-count-one": "Córdoba nicaraguano",
"displayName-count-other": "Córdoba nicaraguano",
symbol: "NIO",
"symbol-alt-narrow": "C$"
},
NLG: {
displayName: "Florim holandês",
"displayName-count-one": "Florim holandês",
"displayName-count-other": "Florins holandeses",
symbol: "NLG"
},
NOK: {
displayName: "Coroa norueguesa",
"displayName-count-one": "Coroa norueguesa",
"displayName-count-other": "Coroas norueguesas",
symbol: "NOK",
"symbol-alt-narrow": "kr"
},
NPR: {
displayName: "Rupia nepalesa",
"displayName-count-one": "Rupia nepalesa",
"displayName-count-other": "Rupias nepalesas",
symbol: "NPR",
"symbol-alt-narrow": "Rs"
},
NZD: {
displayName: "Dólar neozelandês",
"displayName-count-one": "Dólar neozelandês",
"displayName-count-other": "Dólares neozelandeses",
symbol: "NZ$",
"symbol-alt-narrow": "$"
},
OMR: {
displayName: "Rial de Omã",
"displayName-count-one": "Rial de Omã",
"displayName-count-other": "Riais de Omã",
symbol: "OMR"
},
PAB: {
displayName: "Balboa do Panamá",
"displayName-count-one": "Balboa do Panamá",
"displayName-count-other": "Balboas do Panamá",
symbol: "PAB"
},
PEI: {
displayName: "Inti peruano",
"displayName-count-one": "Inti peruano",
"displayName-count-other": "Intis peruanos",
symbol: "PEI"
},
PEN: {
displayName: "Sol peruano",
"displayName-count-one": "Sol peruano",
"displayName-count-other": "Soles peruanos",
symbol: "PEN"
},
PES: {
displayName: "Sol peruano (1863–1965)",
"displayName-count-one": "Sol peruano (1863–1965)",
"displayName-count-other": "Soles peruanos (1863–1965)",
symbol: "PES"
},
PGK: {
displayName: "Kina da Papua-Nova Guiné",
"displayName-count-one": "Kina da Papua-Nova Guiné",
"displayName-count-other": "Kinas da Papua-Nova Guiné",
symbol: "PGK"
},
PHP: {
displayName: "Peso filipino",
"displayName-count-one": "Peso filipino",
"displayName-count-other": "Pesos filipinos",
symbol: "PHP",
"symbol-alt-narrow": "₱"
},
PKR: {
displayName: "Rupia paquistanesa",
"displayName-count-one": "Rupia paquistanesa",
"displayName-count-other": "Rupias paquistanesas",
symbol: "PKR",
"symbol-alt-narrow": "Rs"
},
PLN: {
displayName: "Zloti polaco",
"displayName-count-one": "Zloti polaco",
"displayName-count-other": "Zlotis polacos",
symbol: "PLN",
"symbol-alt-narrow": "zł"
},
PLZ: {
displayName: "Zloti polonês (1950–1995)",
"displayName-count-one": "Zloti polonês (1950–1995)",
"displayName-count-other": "Zlotis poloneses (1950–1995)",
symbol: "PLZ"
},
PTE: {
displayName: "Escudo português",
"displayName-count-one": "Escudo português",
"displayName-count-other": "Escudos portugueses",
symbol: "",
decimal: "$",
group: ","
},
PYG: {
displayName: "Guarani paraguaio",
"displayName-count-one": "Guarani paraguaio",
"displayName-count-other": "Guaranis paraguaios",
symbol: "PYG",
"symbol-alt-narrow": "₲"
},
QAR: {
displayName: "Rial do Catar",
"displayName-count-one": "Rial do Catar",
"displayName-count-other": "Riais do Catar",
symbol: "QAR"
},
RHD: {
displayName: "Dólar rodesiano",
"displayName-count-one": "Dólar da Rodésia",
"displayName-count-other": "Dólares da Rodésia",
symbol: "RHD"
},
ROL: {
displayName: "Leu romeno (1952–2006)",
"displayName-count-one": "Leu antigo da Romênia",
"displayName-count-other": "Leus antigos da Romênia",
symbol: "ROL"
},
RON: {
displayName: "Leu romeno",
"displayName-count-one": "Leu romeno",
"displayName-count-other": "Lei romenos",
symbol: "RON",
"symbol-alt-narrow": "L"
},
RSD: {
displayName: "Dinar sérvio",
"displayName-count-one": "Dinar sérvio",
"displayName-count-other": "Dinares sérvios",
symbol: "RSD"
},
RUB: {
displayName: "Rublo russo",
"displayName-count-one": "Rublo russo",
"displayName-count-other": "Rublos russos",
symbol: "RUB",
"symbol-alt-narrow": "₽"
},
RUR: {
displayName: "Rublo russo (1991–1998)",
"displayName-count-one": "Rublo russo (1991–1998)",
"displayName-count-other": "Rublos russos (1991–1998)",
symbol: "RUR",
"symbol-alt-narrow": "р."
},
RWF: {
displayName: "Franco ruandês",
"displayName-count-one": "Franco ruandês",
"displayName-count-other": "Francos ruandeses",
symbol: "RWF",
"symbol-alt-narrow": "RF"
},
SAR: {
displayName: "Rial saudita",
"displayName-count-one": "Rial saudita",
"displayName-count-other": "Riais sauditas",
symbol: "SAR"
},
SBD: {
displayName: "Dólar das Ilhas Salomão",
"displayName-count-one": "Dólar das Ilhas Salomão",
"displayName-count-other": "Dólares das Ilhas Salomão",
symbol: "SBD",
"symbol-alt-narrow": "$"
},
SCR: {
displayName: "Rupia seichelense",
"displayName-count-one": "Rupia seichelense",
"displayName-count-other": "Rupias seichelenses",
symbol: "SCR"
},
SDD: {
displayName: "Dinar sudanês (1992–2007)",
"displayName-count-one": "Dinar antigo do Sudão",
"displayName-count-other": "Dinares antigos do Sudão",
symbol: "SDD"
},
SDG: {
displayName: "Libra sudanesa",
"displayName-count-one": "Libra sudanesa",
"displayName-count-other": "Libras sudanesas",
symbol: "SDG"
},
SDP: {
displayName: "Libra sudanesa (1957–1998)",
"displayName-count-one": "Libra antiga sudanesa",
"displayName-count-other": "Libras antigas sudanesas",
symbol: "SDP"
},
SEK: {
displayName: "Coroa sueca",
"displayName-count-one": "Coroa sueca",
"displayName-count-other": "Coroas suecas",
symbol: "SEK",
"symbol-alt-narrow": "kr"
},
SGD: {
displayName: "Dólar de Singapura",
"displayName-count-one": "Dólar de Singapura",
"displayName-count-other": "Dólares de Singapura",
symbol: "SGD",
"symbol-alt-narrow": "$"
},
SHP: {
displayName: "Libra de Santa Helena",
"displayName-count-one": "Libra de Santa Helena",
"displayName-count-other": "Libras de Santa Helena",
symbol: "SHP",
"symbol-alt-narrow": "£"
},
SIT: {
displayName: "Tolar Bons esloveno",
"displayName-count-one": "Tolar da Eslovênia",
"displayName-count-other": "Tolares da Eslovênia",
symbol: "SIT"
},
SKK: {
displayName: "Coroa eslovaca",
"displayName-count-one": "Coroa eslovaca",
"displayName-count-other": "Coroas eslovacas",
symbol: "SKK"
},
SLL: {
displayName: "Leone de Serra Leoa",
"displayName-count-one": "Leone de Serra Leoa",
"displayName-count-other": "Leones de Serra Leoa",
symbol: "SLL"
},
SOS: {
displayName: "Xelim somali",
"displayName-count-one": "Xelim somali",
"displayName-count-other": "Xelins somalis",
symbol: "SOS"
},
SRD: {
displayName: "Dólar do Suriname",
"displayName-count-one": "Dólar do Suriname",
"displayName-count-other": "Dólares do Suriname",
symbol: "SRD",
"symbol-alt-narrow": "$"
},
SRG: {
displayName: "Florim do Suriname",
"displayName-count-one": "Florim do Suriname",
"displayName-count-other": "Florins do Suriname",
symbol: "SRG"
},
SSP: {
displayName: "Libra sul-sudanesa",
"displayName-count-one": "Libra sul-sudanesa",
"displayName-count-other": "Libras sul-sudanesas",
symbol: "SSP",
"symbol-alt-narrow": "£"
},
STD: {
displayName: "Dobra de São Tomé e Príncipe",
"displayName-count-one": "Dobra de São Tomé e Príncipe",
"displayName-count-other": "Dobras de São Tomé e Príncipe",
symbol: "STD",
"symbol-alt-narrow": "Db"
},
SUR: {
displayName: "Rublo soviético",
"displayName-count-one": "Rublo soviético",
"displayName-count-other": "Rublos soviéticos",
symbol: "SUR"
},
SVC: {
displayName: "Colom salvadorenho",
"displayName-count-one": "Colon de El Salvador",
"displayName-count-other": "Colons de El Salvador",
symbol: "SVC"
},
SYP: {
displayName: "Libra síria",
"displayName-count-one": "Libra síria",
"displayName-count-other": "Libras sírias",
symbol: "SYP",
"symbol-alt-narrow": "£"
},
SZL: {
displayName: "Lilangeni da Suazilândia",
"displayName-count-one": "Lilangeni da Suazilândia",
"displayName-count-other": "Lilangenis da Suazilândia",
symbol: "SZL"
},
THB: {
displayName: "Baht da Tailândia",
"displayName-count-one": "Baht da Tailândia",
"displayName-count-other": "Bahts da Tailândia",
symbol: "฿",
"symbol-alt-narrow": "฿"
},
TJR: {
displayName: "Rublo do Tadjiquistão",
"displayName-count-one": "Rublo do Tajaquistão",
"displayName-count-other": "Rublos do Tajaquistão",
symbol: "TJR"
},
TJS: {
displayName: "Somoni do Tajaquistão",
"displayName-count-one": "Somoni do Tajaquistão",
"displayName-count-other": "Somonis do Tajaquistão",
symbol: "TJS"
},
TMM: {
displayName: "Manat do Turcomenistão (1993–2009)",
"displayName-count-one": "Manat do Turcomenistão (1993–2009)",
"displayName-count-other": "Manats do Turcomenistão (1993–2009)",
symbol: "TMM"
},
TMT: {
displayName: "Manat do Turquemenistão",
"displayName-count-one": "Manat do Turquemenistão",
"displayName-count-other": "Manats do Turquemenistão",
symbol: "TMT"
},
TND: {
displayName: "Dinar tunisino",
"displayName-count-one": "Dinar tunisino",
"displayName-count-other": "Dinares tunisinos",
symbol: "TND"
},
TOP: {
displayName: "Paʻanga de Tonga",
"displayName-count-one": "Paʻanga de Tonga",
"displayName-count-other": "Paʻangas de Tonga",
symbol: "TOP",
"symbol-alt-narrow": "T$"
},
TPE: {
displayName: "Escudo timorense",
"displayName-count-one": "Escudo do Timor",
"displayName-count-other": "Escudos do Timor",
symbol: "TPE"
},
TRL: {
displayName: "Lira turca (1922–2005)",
"displayName-count-one": "Lira turca antiga",
"displayName-count-other": "Liras turcas antigas",
symbol: "TRL"
},
TRY: {
displayName: "Lira turca",
"displayName-count-one": "Lira turca",
"displayName-count-other": "Liras turcas",
symbol: "TRY",
"symbol-alt-narrow": "₺",
"symbol-alt-variant": "TL"
},
TTD: {
displayName: "Dólar de Trindade e Tobago",
"displayName-count-one": "Dólar de Trindade e Tobago",
"displayName-count-other": "Dólares de Trindade e Tobago",
symbol: "TTD",
"symbol-alt-narrow": "$"
},
TWD: {
displayName: "Novo dólar taiwanês",
"displayName-count-one": "Novo dólar taiwanês",
"displayName-count-other": "Novos dólares taiwaneses",
symbol: "NT$",
"symbol-alt-narrow": "NT$"
},
TZS: {
displayName: "Xelim tanzaniano",
"displayName-count-one": "Xelim tanzaniano",
"displayName-count-other": "Xelins tanzanianos",
symbol: "TZS"
},
UAH: {
displayName: "Hryvnia da Ucrânia",
"displayName-count-one": "Hryvnia da Ucrânia",
"displayName-count-other": "Hryvnias da Ucrânia",
symbol: "UAH",
"symbol-alt-narrow": "₴"
},
UAK: {
displayName: "Karbovanetz ucraniano",
"displayName-count-one": "Karbovanetz da Ucrânia",
"displayName-count-other": "Karbovanetzs da Ucrânia",
symbol: "UAK"
},
UGS: {
displayName: "Xelim ugandense (1966–1987)",
"displayName-count-one": "Shilling de Uganda (1966–1987)",
"displayName-count-other": "Shillings de Uganda (1966–1987)",
symbol: "UGS"
},
UGX: {
displayName: "Xelim ugandense",
"displayName-count-one": "Xelim ugandense",
"displayName-count-other": "Xelins ugandenses",
symbol: "UGX"
},
USD: {
displayName: "Dólar dos Estados Unidos",
"displayName-count-one": "Dólar dos Estados Unidos",
"displayName-count-other": "Dólares dos Estados Unidos",
symbol: "US$",
"symbol-alt-narrow": "$"
},
USN: {
displayName: "Dólar norte-americano (Dia seguinte)",
"displayName-count-one": "Dólar americano (dia seguinte)",
"displayName-count-other": "Dólares americanos (dia seguinte)",
symbol: "USN"
},
USS: {
displayName: "Dólar norte-americano (Mesmo dia)",
"displayName-count-one": "Dólar americano (mesmo dia)",
"displayName-count-other": "Dólares americanos (mesmo dia)",
symbol: "USS"
},
UYI: {
displayName: "Peso uruguaio en unidades indexadas",
"displayName-count-one": "Peso uruguaio em unidades indexadas",
"displayName-count-other": "Pesos uruguaios em unidades indexadas",
symbol: "UYI"
},
UYP: {
displayName: "Peso uruguaio (1975–1993)",
"displayName-count-one": "Peso uruguaio (1975–1993)",
"displayName-count-other": "Pesos uruguaios (1975–1993)",
symbol: "UYP"
},
UYU: {
displayName: "Peso uruguaio",
"displayName-count-one": "Peso uruguaio",
"displayName-count-other": "Pesos uruguaios",
symbol: "UYU",
"symbol-alt-narrow": "$"
},
UZS: {
displayName: "Som do Uzbequistão",
"displayName-count-one": "Som do Uzbequistão",
"displayName-count-other": "Sons do Uzbequistão",
symbol: "UZS"
},
VEB: {
displayName: "Bolívar venezuelano (1871–2008)",
"displayName-count-one": "Bolívar venezuelano (1871–2008)",
"displayName-count-other": "Bolívares venezuelanos (1871–2008)",
symbol: "VEB"
},
VEF: {
displayName: "Bolívar venezuelano",
"displayName-count-one": "Bolívar venezuelano",
"displayName-count-other": "Bolívares venezuelanos",
symbol: "VEF",
"symbol-alt-narrow": "Bs"
},
VND: {
displayName: "Dong vietnamita",
"displayName-count-one": "Dong vietnamita",
"displayName-count-other": "Dongs vietnamitas",
symbol: "₫",
"symbol-alt-narrow": "₫"
},
VNN: {
displayName: "Dong vietnamita (1978–1985)",
"displayName-count-one": "Dong vietnamita (1978–1985)",
"displayName-count-other": "Dong vietnamita (1978–1985)",
symbol: "VNN"
},
VUV: {
displayName: "Vatu de Vanuatu",
"displayName-count-one": "Vatu de Vanuatu",
"displayName-count-other": "Vatus de Vanuatu",
symbol: "VUV"
},
WST: {
displayName: "Tala samoano",
"displayName-count-one": "Tala samoano",
"displayName-count-other": "Talas samoanos",
symbol: "WST"
},
XAF: {
displayName: "Franco CFA (BEAC)",
"displayName-count-one": "Franco CFA (BEAC)",
"displayName-count-other": "Francos CFA (BEAC)",
symbol: "FCFA"
},
XAG: {
displayName: "Prata",
"displayName-count-one": "Prata",
"displayName-count-other": "Pratas",
symbol: "XAG"
},
XAU: {
displayName: "Ouro",
"displayName-count-one": "Ouro",
"displayName-count-other": "Ouros",
symbol: "XAU"
},
XBA: {
displayName: "Unidade Composta Europeia",
"displayName-count-one": "Unidade de composição europeia",
"displayName-count-other": "Unidades de composição europeias",
symbol: "XBA"
},
XBB: {
displayName: "Unidade Monetária Europeia",
"displayName-count-one": "Unidade monetária europeia",
"displayName-count-other": "Unidades monetárias europeias",
symbol: "XBB"
},
XBC: {
displayName: "Unidade de Conta Europeia (XBC)",
"displayName-count-one": "Unidade europeia de conta (XBC)",
"displayName-count-other": "Unidades europeias de conta (XBC)",
symbol: "XBC"
},
XBD: {
displayName: "Unidade de Conta Europeia (XBD)",
"displayName-count-one": "Unidade europeia de conta (XBD)",
"displayName-count-other": "Unidades europeias de conta (XBD)",
symbol: "XBD"
},
XCD: {
displayName: "Dólar das Caraíbas Orientais",
"displayName-count-one": "Dólar das Caraíbas Orientais",
"displayName-count-other": "Dólares das Caraíbas Orientais",
symbol: "EC$",
"symbol-alt-narrow": "$"
},
XDR: {
displayName: "Direitos Especiais de Giro",
"displayName-count-one": "Direitos de desenho especiais",
"displayName-count-other": "Direitos de desenho especiais",
symbol: "XDR"
},
XEU: {
displayName: "Unidade de Moeda Europeia",
"displayName-count-one": "Unidade de moeda europeia",
"displayName-count-other": "Unidades de moedas europeias",
symbol: "XEU"
},
XFO: {
displayName: "Franco-ouro francês",
"displayName-count-one": "Franco de ouro francês",
"displayName-count-other": "Francos de ouro franceses",
symbol: "XFO"
},
XFU: {
displayName: "Franco UIC francês",
"displayName-count-one": "Franco UIC francês",
"displayName-count-other": "Francos UIC franceses",
symbol: "XFU"
},
XOF: {
displayName: "Franco CFA (BCEAO)",
"displayName-count-one": "Franco CFA (BCEAO)",
"displayName-count-other": "Francos CFA (BCEAO)",
symbol: "CFA"
},
XPD: {
displayName: "Paládio",
"displayName-count-one": "Paládio",
"displayName-count-other": "Paládios",
symbol: "XPD"
},
XPF: {
displayName: "Franco CFP",
"displayName-count-one": "Franco CFP",
"displayName-count-other": "Francos CFP",
symbol: "CFPF"
},
XPT: {
displayName: "Platina",
"displayName-count-one": "Platina",
"displayName-count-other": "Platinas",
symbol: "XPT"
},
XRE: {
displayName: "Fundos RINET",
"displayName-count-one": "Fundos RINET",
"displayName-count-other": "Fundos RINET",
symbol: "XRE"
},
XSU: {
displayName: "XSU",
symbol: "XSU"
},
XTS: {
displayName: "Código de Moeda de Teste",
"displayName-count-one": "Código de moeda de teste",
"displayName-count-other": "Códigos de moeda de teste",
symbol: "XTS"
},
XUA: {
displayName: "XUA",
symbol: "XUA"
},
XXX: {
displayName: "Moeda desconhecida",
"displayName-count-one": "(moeda desconhecida)",
"displayName-count-other": "(moedas desconhecidas)",
symbol: "XXX"
},
YDD: {
displayName: "Dinar iemenita",
"displayName-count-one": "Dinar do Iêmen",
"displayName-count-other": "Dinares do Iêmen",
symbol: "YDD"
},
YER: {
displayName: "Rial iemenita",
"displayName-count-one": "Rial iemenita",
"displayName-count-other": "Riais iemenitas",
symbol: "YER"
},
YUD: {
displayName: "Dinar forte iugoslavo (1966–1990)",
"displayName-count-one": "Dinar forte iugoslavo",
"displayName-count-other": "Dinares fortes iugoslavos",
symbol: "YUD"
},
YUM: {
displayName: "Dinar noviy iugoslavo (1994–2002)",
"displayName-count-one": "Dinar noviy da Iugoslávia",
"displayName-count-other": "Dinares noviy da Iugoslávia",
symbol: "YUM"
},
YUN: {
displayName: "Dinar conversível iugoslavo (1990–1992)",
"displayName-count-one": "Dinar conversível da Iugoslávia",
"displayName-count-other": "Dinares conversíveis da Iugoslávia",
symbol: "YUN"
},
YUR: {
displayName: "Dinar reformado iugoslavo (1992–1993)",
"displayName-count-one": "Dinar iugoslavo reformado",
"displayName-count-other": "Dinares iugoslavos reformados",
symbol: "YUR"
},
ZAL: {
displayName: "Rand sul-africano (financeiro)",
"displayName-count-one": "Rand da África do Sul (financeiro)",
"displayName-count-other": "Rands da África do Sul (financeiro)",
symbol: "ZAL"
},
ZAR: {
displayName: "Rand sul-africano",
"displayName-count-one": "Rand sul-africano",
"displayName-count-other": "Rands sul-africanos",
symbol: "ZAR",
"symbol-alt-narrow": "R"
},
ZMK: {
displayName: "Kwacha zambiano (1968–2012)",
"displayName-count-one": "Kwacha zambiano (1968–2012)",
"displayName-count-other": "Kwachas zambianos (1968–2012)",
symbol: "ZMK"
},
ZMW: {
displayName: "Kwacha zambiano",
"displayName-count-one": "Kwacha zambiano",
"displayName-count-other": "Kwachas zambianos",
symbol: "ZMW",
"symbol-alt-narrow": "ZK"
},
ZRN: {
displayName: "Zaire Novo zairense (1993–1998)",
"displayName-count-one": "Novo zaire do Zaire",
"displayName-count-other": "Novos zaires do Zaire",
symbol: "ZRN"
},
ZRZ: {
displayName: "Zaire zairense (1971–1993)",
"displayName-count-one": "Zaire do Zaire",
"displayName-count-other": "Zaires do Zaire",
symbol: "ZRZ"
},
ZWD: {
displayName: "Dólar do Zimbábue (1980–2008)",
"displayName-count-one": "Dólar do Zimbábue",
"displayName-count-other": "Dólares do Zimbábue",
symbol: "ZWD"
},
ZWL: {
displayName: "Dólar do Zimbábue (2009)",
"displayName-count-one": "Dólar do Zimbábue (2009)",
"displayName-count-other": "Dólares do Zimbábue (2009)",
symbol: "ZWL"
},
ZWR: {
displayName: "Dólar do Zimbábue (2008)",
"displayName-count-one": "Dólar do Zimbábue (2008)",
"displayName-count-other": "Dólares do Zimbábue (2008)",
symbol: "ZWR"
}
},
localeCurrency: "CHF"
},
calendar: {
patterns: {
d: "dd/MM/y",
D: "EEEE, d 'de' MMMM 'de' y",
m: "d/MM",
M: "d 'de' MMMM",
y: "MM/y",
Y: "MMMM 'de' y",
F: "EEEE, d 'de' MMMM 'de' y HH:mm:ss",
g: "dd/MM/y HH:mm",
G: "dd/MM/y HH:mm:ss",
t: "HH:mm",
T: "HH:mm:ss",
s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss",
u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'"
},
dateTimeFormats: {
full: "{1} 'às' {0}",
long: "{1} 'às' {0}",
medium: "{1}, {0}",
short: "{1}, {0}",
availableFormats: {
d: "d",
E: "ccc",
Ed: "E, d",
Ehm: "E, h:mm a",
EHm: "E, HH:mm",
Ehms: "E, h:mm:ss a",
EHms: "E, HH:mm:ss",
Gy: "y G",
GyMMM: "MMM 'de' y G",
GyMMMd: "d 'de' MMM 'de' y G",
GyMMMEd: "E, d 'de' MMM 'de' y G",
h: "h a",
H: "HH",
hm: "h:mm a",
Hm: "HH:mm",
hms: "h:mm:ss a",
Hms: "HH:mm:ss",
hmsv: "h:mm:ss a v",
Hmsv: "HH:mm:ss v",
hmv: "h:mm a v",
Hmv: "HH:mm v",
M: "L",
Md: "dd/MM",
MEd: "E, dd/MM",
MMdd: "dd/MM",
MMM: "LLL",
MMMd: "d/MM",
MMMEd: "E, d/MM",
MMMMd: "d 'de' MMMM",
MMMMEd: "ccc, d 'de' MMMM",
"MMMMW-count-one": "W.'ª' 'semana' 'de' MMM",
"MMMMW-count-other": "W.'ª' 'semana' 'de' MMM",
ms: "mm:ss",
y: "y",
yM: "MM/y",
yMd: "dd/MM/y",
yMEd: "E, dd/MM/y",
yMM: "MM/y",
yMMM: "MM/y",
yMMMd: "d/MM/y",
yMMMEd: "E, d/MM/y",
yMMMEEEEd: "EEEE, d/MM/y",
yMMMM: "MMMM 'de' y",
yMMMMd: "d 'de' MMMM 'de' y",
yMMMMEd: "ccc, d 'de' MMMM 'de' y",
yQQQ: "QQQQ 'de' y",
yQQQQ: "QQQQ 'de' y",
"yw-count-one": "w.'ª' 'semana' 'de' y",
"yw-count-other": "w.'ª' 'semana' 'de' y"
}
},
timeFormats: {
full: "HH:mm:ss zzzz",
long: "HH:mm:ss z",
medium: "HH:mm:ss",
short: "HH:mm"
},
dateFormats: {
full: "EEEE, d 'de' MMMM 'de' y",
long: "d 'de' MMMM 'de' y",
medium: "dd/MM/y",
short: "dd/MM/yy"
},
days: {
format: {
abbreviated: [
"domingo",
"segunda",
"terça",
"quarta",
"quinta",
"sexta",
"sábado"
],
narrow: [
"D",
"S",
"T",
"Q",
"Q",
"S",
"S"
],
short: [
"dom",
"seg",
"ter",
"qua",
"qui",
"sex",
"sáb"
],
wide: [
"domingo",
"segunda-feira",
"terça-feira",
"quarta-feira",
"quinta-feira",
"sexta-feira",
"sábado"
]
},
"stand-alone": {
abbreviated: [
"domingo",
"segunda",
"terça",
"quarta",
"quinta",
"sexta",
"sábado"
],
narrow: [
"D",
"S",
"T",
"Q",
"Q",
"S",
"S"
],
short: [
"dom",
"seg",
"ter",
"qua",
"qui",
"sex",
"sáb"
],
wide: [
"domingo",
"segunda-feira",
"terça-feira",
"quarta-feira",
"quinta-feira",
"sexta-feira",
"sábado"
]
}
},
months: {
format: {
abbreviated: [
"jan",
"fev",
"mar",
"abr",
"mai",
"jun",
"jul",
"ago",
"set",
"out",
"nov",
"dez"
],
narrow: [
"J",
"F",
"M",
"A",
"M",
"J",
"J",
"A",
"S",
"O",
"N",
"D"
],
wide: [
"janeiro",
"fevereiro",
"março",
"abril",
"maio",
"junho",
"julho",
"agosto",
"setembro",
"outubro",
"novembro",
"dezembro"
]
},
"stand-alone": {
abbreviated: [
"jan",
"fev",
"mar",
"abr",
"mai",
"jun",
"jul",
"ago",
"set",
"out",
"nov",
"dez"
],
narrow: [
"J",
"F",
"M",
"A",
"M",
"J",
"J",
"A",
"S",
"O",
"N",
"D"
],
wide: [
"janeiro",
"fevereiro",
"março",
"abril",
"maio",
"junho",
"julho",
"agosto",
"setembro",
"outubro",
"novembro",
"dezembro"
]
}
},
quarters: {
format: {
abbreviated: [
"T1",
"T2",
"T3",
"T4"
],
narrow: [
"1",
"2",
"3",
"4"
],
wide: [
"1.º trimestre",
"2.º trimestre",
"3.º trimestre",
"4.º trimestre"
]
},
"stand-alone": {
abbreviated: [
"T1",
"T2",
"T3",
"T4"
],
narrow: [
"1",
"2",
"3",
"4"
],
wide: [
"1.º trimestre",
"2.º trimestre",
"3.º trimestre",
"4.º trimestre"
]
}
},
dayPeriods: {
format: {
abbreviated: {
midnight: "meia-noite",
am: "a.m.",
noon: "meio-dia",
pm: "p.m.",
morning1: "da manhã",
afternoon1: "da tarde",
evening1: "da noite",
night1: "da madrugada"
},
narrow: {
midnight: "meia-noite",
am: "a.m.",
noon: "meio-dia",
pm: "p.m.",
morning1: "manhã",
afternoon1: "tarde",
evening1: "noite",
night1: "madrugada"
},
wide: {
midnight: "meia-noite",
am: "da manhã",
noon: "meio-dia",
pm: "da tarde",
morning1: "da manhã",
afternoon1: "da tarde",
evening1: "da noite",
night1: "da madrugada"
}
},
"stand-alone": {
abbreviated: {
midnight: "meia-noite",
am: "a.m.",
noon: "meio-dia",
pm: "p.m.",
morning1: "manhã",
afternoon1: "tarde",
evening1: "noite",
night1: "madrugada"
},
narrow: {
midnight: "meia-noite",
am: "a.m.",
noon: "meio-dia",
pm: "p.m.",
morning1: "manhã",
afternoon1: "tarde",
evening1: "noite",
night1: "madrugada"
},
wide: {
midnight: "meia-noite",
am: "manhã",
noon: "meio-dia",
pm: "tarde",
morning1: "manhã",
afternoon1: "tarde",
evening1: "noite",
night1: "madrugada"
}
}
},
eras: {
format: {
wide: {
0: "antes de Cristo",
1: "depois de Cristo",
"0-alt-variant": "antes da Era Comum",
"1-alt-variant": "Era Comum"
},
abbreviated: {
0: "a.C.",
1: "d.C.",
"0-alt-variant": "a.E.C.",
"1-alt-variant": "E.C."
},
narrow: {
0: "a.C.",
1: "d.C.",
"0-alt-variant": "a.E.C.",
"1-alt-variant": "E.C."
}
}
},
gmtFormat: "GMT{0}",
gmtZeroFormat: "GMT",
dateFields: {
era: {
wide: "era",
short: "era",
narrow: "era"
},
year: {
wide: "ano",
short: "ano",
narrow: "ano"
},
quarter: {
wide: "trimestre",
short: "trim.",
narrow: "trim."
},
month: {
wide: "mês",
short: "mês",
narrow: "mês"
},
week: {
wide: "semana",
short: "sem.",
narrow: "sem."
},
weekOfMonth: {
wide: "Week Of Month",
short: "Week Of Month",
narrow: "Week Of Month"
},
day: {
wide: "dia",
short: "dia",
narrow: "dia"
},
dayOfYear: {
wide: "Day Of Year",
short: "Day Of Year",
narrow: "Day Of Year"
},
weekday: {
wide: "dia da semana",
short: "dia da semana",
narrow: "dia da semana"
},
weekdayOfMonth: {
wide: "Weekday Of Month",
short: "Weekday Of Month",
narrow: "Weekday Of Month"
},
dayperiod: {
short: "AM/PM",
wide: "AM/PM",
narrow: "AM/PM"
},
hour: {
wide: "hora",
short: "h",
narrow: "h"
},
minute: {
wide: "minuto",
short: "min",
narrow: "min"
},
second: {
wide: "segundo",
short: "s",
narrow: "s"
},
zone: {
wide: "fuso horário",
short: "fuso horário",
narrow: "fuso horário"
}
}
},
firstDay: 1,
likelySubtags: {
pt: "pt-Latn-BR"
}
});
| antpost/antpost-client | node_modules/@progress/kendo-angular-intl/locales/pt-CH/all.js | JavaScript | mit | 93,114 |
define(function(require) {
var Checker = require("checkers/controller/Checker"),
GameBoard = require("checkers/controller/GameBoard"),
GameSpace = require("checkers/controller/GameSpace");
var instance = null;
function GameBoardUtil() {
}
var getInstance = function() {
if (instance === null) {
instance = new GameBoardUtil();
}
return instance;
}
GameBoardUtil.prototype.getValidMoves = function(checker, gameBoard, posDir) {
var validMoves = new Array();
$.merge(validMoves, this.getEmptySpaceMoves(checker, gameBoard, posDir));
$.merge(validMoves, this.getJumpMoves(checker, gameBoard, posDir));
return validMoves;
}
GameBoardUtil.prototype.getEmptySpaceMoves = function(checker, gameBoard, posDir) {
var emptySpaceMoves = new Array();
var row = checker.getRow() + posDir;
// Checks left move
if (this.isValidMove(row, checker.getColumn() - 1)) {
var gameSpace = gameBoard.getGameSpace(row, checker.getColumn() - 1)
if (gameSpace.isEmpty()) {
emptySpaceMoves.push(gameSpace);
}
}
// Checks right move
if (this.isValidMove(row, checker.getColumn() + 1)) {
var gameSpace = gameBoard.getGameSpace(row, checker.getColumn() + 1);
if (gameSpace.isEmpty()) {
emptySpaceMoves.push(gameSpace);
}
}
if (checker.isKing()) {
var kRow = checker.getRow() - posDir;
// Checks left move
if (this.isValidMove(kRow, checker.getColumn() - 1)) {
var gameSpace = gameBoard.getGameSpace(kRow, checker.getColumn() - 1)
if (gameSpace.isEmpty()) {
emptySpaceMoves.push(gameSpace);
}
}
// Checks right move
if (this.isValidMove(kRow, checker.getColumn() + 1)) {
var gameSpace = gameBoard.getGameSpace(kRow, checker.getColumn() + 1);
if (gameSpace.isEmpty()) {
emptySpaceMoves.push(gameSpace);
}
}
}
return emptySpaceMoves;
}
GameBoardUtil.prototype.isValidMove = function(row, column) {
if (row < 0 || row >= GameBoard.NUMSQUARES || column < 0 || column >= GameBoard.NUMSQUARES) {
return false;
}
return true;
}
GameBoardUtil.prototype.getJumpMoves = function(checker, gameBoard, posDir) {
var jumpMoves = new Array();
var row = checker.getRow() + posDir * 2;
// Checks left jump move
if (this.isValidMove(row, checker.getColumn() - 2)) {
var gameSpace = gameBoard.getGameSpace(row, checker.getColumn() - 2);
if (gameSpace.isEmpty()) {
var jumpedGameSpace = gameBoard.getGameSpace(row - posDir, checker.getColumn() - 1);
if (!jumpedGameSpace.isEmpty() && jumpedGameSpace.getChecker().getPlayerId() != checker.getPlayerId()) {
jumpMoves.push(gameSpace);
}
}
}
// Checks right jump move
if (this.isValidMove(row, checker.getColumn() + 2)) {
var gameSpace = gameBoard.getGameSpace(row, checker.getColumn() + 2);
if (gameSpace.isEmpty()) {
var jumpedGameSpace = gameBoard.getGameSpace(row - posDir, checker.getColumn() + 1);
if (!jumpedGameSpace.isEmpty() && jumpedGameSpace.getChecker().getPlayerId() != checker.getPlayerId()) {
jumpMoves.push(gameSpace);
}
}
}
if (checker.isKing()) {
// Checks left jump move
var kRow = checker.getRow() - posDir * 2;
if (this.isValidMove(kRow, checker.getColumn() - 2)) {
var gameSpace = gameBoard.getGameSpace(kRow, checker.getColumn() - 2);
if (gameSpace.isEmpty()) {
var jumpedGameSpace = gameBoard.getGameSpace(kRow + posDir, checker.getColumn() - 1);
if (!jumpedGameSpace.isEmpty() && jumpedGameSpace.getChecker().getPlayerId() != checker.getPlayerId()) {
jumpMoves.push(gameSpace);
}
}
}
// Checks right jump move
if (this.isValidMove(kRow, checker.getColumn() + 2)) {
var gameSpace = gameBoard.getGameSpace(kRow, checker.getColumn() + 2);
if (gameSpace.isEmpty()) {
var jumpedGameSpace = gameBoard.getGameSpace(kRow + posDir, checker.getColumn() + 1);
if (!jumpedGameSpace.isEmpty() && jumpedGameSpace.getChecker().getPlayerId() != checker.getPlayerId()) {
jumpMoves.push(gameSpace);
}
}
}
}
return jumpMoves;
}
return ({getInstance:getInstance});
}); | RobStrader/Robs-Arcade | js/checkers/util/GameBoardUtil.js | JavaScript | mit | 5,153 |
import { LOCAL_STORAGE_REMOVE_ITEM, LOCAL_STORAGE_SET_ITEM } from './actionTypes'
import createMiddleware from './middleware'
describe('middleware', () => {
let removeItem
let setItem
let middleware
let next
let store
beforeEach(() => {
removeItem = jest.fn()
setItem = jest.fn()
middleware = createMiddleware({
removeItem,
setItem,
})
next = jest.fn()
store = {
dispatch: jest.fn(),
getState: jest.fn(),
}
})
it('calls next on dummy actionType', () => {
const action = {
type: 'dummyType',
payload: {
key: 'key',
},
}
middleware(store)(next)(action)
expect(next.mock.calls.length).toBe(1)
})
it(`calls removeItem on ${LOCAL_STORAGE_REMOVE_ITEM}`, () => {
const action = {
type: LOCAL_STORAGE_REMOVE_ITEM,
payload: {
key: 'key',
},
}
middleware(store)(next)(action)
expect(removeItem.mock.calls.length).toBe(1)
})
it(`calls removeItem on ${LOCAL_STORAGE_SET_ITEM}`, () => {
const action = {
type: LOCAL_STORAGE_SET_ITEM,
payload: {
key: 'key',
value: 'value',
},
}
middleware(store)(next)(action)
expect(setItem.mock.calls.length).toBe(1)
})
})
| fredrikolovsson/redux-module-local-storage | src/middleware.test.js | JavaScript | mit | 1,262 |
jQuery.each(param_obj, function (index, value) {
if (!isNaN(value)) {
param_obj[index] = parseInt(value);
}
});
function Portfolio_Gallery_Full_Height(id) {
var _this = this;
_this.container = jQuery('#' + id + '.view-full-height');
_this.hasLoading = _this.container.data("show-loading") == "on";
_this.optionsBlock = _this.container.parent().find('div[id^="huge_it_portfolio_options_"]');
_this.filtersBlock = _this.container.parent().find('div[id^="huge_it_portfolio_filters_"]');
_this.content = _this.container.parent();
_this.element = _this.container.find('.portelement');
_this.defaultBlockHeight = param_obj.ht_view1_block_height;
_this.defaultBlockWidth = param_obj.ht_view1_block_width;
_this.optionSets = _this.optionsBlock.find('.option-set');
_this.optionLinks = _this.optionSets.find('a');
_this.sortBy = _this.optionsBlock.find('#sort-by');
_this.filterButton = _this.filtersBlock.find('ul li');
if (_this.container.data('show-center') == 'on' && ( ( !_this.content.hasClass('sortingActive') && !_this.content.hasClass('filteringActive') )
|| ( _this.optionsBlock.data('sorting-position') == 'top' && _this.filtersBlock.data('filtering-position') == 'top' ) ||
( _this.optionsBlock.data('sorting-position') == 'top' && _this.filtersBlock.data('filtering-position') == '' ) || ( _this.optionsBlock.data('sorting-position') == '' && _this.filtersBlock.data('filtering-position') == 'top' ) )) {
_this.isCentered = _this.container.data("show-center") == "on";
}
_this.documentReady = function () {
_this.container.hugeitmicro({
itemSelector: _this.element,
masonry: {
columnWidth: _this.defaultBlockWidth + 20 + param_obj.ht_view1_element_border_width * 2
},
masonryHorizontal: {
rowHeight: 300 + 20
},
cellsByRow: {
columnWidth: 300 + 20,
rowHeight: 240
},
cellsByColumn: {
columnWidth: 300 + 20,
rowHeight: 240
},
getSortData: {
symbol: function ($elem) {
return $elem.attr('data-symbol');
},
category: function ($elem) {
return $elem.attr('data-category');
},
number: function ($elem) {
return parseInt($elem.find('.number').text(), 10);
},
weight: function ($elem) {
return parseFloat($elem.find('.weight').text().replace(/[\(\)]/g, ''));
},
id: function ($elem) {
return $elem.find('.id').text();
}
}
});
setInterval(function(){
_this.container.hugeitmicro('reLayout');
});
};
_this.manageLoading = function () {
if (_this.hasLoading) {
_this.container.css({'opacity': 1});
_this.optionsBlock.css({'opacity': 1});
_this.filtersBlock.css({'opacity': 1});
_this.content.find('div[id^="huge-it-container-loading-overlay_"]').css('display', 'none');
}
};
_this.showCenter = function () {
if (_this.isCentered) {
var count = _this.element.length;
var elementwidth = _this.defaultBlockWidth + 10 + param_obj.ht_view1_element_border_width * 2;
var enterycontent = _this.content.width();
var whole = ~~(enterycontent / (elementwidth));
if (whole > count) whole = count;
if (whole == 0) {
return false;
}
else {
var sectionwidth = whole * elementwidth + (whole - 1) * 20;
}
_this.container.width(sectionwidth).css({
"margin": "0px auto",
"overflow": "hidden"
});
console.log(elementwidth + " " + enterycontent + " " + whole + " " + sectionwidth);
}
};
_this.addEventListeners = function () {
_this.optionLinks.on('click', _this.optionsClick);
_this.optionsBlock.find('#shuffle a').on('click',_this.randomClick);
_this.filterButton.on('click', _this.filtersClick);
jQuery(window).resize(_this.resizeEvent);
};
_this.resizeEvent = function(){
_this.container.hugeitmicro('reLayout');
_this.showCenter();
};
_this.optionsClick = function () {
var $this = jQuery(this);
if ($this.hasClass('selected')) {
return false;
}
var $optionSet = $this.parents('.option-set');
$optionSet.find('.selected').removeClass('selected');
$this.addClass('selected');
var options = {},
key = $optionSet.attr('data-option-key'),
value = $this.attr('data-option-value');
value = value === 'false' ? false : value;
options[key] = value;
if (key === 'layoutMode' && typeof changeLayoutMode === 'function') {
changeLayoutMode($this, options)
} else {
_this.container.hugeitmicro(options);
}
return false;
};
_this.randomClick = function () {
_this.container.hugeitmicro('shuffle');
_this.sortBy.find('.selected').removeClass('selected');
_this.sortBy.find('[data-option-value="random"]').addClass('selected');
return false;
};
_this.filtersClick = function () {
_this.filterButton.each(function () {
jQuery(this).removeClass('active');
});
jQuery(this).addClass('active');
// get filter value from option value
var filterValue = jQuery(this).attr('rel');
// use filterFn if matches value
_this.container.hugeitmicro({filter: filterValue});
};
_this.init = function () {
_this.showCenter();
jQuery(window).load(_this.manageLoading);
_this.documentReady();
_this.addEventListeners();
};
this.init();
}
var portfolios = [];
jQuery(document).ready(function () {
jQuery(".huge_it_portfolio_container.view-full-height").each(function (i) {
var id = jQuery(this).attr('id');
portfolios[i] = new Portfolio_Gallery_Full_Height(id);
});
}); | rahul121290/php | wp-content/plugins/portfolio-gallery/assets/js/view-full-height.js | JavaScript | mit | 6,558 |
import s from './Callouts.css';
import React, { PropTypes } from 'react';
import numbro from 'numbro';
function diversityAtParityOrGreater(conf) {
return conf.diversityPercentage >= 50;
}
function confFromCurrentYear(conf) {
return conf.year == (new Date()).getFullYear();
}
function diversityAccumulator(accumulator, conf) {
return accumulator + conf.diversityPercentage;
}
function diversitySorter(confA, confB) {
if (confA.diversityPercentage < confB.diversityPercentage) {
return 1;
}
if (confA.diversityPercentage > confB.diversityPercentage) {
return -1;
}
return 0;
}
class Callouts extends React.Component {
constructor(props) {
super(props);
this.currentYearConfs = props.confs.filter(confFromCurrentYear);
this.state = {
confs: props.confs,
bestPerformer: props.confs.sort(diversitySorter)[0],
numberOfConfs: props.confs.length,
numberOfConfsAtParityOrGreater: props.confs.filter(diversityAtParityOrGreater).length,
averageDiversity: props.confs.reduce(diversityAccumulator, 0) / props.confs.length,
averageDiversityCurrentYear: this.currentYearConfs.reduce(diversityAccumulator, 0) / this.currentYearConfs.length
};
}
render() {
return (
<div className={s.container}>
<div className="row">
<div className="col-sm-2">
<div className={s.title}>Conferences<br/>tracked</div>
<div className={s.pop}>{this.state.numberOfConfs}</div>
</div>
<div className="col-sm-2">
<div className={s.title}>Best<br/>performer</div>
<div className={s.body}><strong>{this.state.bestPerformer.name} ({this.state.bestPerformer.year})</strong><br/>{numbro(this.state.bestPerformer.diversityPercentage).format('0')}%</div>
</div>
<div className="col-sm-2">
<div className={s.title}>Biggest recent improver</div>
<div className={s.body}><strong>1st Conf</strong><br/>+36%<br/>2016 -> 2017</div>
</div>
<div className="col-sm-2" id={s.nbrConfAtParity}>
<div className={s.title}>#confs >= 50%<br/>diversity</div>
<div className={s.pop}>{this.state.numberOfConfsAtParityOrGreater}</div>
</div>
<div className="col-sm-2">
<div className={s.title}>Average<br/>f:m%</div>
<div className={s.pop}>{numbro(this.state.averageDiversity).format('0')}%</div>
</div>
<div className="col-sm-2">
<div className={s.title}>Average<br/>f:m% (2017)</div>
<div className={s.pop}>{numbro(this.state.averageDiversityCurrentYear).format('0')}%</div>
</div>
</div>
</div>
);
}
}
export default Callouts;
| andeemarks/conf-gen-div-react | components/Callouts/Callouts.js | JavaScript | mit | 2,762 |
/*! simpler-sidebar v1.4.9 (https://github.com/dcdeiv/simpler-sidebar)
** Copyright (c) 2015 - 2016 Davide Di Criscito
** Dual licensed under MIT and GPL-2.0
*/
( function( $ ) {
$.fn.simplerSidebar = function( options ) {
var cfg = $.extend( true, $.fn.simplerSidebar.settings, options );
return this.each( function() {
var align, sbw, ssbInit, ssbStyle, maskInit, maskStyle,
attr = cfg.attr,
$sidebar = $( this ),
$opener = $( cfg.opener ),
$links = cfg.sidebar.closingLinks,
duration = cfg.animation.duration,
sbMaxW = cfg.sidebar.width,
gap = cfg.sidebar.gap,
winMaxW = sbMaxW + gap,
w = $( window ).width(),
animationStart = {},
animationReset = {},
hiddenFlow = function() {
$( "body, html" ).css( "overflow", "hidden" );
},
autoFlow = function() {
$( "body, html" ).css( "overflow", "auto" );
},
activate = {
duration: duration,
easing: cfg.animation.easing,
complete: hiddenFlow
},
deactivate = {
duration: duration,
easing: cfg.animation.easing,
complete: autoFlow
},
animateOpen = function() {
$sidebar
.animate( animationStart, activate )
.attr( "data-" + attr, "active" );
$mask.fadeIn( duration );
},
animateClose = function() {
$sidebar
.animate( animationReset, deactivate )
.attr( "data-" + attr, "disabled" );
$mask.fadeOut( duration );
},
closeSidebar = function() {
var isWhat = $sidebar.attr( "data-" + attr ),
csbw = $sidebar.width();
animationReset[ align ] = -csbw;
if ( isWhat === "active" ) {
animateClose();
}
},
$mask = $( "<div>" ).attr( "data-" + attr, "mask" );
//Checking sidebar align
if ( [ undefined, "right" ].indexOf( cfg.sidebar.align ) !== -1 ) {
align = "right";
} else if ( cfg.sidebar.align === "left" ) {
align = "left";
} else {
console.log( "ERR sidebar.align: you typed \"" + cfg.sidebar.align + "\". You should choose between \"right\" or \"left\"." );
}
//Sidebar style
if ( w < winMaxW ) {
sbw = w - gap;
} else {
sbw = sbMaxW;
}
ssbInit = {
position: "fixed",
top: cfg.top,
bottom: 0,
width: sbw
};
ssbInit[ align ] = -sbw;
animationStart[ align ] = 0;
ssbStyle = $.extend( true, ssbInit, cfg.sidebar.css );
$sidebar.css( ssbStyle )
.attr( "data-" + attr, "disabled" );
//Mask style
maskInit = {
position: "fixed",
top: cfg.top,
right: 0,
bottom: 0,
left: 0,
zIndex: cfg.sidebar.css.zIndex - 1,
display: "none"
};
maskStyle = $.extend( true, maskInit, cfg.mask.css );
//Appending Mask if mask.display is true
if ( [ true, "true", false, "false" ].indexOf( cfg.mask.display) !== -1 ) {
if ( [ true, "true" ].indexOf( cfg.mask.display ) !== -1 ) {
$mask.appendTo( "body" ).css( maskStyle );
}
} else {
console.log( "ERR mask.display: you typed \"" + cfg.mask.display + "\". You should choose between true or false." );
}
//Opening and closing the Sidebar when $opener is clicked
$opener.click( function() {
var isWhat = $sidebar.attr( "data-" + attr ),
csbw = $sidebar.width();
animationReset[ align ] = -csbw;
if ( isWhat === "disabled" ) {
animateOpen();
} else if ( isWhat === "active" ) {
animateClose();
}
});
//Closing Sidebar when the mask is clicked
$mask.click( closeSidebar );
//Closing Sidebar when a link inside of it is clicked
$sidebar.on( "click", $links, closeSidebar );
//Adjusting width;
$( window ).resize( function() {
var rsbw, update,
isWhat = $sidebar.attr( "data-" + attr ),
nw = $( window ).width();
if ( nw < winMaxW ) {
rsbw = nw - gap;
} else {
rsbw = sbMaxW;
}
update = {
width: rsbw
};
if ( isWhat === "disabled" ) {
update[ align ] = -rsbw;
$sidebar.css( update );
} else if ( isWhat === "active" ) {
$sidebar.css( update );
}
});
});
};
$.fn.simplerSidebar.settings = {
attr: "simplersidebar",
top: 0,
animation: {
duration: 500,
easing: "swing"
},
sidebar: {
width: 300,
gap: 64,
closingLinks: "a",
css: {
zIndex: 3000
}
},
mask: {
display: true,
css: {
backgroundColor: "black",
opacity: 0.5,
filter: "Alpha(opacity=50)"
}
}
};
} )( jQuery );
| matrharr/first_aid | bower_components/simpler-sidebar/dist/jquery.simpler-sidebar.js | JavaScript | mit | 4,289 |
// Fill in topbar details.
$('header .right').append(Handlebars.templates.userTopbar(user));
// Fill in sidebar details.
user.created_at = moment(user.created_at).format('MMM DD, YYYY');
var userStars = {user: user, stars: stars};
$('aside').prepend(Handlebars.templates.userSidebar(userStars));
// Populate the organizations list on the sidebar.
var orgList = $('aside #organizations');
orgs.forEach(function (org) {
orgList.append(Handlebars.templates.org(org));
});
// Populate the repos list in the main page.
var repoList = $('section.main .repo-list');
repos = _.sortBy( repos, 'updated_at' ).reverse();
repos.forEach(function (repo) {
repo.updated_at = moment(repo.updated_at).fromNow();
repoList.append(Handlebars.templates.repo(repo));
});
| bholben/GitHub | app/scripts/main.js | JavaScript | mit | 760 |
import { faker } from 'ember-cli-mirage';
import lodash from 'npm:lodash';
export const CONTAINER_MEMORY = 8023089152;
export function getPorts(isContainer=false) {
let ports = [];
for (let j = 1; j <= faker.random.number({ max: 3 }); j++) {
let obj = {
name: faker.hacker.noun(),
protocol: 'TCP',
};
obj[isContainer ? 'hostPort': 'port'] = faker.random.number();
obj[isContainer ? 'containerPort': 'targetPort'] = faker.random.number();
ports.push(obj);
}
return ports;
}
export function getLabels() {
let labels = {};
for (let j = 1; j <= faker.random.number({ max: 3 }); j++) {
labels[faker.hacker.verb()] = faker.hacker.noun();
}
return labels;
}
export function getSpec(isContainer=false) {
let containers = [];
for (let j = 1; j <= faker.random.number({ min: 1, max: 5 }); j++) {
const name = faker.hacker.verb();
containers.push({
name,
image: `${name}:v${j / 2}`,
ports: getPorts(isContainer),
terminationMessagePath: '/dev/termination-log',
imagePullPolicy: faker.random.arrayElement(['Always', 'Never', 'IfNotPresent'])
});
}
return {
containers,
restartPolicy: faker.random.arrayElement(['Always', 'OnFailure', 'Never']),
terminationGracePeriodSeconds: faker.random.number(),
dnsPolicy: faker.random.arrayElement(['ClusterFirst', 'Default']),
nodeName: faker.internet.ip(),
hostNetwork: faker.random.boolean()
};
}
export function getId(kind, index) {
return `${kind.toLowerCase()}-${index}`;
}
export function getMetadata(kind='Node', index=0, namespace=null) {
let name = getId(kind, index),
creationTimestamp = faker.date.recent(),
labels = getLabels();
if (!namespace && kind !== 'Node') {
namespace = faker.random.arrayElement(['default', 'kube-system', 'app-namespace']);
}
return { name, namespace, creationTimestamp, labels };
}
export function getCAdvisorContainerSpec() {
return {
creation_time: faker.date.recent(),
has_cpu: true,
has_memory: true,
has_filesystem: true,
memory: {
limit: CONTAINER_MEMORY
}
};
}
export function getStat(total, timestamp, cpus=4) {
let per_cpu_usage = [],
maxPerCpu = Math.round(total / cpus);
for (let i = 1; i < cpus; i++) {
per_cpu_usage.push(faker.random.number({ max: maxPerCpu }));
}
let cpu = { usage: { total, per_cpu_usage } },
memory = { usage: faker.random.number({ max: CONTAINER_MEMORY }) },
filesystems = [],
devices = [
'/dev/sda1',
'docker-8:1-7083173-pool',
'/dev/mapper/docker-8:1-7083173-8f138ecc6e8dc81a08b9fee2f256415e96de06a8eb4ab247bde008932fc53c3a'
];
lodash.each(devices, (device) => {
let min = 1024,
max = 1024 * 20,
capacity = faker.random.number({ min, max }),
usage = faker.random.number({ min, max: capacity });
filesystems.push({ device, capacity, usage });
});
return { timestamp, cpu, memory, filesystem: filesystems };
}
| holandes22/kube-admin | app/mirage/factories/fakers.js | JavaScript | mit | 3,027 |
module.exports = function () {
return {
templateUrl : './shared/partials/footer/directives/footer.html',
controller: require('./footerCtrl'),
restrict: 'E',
scope: {}
};
};
| Arodang/Moroja | app/shared/partials/footer/directives/footerDirective.js | JavaScript | mit | 214 |
import React from 'react';
import PropTypes from 'prop-types';
import ColumnChart from './columnChart';
import Tooltip from './../tooltip/tooltip';
import {dateFormats} from './../../utils/displayFormats';
import './columnWidget.css';
const ColumnWidget = ({
chartTitle,
chartDescription,
chartUpdatedDate,
series,
xAxis,
yAxis,
viewport,
displayHighContrast,
}) => {
return (
<article role="article" className="D_widget">
<header>
{chartDescription && <div className="D_CW_infoContainer"><Tooltip text={chartDescription} viewport={viewport} /></div>}
<h1 className="highcharts-title">{chartTitle}</h1>
<span className="highcharts-subtitle">Last updated at <time dateTime={dateFormats.dateTime(chartUpdatedDate)}>{dateFormats.dayMonthYear(chartUpdatedDate)}</time></span>
</header>
<section>
<ColumnChart series={series}
xAxis={xAxis}
yAxis={yAxis}
chartDescription={chartDescription}
displayHighContrast={displayHighContrast} />
</section>
</article>
)
};
if (__DEV__) {
ColumnWidget.propTypes = {
chartTitle: PropTypes.string,
chartDescription: PropTypes.string,
chartUpdatedDate: PropTypes.string,
series: PropTypes.arrayOf(PropTypes.shape({
name: PropTypes.string.isRequired,
units: PropTypes.string,
color: PropTypes.string,
data: PropTypes.array.isRequired,
})).isRequired,
xAxis: PropTypes.arrayOf(PropTypes.shape({
categories: PropTypes.array,
})),
yAxis: PropTypes.arrayOf(PropTypes.shape({
title: PropTypes.object,
})),
viewport: PropTypes.oneOf(['sm', 'md', 'lg', 'xl']),
displayHighContrast: PropTypes.bool,
};
}
export default ColumnWidget;
| govau/datavizkit | src/components/columnWidget/columnWidget.js | JavaScript | mit | 1,815 |
import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import App from './containers/App';
import configureStore from './store/configureStore';
import 'todomvc-app-css/index.css';
const store = configureStore();
render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('layout')
);
| demones/react-guide | examples/react-redux-example/app/todomvc/index.js | JavaScript | mit | 363 |
//
// window.onload = function() {
// var data = {username:'52200', password:'123', remember:52200};
// fetch('/api/users/getUser?id=1').then(function(res) {
// console.log("请求的数据是", res);
// if (res.ok) {
// alert('Submitted!');
// } else {
// alert('Error!');
// }
// }).then(function(body) {
// console.log("请求body的数据是", body);
// // body
// });
// }; | Hitheworld/HelloKoa2 | public/javascript/data.js | JavaScript | mit | 466 |
Meteor.methods({
addAllUserToRoom(rid, activeUsersOnly = false) {
check (rid, String);
check (activeUsersOnly, Boolean);
if (RocketChat.authz.hasRole(this.userId, 'admin') === true) {
const userCount = RocketChat.models.Users.find().count();
if (userCount > RocketChat.settings.get('API_User_Limit')) {
throw new Meteor.Error('error-user-limit-exceeded', 'User Limit Exceeded', {
method: 'addAllToRoom',
});
}
const room = RocketChat.models.Rooms.findOneById(rid);
if (room == null) {
throw new Meteor.Error('error-invalid-room', 'Invalid room', {
method: 'addAllToRoom',
});
}
const userFilter = {};
if (activeUsersOnly === true) {
userFilter.active = true;
}
const users = RocketChat.models.Users.find(userFilter).fetch();
const now = new Date();
users.forEach(function(user) {
const subscription = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(rid, user._id);
if (subscription != null) {
return;
}
RocketChat.callbacks.run('beforeJoinRoom', user, room);
RocketChat.models.Subscriptions.createWithRoomAndUser(room, user, {
ts: now,
open: true,
alert: true,
unread: 1,
userMentions: 1,
groupMentions: 0,
});
RocketChat.models.Messages.createUserJoinWithRoomIdAndUser(rid, user, {
ts: now,
});
Meteor.defer(function() {});
return RocketChat.callbacks.run('afterJoinRoom', user, room);
});
return true;
} else {
throw (new Meteor.Error(403, 'Access to Method Forbidden', {
method: 'addAllToRoom',
}));
}
},
});
| flaviogrossi/Rocket.Chat | server/methods/addAllUserToRoom.js | JavaScript | mit | 1,600 |
const HttpStatus = require('http-status-codes');
const build = status => {
return (ctx, message) => {
ctx.status = status
ctx.body = message || {message: HttpStatus.getStatusText(status)}
return ctx
}
}
module.exports = {
accepted: build(HttpStatus.ACCEPTED), // 202
badGateway: build(HttpStatus.BAD_GATEWAY), // 502
badRequest: build(HttpStatus.BAD_REQUEST), // 400
conflict: build(HttpStatus.CONFLICT), // 409
continue: build(HttpStatus.CONTINUE), // 100
created: build(HttpStatus.CREATED), // 201
expectationFailed: build(HttpStatus.EXPECTATION_FAILED), // 417
failedDependency: build(HttpStatus.FAILED_DEPENDENCY), // 424
forbidden: build(HttpStatus.FORBIDDEN), // 403
gatewayTimeout: build(HttpStatus.GATEWAY_TIMEOUT), // 504
gone: build(HttpStatus.GONE), // 410
httpVersionNotSupported: build(HttpStatus.HTTP_VERSION_NOT_SUPPORTED), // 505
imATeapot: build(HttpStatus.IM_A_TEAPOT), // 418
insufficientSpaceOnResource: build(HttpStatus.INSUFFICIENT_SPACE_ON_RESOURCE), // 419
insufficientStorage: build(HttpStatus.INSUFFICIENT_STORAGE), // 507
internalServerError: build(HttpStatus.INTERNAL_SERVER_ERROR), // 500
lengthRequired: build(HttpStatus.LENGTH_REQUIRED), // 411
locked: build(HttpStatus.LOCKED), // 423
methodFailure: build(HttpStatus.METHOD_FAILURE), // 420
methodNotAllowed: build(HttpStatus.METHOD_NOT_ALLOWED), // 405
movedPermanently: build(HttpStatus.MOVED_PERMANENTLY), // 301
movedTemporarily: build(HttpStatus.MOVED_TEMPORARILY), // 302
multiStatus: build(HttpStatus.MULTI_STATUS), // 207
multipleChoices: build(HttpStatus.MULTIPLE_CHOICES), // 300
networkAuthenticationRequired: build(HttpStatus.NETWORK_AUTHENTICATION_REQUIRED), // 511
noContent: build(HttpStatus.NO_CONTENT), // 204
nonAuthoritativeInformation: build(HttpStatus.NON_AUTHORITATIVE_INFORMATION), // 203
notAcceptable: build(HttpStatus.NOT_ACCEPTABLE), // 406
notFound: build(HttpStatus.NOT_FOUND), // 404
notImplemented: build(HttpStatus.NOT_IMPLEMENTED), // 501
notModified: build(HttpStatus.NOT_MODIFIED), // 304
ok: build(HttpStatus.OK), // 200
partialContent: build(HttpStatus.PARTIAL_CONTENT), // 206
paymentRequired: build(HttpStatus.PAYMENT_REQUIRED), // 402
permanentRedirect: build(HttpStatus.PERMANENT_REDIRECT), // 308
preconditionFailed: build(HttpStatus.PRECONDITION_FAILED), // 412
preconditionRequired: build(HttpStatus.PRECONDITION_REQUIRED), // 428
processing: build(HttpStatus.PROCESSING), // 102
proxyAuthenticationRequired: build(HttpStatus.PROXY_AUTHENTICATION_REQUIRED), // 407
requestHeaderFieldsTooLarge: build(HttpStatus.REQUEST_HEADER_FIELDS_TOO_LARGE), // 431
requestTimeout: build(HttpStatus.REQUEST_TIMEOUT), // 408
requestTooLong: build(HttpStatus.REQUEST_TOO_LONG), // 413
requestUriTooLong: build(HttpStatus.REQUEST_URI_TOO_LONG), // 414
requestedRangeNotSatisfiable: build(HttpStatus.REQUESTED_RANGE_NOT_SATISFIABLE), // 416
resetContent: build(HttpStatus.RESET_CONTENT), // 205
seeOther: build(HttpStatus.SEE_OTHER), // 303
serviceUnavailable: build(HttpStatus.SERVICE_UNAVAILABLE), // 503
switchingProtocols: build(HttpStatus.SWITCHING_PROTOCOLS), // 101
temporaryRedirect: build(HttpStatus.TEMPORARY_REDIRECT), // 307
tooManyRequests: build(HttpStatus.TOO_MANY_REQUESTS), // 429
unauthorized: build(HttpStatus.UNAUTHORIZED), // 401
unprocessableEntity: build(HttpStatus.UNPROCESSABLE_ENTITY), // 422
unsupportedMediaType: build(HttpStatus.UNSUPPORTED_MEDIA_TYPE), // 415
useProxy: build(HttpStatus.USE_PROXY) // 305
} | lohanbodevan/http-responses | index.js | JavaScript | mit | 3,695 |
module.exports = function verify(check) {
if (typeof check !== 'object') {
throw new Error('check is not an object');
}
var errors = [];
Object.keys(check).forEach(_verify, check);
if (errors.length > 0) {
throw new Error('Health checks failed: '+ errors.join(', '));
}
return true;
function _verify(key, i) {
if (this[key] === false || this[key] instanceof Error) {
errors.push(key);
}
else if (this[key] && typeof this[key] === 'object' && !Array.isArray(this[key])) {
Object.keys(this[key]).forEach(_verify, this[key]);
}
}
};
| super-useful/su-healthcheck | lib/verify.js | JavaScript | mit | 644 |
/* globals describe, beforeEach, it, expect, inject, vehicles, VehicleMock */
describe("Vehicles Factory:", function() {
'use strict';
var $httpBackend,
vehicles,
request,
Showcase;
// Load the main module
beforeEach(module('sc'));
beforeEach(inject(function($injector, _vehicles_, _Showcase_) {
$httpBackend = $injector.get('$httpBackend');
vehicles = _vehicles_;
Showcase = _Showcase_;
request = $httpBackend.whenGET(Showcase.API + 'vehicles').respond(200, angular.copy(VehicleMock.ALL));
$httpBackend.whenGET(Showcase.API + 'vehicles/1').respond(200, VehicleMock.DETAIL);
$httpBackend.whenGET(Showcase.API + 'vehicles/compare/1').respond(200, angular.copy(VehicleMock.COMPARE));
}));
it("should return 4 vehicles", function() {
vehicles.getAll().then(function(response) {
expect(response.length).toEqual(4);
});
$httpBackend.flush();
});
it("should return Toyota as the first Brand", function() {
vehicles.getAll().then(function(response) {
expect(response[0].brand).toEqual('Toyota');
});
$httpBackend.flush();
});
it("should return a 404 error", function() {
request.respond(404, {error: true});
$httpBackend.expectGET(Showcase.API + 'vehicles');
vehicles.getAll().catch(function(error) {
expect(error.error).toBe(true);
});
$httpBackend.flush();
});
it("should return vehicle detail", function() {
vehicles.get(1).then(function(response) {
expect(response.model).toEqual('Avalon');
});
$httpBackend.flush();
});
it("should compare 3 vehicles", function() {
vehicles.compare(1,2,3).then(function(response) {
expect(response.length).toEqual(2);
});
$httpBackend.flush();
});
}); | jandrade/showcase | test/unit/vehicles/factories/vehicles.factory.spec.js | JavaScript | mit | 1,683 |
import { createGlobalStyle } from 'styled-components';
export const GlobalStyle = createGlobalStyle`
body {
margin: 0;
font-family: 'Montserrat', sans-serif;
}
* {
box-sizing: border-box;
}
`;
| hakonhk/vaerhona | ui/global-style.js | JavaScript | mit | 215 |
import React, { Component, PropTypes } from 'react'
import cx from 'classnames'
import { Icon } from '../icon'
import { capitalize } from 'utils/string'
import './button.view.styl'
export class Button extends Component {
static propTypes = {
className: PropTypes.string,
children: PropTypes.oneOfType([
PropTypes.element,
PropTypes.string
]),
icon: PropTypes.string,
type: PropTypes.oneOf(['primary', 'text', 'danger', 'normal']),
htmlType: PropTypes.oneOf(['submit', 'button', 'reset']),
size: PropTypes.oneOf(['small', 'normal', 'large']),
block: PropTypes.bool,
loading: PropTypes.bool,
disabled: PropTypes.bool,
ghost: PropTypes.bool,
onClick: PropTypes.func
}
static defaultProps = {
type: 'primary',
size: 'normal',
onClick: () => {}
}
getRootClassNames () {
const {
className,
type,
size,
block,
loading,
disabled,
ghost
} = this.props
return cx(
'button',
`button${capitalize(type)}`,
`size${capitalize(size)}`,
{ isBlock: block },
{ isGhost: ghost },
{ isLoading: loading },
{ isDisabled: disabled },
className
)
}
handleClick = (e) => {
const {
loading,
disabled,
onClick
} = this.props
if (loading || disabled) {
e.preventDefault()
return null
}
if (onClick) {
onClick(e)
}
}
render () {
const {
icon,
htmlType,
// loading,
children
} = this.props
const iconName = icon // @OLD: loading ? 'loading' : icon
const iconNode = iconName ? <Icon name={iconName} /> : null
return (
<button
className={this.getRootClassNames()}
onClick={this.handleClick}
type={htmlType || 'button'}
>
{iconNode}{children}
</button>
)
}
}
| seccom/kpass | web/src/uis/generics/button/button.view.js | JavaScript | mit | 1,895 |
'use strict';
var os = require('os');
// expose our config directly to our application using module.exports
module.exports = {
'twitterAuth' : {
'consumerKey' : process.env.TWITTER_CONSUMER_KEY || 'unknown',
'consumerSecret' : process.env.TWITTER_CONSUMER_SECRET || 'unknown' ,
'callbackURL' : 'http://' + os.hostname() + '/auth/twitter/callback'
}
};
| codefellows/oaa | config/auth.js | JavaScript | mit | 380 |
var mySteal = require('@steal');
if (typeof window !== "undefined" && window.assert) {
assert.ok(mySteal.loader == steal.loader, "The steal's loader is the loader");
done();
} else {
console.log("Systems", mySteal.loader == steal.loader);
}
| stealjs/steal | test/current-steal/main.js | JavaScript | mit | 245 |
define(function(require, exports, module) {
require('jquery.cycle2');
exports.run = function() {
$('.homepage-feature').cycle({
fx:"scrollHorz",
slides: "> a, > img",
log: "false",
pauseOnHover: "true"
});
$('.live-rating-course').find('.media-body').hover(function() {
$( this ).find( ".rating" ).show();
}, function() {
$( this ).find( ".rating" ).hide();
});
};
}); | smeagonline-developers/OnlineEducationPlatform---SMEAGonline | src/Topxia/WebBundle/Resources/public/js/controller/live-course/index.js | JavaScript | mit | 467 |
import React from 'react';
import Slider from 'material-ui/Slider';
/**
* The `defaultValue` property sets the initial position of the slider.
* The slider appearance changes when not at the starting position.
*/
const SliderTransparency = (props) => (
<Slider defaultValue={props.transparency} onChange={props.update} sliderStyle={{margin:'auto',pointerEvents:'all'}} axis='y' style={{height:'400px', paddingTop:"30px"}}
data-tip={`Opacity`}
data-offset="{'top': -30}"
/>
);
export default SliderTransparency;
| ekatzenstein/three.js-live | src/components/SliderTransparency.js | JavaScript | mit | 543 |
import { Transform } from './transform.js';
/**
* Calculate the transform for a Cornerstone enabled element
*
* @param {EnabledElement} enabledElement The Cornerstone Enabled Element
* @param {Number} [scale] The viewport scale
* @return {Transform} The current transform
*/
export default function (enabledElement, scale) {
const transform = new Transform();
transform.translate(enabledElement.canvas.width / 2, enabledElement.canvas.height / 2);
// Apply the rotation before scaling for non square pixels
const angle = enabledElement.viewport.rotation;
if (angle !== 0) {
transform.rotate(angle * Math.PI / 180);
}
// Apply the scale
let widthScale = enabledElement.viewport.scale;
let heightScale = enabledElement.viewport.scale;
if (enabledElement.image.rowPixelSpacing < enabledElement.image.columnPixelSpacing) {
widthScale *= (enabledElement.image.columnPixelSpacing / enabledElement.image.rowPixelSpacing);
} else if (enabledElement.image.columnPixelSpacing < enabledElement.image.rowPixelSpacing) {
heightScale *= (enabledElement.image.rowPixelSpacing / enabledElement.image.columnPixelSpacing);
}
transform.scale(widthScale, heightScale);
// Unrotate to so we can translate unrotated
if (angle !== 0) {
transform.rotate(-angle * Math.PI / 180);
}
// Apply the pan offset
transform.translate(enabledElement.viewport.translation.x, enabledElement.viewport.translation.y);
// Rotate again so we can apply general scale
if (angle !== 0) {
transform.rotate(angle * Math.PI / 180);
}
if (scale !== undefined) {
// Apply the font scale
transform.scale(scale, scale);
}
// Apply Flip if required
if (enabledElement.viewport.hflip) {
transform.scale(-1, 1);
}
if (enabledElement.viewport.vflip) {
transform.scale(1, -1);
}
// Translate the origin back to the corner of the image so the event handlers can draw in image coordinate system
transform.translate(-enabledElement.image.width / 2, -enabledElement.image.height / 2);
return transform;
}
| google/cornerstone | src/internal/calculateTransform.js | JavaScript | mit | 2,065 |
import Express from 'express';
import compression from 'compression';
import mongoose from 'mongoose';
import bodyParser from 'body-parser';
import path from 'path';
import IntlWrapper from '../client/modules/Intl/IntlWrapper';
// Webpack Requirements
import webpack from 'webpack';
import config from '../webpack.config.dev';
import webpackDevMiddleware from 'webpack-dev-middleware';
import webpackHotMiddleware from 'webpack-hot-middleware';
// Initialize the Express App
const app = new Express();
// Run Webpack dev server in development mode
if (process.env.NODE_ENV === 'development') {
const compiler = webpack(config);
app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: config.output.publicPath }));
app.use(webpackHotMiddleware(compiler));
}
// React And Redux Setup
import { configureStore } from '../client/store';
import { Provider } from 'react-redux';
import React from 'react';
import { renderToString } from 'react-dom/server';
import { match, RouterContext } from 'react-router';
import Helmet from 'react-helmet';
// Import required modules
import routes from '../client/routes';
import { fetchComponentData } from './util/fetchData';
import posts from './routes/post.routes';
import medicalRights from './routes/medicalrights.routes';
import populateDB from './routes/populateDB.routes';
import dummyData from './dummyData';
import serverConfig from './config';
// Set native promises as mongoose promise
mongoose.Promise = global.Promise;
// MongoDB Connection
mongoose.connect(serverConfig.mongoURL, (error) => {
if (error) {
console.error('Please make sure Mongodb is installed and running!'); // eslint-disable-line no-console
throw error;
}
// feed some dummy data in DB.
//dummyData();
});
// Apply body Parser and server public assets and routes
app.use(compression());
app.use(bodyParser.json({ limit: '20mb' }));
app.use(bodyParser.urlencoded({ limit: '20mb', extended: false }));
app.use(Express.static(path.resolve(__dirname, '../dist')));
app.use('/api', posts);
app.use('/api', medicalRights);
app.use('/api', populateDB);
// Render Initial HTML
const renderFullPage = (html, initialState) => {
const head = Helmet.rewind();
// Import Manifests
const assetsManifest = process.env.webpackAssets && JSON.parse(process.env.webpackAssets);
const chunkManifest = process.env.webpackChunkAssets && JSON.parse(process.env.webpackChunkAssets);
return `
<!doctype html>
<html>
<head>
${head.base.toString()}
${head.title.toString()}
${head.meta.toString()}
${head.link.toString()}
${head.script.toString()}
${process.env.NODE_ENV === 'production' ? `<link rel='stylesheet' href='${assetsManifest['/app.css']}' />` : ''}
<link href='https://fonts.googleapis.com/css?family=Lato:400,300,700' rel='stylesheet' type='text/css'/>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/latest/css/bootstrap.min.css" type='text/css'>
<link rel="shortcut icon" href="http://res.cloudinary.com/hashnode/image/upload/v1455629445/static_imgs/mern/mern-favicon-circle-fill.png" type="image/png" />
<style>
/* local page styles */
html h1 {
font-size: 26px;
margin-left: 10px;
}
html h2 {
font-size: 22px;
margin-left: 10px;
}
html h3 {
font-size: 14px;
margin-left: 10px;
}
html h4 {
font-size: 16px;
}
.progtrckr {
text-align: center;
padding-bottom: 16px;
// border-bottom: solid 1px;
}
.progtrckr li {
margin-bottom: 10px;
}
.val-err-tooltip {
background-color: red;
padding: 3px 5px 3px 10px;
font-size: 14px;
color: #fff;
}
.step {
// background-color: #ccc;
border:1px solid #e5e5e5;
min-height: 437px;
padding: 10px;
max-width: 815px;
}
html .row, html .form-horizontal .form-group {
margin: 0;
}
.footer-buttons {
margin-top: 10px;
margin-bottom: 50px;
}
html .step3 label, html .step4 label {
font-size: 20px;
text-align: left;
}
html .form-horizontal .control-label {
text-align: left;
}
.review .txt {
font-size: 20px;
text-align: left;
margin: 0;
padding: 0;
}
html body .saving {
background-color: #5cb85c;
width: 90%;
padding: 5px;
font-size: 16px;
}
code {
position: relative;
left: 12px;
line-height: 25px;
}
.eg-jump-lnk {
margin-top: 50px;
font-style: italic;
}
.lib-version {
font-size: 12px;
background-color: rgba(255, 255, 0, 0.38);
position: absolute;
right: 10px;
top: 10px;
padding: 5px;
}
html .content {
margin-left: 10px;
}
span.red {
color: #d9534f;
}
span.green {
color: #3c763d;
}
span.bold {
font-weight: bold;
}
html .hoc-alert {
margin-top: 20px;
}
html .form-block-holder {
margin-top: 20px !important;
}
ol.progtrckr {
margin: 0;
padding-bottom: 2.2rem;
list-style-type: none;
}
ol.progtrckr li {
display: inline-block;
text-align: center;
line-height: 4.5rem;
padding: 0 0.7rem;
cursor: pointer;
}
ol.progtrckr li span {
padding: 0 1.5rem;
}
@media (max-width: 650px) {
.progtrckr li span {
display: none;
}
}
.progtrckr em {
display: none;
font-weight: 700;
padding-left: 1rem;
}
@media (max-width: 650px) {
.progtrckr em {
display: inline;
}
border-bottom: solid 1px;
}
@media (max-width: 650px) {
.step {
max-height=320px;
min-height=437px;
min-width=300px;
}
}
}
ol.progtrckr li.progtrckr-todo {
color: silver;
border-bottom: 4px solid silver;
}
ol.progtrckr li.progtrckr-doing {
color: black;
border-bottom: 4px solid #33C3F0;
}
ol.progtrckr li.progtrckr-done {
color: black;
border-bottom: 4px solid #33C3F0;
}
ol.progtrckr li:after {
content: "\\00a0\\00a0";
}
ol.progtrckr li:before {
position: relative;
bottom: -3.7rem;
float: left;
left: 50%;
}
ol.progtrckr li.progtrckr-todo:before {
content: "\\039F";
color: silver;
background-color: white;
width: 1.2em;
line-height: 1.4em;
}
ol.progtrckr li.progtrckr-todo:hover:before {
color: #0FA0CE;
}
ol.progtrckr li.progtrckr-doing:before {
content: "\\2022";
color: white;
background-color: #33C3F0;
width: 1.2em;
line-height: 1.2em;
border-radius: 1.2em;
}
ol.progtrckr li.progtrckr-doing:hover:before {
color: #0FA0CE;
}
ol.progtrckr li.progtrckr-done:before {
content: "\\2713";
color: white;
background-color: #33C3F0;
width: 1.2em;
line-height: 1.2em;
border-radius: 1.2em;
}
ol.progtrckr li.progtrckr-done:hover:before {
color: #0FA0CE;
}
</style>
</head>
<body>
<div id="root">${html}</div>
<script>
window.__INITIAL_STATE__ = ${JSON.stringify(initialState)};
${process.env.NODE_ENV === 'production' ?
`//<![CDATA[
window.webpackManifest = ${JSON.stringify(chunkManifest)};
//]]>` : ''}
</script>
<script src='${process.env.NODE_ENV === 'production' ? assetsManifest['/vendor.js'] : '/vendor.js'}'></script>
<script src='${process.env.NODE_ENV === 'production' ? assetsManifest['/app.js'] : '/app.js'}'></script>
</body>
</html>
`;
};
const renderError = err => {
const softTab = '    ';
const errTrace = process.env.NODE_ENV !== 'production' ?
`:<br><br><pre style="color:red">${softTab}${err.stack.replace(/\n/g, `<br>${softTab}`)}</pre>` : '';
return renderFullPage(`Server Error${errTrace}`, {});
};
// Server Side Rendering based on routes matched by React-router.
app.use((req, res, next) => {
match({ routes, location: req.url }, (err, redirectLocation, renderProps) => {
if (err) {
return res.status(500).end(renderError(err));
}
if (redirectLocation) {
return res.redirect(302, redirectLocation.pathname + redirectLocation.search);
}
if (!renderProps) {
return next();
}
const store = configureStore();
return fetchComponentData(store, renderProps.components, renderProps.params)
.then(() => {
const initialView = renderToString(
<Provider store={store}>
<IntlWrapper>
<RouterContext {...renderProps} />
</IntlWrapper>
</Provider>
);
const finalState = store.getState();
res
.set('Content-Type', 'text/html')
.status(200)
.end(renderFullPage(initialView, finalState));
})
.catch((error) => next(error));
});
});
// start app
app.listen(serverConfig.port, (error) => {
if (!error) {
console.log(`MERN is running on port: ${serverConfig.port}! Build something amazing!`); // eslint-disable-line
}
});
export default app;
| zivkaziv/MazorTech | server/server.js | JavaScript | mit | 8,791 |
'use strict';
const AWS = require('aws-sdk');
let x = "/delegationset/NHKXBB6SHGKLN";
console.log(x.replace('/delegationset/', ''));
return;
const route53 = new AWS.Route53();
route53.listHostedZones({}).promise()
.then(response => {
console.log(response);
return response.HostedZones.find(hostedZone => {
return hostedZone.Name === 'manapaho.com.';
});
})
.catch(err => {
console.log(err);
})
.then(hostedZone => {
console.log(hostedZone);
});
return;
/*
route53.listReusableDelegationSets({}).promise()
.then(response => {
return response.DelegationSets.find(delegationSet => {
return delegationSet.CallerReference === 'arn:aws:lambda:us-east-1:238541850529:function:Prod-Wessels-us-east-1-Route53ReusableDelegationSet';
});
})
.catch(err => {
console.log(err);
})
.then(reusableDelegationSet => {
console.log(reusableDelegationSet);
});
return;
AWS.config.update({region: 'us-east-1'});
let stackName = 'Prod-Manapaho-us-east-1-NameServerSet';
let responseStatus = "FAILED";
let responseData = {};
let cfn = new AWS.CloudFormation();
cfn.describeStacks({StackName: stackName}).promise()
.then(data => {
console.log('333333333333333333333', JSON.stringify(data, null, 2));
data.Stacks[0].Outputs.forEach(function (output) {
responseData[output.OutputKey] = output.OutputValue;
});
responseStatus = "SUCCESS";
console.log(JSON.stringify(responseData, null, 2));
})
.catch(err => {
console.log('4444444444444444444444444');
console.log('FAILED TO DESCRIBE STACK:', err);
});
return;
const route53 = new AWS.Route53();
route53.listReusableDelegationSets({}).promise()
.then(response => {
console.log(response.DelegationSets.find(delegationSet => {
return delegationSet.CallerReference === 'arn:aws:lambda:us-east-1:238541850529:function:Prod-Manapaho-us-east-1-Route53ReusableDelegationSet';
}));
})
.catch(err => {
console.log(err);
});
return;
route53.createReusableDelegationSet({CallerReference: 'createReusableDelegationSet'}).promise()
.then(response => {
console.log('XXXXXXXX', JSON.stringify(response, null, 2));
})
.catch(err => {
console.log(err, err.stack);
});
*/
| manapaho/cloudy | .temp/test.js | JavaScript | mit | 2,248 |
const defaultEnv = process.env.NODE_ENV || 'development';
function getEnv(name = defaultEnv) {
const isProduction = name === 'production' || name === 'prod';
const isDev = !isProduction;
return { name, isProduction, isDev, getEnv };
}
const env = getEnv();
module.exports = env;
| tofishes/a-rule | utils/env.js | JavaScript | mit | 289 |
// Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '@angular-devkit/build-angular'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage-istanbul-reporter'),
require('@angular-devkit/build-angular/plugins/karma')
],
client: {
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
coverageIstanbulReporter: {
dir: require('path').join(__dirname, './coverage/DashboardHub'),
reports: ['html', 'lcovonly', 'text-summary'],
fixWebpackSourcePaths: true
},
reporters: ['progress', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false,
restartOnFileChange: true
});
};
| DashboardHub/Website | karma.conf.js | JavaScript | mit | 1,024 |
var React = require('react-native');
var {
StyleSheet,
View,
Animated,
} = React;
var Dot = React.createClass({
propTypes: {
isPlacedCorrectly: React.PropTypes.bool.isRequired,
},
getInitialState: function() {
return {
scale: new Animated.Value(this.props.isPlacedCorrectly ? 1 : 0.1),
visible: this.props.isPlacedCorrectly,
};
},
componentWillReceiveProps: function(nextProps) {
if (!this.props.isPlacedCorrectly && nextProps.isPlacedCorrectly) {
this.animateShow();
} else if (this.props.isPlacedCorrectly && !nextProps.isPlacedCorrectly) {
this.animateHide();
}
},
animateShow: function() {
this.setState({visible: true}, () => {
Animated.timing(this.state.scale, {
toValue: 1,
duration: 100,
}).start();
});
},
animateHide: function() {
Animated.timing(this.state.scale, {
toValue: 0.1,
duration: 100,
}).start(() => this.setState({visible: false}));
},
render: function() {
if (!this.state.visible) {
return null;
}
return (
<Animated.View style={[styles.dot, {transform: [{scale: this.state.scale}]}]}/>
);
},
});
var styles = StyleSheet.create({
dot: {
backgroundColor: '#FF3366',
width: 6,
height: 6,
borderRadius: 3,
margin: 3,
},
});
module.exports = Dot;
| nosovsh/fifteen | src/Dot.js | JavaScript | mit | 1,364 |
var namespacehryky_1_1log =
[
[ "AutoElapsed", "structhryky_1_1log_1_1_auto_elapsed.html", null ],
[ "level_type", "namespacehryky_1_1log.html#a6005efaf1fc45416ed6aa211f939993f", null ],
[ "writer_type", "namespacehryky_1_1log.html#a855ba68dea65f57a39b7a1cb03aee800", null ],
[ "write", "namespacehryky_1_1log.html#a5c7e76e7e42521f83c90fc8813f1f3ea", null ]
]; | hiroyuki-seki/hryky-codebase | doc/html/namespacehryky_1_1log.js | JavaScript | mit | 376 |
/****************************************************************************
Copyright (c) 2011-2012 cocos2d-x.org
Copyright (c) 2013-2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
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.
****************************************************************************/
/**
* Base class for ccs.Bone objects.
* @class
* @extends ccs.Node
*
* @property {ccs.BoneData} boneData - The bone data
* @property {ccs.Armature} armature - The armature
* @property {ccs.Bone} parentBone - The parent bone
* @property {ccs.Armature} childArmature - The child armature
* @property {Array} childrenBone - <@readonly> All children bones
* @property {ccs.Tween} tween - <@readonly> Tween
* @property {ccs.FrameData} tweenData - <@readonly> The tween data
* @property {ccs.ColliderFilter} colliderFilter - The collider filter
* @property {ccs.DisplayManager} displayManager - The displayManager
* @property {Boolean} ignoreMovementBoneData - Indicate whether force the bone to show When CCArmature play a animation and there isn't a CCMovementBoneData of this bone in this CCMovementData.
* @property {String} name - The name of the bone
* @property {Boolean} blendDirty - Indicate whether the blend is dirty
*
*/
ccs.Bone = ccs.Node.extend(/** @lends ccs.Bone# */{
_boneData: null,
_armature: null,
_childArmature: null,
_displayManager: null,
ignoreMovementBoneData: false,
_tween: null,
_tweenData: null,
_parentBone: null,
_boneTransformDirty: false,
_worldTransform: null,
_blendFunc: 0,
blendDirty: false,
_worldInfo: null,
_armatureParentBone: null,
_dataVersion: 0,
_className: "Bone",
ctor: function () {
cc.Node.prototype.ctor.call(this);
this._tweenData = null;
this._parentBone = null;
this._armature = null;
this._childArmature = null;
this._boneData = null;
this._tween = null;
this._displayManager = null;
this.ignoreMovementBoneData = false;
this._worldTransform = cc.affineTransformMake(1, 0, 0, 1, 0, 0);
this._boneTransformDirty = true;
this._blendFunc = new cc.BlendFunc(cc.BLEND_SRC, cc.BLEND_DST);
this.blendDirty = false;
this._worldInfo = null;
this._armatureParentBone = null;
this._dataVersion = 0;
},
/**
* Initializes a CCBone with the specified name
* @param {String} name
* @return {Boolean}
*/
init: function (name) {
// cc.Node.prototype.init.call(this);
if (name) {
this._name = name;
}
this._tweenData = new ccs.FrameData();
this._tween = new ccs.Tween();
this._tween.init(this);
this._displayManager = new ccs.DisplayManager();
this._displayManager.init(this);
this._worldInfo = new ccs.BaseData();
this._boneData = new ccs.BaseData();
return true;
},
/**
* set the boneData
* @param {ccs.BoneData} boneData
*/
setBoneData: function (boneData) {
cc.assert(boneData, "_boneData must not be null");
if(this._boneData != boneData)
this._boneData = boneData;
this.setName(this._boneData.name);
this._localZOrder = this._boneData.zOrder;
this._displayManager.initDisplayList(boneData);
},
/**
* boneData getter
* @return {ccs.BoneData}
*/
getBoneData: function () {
return this._boneData;
},
/**
* set the armature
* @param {ccs.Armature} armature
*/
setArmature: function (armature) {
this._armature = armature;
if (armature) {
this._tween.setAnimation(this._armature.getAnimation());
this._dataVersion = this._armature.getArmatureData().dataVersion;
this._armatureParentBone = this._armature.getParentBone();
} else {
this._armatureParentBone = null;
}
},
/**
* armature getter
* @return {ccs.Armature}
*/
getArmature: function () {
return this._armature;
},
/**
* update worldTransform
* @param {Number} delta
*/
update: function (delta) {
if (this._parentBone)
this._boneTransformDirty = this._boneTransformDirty || this._parentBone.isTransformDirty();
if (this._armatureParentBone && !this._boneTransformDirty)
this._boneTransformDirty = this._armatureParentBone.isTransformDirty();
if (this._boneTransformDirty){
var locTweenData = this._tweenData;
if (this._dataVersion >= ccs.CONST_VERSION_COMBINED){
ccs.TransformHelp.nodeConcat(locTweenData, this._boneData);
locTweenData.scaleX -= 1;
locTweenData.scaleY -= 1;
}
var locWorldInfo = this._worldInfo;
locWorldInfo.copy(locTweenData);
locWorldInfo.x = locTweenData.x + this._position.x;
locWorldInfo.y = locTweenData.y + this._position.y;
locWorldInfo.scaleX = locTweenData.scaleX * this._scaleX;
locWorldInfo.scaleY = locTweenData.scaleY * this._scaleY;
locWorldInfo.skewX = locTweenData.skewX + this._skewX + this._rotationX;
locWorldInfo.skewY = locTweenData.skewY + this._skewY - this._rotationY;
if(this._parentBone)
this.applyParentTransform(this._parentBone);
else {
if (this._armatureParentBone)
this.applyParentTransform(this._armatureParentBone);
}
ccs.TransformHelp.nodeToMatrix(locWorldInfo, this._worldTransform);
if (this._armatureParentBone)
this._worldTransform = cc.affineTransformConcat(this._worldTransform, this._armature.getNodeToParentTransform()); //TODO TransformConcat
}
ccs.displayFactory.updateDisplay(this, delta, this._boneTransformDirty || this._armature.getArmatureTransformDirty());
for(var i=0; i<this._children.length; i++) {
var childBone = this._children[i];
childBone.update(delta);
}
this._boneTransformDirty = false;
},
applyParentTransform: function (parent) {
var locWorldInfo = this._worldInfo;
var locParentWorldTransform = parent._worldTransform;
var locParentWorldInfo = parent._worldInfo;
var x = locWorldInfo.x;
var y = locWorldInfo.y;
locWorldInfo.x = x * locParentWorldTransform.a + y * locParentWorldTransform.c + locParentWorldInfo.x;
locWorldInfo.y = x * locParentWorldTransform.b + y * locParentWorldTransform.d + locParentWorldInfo.y;
locWorldInfo.scaleX = locWorldInfo.scaleX * locParentWorldInfo.scaleX;
locWorldInfo.scaleY = locWorldInfo.scaleY * locParentWorldInfo.scaleY;
locWorldInfo.skewX = locWorldInfo.skewX + locParentWorldInfo.skewX;
locWorldInfo.skewY = locWorldInfo.skewY + locParentWorldInfo.skewY;
},
/**
* BlendFunc setter
* @param {cc.BlendFunc} blendFunc
*/
setBlendFunc: function (blendFunc) {
if (this._blendFunc.src != blendFunc.src || this._blendFunc.dst != blendFunc.dst) {
this._blendFunc = blendFunc;
this.blendDirty = true;
}
},
/**
* update display color
* @param {cc.Color} color
*/
updateDisplayedColor: function (color) {
this._realColor = cc.color(255, 255, 255);
cc.Node.prototype.updateDisplayedColor.call(this, color);
this.updateColor();
},
/**
* update display opacity
* @param {Number} opacity
*/
updateDisplayedOpacity: function (opacity) {
this._realOpacity = 255;
cc.Node.prototype.updateDisplayedOpacity.call(this, opacity);
this.updateColor();
},
/**
* update display color
*/
updateColor: function () {
var display = this._displayManager.getDisplayRenderNode();
if (display != null) {
display.setColor(
cc.color(
this._displayedColor.r * this._tweenData.r / 255,
this._displayedColor.g * this._tweenData.g / 255,
this._displayedColor.b * this._tweenData.b / 255));
display.setOpacity(this._displayedOpacity * this._tweenData.a / 255);
}
},
/**
* update display zOrder
*/
updateZOrder: function () {
if (this._armature.getArmatureData().dataVersion >= ccs.CONST_VERSION_COMBINED) {
var zorder = this._tweenData.zOrder + this._boneData.zOrder;
this.setLocalZOrder(zorder);
} else {
this.setLocalZOrder(this._tweenData.zOrder);
}
},
/**
* Add a child to this bone, and it will let this child call setParent(ccs.Bone) function to set self to it's parent
* @param {ccs.Bone} child
*/
addChildBone: function (child) {
cc.assert(child, "Argument must be non-nil");
cc.assert(!child.parentBone, "child already added. It can't be added again");
if (this._children.indexOf(child) < 0) {
this._children.push(child);
child.setParentBone(this);
}
},
/**
* Removes a child bone
* @param {ccs.Bone} bone
* @param {Boolean} recursion
*/
removeChildBone: function (bone, recursion) {
if (this._children.length > 0 && this._children.getIndex(bone) != -1 ) {
if(recursion) {
var ccbones = bone._children;
for(var i=0; i<ccbones.length; i++){
var ccBone = ccbones[i];
bone.removeChildBone(ccBone, recursion);
}
}
bone.setParentBone(null);
bone.getDisplayManager().setCurrentDecorativeDisplay(null);
cc.arrayRemoveObject(this._children, bone);
}
},
/**
* Remove itself from its parent CCBone.
* @param {Boolean} recursion
*/
removeFromParent: function (recursion) {
if (this._parentBone) {
this._parentBone.removeChildBone(this, recursion);
}
},
/**
* Set parent bone.
* If _parent is NUll, then also remove this bone from armature.
* It will not set the CCArmature, if you want to add the bone to a CCArmature, you should use ccs.Armature.addBone(bone, parentName).
* @param {ccs.Bone} parent the parent bone.
*/
setParentBone: function (parent) {
this._parentBone = parent;
},
getParentBone: function(){
return this._parentBone;
},
/**
* child armature setter
* @param {ccs.Armature} armature
*/
setChildArmature: function (armature) {
if (this._childArmature != armature) {
if (armature == null && this._childArmature)
this._childArmature.setParentBone(null);
this._childArmature = armature;
}
},
/**
* child armature getter
* @return {ccs.Armature}
*/
getChildArmature: function () {
return this._childArmature;
},
/**
* tween getter
* @return {ccs.Tween}
*/
getTween: function () {
return this._tween;
},
/**
* zOrder setter
* @param {Number} zOrder
*/
setLocalZOrder: function (zOrder) {
if (this._localZOrder != zOrder)
cc.Node.prototype.setLocalZOrder.call(this, zOrder);
},
getNodeToArmatureTransform: function(){
return this._worldTransform;
},
getNodeToWorldTransform: function(){
return cc.affineTransformConcat(this._worldTransform, this._armature.getNodeToWorldTransform());
},
/**
* get render node
* @returns {cc.Node}
*/
getDisplayRenderNode: function () {
return this._displayManager.getDisplayRenderNode();
},
/**
* get render node type
* @returns {Number}
*/
getDisplayRenderNodeType: function () {
return this._displayManager.getDisplayRenderNodeType();
},
/**
* Add display and use _displayData init the display.
* If index already have a display, then replace it.
* If index is current display index, then also change display to _index
* @param {ccs.DisplayData} displayData it include the display information, like DisplayType.
* If you want to create a sprite display, then create a CCSpriteDisplayData param
*@param {Number} index the index of the display you want to replace or add to
* -1 : append display from back
*/
addDisplay: function (displayData, index) {
index = index || 0;
return this._displayManager.addDisplay(displayData, index);
},
/**
* remove display
* @param {Number} index
*/
removeDisplay: function (index) {
this._displayManager.removeDisplay(index);
},
/**
* change display by index
* @param {Number} index
* @param {Boolean} force
*/
changeDisplayByIndex: function (index, force) {
cc.log("changeDisplayByIndex is deprecated. Use changeDisplayWithIndex instead.");
this.changeDisplayWithIndex(index, force);
},
changeDisplayByName: function(name, force){
this.changeDisplayWithName(name, force);
},
/**
* change display with index
* @param {Number} index
* @param {Boolean} force
*/
changeDisplayWithIndex: function (index, force) {
this._displayManager.changeDisplayWithIndex(index, force);
},
/**
* change display with name
* @param {String} name
* @param {Boolean} force
*/
changeDisplayWithName: function (name, force) {
this._displayManager.changeDisplayWithName(name, force);
},
getColliderDetector: function(){
var decoDisplay = this._displayManager.getCurrentDecorativeDisplay();
if (decoDisplay){
var detector = decoDisplay.getColliderDetector();
if (detector)
return detector;
}
return null;
},
/**
* collider filter setter
* @param {cc.ColliderFilter} filter
*/
setColliderFilter: function (filter) {
var displayList = this._displayManager.getDecorativeDisplayList();
for (var i = 0; i < displayList.length; i++) {
var locDecoDisplay = displayList[i];
var locDetector = locDecoDisplay.getColliderDetector();
if (locDetector) {
locDetector.setColliderFilter(filter);
}
}
},
/**
* collider filter getter
* @returns {cc.ColliderFilter}
*/
getColliderFilter: function () {
var decoDisplay = this.displayManager.getCurrentDecorativeDisplay();
if (decoDisplay) {
var detector = decoDisplay.getColliderDetector();
if (detector)
return detector.getColliderFilter();
}
return null;
},
/**
* transform dirty setter
* @param {Boolean} dirty
*/
setTransformDirty: function (dirty) {
this._boneTransformDirty = dirty;
},
/**
* transform dirty getter
* @return {Boolean}
*/
isTransformDirty: function () {
return this._boneTransformDirty;
},
/**
* displayManager dirty getter
* @return {ccs.DisplayManager}
*/
getDisplayManager: function () {
return this._displayManager;
},
/**
* When CCArmature play a animation, if there is not a CCMovementBoneData of this bone in this CCMovementData, this bone will hide.
* Set IgnoreMovementBoneData to true, then this bone will also show.
* @param {Boolean} bool
*/
setIgnoreMovementBoneData: function (bool) {
this._ignoreMovementBoneData = bool;
},
isIgnoreMovementBoneData: function(){
return this._ignoreMovementBoneData;
},
/**
* blendType getter
* @return {cc.BlendFunc}
*/
getBlendFunc: function () {
return this._blendFunc;
},
setBlendDirty: function (dirty) {
this._blendDirty = dirty;
},
isBlendDirty: function () {
return this._blendDirty;
},
/**
* tweenData getter
* @return {ccs.FrameData}
*/
getTweenData: function () {
return this._tweenData;
},
getWorldInfo: function(){
return this._worldInfo;
},
/**
* child bone getter
* @return {Array}
* @deprecated
*/
getChildrenBone: function () {
return this._children;
},
/**
* @deprecated
* return world transform
* @return {{a:0.b:0,c:0,d:0,tx:0,ty:0}}
*/
nodeToArmatureTransform: function () {
return this.getNodeToArmatureTransform();
},
/**
* @deprecated
* Returns the world affine transform matrix. The matrix is in Pixels.
* @returns {cc.AffineTransform}
*/
nodeToWorldTransform: function () {
return this.getNodeToWorldTransform();
},
/**
* @deprecated
* get the collider body list in this bone.
* @returns {*}
*/
getColliderBodyList: function () {
var detector = this.getColliderDetector();
if(detector)
return detector.getColliderBodyList();
return null;
},
/**
* ignoreMovementBoneData getter
* @return {Boolean}
*/
getIgnoreMovementBoneData: function () {
return this.isIgnoreMovementBoneData();
}
});
var _p = ccs.Bone.prototype;
// Extended properties
/** @expose */
_p.boneData;
cc.defineGetterSetter(_p, "boneData", _p.getBoneData, _p.setBoneData);
/** @expose */
_p.armature;
cc.defineGetterSetter(_p, "armature", _p.getArmature, _p.setArmature);
/** @expose */
_p.childArmature;
cc.defineGetterSetter(_p, "childArmature", _p.getChildArmature, _p.setChildArmature);
/** @expose */
_p.childrenBone;
cc.defineGetterSetter(_p, "childrenBone", _p.getChildrenBone);
/** @expose */
_p.tween;
cc.defineGetterSetter(_p, "tween", _p.getTween);
/** @expose */
_p.tweenData;
cc.defineGetterSetter(_p, "tweenData", _p.getTweenData);
/** @expose */
_p.colliderFilter;
cc.defineGetterSetter(_p, "colliderFilter", _p.getColliderFilter, _p.setColliderFilter);
_p = null;
/**
* allocates and initializes a bone.
* @constructs
* @return {ccs.Bone}
* @example
* // example
* var bone = ccs.Bone.create();
*/
ccs.Bone.create = function (name) {
var bone = new ccs.Bone();
if (bone && bone.init(name))
return bone;
return null;
}; | zry656565/MoonWarriors | frameworks/cocos2d-html5/extensions/cocostudio/armature/CCBone.js | JavaScript | mit | 19,960 |
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'use strict';
var util = require('util');
var msRest = require('ms-rest');
var WebResource = msRest.WebResource;
/**
* @class
* Implicit
* __NOTE__: An instance of this class is automatically created for an
* instance of the AutoRestRequiredOptionalTestService.
* Initializes a new instance of the Implicit class.
* @constructor
*
* @param {AutoRestRequiredOptionalTestService} client Reference to the service client.
*/
function Implicit(client) {
this.client = client;
}
/**
* Test implicitly required path parameter
*
* @param {string} pathParameter
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} callback
*
* @returns {function} callback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object.
* See {@link ErrorModel} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
Implicit.prototype.getRequiredPath = function (pathParameter, options, callback) {
var client = this.client;
if(!callback && typeof options === 'function') {
callback = options;
options = null;
}
if (!callback) {
throw new Error('callback cannot be null.');
}
// Validate
try {
if (pathParameter === null || pathParameter === undefined || typeof pathParameter.valueOf() !== 'string') {
throw new Error('pathParameter cannot be null or undefined and it must be of type string.');
}
} catch (error) {
return callback(error);
}
// Construct URL
var baseUrl = this.client.baseUri;
var requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'reqopt/implicit/required/path/{pathParameter}';
requestUrl = requestUrl.replace('{pathParameter}', encodeURIComponent(pathParameter));
// Create HTTP transport objects
var httpRequest = new WebResource();
httpRequest.method = 'GET';
httpRequest.headers = {};
httpRequest.url = requestUrl;
// Set Headers
if(options) {
for(var headerName in options['customHeaders']) {
if (options['customHeaders'].hasOwnProperty(headerName)) {
httpRequest.headers[headerName] = options['customHeaders'][headerName];
}
}
}
httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
httpRequest.body = null;
// Send Request
return client.pipeline(httpRequest, function (err, response, responseBody) {
if (err) {
return callback(err);
}
var statusCode = response.statusCode;
if (statusCode < 200 || statusCode >= 300) {
var error = new Error(responseBody);
error.statusCode = response.statusCode;
error.request = msRest.stripRequest(httpRequest);
error.response = msRest.stripResponse(response);
if (responseBody === '') responseBody = null;
var parsedErrorResponse;
try {
parsedErrorResponse = JSON.parse(responseBody);
if (parsedErrorResponse) {
if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error;
if (parsedErrorResponse.code) error.code = parsedErrorResponse.code;
if (parsedErrorResponse.message) error.message = parsedErrorResponse.message;
}
if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
var resultMapper = new client.models['ErrorModel']().mapper();
error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body');
}
} catch (defaultError) {
error.message = util.format('Error "%s" occurred in deserializing the responseBody ' +
'- "%s" for the default response.', defaultError.message, responseBody);
return callback(error);
}
return callback(error);
}
// Create Result
var result = null;
if (responseBody === '') responseBody = null;
var parsedResponse = null;
try {
parsedResponse = JSON.parse(responseBody);
result = JSON.parse(responseBody);
if (parsedResponse !== null && parsedResponse !== undefined) {
var resultMapper = new client.models['ErrorModel']().mapper();
result = client.deserialize(resultMapper, parsedResponse, 'result');
}
} catch (error) {
var deserializationError = new Error(util.format('Error "%s" occurred in deserializing the responseBody - "%s"', error, responseBody));
deserializationError.request = msRest.stripRequest(httpRequest);
deserializationError.response = msRest.stripResponse(response);
return callback(deserializationError);
}
return callback(null, result, httpRequest, response);
});
};
/**
* Test implicitly optional query parameter
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.queryParameter]
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} callback
*
* @returns {function} callback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
Implicit.prototype.putOptionalQuery = function (options, callback) {
var client = this.client;
if(!callback && typeof options === 'function') {
callback = options;
options = null;
}
if (!callback) {
throw new Error('callback cannot be null.');
}
var queryParameter = (options && options.queryParameter !== undefined) ? options.queryParameter : undefined;
// Validate
try {
if (queryParameter !== null && queryParameter !== undefined && typeof queryParameter.valueOf() !== 'string') {
throw new Error('queryParameter must be of type string.');
}
} catch (error) {
return callback(error);
}
// Construct URL
var baseUrl = this.client.baseUri;
var requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'reqopt/implicit/optional/query';
var queryParameters = [];
if (queryParameter !== null && queryParameter !== undefined) {
queryParameters.push('queryParameter=' + encodeURIComponent(queryParameter));
}
if (queryParameters.length > 0) {
requestUrl += '?' + queryParameters.join('&');
}
// Create HTTP transport objects
var httpRequest = new WebResource();
httpRequest.method = 'PUT';
httpRequest.headers = {};
httpRequest.url = requestUrl;
// Set Headers
if(options) {
for(var headerName in options['customHeaders']) {
if (options['customHeaders'].hasOwnProperty(headerName)) {
httpRequest.headers[headerName] = options['customHeaders'][headerName];
}
}
}
httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
httpRequest.body = null;
// Send Request
return client.pipeline(httpRequest, function (err, response, responseBody) {
if (err) {
return callback(err);
}
var statusCode = response.statusCode;
if (statusCode !== 200) {
var error = new Error(responseBody);
error.statusCode = response.statusCode;
error.request = msRest.stripRequest(httpRequest);
error.response = msRest.stripResponse(response);
if (responseBody === '') responseBody = null;
var parsedErrorResponse;
try {
parsedErrorResponse = JSON.parse(responseBody);
if (parsedErrorResponse) {
if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error;
if (parsedErrorResponse.code) error.code = parsedErrorResponse.code;
if (parsedErrorResponse.message) error.message = parsedErrorResponse.message;
}
if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
var resultMapper = new client.models['ErrorModel']().mapper();
error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body');
}
} catch (defaultError) {
error.message = util.format('Error "%s" occurred in deserializing the responseBody ' +
'- "%s" for the default response.', defaultError.message, responseBody);
return callback(error);
}
return callback(error);
}
// Create Result
var result = null;
if (responseBody === '') responseBody = null;
return callback(null, result, httpRequest, response);
});
};
/**
* Test implicitly optional header parameter
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.queryParameter]
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} callback
*
* @returns {function} callback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
Implicit.prototype.putOptionalHeader = function (options, callback) {
var client = this.client;
if(!callback && typeof options === 'function') {
callback = options;
options = null;
}
if (!callback) {
throw new Error('callback cannot be null.');
}
var queryParameter = (options && options.queryParameter !== undefined) ? options.queryParameter : undefined;
// Validate
try {
if (queryParameter !== null && queryParameter !== undefined && typeof queryParameter.valueOf() !== 'string') {
throw new Error('queryParameter must be of type string.');
}
} catch (error) {
return callback(error);
}
// Construct URL
var baseUrl = this.client.baseUri;
var requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'reqopt/implicit/optional/header';
// Create HTTP transport objects
var httpRequest = new WebResource();
httpRequest.method = 'PUT';
httpRequest.headers = {};
httpRequest.url = requestUrl;
// Set Headers
if (queryParameter !== undefined && queryParameter !== null) {
httpRequest.headers['queryParameter'] = queryParameter;
}
if(options) {
for(var headerName in options['customHeaders']) {
if (options['customHeaders'].hasOwnProperty(headerName)) {
httpRequest.headers[headerName] = options['customHeaders'][headerName];
}
}
}
httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
httpRequest.body = null;
// Send Request
return client.pipeline(httpRequest, function (err, response, responseBody) {
if (err) {
return callback(err);
}
var statusCode = response.statusCode;
if (statusCode !== 200) {
var error = new Error(responseBody);
error.statusCode = response.statusCode;
error.request = msRest.stripRequest(httpRequest);
error.response = msRest.stripResponse(response);
if (responseBody === '') responseBody = null;
var parsedErrorResponse;
try {
parsedErrorResponse = JSON.parse(responseBody);
if (parsedErrorResponse) {
if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error;
if (parsedErrorResponse.code) error.code = parsedErrorResponse.code;
if (parsedErrorResponse.message) error.message = parsedErrorResponse.message;
}
if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
var resultMapper = new client.models['ErrorModel']().mapper();
error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body');
}
} catch (defaultError) {
error.message = util.format('Error "%s" occurred in deserializing the responseBody ' +
'- "%s" for the default response.', defaultError.message, responseBody);
return callback(error);
}
return callback(error);
}
// Create Result
var result = null;
if (responseBody === '') responseBody = null;
return callback(null, result, httpRequest, response);
});
};
/**
* Test implicitly optional body parameter
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.bodyParameter]
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} callback
*
* @returns {function} callback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
Implicit.prototype.putOptionalBody = function (options, callback) {
var client = this.client;
if(!callback && typeof options === 'function') {
callback = options;
options = null;
}
if (!callback) {
throw new Error('callback cannot be null.');
}
var bodyParameter = (options && options.bodyParameter !== undefined) ? options.bodyParameter : undefined;
// Validate
try {
if (bodyParameter !== null && bodyParameter !== undefined && typeof bodyParameter.valueOf() !== 'string') {
throw new Error('bodyParameter must be of type string.');
}
} catch (error) {
return callback(error);
}
// Construct URL
var baseUrl = this.client.baseUri;
var requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'reqopt/implicit/optional/body';
// Create HTTP transport objects
var httpRequest = new WebResource();
httpRequest.method = 'PUT';
httpRequest.headers = {};
httpRequest.url = requestUrl;
// Set Headers
if(options) {
for(var headerName in options['customHeaders']) {
if (options['customHeaders'].hasOwnProperty(headerName)) {
httpRequest.headers[headerName] = options['customHeaders'][headerName];
}
}
}
httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
// Serialize Request
var requestContent = null;
var requestModel = null;
try {
if (bodyParameter !== null && bodyParameter !== undefined) {
var requestModelMapper = {
required: false,
serializedName: 'bodyParameter',
type: {
name: 'String'
}
};
requestModel = client.serialize(requestModelMapper, bodyParameter, 'bodyParameter');
requestContent = JSON.stringify(requestModel);
}
} catch (error) {
var serializationError = new Error(util.format('Error "%s" occurred in serializing the ' +
'payload - "%s"', error.message, util.inspect(bodyParameter, {depth: null})));
return callback(serializationError);
}
httpRequest.body = requestContent;
// Send Request
return client.pipeline(httpRequest, function (err, response, responseBody) {
if (err) {
return callback(err);
}
var statusCode = response.statusCode;
if (statusCode !== 200) {
var error = new Error(responseBody);
error.statusCode = response.statusCode;
error.request = msRest.stripRequest(httpRequest);
error.response = msRest.stripResponse(response);
if (responseBody === '') responseBody = null;
var parsedErrorResponse;
try {
parsedErrorResponse = JSON.parse(responseBody);
if (parsedErrorResponse) {
if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error;
if (parsedErrorResponse.code) error.code = parsedErrorResponse.code;
if (parsedErrorResponse.message) error.message = parsedErrorResponse.message;
}
if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
var resultMapper = new client.models['ErrorModel']().mapper();
error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body');
}
} catch (defaultError) {
error.message = util.format('Error "%s" occurred in deserializing the responseBody ' +
'- "%s" for the default response.', defaultError.message, responseBody);
return callback(error);
}
return callback(error);
}
// Create Result
var result = null;
if (responseBody === '') responseBody = null;
return callback(null, result, httpRequest, response);
});
};
/**
* Test implicitly required path parameter
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} callback
*
* @returns {function} callback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object.
* See {@link ErrorModel} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
Implicit.prototype.getRequiredGlobalPath = function (options, callback) {
var client = this.client;
if(!callback && typeof options === 'function') {
callback = options;
options = null;
}
if (!callback) {
throw new Error('callback cannot be null.');
}
// Validate
try {
if (this.client.requiredGlobalPath === null || this.client.requiredGlobalPath === undefined || typeof this.client.requiredGlobalPath.valueOf() !== 'string') {
throw new Error('this.client.requiredGlobalPath cannot be null or undefined and it must be of type string.');
}
} catch (error) {
return callback(error);
}
// Construct URL
var baseUrl = this.client.baseUri;
var requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'reqopt/global/required/path/{required-global-path}';
requestUrl = requestUrl.replace('{required-global-path}', encodeURIComponent(this.client.requiredGlobalPath));
// Create HTTP transport objects
var httpRequest = new WebResource();
httpRequest.method = 'GET';
httpRequest.headers = {};
httpRequest.url = requestUrl;
// Set Headers
if(options) {
for(var headerName in options['customHeaders']) {
if (options['customHeaders'].hasOwnProperty(headerName)) {
httpRequest.headers[headerName] = options['customHeaders'][headerName];
}
}
}
httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
httpRequest.body = null;
// Send Request
return client.pipeline(httpRequest, function (err, response, responseBody) {
if (err) {
return callback(err);
}
var statusCode = response.statusCode;
if (statusCode < 200 || statusCode >= 300) {
var error = new Error(responseBody);
error.statusCode = response.statusCode;
error.request = msRest.stripRequest(httpRequest);
error.response = msRest.stripResponse(response);
if (responseBody === '') responseBody = null;
var parsedErrorResponse;
try {
parsedErrorResponse = JSON.parse(responseBody);
if (parsedErrorResponse) {
if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error;
if (parsedErrorResponse.code) error.code = parsedErrorResponse.code;
if (parsedErrorResponse.message) error.message = parsedErrorResponse.message;
}
if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
var resultMapper = new client.models['ErrorModel']().mapper();
error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body');
}
} catch (defaultError) {
error.message = util.format('Error "%s" occurred in deserializing the responseBody ' +
'- "%s" for the default response.', defaultError.message, responseBody);
return callback(error);
}
return callback(error);
}
// Create Result
var result = null;
if (responseBody === '') responseBody = null;
var parsedResponse = null;
try {
parsedResponse = JSON.parse(responseBody);
result = JSON.parse(responseBody);
if (parsedResponse !== null && parsedResponse !== undefined) {
var resultMapper = new client.models['ErrorModel']().mapper();
result = client.deserialize(resultMapper, parsedResponse, 'result');
}
} catch (error) {
var deserializationError = new Error(util.format('Error "%s" occurred in deserializing the responseBody - "%s"', error, responseBody));
deserializationError.request = msRest.stripRequest(httpRequest);
deserializationError.response = msRest.stripResponse(response);
return callback(deserializationError);
}
return callback(null, result, httpRequest, response);
});
};
/**
* Test implicitly required query parameter
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} callback
*
* @returns {function} callback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object.
* See {@link ErrorModel} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
Implicit.prototype.getRequiredGlobalQuery = function (options, callback) {
var client = this.client;
if(!callback && typeof options === 'function') {
callback = options;
options = null;
}
if (!callback) {
throw new Error('callback cannot be null.');
}
// Validate
try {
if (this.client.requiredGlobalQuery === null || this.client.requiredGlobalQuery === undefined || typeof this.client.requiredGlobalQuery.valueOf() !== 'string') {
throw new Error('this.client.requiredGlobalQuery cannot be null or undefined and it must be of type string.');
}
} catch (error) {
return callback(error);
}
// Construct URL
var baseUrl = this.client.baseUri;
var requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'reqopt/global/required/query';
var queryParameters = [];
queryParameters.push('required-global-query=' + encodeURIComponent(this.client.requiredGlobalQuery));
if (queryParameters.length > 0) {
requestUrl += '?' + queryParameters.join('&');
}
// Create HTTP transport objects
var httpRequest = new WebResource();
httpRequest.method = 'GET';
httpRequest.headers = {};
httpRequest.url = requestUrl;
// Set Headers
if(options) {
for(var headerName in options['customHeaders']) {
if (options['customHeaders'].hasOwnProperty(headerName)) {
httpRequest.headers[headerName] = options['customHeaders'][headerName];
}
}
}
httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
httpRequest.body = null;
// Send Request
return client.pipeline(httpRequest, function (err, response, responseBody) {
if (err) {
return callback(err);
}
var statusCode = response.statusCode;
if (statusCode < 200 || statusCode >= 300) {
var error = new Error(responseBody);
error.statusCode = response.statusCode;
error.request = msRest.stripRequest(httpRequest);
error.response = msRest.stripResponse(response);
if (responseBody === '') responseBody = null;
var parsedErrorResponse;
try {
parsedErrorResponse = JSON.parse(responseBody);
if (parsedErrorResponse) {
if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error;
if (parsedErrorResponse.code) error.code = parsedErrorResponse.code;
if (parsedErrorResponse.message) error.message = parsedErrorResponse.message;
}
if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
var resultMapper = new client.models['ErrorModel']().mapper();
error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body');
}
} catch (defaultError) {
error.message = util.format('Error "%s" occurred in deserializing the responseBody ' +
'- "%s" for the default response.', defaultError.message, responseBody);
return callback(error);
}
return callback(error);
}
// Create Result
var result = null;
if (responseBody === '') responseBody = null;
var parsedResponse = null;
try {
parsedResponse = JSON.parse(responseBody);
result = JSON.parse(responseBody);
if (parsedResponse !== null && parsedResponse !== undefined) {
var resultMapper = new client.models['ErrorModel']().mapper();
result = client.deserialize(resultMapper, parsedResponse, 'result');
}
} catch (error) {
var deserializationError = new Error(util.format('Error "%s" occurred in deserializing the responseBody - "%s"', error, responseBody));
deserializationError.request = msRest.stripRequest(httpRequest);
deserializationError.response = msRest.stripResponse(response);
return callback(deserializationError);
}
return callback(null, result, httpRequest, response);
});
};
/**
* Test implicitly optional query parameter
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} callback
*
* @returns {function} callback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object.
* See {@link ErrorModel} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
Implicit.prototype.getOptionalGlobalQuery = function (options, callback) {
var client = this.client;
if(!callback && typeof options === 'function') {
callback = options;
options = null;
}
if (!callback) {
throw new Error('callback cannot be null.');
}
// Validate
try {
if (this.client.optionalGlobalQuery !== null && this.client.optionalGlobalQuery !== undefined && typeof this.client.optionalGlobalQuery !== 'number') {
throw new Error('this.client.optionalGlobalQuery must be of type number.');
}
} catch (error) {
return callback(error);
}
// Construct URL
var baseUrl = this.client.baseUri;
var requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'reqopt/global/optional/query';
var queryParameters = [];
if (this.client.optionalGlobalQuery !== null && this.client.optionalGlobalQuery !== undefined) {
queryParameters.push('optional-global-query=' + encodeURIComponent(this.client.optionalGlobalQuery.toString()));
}
if (queryParameters.length > 0) {
requestUrl += '?' + queryParameters.join('&');
}
// Create HTTP transport objects
var httpRequest = new WebResource();
httpRequest.method = 'GET';
httpRequest.headers = {};
httpRequest.url = requestUrl;
// Set Headers
if(options) {
for(var headerName in options['customHeaders']) {
if (options['customHeaders'].hasOwnProperty(headerName)) {
httpRequest.headers[headerName] = options['customHeaders'][headerName];
}
}
}
httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
httpRequest.body = null;
// Send Request
return client.pipeline(httpRequest, function (err, response, responseBody) {
if (err) {
return callback(err);
}
var statusCode = response.statusCode;
if (statusCode < 200 || statusCode >= 300) {
var error = new Error(responseBody);
error.statusCode = response.statusCode;
error.request = msRest.stripRequest(httpRequest);
error.response = msRest.stripResponse(response);
if (responseBody === '') responseBody = null;
var parsedErrorResponse;
try {
parsedErrorResponse = JSON.parse(responseBody);
if (parsedErrorResponse) {
if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error;
if (parsedErrorResponse.code) error.code = parsedErrorResponse.code;
if (parsedErrorResponse.message) error.message = parsedErrorResponse.message;
}
if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
var resultMapper = new client.models['ErrorModel']().mapper();
error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body');
}
} catch (defaultError) {
error.message = util.format('Error "%s" occurred in deserializing the responseBody ' +
'- "%s" for the default response.', defaultError.message, responseBody);
return callback(error);
}
return callback(error);
}
// Create Result
var result = null;
if (responseBody === '') responseBody = null;
var parsedResponse = null;
try {
parsedResponse = JSON.parse(responseBody);
result = JSON.parse(responseBody);
if (parsedResponse !== null && parsedResponse !== undefined) {
var resultMapper = new client.models['ErrorModel']().mapper();
result = client.deserialize(resultMapper, parsedResponse, 'result');
}
} catch (error) {
var deserializationError = new Error(util.format('Error "%s" occurred in deserializing the responseBody - "%s"', error, responseBody));
deserializationError.request = msRest.stripRequest(httpRequest);
deserializationError.response = msRest.stripResponse(response);
return callback(deserializationError);
}
return callback(null, result, httpRequest, response);
});
};
module.exports = Implicit;
| fhoring/autorest | src/generator/AutoRest.NodeJS.Tests/Expected/AcceptanceTests/RequiredOptional/operations/implicit.js | JavaScript | mit | 31,107 |
/*!
* Bootstrap v3.3.6 (http://getbootstrap.com)
* Copyright 2011-2015 Twitter, Inc.
* Licensed under the MIT license
*/
if (typeof jQuery === 'undefined') {
throw new Error('Bootstrap\'s JavaScript requires jQuery')
}
+
function($) {
'use strict';
var version = $.fn.jquery.split(' ')[0].split('.')
if ((version[0] < 2 && version[1] < 9) || (version[0] == 1 && version[1] == 9 && version[2] < 1) || (version[0] > 2)) {
throw new Error('Bootstrap\'s JavaScript requires jQuery version 1.9.1 or higher, but lower than version 3')
}
}(jQuery);
/* ========================================================================
* Bootstrap: transition.js v3.3.6
* http://getbootstrap.com/javascript/#transitions
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+
function($) {
'use strict';
// CSS TRANSITION SUPPORT (Shoutout: http://www.modernizr.com/)
// ============================================================
function transitionEnd() {
var el = document.createElement('bootstrap')
var transEndEventNames = {
WebkitTransition: 'webkitTransitionEnd',
MozTransition: 'transitionend',
OTransition: 'oTransitionEnd otransitionend',
transition: 'transitionend'
}
for (var name in transEndEventNames) {
if (el.style[name] !== undefined) {
return { end: transEndEventNames[name] }
}
}
return false // explicit for ie8 ( ._.)
}
// http://blog.alexmaccaw.com/css-transitions
$.fn.emulateTransitionEnd = function(duration) {
var called = false
var $el = this
$(this).one('bsTransitionEnd', function() { called = true })
var callback = function() { if (!called) $($el).trigger($.support.transition.end) }
setTimeout(callback, duration)
return this
}
$(function() {
$.support.transition = transitionEnd()
if (!$.support.transition) return
$.event.special.bsTransitionEnd = {
bindType: $.support.transition.end,
delegateType: $.support.transition.end,
handle: function(e) {
if ($(e.target).is(this)) return e.handleObj.handler.apply(this, arguments)
}
}
})
}(jQuery);
/* ========================================================================
* Bootstrap: alert.js v3.3.6
* http://getbootstrap.com/javascript/#alerts
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+
function($) {
'use strict';
// ALERT CLASS DEFINITION
// ======================
var dismiss = '[data-dismiss="alert"]'
var Alert = function(el) {
$(el).on('click', dismiss, this.close)
}
Alert.VERSION = '3.3.6'
Alert.TRANSITION_DURATION = 150
Alert.prototype.close = function(e) {
var $this = $(this)
var selector = $this.attr('data-target')
if (!selector) {
selector = $this.attr('href')
selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
}
var $parent = $(selector)
if (e) e.preventDefault()
if (!$parent.length) {
$parent = $this.closest('.alert')
}
$parent.trigger(e = $.Event('close.bs.alert'))
if (e.isDefaultPrevented()) return
$parent.removeClass('in')
function removeElement() {
// detach from parent, fire event then clean up data
$parent.detach().trigger('closed.bs.alert').remove()
}
$.support.transition && $parent.hasClass('fade') ?
$parent
.one('bsTransitionEnd', removeElement)
.emulateTransitionEnd(Alert.TRANSITION_DURATION) :
removeElement()
}
// ALERT PLUGIN DEFINITION
// =======================
function Plugin(option) {
return this.each(function() {
var $this = $(this)
var data = $this.data('bs.alert')
if (!data) $this.data('bs.alert', (data = new Alert(this)))
if (typeof option == 'string') data[option].call($this)
})
}
var old = $.fn.alert
$.fn.alert = Plugin
$.fn.alert.Constructor = Alert
// ALERT NO CONFLICT
// =================
$.fn.alert.noConflict = function() {
$.fn.alert = old
return this
}
// ALERT DATA-API
// ==============
$(document).on('click.bs.alert.data-api', dismiss, Alert.prototype.close)
}(jQuery);
/* ========================================================================
* Bootstrap: button.js v3.3.6
* http://getbootstrap.com/javascript/#buttons
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+
function($) {
'use strict';
// BUTTON PUBLIC CLASS DEFINITION
// ==============================
var Button = function(element, options) {
this.$element = $(element)
this.options = $.extend({}, Button.DEFAULTS, options)
this.isLoading = false
}
Button.VERSION = '3.3.6'
Button.DEFAULTS = {
loadingText: 'loading...'
}
Button.prototype.setState = function(state) {
var d = 'disabled'
var $el = this.$element
var val = $el.is('input') ? 'val' : 'html'
var data = $el.data()
state += 'Text'
if (data.resetText == null) $el.data('resetText', $el[val]())
// push to event loop to allow forms to submit
setTimeout($.proxy(function() {
$el[val](data[state] == null ? this.options[state] : data[state])
if (state == 'loadingText') {
this.isLoading = true
$el.addClass(d).attr(d, d)
} else if (this.isLoading) {
this.isLoading = false
$el.removeClass(d).removeAttr(d)
}
}, this), 0)
}
Button.prototype.toggle = function() {
var changed = true
var $parent = this.$element.closest('[data-toggle="buttons"]')
if ($parent.length) {
var $input = this.$element.find('input')
if ($input.prop('type') == 'radio') {
if ($input.prop('checked')) changed = false
$parent.find('.active').removeClass('active')
this.$element.addClass('active')
} else if ($input.prop('type') == 'checkbox') {
if (($input.prop('checked')) !== this.$element.hasClass('active')) changed = false
this.$element.toggleClass('active')
}
$input.prop('checked', this.$element.hasClass('active'))
if (changed) $input.trigger('change')
} else {
this.$element.attr('aria-pressed', !this.$element.hasClass('active'))
this.$element.toggleClass('active')
}
}
// BUTTON PLUGIN DEFINITION
// ========================
function Plugin(option) {
return this.each(function() {
var $this = $(this)
var data = $this.data('bs.button')
var options = typeof option == 'object' && option
if (!data) $this.data('bs.button', (data = new Button(this, options)))
if (option == 'toggle') data.toggle()
else if (option) data.setState(option)
})
}
var old = $.fn.button
$.fn.button = Plugin
$.fn.button.Constructor = Button
// BUTTON NO CONFLICT
// ==================
$.fn.button.noConflict = function() {
$.fn.button = old
return this
}
// BUTTON DATA-API
// ===============
$(document)
.on('click.bs.button.data-api', '[data-toggle^="button"]', function(e) {
var $btn = $(e.target)
if (!$btn.hasClass('btn')) $btn = $btn.closest('.btn')
Plugin.call($btn, 'toggle')
if (!($(e.target).is('input[type="radio"]') || $(e.target).is('input[type="checkbox"]'))) e.preventDefault()
})
.on('focus.bs.button.data-api blur.bs.button.data-api', '[data-toggle^="button"]', function(e) {
$(e.target).closest('.btn').toggleClass('focus', /^focus(in)?$/.test(e.type))
})
}(jQuery);
/* ========================================================================
* Bootstrap: carousel.js v3.3.6
* http://getbootstrap.com/javascript/#carousel
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+
function($) {
'use strict';
// CAROUSEL CLASS DEFINITION
// =========================
var Carousel = function(element, options) {
this.$element = $(element)
this.$indicators = this.$element.find('.carousel-indicators')
this.options = options
this.paused = null
this.sliding = null
this.interval = null
this.$active = null
this.$items = null
this.options.keyboard && this.$element.on('keydown.bs.carousel', $.proxy(this.keydown, this))
this.options.pause == 'hover' && !('ontouchstart' in document.documentElement) && this.$element
.on('mouseenter.bs.carousel', $.proxy(this.pause, this))
.on('mouseleave.bs.carousel', $.proxy(this.cycle, this))
}
Carousel.VERSION = '3.3.6'
Carousel.TRANSITION_DURATION = 600
Carousel.DEFAULTS = {
interval: 5000,
pause: 'hover',
wrap: true,
keyboard: true
}
Carousel.prototype.keydown = function(e) {
if (/input|textarea/i.test(e.target.tagName)) return
switch (e.which) {
case 37:
this.prev();
break
case 39:
this.next();
break
default:
return
}
e.preventDefault()
}
Carousel.prototype.cycle = function(e) {
e || (this.paused = false)
this.interval && clearInterval(this.interval)
this.options.interval &&
!this.paused &&
(this.interval = setInterval($.proxy(this.next, this), this.options.interval))
return this
}
Carousel.prototype.getItemIndex = function(item) {
this.$items = item.parent().children('.item')
return this.$items.index(item || this.$active)
}
Carousel.prototype.getItemForDirection = function(direction, active) {
var activeIndex = this.getItemIndex(active)
var willWrap = (direction == 'prev' && activeIndex === 0) ||
(direction == 'next' && activeIndex == (this.$items.length - 1))
if (willWrap && !this.options.wrap) return active
var delta = direction == 'prev' ? -1 : 1
var itemIndex = (activeIndex + delta) % this.$items.length
return this.$items.eq(itemIndex)
}
Carousel.prototype.to = function(pos) {
var that = this
var activeIndex = this.getItemIndex(this.$active = this.$element.find('.item.active'))
if (pos > (this.$items.length - 1) || pos < 0) return
if (this.sliding) return this.$element.one('slid.bs.carousel', function() { that.to(pos) }) // yes, "slid"
if (activeIndex == pos) return this.pause().cycle()
return this.slide(pos > activeIndex ? 'next' : 'prev', this.$items.eq(pos))
}
Carousel.prototype.pause = function(e) {
e || (this.paused = true)
if (this.$element.find('.next, .prev').length && $.support.transition) {
this.$element.trigger($.support.transition.end)
this.cycle(true)
}
this.interval = clearInterval(this.interval)
return this
}
Carousel.prototype.next = function() {
if (this.sliding) return
return this.slide('next')
}
Carousel.prototype.prev = function() {
if (this.sliding) return
return this.slide('prev')
}
Carousel.prototype.slide = function(type, next) {
var $active = this.$element.find('.item.active')
var $next = next || this.getItemForDirection(type, $active)
var isCycling = this.interval
var direction = type == 'next' ? 'left' : 'right'
var that = this
if ($next.hasClass('active')) return (this.sliding = false)
var relatedTarget = $next[0]
var slideEvent = $.Event('slide.bs.carousel', {
relatedTarget: relatedTarget,
direction: direction
})
this.$element.trigger(slideEvent)
if (slideEvent.isDefaultPrevented()) return
this.sliding = true
isCycling && this.pause()
if (this.$indicators.length) {
this.$indicators.find('.active').removeClass('active')
var $nextIndicator = $(this.$indicators.children()[this.getItemIndex($next)])
$nextIndicator && $nextIndicator.addClass('active')
}
var slidEvent = $.Event('slid.bs.carousel', { relatedTarget: relatedTarget, direction: direction }) // yes, "slid"
if ($.support.transition && this.$element.hasClass('slide')) {
$next.addClass(type)
$next[0].offsetWidth // force reflow
$active.addClass(direction)
$next.addClass(direction)
$active
.one('bsTransitionEnd', function() {
$next.removeClass([type, direction].join(' ')).addClass('active')
$active.removeClass(['active', direction].join(' '))
that.sliding = false
setTimeout(function() {
that.$element.trigger(slidEvent)
}, 0)
})
.emulateTransitionEnd(Carousel.TRANSITION_DURATION)
} else {
$active.removeClass('active')
$next.addClass('active')
this.sliding = false
this.$element.trigger(slidEvent)
}
isCycling && this.cycle()
return this
}
// CAROUSEL PLUGIN DEFINITION
// ==========================
function Plugin(option) {
return this.each(function() {
var $this = $(this)
var data = $this.data('bs.carousel')
var options = $.extend({}, Carousel.DEFAULTS, $this.data(), typeof option == 'object' && option)
var action = typeof option == 'string' ? option : options.slide
if (!data) $this.data('bs.carousel', (data = new Carousel(this, options)))
if (typeof option == 'number') data.to(option)
else if (action) data[action]()
else if (options.interval) data.pause().cycle()
})
}
var old = $.fn.carousel
$.fn.carousel = Plugin
$.fn.carousel.Constructor = Carousel
// CAROUSEL NO CONFLICT
// ====================
$.fn.carousel.noConflict = function() {
$.fn.carousel = old
return this
}
// CAROUSEL DATA-API
// =================
var clickHandler = function(e) {
var href
var $this = $(this)
var $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) // strip for ie7
if (!$target.hasClass('carousel')) return
var options = $.extend({}, $target.data(), $this.data())
var slideIndex = $this.attr('data-slide-to')
if (slideIndex) options.interval = false
Plugin.call($target, options)
if (slideIndex) {
$target.data('bs.carousel').to(slideIndex)
}
e.preventDefault()
}
$(document)
.on('click.bs.carousel.data-api', '[data-slide]', clickHandler)
.on('click.bs.carousel.data-api', '[data-slide-to]', clickHandler)
$(window).on('load', function() {
$('[data-ride="carousel"]').each(function() {
var $carousel = $(this)
Plugin.call($carousel, $carousel.data())
})
})
}(jQuery);
/* ========================================================================
* Bootstrap: collapse.js v3.3.6
* http://getbootstrap.com/javascript/#collapse
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+
function($) {
'use strict';
// COLLAPSE PUBLIC CLASS DEFINITION
// ================================
var Collapse = function(element, options) {
this.$element = $(element)
this.options = $.extend({}, Collapse.DEFAULTS, options)
this.$trigger = $('[data-toggle="collapse"][href="#' + element.id + '"],' +
'[data-toggle="collapse"][data-target="#' + element.id + '"]')
this.transitioning = null
if (this.options.parent) {
this.$parent = this.getParent()
} else {
this.addAriaAndCollapsedClass(this.$element, this.$trigger)
}
if (this.options.toggle) this.toggle()
}
Collapse.VERSION = '3.3.6'
Collapse.TRANSITION_DURATION = 350
Collapse.DEFAULTS = {
toggle: true
}
Collapse.prototype.dimension = function() {
var hasWidth = this.$element.hasClass('width')
return hasWidth ? 'width' : 'height'
}
Collapse.prototype.show = function() {
if (this.transitioning || this.$element.hasClass('in')) return
var activesData
var actives = this.$parent && this.$parent.children('.panel').children('.in, .collapsing')
if (actives && actives.length) {
activesData = actives.data('bs.collapse')
if (activesData && activesData.transitioning) return
}
var startEvent = $.Event('show.bs.collapse')
this.$element.trigger(startEvent)
if (startEvent.isDefaultPrevented()) return
if (actives && actives.length) {
Plugin.call(actives, 'hide')
activesData || actives.data('bs.collapse', null)
}
var dimension = this.dimension()
this.$element
.removeClass('collapse')
.addClass('collapsing')[dimension](0)
.attr('aria-expanded', true)
this.$trigger
.removeClass('collapsed')
.attr('aria-expanded', true)
this.transitioning = 1
var complete = function() {
this.$element
.removeClass('collapsing')
.addClass('collapse in')[dimension]('')
this.transitioning = 0
this.$element
.trigger('shown.bs.collapse')
}
if (!$.support.transition) return complete.call(this)
var scrollSize = $.camelCase(['scroll', dimension].join('-'))
this.$element
.one('bsTransitionEnd', $.proxy(complete, this))
.emulateTransitionEnd(Collapse.TRANSITION_DURATION)[dimension](this.$element[0][scrollSize])
}
Collapse.prototype.hide = function() {
if (this.transitioning || !this.$element.hasClass('in')) return
var startEvent = $.Event('hide.bs.collapse')
this.$element.trigger(startEvent)
if (startEvent.isDefaultPrevented()) return
var dimension = this.dimension()
this.$element[dimension](this.$element[dimension]())[0].offsetHeight
this.$element
.addClass('collapsing')
.removeClass('collapse in')
.attr('aria-expanded', false)
this.$trigger
.addClass('collapsed')
.attr('aria-expanded', false)
this.transitioning = 1
var complete = function() {
this.transitioning = 0
this.$element
.removeClass('collapsing')
.addClass('collapse')
.trigger('hidden.bs.collapse')
}
if (!$.support.transition) return complete.call(this)
this.$element[dimension](0)
.one('bsTransitionEnd', $.proxy(complete, this))
.emulateTransitionEnd(Collapse.TRANSITION_DURATION)
}
Collapse.prototype.toggle = function() {
this[this.$element.hasClass('in') ? 'hide' : 'show']()
}
Collapse.prototype.getParent = function() {
return $(this.options.parent)
.find('[data-toggle="collapse"][data-parent="' + this.options.parent + '"]')
.each($.proxy(function(i, element) {
var $element = $(element)
this.addAriaAndCollapsedClass(getTargetFromTrigger($element), $element)
}, this))
.end()
}
Collapse.prototype.addAriaAndCollapsedClass = function($element, $trigger) {
var isOpen = $element.hasClass('in')
$element.attr('aria-expanded', isOpen)
$trigger
.toggleClass('collapsed', !isOpen)
.attr('aria-expanded', isOpen)
}
function getTargetFromTrigger($trigger) {
var href
var target = $trigger.attr('data-target') ||
(href = $trigger.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') // strip for ie7
return $(target)
}
// COLLAPSE PLUGIN DEFINITION
// ==========================
function Plugin(option) {
return this.each(function() {
var $this = $(this)
var data = $this.data('bs.collapse')
var options = $.extend({}, Collapse.DEFAULTS, $this.data(), typeof option == 'object' && option)
if (!data && options.toggle && /show|hide/.test(option)) options.toggle = false
if (!data) $this.data('bs.collapse', (data = new Collapse(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.collapse
$.fn.collapse = Plugin
$.fn.collapse.Constructor = Collapse
// COLLAPSE NO CONFLICT
// ====================
$.fn.collapse.noConflict = function() {
$.fn.collapse = old
return this
}
// COLLAPSE DATA-API
// =================
$(document).on('click.bs.collapse.data-api', '[data-toggle="collapse"]', function(e) {
var $this = $(this)
if (!$this.attr('data-target')) e.preventDefault()
var $target = getTargetFromTrigger($this)
var data = $target.data('bs.collapse')
var option = data ? 'toggle' : $this.data()
Plugin.call($target, option)
})
}(jQuery);
/* ========================================================================
* Bootstrap: dropdown.js v3.3.6
* http://getbootstrap.com/javascript/#dropdowns
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+
function($) {
'use strict';
// DROPDOWN CLASS DEFINITION
// =========================
var backdrop = '.dropdown-backdrop'
var toggle = '[data-toggle="dropdown"]'
var Dropdown = function(element) {
$(element).on('click.bs.dropdown', this.toggle)
}
Dropdown.VERSION = '3.3.6'
function getParent($this) {
var selector = $this.attr('data-target')
if (!selector) {
selector = $this.attr('href')
selector = selector && /#[A-Za-z]/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
}
var $parent = selector && $(selector)
return $parent && $parent.length ? $parent : $this.parent()
}
function clearMenus(e) {
if (e && e.which === 3) return
$(backdrop).remove()
$(toggle).each(function() {
var $this = $(this)
var $parent = getParent($this)
var relatedTarget = { relatedTarget: this }
if (!$parent.hasClass('open')) return
if (e && e.type == 'click' && /input|textarea/i.test(e.target.tagName) && $.contains($parent[0], e.target)) return
$parent.trigger(e = $.Event('hide.bs.dropdown', relatedTarget))
if (e.isDefaultPrevented()) return
$this.attr('aria-expanded', 'false')
$parent.removeClass('open').trigger($.Event('hidden.bs.dropdown', relatedTarget))
})
}
Dropdown.prototype.toggle = function(e) {
var $this = $(this)
if ($this.is('.disabled, :disabled')) return
var $parent = getParent($this)
var isActive = $parent.hasClass('open')
clearMenus()
if (!isActive) {
if ('ontouchstart' in document.documentElement && !$parent.closest('.navbar-nav').length) {
// if mobile we use a backdrop because click events don't delegate
$(document.createElement('div'))
.addClass('dropdown-backdrop')
.insertAfter($(this))
.on('click', clearMenus)
}
var relatedTarget = { relatedTarget: this }
$parent.trigger(e = $.Event('show.bs.dropdown', relatedTarget))
if (e.isDefaultPrevented()) return
$this
.trigger('focus')
.attr('aria-expanded', 'true')
$parent
.toggleClass('open')
.trigger($.Event('shown.bs.dropdown', relatedTarget))
}
return false
}
Dropdown.prototype.keydown = function(e) {
if (!/(38|40|27|32)/.test(e.which) || /input|textarea/i.test(e.target.tagName)) return
var $this = $(this)
e.preventDefault()
e.stopPropagation()
if ($this.is('.disabled, :disabled')) return
var $parent = getParent($this)
var isActive = $parent.hasClass('open')
if (!isActive && e.which != 27 || isActive && e.which == 27) {
if (e.which == 27) $parent.find(toggle).trigger('focus')
return $this.trigger('click')
}
var desc = ' li:not(.disabled):visible a'
var $items = $parent.find('.dropdown-menu' + desc)
if (!$items.length) return
var index = $items.index(e.target)
if (e.which == 38 && index > 0) index-- // up
if (e.which == 40 && index < $items.length - 1) index++ // down
if (!~index) index = 0
$items.eq(index).trigger('focus')
}
// DROPDOWN PLUGIN DEFINITION
// ==========================
function Plugin(option) {
return this.each(function() {
var $this = $(this)
var data = $this.data('bs.dropdown')
if (!data) $this.data('bs.dropdown', (data = new Dropdown(this)))
if (typeof option == 'string') data[option].call($this)
})
}
var old = $.fn.dropdown
$.fn.dropdown = Plugin
$.fn.dropdown.Constructor = Dropdown
// DROPDOWN NO CONFLICT
// ====================
$.fn.dropdown.noConflict = function() {
$.fn.dropdown = old
return this
}
// APPLY TO STANDARD DROPDOWN ELEMENTS
// ===================================
$(document)
.on('click.bs.dropdown.data-api', clearMenus)
.on('click.bs.dropdown.data-api', '.dropdown form', function(e) { e.stopPropagation() })
.on('click.bs.dropdown.data-api', toggle, Dropdown.prototype.toggle)
.on('keydown.bs.dropdown.data-api', toggle, Dropdown.prototype.keydown)
.on('keydown.bs.dropdown.data-api', '.dropdown-menu', Dropdown.prototype.keydown)
}(jQuery);
/* ========================================================================
* Bootstrap: modal.js v3.3.6
* http://getbootstrap.com/javascript/#modals
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+
function($) {
'use strict';
// MODAL CLASS DEFINITION
// ======================
var Modal = function(element, options) {
this.options = options
this.$body = $(document.body)
this.$element = $(element)
this.$dialog = this.$element.find('.modal-dialog')
this.$backdrop = null
this.isShown = null
this.originalBodyPad = null
this.scrollbarWidth = 0
this.ignoreBackdropClick = false
if (this.options.remote) {
this.$element
.find('.modal-content')
.load(this.options.remote, $.proxy(function() {
this.$element.trigger('loaded.bs.modal')
}, this))
}
}
Modal.VERSION = '3.3.6'
Modal.TRANSITION_DURATION = 300
Modal.BACKDROP_TRANSITION_DURATION = 150
Modal.DEFAULTS = {
backdrop: true,
keyboard: true,
show: true
}
Modal.prototype.toggle = function(_relatedTarget) {
return this.isShown ? this.hide() : this.show(_relatedTarget)
}
Modal.prototype.show = function(_relatedTarget) {
var that = this
var e = $.Event('show.bs.modal', { relatedTarget: _relatedTarget })
this.$element.trigger(e)
if (this.isShown || e.isDefaultPrevented()) return
this.isShown = true
this.checkScrollbar()
this.setScrollbar()
this.$body.addClass('modal-open')
this.escape()
this.resize()
this.$element.on('click.dismiss.bs.modal', '[data-dismiss="modal"]', $.proxy(this.hide, this))
this.$dialog.on('mousedown.dismiss.bs.modal', function() {
that.$element.one('mouseup.dismiss.bs.modal', function(e) {
if ($(e.target).is(that.$element)) that.ignoreBackdropClick = true
})
})
this.backdrop(function() {
var transition = $.support.transition && that.$element.hasClass('fade')
if (!that.$element.parent().length) {
that.$element.appendTo(that.$body) // don't move modals dom position
}
that.$element
.show()
.scrollTop(0)
that.adjustDialog()
if (transition) {
that.$element[0].offsetWidth // force reflow
}
that.$element.addClass('in')
that.enforceFocus()
var e = $.Event('shown.bs.modal', { relatedTarget: _relatedTarget })
transition ?
that.$dialog // wait for modal to slide in
.one('bsTransitionEnd', function() {
that.$element.trigger('focus').trigger(e)
})
.emulateTransitionEnd(Modal.TRANSITION_DURATION) :
that.$element.trigger('focus').trigger(e)
})
}
Modal.prototype.hide = function(e) {
if (e) e.preventDefault()
e = $.Event('hide.bs.modal')
this.$element.trigger(e)
if (!this.isShown || e.isDefaultPrevented()) return
this.isShown = false
this.escape()
this.resize()
$(document).off('focusin.bs.modal')
this.$element
.removeClass('in')
.off('click.dismiss.bs.modal')
.off('mouseup.dismiss.bs.modal')
this.$dialog.off('mousedown.dismiss.bs.modal')
$.support.transition && this.$element.hasClass('fade') ?
this.$element
.one('bsTransitionEnd', $.proxy(this.hideModal, this))
.emulateTransitionEnd(Modal.TRANSITION_DURATION) :
this.hideModal()
}
Modal.prototype.enforceFocus = function() {
$(document)
.off('focusin.bs.modal') // guard against infinite focus loop
.on('focusin.bs.modal', $.proxy(function(e) {
if (this.$element[0] !== e.target && !this.$element.has(e.target).length) {
this.$element.trigger('focus')
}
}, this))
}
Modal.prototype.escape = function() {
if (this.isShown && this.options.keyboard) {
this.$element.on('keydown.dismiss.bs.modal', $.proxy(function(e) {
e.which == 27 && this.hide()
}, this))
} else if (!this.isShown) {
this.$element.off('keydown.dismiss.bs.modal')
}
}
Modal.prototype.resize = function() {
if (this.isShown) {
$(window).on('resize.bs.modal', $.proxy(this.handleUpdate, this))
} else {
$(window).off('resize.bs.modal')
}
}
Modal.prototype.hideModal = function() {
var that = this
this.$element.hide()
this.backdrop(function() {
that.$body.removeClass('modal-open')
that.resetAdjustments()
that.resetScrollbar()
that.$element.trigger('hidden.bs.modal')
})
}
Modal.prototype.removeBackdrop = function() {
this.$backdrop && this.$backdrop.remove()
this.$backdrop = null
}
Modal.prototype.backdrop = function(callback) {
var that = this
var animate = this.$element.hasClass('fade') ? 'fade' : ''
if (this.isShown && this.options.backdrop) {
var doAnimate = $.support.transition && animate
this.$backdrop = $(document.createElement('div'))
.addClass('modal-backdrop ' + animate)
.appendTo(this.$body)
this.$element.on('click.dismiss.bs.modal', $.proxy(function(e) {
if (this.ignoreBackdropClick) {
this.ignoreBackdropClick = false
return
}
if (e.target !== e.currentTarget) return
this.options.backdrop == 'static' ?
this.$element[0].focus() :
this.hide()
}, this))
if (doAnimate) this.$backdrop[0].offsetWidth // force reflow
this.$backdrop.addClass('in')
if (!callback) return
doAnimate ?
this.$backdrop
.one('bsTransitionEnd', callback)
.emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) :
callback()
} else if (!this.isShown && this.$backdrop) {
this.$backdrop.removeClass('in')
var callbackRemove = function() {
that.removeBackdrop()
callback && callback()
}
$.support.transition && this.$element.hasClass('fade') ?
this.$backdrop
.one('bsTransitionEnd', callbackRemove)
.emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) :
callbackRemove()
} else if (callback) {
callback()
}
}
// these following methods are used to handle overflowing modals
Modal.prototype.handleUpdate = function() {
this.adjustDialog()
}
Modal.prototype.adjustDialog = function() {
var modalIsOverflowing = this.$element[0].scrollHeight > document.documentElement.clientHeight
this.$element.css({
paddingLeft: !this.bodyIsOverflowing && modalIsOverflowing ? this.scrollbarWidth : '',
paddingRight: this.bodyIsOverflowing && !modalIsOverflowing ? this.scrollbarWidth : ''
})
}
Modal.prototype.resetAdjustments = function() {
this.$element.css({
paddingLeft: '',
paddingRight: ''
})
}
Modal.prototype.checkScrollbar = function() {
var fullWindowWidth = window.innerWidth
if (!fullWindowWidth) { // workaround for missing window.innerWidth in IE8
var documentElementRect = document.documentElement.getBoundingClientRect()
fullWindowWidth = documentElementRect.right - Math.abs(documentElementRect.left)
}
this.bodyIsOverflowing = document.body.clientWidth < fullWindowWidth
this.scrollbarWidth = this.measureScrollbar()
}
Modal.prototype.setScrollbar = function() {
var bodyPad = parseInt((this.$body.css('padding-right') || 0), 10)
this.originalBodyPad = document.body.style.paddingRight || ''
if (this.bodyIsOverflowing) this.$body.css('padding-right', bodyPad + this.scrollbarWidth)
}
Modal.prototype.resetScrollbar = function() {
this.$body.css('padding-right', this.originalBodyPad)
}
Modal.prototype.measureScrollbar = function() { // thx walsh
var scrollDiv = document.createElement('div')
scrollDiv.className = 'modal-scrollbar-measure'
this.$body.append(scrollDiv)
var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth
this.$body[0].removeChild(scrollDiv)
return scrollbarWidth
}
// MODAL PLUGIN DEFINITION
// =======================
function Plugin(option, _relatedTarget) {
return this.each(function() {
var $this = $(this)
var data = $this.data('bs.modal')
var options = $.extend({}, Modal.DEFAULTS, $this.data(), typeof option == 'object' && option)
if (!data) $this.data('bs.modal', (data = new Modal(this, options)))
if (typeof option == 'string') data[option](_relatedTarget)
else if (options.show) data.show(_relatedTarget)
})
}
var old = $.fn.modal
$.fn.modal = Plugin
$.fn.modal.Constructor = Modal
// MODAL NO CONFLICT
// =================
$.fn.modal.noConflict = function() {
$.fn.modal = old
return this
}
// MODAL DATA-API
// ==============
$(document).on('click.bs.modal.data-api', '[data-toggle="modal"]', function(e) {
var $this = $(this)
var href = $this.attr('href')
var $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) // strip for ie7
var option = $target.data('bs.modal') ? 'toggle' : $.extend({ remote: !/#/.test(href) && href }, $target.data(), $this.data())
if ($this.is('a')) e.preventDefault()
$target.one('show.bs.modal', function(showEvent) {
if (showEvent.isDefaultPrevented()) return // only register focus restorer if modal will actually get shown
$target.one('hidden.bs.modal', function() {
$this.is(':visible') && $this.trigger('focus')
})
})
Plugin.call($target, option, this)
})
}(jQuery);
/* ========================================================================
* Bootstrap: tooltip.js v3.3.6
* http://getbootstrap.com/javascript/#tooltip
* Inspired by the original jQuery.tipsy by Jason Frame
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+
function($) {
'use strict';
// TOOLTIP PUBLIC CLASS DEFINITION
// ===============================
var Tooltip = function(element, options) {
this.type = null
this.options = null
this.enabled = null
this.timeout = null
this.hoverState = null
this.$element = null
this.inState = null
this.init('tooltip', element, options)
}
Tooltip.VERSION = '3.3.6'
Tooltip.TRANSITION_DURATION = 150
Tooltip.DEFAULTS = {
animation: true,
placement: 'top',
selector: false,
template: '<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',
trigger: 'hover focus',
title: '',
delay: 0,
html: false,
container: false,
viewport: {
selector: 'body',
padding: 0
}
}
Tooltip.prototype.init = function(type, element, options) {
this.enabled = true
this.type = type
this.$element = $(element)
this.options = this.getOptions(options)
this.$viewport = this.options.viewport && $($.isFunction(this.options.viewport) ? this.options.viewport.call(this, this.$element) : (this.options.viewport.selector || this.options.viewport))
this.inState = { click: false, hover: false, focus: false }
if (this.$element[0] instanceof document.constructor && !this.options.selector) {
throw new Error('`selector` option must be specified when initializing ' + this.type + ' on the window.document object!')
}
var triggers = this.options.trigger.split(' ')
for (var i = triggers.length; i--;) {
var trigger = triggers[i]
if (trigger == 'click') {
this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this))
} else if (trigger != 'manual') {
var eventIn = trigger == 'hover' ? 'mouseenter' : 'focusin'
var eventOut = trigger == 'hover' ? 'mouseleave' : 'focusout'
this.$element.on(eventIn + '.' + this.type, this.options.selector, $.proxy(this.enter, this))
this.$element.on(eventOut + '.' + this.type, this.options.selector, $.proxy(this.leave, this))
}
}
this.options.selector ?
(this._options = $.extend({}, this.options, { trigger: 'manual', selector: '' })) :
this.fixTitle()
}
Tooltip.prototype.getDefaults = function() {
return Tooltip.DEFAULTS
}
Tooltip.prototype.getOptions = function(options) {
options = $.extend({}, this.getDefaults(), this.$element.data(), options)
if (options.delay && typeof options.delay == 'number') {
options.delay = {
show: options.delay,
hide: options.delay
}
}
return options
}
Tooltip.prototype.getDelegateOptions = function() {
var options = {}
var defaults = this.getDefaults()
this._options && $.each(this._options, function(key, value) {
if (defaults[key] != value) options[key] = value
})
return options
}
Tooltip.prototype.enter = function(obj) {
var self = obj instanceof this.constructor ?
obj : $(obj.currentTarget).data('bs.' + this.type)
if (!self) {
self = new this.constructor(obj.currentTarget, this.getDelegateOptions())
$(obj.currentTarget).data('bs.' + this.type, self)
}
if (obj instanceof $.Event) {
self.inState[obj.type == 'focusin' ? 'focus' : 'hover'] = true
}
if (self.tip().hasClass('in') || self.hoverState == 'in') {
self.hoverState = 'in'
return
}
clearTimeout(self.timeout)
self.hoverState = 'in'
if (!self.options.delay || !self.options.delay.show) return self.show()
self.timeout = setTimeout(function() {
if (self.hoverState == 'in') self.show()
}, self.options.delay.show)
}
Tooltip.prototype.isInStateTrue = function() {
for (var key in this.inState) {
if (this.inState[key]) return true
}
return false
}
Tooltip.prototype.leave = function(obj) {
var self = obj instanceof this.constructor ?
obj : $(obj.currentTarget).data('bs.' + this.type)
if (!self) {
self = new this.constructor(obj.currentTarget, this.getDelegateOptions())
$(obj.currentTarget).data('bs.' + this.type, self)
}
if (obj instanceof $.Event) {
self.inState[obj.type == 'focusout' ? 'focus' : 'hover'] = false
}
if (self.isInStateTrue()) return
clearTimeout(self.timeout)
self.hoverState = 'out'
if (!self.options.delay || !self.options.delay.hide) return self.hide()
self.timeout = setTimeout(function() {
if (self.hoverState == 'out') self.hide()
}, self.options.delay.hide)
}
Tooltip.prototype.show = function() {
var e = $.Event('show.bs.' + this.type)
if (this.hasContent() && this.enabled) {
this.$element.trigger(e)
var inDom = $.contains(this.$element[0].ownerDocument.documentElement, this.$element[0])
if (e.isDefaultPrevented() || !inDom) return
var that = this
var $tip = this.tip()
var tipId = this.getUID(this.type)
this.setContent()
$tip.attr('id', tipId)
this.$element.attr('aria-describedby', tipId)
if (this.options.animation) $tip.addClass('fade')
var placement = typeof this.options.placement == 'function' ?
this.options.placement.call(this, $tip[0], this.$element[0]) :
this.options.placement
var autoToken = /\s?auto?\s?/i
var autoPlace = autoToken.test(placement)
if (autoPlace) placement = placement.replace(autoToken, '') || 'top'
$tip
.detach()
.css({ top: 0, left: 0, display: 'block' })
.addClass(placement)
.data('bs.' + this.type, this)
this.options.container ? $tip.appendTo(this.options.container) : $tip.insertAfter(this.$element)
this.$element.trigger('inserted.bs.' + this.type)
var pos = this.getPosition()
var actualWidth = $tip[0].offsetWidth
var actualHeight = $tip[0].offsetHeight
if (autoPlace) {
var orgPlacement = placement
var viewportDim = this.getPosition(this.$viewport)
placement = placement == 'bottom' && pos.bottom + actualHeight > viewportDim.bottom ? 'top' :
placement == 'top' && pos.top - actualHeight < viewportDim.top ? 'bottom' :
placement == 'right' && pos.right + actualWidth > viewportDim.width ? 'left' :
placement == 'left' && pos.left - actualWidth < viewportDim.left ? 'right' :
placement
$tip
.removeClass(orgPlacement)
.addClass(placement)
}
var calculatedOffset = this.getCalculatedOffset(placement, pos, actualWidth, actualHeight)
this.applyPlacement(calculatedOffset, placement)
var complete = function() {
var prevHoverState = that.hoverState
that.$element.trigger('shown.bs.' + that.type)
that.hoverState = null
if (prevHoverState == 'out') that.leave(that)
}
$.support.transition && this.$tip.hasClass('fade') ?
$tip
.one('bsTransitionEnd', complete)
.emulateTransitionEnd(Tooltip.TRANSITION_DURATION) :
complete()
}
}
Tooltip.prototype.applyPlacement = function(offset, placement) {
var $tip = this.tip()
var width = $tip[0].offsetWidth
var height = $tip[0].offsetHeight
// manually read margins because getBoundingClientRect includes difference
var marginTop = parseInt($tip.css('margin-top'), 10)
var marginLeft = parseInt($tip.css('margin-left'), 10)
// we must check for NaN for ie 8/9
if (isNaN(marginTop)) marginTop = 0
if (isNaN(marginLeft)) marginLeft = 0
offset.top += marginTop
offset.left += marginLeft
// $.fn.offset doesn't round pixel values
// so we use setOffset directly with our own function B-0
$.offset.setOffset($tip[0], $.extend({
using: function(props) {
$tip.css({
top: Math.round(props.top),
left: Math.round(props.left)
})
}
}, offset), 0)
$tip.addClass('in')
// check to see if placing tip in new offset caused the tip to resize itself
var actualWidth = $tip[0].offsetWidth
var actualHeight = $tip[0].offsetHeight
if (placement == 'top' && actualHeight != height) {
offset.top = offset.top + height - actualHeight
}
var delta = this.getViewportAdjustedDelta(placement, offset, actualWidth, actualHeight)
if (delta.left) offset.left += delta.left
else offset.top += delta.top
var isVertical = /top|bottom/.test(placement)
var arrowDelta = isVertical ? delta.left * 2 - width + actualWidth : delta.top * 2 - height + actualHeight
var arrowOffsetPosition = isVertical ? 'offsetWidth' : 'offsetHeight'
$tip.offset(offset)
this.replaceArrow(arrowDelta, $tip[0][arrowOffsetPosition], isVertical)
}
Tooltip.prototype.replaceArrow = function(delta, dimension, isVertical) {
this.arrow()
.css(isVertical ? 'left' : 'top', 50 * (1 - delta / dimension) + '%')
.css(isVertical ? 'top' : 'left', '')
}
Tooltip.prototype.setContent = function() {
var $tip = this.tip()
var title = this.getTitle()
$tip.find('.tooltip-inner')[this.options.html ? 'html' : 'text'](title)
$tip.removeClass('fade in top bottom left right')
}
Tooltip.prototype.hide = function(callback) {
var that = this
var $tip = $(this.$tip)
var e = $.Event('hide.bs.' + this.type)
function complete() {
if (that.hoverState != 'in') $tip.detach()
that.$element
.removeAttr('aria-describedby')
.trigger('hidden.bs.' + that.type)
callback && callback()
}
this.$element.trigger(e)
if (e.isDefaultPrevented()) return
$tip.removeClass('in')
$.support.transition && $tip.hasClass('fade') ?
$tip
.one('bsTransitionEnd', complete)
.emulateTransitionEnd(Tooltip.TRANSITION_DURATION) :
complete()
this.hoverState = null
return this
}
Tooltip.prototype.fixTitle = function() {
var $e = this.$element
if ($e.attr('title') || typeof $e.attr('data-original-title') != 'string') {
$e.attr('data-original-title', $e.attr('title') || '').attr('title', '')
}
}
Tooltip.prototype.hasContent = function() {
return this.getTitle()
}
Tooltip.prototype.getPosition = function($element) {
$element = $element || this.$element
var el = $element[0]
var isBody = el.tagName == 'BODY'
var elRect = el.getBoundingClientRect()
if (elRect.width == null) {
// width and height are missing in IE8, so compute them manually; see https://github.com/twbs/bootstrap/issues/14093
elRect = $.extend({}, elRect, { width: elRect.right - elRect.left, height: elRect.bottom - elRect.top })
}
var elOffset = isBody ? { top: 0, left: 0 } : $element.offset()
var scroll = { scroll: isBody ? document.documentElement.scrollTop || document.body.scrollTop : $element.scrollTop() }
var outerDims = isBody ? { width: $(window).width(), height: $(window).height() } : null
return $.extend({}, elRect, scroll, outerDims, elOffset)
}
Tooltip.prototype.getCalculatedOffset = function(placement, pos, actualWidth, actualHeight) {
return placement == 'bottom' ? { top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2 } :
placement == 'top' ? { top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2 } :
placement == 'left' ? { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth } :
/* placement == 'right' */
{ top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width }
}
Tooltip.prototype.getViewportAdjustedDelta = function(placement, pos, actualWidth, actualHeight) {
var delta = { top: 0, left: 0 }
if (!this.$viewport) return delta
var viewportPadding = this.options.viewport && this.options.viewport.padding || 0
var viewportDimensions = this.getPosition(this.$viewport)
if (/right|left/.test(placement)) {
var topEdgeOffset = pos.top - viewportPadding - viewportDimensions.scroll
var bottomEdgeOffset = pos.top + viewportPadding - viewportDimensions.scroll + actualHeight
if (topEdgeOffset < viewportDimensions.top) { // top overflow
delta.top = viewportDimensions.top - topEdgeOffset
} else if (bottomEdgeOffset > viewportDimensions.top + viewportDimensions.height) { // bottom overflow
delta.top = viewportDimensions.top + viewportDimensions.height - bottomEdgeOffset
}
} else {
var leftEdgeOffset = pos.left - viewportPadding
var rightEdgeOffset = pos.left + viewportPadding + actualWidth
if (leftEdgeOffset < viewportDimensions.left) { // left overflow
delta.left = viewportDimensions.left - leftEdgeOffset
} else if (rightEdgeOffset > viewportDimensions.right) { // right overflow
delta.left = viewportDimensions.left + viewportDimensions.width - rightEdgeOffset
}
}
return delta
}
Tooltip.prototype.getTitle = function() {
var title
var $e = this.$element
var o = this.options
title = $e.attr('data-original-title') ||
(typeof o.title == 'function' ? o.title.call($e[0]) : o.title)
return title
}
Tooltip.prototype.getUID = function(prefix) {
do prefix += ~~(Math.random() * 1000000)
while (document.getElementById(prefix))
return prefix
}
Tooltip.prototype.tip = function() {
if (!this.$tip) {
this.$tip = $(this.options.template)
if (this.$tip.length != 1) {
throw new Error(this.type + ' `template` option must consist of exactly 1 top-level element!')
}
}
return this.$tip
}
Tooltip.prototype.arrow = function() {
return (this.$arrow = this.$arrow || this.tip().find('.tooltip-arrow'))
}
Tooltip.prototype.enable = function() {
this.enabled = true
}
Tooltip.prototype.disable = function() {
this.enabled = false
}
Tooltip.prototype.toggleEnabled = function() {
this.enabled = !this.enabled
}
Tooltip.prototype.toggle = function(e) {
var self = this
if (e) {
self = $(e.currentTarget).data('bs.' + this.type)
if (!self) {
self = new this.constructor(e.currentTarget, this.getDelegateOptions())
$(e.currentTarget).data('bs.' + this.type, self)
}
}
if (e) {
self.inState.click = !self.inState.click
if (self.isInStateTrue()) self.enter(self)
else self.leave(self)
} else {
self.tip().hasClass('in') ? self.leave(self) : self.enter(self)
}
}
Tooltip.prototype.destroy = function() {
var that = this
clearTimeout(this.timeout)
this.hide(function() {
that.$element.off('.' + that.type).removeData('bs.' + that.type)
if (that.$tip) {
that.$tip.detach()
}
that.$tip = null
that.$arrow = null
that.$viewport = null
})
}
// TOOLTIP PLUGIN DEFINITION
// =========================
function Plugin(option) {
return this.each(function() {
var $this = $(this)
var data = $this.data('bs.tooltip')
var options = typeof option == 'object' && option
if (!data && /destroy|hide/.test(option)) return
if (!data) $this.data('bs.tooltip', (data = new Tooltip(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.tooltip
$.fn.tooltip = Plugin
$.fn.tooltip.Constructor = Tooltip
// TOOLTIP NO CONFLICT
// ===================
$.fn.tooltip.noConflict = function() {
$.fn.tooltip = old
return this
}
}(jQuery);
/* ========================================================================
* Bootstrap: popover.js v3.3.6
* http://getbootstrap.com/javascript/#popovers
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+
function($) {
'use strict';
// POPOVER PUBLIC CLASS DEFINITION
// ===============================
var Popover = function(element, options) {
this.init('popover', element, options)
}
if (!$.fn.tooltip) throw new Error('Popover requires tooltip.js')
Popover.VERSION = '3.3.6'
Popover.DEFAULTS = $.extend({}, $.fn.tooltip.Constructor.DEFAULTS, {
placement: 'right',
trigger: 'click',
content: '',
template: '<div class="popover" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'
})
// NOTE: POPOVER EXTENDS tooltip.js
// ================================
Popover.prototype = $.extend({}, $.fn.tooltip.Constructor.prototype)
Popover.prototype.constructor = Popover
Popover.prototype.getDefaults = function() {
return Popover.DEFAULTS
}
Popover.prototype.setContent = function() {
var $tip = this.tip()
var title = this.getTitle()
var content = this.getContent()
$tip.find('.popover-title')[this.options.html ? 'html' : 'text'](title)
$tip.find('.popover-content').children().detach().end()[ // we use append for html objects to maintain js events
this.options.html ? (typeof content == 'string' ? 'html' : 'append') : 'text'
](content)
$tip.removeClass('fade top bottom left right in')
// IE8 doesn't accept hiding via the `:empty` pseudo selector, we have to do
// this manually by checking the contents.
if (!$tip.find('.popover-title').html()) $tip.find('.popover-title').hide()
}
Popover.prototype.hasContent = function() {
return this.getTitle() || this.getContent()
}
Popover.prototype.getContent = function() {
var $e = this.$element
var o = this.options
return $e.attr('data-content') ||
(typeof o.content == 'function' ?
o.content.call($e[0]) :
o.content)
}
Popover.prototype.arrow = function() {
return (this.$arrow = this.$arrow || this.tip().find('.arrow'))
}
// POPOVER PLUGIN DEFINITION
// =========================
function Plugin(option) {
return this.each(function() {
var $this = $(this)
var data = $this.data('bs.popover')
var options = typeof option == 'object' && option
if (!data && /destroy|hide/.test(option)) return
if (!data) $this.data('bs.popover', (data = new Popover(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.popover
$.fn.popover = Plugin
$.fn.popover.Constructor = Popover
// POPOVER NO CONFLICT
// ===================
$.fn.popover.noConflict = function() {
$.fn.popover = old
return this
}
}(jQuery);
/* ========================================================================
* Bootstrap: scrollspy.js v3.3.6
* http://getbootstrap.com/javascript/#scrollspy
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+
function($) {
'use strict';
// SCROLLSPY CLASS DEFINITION
// ==========================
function ScrollSpy(element, options) {
this.$body = $(document.body)
this.$scrollElement = $(element).is(document.body) ? $(window) : $(element)
this.options = $.extend({}, ScrollSpy.DEFAULTS, options)
this.selector = (this.options.target || '') + ' .nav li > a'
this.offsets = []
this.targets = []
this.activeTarget = null
this.scrollHeight = 0
this.$scrollElement.on('scroll.bs.scrollspy', $.proxy(this.process, this))
this.refresh()
this.process()
}
ScrollSpy.VERSION = '3.3.6'
ScrollSpy.DEFAULTS = {
offset: 10
}
ScrollSpy.prototype.getScrollHeight = function() {
return this.$scrollElement[0].scrollHeight || Math.max(this.$body[0].scrollHeight, document.documentElement.scrollHeight)
}
ScrollSpy.prototype.refresh = function() {
var that = this
var offsetMethod = 'offset'
var offsetBase = 0
this.offsets = []
this.targets = []
this.scrollHeight = this.getScrollHeight()
if (!$.isWindow(this.$scrollElement[0])) {
offsetMethod = 'position'
offsetBase = this.$scrollElement.scrollTop()
}
this.$body
.find(this.selector)
.map(function() {
var $el = $(this)
var href = $el.data('target') || $el.attr('href')
var $href = /^#./.test(href) && $(href)
return ($href &&
$href.length &&
$href.is(':visible') &&
[
[$href[offsetMethod]().top + offsetBase, href]
]) || null
})
.sort(function(a, b) { return a[0] - b[0] })
.each(function() {
that.offsets.push(this[0])
that.targets.push(this[1])
})
}
ScrollSpy.prototype.process = function() {
var scrollTop = this.$scrollElement.scrollTop() + this.options.offset
var scrollHeight = this.getScrollHeight()
var maxScroll = this.options.offset + scrollHeight - this.$scrollElement.height()
var offsets = this.offsets
var targets = this.targets
var activeTarget = this.activeTarget
var i
if (this.scrollHeight != scrollHeight) {
this.refresh()
}
if (scrollTop >= maxScroll) {
return activeTarget != (i = targets[targets.length - 1]) && this.activate(i)
}
if (activeTarget && scrollTop < offsets[0]) {
this.activeTarget = null
return this.clear()
}
for (i = offsets.length; i--;) {
activeTarget != targets[i] &&
scrollTop >= offsets[i] &&
(offsets[i + 1] === undefined || scrollTop < offsets[i + 1]) &&
this.activate(targets[i])
}
}
ScrollSpy.prototype.activate = function(target) {
this.activeTarget = target
this.clear()
var selector = this.selector +
'[data-target="' + target + '"],' +
this.selector + '[href="' + target + '"]'
var active = $(selector)
.parents('li')
.addClass('active')
if (active.parent('.dropdown-menu').length) {
active = active
.closest('li.dropdown')
.addClass('active')
}
active.trigger('activate.bs.scrollspy')
}
ScrollSpy.prototype.clear = function() {
$(this.selector)
.parentsUntil(this.options.target, '.active')
.removeClass('active')
}
// SCROLLSPY PLUGIN DEFINITION
// ===========================
function Plugin(option) {
return this.each(function() {
var $this = $(this)
var data = $this.data('bs.scrollspy')
var options = typeof option == 'object' && option
if (!data) $this.data('bs.scrollspy', (data = new ScrollSpy(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.scrollspy
$.fn.scrollspy = Plugin
$.fn.scrollspy.Constructor = ScrollSpy
// SCROLLSPY NO CONFLICT
// =====================
$.fn.scrollspy.noConflict = function() {
$.fn.scrollspy = old
return this
}
// SCROLLSPY DATA-API
// ==================
$(window).on('load.bs.scrollspy.data-api', function() {
$('[data-spy="scroll"]').each(function() {
var $spy = $(this)
Plugin.call($spy, $spy.data())
})
})
}(jQuery);
/* ========================================================================
* Bootstrap: tab.js v3.3.6
* http://getbootstrap.com/javascript/#tabs
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+
function($) {
'use strict';
// TAB CLASS DEFINITION
// ====================
var Tab = function(element) {
// jscs:disable requireDollarBeforejQueryAssignment
this.element = $(element)
// jscs:enable requireDollarBeforejQueryAssignment
}
Tab.VERSION = '3.3.6'
Tab.TRANSITION_DURATION = 150
Tab.prototype.show = function() {
var $this = this.element
var $ul = $this.closest('ul:not(.dropdown-menu)')
var selector = $this.data('target')
if (!selector) {
selector = $this.attr('href')
selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
}
if ($this.parent('li').hasClass('active')) return
var $previous = $ul.find('.active:last a')
var hideEvent = $.Event('hide.bs.tab', {
relatedTarget: $this[0]
})
var showEvent = $.Event('show.bs.tab', {
relatedTarget: $previous[0]
})
$previous.trigger(hideEvent)
$this.trigger(showEvent)
if (showEvent.isDefaultPrevented() || hideEvent.isDefaultPrevented()) return
var $target = $(selector)
this.activate($this.closest('li'), $ul)
this.activate($target, $target.parent(), function() {
$previous.trigger({
type: 'hidden.bs.tab',
relatedTarget: $this[0]
})
$this.trigger({
type: 'shown.bs.tab',
relatedTarget: $previous[0]
})
})
}
Tab.prototype.activate = function(element, container, callback) {
var $active = container.find('> .active')
var transition = callback &&
$.support.transition &&
($active.length && $active.hasClass('fade') || !!container.find('> .fade').length)
function next() {
$active
.removeClass('active')
.find('> .dropdown-menu > .active')
.removeClass('active')
.end()
.find('[data-toggle="tab"]')
.attr('aria-expanded', false)
element
.addClass('active')
.find('[data-toggle="tab"]')
.attr('aria-expanded', true)
if (transition) {
element[0].offsetWidth // reflow for transition
element.addClass('in')
} else {
element.removeClass('fade')
}
if (element.parent('.dropdown-menu').length) {
element
.closest('li.dropdown')
.addClass('active')
.end()
.find('[data-toggle="tab"]')
.attr('aria-expanded', true)
}
callback && callback()
}
$active.length && transition ?
$active
.one('bsTransitionEnd', next)
.emulateTransitionEnd(Tab.TRANSITION_DURATION) :
next()
$active.removeClass('in')
}
// TAB PLUGIN DEFINITION
// =====================
function Plugin(option) {
return this.each(function() {
var $this = $(this)
var data = $this.data('bs.tab')
if (!data) $this.data('bs.tab', (data = new Tab(this)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.tab
$.fn.tab = Plugin
$.fn.tab.Constructor = Tab
// TAB NO CONFLICT
// ===============
$.fn.tab.noConflict = function() {
$.fn.tab = old
return this
}
// TAB DATA-API
// ============
var clickHandler = function(e) {
e.preventDefault()
Plugin.call($(this), 'show')
}
$(document)
.on('click.bs.tab.data-api', '[data-toggle="tab"]', clickHandler)
.on('click.bs.tab.data-api', '[data-toggle="pill"]', clickHandler)
}(jQuery);
/* ========================================================================
* Bootstrap: affix.js v3.3.6
* http://getbootstrap.com/javascript/#affix
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+
function($) {
'use strict';
// AFFIX CLASS DEFINITION
// ======================
var Affix = function(element, options) {
this.options = $.extend({}, Affix.DEFAULTS, options)
this.$target = $(this.options.target)
.on('scroll.bs.affix.data-api', $.proxy(this.checkPosition, this))
.on('click.bs.affix.data-api', $.proxy(this.checkPositionWithEventLoop, this))
this.$element = $(element)
this.affixed = null
this.unpin = null
this.pinnedOffset = null
this.checkPosition()
}
Affix.VERSION = '3.3.6'
Affix.RESET = 'affix affix-top affix-bottom'
Affix.DEFAULTS = {
offset: 0,
target: window
}
Affix.prototype.getState = function(scrollHeight, height, offsetTop, offsetBottom) {
var scrollTop = this.$target.scrollTop()
var position = this.$element.offset()
var targetHeight = this.$target.height()
if (offsetTop != null && this.affixed == 'top') return scrollTop < offsetTop ? 'top' : false
if (this.affixed == 'bottom') {
if (offsetTop != null) return (scrollTop + this.unpin <= position.top) ? false : 'bottom'
return (scrollTop + targetHeight <= scrollHeight - offsetBottom) ? false : 'bottom'
}
var initializing = this.affixed == null
var colliderTop = initializing ? scrollTop : position.top
var colliderHeight = initializing ? targetHeight : height
if (offsetTop != null && scrollTop <= offsetTop) return 'top'
if (offsetBottom != null && (colliderTop + colliderHeight >= scrollHeight - offsetBottom)) return 'bottom'
return false
}
Affix.prototype.getPinnedOffset = function() {
if (this.pinnedOffset) return this.pinnedOffset
this.$element.removeClass(Affix.RESET).addClass('affix')
var scrollTop = this.$target.scrollTop()
var position = this.$element.offset()
return (this.pinnedOffset = position.top - scrollTop)
}
Affix.prototype.checkPositionWithEventLoop = function() {
setTimeout($.proxy(this.checkPosition, this), 1)
}
Affix.prototype.checkPosition = function() {
if (!this.$element.is(':visible')) return
var height = this.$element.height()
var offset = this.options.offset
var offsetTop = offset.top
var offsetBottom = offset.bottom
var scrollHeight = Math.max($(document).height(), $(document.body).height())
if (typeof offset != 'object') offsetBottom = offsetTop = offset
if (typeof offsetTop == 'function') offsetTop = offset.top(this.$element)
if (typeof offsetBottom == 'function') offsetBottom = offset.bottom(this.$element)
var affix = this.getState(scrollHeight, height, offsetTop, offsetBottom)
if (this.affixed != affix) {
if (this.unpin != null) this.$element.css('top', '')
var affixType = 'affix' + (affix ? '-' + affix : '')
var e = $.Event(affixType + '.bs.affix')
this.$element.trigger(e)
if (e.isDefaultPrevented()) return
this.affixed = affix
this.unpin = affix == 'bottom' ? this.getPinnedOffset() : null
this.$element
.removeClass(Affix.RESET)
.addClass(affixType)
.trigger(affixType.replace('affix', 'affixed') + '.bs.affix')
}
if (affix == 'bottom') {
this.$element.offset({
top: scrollHeight - height - offsetBottom
})
}
}
// AFFIX PLUGIN DEFINITION
// =======================
function Plugin(option) {
return this.each(function() {
var $this = $(this)
var data = $this.data('bs.affix')
var options = typeof option == 'object' && option
if (!data) $this.data('bs.affix', (data = new Affix(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.affix
$.fn.affix = Plugin
$.fn.affix.Constructor = Affix
// AFFIX NO CONFLICT
// =================
$.fn.affix.noConflict = function() {
$.fn.affix = old
return this
}
// AFFIX DATA-API
// ==============
$(window).on('load', function() {
$('[data-spy="affix"]').each(function() {
var $spy = $(this)
var data = $spy.data()
data.offset = data.offset || {}
if (data.offsetBottom != null) data.offset.bottom = data.offsetBottom
if (data.offsetTop != null) data.offset.top = data.offsetTop
Plugin.call($spy, data)
})
})
}(jQuery); | octapush/octapushJS | docs/assets/bootstrap/js/bootstrap.js | JavaScript | mit | 75,339 |
var assert = require('assert');
describe('src/components/model/classes/Collection', function () {
var Collection = require('../../../../src/components/model/classes/Collection');
var collection;
var handler = function (event, changes) {
callbacks[event]++;
};
var callbacks = {
add: 0,
remove: 0,
change: 0
};
describe.only('new Collection(obj)', function () {
it('Should return a new Collection instance', function (done) {
collection = new Collection([1, 2, 3], handler);
done();
});
});
describe.only('.push(item)', function () {
it('Should call "add" callback', function (done) {
collection.push(4);
assert(callbacks.add, 1);
done();
});
});
describe.only('.unshift(item)', function () {
it('Should call "add" callback', function (done) {
collection.unshift(0);
assert(callbacks.add, 2);
done();
});
});
describe.only('.pop()', function () {
it('Should call "remove" callback', function (done) {
collection.pop();
assert(callbacks.remove, 1);
done();
});
});
describe.only('.shift()', function () {
it('Should call "remove" callback', function (done) {
collection.shift();
assert(callbacks.remove, 2);
done();
});
});
describe.only('.splice(index, number)', function () {
it('Should call "remove" callback', function (done) {
collection.splice(0, 1);
assert(callbacks.remove, 3);
done();
});
});
describe.only('.reverse()', function () {
it('Should call "change" callback', function (done) {
collection.reverse();
assert(callbacks.change, 1);
done();
});
});
describe.only('.sort()', function () {
it('Should call "change" callback', function (done) {
collection.sort(function (a, b) {
return -1;
});
assert(callbacks.change, 2);
done();
});
});
});
| moduleon/nucleon | test/components/model/classes/Collection.js | JavaScript | mit | 2,216 |
/**
* boot/middleware.js
* Express middleware
*/
| swhite24/react-todo-exploration | server/boot/middleware.js | JavaScript | mit | 52 |
import React from 'react';
import Status from 'components/Status';
import renderer from 'react-test-renderer';
describe('Status component', () => {
function getComponent(piecesLeftCount) {
return renderer.create(
<Status piecesLeftCount={piecesLeftCount} />
);
}
it('should show pieces left', () => {
expect(getComponent(9).toJSON()).toMatchSnapshot();
});
it('should show "Done" when no pieces left', () => {
expect(getComponent(0).toJSON()).toMatchSnapshot();
});
});
| dawid-drelichowski/puzzle-react-redux | src/js/tests/components/Status.test.js | JavaScript | mit | 507 |
var struct_l_p_c___r_t_c___type_def =
[
[ "ALDOM", "struct_l_p_c___r_t_c___type_def.html#aae1199a3f1f40f90aba18aee4d6325fd", null ],
[ "ALDOW", "struct_l_p_c___r_t_c___type_def.html#a5f56710f005f96878defbdb8ef1333c2", null ],
[ "ALDOY", "struct_l_p_c___r_t_c___type_def.html#a4c7ceb477c4a865ae51f5052dd558667", null ],
[ "ALHOUR", "struct_l_p_c___r_t_c___type_def.html#ac56690c26258c2cf9d28d09cc3447c1d", null ],
[ "ALMIN", "struct_l_p_c___r_t_c___type_def.html#a7e45902fca36066b22f41d0ef60d3c36", null ],
[ "ALMON", "struct_l_p_c___r_t_c___type_def.html#ad22f635b8c8b51dad2956e797a4dd9d3", null ],
[ "ALSEC", "struct_l_p_c___r_t_c___type_def.html#af3ff64ab3671109971425a05194acc7c", null ],
[ "ALYEAR", "struct_l_p_c___r_t_c___type_def.html#ab7f49ad885a354164adc263629d3a555", null ],
[ "AMR", "struct_l_p_c___r_t_c___type_def.html#a13f4e9721184b326043e6c6596f87790", null ],
[ "CALIBRATION", "struct_l_p_c___r_t_c___type_def.html#abe224f8608ae3d2c5b1036bf943b6c27", null ],
[ "CCR", "struct_l_p_c___r_t_c___type_def.html#af959ddb88caef28108c2926e310a72bd", null ],
[ "CIIR", "struct_l_p_c___r_t_c___type_def.html#a0df12e53986b72fbfcdceb537f7bf20e", null ],
[ "CTIME0", "struct_l_p_c___r_t_c___type_def.html#a97fa06b91b698236cb770d9618707bef", null ],
[ "CTIME1", "struct_l_p_c___r_t_c___type_def.html#a5b1a1b981a72c6d1cd482e75f1d44de4", null ],
[ "CTIME2", "struct_l_p_c___r_t_c___type_def.html#a411e06dfdcddd3fc19170231aa3a98be", null ],
[ "DOM", "struct_l_p_c___r_t_c___type_def.html#a7c70513eabbefbc5c5dd865a01ecc487", null ],
[ "DOW", "struct_l_p_c___r_t_c___type_def.html#a61f22d3ccb1c82db258f66d7d930db35", null ],
[ "DOY", "struct_l_p_c___r_t_c___type_def.html#a7b4a3d5692df3c5062ec927cedd16734", null ],
[ "GPREG0", "struct_l_p_c___r_t_c___type_def.html#ac42f0d8452c678fa007f0e0b862fb0c6", null ],
[ "GPREG1", "struct_l_p_c___r_t_c___type_def.html#abee4ae6eab2c33bdf38985d3b8a439f1", null ],
[ "GPREG2", "struct_l_p_c___r_t_c___type_def.html#a75f852bb2980febd2af7cc583e1445ec", null ],
[ "GPREG3", "struct_l_p_c___r_t_c___type_def.html#aad058be0cc120fffbbc66ad6f7c0c731", null ],
[ "GPREG4", "struct_l_p_c___r_t_c___type_def.html#afcc8f7898dce77fdb1082ff681387692", null ],
[ "HOUR", "struct_l_p_c___r_t_c___type_def.html#a76b8d6a8b13febe4289797f34ba73998", null ],
[ "ILR", "struct_l_p_c___r_t_c___type_def.html#aba869620e961b6eb9280229dad81e458", null ],
[ "MIN", "struct_l_p_c___r_t_c___type_def.html#a7a07167f54a5412387ee581fcd6dd2e0", null ],
[ "MONTH", "struct_l_p_c___r_t_c___type_def.html#a28fb9798e07b54b1098e9efe96ac244a", null ],
[ "RESERVED0", "struct_l_p_c___r_t_c___type_def.html#ad539ffa4484980685ca2da36b54fe61d", null ],
[ "RESERVED1", "struct_l_p_c___r_t_c___type_def.html#ad9fb3ef44fb733b524dcad0dfe34290e", null ],
[ "RESERVED10", "struct_l_p_c___r_t_c___type_def.html#a2d9caf1d8be9f2169521470b6ccd0377", null ],
[ "RESERVED11", "struct_l_p_c___r_t_c___type_def.html#a11e504ee49142f46dcc67740ae9235e5", null ],
[ "RESERVED12", "struct_l_p_c___r_t_c___type_def.html#a06137f06d699f26661c55209218bcada", null ],
[ "RESERVED13", "struct_l_p_c___r_t_c___type_def.html#a17672e7a5546cef19ee778266224c193", null ],
[ "RESERVED14", "struct_l_p_c___r_t_c___type_def.html#a1b9781efee5466ce7886eae907f24e60", null ],
[ "RESERVED15", "struct_l_p_c___r_t_c___type_def.html#a781148146471db4cd7d04029e383d115", null ],
[ "RESERVED16", "struct_l_p_c___r_t_c___type_def.html#af3ff60ce094e476f447a8046d873acb0", null ],
[ "RESERVED17", "struct_l_p_c___r_t_c___type_def.html#ae98d0c41e0bb8aef875fa8b53b25af54", null ],
[ "RESERVED18", "struct_l_p_c___r_t_c___type_def.html#aae0a4a7536dc03a352e8c48436b10263", null ],
[ "RESERVED19", "struct_l_p_c___r_t_c___type_def.html#a5552e97d80fc1a5bd195a9c81b270ffc", null ],
[ "RESERVED2", "struct_l_p_c___r_t_c___type_def.html#aff8b921ce3122ac6c22dc654a4f1b7ca", null ],
[ "RESERVED20", "struct_l_p_c___r_t_c___type_def.html#af7fcad34b88077879694c020956bf69b", null ],
[ "RESERVED21", "struct_l_p_c___r_t_c___type_def.html#ae26a65f4079b1f3af0490c463e6f6e90", null ],
[ "RESERVED3", "struct_l_p_c___r_t_c___type_def.html#a1936698394c9e65033538255b609f5d5", null ],
[ "RESERVED4", "struct_l_p_c___r_t_c___type_def.html#a23568af560875ec74b660f1860e06d3b", null ],
[ "RESERVED5", "struct_l_p_c___r_t_c___type_def.html#a17b8ef27f4663f5d6b0fe9c46ab9bc3d", null ],
[ "RESERVED6", "struct_l_p_c___r_t_c___type_def.html#a585b017c54971fb297a30e3927437015", null ],
[ "RESERVED7", "struct_l_p_c___r_t_c___type_def.html#af2e6e355909e4223f7665881b0514716", null ],
[ "RESERVED8", "struct_l_p_c___r_t_c___type_def.html#a8cb0d97b1d31d1921acc7aa587d1c60b", null ],
[ "RESERVED9", "struct_l_p_c___r_t_c___type_def.html#ad8b1fadb520f7a200ee0046e110edc79", null ],
[ "RTC_AUX", "struct_l_p_c___r_t_c___type_def.html#a8a91a5b909fbba65b28d972c3164a4ed", null ],
[ "RTC_AUXEN", "struct_l_p_c___r_t_c___type_def.html#a4f807cc73e86fa24a247e0dce31512a4", null ],
[ "SEC", "struct_l_p_c___r_t_c___type_def.html#a77f4a78b486ec068e5ced41419805802", null ],
[ "YEAR", "struct_l_p_c___r_t_c___type_def.html#aaf0ddcf6e202e34e9cf7b35c584f9849", null ]
]; | NicoLingg/TemperatureSensor_DS1621 | html/struct_l_p_c___r_t_c___type_def.js | JavaScript | mit | 5,285 |
/**
* @author Richard Davey <[email protected]>
* @copyright 2018 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
var RemoveTileAt = require('./RemoveTileAt');
var WorldToTileX = require('./WorldToTileX');
var WorldToTileY = require('./WorldToTileY');
/**
* Removes the tile at the given world coordinates in the specified layer and updates the layer's
* collision information.
*
* @function Phaser.Tilemaps.Components.RemoveTileAtWorldXY
* @private
* @since 3.0.0
*
* @param {number} worldX - [description]
* @param {number} worldY - [description]
* @param {boolean} [replaceWithNull=true] - If true, this will replace the tile at the specified
* location with null instead of a Tile with an index of -1.
* @param {boolean} [recalculateFaces=true] - [description]
* @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - [description]
* @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon.
*
* @return {Phaser.Tilemaps.Tile} The Tile object that was removed.
*/
var RemoveTileAtWorldXY = function (worldX, worldY, replaceWithNull, recalculateFaces, camera, layer)
{
var tileX = WorldToTileX(worldX, true, camera, layer);
var tileY = WorldToTileY(worldY, true, camera, layer);
return RemoveTileAt(tileX, tileY, replaceWithNull, recalculateFaces, layer);
};
module.exports = RemoveTileAtWorldXY;
| pixelpicosean/phaser | src/tilemaps/components/RemoveTileAtWorldXY.js | JavaScript | mit | 1,442 |
/**
* Created by JiaHao on 27/10/15.
*/
var fs = require('fs');
var path = require('path');
var normalizeNewline = require('normalize-newline');
function occurenceIndexes(inp, toFind) {
var indices = [];
var element = toFind;
var idx = inp.indexOf(element);
while (idx != -1) {
indices.push(idx);
idx = inp.indexOf(element, idx + 1);
}
return indices;
}
const ANNONATION = {
start: '{',
end: '}'
};
/**
* Parses a file at a path
* @param path
* @returns {Array}
* @param annotation
*/
function parseText(path, annotation) {
var rawText = normalizeNewline(fs.readFileSync(path).toString());
var annotationToken = annotation || ANNONATION;
var startOccurances = occurenceIndexes(rawText, annotationToken.start);
var endOccurances = occurenceIndexes(rawText, annotationToken.end);
var allOccurances = startOccurances.concat(endOccurances).sort(function(a, b){return a-b});
var subtractIndexes = {};
for (var i = 0; i < allOccurances.length; i++) {
subtractIndexes[allOccurances[i]] = i;
}
var result = [];
var stack = []; // stack of start occurances
var counter = 0;
var startOccuranceCounter = 0;
var endOccuranceCounter = 0;
var startOccuranceNext;
var endOccuranceNext;
while (counter < rawText.length) {
startOccuranceNext = startOccurances[startOccuranceCounter];
endOccuranceNext = endOccurances[endOccuranceCounter];
if (counter === startOccuranceNext) {
stack.push(startOccuranceNext);
startOccuranceCounter+=1;
} else if (counter === endOccuranceNext) {
var stackNext = stack.pop();
result.push([stackNext, endOccuranceNext]);
endOccuranceCounter+=1;
}
counter += 1;
}
var subtractFunction = function (element) {
return element - subtractIndexes[element];
};
result = result.map(function (tuple) {
return tuple.map(subtractFunction);
});
return result;
}
module.exports = parseText;
if (require.main === module) {
var expected = [
[6, 10],
[35, 39],
[71, 76],
[296, 303],
[356,362]
];
var toParsePath = path.join(__dirname, '../', 'examples/annotatedData.txt');
var result = parseText(toParsePath);
}
| jiahaog/brat | lib/parser.js | JavaScript | mit | 2,364 |
module.exports.sum = function (arr, prop, exp) {
var total = 0
for (var i = 0, _len = arr.length; i < _len; i++) {
var value = arr[i][prop];
if (exp) {
if (arr[i][exp.field] == exp.value) {
total += value * 1;
}
} else {
total += value * 1;
}
}
return total
};
| inamvar/bean | util/array.js | JavaScript | mit | 375 |
describe('Modules.Ellipsis.js', function() {
it('should exist with expected constructures', function() {
expect(moj.Modules.CaseCreation.init).toBeDefined();
});
});
| ministryofjustice/correspondence_tool_staff | spec/javascripts/modules/EllipsisSpec.js | JavaScript | mit | 174 |
import React, { Component } from 'react'
import {
Circle,
FeatureGroup,
LayerGroup,
Map,
Popup,
Rectangle,
TileLayer,
} from '../../src'
export default class OtherLayersExample extends Component {
render () {
const center = [51.505, -0.09]
const rectangle = [
[51.49, -0.08],
[51.5, -0.06],
]
return (
<Map center={center} zoom={13}>
<TileLayer
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url='http://{s}.tile.osm.org/{z}/{x}/{y}.png'
/>
<LayerGroup>
<Circle center={center} fillColor='blue' radius={200} />
<Circle center={center} fillColor='red' radius={100} stroke={false} />
<LayerGroup>
<Circle center={[51.51, -0.08]} color='green' fillColor='green' radius={100} />
</LayerGroup>
</LayerGroup>
<FeatureGroup color='purple'>
<Popup>
<span>Popup in FeatureGroup</span>
</Popup>
<Circle center={[51.51, -0.06]} radius={200} />
<Rectangle bounds={rectangle} />
</FeatureGroup>
</Map>
)
}
}
| yavuzmester/react-leaflet | example/components/other-layers.js | JavaScript | mit | 1,171 |
/**
* @author shirishgoyal
* created on 16.12.2015
*/
(function () {
'use strict';
angular.module('BlurAdmin.pages.auth', [
'BlurAdmin.services'
])
.config(routeConfig);
/** @ngInject */
function routeConfig($stateProvider) {
$stateProvider
.state('auth', {
url: '/auth',
abstract: true,
views: {
'full_screen': {
templateUrl: 'static/app/pages/auth/auth.html'
}
},
authenticate: false
})
// .state('auth.register', {
// url: '/register',
// templateUrl: 'static/app/pages/auth/register.html',
// controller: 'RegisterPageCtrl',
// controllerAs: 'vm'
// })
// .state('auth.login', {
// url: '/login',
// templateUrl: 'static/app/pages/auth/login.html',
// controller: 'LoginPageCtrl',
// controllerAs: 'vm'
// })
;
}
})();
| crowd-course/scholars | static/app/pages/auth/auth.module.js | JavaScript | mit | 1,130 |
/**
* Base js functions
*/
$(document).ready(function(){
//Init jQuery Masonry layout
init_masonry();
//Select menu onchange
$("#collapsed-navbar").change(function () {
window.location = $(this).val();
});
});
function init_masonry(){
var $container = $('#content');
$container.imagesLoaded( function(){
$container.masonry({
itemSelector: '.box',
isAnimated: true
});
});
}
*/
$(document).ready(function(){
//Start carousel
$('.carousel').carousel({interval:false});
}); | goldschadt/mason | assets/js/base.js | JavaScript | mit | 563 |
var React = require('react');
var RulePicker = require('./RulePicker.js');
var TimePicker = require('react-time-picker');
var DatePicker = require('react-date-picker');
var RuleSummary = require("./RuleSummary.js");
var moment = require('moment');
var Tabs = require('react-simpletabs');
var RecurringSelect = React.createClass({displayName: "RecurringSelect",
getInitialState: function() {
return ({
rule: "daily",
interval: 1,
validations: null,
until: moment().format('YYYY-MM-DD'),
startTime: "10:00 AM"
});
},
handleRuleChange: function(e) {
var rule = e.target.value;
var validations = null;
if (rule === "weekly") validations = [];
if (rule === "monthly (by day of week)") {
rule = "monthly";
validations = {1: [], 2: [], 3: [], 4: []};
}
if (rule === "monthly (by day of month)") {
rule = "monthly";
validations = [];
}
this.setState({
rule: rule,
validations: validations
});
},
handleIntervalChange: function(e) {
var interval;
if (e.target.value != "") {
interval = parseInt(e.target.value);
} else {
interval = 0;
}
this.setState({
interval: interval
});
},
handleValidationsChange: function(validations) {
this.setState({
validations: validations
});
},
handleEndDateChange: function (date) {
this.setState({
until: date
});
},
handleTimeChange: function(time) {
this.setState({
startTime: time
});
},
handleSave: function(e) {
var hash = this.state;
console.log(hash.validations);
var iceCubeHash = {};
var start = moment(hash.startTime, "hh:mm a A");
var minute = start.minute();
var hour = start.hour();
var rule_type;
switch (hash.rule) {
case 'daily':
rule_type = "IceCube::DailyRule";
break;
case 'weekly':
rule_type = "IceCube::WeeklyRule";
break;
case 'monthly':
rule_type = "IceCube::MonthlyRule";
break;
case 'yearly':
rule_type = "IceCube::YearlyRule";
break;
}
var interval = hash.interval;
var validations = hash.validations == null ? {} : hash.validations;
var newValidations = {};
if (Array.isArray(validations) && rule_type == "IceCube::WeeklyRule") {
newValidations["day"] = validations
} else if (Array.isArray(validations) && rule_type == "IceCube::MonthlyRule") {
newValidations["day_of_month"] = validations;
} else if (rule_type == "IceCube::MonthlyRule") {
newValidations["day_of_week"] = validations;
}
newValidations["hour_of_day"] = hour;
newValidations["minute_of_hour"] = minute;
var until = hash.until;
iceCubeHash["rule_type"] = rule_type;
iceCubeHash["interval"] = interval;
iceCubeHash["validations"] = newValidations;
iceCubeHash["until"] = until;
this.props.onSave(JSON.stringify(iceCubeHash));
},
render: function() {
return (
React.createElement("div", {className: "recurring-select"},
React.createElement(Tabs, null,
React.createElement(Tabs.Panel, {title: "Recurrence Rule"},
React.createElement(RulePicker, {
rule: this.state.rule,
interval: this.state.interval,
validations: this.state.validations,
onRuleChange: this.handleRuleChange,
onIntervalChange: this.handleIntervalChange,
onValidationsChange: this.handleValidationsChange})
),
React.createElement(Tabs.Panel, {title: "Occurence Time"},
React.createElement(TimePicker, {value: this.state.startTime, onChange: this.handleTimeChange})
),
React.createElement(Tabs.Panel, {title: "Recurring Until"},
React.createElement(DatePicker, {minDate: moment().format("YYYY-MM-DD"), date: this.state.until, onChange: this.handleEndDateChange})
)
),
React.createElement("hr", null),
React.createElement(RuleSummary, {fields: this.state}),
React.createElement("button", {className: "btn save", onClick: this.handleSave}, "Save")
)
);
}
});
module.exports = RecurringSelect;
| colinwahl/react-recurring-select | dist/RecurringSelect.js | JavaScript | mit | 4,318 |
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = eachLimit;
var _eachOfLimit = require('./internal/eachOfLimit');
var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit);
var _withoutIndex = require('./internal/withoutIndex');
var _withoutIndex2 = _interopRequireDefault(_withoutIndex);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* The same as [`each`]{@link module:Collections.each} but runs a maximum of `limit` async operations at a time.
*
* @name eachLimit
* @static
* @memberOf module:Collections
* @method
* @see [async.each]{@link module:Collections.each}
* @alias forEachLimit
* @category Collection
* @param {Array|Iterable|Object} coll - A colleciton to iterate over.
* @param {number} limit - The maximum number of async operations at a time.
* @param {Function} iteratee - A function to apply to each item in `coll`. The
* iteratee is passed a `callback(err)` which must be called once it has
* completed. If no error has occurred, the `callback` should be run without
* arguments or with an explicit `null` argument. The array index is not passed
* to the iteratee. Invoked with (item, callback). If you need the index, use
* `eachOfLimit`.
* @param {Function} [callback] - A callback which is called when all
* `iteratee` functions have finished, or an error occurs. Invoked with (err).
*/
function eachLimit(coll, limit, iteratee, callback) {
(0, _eachOfLimit2.default)(limit)(coll, (0, _withoutIndex2.default)(iteratee), callback);
}
module.exports = exports['default'];
| muhbalhester/comex-app | node_modules/async/eachLimit.js | JavaScript | mit | 1,623 |
angular.module('green-streak.controllers', ['LocalStorageModule'])
.controller('MenuController', function ($scope, $location, MenuService) {
// "MenuService" is a service returning mock data (services.js)
$scope.list = MenuService.all();
$scope.goTo = function (page) {
console.log('Going to ' + page);
$scope.sideMenuController.toggleLeft();
$location.url('/' + page);
};
})
.controller('AuthController', function ($scope, $ionicPlatform, $state, localStorageService) {
$scope.leftButtons = [
{
type: 'button-icon icon ion-navicon',
tap: function (e) {
$scope.sideMenuController.toggleLeft();
}
}
];
$scope.rightButtons = [];
})
.controller('IndexController', function ($scope, $ionicPlatform, $state, localStorageService) {
// var authenticated = localStorageService.get('authenticated');
// if (authenticated)
// {
// $state.go('one');
// }
$scope.navTitle = "Green Streak";
$scope.user = {userName: ''};
$scope.search = function () {
console.log("Searching for userName: " + $scope.user.userName)
localStorageService.set("userName", $scope.user.userName);
$state.go('square');
};
$scope.leftButtons = [
{
type: 'button-icon icon ion-navicon',
tap: function (e) {
$scope.sideMenuController.toggleLeft();
}
}
];
$scope.rightButtons = [];
})
.controller("CallbackController", function ($scope, $location, $state, AuthService, localStorageService) {
$scope.currentURL = $location.absUrl();
var paramPartOfURL = $scope.currentURL.slice($scope.currentURL.indexOf('code=') + 5);
var indexOfSlash = paramPartOfURL.indexOf('/');
var oAuthCode = paramPartOfURL.slice(0, indexOfSlash)
AuthService.get({'tokenId': oAuthCode}, function (success) {
localStorageService.add("authenticated", true);
$state.go('one');
}, function (error) { // error callback
localStorageService.remove("authenticated");
});
})
.controller('OneController', function ($scope, LanguageCountService) {
$scope.navTitle = "Language Data by count";
$scope.d3Data = LanguageCountService.query();
$scope.d3OnClick = function (item) {
// alert(item.name);
};
$scope.leftButtons = [
{
type: 'button-icon icon ion-navicon',
tap: function (e) {
$scope.sideMenuController.toggleLeft();
}
}
];
$scope.rightButtons = [];
})
.controller('SquareController', function ($scope, ContributionsService, localStorageService) {
$scope.navTitle = "Daily Contribution";
$scope.contributionData = ContributionsService.list({'userId': localStorageService.get("userName")}, function (success) {
var result = [];
for (var i = 0; i < success.length; i++) {
result.push(success[i][1]);
}
console.log("returning results")
$scope.contributionData = result;
});
$scope.deviceWidth = window.innerWidth || document.body.clientWidth;
$scope.deviceHeight = window.innerHeight || document.body.clientHeight;
$scope.leftButtons = [
{
type: 'button-icon icon ion-navicon',
tap: function (e) {
$scope.sideMenuController.toggleLeft();
}
}
];
$scope.rightButtons = [];
})
.controller('ThreeController', function ($scope) {
$scope.navTitle = "Page Three Title";
$scope.leftButtons = [
{
type: 'button-icon icon ion-navicon',
tap: function (e) {
$scope.sideMenuController.toggleLeft();
}
}
];
$scope.rightButtons = [];
});
| GeorgiCodes/green-streak-ui | www/js/controllers.js | JavaScript | mit | 4,242 |
import templateUrl from './image.html';
import controller from './image-controller';
export default {
name: 'image',
url: '/:image',
templateUrl,
controller,
controllerAs: 'image',
resolve: {
image: ['$http', '$stateParams', function($http, $stateParams){
const config = {
method: 'GET',
url: 'api/images/'+$stateParams.image,
params: {metadata: true}
};
return $http(config);
}]
}
};
| tamaracha/wbt-framework | src/main/author/images/image/index.js | JavaScript | mit | 449 |
const mongoose = require('mongoose')
let literatureSchema = mongoose.Schema({
category: { type: String, required: true},
name: { type: String, required: true },
description: { type: String },
content: { type: String, required: true },
author: { type: mongoose.Schema.Types.ObjectId, required: true, ref: 'User' },
comments: [{type: mongoose.Schema.Types.ObjectId, ref: 'Comment'}],
views: {type: Number},
date: { type: String }
})
literatureSchema.method({
prepareDelete: function () {
let User = mongoose.model('User')
User.findById(this.author).then(user => {
"use strict";
if (user) {
user.literature.remove(this.id)
user.save()
}
})
let Comment = mongoose.model('Comment')
for (let commentId of this.comments) {
Comment.findOneAndRemove(commentId).populate('author').then(comment => {
"use strict";
if (comment) {
let author = comment.author
let index = author.comments.indexOf(commentId)
let count = 1
author.comments.splice(index, count);
author.save()
comment.save()
}
})
}
}
})
literatureSchema.set('versionKey', false);
const Literature = mongoose.model('Literature', literatureSchema)
module.exports = Literature | losko/CodeNameSite | server/data/Literature.js | JavaScript | mit | 1,477 |
// Saves options to chrome.storage
function save_options () {
var saveDict = []
var i = 1
$('input').map(function () {
var dict = {
id: 'scbcc' + i,
value: this.value
}
i++
console.log('save: ', dict)
ga('send', 'event', 'setting', 'save', this.value)
saveDict.push(dict)
}).get()
chrome.storage.sync.set({
scbccRegexDict: saveDict
})
}
// Restores select box and checkbox state using the preferences
// stored in chrome.storage.
function restore_options () {
chrome.storage.sync.get({
scbccRegexDict: []
}, function (items) {
$('#field1').attr('value', items.scbccRegexDict[0].value)
for (var i = 0; i < items.scbccRegexDict.length; i++) {
var value = items.scbccRegexDict[i].value
var next = i
var addto = '#remove' + next
var addRemove = '#field' + (next + 1)
next = next + 1
var newIn = '<input autocomplete="off" placeholder="e.g. /this is test/g" id="field' + next + '" name="field' + next + '" type="text" tabindex="1" value=' + value + '>'
var newInput = $(newIn)
var removeBtn = '<button id="remove' + (next) + '" class="btn btn-danger remove-me" >-</button>'
var removeButton = $(removeBtn)
$(addto).after(newInput)
if (i !== 0) {
$(addRemove).after(removeButton)
}
$('#count').val(next)
$('.remove-me').click(function (e) {
e.preventDefault()
ga('send', 'event', 'setting', 'remove_regex')
var fieldNum = this.id.charAt(this.id.length - 1)
var fieldID = '#field' + fieldNum
$(this).remove()
$(fieldID).remove()
$('#style').attr('href', 'extra/styles.css')
})
}
var next = items.scbccRegexDict.length || 1
$('.add-more').click(function (e) {
ga('send', 'event', 'setting', 'add_regex')
e.preventDefault()
var addto = '#remove' + next
var addRemove = '#field' + (next + 1)
next = next + 1
var newIn = '<input autocomplete="off" placeholder="e.g. /this is test/g" id="field' + next + '" name="field' + next + '" type="text" tabindex="1">'
var newInput = $(newIn)
var removeBtn = '<button id="remove' + (next) + '" class="btn btn-danger remove-me" >-</button>'
var removeButton = $(removeBtn)
$(addto).after(newInput)
$(addRemove).after(removeButton)
$('#count').val(next)
$('.remove-me').click(function (e) {
e.preventDefault()
ga('send', 'event', 'setting', 'remove_regex')
var fieldNum = this.id.charAt(this.id.length - 1)
var fieldID = '#field' + fieldNum
$(this).remove()
$(fieldID).remove()
$('#style').attr('href', 'extra/styles.css')
})
})
})
}
document.addEventListener('DOMContentLoaded', restore_options)
document.getElementById('save').addEventListener('click', save_options)
| samcheuk/boring-copy-cat | options.js | JavaScript | mit | 2,881 |
'use strict';
module.exports = {
colors: {
black: '#000000',
red: '#D54E53',
green: '#B9CA4A',
yellow: '#E7C547',
blue: '#7AA6DA',
magenta: '#C397D8',
cyan: '#70C0B1',
white: '#EAEAEA',
lightBlack: '#969896',
lightRed: '#D54E53',
lightGreen: '#B9CA4A',
lightYellow: '#E7C547',
lightBlue: '#7AA6DA',
lightMagenta: '#C397D8',
lightCyan: '#70C0B1',
lightWhite: '#EAEAEA',
},
// Default
backgroundColor: '#000000',
foregroundColor: '#EAEAEA',
cursorColor: '#EAEAEA',
borderColor: '#171717',
// Accent color
accentColor: '#7AA6DA',
// Other
tabTitleColor: 'rgba(255, 255, 255, 0.2)',
selectedTabTitleColor: '#EAEAEA',
};
| ooJerryLeeoo/hyper-material-box | scheme/tomorrow-night-bright.js | JavaScript | mit | 708 |
/**
* @Author: Yingya Zhang <zyy>
* @Date: 2016-07-08 11:29:00
* @Email: [email protected]
* @Last modified by: zyy
* @Last modified time: 2016-07-10 22:18:85
*/
import {
notexist,
isEmpty
} from 'type'
import {
calcHeight,
remove,
dataset
} from 'dom'
describe('dom', () => {
it('calcHeight', () => {
const height = 42
const p = document.createElement('p')
p.id = 'calcHeight-' + (+new Date())
p.style.margin = 0
p.style.padding = 0
p.style.lineHeight = height + 'px'
p.style.fontSize = '18px'
const textNode = document.createTextNode('text')
p.appendChild(textNode)
const height1 = calcHeight(p)
expect(height1).toBe(height)
})
it('remove', () => {
const domStr = '<div id="divRemove"></div>'
document.body.innerHTML += domStr
const div = document.getElementById('divRemove')
expect(div.parentNode).toEqual(jasmine.anything())
remove(div)
expect(notexist(div.parentNode)).toBe(true)
})
it('dataset', () => {
const domStr = '<div id="divDataset"></div>'
document.body.innerHTML += domStr
const div = document.getElementById('divDataset')
const name = dataset(div, 'name')
expect(isEmpty(name)).toBe(true)
dataset(div, 'name', 'foo')
expect(dataset(div, 'name')).toBe('foo')
remove(div)
})
// TODO html2node
})
| zoro-js/zoro-base | test/unit/specs/dom/index_spec.js | JavaScript | mit | 1,346 |
/* http://fiidmi.fi/documentation/customer_order_history */
module.exports = {
"bonus": {
"type": "object",
"properties": {
"session_id": { "type": "string", "minLength": 2, "maxLength": 50 },
"restaurant_id": { "type": "string", "minLength": 1, "maxLength": 50 }
},
"required": ["session_id", "restaurant_id"]
},
"po_credit": {
"type": "object",
"properties": {
"session_id": { "type": "string", "minLength": 2, "maxLength": 50 }
},
"required": ["session_id", "order_id"]
}
};
| tidhr/node-fiidmi | lib/api/3.3/customer/information.js | JavaScript | mit | 526 |
export function Fragment(props, ...children) {
return collect(children);
}
const ATTR_PROPS = '_props';
function collect(children) {
const ch = [];
const push = (c) => {
if (c !== null && c !== undefined && c !== '' && c !== false) {
ch.push((typeof c === 'function' || typeof c === 'object') ? c : `${c}`);
}
};
children && children.forEach(c => {
if (Array.isArray(c)) {
c.forEach(i => push(i));
}
else {
push(c);
}
});
return ch;
}
export function createElement(tag, props, ...children) {
const ch = collect(children);
if (typeof tag === 'string')
return { tag, props, children: ch };
else if (Array.isArray(tag))
return tag; // JSX fragments - babel
else if (tag === undefined && children)
return ch; // JSX fragments - typescript
else if (Object.getPrototypeOf(tag).__isAppRunComponent)
return { tag, props, children: ch }; // createComponent(tag, { ...props, children });
else if (typeof tag === 'function')
return tag(props, ch);
else
throw new Error(`Unknown tag in vdom ${tag}`);
}
;
const keyCache = new WeakMap();
export const updateElement = render;
export function render(element, nodes, parent = {}) {
// console.log('render', element, node);
// tslint:disable-next-line
if (nodes == null || nodes === false)
return;
nodes = createComponent(nodes, parent);
const isSvg = (element === null || element === void 0 ? void 0 : element.nodeName) === "SVG";
if (!element)
return;
if (Array.isArray(nodes)) {
updateChildren(element, nodes, isSvg);
}
else {
updateChildren(element, [nodes], isSvg);
}
}
function same(el, node) {
// if (!el || !node) return false;
const key1 = el.nodeName;
const key2 = `${node.tag || ''}`;
return key1.toUpperCase() === key2.toUpperCase();
}
function update(element, node, isSvg) {
if (node['_op'] === 3)
return;
// console.assert(!!element);
isSvg = isSvg || node.tag === "svg";
if (!same(element, node)) {
element.parentNode.replaceChild(create(node, isSvg), element);
return;
}
!(node['_op'] & 2) && updateChildren(element, node.children, isSvg);
!(node['_op'] & 1) && updateProps(element, node.props, isSvg);
}
function updateChildren(element, children, isSvg) {
var _a;
const old_len = ((_a = element.childNodes) === null || _a === void 0 ? void 0 : _a.length) || 0;
const new_len = (children === null || children === void 0 ? void 0 : children.length) || 0;
const len = Math.min(old_len, new_len);
for (let i = 0; i < len; i++) {
const child = children[i];
if (child['_op'] === 3)
continue;
const el = element.childNodes[i];
if (typeof child === 'string') {
if (el.textContent !== child) {
if (el.nodeType === 3) {
el.nodeValue = child;
}
else {
element.replaceChild(createText(child), el);
}
}
}
else if (child instanceof HTMLElement || child instanceof SVGElement) {
element.insertBefore(child, el);
}
else {
const key = child.props && child.props['key'];
if (key) {
if (el.key === key) {
update(element.childNodes[i], child, isSvg);
}
else {
// console.log(el.key, key);
const old = keyCache[key];
if (old) {
const temp = old.nextSibling;
element.insertBefore(old, el);
temp ? element.insertBefore(el, temp) : element.appendChild(el);
update(element.childNodes[i], child, isSvg);
}
else {
element.replaceChild(create(child, isSvg), el);
}
}
}
else {
update(element.childNodes[i], child, isSvg);
}
}
}
let n = element.childNodes.length;
while (n > len) {
element.removeChild(element.lastChild);
n--;
}
if (new_len > len) {
const d = document.createDocumentFragment();
for (let i = len; i < children.length; i++) {
d.appendChild(create(children[i], isSvg));
}
element.appendChild(d);
}
}
function createText(node) {
if ((node === null || node === void 0 ? void 0 : node.indexOf('_html:')) === 0) { // ?
const div = document.createElement('div');
div.insertAdjacentHTML('afterbegin', node.substring(6));
return div;
}
else {
return document.createTextNode(node !== null && node !== void 0 ? node : '');
}
}
function create(node, isSvg) {
// console.assert(node !== null && node !== undefined);
if ((node instanceof HTMLElement) || (node instanceof SVGElement))
return node;
if (typeof node === "string")
return createText(node);
if (!node.tag || (typeof node.tag === 'function'))
return createText(JSON.stringify(node));
isSvg = isSvg || node.tag === "svg";
const element = isSvg
? document.createElementNS("http://www.w3.org/2000/svg", node.tag)
: document.createElement(node.tag);
updateProps(element, node.props, isSvg);
if (node.children)
node.children.forEach(child => element.appendChild(create(child, isSvg)));
return element;
}
function mergeProps(oldProps, newProps) {
newProps['class'] = newProps['class'] || newProps['className'];
delete newProps['className'];
const props = {};
if (oldProps)
Object.keys(oldProps).forEach(p => props[p] = null);
if (newProps)
Object.keys(newProps).forEach(p => props[p] = newProps[p]);
return props;
}
export function updateProps(element, props, isSvg) {
// console.assert(!!element);
const cached = element[ATTR_PROPS] || {};
props = mergeProps(cached, props || {});
element[ATTR_PROPS] = props;
for (const name in props) {
const value = props[name];
// if (cached[name] === value) continue;
// console.log('updateProps', name, value);
if (name.startsWith('data-')) {
const dname = name.substring(5);
const cname = dname.replace(/-(\w)/g, (match) => match[1].toUpperCase());
if (element.dataset[cname] !== value) {
if (value || value === "")
element.dataset[cname] = value;
else
delete element.dataset[cname];
}
}
else if (name === 'style') {
if (element.style.cssText)
element.style.cssText = '';
if (typeof value === 'string')
element.style.cssText = value;
else {
for (const s in value) {
if (element.style[s] !== value[s])
element.style[s] = value[s];
}
}
}
else if (name.startsWith('xlink')) {
const xname = name.replace('xlink', '').toLowerCase();
if (value == null || value === false) {
element.removeAttributeNS('http://www.w3.org/1999/xlink', xname);
}
else {
element.setAttributeNS('http://www.w3.org/1999/xlink', xname, value);
}
}
else if (name.startsWith('on')) {
if (!value || typeof value === 'function') {
element[name] = value;
}
else if (typeof value === 'string') {
if (value)
element.setAttribute(name, value);
else
element.removeAttribute(name);
}
}
else if (/^id$|^class$|^list$|^readonly$|^contenteditable$|^role|-/g.test(name) || isSvg) {
if (element.getAttribute(name) !== value) {
if (value)
element.setAttribute(name, value);
else
element.removeAttribute(name);
}
}
else if (element[name] !== value) {
element[name] = value;
}
if (name === 'key' && value)
keyCache[value] = element;
}
if (props && typeof props['ref'] === 'function') {
window.requestAnimationFrame(() => props['ref'](element));
}
}
function render_component(node, parent, idx) {
const { tag, props, children } = node;
let key = `_${idx}`;
let id = props && props['id'];
if (!id)
id = `_${idx}${Date.now()}`;
else
key = id;
let asTag = 'section';
if (props && props['as']) {
asTag = props['as'];
delete props['as'];
}
if (!parent.__componentCache)
parent.__componentCache = {};
let component = parent.__componentCache[key];
if (!component || !(component instanceof tag) || !component.element) {
const element = document.createElement(asTag);
component = parent.__componentCache[key] = new tag(Object.assign(Object.assign({}, props), { children })).start(element);
}
if (component.mounted) {
const new_state = component.mounted(props, children, component.state);
(typeof new_state !== 'undefined') && component.setState(new_state);
}
updateProps(component.element, props, false);
return component.element;
}
function createComponent(node, parent, idx = 0) {
var _a;
if (typeof node === 'string')
return node;
if (Array.isArray(node))
return node.map(child => createComponent(child, parent, idx++));
let vdom = node;
if (node && typeof node.tag === 'function' && Object.getPrototypeOf(node.tag).__isAppRunComponent) {
vdom = render_component(node, parent, idx);
}
if (vdom && Array.isArray(vdom.children)) {
const new_parent = (_a = vdom.props) === null || _a === void 0 ? void 0 : _a._component;
if (new_parent) {
let i = 0;
vdom.children = vdom.children.map(child => createComponent(child, new_parent, i++));
}
else {
vdom.children = vdom.children.map(child => createComponent(child, parent, idx++));
}
}
return vdom;
}
//# sourceMappingURL=vdom-my.js.map | yysun/apprun | esm/vdom-my.js | JavaScript | mit | 10,531 |
var ItineraryWalkStep = require('./itinerary-walk-step')
var Backbone = window.Backbone
var ItineraryWalkSteps = Backbone.Collection.extend({
model: ItineraryWalkStep
})
module.exports = ItineraryWalkSteps
| ed-g/otp.js | lib/itinerary-walk-steps.js | JavaScript | mit | 211 |
/*
* Copyright (c) 2015 by Greg Reimer <[email protected]>
* MIT License. See license.txt for more info.
*/
var stream = require('stream')
, util = require('util')
, co = require('co')
, unresolved = require('./unresolved')
// -----------------------------------------------------
function Readable(opts, sender) {
stream.Readable.call(this, opts);
this._ponySending = unresolved();
var self = this;
function output(data, enc) {
return self._ponySending.then(function() {
if (!self.push(data, enc)) {
self._ponySending = unresolved();
}
});
}
co(sender.bind(this, output))
.then(function() { self.push(null); })
.catch(function(err) { self.emit('error', err); });
}
util.inherits(Readable, stream.Readable);
Readable.prototype._read = function() {
this._ponySending.resolve();
};
// -----------------------------------------------------
module.exports = Readable;
| greim/eventual-pony | lib/readable.js | JavaScript | mit | 929 |
// flow-typed signature: 382f7ff956662b19ae5c130ba0ebece6
// flow-typed version: <<STUB>>/deepclone_v1.0.2/flow_v0.56.0
/**
* This is an autogenerated libdef stub for:
*
* 'deepclone'
*
* Fill this stub out by replacing all the `any` types.
*
* Once filled out, we encourage you to share your work with the
* community by sending a pull request to:
* https://github.com/flowtype/flow-typed
*/
declare module 'deepclone' {
declare module.exports: any;
}
| codefoundries/UniversalRelayBoilerplate | flow-typed/npm/deepclone_vx.x.x.js | JavaScript | mit | 469 |
'use strict';
describe('E2E testing: Change password', function () {
var constants = require('../../../testConstants');
var loginPage = require('../../pages/loginPage');
var header = require('../../pages/pageHeader');
var changePasswordPage = require('../../pages/changePasswordPage');
var expectedCondition = protractor.ExpectedConditions;
var CONDITION_TIMEOUT = 3000;
var newPassword = '12345678';
it('setup: login as user, go to change password page', function () {
loginPage.loginAsUser();
changePasswordPage.get();
});
it('refuses to allow form submission if the confirm input does not match', function () {
changePasswordPage.password.sendKeys(newPassword);
changePasswordPage.confirm.sendKeys('blah12345');
expect(changePasswordPage.submitButton.isEnabled()).toBeFalsy();
changePasswordPage.password.clear();
changePasswordPage.confirm.clear();
});
it('allows form submission if the confirm input matches', function () {
changePasswordPage.password.sendKeys(newPassword);
changePasswordPage.confirm.sendKeys(newPassword);
expect(changePasswordPage.submitButton.isEnabled()).toBeTruthy();
changePasswordPage.password.clear();
changePasswordPage.confirm.clear();
});
/* cant test this yet because I don't know how to test for HTML 5 form validation - cjh 2014-06
it('should not allow a password less than 7 characters', function() {
var shortPassword = '12345';
changePasswordPage.password.sendKeys(shortPassword);
changePasswordPage.confirm.sendKeys(shortPassword);
expect(changePasswordPage.submitButton.isEnabled()).toBe(false);
changePasswordPage.password.clear();
changePasswordPage.confirm.clear();
});
*/
it('can successfully changes user\'s password after form submission', function () {
changePasswordPage.password.sendKeys(newPassword);
changePasswordPage.confirm.sendKeys(newPassword);
browser.wait(expectedCondition.visibilityOf(changePasswordPage.passwordMatchImage),
CONDITION_TIMEOUT);
browser.wait(expectedCondition.elementToBeClickable(changePasswordPage.submitButton),
CONDITION_TIMEOUT);
changePasswordPage.submitButton.click();
expect(changePasswordPage.noticeList.count()).toBe(1);
expect(changePasswordPage.noticeList.first().getText()).toContain('Password Updated');
loginPage.logout();
loginPage.login(constants.memberUsername, newPassword);
browser.wait(expectedCondition.visibilityOf(header.myProjects.button), CONDITION_TIMEOUT);
expect(header.myProjects.button.isDisplayed()).toBe(true);
// reset password back to original
changePasswordPage.get();
changePasswordPage.password.sendKeys(constants.memberPassword);
changePasswordPage.confirm.sendKeys(constants.memberPassword);
browser.wait(expectedCondition.visibilityOf(changePasswordPage.passwordMatchImage),
CONDITION_TIMEOUT);
browser.wait(expectedCondition.elementToBeClickable(changePasswordPage.submitButton),
CONDITION_TIMEOUT);
changePasswordPage.submitButton.click();
});
});
| sil-student-projects/web-languageforge | test/app/bellows/changepassword/e2e/changepassword.spec.js | JavaScript | mit | 3,105 |
/**
* The MIT License (MIT)
*
* Copyright (c) 2014-2022 Mickael Jeanroy
*
* 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.
*/
import {isNumber} from './is-number.js';
/**
* Check that a given value is a falsy value.
*
* @param {*} a Value to check.
* @return {boolean} `true` if parameter is a falsy value.
*/
export function isFiniteNumber(a) {
return isNumber(a) && isFinite(a);
}
| mjeanroy/jasmine-utils | src/core/util/is-finite-number.js | JavaScript | mit | 1,420 |
/**
* Created by TC on 2016/10/10.
*/
import React, {
Component,
} from 'react'
import {
Image,
View,
ToastAndroid,
ActivityIndicator,
}
from 'react-native'
import PixelRatio from "react-native/Libraries/Utilities/PixelRatio";
class GirlComponent extends Component {
constructor(props) {
super(props);
this.state = {
imgUrl: ''
}
}
loadImage() {
this.setState({imgUrl: ''});
this.getImage();
}
componentWillMount() {
this.getImage();
}
getImage() {
fetch('http://gank.io/api/data/福利/100/1')//异步请求图片
.then((response) => {
return response.json();
})
.then((responseJson) => {
if (responseJson.results) {
const index = Math.ceil(Math.random() * 100 - 1);//随机取一张福利图
this.setState({imgUrl: responseJson.results[index].url});
}
}).catch((error) => console.error(error))
.done();
}
render() {
if (this.state.imgUrl.length == 0) {
return (
<View style={ {flex: 1, flexDirection: 'row', justifyContent: 'center', alignItems: 'center'}}>
<ActivityIndicator size='large' color='#00BCD4'/>
</View>
);
} else {
return (
<View style={{flexDirection: 'column', flex: 1}}>
<Image source={{uri: this.state.imgUrl}}
style={{width: 200 * PixelRatio.get(), height: 200 * PixelRatio.get()}}/>
</View>
);
}
}
}
export default GirlComponent; | huxinmin/PracticeMakesPerfect | reactNative/reactnativelearn-master/js/GirlComponent.js | JavaScript | mit | 1,751 |
export * from '../common';
export NodeBundle from './NodeBundle';
export CommonJsResolver from './CommonJsResolver';
| stephenbunch/palkia | src/node/index.js | JavaScript | mit | 117 |
/*!
* maptalks.snapto v0.1.11
* LICENSE : MIT
* (c) 2016-2018 maptalks.org
*/
/*!
* requires maptalks@^0.33.1
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('maptalks')) :
typeof define === 'function' && define.amd ? define(['exports', 'maptalks'], factory) :
(factory((global.maptalks = global.maptalks || {}),global.maptalks));
}(this, (function (exports,maptalks) { 'use strict';
var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
function createCommonjsModule(fn, module) {
return module = { exports: {} }, fn(module, module.exports), module.exports;
}
var quickselect$1 = createCommonjsModule(function (module, exports) {
(function (global, factory) {
module.exports = factory();
})(commonjsGlobal, function () {
'use strict';
function quickselect(arr, k, left, right, compare) {
quickselectStep(arr, k, left || 0, right || arr.length - 1, compare || defaultCompare);
}
function quickselectStep(arr, k, left, right, compare) {
while (right > left) {
if (right - left > 600) {
var n = right - left + 1;
var m = k - left + 1;
var z = Math.log(n);
var s = 0.5 * Math.exp(2 * z / 3);
var sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1);
var newLeft = Math.max(left, Math.floor(k - m * s / n + sd));
var newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd));
quickselectStep(arr, k, newLeft, newRight, compare);
}
var t = arr[k];
var i = left;
var j = right;
swap(arr, left, k);
if (compare(arr[right], t) > 0) swap(arr, left, right);
while (i < j) {
swap(arr, i, j);
i++;
j--;
while (compare(arr[i], t) < 0) {
i++;
}while (compare(arr[j], t) > 0) {
j--;
}
}
if (compare(arr[left], t) === 0) swap(arr, left, j);else {
j++;
swap(arr, j, right);
}
if (j <= k) left = j + 1;
if (k <= j) right = j - 1;
}
}
function swap(arr, i, j) {
var tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
function defaultCompare(a, b) {
return a < b ? -1 : a > b ? 1 : 0;
}
return quickselect;
});
});
var index$1 = rbush$2;
var default_1 = rbush$2;
var quickselect = quickselect$1;
function rbush$2(maxEntries, format) {
if (!(this instanceof rbush$2)) return new rbush$2(maxEntries, format);
// max entries in a node is 9 by default; min node fill is 40% for best performance
this._maxEntries = Math.max(4, maxEntries || 9);
this._minEntries = Math.max(2, Math.ceil(this._maxEntries * 0.4));
if (format) {
this._initFormat(format);
}
this.clear();
}
rbush$2.prototype = {
all: function all() {
return this._all(this.data, []);
},
search: function search(bbox) {
var node = this.data,
result = [],
toBBox = this.toBBox;
if (!intersects(bbox, node)) return result;
var nodesToSearch = [],
i,
len,
child,
childBBox;
while (node) {
for (i = 0, len = node.children.length; i < len; i++) {
child = node.children[i];
childBBox = node.leaf ? toBBox(child) : child;
if (intersects(bbox, childBBox)) {
if (node.leaf) result.push(child);else if (contains(bbox, childBBox)) this._all(child, result);else nodesToSearch.push(child);
}
}
node = nodesToSearch.pop();
}
return result;
},
collides: function collides(bbox) {
var node = this.data,
toBBox = this.toBBox;
if (!intersects(bbox, node)) return false;
var nodesToSearch = [],
i,
len,
child,
childBBox;
while (node) {
for (i = 0, len = node.children.length; i < len; i++) {
child = node.children[i];
childBBox = node.leaf ? toBBox(child) : child;
if (intersects(bbox, childBBox)) {
if (node.leaf || contains(bbox, childBBox)) return true;
nodesToSearch.push(child);
}
}
node = nodesToSearch.pop();
}
return false;
},
load: function load(data) {
if (!(data && data.length)) return this;
if (data.length < this._minEntries) {
for (var i = 0, len = data.length; i < len; i++) {
this.insert(data[i]);
}
return this;
}
// recursively build the tree with the given data from scratch using OMT algorithm
var node = this._build(data.slice(), 0, data.length - 1, 0);
if (!this.data.children.length) {
// save as is if tree is empty
this.data = node;
} else if (this.data.height === node.height) {
// split root if trees have the same height
this._splitRoot(this.data, node);
} else {
if (this.data.height < node.height) {
// swap trees if inserted one is bigger
var tmpNode = this.data;
this.data = node;
node = tmpNode;
}
// insert the small tree into the large tree at appropriate level
this._insert(node, this.data.height - node.height - 1, true);
}
return this;
},
insert: function insert(item) {
if (item) this._insert(item, this.data.height - 1);
return this;
},
clear: function clear() {
this.data = createNode([]);
return this;
},
remove: function remove(item, equalsFn) {
if (!item) return this;
var node = this.data,
bbox = this.toBBox(item),
path = [],
indexes = [],
i,
parent,
index,
goingUp;
// depth-first iterative tree traversal
while (node || path.length) {
if (!node) {
// go up
node = path.pop();
parent = path[path.length - 1];
i = indexes.pop();
goingUp = true;
}
if (node.leaf) {
// check current node
index = findItem(item, node.children, equalsFn);
if (index !== -1) {
// item found, remove the item and condense tree upwards
node.children.splice(index, 1);
path.push(node);
this._condense(path);
return this;
}
}
if (!goingUp && !node.leaf && contains(node, bbox)) {
// go down
path.push(node);
indexes.push(i);
i = 0;
parent = node;
node = node.children[0];
} else if (parent) {
// go right
i++;
node = parent.children[i];
goingUp = false;
} else node = null; // nothing found
}
return this;
},
toBBox: function toBBox(item) {
return item;
},
compareMinX: compareNodeMinX,
compareMinY: compareNodeMinY,
toJSON: function toJSON() {
return this.data;
},
fromJSON: function fromJSON(data) {
this.data = data;
return this;
},
_all: function _all(node, result) {
var nodesToSearch = [];
while (node) {
if (node.leaf) result.push.apply(result, node.children);else nodesToSearch.push.apply(nodesToSearch, node.children);
node = nodesToSearch.pop();
}
return result;
},
_build: function _build(items, left, right, height) {
var N = right - left + 1,
M = this._maxEntries,
node;
if (N <= M) {
// reached leaf level; return leaf
node = createNode(items.slice(left, right + 1));
calcBBox(node, this.toBBox);
return node;
}
if (!height) {
// target height of the bulk-loaded tree
height = Math.ceil(Math.log(N) / Math.log(M));
// target number of root entries to maximize storage utilization
M = Math.ceil(N / Math.pow(M, height - 1));
}
node = createNode([]);
node.leaf = false;
node.height = height;
// split the items into M mostly square tiles
var N2 = Math.ceil(N / M),
N1 = N2 * Math.ceil(Math.sqrt(M)),
i,
j,
right2,
right3;
multiSelect(items, left, right, N1, this.compareMinX);
for (i = left; i <= right; i += N1) {
right2 = Math.min(i + N1 - 1, right);
multiSelect(items, i, right2, N2, this.compareMinY);
for (j = i; j <= right2; j += N2) {
right3 = Math.min(j + N2 - 1, right2);
// pack each entry recursively
node.children.push(this._build(items, j, right3, height - 1));
}
}
calcBBox(node, this.toBBox);
return node;
},
_chooseSubtree: function _chooseSubtree(bbox, node, level, path) {
var i, len, child, targetNode, area, enlargement, minArea, minEnlargement;
while (true) {
path.push(node);
if (node.leaf || path.length - 1 === level) break;
minArea = minEnlargement = Infinity;
for (i = 0, len = node.children.length; i < len; i++) {
child = node.children[i];
area = bboxArea(child);
enlargement = enlargedArea(bbox, child) - area;
// choose entry with the least area enlargement
if (enlargement < minEnlargement) {
minEnlargement = enlargement;
minArea = area < minArea ? area : minArea;
targetNode = child;
} else if (enlargement === minEnlargement) {
// otherwise choose one with the smallest area
if (area < minArea) {
minArea = area;
targetNode = child;
}
}
}
node = targetNode || node.children[0];
}
return node;
},
_insert: function _insert(item, level, isNode) {
var toBBox = this.toBBox,
bbox = isNode ? item : toBBox(item),
insertPath = [];
// find the best node for accommodating the item, saving all nodes along the path too
var node = this._chooseSubtree(bbox, this.data, level, insertPath);
// put the item into the node
node.children.push(item);
extend(node, bbox);
// split on node overflow; propagate upwards if necessary
while (level >= 0) {
if (insertPath[level].children.length > this._maxEntries) {
this._split(insertPath, level);
level--;
} else break;
}
// adjust bboxes along the insertion path
this._adjustParentBBoxes(bbox, insertPath, level);
},
// split overflowed node into two
_split: function _split(insertPath, level) {
var node = insertPath[level],
M = node.children.length,
m = this._minEntries;
this._chooseSplitAxis(node, m, M);
var splitIndex = this._chooseSplitIndex(node, m, M);
var newNode = createNode(node.children.splice(splitIndex, node.children.length - splitIndex));
newNode.height = node.height;
newNode.leaf = node.leaf;
calcBBox(node, this.toBBox);
calcBBox(newNode, this.toBBox);
if (level) insertPath[level - 1].children.push(newNode);else this._splitRoot(node, newNode);
},
_splitRoot: function _splitRoot(node, newNode) {
// split root node
this.data = createNode([node, newNode]);
this.data.height = node.height + 1;
this.data.leaf = false;
calcBBox(this.data, this.toBBox);
},
_chooseSplitIndex: function _chooseSplitIndex(node, m, M) {
var i, bbox1, bbox2, overlap, area, minOverlap, minArea, index;
minOverlap = minArea = Infinity;
for (i = m; i <= M - m; i++) {
bbox1 = distBBox(node, 0, i, this.toBBox);
bbox2 = distBBox(node, i, M, this.toBBox);
overlap = intersectionArea(bbox1, bbox2);
area = bboxArea(bbox1) + bboxArea(bbox2);
// choose distribution with minimum overlap
if (overlap < minOverlap) {
minOverlap = overlap;
index = i;
minArea = area < minArea ? area : minArea;
} else if (overlap === minOverlap) {
// otherwise choose distribution with minimum area
if (area < minArea) {
minArea = area;
index = i;
}
}
}
return index;
},
// sorts node children by the best axis for split
_chooseSplitAxis: function _chooseSplitAxis(node, m, M) {
var compareMinX = node.leaf ? this.compareMinX : compareNodeMinX,
compareMinY = node.leaf ? this.compareMinY : compareNodeMinY,
xMargin = this._allDistMargin(node, m, M, compareMinX),
yMargin = this._allDistMargin(node, m, M, compareMinY);
// if total distributions margin value is minimal for x, sort by minX,
// otherwise it's already sorted by minY
if (xMargin < yMargin) node.children.sort(compareMinX);
},
// total margin of all possible split distributions where each node is at least m full
_allDistMargin: function _allDistMargin(node, m, M, compare) {
node.children.sort(compare);
var toBBox = this.toBBox,
leftBBox = distBBox(node, 0, m, toBBox),
rightBBox = distBBox(node, M - m, M, toBBox),
margin = bboxMargin(leftBBox) + bboxMargin(rightBBox),
i,
child;
for (i = m; i < M - m; i++) {
child = node.children[i];
extend(leftBBox, node.leaf ? toBBox(child) : child);
margin += bboxMargin(leftBBox);
}
for (i = M - m - 1; i >= m; i--) {
child = node.children[i];
extend(rightBBox, node.leaf ? toBBox(child) : child);
margin += bboxMargin(rightBBox);
}
return margin;
},
_adjustParentBBoxes: function _adjustParentBBoxes(bbox, path, level) {
// adjust bboxes along the given tree path
for (var i = level; i >= 0; i--) {
extend(path[i], bbox);
}
},
_condense: function _condense(path) {
// go through the path, removing empty nodes and updating bboxes
for (var i = path.length - 1, siblings; i >= 0; i--) {
if (path[i].children.length === 0) {
if (i > 0) {
siblings = path[i - 1].children;
siblings.splice(siblings.indexOf(path[i]), 1);
} else this.clear();
} else calcBBox(path[i], this.toBBox);
}
},
_initFormat: function _initFormat(format) {
// data format (minX, minY, maxX, maxY accessors)
// uses eval-type function compilation instead of just accepting a toBBox function
// because the algorithms are very sensitive to sorting functions performance,
// so they should be dead simple and without inner calls
var compareArr = ['return a', ' - b', ';'];
this.compareMinX = new Function('a', 'b', compareArr.join(format[0]));
this.compareMinY = new Function('a', 'b', compareArr.join(format[1]));
this.toBBox = new Function('a', 'return {minX: a' + format[0] + ', minY: a' + format[1] + ', maxX: a' + format[2] + ', maxY: a' + format[3] + '};');
}
};
function findItem(item, items, equalsFn) {
if (!equalsFn) return items.indexOf(item);
for (var i = 0; i < items.length; i++) {
if (equalsFn(item, items[i])) return i;
}
return -1;
}
// calculate node's bbox from bboxes of its children
function calcBBox(node, toBBox) {
distBBox(node, 0, node.children.length, toBBox, node);
}
// min bounding rectangle of node children from k to p-1
function distBBox(node, k, p, toBBox, destNode) {
if (!destNode) destNode = createNode(null);
destNode.minX = Infinity;
destNode.minY = Infinity;
destNode.maxX = -Infinity;
destNode.maxY = -Infinity;
for (var i = k, child; i < p; i++) {
child = node.children[i];
extend(destNode, node.leaf ? toBBox(child) : child);
}
return destNode;
}
function extend(a, b) {
a.minX = Math.min(a.minX, b.minX);
a.minY = Math.min(a.minY, b.minY);
a.maxX = Math.max(a.maxX, b.maxX);
a.maxY = Math.max(a.maxY, b.maxY);
return a;
}
function compareNodeMinX(a, b) {
return a.minX - b.minX;
}
function compareNodeMinY(a, b) {
return a.minY - b.minY;
}
function bboxArea(a) {
return (a.maxX - a.minX) * (a.maxY - a.minY);
}
function bboxMargin(a) {
return a.maxX - a.minX + (a.maxY - a.minY);
}
function enlargedArea(a, b) {
return (Math.max(b.maxX, a.maxX) - Math.min(b.minX, a.minX)) * (Math.max(b.maxY, a.maxY) - Math.min(b.minY, a.minY));
}
function intersectionArea(a, b) {
var minX = Math.max(a.minX, b.minX),
minY = Math.max(a.minY, b.minY),
maxX = Math.min(a.maxX, b.maxX),
maxY = Math.min(a.maxY, b.maxY);
return Math.max(0, maxX - minX) * Math.max(0, maxY - minY);
}
function contains(a, b) {
return a.minX <= b.minX && a.minY <= b.minY && b.maxX <= a.maxX && b.maxY <= a.maxY;
}
function intersects(a, b) {
return b.minX <= a.maxX && b.minY <= a.maxY && b.maxX >= a.minX && b.maxY >= a.minY;
}
function createNode(children) {
return {
children: children,
height: 1,
leaf: true,
minX: Infinity,
minY: Infinity,
maxX: -Infinity,
maxY: -Infinity
};
}
// sort an array so that items come in groups of n unsorted items, with groups sorted between each other;
// combines selection algorithm with binary divide & conquer approach
function multiSelect(arr, left, right, n, compare) {
var stack = [left, right],
mid;
while (stack.length) {
right = stack.pop();
left = stack.pop();
if (right - left <= n) continue;
mid = left + Math.ceil((right - left) / n / 2) * n;
quickselect(arr, mid, left, right, compare);
stack.push(left, mid, mid, right);
}
}
index$1.default = default_1;
/**
* GeoJSON BBox
*
* @private
* @typedef {[number, number, number, number]} BBox
*/
/**
* GeoJSON Id
*
* @private
* @typedef {(number|string)} Id
*/
/**
* GeoJSON FeatureCollection
*
* @private
* @typedef {Object} FeatureCollection
* @property {string} type
* @property {?Id} id
* @property {?BBox} bbox
* @property {Feature[]} features
*/
/**
* GeoJSON Feature
*
* @private
* @typedef {Object} Feature
* @property {string} type
* @property {?Id} id
* @property {?BBox} bbox
* @property {*} properties
* @property {Geometry} geometry
*/
/**
* GeoJSON Geometry
*
* @private
* @typedef {Object} Geometry
* @property {string} type
* @property {any[]} coordinates
*/
/**
* Callback for coordEach
*
* @callback coordEachCallback
* @param {Array<number>} currentCoord The current coordinate being processed.
* @param {number} coordIndex The current index of the coordinate being processed.
* Starts at index 0.
* @param {number} featureIndex The current index of the feature being processed.
* @param {number} featureSubIndex The current subIndex of the feature being processed.
*/
/**
* Iterate over coordinates in any GeoJSON object, similar to Array.forEach()
*
* @name coordEach
* @param {(FeatureCollection|Feature|Geometry)} geojson any GeoJSON object
* @param {Function} callback a method that takes (currentCoord, coordIndex, featureIndex, featureSubIndex)
* @param {boolean} [excludeWrapCoord=false] whether or not to include the final coordinate of LinearRings that wraps the ring in its iteration.
* @example
* var features = turf.featureCollection([
* turf.point([26, 37], {"foo": "bar"}),
* turf.point([36, 53], {"hello": "world"})
* ]);
*
* turf.coordEach(features, function (currentCoord, coordIndex, featureIndex, featureSubIndex) {
* //=currentCoord
* //=coordIndex
* //=featureIndex
* //=featureSubIndex
* });
*/
function coordEach$1(geojson, callback, excludeWrapCoord) {
// Handles null Geometry -- Skips this GeoJSON
if (geojson === null) return;
var featureIndex,
geometryIndex,
j,
k,
l,
geometry,
stopG,
coords,
geometryMaybeCollection,
wrapShrink = 0,
coordIndex = 0,
isGeometryCollection,
type = geojson.type,
isFeatureCollection = type === 'FeatureCollection',
isFeature = type === 'Feature',
stop = isFeatureCollection ? geojson.features.length : 1;
// This logic may look a little weird. The reason why it is that way
// is because it's trying to be fast. GeoJSON supports multiple kinds
// of objects at its root: FeatureCollection, Features, Geometries.
// This function has the responsibility of handling all of them, and that
// means that some of the `for` loops you see below actually just don't apply
// to certain inputs. For instance, if you give this just a
// Point geometry, then both loops are short-circuited and all we do
// is gradually rename the input until it's called 'geometry'.
//
// This also aims to allocate as few resources as possible: just a
// few numbers and booleans, rather than any temporary arrays as would
// be required with the normalization approach.
for (featureIndex = 0; featureIndex < stop; featureIndex++) {
geometryMaybeCollection = isFeatureCollection ? geojson.features[featureIndex].geometry : isFeature ? geojson.geometry : geojson;
isGeometryCollection = geometryMaybeCollection ? geometryMaybeCollection.type === 'GeometryCollection' : false;
stopG = isGeometryCollection ? geometryMaybeCollection.geometries.length : 1;
for (geometryIndex = 0; geometryIndex < stopG; geometryIndex++) {
var featureSubIndex = 0;
geometry = isGeometryCollection ? geometryMaybeCollection.geometries[geometryIndex] : geometryMaybeCollection;
// Handles null Geometry -- Skips this geometry
if (geometry === null) continue;
coords = geometry.coordinates;
var geomType = geometry.type;
wrapShrink = excludeWrapCoord && (geomType === 'Polygon' || geomType === 'MultiPolygon') ? 1 : 0;
switch (geomType) {
case null:
break;
case 'Point':
callback(coords, coordIndex, featureIndex, featureSubIndex);
coordIndex++;
featureSubIndex++;
break;
case 'LineString':
case 'MultiPoint':
for (j = 0; j < coords.length; j++) {
callback(coords[j], coordIndex, featureIndex, featureSubIndex);
coordIndex++;
if (geomType === 'MultiPoint') featureSubIndex++;
}
if (geomType === 'LineString') featureSubIndex++;
break;
case 'Polygon':
case 'MultiLineString':
for (j = 0; j < coords.length; j++) {
for (k = 0; k < coords[j].length - wrapShrink; k++) {
callback(coords[j][k], coordIndex, featureIndex, featureSubIndex);
coordIndex++;
}
if (geomType === 'MultiLineString') featureSubIndex++;
}
if (geomType === 'Polygon') featureSubIndex++;
break;
case 'MultiPolygon':
for (j = 0; j < coords.length; j++) {
for (k = 0; k < coords[j].length; k++) {
for (l = 0; l < coords[j][k].length - wrapShrink; l++) {
callback(coords[j][k][l], coordIndex, featureIndex, featureSubIndex);
coordIndex++;
}
}featureSubIndex++;
}
break;
case 'GeometryCollection':
for (j = 0; j < geometry.geometries.length; j++) {
coordEach$1(geometry.geometries[j], callback, excludeWrapCoord);
}break;
default:
throw new Error('Unknown Geometry Type');
}
}
}
}
/**
* Callback for coordReduce
*
* The first time the callback function is called, the values provided as arguments depend
* on whether the reduce method has an initialValue argument.
*
* If an initialValue is provided to the reduce method:
* - The previousValue argument is initialValue.
* - The currentValue argument is the value of the first element present in the array.
*
* If an initialValue is not provided:
* - The previousValue argument is the value of the first element present in the array.
* - The currentValue argument is the value of the second element present in the array.
*
* @callback coordReduceCallback
* @param {*} previousValue The accumulated value previously returned in the last invocation
* of the callback, or initialValue, if supplied.
* @param {Array<number>} currentCoord The current coordinate being processed.
* @param {number} coordIndex The current index of the coordinate being processed.
* Starts at index 0, if an initialValue is provided, and at index 1 otherwise.
* @param {number} featureIndex The current index of the feature being processed.
* @param {number} featureSubIndex The current subIndex of the feature being processed.
*/
/**
* Reduce coordinates in any GeoJSON object, similar to Array.reduce()
*
* @name coordReduce
* @param {FeatureCollection|Geometry|Feature} geojson any GeoJSON object
* @param {Function} callback a method that takes (previousValue, currentCoord, coordIndex)
* @param {*} [initialValue] Value to use as the first argument to the first call of the callback.
* @param {boolean} [excludeWrapCoord=false] whether or not to include the final coordinate of LinearRings that wraps the ring in its iteration.
* @returns {*} The value that results from the reduction.
* @example
* var features = turf.featureCollection([
* turf.point([26, 37], {"foo": "bar"}),
* turf.point([36, 53], {"hello": "world"})
* ]);
*
* turf.coordReduce(features, function (previousValue, currentCoord, coordIndex, featureIndex, featureSubIndex) {
* //=previousValue
* //=currentCoord
* //=coordIndex
* //=featureIndex
* //=featureSubIndex
* return currentCoord;
* });
*/
function coordReduce(geojson, callback, initialValue, excludeWrapCoord) {
var previousValue = initialValue;
coordEach$1(geojson, function (currentCoord, coordIndex, featureIndex, featureSubIndex) {
if (coordIndex === 0 && initialValue === undefined) previousValue = currentCoord;else previousValue = callback(previousValue, currentCoord, coordIndex, featureIndex, featureSubIndex);
}, excludeWrapCoord);
return previousValue;
}
/**
* Callback for propEach
*
* @callback propEachCallback
* @param {Object} currentProperties The current properties being processed.
* @param {number} featureIndex The index of the current element being processed in the
* array.Starts at index 0, if an initialValue is provided, and at index 1 otherwise.
*/
/**
* Iterate over properties in any GeoJSON object, similar to Array.forEach()
*
* @name propEach
* @param {(FeatureCollection|Feature)} geojson any GeoJSON object
* @param {Function} callback a method that takes (currentProperties, featureIndex)
* @example
* var features = turf.featureCollection([
* turf.point([26, 37], {foo: 'bar'}),
* turf.point([36, 53], {hello: 'world'})
* ]);
*
* turf.propEach(features, function (currentProperties, featureIndex) {
* //=currentProperties
* //=featureIndex
* });
*/
function propEach(geojson, callback) {
var i;
switch (geojson.type) {
case 'FeatureCollection':
for (i = 0; i < geojson.features.length; i++) {
callback(geojson.features[i].properties, i);
}
break;
case 'Feature':
callback(geojson.properties, 0);
break;
}
}
/**
* Callback for propReduce
*
* The first time the callback function is called, the values provided as arguments depend
* on whether the reduce method has an initialValue argument.
*
* If an initialValue is provided to the reduce method:
* - The previousValue argument is initialValue.
* - The currentValue argument is the value of the first element present in the array.
*
* If an initialValue is not provided:
* - The previousValue argument is the value of the first element present in the array.
* - The currentValue argument is the value of the second element present in the array.
*
* @callback propReduceCallback
* @param {*} previousValue The accumulated value previously returned in the last invocation
* of the callback, or initialValue, if supplied.
* @param {*} currentProperties The current properties being processed.
* @param {number} featureIndex The index of the current element being processed in the
* array.Starts at index 0, if an initialValue is provided, and at index 1 otherwise.
*/
/**
* Reduce properties in any GeoJSON object into a single value,
* similar to how Array.reduce works. However, in this case we lazily run
* the reduction, so an array of all properties is unnecessary.
*
* @name propReduce
* @param {(FeatureCollection|Feature)} geojson any GeoJSON object
* @param {Function} callback a method that takes (previousValue, currentProperties, featureIndex)
* @param {*} [initialValue] Value to use as the first argument to the first call of the callback.
* @returns {*} The value that results from the reduction.
* @example
* var features = turf.featureCollection([
* turf.point([26, 37], {foo: 'bar'}),
* turf.point([36, 53], {hello: 'world'})
* ]);
*
* turf.propReduce(features, function (previousValue, currentProperties, featureIndex) {
* //=previousValue
* //=currentProperties
* //=featureIndex
* return currentProperties
* });
*/
function propReduce(geojson, callback, initialValue) {
var previousValue = initialValue;
propEach(geojson, function (currentProperties, featureIndex) {
if (featureIndex === 0 && initialValue === undefined) previousValue = currentProperties;else previousValue = callback(previousValue, currentProperties, featureIndex);
});
return previousValue;
}
/**
* Callback for featureEach
*
* @callback featureEachCallback
* @param {Feature<any>} currentFeature The current feature being processed.
* @param {number} featureIndex The index of the current element being processed in the
* array.Starts at index 0, if an initialValue is provided, and at index 1 otherwise.
*/
/**
* Iterate over features in any GeoJSON object, similar to
* Array.forEach.
*
* @name featureEach
* @param {(FeatureCollection|Feature|Geometry)} geojson any GeoJSON object
* @param {Function} callback a method that takes (currentFeature, featureIndex)
* @example
* var features = turf.featureCollection([
* turf.point([26, 37], {foo: 'bar'}),
* turf.point([36, 53], {hello: 'world'})
* ]);
*
* turf.featureEach(features, function (currentFeature, featureIndex) {
* //=currentFeature
* //=featureIndex
* });
*/
function featureEach$1(geojson, callback) {
if (geojson.type === 'Feature') {
callback(geojson, 0);
} else if (geojson.type === 'FeatureCollection') {
for (var i = 0; i < geojson.features.length; i++) {
callback(geojson.features[i], i);
}
}
}
/**
* Callback for featureReduce
*
* The first time the callback function is called, the values provided as arguments depend
* on whether the reduce method has an initialValue argument.
*
* If an initialValue is provided to the reduce method:
* - The previousValue argument is initialValue.
* - The currentValue argument is the value of the first element present in the array.
*
* If an initialValue is not provided:
* - The previousValue argument is the value of the first element present in the array.
* - The currentValue argument is the value of the second element present in the array.
*
* @callback featureReduceCallback
* @param {*} previousValue The accumulated value previously returned in the last invocation
* of the callback, or initialValue, if supplied.
* @param {Feature} currentFeature The current Feature being processed.
* @param {number} featureIndex The index of the current element being processed in the
* array.Starts at index 0, if an initialValue is provided, and at index 1 otherwise.
*/
/**
* Reduce features in any GeoJSON object, similar to Array.reduce().
*
* @name featureReduce
* @param {(FeatureCollection|Feature|Geometry)} geojson any GeoJSON object
* @param {Function} callback a method that takes (previousValue, currentFeature, featureIndex)
* @param {*} [initialValue] Value to use as the first argument to the first call of the callback.
* @returns {*} The value that results from the reduction.
* @example
* var features = turf.featureCollection([
* turf.point([26, 37], {"foo": "bar"}),
* turf.point([36, 53], {"hello": "world"})
* ]);
*
* turf.featureReduce(features, function (previousValue, currentFeature, featureIndex) {
* //=previousValue
* //=currentFeature
* //=featureIndex
* return currentFeature
* });
*/
function featureReduce(geojson, callback, initialValue) {
var previousValue = initialValue;
featureEach$1(geojson, function (currentFeature, featureIndex) {
if (featureIndex === 0 && initialValue === undefined) previousValue = currentFeature;else previousValue = callback(previousValue, currentFeature, featureIndex);
});
return previousValue;
}
/**
* Get all coordinates from any GeoJSON object.
*
* @name coordAll
* @param {(FeatureCollection|Feature|Geometry)} geojson any GeoJSON object
* @returns {Array<Array<number>>} coordinate position array
* @example
* var features = turf.featureCollection([
* turf.point([26, 37], {foo: 'bar'}),
* turf.point([36, 53], {hello: 'world'})
* ]);
*
* var coords = turf.coordAll(features);
* //= [[26, 37], [36, 53]]
*/
function coordAll(geojson) {
var coords = [];
coordEach$1(geojson, function (coord) {
coords.push(coord);
});
return coords;
}
/**
* Callback for geomEach
*
* @callback geomEachCallback
* @param {Geometry} currentGeometry The current geometry being processed.
* @param {number} currentIndex The index of the current element being processed in the
* array. Starts at index 0, if an initialValue is provided, and at index 1 otherwise.
* @param {number} currentProperties The current feature properties being processed.
*/
/**
* Iterate over each geometry in any GeoJSON object, similar to Array.forEach()
*
* @name geomEach
* @param {(FeatureCollection|Feature|Geometry)} geojson any GeoJSON object
* @param {Function} callback a method that takes (currentGeometry, featureIndex, currentProperties)
* @example
* var features = turf.featureCollection([
* turf.point([26, 37], {foo: 'bar'}),
* turf.point([36, 53], {hello: 'world'})
* ]);
*
* turf.geomEach(features, function (currentGeometry, featureIndex, currentProperties) {
* //=currentGeometry
* //=featureIndex
* //=currentProperties
* });
*/
function geomEach(geojson, callback) {
var i,
j,
g,
geometry,
stopG,
geometryMaybeCollection,
isGeometryCollection,
geometryProperties,
featureIndex = 0,
isFeatureCollection = geojson.type === 'FeatureCollection',
isFeature = geojson.type === 'Feature',
stop = isFeatureCollection ? geojson.features.length : 1;
// This logic may look a little weird. The reason why it is that way
// is because it's trying to be fast. GeoJSON supports multiple kinds
// of objects at its root: FeatureCollection, Features, Geometries.
// This function has the responsibility of handling all of them, and that
// means that some of the `for` loops you see below actually just don't apply
// to certain inputs. For instance, if you give this just a
// Point geometry, then both loops are short-circuited and all we do
// is gradually rename the input until it's called 'geometry'.
//
// This also aims to allocate as few resources as possible: just a
// few numbers and booleans, rather than any temporary arrays as would
// be required with the normalization approach.
for (i = 0; i < stop; i++) {
geometryMaybeCollection = isFeatureCollection ? geojson.features[i].geometry : isFeature ? geojson.geometry : geojson;
geometryProperties = isFeatureCollection ? geojson.features[i].properties : isFeature ? geojson.properties : {};
isGeometryCollection = geometryMaybeCollection ? geometryMaybeCollection.type === 'GeometryCollection' : false;
stopG = isGeometryCollection ? geometryMaybeCollection.geometries.length : 1;
for (g = 0; g < stopG; g++) {
geometry = isGeometryCollection ? geometryMaybeCollection.geometries[g] : geometryMaybeCollection;
// Handle null Geometry
if (geometry === null) {
callback(null, featureIndex, geometryProperties);
continue;
}
switch (geometry.type) {
case 'Point':
case 'LineString':
case 'MultiPoint':
case 'Polygon':
case 'MultiLineString':
case 'MultiPolygon':
{
callback(geometry, featureIndex, geometryProperties);
break;
}
case 'GeometryCollection':
{
for (j = 0; j < geometry.geometries.length; j++) {
callback(geometry.geometries[j], featureIndex, geometryProperties);
}
break;
}
default:
throw new Error('Unknown Geometry Type');
}
}
// Only increase `featureIndex` per each feature
featureIndex++;
}
}
/**
* Callback for geomReduce
*
* The first time the callback function is called, the values provided as arguments depend
* on whether the reduce method has an initialValue argument.
*
* If an initialValue is provided to the reduce method:
* - The previousValue argument is initialValue.
* - The currentValue argument is the value of the first element present in the array.
*
* If an initialValue is not provided:
* - The previousValue argument is the value of the first element present in the array.
* - The currentValue argument is the value of the second element present in the array.
*
* @callback geomReduceCallback
* @param {*} previousValue The accumulated value previously returned in the last invocation
* of the callback, or initialValue, if supplied.
* @param {Geometry} currentGeometry The current Feature being processed.
* @param {number} currentIndex The index of the current element being processed in the
* array.Starts at index 0, if an initialValue is provided, and at index 1 otherwise.
* @param {Object} currentProperties The current feature properties being processed.
*/
/**
* Reduce geometry in any GeoJSON object, similar to Array.reduce().
*
* @name geomReduce
* @param {(FeatureCollection|Feature|Geometry)} geojson any GeoJSON object
* @param {Function} callback a method that takes (previousValue, currentGeometry, featureIndex, currentProperties)
* @param {*} [initialValue] Value to use as the first argument to the first call of the callback.
* @returns {*} The value that results from the reduction.
* @example
* var features = turf.featureCollection([
* turf.point([26, 37], {foo: 'bar'}),
* turf.point([36, 53], {hello: 'world'})
* ]);
*
* turf.geomReduce(features, function (previousValue, currentGeometry, featureIndex, currentProperties) {
* //=previousValue
* //=currentGeometry
* //=featureIndex
* //=currentProperties
* return currentGeometry
* });
*/
function geomReduce(geojson, callback, initialValue) {
var previousValue = initialValue;
geomEach(geojson, function (currentGeometry, currentIndex, currentProperties) {
if (currentIndex === 0 && initialValue === undefined) previousValue = currentGeometry;else previousValue = callback(previousValue, currentGeometry, currentIndex, currentProperties);
});
return previousValue;
}
/**
* Callback for flattenEach
*
* @callback flattenEachCallback
* @param {Feature} currentFeature The current flattened feature being processed.
* @param {number} featureIndex The index of the current element being processed in the
* array. Starts at index 0, if an initialValue is provided, and at index 1 otherwise.
* @param {number} featureSubIndex The subindex of the current element being processed in the
* array. Starts at index 0 and increases if the flattened feature was a multi-geometry.
*/
/**
* Iterate over flattened features in any GeoJSON object, similar to
* Array.forEach.
*
* @name flattenEach
* @param {(FeatureCollection|Feature|Geometry)} geojson any GeoJSON object
* @param {Function} callback a method that takes (currentFeature, featureIndex, featureSubIndex)
* @example
* var features = turf.featureCollection([
* turf.point([26, 37], {foo: 'bar'}),
* turf.multiPoint([[40, 30], [36, 53]], {hello: 'world'})
* ]);
*
* turf.flattenEach(features, function (currentFeature, featureIndex, featureSubIndex) {
* //=currentFeature
* //=featureIndex
* //=featureSubIndex
* });
*/
function flattenEach(geojson, callback) {
geomEach(geojson, function (geometry, featureIndex, properties) {
// Callback for single geometry
var type = geometry === null ? null : geometry.type;
switch (type) {
case null:
case 'Point':
case 'LineString':
case 'Polygon':
callback(feature(geometry, properties), featureIndex, 0);
return;
}
var geomType;
// Callback for multi-geometry
switch (type) {
case 'MultiPoint':
geomType = 'Point';
break;
case 'MultiLineString':
geomType = 'LineString';
break;
case 'MultiPolygon':
geomType = 'Polygon';
break;
}
geometry.coordinates.forEach(function (coordinate, featureSubIndex) {
var geom = {
type: geomType,
coordinates: coordinate
};
callback(feature(geom, properties), featureIndex, featureSubIndex);
});
});
}
/**
* Callback for flattenReduce
*
* The first time the callback function is called, the values provided as arguments depend
* on whether the reduce method has an initialValue argument.
*
* If an initialValue is provided to the reduce method:
* - The previousValue argument is initialValue.
* - The currentValue argument is the value of the first element present in the array.
*
* If an initialValue is not provided:
* - The previousValue argument is the value of the first element present in the array.
* - The currentValue argument is the value of the second element present in the array.
*
* @callback flattenReduceCallback
* @param {*} previousValue The accumulated value previously returned in the last invocation
* of the callback, or initialValue, if supplied.
* @param {Feature} currentFeature The current Feature being processed.
* @param {number} featureIndex The index of the current element being processed in the
* array.Starts at index 0, if an initialValue is provided, and at index 1 otherwise.
* @param {number} featureSubIndex The subindex of the current element being processed in the
* array. Starts at index 0 and increases if the flattened feature was a multi-geometry.
*/
/**
* Reduce flattened features in any GeoJSON object, similar to Array.reduce().
*
* @name flattenReduce
* @param {(FeatureCollection|Feature|Geometry)} geojson any GeoJSON object
* @param {Function} callback a method that takes (previousValue, currentFeature, featureIndex, featureSubIndex)
* @param {*} [initialValue] Value to use as the first argument to the first call of the callback.
* @returns {*} The value that results from the reduction.
* @example
* var features = turf.featureCollection([
* turf.point([26, 37], {foo: 'bar'}),
* turf.multiPoint([[40, 30], [36, 53]], {hello: 'world'})
* ]);
*
* turf.flattenReduce(features, function (previousValue, currentFeature, featureIndex, featureSubIndex) {
* //=previousValue
* //=currentFeature
* //=featureIndex
* //=featureSubIndex
* return currentFeature
* });
*/
function flattenReduce(geojson, callback, initialValue) {
var previousValue = initialValue;
flattenEach(geojson, function (currentFeature, featureIndex, featureSubIndex) {
if (featureIndex === 0 && featureSubIndex === 0 && initialValue === undefined) previousValue = currentFeature;else previousValue = callback(previousValue, currentFeature, featureIndex, featureSubIndex);
});
return previousValue;
}
/**
* Callback for segmentEach
*
* @callback segmentEachCallback
* @param {Feature<LineString>} currentSegment The current segment being processed.
* @param {number} featureIndex The featureIndex currently being processed, starts at index 0.
* @param {number} featureSubIndex The featureSubIndex currently being processed, starts at index 0.
* @param {number} segmentIndex The segmentIndex currently being processed, starts at index 0.
* @returns {void}
*/
/**
* Iterate over 2-vertex line segment in any GeoJSON object, similar to Array.forEach()
* (Multi)Point geometries do not contain segments therefore they are ignored during this operation.
*
* @param {(FeatureCollection|Feature|Geometry)} geojson any GeoJSON
* @param {Function} callback a method that takes (currentSegment, featureIndex, featureSubIndex)
* @returns {void}
* @example
* var polygon = turf.polygon([[[-50, 5], [-40, -10], [-50, -10], [-40, 5], [-50, 5]]]);
*
* // Iterate over GeoJSON by 2-vertex segments
* turf.segmentEach(polygon, function (currentSegment, featureIndex, featureSubIndex, segmentIndex) {
* //= currentSegment
* //= featureIndex
* //= featureSubIndex
* //= segmentIndex
* });
*
* // Calculate the total number of segments
* var total = 0;
* turf.segmentEach(polygon, function () {
* total++;
* });
*/
function segmentEach(geojson, callback) {
flattenEach(geojson, function (feature, featureIndex, featureSubIndex) {
var segmentIndex = 0;
// Exclude null Geometries
if (!feature.geometry) return;
// (Multi)Point geometries do not contain segments therefore they are ignored during this operation.
var type = feature.geometry.type;
if (type === 'Point' || type === 'MultiPoint') return;
// Generate 2-vertex line segments
coordReduce(feature, function (previousCoords, currentCoord) {
var currentSegment = lineString([previousCoords, currentCoord], feature.properties);
callback(currentSegment, featureIndex, featureSubIndex, segmentIndex);
segmentIndex++;
return currentCoord;
});
});
}
/**
* Callback for segmentReduce
*
* The first time the callback function is called, the values provided as arguments depend
* on whether the reduce method has an initialValue argument.
*
* If an initialValue is provided to the reduce method:
* - The previousValue argument is initialValue.
* - The currentValue argument is the value of the first element present in the array.
*
* If an initialValue is not provided:
* - The previousValue argument is the value of the first element present in the array.
* - The currentValue argument is the value of the second element present in the array.
*
* @callback segmentReduceCallback
* @param {*} [previousValue] The accumulated value previously returned in the last invocation
* of the callback, or initialValue, if supplied.
* @param {Feature<LineString>} [currentSegment] The current segment being processed.
* @param {number} featureIndex The featureIndex currently being processed, starts at index 0.
* @param {number} featureSubIndex The featureSubIndex currently being processed, starts at index 0.
* @param {number} segmentIndex The segmentIndex currently being processed, starts at index 0.
*/
/**
* Reduce 2-vertex line segment in any GeoJSON object, similar to Array.reduce()
* (Multi)Point geometries do not contain segments therefore they are ignored during this operation.
*
* @param {(FeatureCollection|Feature|Geometry)} geojson any GeoJSON
* @param {Function} callback a method that takes (previousValue, currentSegment, currentIndex)
* @param {*} [initialValue] Value to use as the first argument to the first call of the callback.
* @returns {void}
* @example
* var polygon = turf.polygon([[[-50, 5], [-40, -10], [-50, -10], [-40, 5], [-50, 5]]]);
*
* // Iterate over GeoJSON by 2-vertex segments
* turf.segmentReduce(polygon, function (previousSegment, currentSegment, featureIndex, featureSubIndex, segmentIndex) {
* //= previousSegment
* //= currentSegment
* //= featureIndex
* //= featureSubIndex
* //= segmentInex
* return currentSegment
* });
*
* // Calculate the total number of segments
* var initialValue = 0
* var total = turf.segmentReduce(polygon, function (previousValue) {
* previousValue++;
* return previousValue;
* }, initialValue);
*/
function segmentReduce(geojson, callback, initialValue) {
var previousValue = initialValue;
var started = false;
segmentEach(geojson, function (currentSegment, featureIndex, featureSubIndex, segmentIndex) {
if (started === false && initialValue === undefined) previousValue = currentSegment;else previousValue = callback(previousValue, currentSegment, featureIndex, featureSubIndex, segmentIndex);
started = true;
});
return previousValue;
}
/**
* Create Feature
*
* @private
* @param {Geometry} geometry GeoJSON Geometry
* @param {Object} properties Properties
* @returns {Feature} GeoJSON Feature
*/
function feature(geometry, properties) {
if (geometry === undefined) throw new Error('No geometry passed');
return {
type: 'Feature',
properties: properties || {},
geometry: geometry
};
}
/**
* Create LineString
*
* @private
* @param {Array<Array<number>>} coordinates Line Coordinates
* @param {Object} properties Properties
* @returns {Feature<LineString>} GeoJSON LineString Feature
*/
function lineString(coordinates, properties) {
if (!coordinates) throw new Error('No coordinates passed');
if (coordinates.length < 2) throw new Error('Coordinates must be an array of two or more positions');
return {
type: 'Feature',
properties: properties || {},
geometry: {
type: 'LineString',
coordinates: coordinates
}
};
}
/**
* Callback for lineEach
*
* @callback lineEachCallback
* @param {Feature<LineString>} currentLine The current LineString|LinearRing being processed.
* @param {number} lineIndex The index of the current element being processed in the array, starts at index 0.
* @param {number} lineSubIndex The sub-index of the current line being processed at index 0
*/
/**
* Iterate over line or ring coordinates in LineString, Polygon, MultiLineString, MultiPolygon Features or Geometries,
* similar to Array.forEach.
*
* @name lineEach
* @param {Geometry|Feature<LineString|Polygon|MultiLineString|MultiPolygon>} geojson object
* @param {Function} callback a method that takes (currentLine, lineIndex, lineSubIndex)
* @example
* var mtLn = turf.multiLineString([
* turf.lineString([[26, 37], [35, 45]]),
* turf.lineString([[36, 53], [38, 50], [41, 55]])
* ]);
*
* turf.lineEach(mtLn, function (currentLine, lineIndex) {
* //=currentLine
* //=lineIndex
* });
*/
function lineEach(geojson, callback) {
// validation
if (!geojson) throw new Error('geojson is required');
var type = geojson.geometry ? geojson.geometry.type : geojson.type;
if (!type) throw new Error('invalid geojson');
if (type === 'FeatureCollection') throw new Error('FeatureCollection is not supported');
if (type === 'GeometryCollection') throw new Error('GeometryCollection is not supported');
var coordinates = geojson.geometry ? geojson.geometry.coordinates : geojson.coordinates;
if (!coordinates) throw new Error('geojson must contain coordinates');
switch (type) {
case 'LineString':
callback(coordinates, 0, 0);
return;
case 'Polygon':
case 'MultiLineString':
var subIndex = 0;
for (var line = 0; line < coordinates.length; line++) {
if (type === 'MultiLineString') subIndex = line;
callback(coordinates[line], line, subIndex);
}
return;
case 'MultiPolygon':
for (var multi = 0; multi < coordinates.length; multi++) {
for (var ring = 0; ring < coordinates[multi].length; ring++) {
callback(coordinates[multi][ring], ring, multi);
}
}
return;
default:
throw new Error(type + ' geometry not supported');
}
}
/**
* Callback for lineReduce
*
* The first time the callback function is called, the values provided as arguments depend
* on whether the reduce method has an initialValue argument.
*
* If an initialValue is provided to the reduce method:
* - The previousValue argument is initialValue.
* - The currentValue argument is the value of the first element present in the array.
*
* If an initialValue is not provided:
* - The previousValue argument is the value of the first element present in the array.
* - The currentValue argument is the value of the second element present in the array.
*
* @callback lineReduceCallback
* @param {*} previousValue The accumulated value previously returned in the last invocation
* of the callback, or initialValue, if supplied.
* @param {Feature<LineString>} currentLine The current LineString|LinearRing being processed.
* @param {number} lineIndex The index of the current element being processed in the
* array. Starts at index 0, if an initialValue is provided, and at index 1 otherwise.
* @param {number} lineSubIndex The sub-index of the current line being processed at index 0
*/
/**
* Reduce features in any GeoJSON object, similar to Array.reduce().
*
* @name lineReduce
* @param {Geometry|Feature<LineString|Polygon|MultiLineString|MultiPolygon>} geojson object
* @param {Function} callback a method that takes (previousValue, currentFeature, featureIndex)
* @param {*} [initialValue] Value to use as the first argument to the first call of the callback.
* @returns {*} The value that results from the reduction.
* @example
* var mtp = turf.multiPolygon([
* turf.polygon([[[12,48],[2,41],[24,38],[12,48]], [[9,44],[13,41],[13,45],[9,44]]]),
* turf.polygon([[[5, 5], [0, 0], [2, 2], [4, 4], [5, 5]]])
* ]);
*
* turf.lineReduce(mtp, function (previousValue, currentLine, lineIndex, lineSubIndex) {
* //=previousValue
* //=currentLine
* //=lineIndex
* //=lineSubIndex
* return currentLine
* }, 2);
*/
function lineReduce(geojson, callback, initialValue) {
var previousValue = initialValue;
lineEach(geojson, function (currentLine, lineIndex, lineSubIndex) {
if (lineIndex === 0 && initialValue === undefined) previousValue = currentLine;else previousValue = callback(previousValue, currentLine, lineIndex, lineSubIndex);
});
return previousValue;
}
var index$3 = Object.freeze({
coordEach: coordEach$1,
coordReduce: coordReduce,
propEach: propEach,
propReduce: propReduce,
featureEach: featureEach$1,
featureReduce: featureReduce,
coordAll: coordAll,
geomEach: geomEach,
geomReduce: geomReduce,
flattenEach: flattenEach,
flattenReduce: flattenReduce,
segmentEach: segmentEach,
segmentReduce: segmentReduce,
feature: feature,
lineString: lineString,
lineEach: lineEach,
lineReduce: lineReduce
});
var require$$1 = ( index$3 && undefined ) || index$3;
var rbush = index$1;
var meta = require$$1;
var featureEach = meta.featureEach;
var coordEach = meta.coordEach;
/**
* GeoJSON implementation of [RBush](https://github.com/mourner/rbush#rbush) spatial index.
*
* @name rbush
* @param {number} [maxEntries=9] defines the maximum number of entries in a tree node. 9 (used by default) is a
* reasonable choice for most applications. Higher value means faster insertion and slower search, and vice versa.
* @returns {RBush} GeoJSON RBush
* @example
* var rbush = require('geojson-rbush')
* var tree = rbush()
*/
var index = function index(maxEntries) {
var tree = rbush(maxEntries);
/**
* [insert](https://github.com/mourner/rbush#data-format)
*
* @param {Feature<any>} feature insert single GeoJSON Feature
* @returns {RBush} GeoJSON RBush
* @example
* var polygon = {
* "type": "Feature",
* "properties": {},
* "geometry": {
* "type": "Polygon",
* "coordinates": [[[-78, 41], [-67, 41], [-67, 48], [-78, 48], [-78, 41]]]
* }
* }
* tree.insert(polygon)
*/
tree.insert = function (feature) {
if (Array.isArray(feature)) {
var bbox = feature;
feature = bboxPolygon(bbox);
feature.bbox = bbox;
} else {
feature.bbox = feature.bbox ? feature.bbox : turfBBox(feature);
}
return rbush.prototype.insert.call(this, feature);
};
/**
* [load](https://github.com/mourner/rbush#bulk-inserting-data)
*
* @param {BBox[]|FeatureCollection<any>} features load entire GeoJSON FeatureCollection
* @returns {RBush} GeoJSON RBush
* @example
* var polygons = {
* "type": "FeatureCollection",
* "features": [
* {
* "type": "Feature",
* "properties": {},
* "geometry": {
* "type": "Polygon",
* "coordinates": [[[-78, 41], [-67, 41], [-67, 48], [-78, 48], [-78, 41]]]
* }
* },
* {
* "type": "Feature",
* "properties": {},
* "geometry": {
* "type": "Polygon",
* "coordinates": [[[-93, 32], [-83, 32], [-83, 39], [-93, 39], [-93, 32]]]
* }
* }
* ]
* }
* tree.load(polygons)
*/
tree.load = function (features) {
var load = [];
// Load an Array of BBox
if (Array.isArray(features)) {
features.forEach(function (bbox) {
var feature = bboxPolygon(bbox);
feature.bbox = bbox;
load.push(feature);
});
} else {
// Load FeatureCollection
featureEach(features, function (feature) {
feature.bbox = feature.bbox ? feature.bbox : turfBBox(feature);
load.push(feature);
});
}
return rbush.prototype.load.call(this, load);
};
/**
* [remove](https://github.com/mourner/rbush#removing-data)
*
* @param {BBox|Feature<any>} feature remove single GeoJSON Feature
* @returns {RBush} GeoJSON RBush
* @example
* var polygon = {
* "type": "Feature",
* "properties": {},
* "geometry": {
* "type": "Polygon",
* "coordinates": [[[-78, 41], [-67, 41], [-67, 48], [-78, 48], [-78, 41]]]
* }
* }
* tree.remove(polygon)
*/
tree.remove = function (feature) {
if (Array.isArray(feature)) {
var bbox = feature;
feature = bboxPolygon(bbox);
feature.bbox = bbox;
}
return rbush.prototype.remove.call(this, feature);
};
/**
* [clear](https://github.com/mourner/rbush#removing-data)
*
* @returns {RBush} GeoJSON Rbush
* @example
* tree.clear()
*/
tree.clear = function () {
return rbush.prototype.clear.call(this);
};
/**
* [search](https://github.com/mourner/rbush#search)
*
* @param {BBox|FeatureCollection|Feature<any>} geojson search with GeoJSON
* @returns {FeatureCollection<any>} all features that intersects with the given GeoJSON.
* @example
* var polygon = {
* "type": "Feature",
* "properties": {},
* "geometry": {
* "type": "Polygon",
* "coordinates": [[[-78, 41], [-67, 41], [-67, 48], [-78, 48], [-78, 41]]]
* }
* }
* tree.search(polygon)
*/
tree.search = function (geojson) {
var features = rbush.prototype.search.call(this, this.toBBox(geojson));
return {
type: 'FeatureCollection',
features: features
};
};
/**
* [collides](https://github.com/mourner/rbush#collisions)
*
* @param {BBox|FeatureCollection|Feature<any>} geojson collides with GeoJSON
* @returns {boolean} true if there are any items intersecting the given GeoJSON, otherwise false.
* @example
* var polygon = {
* "type": "Feature",
* "properties": {},
* "geometry": {
* "type": "Polygon",
* "coordinates": [[[-78, 41], [-67, 41], [-67, 48], [-78, 48], [-78, 41]]]
* }
* }
* tree.collides(polygon)
*/
tree.collides = function (geojson) {
return rbush.prototype.collides.call(this, this.toBBox(geojson));
};
/**
* [all](https://github.com/mourner/rbush#search)
*
* @returns {FeatureCollection<any>} all the features in RBush
* @example
* tree.all()
* //=FeatureCollection
*/
tree.all = function () {
var features = rbush.prototype.all.call(this);
return {
type: 'FeatureCollection',
features: features
};
};
/**
* [toJSON](https://github.com/mourner/rbush#export-and-import)
*
* @returns {any} export data as JSON object
* @example
* var exported = tree.toJSON()
* //=JSON object
*/
tree.toJSON = function () {
return rbush.prototype.toJSON.call(this);
};
/**
* [fromJSON](https://github.com/mourner/rbush#export-and-import)
*
* @param {any} json import previously exported data
* @returns {RBush} GeoJSON RBush
* @example
* var exported = {
* "children": [
* {
* "type": "Feature",
* "geometry": {
* "type": "Point",
* "coordinates": [110, 50]
* },
* "properties": {},
* "bbox": [110, 50, 110, 50]
* }
* ],
* "height": 1,
* "leaf": true,
* "minX": 110,
* "minY": 50,
* "maxX": 110,
* "maxY": 50
* }
* tree.fromJSON(exported)
*/
tree.fromJSON = function (json) {
return rbush.prototype.fromJSON.call(this, json);
};
/**
* Converts GeoJSON to {minX, minY, maxX, maxY} schema
*
* @private
* @param {BBox|FeatureCollectio|Feature<any>} geojson feature(s) to retrieve BBox from
* @returns {Object} converted to {minX, minY, maxX, maxY}
*/
tree.toBBox = function (geojson) {
var bbox;
if (geojson.bbox) bbox = geojson.bbox;else if (Array.isArray(geojson) && geojson.length === 4) bbox = geojson;else bbox = turfBBox(geojson);
return {
minX: bbox[0],
minY: bbox[1],
maxX: bbox[2],
maxY: bbox[3]
};
};
return tree;
};
/**
* Takes a bbox and returns an equivalent {@link Polygon|polygon}.
*
* @private
* @name bboxPolygon
* @param {Array<number>} bbox extent in [minX, minY, maxX, maxY] order
* @returns {Feature<Polygon>} a Polygon representation of the bounding box
* @example
* var bbox = [0, 0, 10, 10];
*
* var poly = turf.bboxPolygon(bbox);
*
* //addToMap
* var addToMap = [poly]
*/
function bboxPolygon(bbox) {
var lowLeft = [bbox[0], bbox[1]];
var topLeft = [bbox[0], bbox[3]];
var topRight = [bbox[2], bbox[3]];
var lowRight = [bbox[2], bbox[1]];
var coordinates = [[lowLeft, lowRight, topRight, topLeft, lowLeft]];
return {
type: 'Feature',
bbox: bbox,
properties: {},
geometry: {
type: 'Polygon',
coordinates: coordinates
}
};
}
/**
* Takes a set of features, calculates the bbox of all input features, and returns a bounding box.
*
* @private
* @name bbox
* @param {FeatureCollection|Feature<any>} geojson input features
* @returns {Array<number>} bbox extent in [minX, minY, maxX, maxY] order
* @example
* var line = turf.lineString([[-74, 40], [-78, 42], [-82, 35]]);
* var bbox = turf.bbox(line);
* var bboxPolygon = turf.bboxPolygon(bbox);
*
* //addToMap
* var addToMap = [line, bboxPolygon]
*/
function turfBBox(geojson) {
var bbox = [Infinity, Infinity, -Infinity, -Infinity];
coordEach(geojson, function (coord) {
if (bbox[0] > coord[0]) bbox[0] = coord[0];
if (bbox[1] > coord[1]) bbox[1] = coord[1];
if (bbox[2] < coord[0]) bbox[2] = coord[0];
if (bbox[3] < coord[1]) bbox[3] = coord[1];
});
return bbox;
}
function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults(subClass, superClass); }
var options = {
'mode': 'line',
'tolerance': 10,
'symbol': {
'markerType': 'ellipse',
'markerFill': '#0f89f5',
'markerLineColor': '#fff',
'markerLineWidth': 2,
'markerLineOpacity': 1,
'markerWidth': 15,
'markerHeight': 15
}
};
/**
* A snap tool used for mouse point to adsorb geometries, it extends maptalks.Class.
*
* Thanks to rbush's author, this pluging has used the rbush to inspect surrounding geometries within tolerance(https://github.com/mourner/rbush)
*
* @author liubgithub(https://github.com/liubgithub)
*
* MIT License
*/
var SnapTool = function (_maptalks$Class) {
_inherits(SnapTool, _maptalks$Class);
function SnapTool(options) {
_classCallCheck(this, SnapTool);
var _this = _possibleConstructorReturn(this, _maptalks$Class.call(this, options));
_this.tree = index();
return _this;
}
SnapTool.prototype.getMode = function getMode() {
this._mode = !this._mode ? this.options['mode'] : this._mode;
if (this._checkMode(this._mode)) {
return this._mode;
} else {
throw new Error('snap mode is invalid');
}
};
SnapTool.prototype.setMode = function setMode(mode) {
if (this._checkMode(this._mode)) {
this._mode = mode;
if (this.snaplayer) {
if (this.snaplayer instanceof Array) {
var _ref;
this.allLayersGeometries = [];
this.snaplayer.forEach(function (tempLayer, index$$1) {
var tempGeometries = tempLayer.getGeometries();
this.allLayersGeometries[index$$1] = this._compositGeometries(tempGeometries);
}.bind(this));
this.allGeometries = (_ref = []).concat.apply(_ref, this.allLayersGeometries);
} else {
var geometries = this.snaplayer.getGeometries();
this.allGeometries = this._compositGeometries(geometries);
}
}
} else {
throw new Error('snap mode is invalid');
}
};
/**
* @param {Map} map object
* When using the snap tool, you should add it to a map firstly.the enable method excute default
*/
SnapTool.prototype.addTo = function addTo(map) {
var id = maptalks.INTERNAL_LAYER_PREFIX + '_snapto';
this._mousemoveLayer = new maptalks.VectorLayer(id).addTo(map);
this._map = map;
this.allGeometries = [];
this.enable();
};
SnapTool.prototype.remove = function remove() {
this.disable();
if (this._mousemoveLayer) {
this._mousemoveLayer.remove();
delete this._mousemoveLayer;
}
};
SnapTool.prototype.getMap = function getMap() {
return this._map;
};
/**
* @param {String} snap mode
* mode should be either 'point' or 'line'
*/
SnapTool.prototype._checkMode = function _checkMode(mode) {
if (mode === 'point' || mode === 'line') {
return true;
} else {
return false;
}
};
/**
* Start snap interaction
*/
SnapTool.prototype.enable = function enable() {
var map = this.getMap();
if (this.snaplayer) {
if (this.snaplayer instanceof Array) {
var _ref2;
this.allLayersGeometries = [];
this.snaplayer.forEach(function (tempLayer, index$$1) {
var tempGeometries = tempLayer.getGeometries();
this.allLayersGeometries[index$$1] = this._compositGeometries(tempGeometries);
}.bind(this));
this.allGeometries = (_ref2 = []).concat.apply(_ref2, this.allLayersGeometries);
} else {
var geometries = this.snaplayer.getGeometries();
this.allGeometries = this._compositGeometries(geometries);
}
}
if (this.allGeometries) {
if (!this._mousemove) {
this._registerEvents(map);
}
if (this._mousemoveLayer) {
this._mousemoveLayer.show();
}
} else {
throw new Error('you should set geometries which are snapped to firstly!');
}
};
/**
* End snap interaction
*/
SnapTool.prototype.disable = function disable() {
var map = this.getMap();
map.off('mousemove touchstart', this._mousemove);
map.off('mousedown', this._mousedown, this);
map.off('mouseup', this._mouseup, this);
if (this._mousemoveLayer) {
this._mousemoveLayer.hide();
}
delete this._mousemove;
this.allGeometries = [];
};
/**
* @param {Geometry||Array<Geometry>} geometries to snap to
* Set geomeries to an array for snapping to
*/
SnapTool.prototype.setGeometries = function setGeometries(geometries) {
geometries = geometries instanceof Array ? geometries : [geometries];
this.allGeometries = this._compositGeometries(geometries);
};
/**
* @param {Layer||maptalk.VectorLayer||Array.<Layer>||Array.<maptalk.VectorLayer>} layer to snap to
* Set layer for snapping to
*/
SnapTool.prototype.setLayer = function setLayer(layer) {
if (layer instanceof Array) {
var _ref5;
this.snaplayer = [];
this.allLayersGeometries = [];
layer.forEach(function (tempLayer, index$$1) {
if (tempLayer instanceof maptalks.VectorLayer) {
this.snaplayer.push(tempLayer);
var tempGeometries = tempLayer.getGeometries();
this.allLayersGeometries[index$$1] = this._compositGeometries(tempGeometries);
tempLayer.on('addgeo', function () {
var _ref3;
var tempGeometries = this.snaplayer[index$$1].getGeometries();
this.allLayersGeometries[index$$1] = this._compositGeometries(tempGeometries);
this.allGeometries = (_ref3 = []).concat.apply(_ref3, this.allLayersGeometries);
}, this);
tempLayer.on('clear', function () {
var _ref4;
this.allLayersGeometries.splice(index$$1, 1);
this.allGeometries = (_ref4 = []).concat.apply(_ref4, this.allLayersGeometries);
}, this);
}
}.bind(this));
this.allGeometries = (_ref5 = []).concat.apply(_ref5, this.allLayersGeometries);
this._mousemoveLayer.bringToFront();
} else if (layer instanceof maptalks.VectorLayer) {
var geometries = layer.getGeometries();
this.snaplayer = layer;
this.allGeometries = this._compositGeometries(geometries);
layer.on('addgeo', function () {
var geometries = this.snaplayer.getGeometries();
this.allGeometries = this._compositGeometries(geometries);
}, this);
this.snaplayer.on('clear', function () {
this._clearGeometries();
}, this);
this._mousemoveLayer.bringToFront();
}
};
/**
* @param {drawTool||maptalks.DrawTool} drawing tool
* When interacting with a drawtool, you should bind the drawtool object to this snapto tool
*/
SnapTool.prototype.bindDrawTool = function bindDrawTool(drawTool) {
var _this2 = this;
if (drawTool instanceof maptalks.DrawTool) {
drawTool.on('drawstart', function (e) {
if (_this2.snapPoint) {
_this2._resetCoordinates(e.target._geometry, _this2.snapPoint);
_this2._resetClickPoint(e.target._clickCoords, _this2.snapPoint);
}
}, this);
drawTool.on('mousemove', function (e) {
if (_this2.snapPoint) {
var mode = e.target.getMode();
var map = e.target.getMap();
if (mode === 'circle' || mode === 'freeHandCircle') {
var radius = map.computeLength(e.target._geometry.getCenter(), _this2.snapPoint);
e.target._geometry.setRadius(radius);
} else if (mode === 'ellipse' || mode === 'freeHandEllipse') {
var center = e.target._geometry.getCenter();
var rx = map.computeLength(center, new maptalks.Coordinate({
x: _this2.snapPoint.x,
y: center.y
}));
var ry = map.computeLength(center, new maptalks.Coordinate({
x: center.x,
y: _this2.snapPoint.y
}));
e.target._geometry.setWidth(rx * 2);
e.target._geometry.setHeight(ry * 2);
} else if (mode === 'rectangle' || mode === 'freeHandRectangle') {
var containerPoint = map.coordToContainerPoint(new maptalks.Coordinate({
x: _this2.snapPoint.x,
y: _this2.snapPoint.y
}));
var firstClick = map.coordToContainerPoint(e.target._geometry.getFirstCoordinate());
var ring = [[firstClick.x, firstClick.y], [containerPoint.x, firstClick.y], [containerPoint.x, containerPoint.y], [firstClick.x, containerPoint.y]];
e.target._geometry.setCoordinates(ring.map(function (c) {
return map.containerPointToCoord(new maptalks.Point(c));
}));
} else {
_this2._resetCoordinates(e.target._geometry, _this2.snapPoint);
}
}
}, this);
drawTool.on('drawvertex', function (e) {
if (_this2.snapPoint) {
_this2._resetCoordinates(e.target._geometry, _this2.snapPoint);
_this2._resetClickPoint(e.target._clickCoords, _this2.snapPoint);
}
}, this);
drawTool.on('drawend', function (e) {
if (_this2.snapPoint) {
var mode = e.target.getMode();
var map = e.target.getMap();
var geometry = e.geometry;
if (mode === 'circle' || mode === 'freeHandCircle') {
var radius = map.computeLength(e.target._geometry.getCenter(), _this2.snapPoint);
geometry.setRadius(radius);
} else if (mode === 'ellipse' || mode === 'freeHandEllipse') {
var center = geometry.getCenter();
var rx = map.computeLength(center, new maptalks.Coordinate({
x: _this2.snapPoint.x,
y: center.y
}));
var ry = map.computeLength(center, new maptalks.Coordinate({
x: center.x,
y: _this2.snapPoint.y
}));
geometry.setWidth(rx * 2);
geometry.setHeight(ry * 2);
} else if (mode === 'rectangle' || mode === 'freeHandRectangle') {
var containerPoint = map.coordToContainerPoint(new maptalks.Coordinate({
x: _this2.snapPoint.x,
y: _this2.snapPoint.y
}));
var firstClick = map.coordToContainerPoint(geometry.getFirstCoordinate());
var ring = [[firstClick.x, firstClick.y], [containerPoint.x, firstClick.y], [containerPoint.x, containerPoint.y], [firstClick.x, containerPoint.y]];
geometry.setCoordinates(ring.map(function (c) {
return map.containerPointToCoord(new maptalks.Point(c));
}));
} else {
_this2._resetCoordinates(geometry, _this2.snapPoint);
}
}
}, this);
}
};
SnapTool.prototype._resetCoordinates = function _resetCoordinates(geometry, snapPoint) {
if (!geometry) return geometry;
var coords = geometry.getCoordinates();
if (geometry instanceof maptalks.Polygon) {
if (geometry instanceof maptalks.Circle) {
return geometry;
}
var coordinates = coords[0];
if (coordinates instanceof Array && coordinates.length > 2) {
coordinates[coordinates.length - 2].x = snapPoint.x;
coordinates[coordinates.length - 2].y = snapPoint.y;
}
} else if (coords instanceof Array) {
coords[coords.length - 1].x = snapPoint.x;
coords[coords.length - 1].y = snapPoint.y;
} else if (coords instanceof maptalks.Coordinate) {
coords.x = snapPoint.x;
coords.y = snapPoint.y;
}
geometry.setCoordinates(coords);
return geometry;
};
SnapTool.prototype._resetClickPoint = function _resetClickPoint(clickCoords, snapPoint) {
if (!clickCoords) return;
clickCoords[clickCoords.length - 1].x = snapPoint.x;
clickCoords[clickCoords.length - 1].y = snapPoint.y;
};
SnapTool.prototype._addGeometries = function _addGeometries(geometries) {
geometries = geometries instanceof Array ? geometries : [geometries];
var addGeometries = this._compositGeometries(geometries);
this.allGeometries = this.allGeometries.concat(addGeometries);
};
SnapTool.prototype._clearGeometries = function _clearGeometries() {
this.addGeometries = [];
};
/**
* @param {Coordinate} mouse's coordinate on map
* Using a point to inspect the surrounding geometries
*/
SnapTool.prototype._prepareGeometries = function _prepareGeometries(coordinate) {
if (this.allGeometries) {
var allGeoInGeojson = this.allGeometries;
this.tree.clear();
this.tree.load({
'type': 'FeatureCollection',
'features': allGeoInGeojson
});
this.inspectExtent = this._createInspectExtent(coordinate);
var availGeometries = this.tree.search(this.inspectExtent);
return availGeometries;
}
return null;
};
SnapTool.prototype._compositGeometries = function _compositGeometries(geometries) {
var geos = [];
var mode = this.getMode();
if (mode === 'point') {
geos = this._compositToPoints(geometries);
} else if (mode === 'line') {
geos = this._compositToLines(geometries);
}
return geos;
};
SnapTool.prototype._compositToPoints = function _compositToPoints(geometries) {
var geos = [];
geometries.forEach(function (geo) {
geos = geos.concat(this._parserToPoints(geo));
}.bind(this));
return geos;
};
SnapTool.prototype._createMarkers = function _createMarkers(coords) {
var markers = [];
coords.forEach(function (coord) {
if (coord instanceof Array) {
coord.forEach(function (_coord) {
var _geo = new maptalks.Marker(_coord, {
properties: {}
});
_geo = _geo.toGeoJSON();
markers.push(_geo);
});
} else {
var _geo = new maptalks.Marker(coord, {
properties: {}
});
_geo = _geo.toGeoJSON();
markers.push(_geo);
}
});
return markers;
};
SnapTool.prototype._parserToPoints = function _parserToPoints(geo) {
var type = geo.getType();
var coordinates = null;
if (type === 'Circle' || type === 'Ellipse') {
coordinates = geo.getShell();
} else coordinates = geo.getCoordinates();
var geos = [];
//two cases,one is single geometry,and another is multi geometries
if (coordinates[0] instanceof Array) {
coordinates.forEach(function (coords) {
var _markers = this._createMarkers(coords);
geos = geos.concat(_markers);
}.bind(this));
} else {
if (!(coordinates instanceof Array)) {
coordinates = [coordinates];
}
var _markers = this._createMarkers(coordinates);
geos = geos.concat(_markers);
}
return geos;
};
SnapTool.prototype._compositToLines = function _compositToLines(geometries) {
var geos = [];
geometries.forEach(function (geo) {
switch (geo.getType()) {
case 'Point':
{
var _geo = geo.toGeoJSON();
_geo.properties = {};
geos.push(_geo);
}
break;
case 'LineString':
case 'Polygon':
geos = geos.concat(this._parserGeometries(geo, 1));
break;
default:
break;
}
}.bind(this));
return geos;
};
SnapTool.prototype._parserGeometries = function _parserGeometries(geo, _len) {
var coordinates = geo.getCoordinates();
var geos = [];
//two cases,one is single geometry,and another is multi geometries
if (coordinates[0] instanceof Array) {
coordinates.forEach(function (coords) {
var _lines = this._createLine(coords, _len, geo);
geos = geos.concat(_lines);
}.bind(this));
} else {
var _lines = this._createLine(coordinates, _len, geo);
geos = geos.concat(_lines);
}
return geos;
};
SnapTool.prototype._createLine = function _createLine(coordinates, _length, geo) {
var lines = [];
var len = coordinates.length - _length;
for (var i = 0; i < len; i++) {
var line = new maptalks.LineString([coordinates[i], coordinates[i + 1]], {
properties: {
obj: geo
}
});
lines.push(line.toGeoJSON());
}
return lines;
};
SnapTool.prototype._createInspectExtent = function _createInspectExtent(coordinate) {
var tolerance = !this.options['tolerance'] ? 10 : this.options['tolerance'];
var map = this.getMap();
var zoom = map.getZoom();
var screenPoint = map.coordinateToPoint(coordinate, zoom);
var lefttop = map.pointToCoordinate(new maptalks.Point([screenPoint.x - tolerance, screenPoint.y - tolerance]), zoom);
var righttop = map.pointToCoordinate(new maptalks.Point([screenPoint.x + tolerance, screenPoint.y - tolerance]), zoom);
var leftbottom = map.pointToCoordinate(new maptalks.Point([screenPoint.x - tolerance, screenPoint.y + tolerance]), zoom);
var rightbottom = map.pointToCoordinate(new maptalks.Point([screenPoint.x + tolerance, screenPoint.y + tolerance]), zoom);
return {
'type': 'Feature',
'properties': {},
'geometry': {
'type': 'Polygon',
'coordinates': [[[lefttop.x, lefttop.y], [righttop.x, righttop.y], [rightbottom.x, rightbottom.y], [leftbottom.x, leftbottom.y]]]
}
};
};
/**
* @param {Map}
* Register mousemove event
*/
SnapTool.prototype._registerEvents = function _registerEvents(map) {
this._needFindGeometry = true;
this._mousemove = function (e) {
this.mousePoint = e.coordinate;
if (!this._marker) {
this._marker = new maptalks.Marker(e.coordinate, {
'symbol': this.options['symbol']
}).addTo(this._mousemoveLayer);
} else {
this._marker.setCoordinates(e.coordinate);
}
//indicate find geometry
if (!this._needFindGeometry) return;
var availGeometries = this._findGeometry(e.coordinate);
if (availGeometries.features.length > 0) {
this.snapPoint = this._getSnapPoint(availGeometries);
if (this.snapPoint) {
this._marker.setCoordinates([this.snapPoint.x, this.snapPoint.y]);
}
} else {
this.snapPoint = null;
}
};
this._mousedown = function () {
this._needFindGeometry = false;
};
this._mouseup = function () {
this._needFindGeometry = true;
};
map.on('mousemove touchstart', this._mousemove, this);
map.on('mousedown', this._mousedown, this);
map.on('mouseup', this._mouseup, this);
};
/**
* @param {Array<geometry>} available geometries which are surrounded
* Calculate the distance from mouse point to every geometry
*/
SnapTool.prototype._setDistance = function _setDistance(geos) {
var geoObjects = [];
for (var i = 0; i < geos.length; i++) {
var geo = geos[i];
if (geo.geometry.type === 'LineString') {
var distance = this._distToPolyline(this.mousePoint, geo);
//geo.properties.distance = distance;
geoObjects.push({
geoObject: geo,
distance: distance
});
} else if (geo.geometry.type === 'Point') {
var _distance = this._distToPoint(this.mousePoint, geo);
//Composite an object including geometry and distance
geoObjects.push({
geoObject: geo,
distance: _distance
});
}
}
return geoObjects;
};
SnapTool.prototype._findNearestGeometries = function _findNearestGeometries(geos) {
var geoObjects = this._setDistance(geos);
geoObjects = geoObjects.sort(this._compare(geoObjects, 'distance'));
return geoObjects[0];
};
SnapTool.prototype._findGeometry = function _findGeometry(coordinate) {
var availGeimetries = this._prepareGeometries(coordinate);
return availGeimetries;
};
SnapTool.prototype._getSnapPoint = function _getSnapPoint(availGeometries) {
var _nearestGeometry = this._findNearestGeometries(availGeometries.features);
var snapPoint = null;
if (!this._validDistance(_nearestGeometry.distance)) {
return null;
}
//when it's point, return itself
if (_nearestGeometry.geoObject.geometry.type === 'Point') {
snapPoint = {
x: _nearestGeometry.geoObject.geometry.coordinates[0],
y: _nearestGeometry.geoObject.geometry.coordinates[1]
};
} else if (_nearestGeometry.geoObject.geometry.type === 'LineString') {
//when it's line,return the vertical insect point
var nearestLine = this._setEquation(_nearestGeometry.geoObject);
//whether k exists
if (nearestLine.A === 0) {
snapPoint = {
x: this.mousePoint.x,
y: _nearestGeometry.geoObject.geometry.coordinates[0][1]
};
} else if (nearestLine.A === Infinity) {
snapPoint = {
x: _nearestGeometry.geoObject.geometry.coordinates[0][0],
y: this.mousePoint.y
};
} else {
var k = nearestLine.B / nearestLine.A;
var verticalLine = this._setVertiEquation(k, this.mousePoint);
snapPoint = this._solveEquation(nearestLine, verticalLine);
}
}
return snapPoint;
};
//Calculate the distance from a point to a line
SnapTool.prototype._distToPolyline = function _distToPolyline(point, line) {
var equation = this._setEquation(line);
var A = equation.A;
var B = equation.B;
var C = equation.C;
var distance = Math.abs((A * point.x + B * point.y + C) / Math.sqrt(Math.pow(A, 2) + Math.pow(B, 2)));
return distance;
};
SnapTool.prototype._validDistance = function _validDistance(distance) {
var map = this.getMap();
var resolution = map.getResolution();
var tolerance = this.options['tolerance'];
if (distance / resolution > tolerance) {
return false;
} else {
return true;
}
};
SnapTool.prototype._distToPoint = function _distToPoint(mousePoint, toPoint) {
var from = [mousePoint.x, mousePoint.y];
var to = toPoint.geometry.coordinates;
return Math.sqrt(Math.pow(from[0] - to[0], 2) + Math.pow(from[1] - to[1], 2));
};
//create a line's equation
SnapTool.prototype._setEquation = function _setEquation(line) {
var coords = line.geometry.coordinates;
var from = coords[0];
var to = coords[1];
var k = Number((from[1] - to[1]) / (from[0] - to[0]).toString());
var A = k;
var B = -1;
var C = from[1] - k * from[0];
return {
A: A,
B: B,
C: C
};
};
SnapTool.prototype._setVertiEquation = function _setVertiEquation(k, point) {
var b = point.y - k * point.x;
var A = k;
var B = -1;
var C = b;
return {
A: A,
B: B,
C: C
};
};
SnapTool.prototype._solveEquation = function _solveEquation(equationW, equationU) {
var A1 = equationW.A,
B1 = equationW.B,
C1 = equationW.C;
var A2 = equationU.A,
B2 = equationU.B,
C2 = equationU.C;
var x = (B1 * C2 - C1 * B2) / (A1 * B2 - A2 * B1);
var y = (A1 * C2 - A2 * C1) / (B1 * A2 - B2 * A1);
return {
x: x,
y: y
};
};
SnapTool.prototype._compare = function _compare(data, propertyName) {
return function (object1, object2) {
var value1 = object1[propertyName];
var value2 = object2[propertyName];
if (value2 < value1) {
return 1;
} else if (value2 > value1) {
return -1;
} else {
return 0;
}
};
};
return SnapTool;
}(maptalks.Class);
SnapTool.mergeOptions(options);
exports.SnapTool = SnapTool;
Object.defineProperty(exports, '__esModule', { value: true });
typeof console !== 'undefined' && console.log('maptalks.snapto v0.1.11, requires maptalks@^0.33.1.');
})));
| liubgithub/maptalks.snapto | dist/maptalks.snapto.js | JavaScript | mit | 96,163 |
const webpack = require("webpack");
const path = require("path");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const AssetsPlugin = require("assets-webpack-plugin");
module.exports = {
entry: {
main: path.join(__dirname, "src", "index.js")
},
output: {
path: path.join(__dirname, "dist")
},
module: {
rules: [
{
test: /\.((png)|(eot)|(woff)|(woff2)|(ttf)|(svg)|(gif))(\?v=\d+\.\d+\.\d+)?$/,
loader: "file-loader?name=/[hash].[ext]"
},
{test: /\.json$/, loader: "json-loader"},
{
loader: "babel-loader",
test: /\.js?$/,
exclude: /node_modules/,
query: {cacheDirectory: true}
},
{
test: /\.(sa|sc|c)ss$/,
exclude: /node_modules/,
use: ["style-loader", MiniCssExtractPlugin.loader, "css-loader", "postcss-loader", "sass-loader"]
}
]
},
plugins: [
new webpack.ProvidePlugin({
fetch: "imports-loader?this=>global!exports-loader?global.fetch!whatwg-fetch"
}),
new AssetsPlugin({
filename: "webpack.json",
path: path.join(process.cwd(), "site/data"),
prettyPrint: true
}),
// new CopyWebpackPlugin([
// {
// from: "./src/fonts/",
// to: "fonts/",
// flatten: true
// }
// ])
]
};
| codemeyer/ArgData | Docs/webpack.common.js | JavaScript | mit | 1,390 |
window.onload=function() {
var start = document.getElementById('start');
start.onclick = function () {
var name = document.getElementById('Name').value;
var id = document.getElementById('Id').value;
var tel = document.getElementById("Tel").value;
if (name == "") {
alert("请输入名字");
return false;
}
if (!isName(name)) {
alert("请输入正确的姓名")
return false;
}
if (id =="") {
alert("请输入学号");
return false;
}
if (!isId(id)) {
alert("请输入正确学号");
return false;
}
if (tel == "") {
alert("请输入电话号码");
return false;
}
if (!isTelephone(tel)) {
alert("请输入正确的手机号码");
return false;
}
else {
start.submit();
// document.getElementById("myform").submit();
// window.open("answer.html","_self");
}
}
function isName(obj) {
var nameReg = /[\u4E00-\u9FA5]+$/;
return nameReg.test(obj);
}
function isId(obj) {
var emailReg = /^2017\d{8}$/;
return emailReg.test(obj);
}
function isTelephone(obj) {
reg = /^1[34578]\d{9}$/;
return reg.test(obj);
}
} | StaticWalk/exam | src/main/resources/static/js/login.js | JavaScript | mit | 1,412 |
(function (){
"use strict";
(function() {
var $bordered = $('.bordered');
window.setInterval(function() {
var top = window.pageYOffset || document.documentElement.scrollTop;
if(top > 0) {
$bordered.fadeOut('fast');
} else if(top == 0 && !$bordered.is(':visible')) {
$bordered.fadeIn("fast");
}
}, 200);
})();
$(function() {
$('.scroll').click(function(e) {
e.preventDefault();
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top
}, 1000);
return false;
}
}
});
});
(function () {
var $hash = $(location.hash);
if ($hash.hasClass('modal')) {
$hash.modal('show');
}
})();
//
// carousels intervals and disabled the keyboard support
//
$(document).ready(function(){
$('#backgroundCarousel').carousel({
interval: 10000000, // TODO just one slide for now
keyboard : false
});
$('#partnersCarousel').carousel({
interval: 4000,
keyboard : false
});
});
})();
(function(){
"use strict";
//
// toggle popups from pricing dialog to the partners dialog
//
var cennik = $("#cennik");
var ponuka = $("#ponuka");
function toggle(){
cennik.modal("toggle");
ponuka.modal("toggle");
}
$("#cennik button").on("click", toggle);
})();
(function(){
"use strict";
//
// deep linking for tracking google analytics
// requested by michael, should not be also standard deep linking
//
function setDeeplinking(event){
window.location.hash = $(event.target).data("target");
}
function clearDeeplinking(event){
window.location.hash = "";
}
$("nav .menu").on("click", setDeeplinking);
$("#try").on("click", setDeeplinking);
$('#cennik').on('hidden.bs.modal', clearDeeplinking);
$('#ponuka').on('hidden.bs.modal', clearDeeplinking);
$('#kontakt').on('hidden.bs.modal', clearDeeplinking);
})();
(function(){
"use strict";
//
// sending emails via the rest api
//
$("#form1").on("click", function(e){
e.preventDefault();
sendContent(
$("#formName1")[0].value,
$("#formEmail1")[0].value,
$("#formNote1")[0].value,
$($("#events1")[0]).prop('checked'),
function(){
$("#formName1").css("display", "none");
$("#form1").css("display", "none");
$("#formEmail1").css("display", "none");
$("#formNote1").css("display", "none");
$("#events1").css("display", "none");
$(".events-align label").css("display", "none");
$("#mobilethanks").css("display", "block");
}
);
});
$("#form2").on("click", function(e){
e.preventDefault();
sendContent(
$("#formName2")[0].value,
$("#formEmail2")[0].value,
$("#formNote2")[0].value,
$($("#events2")[0]).prop('checked'),
function emptyCallback(){}
);
});
function sendContent(name, email, note, newsletter, callback){
var EMAIL_RECIPIENT = "[email protected]";
var NAME_RECIPIENT = "HalmiSpace";
var SND_EMAIL_RECIPIENT = "[email protected]";
var SND_NAME_RECIPIENT = "Lolovia";
if (!email){
email = ":( Uchádzač nespokytol žiadny email.";
}
if (!note){
note = ":( Uchádzač neposlal žiadnu poznámku.";
}
if (!name){
name = "Uchádzač";
}
console.log("newsletter", newsletter);
var wantsReceiveEmail = newsletter
? "Áno, mám záujem o newsletter."
: "Nemám záujem o newsletter.";
var toParam = {
"email": EMAIL_RECIPIENT,
"name": NAME_RECIPIENT,
"type": "to"
};
var message = "";
message += "Uchádzač: " + name + "<br/>";
message += "Email: " + email + "<br/>";
message += "Poznámka: " + note + "<br/>";
message += "Newsletter: " + wantsReceiveEmail + "<br/>";
var messageParam = {
"from_email": "[email protected]",
"to": [toParam, {
"email": SND_EMAIL_RECIPIENT,
"name": SND_NAME_RECIPIENT,
"type": "to"
}],
"headers": {
"Reply-To": email
},
"autotext": "true",
"subject": "Uchádzač o coworking: " + name,
"html": message
};
var opts = {
url: "https://mandrillapp.com/api/1.0/messages/send.json",
data: { "key": "9WZGkQuvFHBbuy-p8ZOPjQ", "message": messageParam },
type: "POST",
crossDomain: true,
success: function(msg){ console.info("success email message", msg[0]); },
error : function(){ alert("Vyskytla sa chyba, kontaktuj nas na [email protected]!") }
};
$.ajax(opts).done(function(){
$("#formName1")[0].value = "";
$("#formEmail1")[0].value = "";
$("#formNote1")[0].value = "";
$("#formName2")[0].value = "";
$("#formEmail2")[0].value = "";
$("#formNote2")[0].value = "";
$("#thanks").addClass("active");
callback();
});
}
})(); | martinmaricak/HalmiCaffe | assets/javascript.js | JavaScript | mit | 5,224 |
describe('$materialPopup service', function() {
beforeEach(module('material.services.popup', 'ngAnimateMock'));
function setup(options) {
var popup;
inject(function($materialPopup, $rootScope) {
$materialPopup(options).then(function(p) {
popup = p;
});
$rootScope.$apply();
});
return popup;
}
describe('enter()', function() {
it('should append to options.appendTo', inject(function($animate, $rootScope) {
var parent = angular.element('<div id="parent">');
var popup = setup({
appendTo: parent,
template: '<div id="element"></div>'
});
popup.enter();
$rootScope.$digest();
expect($animate.queue.shift().event).toBe('enter');
expect(popup.element.parent()[0]).toBe(parent[0]); //fails
}));
it('should append to $rootElement by default', inject(function($rootScope, $document, $rootElement) {
var popup = setup({
template: '<div id="element"></div>'
});
popup.enter();
$rootScope.$digest();
expect(popup.element.parent()[0]).toBe($rootElement[0]);
}));
});
describe('destroy()', function() {
it('should leave and then destroy scope', inject(function($rootScope, $animate) {
var popup = setup({
template: '<div>'
});
popup.enter();
$rootScope.$apply();
var scope = popup.element.scope();
spyOn($animate, 'leave').andCallFake(function(element, cb) { cb(); });
spyOn(scope, '$destroy');
popup.destroy();
expect($animate.leave).toHaveBeenCalled();
expect(scope.$destroy).toHaveBeenCalled();
}));
});
});
| stackmates/common.client.build | src/common/style/sass/material/services/popup/popup.spec.js | JavaScript | mit | 1,657 |
/**
* Created by Samuel Schmid on 23.03.14.
*
* Class for Database Handling
*
* Containing
* - App Config
* - Database Information
*
* @type {Database}
*/
module.exports = Database;
Array.prototype.contains = function(obj) {
var i = this.length;
while (i--) {
if (this[i] === obj) {
return true;
}
}
return false;
}
String.prototype.replaceAll = function(target, replacement) {
return this.split(target).join(replacement);
};
function Database(grunt) {
this.grunt = grunt;
this.appconfig = grunt.config().appconfig;
this.db = this.appconfig.db;
}
/**
* delete Database Schemes of Docs
*
* @param docs
*/
Database.prototype.deleteSchemes = function(docs) {
var grunt = this.grunt;
grunt.log.debug("start ");
if(docs.docs.length > 0) {
var firstDoc = docs.docs[0];
var rootfolder = firstDoc.schemefolder.split("/")[0];
grunt.log.debug("Database: delete files in folder:" + rootfolder);
grunt.file.delete(rootfolder);
} else {
grunt.log.debug("Empty");
return;
}
}
/**
* create Database Schemes for Docs
*
* @param docs
*/
Database.prototype.createSchemes = function(docs) {
var grunt = this.grunt;
if(this.db.name === "mongodb") {
if(this.db.provider === "mongoose") {
grunt.log.write("start writing schemes for database " + this.db.name + " and provider "+this.db.provider + ".");
var Provider = require('./providers/mongoose/mongoose-provider.js');
var provider = new Provider(grunt);
for(var i=0;i<docs.docs.length;i++) {
var doc = docs.docs[i];
if(doc.json.type.endsWith('.abstract')) {
provider.writeAbstractScheme(doc);
}
}
for(var i=0;i<docs.docs.length;i++) {
var doc = docs.docs[i];
if(!doc.json.type.endsWith('.apidescription') && !doc.json.type.endsWith('.abstract')) {
provider.writeScheme(doc);
}
}
provider.writeLib();
} else {
grunt.log.write("cannot create schemes for database " + this.db.name + ", because there we can't use the provider "+this.db.provider+" for it.");
}
} else {
grunt.log.write("cannot create schemes for database " + this.db.name + ", because there is no provider for it.");
}
}
| veith/restapiexpress | grunt/database/database.js | JavaScript | mit | 2,478 |
Test.expect(reverseWords('The quick brown fox jumps over the lazy dog.') === 'ehT kciuq nworb xof spmuj revo eht yzal .god');
Test.expect(reverseWords('apple') === 'elppa');
Test.expect(reverseWords('a b c d') === 'a b c d');
Test.expect(reverseWords('double spaced words') === 'elbuod decaps sdrow'); | bakula/codewars_js | completed Kata/6kyu and below/045_Reverse words/specs.js | JavaScript | mit | 305 |
'use strict';
import { gl } from './Context';
import { mat4 } from 'gl-matrix';
import Camera from './Camera';
class OrthographicCamera extends Camera
{
constructor(
{
path,
uniforms,
background,
translucence,
right,
top,
name = 'orthographic.camera',
left = -1,
bottom = -1,
near = 0.1,
far = 1
} = {})
{
super({ name, path, uniforms, background, translucence });
this.left = left;
this.right = right;
this.bottom = bottom;
this.top = top;
this.near = near;
this.far = far;
this.inheritance = ['Entity', 'Structure', 'Camera', 'OrthographicCamera'];
this.configure();
}
get left()
{
return this._left;
}
set left(left)
{
this._left = left;
}
get right()
{
return this._right;
}
set right(right)
{
this._right = right;
}
get bottom()
{
return this._bottom;
}
set bottom(bottom)
{
this._bottom = bottom;
}
get top()
{
return this._top;
}
set top(top)
{
this._top = top;
}
get near()
{
return this._near;
}
set near(near)
{
this._near = near;
}
get far()
{
return this._far;
}
set far(far)
{
this._far = far;
}
configure()
{
super.configure();
mat4.ortho(this.projectionMatrix, this.left, this.right, this.bottom, this.top, this.near, this.far);
mat4.identity(this.modelViewMatrix);
}
bind(program)
{
super.bind(program);
gl.disable(gl.DEPTH_TEST);
gl.viewport(0, 0, this.right, this.top);
}
}
export default OrthographicCamera;
| allotrop3/four | src/OrthographicCamera.js | JavaScript | mit | 1,846 |
// Karma configuration
// Generated on Wed Feb 17 2016 10:45:47 GMT+0100 (CET)
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: './',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['systemjs', 'jasmine'],
// list of files / patterns to load in the browser
files: [
'app/**/*spec.js'
],
systemjs: {
// Point out where the SystemJS config file is
configFile: 'app/systemjs.config.js',
serveFiles: [
'app/**/*.js'
]
},
plugins: [
'karma-systemjs',
'karma-chrome-launcher',
'karma-firefox-launcher',
'karma-phantomjs-launcher',
'karma-jasmine',
'karma-junit-reporter',
'karma-coverage'
],
// list of files to exclude
exclude: [],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'app/**/!(*spec).js': ['coverage']
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress', 'coverage'],
coverageReporter: {
reporters:[
{type: 'lcov', subdir: 'report-lcov'},
{type: 'json', subdir: 'report-json', file: 'coverage-final.json'},
]
},
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['PhantomJS'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: true,
// Concurrency level
// how many browser should be started simultaneous
concurrency: Infinity
})
}
| bourdeau/jdhm-bo | karma.conf.js | JavaScript | mit | 2,590 |
'use strict'
// create a net-peer compatible object based on a UDP datagram socket
module.exports = function udpAdapter(udpSocket, udpDestinationHost, udpDestinationPort) {
const _listeners = []
udpSocket.on('message', (msg, rinfo) => {
//console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`)
for(let i=0; i < _listeners.length; i++) {
_listeners[i](msg)
}
})
let on = function(event, fn) {
if (event === 'data') {
_listeners.push(fn)
}
}
let send = function(message) {
udpSocket.send(Buffer.from(message.buffer), udpDestinationPort, udpDestinationHost, (err) => { })
}
return Object.freeze({ on, send })
}
| mreinstein/net-peer | examples/udp/udp-adapter.js | JavaScript | mit | 680 |
var Filter = require('broccoli-filter')
module.exports = WrapFilter;
WrapFilter.prototype = Object.create(Filter.prototype);
WrapFilter.prototype.constructor = WrapFilter;
function WrapFilter (inputTree, options) {
if (!(this instanceof WrapFilter)) return new WrapFilter(inputTree, options)
Filter.call(this, inputTree, options)
this.options = options || {};
this.options.extensions = this.options.extensions || ['js'];
this.extensions = this.options.extensions;
}
WrapFilter.prototype.processString = function (string) {
var wrapper = this.options.wrapper;
if ( !(wrapper instanceof Array) ) {
return string;
}
var startWith = wrapper[0] || '';
var endWith = wrapper[1] || '';
return [startWith, string, endWith].join('')
}
| H1D/broccoli-wrap | index.js | JavaScript | mit | 757 |
Template.formeditprofile.events({
'submit #editform': function(event){
event.preventDefault();
var firstNameVar = event.target.firstname.value;
var lastNameVar = event.target.lastname.value;
var classVar = event.target.classvar.value;
Profiles.insert({
uid:Meteor.userId(),
firstname: firstNameVar,
lastname: lastNameVar,
classvar: classVar
});
alert("Done!");
}
});
Template.addprofile.rendered = function(){
this.$('.ui.dropdown').dropdown();
} | zhjch05/MemoryChess | semantic-ui/client/pages/addprofile.js | JavaScript | mit | 477 |
var expect = require('expect.js');
var EventEmitter = require('events').EventEmitter;
var fixtures = require('../fixtures');
var Detector = require('../../lib/detector.js');
describe('Detector', function() {
// Used to test emitted events
var found;
var listener = function(magicNumber) {
found.push(magicNumber);
};
beforeEach(function() {
found = [];
});
describe('constructor', function() {
it('inherits from EventEmitter', function() {
expect(new Detector()).to.be.an(EventEmitter);
});
it('accepts an array of file paths', function() {
var filePaths = ['path1.js', 'path2.js'];
var detector = new Detector(filePaths);
expect(detector._filePaths).to.be(filePaths);
});
it('accepts a boolean to enforce the use of const', function() {
var detector = new Detector([], {
enforceConst: true
});
expect(detector._enforceConst).to.be(true);
});
it('accepts an array of numbers to ignore', function() {
var ignore = [1, 2, 3.4];
var detector = new Detector([], {
ignore: ignore
});
expect(detector._ignore).to.be(ignore);
});
});
describe('run', function() {
it('is compatible with callbacks', function(done) {
var detector = new Detector([fixtures.emptyFile]);
detector.run(function(err) {
done(err);
});
});
it('is compatible with promises', function(done) {
var detector = new Detector([fixtures.emptyFile]);
detector.run().then(function() {
done();
}).catch(done);
});
it('returns an Error if not given an array of file paths', function(done) {
var detector = new Detector();
detector.run().catch(function(err) {
expect(err).to.be.an(Error);
expect(err.message).to.be('filePaths must be a non-empty array of paths');
done();
});
});
});
it('emits end on completion, passing the number of files parsed', function(done) {
var detector = new Detector([fixtures.emptyFile, fixtures.singleVariable]);
detector.on('end', function(numFiles) {
expect(numFiles).to.be(2);
done();
});
detector.run().catch(done);
});
it('emits no events when parsing an empty file', function(done) {
var detector = new Detector([fixtures.emptyFile]);
detector.on('found', listener);
detector.run().then(function() {
expect(found).to.be.empty();
done();
}).catch(done);
});
it('emits no events when the file contains only named constants', function(done) {
var detector = new Detector([fixtures.singleVariable]);
detector.on('found', listener);
detector.run().then(function() {
expect(found).to.be.empty();
done();
}).catch(done);
});
it('emits no events for literals assigned to object properties', function(done) {
var detector = new Detector([fixtures.objectProperties]);
detector.on('found', listener);
detector.run().then(function() {
expect(found).to.have.length(2);
expect(found[0].value).to.be('4');
expect(found[1].value).to.be('5');
done();
}).catch(done);
});
it('emits no events for literals used in AssignmentExpressions', function(done) {
var detector = new Detector([fixtures.assignmentExpressions]);
detector.on('found', listener);
detector.run().then(function() {
expect(found).to.have.length(0);
done();
}).catch(done);
});
it('emits no events for numbers marked by ignore:line', function(done) {
var detector = new Detector([fixtures.lineIgnore]);
detector.on('found', listener);
detector.run().then(function() {
expect(found).to.be.empty();
done();
}).catch(done);
});
it('emits no events between ignore:start / ignore:end', function(done) {
var detector = new Detector([fixtures.blockIgnore]);
detector.on('found', listener);
detector.run().then(function() {
expect(found).to.be.empty();
done();
}).catch(done);
});
it('emits a "found" event containing a magic number, when found', function(done) {
var detector = new Detector([fixtures.secondsInMinute]);
detector.on('found', listener);
detector.run().then(function() {
expect(found).to.have.length(1);
expect(found[0].value).to.be('60');
expect(found[0].file.substr(-18)).to.be('secondsInMinute.js');
expect(found[0].startColumn).to.be(9);
expect(found[0].endColumn).to.be(11);
expect(found[0].fileLength).to.be(4);
expect(found[0].lineNumber).to.be(2);
expect(found[0].lineSource).to.be(' return 60;');
expect(found[0].contextLines).to.eql([
'function getSecondsInMinute() {', ' return 60;', '}'
]);
expect(found[0].contextIndex).to.eql(1);
done();
}).catch(done);
});
it('correctly emits hex and octal values', function(done) {
var detector = new Detector([fixtures.hexOctal]);
detector.on('found', listener);
detector.run().then(function() {
expect(found).to.have.length(3);
expect(found[0].value).to.be('0x1A');
expect(found[1].value).to.be('0x02');
expect(found[2].value).to.be('071');
done();
}).catch(done);
});
it('skips unnamed constants within the ignore list', function(done) {
var detector = new Detector([fixtures.ignore], {
ignore: [0]
});
detector.on('found', listener);
detector.run().then(function() {
expect(found).to.have.length(1);
expect(found[0].value).to.be('1');
done();
}).catch(done);
});
it('ignores the shebang at the start of a file', function(done) {
var detector = new Detector([fixtures.shebang]);
detector.on('found', listener);
detector.run().then(function() {
expect(found).to.have.length(1);
expect(found[0].lineNumber).to.be(4);
expect(found[0].value).to.be('100');
done();
}).catch(done);
});
describe('with detectObjects set to true', function() {
it('emits a "found" event for object literals', function(done) {
var detector = new Detector([fixtures.objectLiterals], {
detectObjects: true
});
detector.on('found', listener);
detector.run().then(function() {
expect(found).to.have.length(1);
expect(found[0].value).to.be('42');
done();
}).catch(done);
});
it('emits a "found" event for property assignments', function(done) {
var detector = new Detector([fixtures.objectProperties], {
detectObjects: true
});
detector.on('found', listener);
detector.run().then(function() {
expect(found).to.have.length(4);
expect(found[0].value).to.be('2');
expect(found[1].value).to.be('3');
expect(found[2].value).to.be('4');
expect(found[3].value).to.be('5');
done();
}).catch(done);
});
});
describe('with enforceConst set to true', function() {
it('emits a "found" event for variable declarations', function(done) {
var detector = new Detector([fixtures.constVariable], {
enforceConst: true
});
detector.on('found', listener);
detector.run().then(function() {
expect(found).to.have.length(1);
expect(found[0].value).to.be('10');
done();
}).catch(done);
});
it('emits a "found" event for object expressions', function(done) {
var detector = new Detector([fixtures.constObject], {
enforceConst: true
});
detector.on('found', listener);
detector.run().then(function() {
expect(found).to.have.length(1);
expect(found[0].value).to.be('10');
done();
}).catch(done);
});
});
});
| dushmis/buddy.js | spec/unit/detectorSpec.js | JavaScript | mit | 7,750 |
import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import './PostListView.scss';
import { toastr } from 'react-redux-toastr';
import { bindActionCreators } from 'redux';
import {
fetchPostsFromApi,
selectPostCategory,
clearPostsErrors,
clearPostsMessages
} from '../../../actions/actionCreators';
import CategoryFilterContainer from '../../CategoryFilterContainer/CategoryFilterContainer';
import {
PostList,
LoadingIndicator,
Divider,
MessagesSection
} from '../../../components';
import NoPostsFound from '../Misc/NoPostsFound';
// containsCategory :: Object -> Object -> Bool
const containsCategory = (post, category) => {
const categories = post.categories.filter(
(cat) => cat._id == category.id
);
return categories.length > 0;
};
// getFilteredPosts :: Object -> [Object] -> [Object]
const getFilteredPosts = (
category,
posts
) => {
if (category === null || category.name === 'All') {
return posts;
}
return posts.filter((post) => {
if (containsCategory(post, category)) {
return post;
}
return undefined;
});
};
/* Only used internally and it's so small so not worth creating a new component */
const SectionSubTitle = ({
title
}) => (
<h4 className="section-sub-title">
{title}
</h4>
);
SectionSubTitle.propTypes = {
title: PropTypes.string.isRequired
};
class PostListView extends React.Component {
constructor(props) {
super(props);
this.handleSelectCategory = this.handleSelectCategory.bind(this);
this.handleChangePage = this.handleChangePage.bind(this);
this.handleClose = this.handleClose.bind(this);
}
componentDidMount() {
const {
posts,
fetchPosts
} = this.props;
if (!posts.items || posts.items.length === 0) {
fetchPosts();
}
}
handleChangePage() {
//TODO: Implement me!!
}
handleSelectCategory(category) {
const {
selectPostCat
} = this.props;
selectPostCat(category);
}
showMessage(message) {
toastr.info(message);
}
handleClose(sender) {
const {
clearErrors,
clearMessages
} = this.props;
const theElement = sender.target.id;
if (theElement === 'button-close-error-panel') {
clearErrors();
} else if (theElement === 'button-close-messages-panel') {
clearMessages();
}
}
render() {
const {
posts,
isFetching,
postCategories,
selectedCategory,
errors,
messages
} = this.props;
const items = posts.items;
const visiblePosts = getFilteredPosts(selectedCategory, items);
return (
<LoadingIndicator isLoading={isFetching}>
<div className="post-list-view__wrapper">
<MessagesSection messages={messages} errors={errors} onClose={this.handleClose} />
<h1 className="section-header">From the Blog</h1>
<SectionSubTitle
title={selectedCategory.name == 'All' ? // eslint-disable-line
'All Posts'
:
`Selected Category: ${selectedCategory.name}`
}
/>
<Divider />
<CategoryFilterContainer
categories={postCategories}
onSelectCategory={this.handleSelectCategory}
selectedCategory={selectedCategory}
/>
{visiblePosts !== undefined && visiblePosts.length > 0 ?
<PostList
posts={visiblePosts}
onChangePage={this.handleChangePage}
/>
:
<NoPostsFound
selectedCategory={selectedCategory}
/>
}
</div>
</LoadingIndicator>
);
}
}
PostListView.propTypes = {
dispatch: PropTypes.func.isRequired,
errors: PropTypes.array.isRequired,
messages: PropTypes.array.isRequired,
posts: PropTypes.object.isRequired,
isFetching: PropTypes.bool.isRequired,
fetchPosts: PropTypes.func.isRequired,
selectPostCat: PropTypes.func.isRequired,
postCategories: PropTypes.array.isRequired,
selectedCategory: PropTypes.object.isRequired,
clearMessages: PropTypes.func.isRequired,
clearErrors: PropTypes.func.isRequired
};
// mapStateToProps :: {State} -> {Props}
const mapStateToProps = (state) => ({
posts: state.posts,
postCategories: state.posts.categories,
selectedCategory: state.posts.selectedCategory,
messages: state.messages.posts,
errors: state.errors.posts,
isFetching: state.posts.isFetching
});
// mapDispatchToProps :: {Dispatch} -> {Props}
const mapDispatchToProps = (dispatch) =>
bindActionCreators({
fetchPosts: () => fetchPostsFromApi(),
selectPostCat: (category) => selectPostCategory(category),
clearMessages: () => clearPostsMessages(),
clearErrors: () => clearPostsErrors()
}, dispatch);
export default connect(
mapStateToProps,
mapDispatchToProps
)(PostListView);
| RyanCCollins/ryancollins.io | app/src/containers/Blog/PostListView/PostListView.js | JavaScript | mit | 4,864 |
version https://git-lfs.github.com/spec/v1
oid sha256:4a4e80129485fe848fa53149568184f09fa2da8648b6476b750ef97344bd4c5b
size 10959
| yogeshsaroya/new-cdnjs | ajax/libs/jsSHA/1.6.0/sha512.js | JavaScript | mit | 130 |
/**
* Module dependencies.
*/
var util = require('sails-util'),
uuid = require('node-uuid'),
path = require('path'),
generateSecret = require('./generateSecret'),
cookie = require('express/node_modules/cookie'),
parseSignedCookie = require('cookie-parser').signedCookie,
ConnectSession = require('express/node_modules/connect').middleware.session.Session;
module.exports = function(sails) {
//////////////////////////////////////////////////////////////////////////////
// TODO:
//
// All of this craziness can be replaced by making the socket.io interpreter
// 100% connect-compatible (it's close!). Then, the connect cookie parser
// can be used directly with Sails' simulated req and res objects.
//
//////////////////////////////////////////////////////////////////////////////
/**
* Prototype for the connect session store wrapper used by the sockets hook.
* Includes a save() method to persist the session data.
*/
function SocketIOSession(options) {
var sid = options.sid,
data = options.data;
this.save = function(cb) {
if (!sid) {
sails.log.error('Trying to save session, but could not determine session ID.');
sails.log.error('This probably means a requesting socket did not send a cookie.');
sails.log.error('Usually, this happens when a socket from an old browser tab ' +
' tries to reconnect.');
sails.log.error('(this can also occur when trying to connect a cross-origin socket.)');
if (cb) cb('Could not save session.');
return;
}
// Merge data directly into instance to allow easy access on `req.session` later
util.defaults(this, data);
// Persist session
Session.set(sid, sails.util.cloneDeep(this), function(err) {
if (err) {
sails.log.error('Could not save session:');
sails.log.error(err);
}
if (cb) cb(err);
});
};
// Set the data on this object, since it will be used as req.session
util.extend(this, options.data);
}
// Session hook
var Session = {
defaults: {
session: {
adapter: 'memory',
key: "sails.sid"
}
},
/**
* Normalize and validate configuration for this hook.
* Then fold any modifications back into `sails.config`
*/
configure: function() {
// Validate config
// Ensure that secret is specified if a custom session store is used
if (sails.config.session) {
if (!util.isObject(sails.config.session)) {
throw new Error('Invalid custom session store configuration!\n' +
'\n' +
'Basic usage ::\n' +
'{ session: { adapter: "memory", secret: "someVerySecureString", /* ...if applicable: host, port, etc... */ } }' +
'\n\nCustom usage ::\n' +
'{ session: { store: { /* some custom connect session store instance */ }, secret: "someVerySecureString", /* ...custom settings.... */ } }'
);
}
}
// If session config is set, but secret is undefined, set a secure, one-time use secret
if (!sails.config.session || !sails.config.session.secret) {
sails.log.verbose('Session secret not defined-- automatically generating one for now...');
if (sails.config.environment === 'production') {
sails.log.warn('Session secret must be identified!');
sails.log.warn('Automatically generating one for now...');
sails.log.error('This generated session secret is NOT OK for production!');
sails.log.error('It will change each time the server starts and break multi-instance deployments.');
sails.log.blank();
sails.log.error('To set up a session secret, add or update it in `config/session.js`:');
sails.log.error('module.exports.session = { secret: "keyboardcat" }');
sails.log.blank();
}
sails.config.session.secret = generateSecret();
}
// Backwards-compatibility / shorthand notation
// (allow mongo or redis session stores to be specified directly)
if (sails.config.session.adapter === 'redis') {
sails.config.session.adapter = 'connect-redis';
}
else if (sails.config.session.adapter === 'mongo') {
sails.config.session.adapter = 'connect-mongo';
}
},
/**
* Create a connection to the configured session store
* and keep it around
*
* @api private
*/
initialize: function(cb) {
var sessionConfig = sails.config.session;
// Intepret session adapter config and "new up" a session store
if (util.isObject(sessionConfig) && !util.isObject(sessionConfig.store)) {
// Unless the session is explicitly disabled, require the appropriate adapter
if (sessionConfig.adapter) {
// 'memory' is a special case
if (sessionConfig.adapter === 'memory') {
var MemoryStore = require('express').session.MemoryStore;
sessionConfig.store = new MemoryStore();
}
// Try and load the specified adapter from the local sails project,
// or catch and return error:
else {
var COULD_NOT_REQUIRE_CONNECT_ADAPTER_ERR = function (adapter, packagejson, e) {
var errMsg;
if (e && typeof e === 'object' && e instanceof Error) {
errMsg = e.stack;
}
else {
errMsg = util.inspect(e);
}
var output = 'Could not load Connect session adapter :: ' + adapter + '\n';
if (packagejson && !packagejson.main) {
output+='(If this is your module, make sure that the module has a "main" configuration in its package.json file)';
}
output+='\nError from adapter:\n'+ errMsg+'\n\n';
// Recommend installation of the session adapter:
output += 'Do you have the Connect session adapter installed in this project?\n';
output += 'Try running the following command in your project\'s root directory:\n';
var installRecommendation = 'npm install ';
if (adapter === 'connect-redis') {
installRecommendation += '[email protected]';
installRecommendation += '\n(Note that `[email protected]` introduced breaking changes- make sure you have v1.4.5 installed!)';
}
else {
installRecommendation += adapter;
installRecommendation +='\n(Note: Make sure the version of the Connect adapter you install is compatible with Express 3/Sails v0.10)';
}
installRecommendation += '\n';
output += installRecommendation;
return output;
};
try {
// Determine the path to the adapter by using the "main" described in its package.json file:
var pathToAdapterDependency;
var pathToAdapterPackage = path.resolve(sails.config.appPath, 'node_modules', sessionConfig.adapter ,'package.json');
var adapterPackage;
try {
adapterPackage = require(pathToAdapterPackage);
pathToAdapterDependency = path.resolve(sails.config.appPath, 'node_modules', sessionConfig.adapter, adapterPackage.main);
}
catch (e) {
return cb(COULD_NOT_REQUIRE_CONNECT_ADAPTER_ERR(sessionConfig.adapter, adapterPackage, e));
}
var SessionAdapter = require(pathToAdapterDependency);
var CustomStore = SessionAdapter(require('express'));
sessionConfig.store = new CustomStore(sessionConfig);
} catch (e) {
// TODO: negotiate error
return cb(COULD_NOT_REQUIRE_CONNECT_ADAPTER_ERR(sessionConfig.adapter, adapterPackage, e));
}
}
}
}
// Save reference in `sails.session`
sails.session = Session;
return cb();
},
/**
* Create a new sid and build an empty session for it.
*
* @param {Object} handshake - a socket "handshake" -- basically, this is like `req`
* @param {Function} cb
* @returns live session, with `id` property === new sid
*/
generate: function(handshake, cb) {
// Generate a session object w/ sid
// This is important since we need this sort of object as the basis for the data
// we'll save directly into the session store.
// (handshake is a pretend `req` object, and 2nd argument is cookie config)
var session = new ConnectSession(handshake, {
cookie: {
// Prevent access from client-side javascript
httpOnly: true,
// Restrict to path
path: '/'
}
});
// Next, persist the new session
Session.set(session.id, session, function(err) {
if (err) return cb(err);
sails.log.verbose('Generated new session (', session.id, ') for socket....');
// Pass back final session object
return cb(null, session);
});
},
/**
* @param {String} sessionId
* @param {Function} cb
*
* @api private
*/
get: function(sessionId, cb) {
if (!util.isFunction(cb)) {
throw new Error('Invalid usage :: `Session.get(sessionId, cb)`');
}
return sails.config.session.store.get(sessionId, cb);
},
/**
* @param {String} sessionId
* @param {} data
* @param {Function} [cb] - optional
*
* @api private
*/
set: function(sessionId, data, cb) {
cb = util.optional(cb);
return sails.config.session.store.set(sessionId, data, cb);
},
/**
* Create a session transaction
*
* Load the Connect session data using the sessionID in the socket.io handshake object
* Mix-in the session.save() method for persisting the data back to the session store.
*
* Functionally equivalent to connect's sessionStore middleware.
*/
fromSocket: function(socket, cb) {
// If a socket makes it here, even though its associated session is not specified,
// it's authorized as far as the app is concerned, so no need to do that again.
// Instead, use the cookie to look up the sid, and then the sid to look up the session data
// If sid doesn't exit in socket, we have to do a little work first to get it
// (or generate a new one-- and therefore a new empty session as well)
if (!socket.handshake.sessionID && !socket.handshake.headers.cookie) {
// If no cookie exists, generate a random one (this will create a new session!)
var generatedCookie = sails.config.session.key + '=' + uuid.v1();
socket.handshake.headers.cookie = generatedCookie;
sails.log.verbose('Could not fetch session, since connecting socket (', socket.id, ') has no cookie.');
sails.log.verbose('Is this a cross-origin socket..?)');
sails.log.verbose('Generated a one-time-use cookie:', generatedCookie);
sails.log.verbose('This will result in an empty session, i.e. (req.session === {})');
// Convert cookie into `sid` using session secret
// Maintain sid in socket so that the session can be queried before processing each incoming message
socket.handshake.cookie = cookie.parse(generatedCookie);
// Parse and decrypt cookie and save it in the socket.handshake
socket.handshake.sessionID = parseSignedCookie(socket.handshake.cookie[sails.config.session.key], sails.config.session.secret);
// Generate and persist a new session in the store
Session.generate(socket.handshake, function(err, sessionData) {
if (err) return cb(err);
sails.log.silly('socket.handshake.sessionID is now :: ', socket.handshake.sessionID);
// Provide access to adapter-agnostic `.save()`
return cb(null, new SocketIOSession({
sid: sessionData.id,
data: sessionData
}));
});
return;
}
try {
// Convert cookie into `sid` using session secret
// Maintain sid in socket so that the session can be queried before processing each incoming message
socket.handshake.cookie = cookie.parse(socket.handshake.headers.cookie);
// Parse and decrypt cookie and save it in the socket.handshake
socket.handshake.sessionID = parseSignedCookie(socket.handshake.cookie[sails.config.session.key], sails.config.session.secret);
} catch (e) {
sails.log.error('Could not load session for socket #' + socket.id);
sails.log.error('The socket\'s cookie could not be parsed into a sessionID.');
sails.log.error('Unless you\'re overriding the `authorization` function, make sure ' +
'you pass in a valid `' + sails.config.session.key + '` cookie');
sails.log.error('(or omit the cookie altogether to have a new session created and an ' +
'encrypted cookie sent in the response header to your socket.io upgrade request)');
return cb(e);
}
// If sid DOES exist, it's easy to look up in the socket
var sid = socket.handshake.sessionID;
// Cache the handshake in case it gets wiped out during the call to Session.get
var handshake = socket.handshake;
// Retrieve session data from store
Session.get(sid, function(err, sessionData) {
if (err) {
sails.log.error('Error retrieving session from socket.');
return cb(err);
}
// sid is not known-- the session secret probably changed
// Or maybe server restarted and it was:
// (a) using an auto-generated secret, or
// (b) using the session memory store
// and so it doesn't recognize the socket's session ID.
else if (!sessionData) {
sails.log.verbose('A socket (' + socket.id + ') is trying to connect with an invalid or expired session ID (' + sid + ').');
sails.log.verbose('Regnerating empty session...');
Session.generate(handshake, function(err, sessionData) {
if (err) return cb(err);
// Provide access to adapter-agnostic `.save()`
return cb(null, new SocketIOSession({
sid: sessionData.id,
data: sessionData
}));
});
}
// Otherwise session exists and everything is ok.
// Instantiate SocketIOSession (provides .save() method)
// And extend it with session data
else return cb(null, new SocketIOSession({
data: sessionData,
sid: sid
}));
});
}
};
return Session;
};
| mnaughto/sails | lib/hooks/session/index.js | JavaScript | mit | 14,850 |
function showErrorMessage(errorMessage) {
$("#authorize-prompt")
.addClass("error-prompt")
.removeClass("success-prompt")
.html(errorMessage);
}
function showSuccessMessage(message) {
$("#authorize-prompt")
.removeClass("error-prompt")
.addClass("success-prompt")
.html(message);
}
function shake() {
var l = 10;
var original = -150;
for( var i = 0; i < 8; i++ ) {
var computed;
if (i % 2 > 0.51) {
computed = original - l;
} else {
computed = original + l;
}
$("#login-box").animate({
"left": computed + "px"
}, 100);
}
$("#login-box").animate({
"left": "-150px"
}, 50);
}
function handleAuthSuccess(data) {
showSuccessMessage(data.message);
$("#login-button").prop("disabled", true);
setTimeout(function() {
location.href = data.redirectUri;
}, 1000);
}
function handleAuthFailure(data) {
showErrorMessage(data.responseJSON.message);
shake();
}
$(function () {
$('[data-toggle="tooltip"]').tooltip()
})
function handleGrantAuthorization() {
var csrf_token = $("#csrf_token").val();
var client_id = $("#client_id").val();
$.ajax("/oauth/authorize", {
"method": "POST",
"data": {
client_id,
csrf_token
},
"success": handleAuthSuccess,
"error": handleAuthFailure
});
} | AndrewMontagne/alliance-auth | static/js/authorize.js | JavaScript | mit | 1,462 |
module.exports = [
'M6 2 L26 2 L26 30',
'L16 24 L6 30 Z'
].join(' ');
| zaccolley/songkick.pink | src/components/Icon/svg/bookmark.js | JavaScript | mit | 75 |
// DATA_TEMPLATE: empty_table
oTest.fnStart("5396 - fnUpdate with 2D arrays for a single row");
$(document).ready(function () {
$('#example thead tr').append('<th>6</th>');
$('#example thead tr').append('<th>7</th>');
$('#example thead tr').append('<th>8</th>');
$('#example thead tr').append('<th>9</th>');
$('#example thead tr').append('<th>10</th>');
var aDataSet = [
[
"1",
"홍길동",
"1154315",
"etc1",
[
[ "[email protected]", "2011-03-04" ],
[ "[email protected]", "2009-07-06" ],
[ "[email protected]", ",hide" ],
[ "[email protected]", "" ]
],
"2011-03-04",
"show"
],
[
"2",
"홍길순",
"2154315",
"etc2",
[
[ "[email protected]", "2009-09-26" ],
[ "[email protected]", "2009-05-21,hide" ],
[ "[email protected]", "2010-03-05" ],
[ "[email protected]", ",hide" ],
[ "[email protected]", "2010-03-05" ]
],
"2010-03-05",
"show"
]
]
var oTable = $('#example').dataTable({
"aaData": aDataSet,
"aoColumns": [
{ "mData": "0"},
{ "mData": "1"},
{ "mData": "2"},
{ "mData": "3"},
{ "mData": "4.0.0"},
{ "mData": "4.0.1"},
{ "mData": "4.1.0"},
{ "mData": "4.1.1"},
{ "mData": "5"},
{ "mData": "6"}
]
});
oTest.fnTest(
"Initialisation",
null,
function () {
return $('#example tbody tr:eq(0) td:eq(0)').html() == '1';
}
);
oTest.fnTest(
"Update row",
function () {
$('#example').dataTable().fnUpdate([
"0",
"홍길순",
"2154315",
"etc2",
[
[ "[email protected]", "2009-09-26" ],
[ "[email protected]", "2009-05-21,hide" ],
[ "[email protected]", "2010-03-05" ],
[ "[email protected]", ",hide" ],
[ "[email protected]", "2010-03-05" ]
],
"2010-03-05",
"show"
], 1);
},
function () {
return $('#example tbody tr:eq(0) td:eq(0)').html() == '0';
}
);
oTest.fnTest(
"Original row preserved",
null,
function () {
return $('#example tbody tr:eq(1) td:eq(0)').html() == '1';
}
);
oTest.fnComplete();
}); | hedi103/projet-decision-commerciale | src/Project/Bundle/AceThemeBundle/Resources/public/css/themes/default/assets/advanced-datatable/media/unit_testing/tests_onhold/1_dom/5396-fnUpdate-arrays-mData.js | JavaScript | mit | 2,746 |
/*
* jQuery Touch Optimized Sliders "R"Us
* HTML media
*
* Copyright (c) Fred Heusschen
* www.frebsite.nl
*/
!function(i){var n="tosrus",e="html";i[n].media[e]={filterAnchors:function(n){return"#"==n.slice(0,1)&&i(n).is("div")},initAnchors:function(e,t){i('<div class="'+i[n]._c("html")+'" />').append(i(t)).appendTo(e),e.removeClass(i[n]._c.loading).trigger(i[n]._e.loaded)},filterSlides:function(i){return i.is("div")},initSlides:function(){}}}(jQuery); | Jezfx/rocket-theme | site assets/plugins/smart-grid-gallery/includes/lightboxes/tosrus/js/media/jquery.tosrus.html.min.js | JavaScript | mit | 462 |
/**
* Knook-mailer
* https://github.com/knook/knook.git
* Auhtors: Alexandre Lagrange-Cetto, Olivier Graziano, Olivier Marin
* Created on 15/04/2016.
* version 0.1.0
*/
'use strict';
module.exports = {
Accounts: require('./src/Accounts'),
Email: require('./src/Email'),
Init: require('./src/Init'),
Prefs: require('./src/Prefs'),
Security: require('./src/Security')
}; | knook/knook-mailer | index.js | JavaScript | mit | 396 |
module.exports = {
KeyQ: {
printable: true,
keyCode: 81,
Default: 'ქ',
Shift: '',
CapsLock: 'Ⴕ',
Shift_CapsLock: '',
Alt: '',
Alt_Shift: ''
},
KeyW: {
printable: true,
keyCode: 87,
Default: 'წ',
Shift: 'ჭ',
CapsLock: 'Ⴜ',
Shift_CapsLock: 'Ⴝ',
Alt: '∑',
Alt_Shift: '„'
},
KeyE: {
printable: true,
keyCode: 69,
Default: 'ე',
Shift: '',
CapsLock: 'Ⴄ',
Shift_CapsLock: '',
Alt: '´',
Alt_Shift: '´'
},
KeyR: {
printable: true,
keyCode: 82,
Default: 'რ',
Shift: 'ღ',
CapsLock: 'Ⴐ',
Shift_CapsLock: 'Ⴖ',
Alt: '®',
Alt_Shift: '‰'
},
KeyT: {
printable: true,
keyCode: 84,
Default: 'ტ',
Shift: 'თ',
CapsLock: 'Ⴒ',
Shift_CapsLock: 'Ⴇ',
Alt: '†',
Alt_Shift: 'ˇ'
},
KeyY: {
printable: true,
keyCode: 89,
Default: 'ყ',
Shift: '',
CapsLock: 'Ⴗ',
Shift_CapsLock: '',
Alt: '¥',
Alt_Shift: 'Á'
},
KeyU: {
printable: true,
keyCode: 85,
Default: 'უ',
Shift: '',
CapsLock: 'Ⴓ',
Shift_CapsLock: '',
Alt: '',
Alt_Shift: ''
},
KeyI: {
printable: true,
keyCode: 73,
Default: 'ი',
Shift: '',
CapsLock: 'Ⴈ',
Shift_CapsLock: '',
Alt: 'ˆ',
Alt_Shift: 'ˆ'
},
KeyO: {
printable: true,
keyCode: 79,
Default: 'ო',
Shift: '`',
CapsLock: 'Ⴍ',
Shift_CapsLock: '',
Alt: 'ø',
Alt_Shift: 'Ø'
},
KeyP: {
printable: true,
keyCode: 80,
Default: 'პ',
Shift: '~',
CapsLock: 'Ⴎ',
Shift_CapsLock: '',
Alt: 'π',
Alt_Shift: '∏'
},
KeyA: {
printable: true,
keyCode: 65,
Default: 'ა',
Shift: '',
CapsLock: 'Ⴀ',
Shift_CapsLock: '',
Alt: 'å',
Alt_Shift: 'Å'
},
KeyS: {
printable: true,
keyCode: 83,
Default: 'ს',
Shift: 'შ',
CapsLock: 'Ⴑ',
Shift_CapsLock: 'Ⴘ',
Alt: 'ß',
Alt_Shift: 'Í'
},
KeyD: {
printable: true,
keyCode: 68,
Default: 'დ',
Shift: '',
CapsLock: 'Ⴃ',
Shift_CapsLock: '',
Alt: '∂',
Alt_Shift: 'Î'
},
KeyF: {
printable: true,
keyCode: 70,
Default: 'ფ',
Shift: '',
CapsLock: 'Ⴔ',
Shift_CapsLock: '',
Alt: 'ƒ',
Alt_Shift: 'Ï'
},
KeyG: {
printable: true,
keyCode: 71,
Default: 'გ',
Shift: '',
CapsLock: 'Ⴂ',
Shift_CapsLock: '',
Alt: '˙',
Alt_Shift: '˝'
},
KeyH: {
printable: true,
keyCode: 72,
Default: 'ჰ',
Shift: '',
CapsLock: 'Ⴠ',
Shift_CapsLock: '',
Alt: '∆',
Alt_Shift: 'Ó'
},
KeyJ: {
printable: true,
keyCode: 74,
Default: 'ჯ',
Shift: 'ჟ',
CapsLock: 'Ⴟ',
Shift_CapsLock: 'Ⴏ',
Alt: '˚',
Alt_Shift: 'Ô'
},
KeyK: {
printable: true,
keyCode: 75,
Default: 'კ',
Shift: '',
CapsLock: 'Ⴉ',
Shift_CapsLock: '',
Alt: '¬',
Alt_Shift: ''
},
KeyL: {
printable: true,
keyCode: 76,
Default: 'ლ',
Shift: '',
CapsLock: 'Ⴊ',
Shift_CapsLock: '',
Alt: 'Ω',
Alt_Shift: 'Ò'
},
KeyZ: {
printable: true,
keyCode: 90,
Default: 'ზ',
Shift: 'ძ',
CapsLock: 'Ⴆ',
Shift_CapsLock: '',
Alt: '≈',
Alt_Shift: '¸'
},
KeyX: {
printable: true,
keyCode: 88,
Default: 'ხ',
Shift: '',
CapsLock: 'Ⴞ',
Shift_CapsLock: '',
Alt: 'ç',
Alt_Shift: '˛'
},
KeyC: {
printable: true,
keyCode: 67,
Default: 'ც',
Shift: 'ჩ',
CapsLock: 'Ⴚ',
Shift_CapsLock: 'Ⴙ',
Alt: '√',
Alt_Shift: 'Ç'
},
KeyV: {
printable: true,
keyCode: 86,
Default: 'ვ',
Shift: '',
CapsLock: 'Ⴅ',
Shift_CapsLock: '',
Alt: '∫',
Alt_Shift: '◊'
},
KeyB: {
printable: true,
keyCode: 66,
Default: 'ბ',
Shift: '',
CapsLock: 'Ⴁ',
Shift_CapsLock: '',
Alt: '˜',
Alt_Shift: 'ı'
},
KeyN: {
printable: true,
keyCode: 78,
Default: 'ნ',
Shift: '',
CapsLock: 'Ⴌ',
Shift_CapsLock: '',
Alt: 'µ',
Alt_Shift: '˜'
},
KeyM: {
printable: true,
keyCode: 77,
Default: 'მ',
Shift: '',
CapsLock: 'Ⴋ',
Shift_CapsLock: '',
Alt: 'µ',
Alt_Shift: 'Â'
},
// digits
Digit1: {
printable: true,
keyCode: 49,
Default: '1',
Shift: '!',
CapsLock: '1',
Shift_CapsLock: '!',
Alt_Shift: '⁄',
Alt: '¡'
},
Digit2: {
printable: true,
keyCode: 50,
Default: '2',
Shift: '@',
CapsLock: '2',
Shift_CapsLock: '@',
Alt_Shift: '€',
Alt: '™'
},
Digit3: {
printable: true,
keyCode: 51,
Default: '3',
Shift: '#',
CapsLock: '3',
Shift_CapsLock: '#',
Alt_Shift: '‹',
Alt: '£'
},
Digit4: {
printable: true,
keyCode: 52,
Default: '4',
Shift: '$',
CapsLock: '4',
Shift_CapsLock: '$',
Alt_Shift: '›',
Alt: '¢'
},
Digit5: {
printable: true,
keyCode: 53,
Default: '5',
Shift: '%',
CapsLock: '5',
Shift_CapsLock: '%',
Alt_Shift: 'fi',
Alt: '∞'
},
Digit6: {
printable: true,
keyCode: 54,
Default: '6',
Shift: '^',
CapsLock: '6',
Shift_CapsLock: '^',
Alt_Shift: 'fl',
Alt: '§'
},
Digit7: {
printable: true,
keyCode: 55,
Default: '7',
Shift: '&',
CapsLock: '7',
Shift_CapsLock: '&',
Alt_Shift: '‡',
Alt: '¶'
},
Digit8: {
printable: true,
keyCode: 56,
Default: '8',
Shift: '*',
CapsLock: '8',
Shift_CapsLock: '*',
Alt_Shift: '°',
Alt: '•'
},
Digit9: {
printable: true,
keyCode: 57,
Default: '9',
Shift: '(',
CapsLock: '9',
Shift_CapsLock: '(',
Alt_Shift: '·',
Alt: 'º'
},
Digit0: {
printable: true,
keyCode: 48,
Default: '0',
Shift: ')',
CapsLock: '0',
Shift_CapsLock: ')',
Alt_Shift: '‚',
Alt: 'º'
},
// symbols
IntlBackslash: {
printable: true,
keyCode: 192,
Default: '§',
Shift: '±',
CapsLock: '§',
Shift_CapsLock: '±',
Alt: '§',
},
Minus: {
printable: true,
keyCode: 189,
Default: '-',
Shift: '_',
CapsLock: '-',
Shift_CapsLock: '_',
Alt: '–',
},
Equal: {
printable: true,
keyCode: 187,
Default: '=',
Shift: '+',
CapsLock: '=',
Shift_CapsLock: '+',
Alt: '≠'
},
BracketLeft: {
printable: true,
keyCode: 219,
Default: '[',
Shift: '{',
CapsLock: '[',
Shift_CapsLock: '{',
Alt: '“'
},
BracketRight: {
printable: true,
keyCode: 221,
Default: ']',
Shift: '}',
CapsLock: ']',
Shift_CapsLock: '}',
Alt: '‘'
},
Semicolon: {
printable: true,
keyCode: 186,
Default: ';',
Shift: ':',
CapsLock: ';',
Shift_CapsLock: ':',
Alt: '…'
},
Quote: {
printable: true,
keyCode: 222,
Default: '\'',
Shift: '"',
CapsLock: '\'',
Shift_CapsLock: '"',
Alt: 'æ'
},
Backslash: {
printable: true,
keyCode: 220,
Default: '\\',
Shift: '|',
CapsLock: '\\',
Shift_CapsLock: '|',
Alt: '«'
},
Backquote: {
printable: true,
keyCode: 192,
Default: '`',
Shift: '~',
CapsLock: '`',
Shift_CapsLock: '~',
Alt: '`'
},
Comma: {
printable: true,
keyCode: 188,
Default: ',',
Shift: '<',
CapsLock: ',',
Shift_CapsLock: '<',
Alt: '≤'
},
Period: {
printable: true,
keyCode: 190,
Default: '.',
Shift: '>',
CapsLock: '.',
Shift_CapsLock: '>',
Alt: '≥'
},
Slash: {
printable: true,
keyCode: 191,
Default: '/',
Shift: '?',
CapsLock: '/',
Shift_CapsLock: '?',
Alt: '÷'
},
// space keys
Tab: {
printable: true,
keyCode: 9
},
Enter: {
keyCode: 13
},
Space: {
printable: true,
keyCode: 32
},
// helper keys
Escape: { keyCode: 27 },
Backspace: { keyCode: 8 },
CapsLock: { keyCode: 20 },
ShiftLeft: { keyCode: 16 },
ShiftRight: { keyCode: 16 },
ControlLeft: { keyCode: 17 },
AltLeft: { keyCode: 18 },
OSLeft: { keyCode: 91 },
Space: { keyCode: 32 },
OSRight: { keyCode: 93 },
AltRight: { keyCode: 18 },
// arrows
ArrowLeft: { keyCode: 37 },
ArrowDown: { keyCode: 40 },
ArrowUp: { keyCode: 38 },
ArrowRight: { keyCode: 39 }
} | mijra/georgiankeyboard.com | data.js | JavaScript | mit | 8,583 |
window.Boid = (function(){
function Boid(x, y, settings){
this.location = new Vector(x, y);
this.acceleration = new Vector(0, 0);
this.velocity = new Vector(Helper.getRandomInt(-1,1), Helper.getRandomInt(-1,1));
this.settings = settings || {};
this.show_connections = settings.show_connections || true;
this.r = settings.r || 3.0;
this.maxspeed = settings.maxspeed || 2;
this.maxforce = settings.maxforce || 0.5;
this.perchSite = settings.perchSite || [h - 100, h - 50];
this.laziness_level = settings.laziness_level || 0.7;
this.min_perch = settings.min_perch || 1;
this.max_perch = settings.max_perch || 100;
this.perching = settings.perching || false;
this.perchTimer = settings.perchTimer || 100;
this.separation_multiple = settings.separation || 0.2;
this.cohesion_multiple = settings.cohesion || 2.0;
this.alignment_multiple = settings.alignment || 1.0;
this.separation_neighbor_dist = (settings.separation_neighbor_dis || 10) * 10;
this.cohesion_neighbor_dist = settings.cohesion_neighbor_dis || 200;
this.alignment_neighbor_dist = settings.alignment_neighbor_dis || 200;
}
Boid.prototype = {
constructor: Boid,
update: function(){
if (this.perching) {
this.perchTimer--;
if (this.perchTimer < 0){
this.perching = false;
}
} else {
this.velocity.add(this.acceleration);
this.velocity.limit(this.maxspeed);
this.location.add(this.velocity);
this.acceleration.multiply(0);
}
},
applyForce: function(force){
this.acceleration.add(force);
},
tired: function(){
var x = Math.random();
if (x < this.laziness_level){
return false;
} else {
return true;
}
},
seek: function(target) {
var desired = Vector.subtract(target, this.location);
desired.normalize();
desired.multiply(this.maxspeed);
var steer = Vector.subtract(desired, this.velocity);
steer.limit(this.maxforce);
return steer;
},
//Leaving this function here for experiments
//You can replace "seek" inside cohesion()
//For a more fish-like behaviour
arrive: function(target) {
var desired = Vector.subtract(target, this.location);
var dMag = desired.magnitude();
desired.normalize();
// closer than 100 pixels?
if (dMag < 100) {
var m = Helper.map(dMag,0,100,0,this.maxspeed);
desired.multiply(m);
} else {
desired.multiply(this.maxspeed);
}
var steer = Vector.subtract(desired, this.velocity);
steer.limit(this.maxforce);
return steer;
},
align: function(boids){
var sum = new Vector();
var count = 0;
for (var i = 0; i < boids.length; i++){
if (boids[i].perching == false) {
var distance = Vector.distance(this.location, boids[i].location);
//if ((distance > 0) && (distance < this.align_neighbor_dist)) {
sum.add(boids[i].velocity);
count++;
//}
}
}
if (count > 0) {
sum.divide(count);
sum.normalize();
sum.multiply(this.maxspeed);
var steer = Vector.subtract(sum,this.velocity);
steer.limit(this.maxforce);
return steer;
} else {
return new Vector(0,0);
}
},
cohesion: function(boids){
var sum = new Vector();
var count = 0;
for (var i = 0; i < boids.length; i++){
if (boids[i].perching == false) {
var distance = Vector.distance(this.location, boids[i].location);
//if ((distance > 0) && (distance < this.cohesion_neighbor_dist)) {
sum.add(boids[i].location);
count++;
//}
}
}
if (count > 0) {
sum.divide(count);
return this.seek(sum);
} else {
return new Vector(0,0);
}
},
separate: function(boids) {
var sum = new Vector();
var count = 0;
for (var i=0; i< boids.length; i++){
var distance = Vector.distance(this.location, boids[i].location);
if ((distance > 0) && (distance < this.separation_neighbor_dist)) {
var diff = Vector.subtract(this.location, boids[i].location);
diff.normalize();
diff.divide(distance);
sum.add(diff);
count++;
}
}
if(count > 0){
sum.divide(count);
sum.normalize();
sum.multiply(this.maxspeed);
var steer = Vector.subtract(sum, this.velocity);
steer.limit(this.maxforce);
}
return sum;
},
borders: function() {
//We are allowing boids to fly a bit outside
//the view and then return.
var offset = 20;
var isTired = this.tired();
if (this.onPerchSite() && isTired ){
this.perching = true;
} else {
if (this.location.x < -offset) this.location.x += 5;
if (this.location.x > w + offset) this.location.x -= 5;
if (this.location.y > h + offset) this.location.y -= 5;
if (this.location.y < -offset) this.location.y += 5;
}
},
onPerchSite: function(){
for (var i = 0; i < this.perchSite.length; i++){
if( this.location.y > this.perchSite[i] -2 && this.location.y < this.perchSite[i] + 2 )
return true;
}
return false;
},
borders2: function() {
var offset = 20;
var isTired = this.tired();
if (this.location.y > this.perchSite - 2 && this.location.y < this.perchSite + 2 && isTired ){
this.perching = true;
} else {
if (this.location.x < -this.r) this.location.x = w+this.r;
if (this.location.y < -this.r) this.location.y = h+this.r;
if (this.location.x > w+this.r) this.location.x = -this.r;
if (this.location.y > h+this.r) this.location.y = -this.r;
}
},
render: function() {
var theta = this.velocity.heading() + Math.PI/2;
context.stroke();
context.save();
context.translate(this.location.x, this.location.y);
context.rotate(theta);
if(this.settings.boid_shape){
this.settings.boid_shape();
} else {
this.default_boid_shape();
}
context.restore();
},
default_boid_shape: function(){
var radius = 5;
context.fillStyle = "#636570";
context.beginPath();
context.arc(0, 0, radius, 0, 2 * Math.PI, false);
context.closePath();
context.fill();
},
flock: function(boids){
var separate = this.separate(boids);
var align = this.align(boids);
var cohesion = this.cohesion(boids);
separate.multiply(this.separation_multiple);
align.multiply(this.alignment_multiple);
cohesion.multiply(this.cohesion_multiple);
this.applyForce(separate);
this.applyForce(align);
this.applyForce(cohesion);
},
run: function(boids){
if (this.perching){
this.perchTimer--;
if(this.perchTimer < 0 )
{
this.perching = false;
this.perchTimer = Helper.getRandomInt(this.min_perch,this.max_perch);
}
} else {
this.flock(boids);
this.update();
this.borders();
}
}
};
return Boid;
})(); | innni/hypela | js/simulation/boid.js | JavaScript | mit | 7,239 |
/*global window*/
(function($){
'use strict';
var Observable = function(){
this.observers = {};
};
Observable.prototype.on = function(event, observer){
(this.observers[event] = this.observers[event] || []).push(observer);
};
Observable.prototype.emit = function(event){
var args = Array.prototype.slice.call(arguments, 1);
(this.observers[event] || []).forEach(function(observer){
observer.apply(this, args);
}.bind(this));
};
var Model = $.Model = function(alpha){
Observable.call(this);
this._alpha = alpha || 30;
};
Model.prototype = Object.create(Observable.prototype);
Model.prototype.constructor = Model;
Model.prototype.alpha = function(alpha){
this._alpha = alpha || this._alpha;
if (alpha !== undefined) {
this.emit('alpha', this._alpha);
}
return this._alpha;
};
var Step = function(){};
Step.prototype.description = function(){
return this.type + this.x + ',' + this.y;
};
var MoveTo = function(x, y){
Step.call(this);
this.type = 'M';
this.x = x;
this.y = y;
};
MoveTo.prototype = Object.create(Step.prototype);
MoveTo.prototype.constructor = MoveTo;
var LineTo = function(x, y){
Step.call(this);
this.type = 'L';
this.x = x;
this.y = y;
};
LineTo.prototype = Object.create(Step.prototype);
LineTo.prototype.constructor = LineTo;
var HalfCircleTo = function(x, y, r, direction) {
Step.call(this);
this.type = 'A';
this.x = x;
this.y = y;
this.r = r;
this.direction = direction;
};
HalfCircleTo.prototype = Object.create(Step.prototype);
HalfCircleTo.prototype.constructor = HalfCircleTo;
HalfCircleTo.prototype.description = function(){
return [
this.type,
this.r + ',' + this.r,
0,
'0,' + (this.direction === -1 ? 1: 0),
this.x + ',' + this.y
].join(' ');
};
var ControlPoints = $.ControlPoints = function(model, direction, x, y){
Observable.call(this);
this.model = model;
this.direction = direction;
this.x = x;
this.y = y;
this.model.on('alpha', this.signal.bind(this));
};
ControlPoints.prototype = Object.create(Observable.prototype);
ControlPoints.prototype.constructor = ControlPoints;
ControlPoints.prototype.signal = function(){
this.emit('controlpoints', this.controlPoints());
};
ControlPoints.prototype.controlPoints = function(){
var alpha = this.model.alpha() * Math.PI / 180;
var sinAlpha = Math.sin(alpha);
var coefficient = 1/2 * sinAlpha * (1 - sinAlpha);
var ab = this.y/(1 + coefficient);
var w = ab * 1/2 * Math.sin(2 * alpha);
var h = ab * 1/2 * Math.cos(2 * alpha);
var r = ab * 1/2 * sinAlpha;
var points = [
new MoveTo(this.x, this.y),
new LineTo(this.x + this.direction * w, this.y - ab/2 - h),
new HalfCircleTo(this.x, this.y - ab, r, this.direction),
];
var n=10;
var ds = ab/n;
var dw = ds * 1/2 * Math.tan(alpha);
for (var index = 0; index < n; index++) {
points.push(new LineTo(this.x + dw, this.y - ab + (index + 1/2) * ds));
points.push(new LineTo(this.x, this.y - ab + (index + 1) * ds));
}
return points;
};
var View = $.View = function(model, path){
this.model = model;
this.path = path;
this.update();
};
View.prototype.update = function(){
this.path.setAttribute('d', this.description());
};
View.prototype.description = function(){
return this.model.controlPoints().map(function(point){
return point.description();
}).join('');
};
})(window.heart = window.heart || {});
| dvberkel/rails.girls.utrecht.2015 | js/heart.js | JavaScript | mit | 4,014 |
import root from './_root.js';
import toString from './toString.js';
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeParseInt = root.parseInt;
/**
* Converts `string` to an integer of the specified radix. If `radix` is
* `undefined` or `0`, a `radix` of `10` is used unless `value` is a
* hexadecimal, in which case a `radix` of `16` is used.
*
* **Note:** This method aligns with the
* [ES5 implementation](https://es5.github.io/#x15.1.2.2) of `parseInt`.
*
* @static
* @memberOf _
* @since 1.1.0
* @category String
* @param {string} string The string to convert.
* @param {number} [radix=10] The radix to interpret `value` by.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {number} Returns the converted integer.
* @example
*
* _.parseInt('08');
* // => 8
*
* _.map(['6', '08', '10'], _.parseInt);
* // => [6, 8, 10]
*/
function parseInt(string, radix, guard) {
if (guard || radix == null) {
radix = 0;
} else if (radix) {
radix = +radix;
}
return nativeParseInt(toString(string), radix || 0);
}
export default parseInt;
| jintoppy/react-training | step9-redux/node_modules/lodash-es/parseInt.js | JavaScript | mit | 1,161 |
Subsets and Splits