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 |
|---|---|---|---|---|---|
๏ปฟ/*global angular*/
(function () {
angular
.module('simplAdmin.vendors')
.controller('VendorListCtrl', ['vendorService', 'translateService', VendorListCtrl]);
function VendorListCtrl(vendorService, translateService) {
var vm = this;
vm.tableStateRef = {};
vm.vendors = [];
vm.translate = translateService;
vm.getVendors = function getVendors(tableState) {
vm.tableStateRef = tableState;
vm.isLoading = true;
vendorService.getVendors(tableState).then(function (result) {
vm.vendors = result.data.items;
tableState.pagination.numberOfPages = result.data.numberOfPages;
tableState.pagination.totalItemCount = result.data.totalRecord;
vm.isLoading = false;
});
};
vm.deleteVendor = function deleteVendor(vendor) {
bootbox.confirm('Are you sure you want to delete this vendor: ' + simplUtil.escapeHtml(vendor.name), function (result) {
if (result) {
vendorService.deleteVendor(vendor)
.then(function (result) {
vm.getVendors(vm.tableStateRef);
toastr.success(vendor.name + ' has been deleted');
})
.catch(function (response) {
toastr.error(response.data.error);
});
}
});
};
}
})();
| simplcommerce/SimplCommerce | src/Modules/SimplCommerce.Module.Vendors/wwwroot/admin/vendors/vendor-list.js | JavaScript | apache-2.0 | 1,543 |
angular.module('ReceitasApp', ['ngRoute', 'minhasDiretivas'])
.config(function ($routeProvider) {
$routeProvider.when('/', {
templateUrl: 'home.html',
});
$routeProvider.when('/adicionar', {
templateUrl: 'adicionar.html',
});
})
.run(['DbFactory', function (DbFactory) {
DbFactory.loadDb();
}]);
| Rfilomeno/MyRecipiesApp | www/js/modules/receitas-app.js | JavaScript | apache-2.0 | 378 |
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
var valid = [];
var test;
test = {
'code': [
'/**',
'* Merges objects into a target object. Note that the target object is mutated.',
'*',
'* @name merge',
'* @type {Function}',
'* @param {Object} target - target object',
'* @param {...Object} source - source objects (i.e., objects to be merged into the target object)',
'* @throws {Error} must provide a target object and one or more source objects',
'* @throws {TypeError} first argument must be an object',
'* @throws {TypeError} source arguments must be objects',
'* @returns {Object} merged (target) object',
'*',
'* @example',
'* var target = {',
'* \'a\': \'beep\'',
'* };',
'* var source = {',
'* \'a\': \'boop\',',
'* \'b\': \'bap\'',
'* };',
'*',
'* var out = merge( target, source );',
'* // returns {\'a\':\'boop\', \'b\':\'bap\'}',
'*/',
'var merge = mergefcn( defaults );'
].join( '\n' )
};
valid.push( test );
test = {
'code': [
'/**',
'* Merges objects into a target object. Note that the target object is mutated.',
'*',
'* @name merge',
'* @type {Function}',
'* @param {Object} target - target object',
'* @param {...Object} source - source objects (i.e., objects to be merged into the target object)',
'* @throws {Error} must provide a target object and one or more source objects',
'* @throws {TypeError} first argument must be an object',
'* @throws {TypeError} source arguments must be objects',
'* @returns {Object} merged (target) object',
'*',
'* @example',
'* var target = {',
'* \'a\': \'beep\'',
'* };',
'* var source = {',
'* \'a\': \'boop\',',
'* \'b\': \'bap\'',
'* };',
'*',
'* var out = merge( target, source );',
'* // returns {...}',
'*/',
'var merge = mergefcn( defaults );'
].join( '\n' )
};
valid.push( test );
test = {
'code': [
'/**',
'* Merges objects into a target object. Note that the target object is mutated.',
'*',
'* @name merge',
'* @type {Function}',
'* @param {Object} target - target object',
'* @param {...Object} source - source objects (i.e., objects to be merged into the target object)',
'* @throws {Error} must provide a target object and one or more source objects',
'* @throws {TypeError} first argument must be an object',
'* @throws {TypeError} source arguments must be objects',
'* @returns {Object} merged (target) object',
'*',
'* @example',
'* var target = {',
'* \'a\': \'beep\'',
'* };',
'* var source = {',
'* \'a\': \'boop\',',
'* \'b\': \'bap\'',
'* };',
'*',
'* var out = merge( target, source );',
'* /* returns {',
'* \'a\':\'boop\',',
'* \'b\':\'bap\'}',
'* *\\/',
'*/',
'var merge = mergefcn( defaults );'
].join( '\n' )
};
valid.push( test );
test = {
'code': [
'/**',
'* Returns a high-resolution time difference.',
'*',
'* ## Notes',
'*',
'* - Output format: `[seconds, nanoseconds]`.',
'*',
'*',
'* @param {NonNegativeIntegerArray} time - high-resolution time',
'* @throws {TypeError} must provide a nonnegative integer array',
'* @throws {RangeError} input array must have length `2`',
'* @returns {NumberArray} high resolution time difference',
'*',
'* @example',
'* var tic = require( \'@stdlib/time/tic\' );',
'*',
'* var start = tic();',
'* var delta = toc( start );',
'* // returns [<number>,<number>]',
'*/',
'function toc( time ) {',
' var now = tic();',
' var sec;',
' var ns;',
' if ( !isNonNegativeIntegerArray( time ) ) {',
' throw new TypeError( \'invalid argument. Must provide an array of nonnegative integers. Value: `\' + time + \'`.\' );',
' }',
' if ( time.length !== 2 ) {',
' throw new RangeError( \'invalid argument. Input array must have length `2`.\' );',
' }',
' sec = now[ 0 ] - time[ 0 ];',
' ns = now[ 1 ] - time[ 1 ];',
' if ( sec > 0 && ns < 0 ) {',
' sec -= 1;',
' ns += 1e9;',
' }',
' else if ( sec < 0 && ns > 0 ) {',
' sec += 1;',
' ns -= 1e9;',
' }',
' return [ sec, ns ];',
'}'
].join( '\n' )
};
valid.push( test );
test = {
'code': [
'/**',
'* Returns Anscombe\'s quartet.',
'*',
'* ## Notes',
'*',
'* - This function synchronously reads data from disk for each invocation. Such behavior is intentional and so is the avoidance of `require`. We assume that invocations are infrequent, and we want to avoid the `require` cache. This means that we allow data to be garbage collected and a user is responsible for explicitly caching data.',
'*',
'*',
'* @throws {Error} unable to read data',
'* @returns {ArrayArray} Anscombe\'s quartet',
'*',
'* @example',
'* var d = data();',
'* // returns [[[10,8.04],...],[[10,9.14],...],[[10,7.46],...],[[8,6.58],...]]',
'*/',
'function data() {',
' var d = readJSON( fpath, opts );',
' if ( d instanceof Error ) {',
' throw d;',
' }',
' return d;',
'}'
].join( '\n' )
};
valid.push( test );
// EXPORTS //
module.exports = valid;
| stdlib-js/stdlib | lib/node_modules/@stdlib/_tools/eslint/rules/jsdoc-doctest-quote-props/test/fixtures/valid.js | JavaScript | apache-2.0 | 5,623 |
import React, { Component } from 'react';
import MePanel from '../components/panels/MePanel';
import { Segment } from 'semantic-ui-react'
import DetailedActivity from './activities/DetailedActivity';
import ActivityGraph from './activities/ActivityGraph';
class ActivityOverview extends Component {
constructor(props) {
super(props);
this.state = {
selectedActivity: {
activityId: "N/A",
averageHeartRate: 0,
date: null,
description: "N/A",
distance: 0,
maxHeartRate: 0,
pace: 0,
time: 0,
type: "N/A",
location: null
}
};
}
renderActivity(activityId) {
let activity = this.props.activities.filter(activity => activity.activityId === activityId);
this.setState({ selectedActivity: activity.length > 0 ? activity[0] : null });
}
render() {
return (
<Segment.Group horizontal>
<Segment compact basic className="rt-statistics-segment">
<MePanel me={this.props.me} loading={this.props.loading} />
</Segment>
<Segment padded loading={this.props.loading} basic>
<ActivityGraph
loading={this.props.loading}
chartData={this.props.chartData}
activities={this.props.activities}
fromDate={this.props.fromDate}
toDate={this.props.toDate}
pointOnClickHandler={this.renderActivity.bind(this)}
/>
<DetailedActivity
loading={this.props.loading}
activity={this.state.selectedActivity}
/>
</Segment>
</Segment.Group>
);
}
}
export default ActivityOverview;
| jeroen-visser/strava | frontend/src/components/ActivityOverview.js | JavaScript | apache-2.0 | 1,666 |
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
const {OAuth2Client} = require('google-auth-library');
const {grpc} = require('google-gax');
const http = require('http');
const url = require('url');
const open = require('open');
const destroyer = require('server-destroy');
// [START nodejs_channel_quickstart]
// Reads the secrets from a `oauth2.keys.json` file, which should be downloaded
// from the Google Developers Console and saved in the same directory with the
// sample app.
// This sample app only calls read-only methods from the Channel API. Include
// additional scopes if calling methods that modify the configuration.
const SCOPES = ['https://www.googleapis.com/auth/apps.order'];
async function listCustomers(authClient, accountId) {
// Imports the Google Cloud client library
const {CloudChannelServiceClient} = require('@google-cloud/channel');
// Instantiates a client using OAuth2 credentials.
const sslCreds = grpc.credentials.createSsl();
const credentials = grpc.credentials.combineChannelCredentials(
sslCreds,
grpc.credentials.createFromGoogleCredential(authClient)
);
// Instantiates a client
const client = new CloudChannelServiceClient({
sslCreds: credentials,
});
// Calls listCustomers() method
const customers = await client.listCustomers({
parent: `accounts/${accountId}`,
});
console.info(customers);
}
/**
* Create a new OAuth2Client, and go through the OAuth2 content
* workflow. Return the full client to the callback.
*/
function getAuthenticatedClient(keys) {
return new Promise((resolve, reject) => {
// Create an oAuth client to authorize the API call. Secrets are kept in a
// `keys.json` file, which should be downloaded from the Google Developers
// Console.
const oAuth2Client = new OAuth2Client(
keys.web.client_id,
keys.web.client_secret,
// The first redirect URL from the `oauth2.keys.json` file will be used
// to generate the OAuth2 callback URL. Update the line below or edit
// the redirect URL in the Google Developers Console if needed.
// This sample app expects the callback URL to be
// 'http://localhost:3000/oauth2callback'
keys.web.redirect_uris[0]
);
// Generate the url that will be used for the consent dialog.
const authorizeUrl = oAuth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES.join(' '),
});
// Open an http server to accept the oauth callback. In this example, the
// only request to our webserver is to /oauth2callback?code=<code>
const server = http
.createServer(async (req, res) => {
try {
if (req.url.indexOf('/oauth2callback') > -1) {
// Acquire the code from the querystring, and close the web
// server.
const qs = new url.URL(req.url, 'http://localhost:3000')
.searchParams;
const code = qs.get('code');
console.log(`Code is ${code}`);
res.end('Authentication successful! Please return to the console.');
server.destroy();
// Now that we have the code, use that to acquire tokens.
const r = await oAuth2Client.getToken(code);
// Make sure to set the credentials on the OAuth2 client.
oAuth2Client.setCredentials(r.tokens);
console.info('Tokens acquired.');
resolve(oAuth2Client);
}
} catch (e) {
reject(e);
}
})
.listen(3000, () => {
// Open the browser to the authorize url to start the workflow.
// This line will not work if you are running the code in the
// environment where a browser is not available. In this case,
// copy the URL and open it manually in a browser.
console.info(`Opening the browser with URL: ${authorizeUrl}`);
open(authorizeUrl, {wait: false}).then(cp => cp.unref());
});
destroyer(server);
});
}
async function main(accountId, keys) {
// TODO: uncomment with your account id
// const accountId = 'C012345'
// TODO: uncomment this line with your oAuth2 file
//const keys = require('./oauth2.keys.json');
getAuthenticatedClient(keys).then(authClient =>
listCustomers(authClient, accountId)
);
}
// [END nodejs_channel_quickstart]
main(...process.argv.slice(2)).catch(err => {
console.error(err.message);
process.exitCode = 1;
});
process.on('unhandledRejection', err => {
console.error(err.message);
process.exitCode = 1;
});
| max-mathieu/nodejs-channel | samples/quickstart.js | JavaScript | apache-2.0 | 5,053 |
/*
* testlistfmt_ka_GE.js - test the list formatter object
*
* Copyright ยฉ 2020, JEDLSoft
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSe-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
if (typeof(ListFmt) === "undefined") {
var ListFmt = require("../../lib/ListFmt.js");
}
if (typeof(ilib) === "undefined") {
var ilib = require("../../lib/ilib.js");
}
module.exports.testlistfmt_ka_GE = {
setUp: function(callback) {
ilib.clearCache();
callback();
},
testListFmtkaGENumberFormatOne: function(test) {
var fmt = new ListFmt({
locale: "ka-GE"
});
test.expect(2);
test.ok(fmt !== null);
test.equal(fmt.format(["แแ แแ"]), "แแ แแ");
test.done();
},
testListFmtkaGENumberFormatTwo: function(test) {
var fmt = new ListFmt({
locale: "ka-GE"
});
test.expect(2);
test.ok(fmt !== null);
test.equal(fmt.format(["แแ แแ", "แแ แ"]), "แแ แแ แแ แแ แ");
test.done();
},
testListFmtkaGENumberFormatThree: function(test) {
var fmt = new ListFmt({
locale: "ka-GE"
});
test.expect(2);
test.ok(fmt !== null);
test.equal(fmt.format(["แแ แแ", "แแ แ", "แกแแแ"]), "แแ แแ, แแ แ แแ แกแแแ");
test.done();
},
testListFmtkaGENumberFormatFour: function(test) {
var fmt = new ListFmt({
locale: "ka-GE"
});
test.expect(2);
test.ok(fmt !== null);
test.equal(fmt.format(["แแ แแ", "แแ แ", "แกแแแ", "แแแฎแ"]), "แแ แแ, แแ แ, แกแแแ แแ แแแฎแ");
test.done();
},
testListFmtkaGENumberFormatFive: function(test) {
var fmt = new ListFmt({
locale: "ka-GE"
});
test.expect(2);
test.ok(fmt !== null);
test.equal(fmt.format(["แแ แแ", "แแ แ", "แกแแแ", "แแแฎแ", "แฎแฃแแ"]), "แแ แแ, แแ แ, แกแแแ, แแแฎแ แแ แฎแฃแแ");
test.done();
},
testListFmtUnitStylekaGENumberFormatOneShort: function(test) {
var fmt = new ListFmt({
locale: "ka-GE",
style: "unit"
});
test.expect(2);
test.ok(fmt !== null);
test.equal(fmt.format(["แแ แแ"]), "แแ แแ");
test.done();
},
testListFmtUnitStylekaGENumberFormatTwoShort: function(test) {
var fmt = new ListFmt({
locale: "ka-GE",
style: "unit"
});
test.expect(2);
test.ok(fmt !== null);
test.equal(fmt.format(["แแ แแ", "แแ แ"]), "แแ แแ, แแ แ");
test.done();
},
testListFmtUnitStylekaGENumberFormatThreeShort: function(test) {
var fmt = new ListFmt({
locale: "ka-GE",
style: "unit"
});
test.expect(2);
test.ok(fmt !== null);
test.equal(fmt.format(["แแ แแ", "แแ แ", "แกแแแ"]), "แแ แแ, แแ แ, แกแแแ");
test.done();
},
testListFmtUnitStylekaGENumberFormatFourShort: function(test) {
var fmt = new ListFmt({
locale: "ka-GE",
style: "unit"
});
test.expect(2);
test.ok(fmt !== null);
test.equal(fmt.format(["แแ แแ", "แแ แ", "แกแแแ", "แแแฎแ"]), "แแ แแ, แแ แ, แกแแแ, แแแฎแ");
test.done();
},
testListFmtUnitStylekaGENumberFormatFiveShort: function(test) {
var fmt = new ListFmt({
locale: "ka-GE",
style: "unit"
});
test.expect(2);
test.ok(fmt !== null);
test.equal(fmt.format(["แแ แแ", "แแ แ", "แกแแแ", "แแแฎแ", "แฎแฃแแ"]), "แแ แแ, แแ แ, แกแแแ, แแแฎแ, แฎแฃแแ");
test.done();
},
testListFmtUnitStylekaGENumberFormatOneFull: function(test) {
var fmt = new ListFmt({
locale: "ka-GE",
style: "unit",
length: "full"
});
test.expect(2);
test.ok(fmt !== null);
test.equal(fmt.format(["แแ แแ"]), "แแ แแ");
test.done();
},
testListFmtUnitStylekaGENumberFormatTwoFull: function(test) {
var fmt = new ListFmt({
locale: "ka-GE",
style: "unit",
length: "full"
});
test.expect(2);
test.ok(fmt !== null);
test.equal(fmt.format(["แแ แแ", "แแ แ"]), "แแ แแ, แแ แ");
test.done();
},
testListFmtUnitStylekaGENumberFormatThreeFull: function(test) {
var fmt = new ListFmt({
locale: "ka-GE",
style: "unit",
length: "full"
});
test.expect(2);
test.ok(fmt !== null);
test.equal(fmt.format(["แแ แแ", "แแ แ", "แกแแแ"]), "แแ แแ, แแ แ, แกแแแ");
test.done();
},
testListFmtUnitStylekaGENumberFormatFourFull: function(test) {
var fmt = new ListFmt({
locale: "ka-GE",
style: "unit",
length: "full"
});
test.expect(2);
test.ok(fmt !== null);
test.equal(fmt.format(["แแ แแ", "แแ แ", "แกแแแ", "แแแฎแ"]), "แแ แแ, แแ แ, แกแแแ, แแแฎแ");
test.done();
},
testListFmtUnitStylekaGENumberFormatFiveFull: function(test) {
var fmt = new ListFmt({
locale: "ka-GE",
style: "unit",
length: "full"
});
test.expect(2);
test.ok(fmt !== null);
test.equal(fmt.format(["แแ แแ", "แแ แ", "แกแแแ", "แแแฎแ", "แฎแฃแแ"]), "แแ แแ, แแ แ, แกแแแ, แแแฎแ, แฎแฃแแ");
test.done();
},
testListFmtORStylekaGENumberFormatOne: function(test) {
var fmt = new ListFmt({
locale: "ka-GE",
style: "disjunction"
});
test.expect(2);
test.ok(fmt !== null);
test.equal(fmt.format(["แแ แแ"]), "แแ แแ");
test.done();
},
testListFmtORStylekaGENumberFormatTwo: function(test) {
var fmt = new ListFmt({
locale: "ka-GE",
style: "disjunction"
});
test.expect(2);
test.ok(fmt !== null);
test.equal(fmt.format(["แแ แแ", "แแ แ"]), "แแ แแ แแ แแ แ");
test.done();
},
testListFmtORStylekaGENumberFormatThree: function(test) {
var fmt = new ListFmt({
locale: "ka-GE",
style: "disjunction"
});
test.expect(2);
test.ok(fmt !== null);
test.equal(fmt.format(["แแ แแ", "แแ แ", "แกแแแ"]), "แแ แแ, แแ แ แแ แกแแแ");
test.done();
},
testListFmtORStylekaGENumberFormatFour: function(test) {
var fmt = new ListFmt({
locale: "ka-GE",
style: "disjunction"
});
test.expect(2);
test.ok(fmt !== null);
test.equal(fmt.format(["แแ แแ", "แแ แ", "แกแแแ", "แแแฎแ"]), "แแ แแ, แแ แ, แกแแแ แแ แแแฎแ");
test.done();
},
testListFmtORStylekaGENumberFormatFiveFull: function(test) {
var fmt = new ListFmt({
locale: "ka-GE",
style: "disjunction"
});
test.expect(2);
test.ok(fmt !== null);
test.equal(fmt.format(["แแ แแ", "แแ แ", "แกแแแ", "แแแฎแ", "แฎแฃแแ"]), "แแ แแ, แแ แ, แกแแแ, แแแฎแ แแ แฎแฃแแ");
test.done();
}
}; | iLib-js/iLib | js/test/strings-ext/testlistfmt_ka_GE.js | JavaScript | apache-2.0 | 8,383 |
/*global define*/
define([
'../Core/BoundingSphere',
'../Core/Cartesian3',
'../Core/clone',
'../Core/Color',
'../Core/ComponentDatatype',
'../Core/defaultValue',
'../Core/defined',
'../Core/defineProperties',
'../Core/destroyObject',
'../Core/DeveloperError',
'../Core/Matrix4',
'../Core/PrimitiveType',
'../Core/RuntimeError',
'../Core/Transforms',
'../Renderer/Buffer',
'../Renderer/BufferUsage',
'../Renderer/DrawCommand',
'../Renderer/ShaderSource',
'../ThirdParty/when',
'./getAttributeOrUniformBySemantic',
'./Model',
'./ModelInstance',
'./SceneMode',
'./ShadowMode'
], function(
BoundingSphere,
Cartesian3,
clone,
Color,
ComponentDatatype,
defaultValue,
defined,
defineProperties,
destroyObject,
DeveloperError,
Matrix4,
PrimitiveType,
RuntimeError,
Transforms,
Buffer,
BufferUsage,
DrawCommand,
ShaderSource,
when,
getAttributeOrUniformBySemantic,
Model,
ModelInstance,
SceneMode,
ShadowMode) {
'use strict';
var LoadState = {
NEEDS_LOAD : 0,
LOADING : 1,
LOADED : 2,
FAILED : 3
};
/**
* A 3D model instance collection. All instances reference the same underlying model, but have unique
* per-instance properties like model matrix, pick id, etc.
*
* Instances are rendered relative-to-center and for best results instances should be positioned close to one another.
* Otherwise there may be precision issues if, for example, instances are placed on opposite sides of the globe.
*
* @alias ModelInstanceCollection
* @constructor
*
* @param {Object} options Object with the following properties:
* @param {Object[]} [options.instances] An array of instances, where each instance contains a modelMatrix and optional batchId when options.batchTable is defined.
* @param {Cesium3DTileBatchTable} [options.batchTable] The batch table of the instanced 3D Tile.
* @param {String} [options.url] The url to the .gltf file.
* @param {Object} [options.headers] HTTP headers to send with the request.
* @param {Object} [options.requestType] The request type, used for request prioritization
* @param {Object|ArrayBuffer|Uint8Array} [options.gltf] The object for the glTF JSON or an arraybuffer of Binary glTF defined by the CESIUM_binary_glTF extension.
* @param {String} [options.basePath=''] The base path that paths in the glTF JSON are relative to.
* @param {Boolean} [options.dynamic=false] Hint if instance model matrices will be updated frequently.
* @param {Boolean} [options.show=true] Determines if the collection will be shown.
* @param {Boolean} [options.allowPicking=true] When <code>true</code>, each instance is pickable with {@link Scene#pick}.
* @param {Boolean} [options.asynchronous=true] Determines if model WebGL resource creation will be spread out over several frames or block until completion once all glTF files are loaded.
* @param {Boolean} [options.incrementallyLoadTextures=true] Determine if textures may continue to stream in after the model is loaded.
* @param {ShadowMode} [options.shadows=ShadowMode.ENABLED] Determines whether the collection casts or receives shadows from each light source.
* @param {Boolean} [options.debugShowBoundingVolume=false] For debugging only. Draws the bounding sphere for the collection.
* @param {Boolean} [options.debugWireframe=false] For debugging only. Draws the instances in wireframe.
*
* @exception {DeveloperError} Must specify either <options.gltf> or <options.url>, but not both.
* @exception {DeveloperError} Shader program cannot be optimized for instancing. Parameters cannot have any of the following semantics: MODEL, MODELINVERSE, MODELVIEWINVERSE, MODELVIEWPROJECTIONINVERSE, MODELINVERSETRANSPOSE.
*
* @private
*/
function ModelInstanceCollection(options) {
options = defaultValue(options, defaultValue.EMPTY_OBJECT);
//>>includeStart('debug', pragmas.debug);
if (!defined(options.gltf) && !defined(options.url)) {
throw new DeveloperError('Either options.gltf or options.url is required.');
}
if (defined(options.gltf) && defined(options.url)) {
throw new DeveloperError('Cannot pass in both options.gltf and options.url.');
}
//>>includeEnd('debug');
this.show = defaultValue(options.show, true);
this._instancingSupported = false;
this._dynamic = defaultValue(options.dynamic, false);
this._allowPicking = defaultValue(options.allowPicking, true);
this._cull = defaultValue(options.cull, true); // Undocumented option
this._ready = false;
this._readyPromise = when.defer();
this._state = LoadState.NEEDS_LOAD;
this._dirty = false;
this._instances = createInstances(this, options.instances);
// When the model instance collection is backed by an i3dm tile,
// use its batch table resources to modify the shaders, attributes, and uniform maps.
this._batchTable = options.batchTable;
this._model = undefined;
this._vertexBufferTypedArray = undefined; // Hold onto the vertex buffer contents when dynamic is true
this._vertexBuffer = undefined;
this._batchIdBuffer = undefined;
this._instancedUniformsByProgram = undefined;
this._drawCommands = [];
this._pickCommands = [];
this._modelCommands = undefined;
this._boundingSphere = createBoundingSphere(this);
this._center = Cartesian3.clone(this._boundingSphere.center);
this._rtcTransform = new Matrix4();
this._rtcModelView = new Matrix4(); // Holds onto uniform
this._mode = undefined;
this.modelMatrix = Matrix4.clone(Matrix4.IDENTITY);
this._modelMatrix = Matrix4.clone(this.modelMatrix);
// Passed on to Model
this._url = options.url;
this._headers = options.headers;
this._requestType = options.requestType;
this._gltf = options.gltf;
this._basePath = options.basePath;
this._asynchronous = options.asynchronous;
this._incrementallyLoadTextures = options.incrementallyLoadTextures;
this._upAxis = options.upAxis; // Undocumented option
this.shadows = defaultValue(options.shadows, ShadowMode.ENABLED);
this._shadows = this.shadows;
this.debugShowBoundingVolume = defaultValue(options.debugShowBoundingVolume, false);
this._debugShowBoundingVolume = false;
this.debugWireframe = defaultValue(options.debugWireframe, false);
this._debugWireframe = false;
}
defineProperties(ModelInstanceCollection.prototype, {
allowPicking : {
get : function() {
return this._allowPicking;
}
},
length : {
get : function() {
return this._instances.length;
}
},
activeAnimations : {
get : function() {
return this._model.activeAnimations;
}
},
ready : {
get : function() {
return this._ready;
}
},
readyPromise : {
get : function() {
return this._readyPromise.promise;
}
}
});
function createInstances(collection, instancesOptions) {
instancesOptions = defaultValue(instancesOptions, []);
var length = instancesOptions.length;
var instances = new Array(length);
for (var i = 0; i < length; ++i) {
var instanceOptions = instancesOptions[i];
var modelMatrix = instanceOptions.modelMatrix;
var instanceId = defaultValue(instanceOptions.batchId, i);
instances[i] = new ModelInstance(collection, modelMatrix, instanceId);
}
return instances;
}
function createBoundingSphere(collection) {
var instancesLength = collection.length;
var points = new Array(instancesLength);
for (var i = 0; i < instancesLength; ++i) {
points[i] = Matrix4.getTranslation(collection._instances[i]._modelMatrix, new Cartesian3());
}
return BoundingSphere.fromPoints(points);
}
var scratchCartesian = new Cartesian3();
var scratchMatrix = new Matrix4();
ModelInstanceCollection.prototype.expandBoundingSphere = function(instanceModelMatrix) {
var translation = Matrix4.getTranslation(instanceModelMatrix, scratchCartesian);
BoundingSphere.expand(this._boundingSphere, translation, this._boundingSphere);
};
function getInstancedUniforms(collection, programName) {
if (defined(collection._instancedUniformsByProgram)) {
return collection._instancedUniformsByProgram[programName];
}
var instancedUniformsByProgram = {};
collection._instancedUniformsByProgram = instancedUniformsByProgram;
// When using CESIUM_RTC_MODELVIEW the CESIUM_RTC center is ignored. Instances are always rendered relative-to-center.
var modelSemantics = ['MODEL', 'MODELVIEW', 'CESIUM_RTC_MODELVIEW', 'MODELVIEWPROJECTION', 'MODELINVERSE', 'MODELVIEWINVERSE', 'MODELVIEWPROJECTIONINVERSE', 'MODELINVERSETRANSPOSE', 'MODELVIEWINVERSETRANSPOSE'];
var supportedSemantics = ['MODELVIEW', 'CESIUM_RTC_MODELVIEW', 'MODELVIEWPROJECTION', 'MODELVIEWINVERSETRANSPOSE'];
var gltf = collection._model.gltf;
var techniques = gltf.techniques;
for (var techniqueName in techniques) {
if (techniques.hasOwnProperty(techniqueName)) {
var technique = techniques[techniqueName];
var parameters = technique.parameters;
var uniforms = technique.uniforms;
var program = technique.program;
// Different techniques may share the same program, skip if already processed.
// This assumes techniques that share a program do not declare different semantics for the same uniforms.
if (!defined(instancedUniformsByProgram[program])) {
var uniformMap = {};
instancedUniformsByProgram[program] = uniformMap;
for (var uniformName in uniforms) {
if (uniforms.hasOwnProperty(uniformName)) {
var parameterName = uniforms[uniformName];
var parameter = parameters[parameterName];
var semantic = parameter.semantic;
if (defined(semantic) && (modelSemantics.indexOf(semantic) > -1)) {
if (supportedSemantics.indexOf(semantic) > -1) {
uniformMap[uniformName] = semantic;
} else {
throw new RuntimeError('Shader program cannot be optimized for instancing. ' +
'Parameter "' + parameter + '" in program "' + programName +
'" uses unsupported semantic "' + semantic + '"'
);
}
}
}
}
}
}
}
return instancedUniformsByProgram[programName];
}
var vertexShaderCached;
function getVertexShaderCallback(collection) {
return function(vs, programName) {
var instancedUniforms = getInstancedUniforms(collection, programName);
var usesBatchTable = defined(collection._batchTable);
var renamedSource = ShaderSource.replaceMain(vs, 'czm_instancing_main');
var globalVarsHeader = '';
var globalVarsMain = '';
for (var uniform in instancedUniforms) {
if (instancedUniforms.hasOwnProperty(uniform)) {
var semantic = instancedUniforms[uniform];
var varName;
if (semantic === 'MODELVIEW' || semantic === 'CESIUM_RTC_MODELVIEW') {
varName = 'czm_instanced_modelView';
} else if (semantic === 'MODELVIEWPROJECTION') {
varName = 'czm_instanced_modelViewProjection';
globalVarsHeader += 'mat4 czm_instanced_modelViewProjection;\n';
globalVarsMain += 'czm_instanced_modelViewProjection = czm_projection * czm_instanced_modelView;\n';
} else if (semantic === 'MODELVIEWINVERSETRANSPOSE') {
varName = 'czm_instanced_modelViewInverseTranspose';
globalVarsHeader += 'mat3 czm_instanced_modelViewInverseTranspose;\n';
globalVarsMain += 'czm_instanced_modelViewInverseTranspose = mat3(czm_instanced_modelView);\n';
}
// Remove the uniform declaration
var regex = new RegExp('uniform.*' + uniform + '.*');
renamedSource = renamedSource.replace(regex, '');
// Replace all occurrences of the uniform with the global variable
regex = new RegExp(uniform + '\\b', 'g');
renamedSource = renamedSource.replace(regex, varName);
}
}
// czm_instanced_model is the model matrix of the instance relative to center
// czm_instanced_modifiedModelView is the transform from the center to view
// czm_instanced_nodeTransform is the local offset of the node within the model
var uniforms =
'uniform mat4 czm_instanced_modifiedModelView;\n' +
'uniform mat4 czm_instanced_nodeTransform;\n';
var batchIdAttribute = usesBatchTable ? 'attribute float a_batchId;\n' : '';
var instancedSource =
uniforms +
globalVarsHeader +
'mat4 czm_instanced_modelView;\n' +
'attribute vec4 czm_modelMatrixRow0;\n' +
'attribute vec4 czm_modelMatrixRow1;\n' +
'attribute vec4 czm_modelMatrixRow2;\n' +
batchIdAttribute +
renamedSource +
'void main()\n' +
'{\n' +
' mat4 czm_instanced_model = mat4(czm_modelMatrixRow0.x, czm_modelMatrixRow1.x, czm_modelMatrixRow2.x, 0.0, czm_modelMatrixRow0.y, czm_modelMatrixRow1.y, czm_modelMatrixRow2.y, 0.0, czm_modelMatrixRow0.z, czm_modelMatrixRow1.z, czm_modelMatrixRow2.z, 0.0, czm_modelMatrixRow0.w, czm_modelMatrixRow1.w, czm_modelMatrixRow2.w, 1.0);\n' +
' czm_instanced_modelView = czm_instanced_modifiedModelView * czm_instanced_model * czm_instanced_nodeTransform;\n' +
globalVarsMain +
' czm_instancing_main();\n' +
'}';
vertexShaderCached = instancedSource;
if (usesBatchTable) {
instancedSource = collection._batchTable.getVertexShaderCallback(true, 'a_batchId')(instancedSource);
}
return instancedSource;
};
}
function getFragmentShaderCallback(collection) {
return function(fs) {
var batchTable = collection._batchTable;
if (defined(batchTable)) {
var gltf = collection._model.gltf;
var diffuseUniformName = getAttributeOrUniformBySemantic(gltf, '_3DTILESDIFFUSE');
fs = batchTable.getFragmentShaderCallback(true, diffuseUniformName)(fs);
}
return fs;
};
}
function getPickVertexShaderCallback(collection) {
return function (vs) {
// Use the vertex shader that was generated earlier
vs = vertexShaderCached;
var usesBatchTable = defined(collection._batchTable);
var allowPicking = collection._allowPicking;
if (usesBatchTable) {
vs = collection._batchTable.getPickVertexShaderCallback('a_batchId')(vs);
} else if (allowPicking) {
vs = ShaderSource.createPickVertexShaderSource(vs);
}
return vs;
};
}
function getPickFragmentShaderCallback(collection) {
return function(fs) {
var usesBatchTable = defined(collection._batchTable);
var allowPicking = collection._allowPicking;
if (usesBatchTable) {
fs = collection._batchTable.getPickFragmentShaderCallback()(fs);
} else if (allowPicking) {
fs = ShaderSource.createPickFragmentShaderSource(fs, 'varying');
}
return fs;
};
}
function createModifiedModelView(collection, context) {
return function() {
return Matrix4.multiply(context.uniformState.view, collection._rtcTransform, collection._rtcModelView);
};
}
function createNodeTransformFunction(node) {
return function() {
return node.computedMatrix;
};
}
function getUniformMapCallback(collection, context) {
return function(uniformMap, programName, node) {
uniformMap = clone(uniformMap);
uniformMap.czm_instanced_modifiedModelView = createModifiedModelView(collection, context);
uniformMap.czm_instanced_nodeTransform = createNodeTransformFunction(node);
// Remove instanced uniforms from the uniform map
var instancedUniforms = getInstancedUniforms(collection, programName);
for (var uniform in instancedUniforms) {
if (instancedUniforms.hasOwnProperty(uniform)) {
delete uniformMap[uniform];
}
}
if (defined(collection._batchTable)) {
uniformMap = collection._batchTable.getUniformMapCallback()(uniformMap);
}
return uniformMap;
};
}
function getPickUniformMapCallback(collection) {
return function(uniformMap) {
// Uses the uniform map generated from getUniformMapCallback
if (defined(collection._batchTable)) {
uniformMap = collection._batchTable.getPickUniformMapCallback()(uniformMap);
}
return uniformMap;
};
}
function getVertexShaderNonInstancedCallback(collection) {
return function(vs) {
if (defined(collection._batchTable)) {
vs = collection._batchTable.getVertexShaderCallback(true, 'a_batchId')(vs);
// Treat a_batchId as a uniform rather than a vertex attribute
vs = 'uniform float a_batchId\n;' + vs;
}
return vs;
};
}
function getPickVertexShaderNonInstancedCallback(collection) {
return function(vs) {
if (defined(collection._batchTable)) {
vs = collection._batchTable.getPickVertexShaderCallback('a_batchId')(vs);
// Treat a_batchId as a uniform rather than a vertex attribute
vs = 'uniform float a_batchId\n;' + vs;
}
return vs;
};
}
function getPickFragmentShaderNonInstancedCallback(collection) {
return function(fs) {
var usesBatchTable = defined(collection._batchTable);
var allowPicking = collection._allowPicking;
if (usesBatchTable) {
fs = collection._batchTable.getPickFragmentShaderCallback()(fs);
} else if (allowPicking) {
fs = ShaderSource.createPickFragmentShaderSource(fs, 'uniform');
}
return fs;
};
}
function getUniformMapNonInstancedCallback(collection) {
return function(uniformMap) {
if (defined(collection._batchTable)) {
uniformMap = collection._batchTable.getUniformMapCallback()(uniformMap);
}
return uniformMap;
};
}
function getVertexBufferTypedArray(collection) {
var instances = collection._instances;
var instancesLength = collection.length;
var collectionCenter = collection._center;
var vertexSizeInFloats = 12;
var bufferData = collection._vertexBufferTypedArray;
if (!defined(bufferData)) {
bufferData = new Float32Array(instancesLength * vertexSizeInFloats);
}
if (collection._dynamic) {
// Hold onto the buffer data so we don't have to allocate new memory every frame.
collection._vertexBufferTypedArray = bufferData;
}
for (var i = 0; i < instancesLength; ++i) {
var modelMatrix = instances[i]._modelMatrix;
// Instance matrix is relative to center
var instanceMatrix = Matrix4.clone(modelMatrix, scratchMatrix);
instanceMatrix[12] -= collectionCenter.x;
instanceMatrix[13] -= collectionCenter.y;
instanceMatrix[14] -= collectionCenter.z;
var offset = i * vertexSizeInFloats;
// First three rows of the model matrix
bufferData[offset + 0] = instanceMatrix[0];
bufferData[offset + 1] = instanceMatrix[4];
bufferData[offset + 2] = instanceMatrix[8];
bufferData[offset + 3] = instanceMatrix[12];
bufferData[offset + 4] = instanceMatrix[1];
bufferData[offset + 5] = instanceMatrix[5];
bufferData[offset + 6] = instanceMatrix[9];
bufferData[offset + 7] = instanceMatrix[13];
bufferData[offset + 8] = instanceMatrix[2];
bufferData[offset + 9] = instanceMatrix[6];
bufferData[offset + 10] = instanceMatrix[10];
bufferData[offset + 11] = instanceMatrix[14];
}
return bufferData;
}
function createVertexBuffer(collection, context) {
var i;
var instances = collection._instances;
var instancesLength = collection.length;
var dynamic = collection._dynamic;
var usesBatchTable = defined(collection._batchTable);
var allowPicking = collection._allowPicking;
if (usesBatchTable) {
var batchIdBufferData = new Uint16Array(instancesLength);
for (i = 0; i < instancesLength; ++i) {
batchIdBufferData[i] = instances[i]._instanceId;
}
collection._batchIdBuffer = Buffer.createVertexBuffer({
context : context,
typedArray : batchIdBufferData,
usage : BufferUsage.STATIC_DRAW
});
}
if (allowPicking && !usesBatchTable) {
var pickIdBuffer = new Uint8Array(instancesLength * 4);
for (i = 0; i < instancesLength; ++i) {
var pickId = collection._pickIds[i];
var pickColor = pickId.color;
var offset = i * 4;
pickIdBuffer[offset] = Color.floatToByte(pickColor.red);
pickIdBuffer[offset + 1] = Color.floatToByte(pickColor.green);
pickIdBuffer[offset + 2] = Color.floatToByte(pickColor.blue);
pickIdBuffer[offset + 3] = Color.floatToByte(pickColor.alpha);
}
collection._pickIdBuffer = Buffer.createVertexBuffer({
context : context,
typedArray : pickIdBuffer,
usage : BufferUsage.STATIC_DRAW
});
}
var vertexBufferTypedArray = getVertexBufferTypedArray(collection);
collection._vertexBuffer = Buffer.createVertexBuffer({
context : context,
typedArray : vertexBufferTypedArray,
usage : dynamic ? BufferUsage.STREAM_DRAW : BufferUsage.STATIC_DRAW
});
}
function updateVertexBuffer(collection) {
var vertexBufferTypedArray = getVertexBufferTypedArray(collection);
collection._vertexBuffer.copyFromArrayView(vertexBufferTypedArray);
}
function createPickIds(collection, context) {
// PERFORMANCE_IDEA: we could skip the pick buffer completely by allocating
// a continuous range of pickIds and then converting the base pickId + batchId
// to RGBA in the shader. The only consider is precision issues, which might
// not be an issue in WebGL 2.
var instances = collection._instances;
var instancesLength = instances.length;
var pickIds = new Array(instancesLength);
for (var i = 0; i < instancesLength; ++i) {
pickIds[i] = context.createPickId(instances[i]);
}
return pickIds;
}
function createModel(collection, context) {
var instancingSupported = collection._instancingSupported;
var usesBatchTable = defined(collection._batchTable);
var allowPicking = collection._allowPicking;
var modelOptions = {
url : collection._url,
headers : collection._headers,
requestType : collection._requestType,
gltf : collection._gltf,
basePath : collection._basePath,
shadows : collection._shadows,
cacheKey : undefined,
asynchronous : collection._asynchronous,
allowPicking : allowPicking,
incrementallyLoadTextures : collection._incrementallyLoadTextures,
upAxis : collection._upAxis,
precreatedAttributes : undefined,
vertexShaderLoaded : undefined,
fragmentShaderLoaded : undefined,
uniformMapLoaded : undefined,
pickVertexShaderLoaded : undefined,
pickFragmentShaderLoaded : undefined,
pickUniformMapLoaded : undefined,
ignoreCommands : true
};
if (allowPicking && !usesBatchTable) {
collection._pickIds = createPickIds(collection, context);
}
if (instancingSupported) {
createVertexBuffer(collection, context);
var vertexSizeInFloats = 12;
var componentSizeInBytes = ComponentDatatype.getSizeInBytes(ComponentDatatype.FLOAT);
var instancedAttributes = {
czm_modelMatrixRow0 : {
index : 0, // updated in Model
vertexBuffer : collection._vertexBuffer,
componentsPerAttribute : 4,
componentDatatype : ComponentDatatype.FLOAT,
normalize : false,
offsetInBytes : 0,
strideInBytes : componentSizeInBytes * vertexSizeInFloats,
instanceDivisor : 1
},
czm_modelMatrixRow1 : {
index : 0, // updated in Model
vertexBuffer : collection._vertexBuffer,
componentsPerAttribute : 4,
componentDatatype : ComponentDatatype.FLOAT,
normalize : false,
offsetInBytes : componentSizeInBytes * 4,
strideInBytes : componentSizeInBytes * vertexSizeInFloats,
instanceDivisor : 1
},
czm_modelMatrixRow2 : {
index : 0, // updated in Model
vertexBuffer : collection._vertexBuffer,
componentsPerAttribute : 4,
componentDatatype : ComponentDatatype.FLOAT,
normalize : false,
offsetInBytes : componentSizeInBytes * 8,
strideInBytes : componentSizeInBytes * vertexSizeInFloats,
instanceDivisor : 1
}
};
// When using a batch table, add a batch id attribute
if (usesBatchTable) {
instancedAttributes.a_batchId = {
index : 0, // updated in Model
vertexBuffer : collection._batchIdBuffer,
componentsPerAttribute : 1,
componentDatatype : ComponentDatatype.UNSIGNED_SHORT,
normalize : false,
offsetInBytes : 0,
strideInBytes : 0,
instanceDivisor : 1
};
}
if (allowPicking && !usesBatchTable) {
instancedAttributes.pickColor = {
index : 0, // updated in Model
vertexBuffer : collection._pickIdBuffer,
componentsPerAttribute : 4,
componentDatatype : ComponentDatatype.UNSIGNED_BYTE,
normalize : true,
offsetInBytes : 0,
strideInBytes : 0,
instanceDivisor : 1
};
}
modelOptions.precreatedAttributes = instancedAttributes;
modelOptions.vertexShaderLoaded = getVertexShaderCallback(collection);
modelOptions.fragmentShaderLoaded = getFragmentShaderCallback(collection);
modelOptions.uniformMapLoaded = getUniformMapCallback(collection, context);
modelOptions.pickVertexShaderLoaded = getPickVertexShaderCallback(collection);
modelOptions.pickFragmentShaderLoaded = getPickFragmentShaderCallback(collection);
modelOptions.pickUniformMapLoaded = getPickUniformMapCallback(collection);
if (defined(collection._url)) {
modelOptions.cacheKey = collection._url + '#instanced';
}
} else {
modelOptions.vertexShaderLoaded = getVertexShaderNonInstancedCallback(collection);
modelOptions.fragmentShaderLoaded = getFragmentShaderCallback(collection);
modelOptions.uniformMapLoaded = getUniformMapNonInstancedCallback(collection, context);
modelOptions.pickVertexShaderLoaded = getPickVertexShaderNonInstancedCallback(collection);
modelOptions.pickFragmentShaderLoaded = getPickFragmentShaderNonInstancedCallback(collection);
modelOptions.pickUniformMapLoaded = getPickUniformMapCallback(collection);
}
if (defined(collection._url)) {
collection._model = Model.fromGltf(modelOptions);
} else {
collection._model = new Model(modelOptions);
}
}
function updateWireframe(collection) {
if (collection._debugWireframe !== collection.debugWireframe) {
collection._debugWireframe = collection.debugWireframe;
// This assumes the original primitive was TRIANGLES and that the triangles
// are connected for the wireframe to look perfect.
var primitiveType = collection.debugWireframe ? PrimitiveType.LINES : PrimitiveType.TRIANGLES;
var commands = collection._drawCommands;
var length = commands.length;
for (var i = 0; i < length; ++i) {
commands[i].primitiveType = primitiveType;
}
}
}
function updateShowBoundingVolume(collection) {
if (collection.debugShowBoundingVolume !== collection._debugShowBoundingVolume) {
collection._debugShowBoundingVolume = collection.debugShowBoundingVolume;
var commands = collection._drawCommands;
var length = commands.length;
for (var i = 0; i < length; ++i) {
commands[i].debugShowBoundingVolume = collection.debugShowBoundingVolume;
}
}
}
function createCommands(collection, drawCommands, pickCommands) {
var commandsLength = drawCommands.length;
var instancesLength = collection.length;
var allowPicking = collection.allowPicking;
var boundingSphere = collection._boundingSphere;
var cull = collection._cull;
for (var i = 0; i < commandsLength; ++i) {
var drawCommand = DrawCommand.shallowClone(drawCommands[i]);
drawCommand.instanceCount = instancesLength;
drawCommand.boundingVolume = boundingSphere;
drawCommand.cull = cull;
collection._drawCommands.push(drawCommand);
if (allowPicking) {
var pickCommand = DrawCommand.shallowClone(pickCommands[i]);
pickCommand.instanceCount = instancesLength;
pickCommand.boundingVolume = boundingSphere;
pickCommand.cull = cull;
collection._pickCommands.push(pickCommand);
}
}
}
function createBatchIdFunction(batchId) {
return function() {
return batchId;
};
}
function createPickColorFunction(color) {
return function() {
return color;
};
}
function createCommandsNonInstanced(collection, drawCommands, pickCommands) {
// When instancing is disabled, create commands for every instance.
var instances = collection._instances;
var commandsLength = drawCommands.length;
var instancesLength = collection.length;
var allowPicking = collection.allowPicking;
var usesBatchTable = defined(collection._batchTable);
var cull = collection._cull;
for (var i = 0; i < commandsLength; ++i) {
for (var j = 0; j < instancesLength; ++j) {
var drawCommand = DrawCommand.shallowClone(drawCommands[i]);
drawCommand.modelMatrix = new Matrix4(); // Updated in updateCommandsNonInstanced
drawCommand.boundingVolume = new BoundingSphere(); // Updated in updateCommandsNonInstanced
drawCommand.cull = cull;
drawCommand.uniformMap = clone(drawCommand.uniformMap);
if (usesBatchTable) {
drawCommand.uniformMap.a_batchId = createBatchIdFunction(instances[j]._instanceId);
}
collection._drawCommands.push(drawCommand);
if (allowPicking) {
var pickCommand = DrawCommand.shallowClone(pickCommands[i]);
pickCommand.modelMatrix = new Matrix4(); // Updated in updateCommandsNonInstanced
pickCommand.boundingVolume = new BoundingSphere(); // Updated in updateCommandsNonInstanced
pickCommand.cull = cull;
pickCommand.uniformMap = clone(pickCommand.uniformMap);
if (usesBatchTable) {
pickCommand.uniformMap.a_batchId = createBatchIdFunction(instances[j]._instanceId);
} else if (allowPicking) {
var pickId = collection._pickIds[j];
pickCommand.uniformMap.czm_pickColor = createPickColorFunction(pickId.color);
}
collection._pickCommands.push(pickCommand);
}
}
}
}
function updateCommandsNonInstanced(collection) {
var modelCommands = collection._modelCommands;
var commandsLength = modelCommands.length;
var instancesLength = collection.length;
var allowPicking = collection.allowPicking;
var collectionTransform = collection._rtcTransform;
var collectionCenter = collection._center;
for (var i = 0; i < commandsLength; ++i) {
var modelCommand = modelCommands[i];
for (var j = 0; j < instancesLength; ++j) {
var commandIndex = i * instancesLength + j;
var drawCommand = collection._drawCommands[commandIndex];
var instanceMatrix = Matrix4.clone(collection._instances[j]._modelMatrix, scratchMatrix);
instanceMatrix[12] -= collectionCenter.x;
instanceMatrix[13] -= collectionCenter.y;
instanceMatrix[14] -= collectionCenter.z;
instanceMatrix = Matrix4.multiply(collectionTransform, instanceMatrix, scratchMatrix);
var nodeMatrix = modelCommand.modelMatrix;
var modelMatrix = drawCommand.modelMatrix;
Matrix4.multiply(instanceMatrix, nodeMatrix, modelMatrix);
var nodeBoundingSphere = modelCommand.boundingVolume;
var boundingSphere = drawCommand.boundingVolume;
BoundingSphere.transform(nodeBoundingSphere, instanceMatrix, boundingSphere);
if (allowPicking) {
var pickCommand = collection._pickCommands[commandIndex];
Matrix4.clone(modelMatrix, pickCommand.modelMatrix);
BoundingSphere.clone(boundingSphere, pickCommand.boundingVolume);
}
}
}
}
function getModelCommands(model) {
var nodeCommands = model._nodeCommands;
var length = nodeCommands.length;
var drawCommands = [];
var pickCommands = [];
for (var i = 0; i < length; ++i) {
var nc = nodeCommands[i];
if (nc.show) {
drawCommands.push(nc.command);
pickCommands.push(nc.pickCommand);
}
}
return {
draw: drawCommands,
pick: pickCommands
};
}
function updateShadows(collection) {
if (collection.shadows !== collection._shadows) {
collection._shadows = collection.shadows;
var castShadows = ShadowMode.castShadows(collection.shadows);
var receiveShadows = ShadowMode.receiveShadows(collection.shadows);
var drawCommands = collection._drawCommands;
var length = drawCommands.length;
for (var i = 0; i < length; ++i) {
var drawCommand = drawCommands[i];
drawCommand.castShadows = castShadows;
drawCommand.receiveShadows = receiveShadows;
}
}
}
ModelInstanceCollection.prototype.update = function(frameState) {
if (frameState.mode === SceneMode.MORPHING) {
return;
}
if (!this.show) {
return;
}
if (this.length === 0) {
return;
}
var context = frameState.context;
if (this._state === LoadState.NEEDS_LOAD) {
this._state = LoadState.LOADING;
this._instancingSupported = context.instancedArrays;
createModel(this, context);
var that = this;
this._model.readyPromise.otherwise(function(error) {
that._state = LoadState.FAILED;
that._readyPromise.reject(error);
});
}
var instancingSupported = this._instancingSupported;
var model = this._model;
model.update(frameState);
if (model.ready && (this._state === LoadState.LOADING)) {
this._state = LoadState.LOADED;
this._ready = true;
// Expand bounding volume to fit the radius of the loaded model including the model's offset from the center
var modelRadius = model.boundingSphere.radius + Cartesian3.magnitude(model.boundingSphere.center);
this._boundingSphere.radius += modelRadius;
var modelCommands = getModelCommands(model);
this._modelCommands = modelCommands.draw;
if (instancingSupported) {
createCommands(this, modelCommands.draw, modelCommands.pick);
} else {
createCommandsNonInstanced(this, modelCommands.draw, modelCommands.pick);
updateCommandsNonInstanced(this);
}
this._readyPromise.resolve(this);
return;
}
if (this._state !== LoadState.LOADED) {
return;
}
var modeChanged = (frameState.mode !== this._mode);
var modelMatrix = this.modelMatrix;
var modelMatrixChanged = !Matrix4.equals(this._modelMatrix, modelMatrix);
if (modeChanged || modelMatrixChanged) {
this._mode = frameState.mode;
Matrix4.clone(modelMatrix, this._modelMatrix);
var rtcTransform = Matrix4.multiplyByTranslation(this._modelMatrix, this._center, this._rtcTransform);
if (this._mode !== SceneMode.SCENE3D) {
rtcTransform = Transforms.basisTo2D(frameState.mapProjection, rtcTransform, rtcTransform);
}
Matrix4.getTranslation(rtcTransform, this._boundingSphere.center);
}
if (instancingSupported && this._dirty) {
// If at least one instance has moved assume the collection is now dynamic
this._dynamic = true;
this._dirty = false;
// PERFORMANCE_IDEA: only update dirty sub-sections instead of the whole collection
updateVertexBuffer(this);
}
// If any node changes due to an animation, update the commands. This could be inefficient if the model is
// composed of many nodes and only one changes, however it is probably fine in the general use case.
// Only applies when instancing is disabled. The instanced shader automatically handles node transformations.
if (!instancingSupported && (model.dirty || this._dirty || modeChanged || modelMatrixChanged)) {
updateCommandsNonInstanced(this);
}
updateShadows(this);
updateWireframe(this);
updateShowBoundingVolume(this);
var passes = frameState.passes;
var commandList = frameState.commandList;
var commands = passes.render ? this._drawCommands : this._pickCommands;
var commandsLength = commands.length;
for (var i = 0; i < commandsLength; ++i) {
commandList.push(commands[i]);
}
};
ModelInstanceCollection.prototype.isDestroyed = function() {
return false;
};
ModelInstanceCollection.prototype.destroy = function() {
this._model = this._model && this._model.destroy();
var pickIds = this._pickIds;
if (defined(pickIds)) {
var length = pickIds.length;
for (var i = 0; i < length; ++i) {
pickIds[i].destroy();
}
}
return destroyObject(this);
};
return ModelInstanceCollection;
});
| omh1280/cesium | Source/Scene/ModelInstanceCollection.js | JavaScript | apache-2.0 | 43,075 |
initSidebarItems({"fn":[["ball_against_ball","Time Of Impact of two balls under translational movement."],["composite_shape_against_shape","Time Of Impact of a composite shape with any other shape, under translational movement."],["plane_against_support_map","Time Of Impact of a plane with a support-mapped shape under translational movement."],["shape_against_composite_shape","Time Of Impact of any shape with a composite shape, under translational movement."],["support_map_against_plane","Time Of Impact of a plane with a support-mapped shape under translational movement."],["support_map_against_support_map","Time of impacts between two support-mapped shapes under translational movement."],["time_of_impact","Computes the smallest time of impact of two shapes under translational movement."]]}); | nitro-devs/nitro-game-engine | docs/ncollide_geometry/query/time_of_impact_internal/sidebar-items.js | JavaScript | apache-2.0 | 803 |
/*
Copyright 2017 The BioBricks Foundation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
var fs = require('fs')
var methodNotAllowed = require('./method-not-allowed')
var notFound = require('./not-found')
var path = require('path')
var BYTES_PER_LINE = require('../bytes-per-accession')
module.exports = function (request, response, configuration) {
if (request.method === 'GET') {
var number = parseInt(request.params.number)
var file = path.join(configuration.directory, 'accessions')
// Get a file descriptor.
fs.open(file, 'r', function (error, fd) {
/* istanbul ignore if */
if (error) {
request.log.error(error)
response.statusCode = 500
response.end()
} else {
// Calculate the offset where the requested accession's line
// begins, if we have it.
var offset = BYTES_PER_LINE * (number - 1)
// Stat the file and compare its size to the offset for the
// accession number requested.
fs.fstat(fd, function (error, stats) {
/* istanbul ignore if */
if (error) {
request.log.error(error)
response.statusCode = 500
response.end()
fs.close(fd)
} else {
// If the accessions file is too small to have the requested
// accession number, respond 404.
if (stats.size < (offset + BYTES_PER_LINE)) {
notFound(request, response, configuration)
// Otherwise, read the line for the accession from the file,
// starting at the calculated offset.
} else {
var buffer = Buffer.alloc(BYTES_PER_LINE - 1)
fs.read(
fd, buffer, 0, buffer.byteLength, offset,
function (error) {
/* istanbul ignore if */
if (error) {
request.log.error(error)
response.statusCode = 500
response.end()
} else {
// Redirect the client to the publication path.
var split = buffer
.toString()
.split(',')
response.statusCode = 303
response.setHeader(
'Location', configuration.base + 'publications/' + split[1]
)
response.end()
}
fs.close(fd, function () {
// pass
})
}
)
}
}
})
}
})
} else {
methodNotAllowed(response)
}
}
| publicdomainchronicle/public-domain-chronicle | routes/accession.js | JavaScript | apache-2.0 | 3,156 |
'use strict';
/**
* @ngdoc function
* @name sbAdminApp.controller:MainCtrl
* @description
* # MainCtrl
* Controller of the sbAdminApp
*/
angular.module('sbAdminApp')
.controller('MainCtrl', function($scope,$position) {
})
.controller('StoreCtrl',['$scope','$position','$state','XLSXReaderService',function ($scope,$position,$state,XLSXReaderService) {
console.log($state.params.id);
$scope.data = [{"UPC":"test"," Short Description":"test","Long description":"test","Store Price":111111,"Metric (ea or lb) ":12,"Department":"Vegetables","Sub-department ":"Fresh","Synonyms":"legumes"},{"UPC":"test2"," Short Description":"test2","Long description":"test2","Store Price":12222,"Metric (ea or lb) ":43,"Department":"Vegetables","Sub-department ":"Fresh","Synonyms":"legumes"}];
$scope.stores = [
{id:1, name:'Store 1'},
{id:2, name:'Store 2'},
{id:3, name:'Store 3'}
];
$scope.store = {};
$scope.saveStore = function (store) {
console.log(store);
store.id = $scope.stores.length + 1;
$scope.store = store;
$scope.stores.unshift(store);
$scope.store = {};
}
if($state.params.id){
$scope.store = _.find($scope.stores, function(chr) {
return chr.id = $state.params.id;
})
};
$scope.import = function (file) {
$scope.isProcessing = true;
$scope.sheets = [];
$scope.excelFile = file;
XLSXReaderService.readFile($scope.excelFile, true, false).then(function (xlsxData) {
$scope.sheets = xlsxData.sheets;
$scope.json_string = JSON.stringify($scope.sheets["Sheet1"], null, 2);
$scope.json_string = $scope.parseExcelData($scope.json_string);
$scope.data = $scope.json_string;
console.log(JSON.stringify($scope.data));
});
}
$scope.parseExcelData = function (json_string) {
var excelData = JSON.parse(json_string);
var headers = excelData.data[0];
var array = [];
for (var i = 1; i < excelData.data.length; i++) {
var item = excelData.data[i];
var element = {};
for (var j = 0; j < item.length; j++) {
if(item[j]!=null){
var propertyName = headers[j];
element[propertyName] = item[j];
}
}
array.push(element);
}
var list = array;
return list;
}
}]);
| ousmaneo/PULinterface | app/scripts/controllers/main.js | JavaScript | apache-2.0 | 2,493 |
// Copyright 2016 The Oppia Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Primary controller for the collection editor page.
*/
// TODO(bhenning): These constants should be provided by the backend.
oppia.constant(
'COLLECTION_DATA_URL_TEMPLATE', '/collection_handler/data/<collection_id>');
oppia.constant(
'WRITABLE_COLLECTION_DATA_URL_TEMPLATE',
'/collection_editor_handler/data/<collection_id>');
oppia.constant(
'COLLECTION_RIGHTS_URL_TEMPLATE',
'/collection_editor_handler/rights/<collection_id>');
oppia.controller('CollectionEditor', ['$scope',
'WritableCollectionBackendApiService', 'CollectionRightsBackendApiService',
'CollectionObjectFactory', 'SkillListObjectFactory',
'CollectionUpdateService', 'UndoRedoService', 'alertsService', function(
$scope, WritableCollectionBackendApiService,
CollectionRightsBackendApiService, CollectionObjectFactory,
SkillListObjectFactory, CollectionUpdateService, UndoRedoService,
alertsService) {
$scope.collection = null;
$scope.collectionId = GLOBALS.collectionId;
$scope.collectionSkillList = SkillListObjectFactory.create([]);
$scope.isPublic = GLOBALS.isPublic;
// Load the collection to be edited.
WritableCollectionBackendApiService.fetchWritableCollection(
$scope.collectionId).then(
function(collectionBackendObject) {
$scope.collection = CollectionObjectFactory.create(
collectionBackendObject);
$scope.collectionSkillList.setSkills(collectionBackendObject.skills);
}, function(error) {
alertsService.addWarning(
error || 'There was an error loading the collection.');
});
$scope.getChangeListCount = function() {
return UndoRedoService.getChangeCount();
};
// To be used after mutating the prerequisite and/or acquired skill lists.
$scope.updateSkillList = function() {
$scope.collectionSkillList.clearSkills();
$scope.collectionSkillList.addSkillsFromSkillList(
$scope.collection.getSkillList());
$scope.collectionSkillList.sortSkills();
};
// An explicit save is needed to push all changes to the backend at once
// because some likely working states of the collection will cause
// validation errors when trying to incrementally save them.
$scope.saveCollection = function(commitMessage) {
// Don't attempt to save the collection if there are no changes pending.
if (!UndoRedoService.hasChanges()) {
return;
}
WritableCollectionBackendApiService.updateCollection(
$scope.collection.getId(), $scope.collection.getVersion(),
commitMessage, UndoRedoService.getCommittableChangeList()).then(
function(collectionBackendObject) {
$scope.collection = CollectionObjectFactory.create(
collectionBackendObject);
$scope.collectionSkillList.setSkills(collectionBackendObject.skills);
UndoRedoService.clearChanges();
}, function(error) {
alertsService.addWarning(
error || 'There was an error updating the collection.');
});
};
$scope.publishCollection = function() {
// TODO(bhenning): Publishing should not be doable when the exploration
// may have errors/warnings. Publish should only show up if the collection
// is private. This also needs a confirmation of destructive action since
// it is not reversible.
CollectionRightsBackendApiService.setCollectionPublic(
$scope.collectionId, $scope.collection.getVersion()).then(
function() {
// TODO(bhenning): There should be a scope-level rights object used,
// instead. The rights object should be loaded with the collection.
$scope.isPublic = true;
}, function() {
alertsService.addWarning(
'There was an error when publishing the collection.');
});
};
}]);
| sbhowmik89/oppia | core/templates/dev/head/collection_editor/CollectionEditor.js | JavaScript | apache-2.0 | 4,502 |
//Create Tab Group
var tabGroup = Titanium.UI.createTabGroup();
// Variables
var Teas = ['#F5F5DC', '#FFE4B5', '#FFE4C4', '#D2B48C', '#C3b091',
'#c3b091', '#926F5B', '#804000', '#654321', '#3D2B1F'];
allRows = [];
var theColours = Ti.UI.createTableView({});
for (var i=0; i<Teas.length; i++){
theRow = Ti.UI.createTableViewRow({backgroundColor:Teas[i], height:50, TeaColour:Teas[i]});
allRows.push(theRow);
}
theColours.setData(allRows);
var options = Ti.UI.createView({layout: 'vertical'});
var showCamera = Ti.UI.createButton({title: 'Show Camera'});
// TeaSelection Function
function getVerdict(colour){
var indicator = colour.charAt(1);
var msg;
switch(indicator){
case 'F': msg = 'Milky'; break;
case 'D': msg = 'Nice'; break;
case 'C': msg = 'Perfect'; break;
case '9': msg = 'A bit strong'; break;
case '8': msg = 'Builders tea'; break;
case '6': msg = 'Send it back'; break;
case '3': msg = 'No milk here'; break;
}
return msg;
};
function showTeaVerdict(_args){
var teaVerdict = Ti.UI.createWindow({layout:'vertical'});
teaVerdict.backgroundColor = _args;
teaVerdict.msg = getVerdict(_args);
var judgement = Ti.UI.createLabel ({text:teaVerdict.msg, top:'50%'});
var close = Ti.UI.createButton ({title:'Choose Again', top:'25%'});
close.addEventListener('click', function(e){
teaVerdict.close();
teaVerdict = null;
});
teaVerdict.add(judgement);
teaVerdict.add(close);
teaVerdict.open();
}
//Camera Function
function showPhoto(_args) {
thePhoto.setImage(_args.media);
}
// Tab 1
var winTea = Titanium.UI.createWindow({
title:'Select Color',
backgroundColor:'#fff'
});
var tabTea = Titanium.UI.createTab({
title:'TeaSelection',
window:winTea
});
winTea.add(theColours);
// Tab 2
var winCamera = Titanium.UI.createWindow({
title:'Camera',
backgroundColor:'#fff'
});
var tabCamera = Titanium.UI.createTab({
title:'Camera',
window:winCamera
});
winCamera.add(showCamera);
// Add Listener
theColours.addEventListener('click', function(e){showTeaVerdict(e.source.TeaColour);});
showCamera.addEventListener('click', function (e) {
Ti.Media.showCamera({animated: true,
autoHide: true,
saveToPhotoGallery: true,
showControls: true,
mediaTypes: [Ti.Media.MEDIA_TYPE_PHOTO],
success: function(e) {showPhoto(e);}
});
});
// Add Tabs
tabGroup.addTab(tabTea);
tabGroup.addTab(tabCamera);
// Open tabGroup
tabGroup.open(); | Bassim-Nasser/TeaSelectionCamera | Resources/app.js | JavaScript | apache-2.0 | 2,752 |
/*!
* Copyright (C) 2015 SequoiaDB Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
var constants = require('./const');
var Node = require('./node');
var util = require('util');
var ReplicaGroup = function (conn, name, groupId) {
Object.defineProperty(this, 'conn', {
value: conn,
enumerable: false
});
this.name = name;
this.groupId = groupId;
this.isCatalog = (name === constants.CATALOG_GROUP);
};
/** \fn bool Stop()
* \brief Stop the current node
* \return True if succeed or False if fail
* \exception SequoiaDB.Error
* \exception System.Exception
*/
ReplicaGroup.prototype.stop = function (callback) {
this.stopStart(false, callback);
};
/** \fn bool Start()
* \brief Start the current node
* \return True if succeed or False if fail
* \exception SequoiaDB.Error
* \exception System.Exception
*/
ReplicaGroup.prototype.start = function (callback) {
this.stopStart(true, callback);
};
/** \fn var GetNodeNum( SDBConst.NodeStatus status)
* \brief Get the count of node with given status
* \param status The specified status as below:
*
* SDB_NODE_ALL
* SDB_NODE_ACTIVE
* SDB_NODE_INACTIVE
* SDB_NODE_UNKNOWN
* \return The count of node
* \exception SequoiaDB.Error
* \exception System.Exception
*/
ReplicaGroup.prototype.getNodeCount = function (callback) {
this.getDetail(function (err, detail) {
if (err) {
return callback(err);
}
var nodes = detail[constants.FIELD_GROUP];
callback(null, nodes.length || 0);
});
};
/** \fn var GetDetail()
* \brief Get the detail information of current group
* \return The detail information in var object
* \exception SequoiaDB.Error
* \exception System.Exception
*/
ReplicaGroup.prototype.getDetail = function (callback) {
var matcher = {};
matcher[constants.FIELD_GROUPNAME] = this.name;
matcher[constants.FIELD_GROUPID] = this.groupId;
this.conn.getList(constants.SDB_LIST_GROUPS, matcher, {}, {}, function (err, cursor) {
if (err) {
return callback(err);
}
if (cursor) {
cursor.next(function (err, detail) {
if (err) {
return callback(err);
}
if (detail) {
callback(null, detail);
} else {
callback(new Error('SDB_CLS_GRP_NOT_EXIST'));
}
});
} else {
callback(new Error('SDB_SYS'));
}
});
};
/** \fn Node CreateNode(string hostName, var port, string dbpath,
Dictionary<string, string> map)
* \brief Create the replica node
* \param hostName The host name of node
* \param port The port of node
* \param dbpath The database path of node
* \param map The other configure information of node
* \return The Node object
* \exception SequoiaDB.Error
* \exception System.Exception
*/
ReplicaGroup.prototype.createNode = function (hostname, port, dbpath, map, callback) {
if (!hostname || port < 0 || port > 65535 || !dbpath) {
throw new Error('SDB_INVALIDARG');
}
var command = constants.ADMIN_PROMPT + constants.CREATE_CMD + " " +
constants.NODE;
var matcher = {};
matcher[constants.FIELD_GROUPNAME] = this.name;
// TODO: ๅ ้คๅฑๆงไธๅฅฝ
delete map[constants.FIELD_GROUPNAME];
matcher[constants.FIELD_HOSTNAME] = hostname;
delete map[constants.FIELD_HOSTNAME];
matcher[constants.SVCNAME] = '' + port;
delete map[constants.SVCNAME];
matcher[constants.DBPATH] = dbpath;
delete map[constants.DBPATH];
util._extend(matcher, map);
var that = this;
this.conn.sendAdminCommand(command, matcher, {}, {}, {}, function (err) {
if (err) {
return callback(err);
}
that.getNode(hostname, port, callback);
});
};
/** \fn void RemoveNode(string hostName, var port,
var configure)
* \brief Remove the specified replica node
* \param hostName The host name of node
* \param port The port of node
* \param configure The configurations for the replica node
* \exception SequoiaDB.Error
* \exception System.Exception
*/
ReplicaGroup.prototype.removeNode = function (hostname, port, configure, callback) {
if (!hostname || port < 0 || port > 65535) {
throw new Error("SDB_INVALIDARG");
}
var command = constants.ADMIN_PROMPT + constants.REMOVE_CMD + " " +
constants.NODE;
var config = {};
config[constants.FIELD_GROUPNAME] = this.name;
config[constants.FIELD_HOSTNAME] = hostname;
config[constants.SVCNAME] = '' + port;
if (!configure) {
var keys = Object.keys(configure);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if (key === constants.FIELD_GROUPNAME ||
key === constants.FIELD_HOSTNAME ||
key === constants.SVCNAME) {
continue;
}
config[key] = configure[key];
}
}
this.conn.sendAdminCommand(command, config, {}, {}, {}, function (err) {
callback(err);
});
};
/** \fn Node GetMaster()
* \brief Get the master node of current group
* \return The fitted node or null
* \exception SequoiaDB.Error
* \exception System.Exception
*/
ReplicaGroup.prototype.getMaster = function (callback) {
var that = this;
this.getDetail(function (err, detail) {
if (err) {
return callback(err);
}
var primaryNode = detail[constants.FIELD_PRIMARYNODE];
var nodes = detail[constants.FIELD_GROUP];
if (typeof primaryNode !== 'number' || !Array.isArray(nodes)) {
return callback(new Error("SDB_SYS"));
}
for (var i = 0; i < nodes.length; i++) {
var node = nodes[i];
var nodeId = node[constants.FIELD_NODEID];
if (typeof nodeId !== 'number') {
return callback(new Error("SDB_SYS"));
}
if (nodeId === primaryNode) {
var extracted = that.extractNode(node);
return callback(null, extracted);
}
}
callback(null, null);
});
};
/** \fn Node GetSlave()
* \brief Get the slave node of current group
* \return The fitted node or null
* \exception SequoiaDB.Error
* \exception System.Exception
*/
ReplicaGroup.prototype.getSlave = function (callback) {
var that = this;
this.getDetail(function (err, detail) {
if (err) {
return callback(err);
}
var primaryID = detail[constants.FIELD_PRIMARYNODE];
var nodes = detail[constants.FIELD_GROUP];
if (typeof primaryID !== 'number' || !Array.isArray(nodes)) {
return callback(new Error("SDB_SYS"));
}
var slaves = [];
var primaryNode;
for (var i = 0; i < nodes.length; i++) {
var node = nodes[i];
var nodeId = node[constants.FIELD_NODEID];
if (typeof nodeId !== 'number') {
return callback(new Error("SDB_SYS"));
}
if (nodeId !== primaryID) {
slaves.push(node);
} else {
primaryNode = node;
}
}
if (slaves.length > 0) {
// ้ๆบๅไธไธช
var index = (new Date().getTime()) % slaves.length;
callback(null, that.extractNode(nodes[index]));
} else {
callback(null, that.extractNode(primaryNode));
}
});
};
/** \fn Node GetNode(string nodeName)
* \brief Get the node by node name
* \param nodeName The node name
* \return The fitted node or null
* \exception SequoiaDB.Error
* \exception System.Exception
*/
ReplicaGroup.prototype.getNodeByName = function (nodename, callback) {
if (!nodename || nodename.indexOf(constants.NODE_NAME_SERVICE_SEP) === -1) {
throw new Error("SDB_INVALIDARG");
}
var parts = nodename.split(constants.NODE_NAME_SERVICE_SEP);
var hostname = parts[0];
var port = parseInt(parts[1], 10);
if (!hostname || !port) {
throw new Error("SDB_INVALIDARG");
}
this.getNode(hostname, port, callback);
};
/** \fn Node GetNode(string hostName, var port)
* \brief Get the node by host name and port
* \param hostName The host name
* \param port The port
* \return The fitted node or null
* \exception SequoiaDB.Error
* \exception System.Exception
*/
ReplicaGroup.prototype.getNode = function (hostname, port, callback) {
var that = this;
this.getDetail(function (err, detail) {
if (err) {
return callback(err);
}
var nodes = detail[constants.FIELD_GROUP];
if (!Array.isArray(nodes)) {
return callback(new Error("SDB_SYS"));
}
for (var i = 0; i < nodes.length; i++) {
var node = nodes[i];
var _hostname = node[constants.FIELD_HOSTNAME];
if (typeof _hostname !== 'string') {
return callback(new Error("SDB_SYS"));
}
if (hostname === _hostname) {
var extracted = that.extractNode(node);
if (extracted.port === port) {
return callback(null, extracted);
}
}
}
callback(null, null);
});
};
ReplicaGroup.prototype.extractNode = function (node) {
var hostname = node[constants.FIELD_HOSTNAME];
if (typeof hostname !== 'string') {
throw new Error("SDB_SYS");
}
var nodeId = node[constants.FIELD_NODEID];
if (typeof nodeId !== 'number') {
throw new Error("SDB_SYS");
}
var svcs = node[constants.FIELD_SERVICE];
if (!Array.isArray(svcs)) {
throw new Error("SDB_SYS");
}
for (var i = 0; i < svcs.length; i++) {
var svc = svcs[i];
var type = svc[constants.FIELD_SERVICE_TYPE];
if (typeof type !== 'number') {
throw new Error("SDB_SYS");
}
if (type === 0) {
var serviceName = svc[constants.FIELD_NAME];
return new Node(this, hostname, parseInt(serviceName, 10), nodeId);
}
}
return null;
};
ReplicaGroup.prototype.stopStart = function (start, callback) {
var command = constants.ADMIN_PROMPT +
(start ? constants.ACTIVE_CMD
: constants.SHUTDOWN_CMD) + " " + constants.GROUP;
var matcher = {};
matcher[constants.FIELD_GROUPNAME] = this.name;
matcher[constants.FIELD_GROUPID] = this.groupId;
this.conn.sendAdminCommand(command, matcher, {}, {}, {}, function (err, response) {
callback(null, !err);
});
};
module.exports = ReplicaGroup;
| dphdjy/node-sequoiadb | lib/replica_group.js | JavaScript | apache-2.0 | 10,516 |
/*
* Copyright 2010-2011 Research In Motion Limited.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* <div><p>
* The Attendee object is an instance object, where if a new instance is desired, it must be created using the new keyword.
* </p></div>
* @toc {PIM} Attendee
* @BB50+
* @class The Attendee object is used to represent a person who is invited to a calendar appointment.
* @featureID blackberry.pim.Attendee
* @constructor Constructor for a new Attendee object.
* @example
* <script type="text/javascript">
* // Create our Event
* var newAppt = new blackberry.pim.Appointment();
* newAppt.location = "Your office";
* newAppt.summary = "Talk about new project";
* newAppt.freeBusy = 0; // Free
*
* // Create our hour time slot
* var start = new Date();
* newAppt.start = start;
* var end = start.setHours(start.getHours() + 1);
* newAppt.end = end;
*
* // Create Attendee
* var attendees = [];
* var onlyAttendee = new blackberry.pim.Attendee();
* onlyAttendee.address = "john@foo.com";
* onlyAttendee.type = blackberry.pim.Attendee.INVITED;
* attendees.push(onlyAttendee);
*
* newAppt.attendees = attendees;
* newAppt.save();
* </script>
*/
blackberry.pim.Attendee = function() { };
/**
* Event organizer
* @type Number
* @constant
* @BB50+
*/
blackberry.pim.Attendee.ORGANIZER = 0;
/**
* Attendee as been invited.
* @type Number
* @constant
* @BB50+
*/
blackberry.pim.Attendee.INVITED = 1;
/**
* Attendee has accepted the invitation.
* @type Number
* @constant
* @BB50+
*/
blackberry.pim.Attendee.ACCEPTED = 2;
/**
* Attendee has declined the invitation.
* @type Number
* @constant
* @BB50+
*/
blackberry.pim.Attendee.DECLINED = 3;
/**
* Attendee has tentatively accepted the invitation.
* @type Number
* @constant
* @BB50+
*/
blackberry.pim.Attendee.TENTATIVE = 4;
/**
* Indicates the type of a particular attendee. Value can be one of the Attendee types.
* @type Number
* @BB50+
*/
blackberry.pim.Attendee.prototype.type = { };
/**
* Contains the email address of a particular attendee.
* @type String
* @BB50+
*/
blackberry.pim.Attendee.prototype.address = { };
| marek/WebWorks-API-Docs | api/blackberry_pim_Attendee.js | JavaScript | apache-2.0 | 2,878 |
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const diagnostics = tslib_1.__importStar(require("./diagnostics"));
const log = diagnostics.log; // new diagnostics.Logger( __filename );
//import compression = require("./compression");
//export import axios = require("axios");
const axios = tslib_1.__importStar(require("axios"));
exports.axios = axios;
const remote_http_endpoint_1 = require("./_net/remote-http-endpoint");
exports.RemoteHttpEndpoint = remote_http_endpoint_1.RemoteHttpEndpoint;
//module _test {
// describe(__filename, () => {
// describe("EzEndpoint", () => {
// describe("success cases", () => {
// let test: any = it("basic ezEndpoint, roundtrip phantomjscloud", () => {
// const testEzEndpoint = new EzEndpoint<any, any>({ origin: "http://phantomjscloud.com", path: "/api/browser/v2/a-demo-key-with-low-quota-per-ip-address/" }, { timeout: 3000, interval: 100, backoff: 3 }, {}, );
// const targetUrl = "https://example.com";
// const requestPayload = {
// pages: [
// {
// url: targetUrl,
// renderType: "html",
// outputAsJson: true,
// }
// ],
// };
// return testEzEndpoint.post(requestPayload)
// .then((response) => {
// log.assert(response.status === 200, "should get success response", { response });
// log.assert(targetUrl === response.data.pageResponses[0].pageRequest.url, "response contents should contain a value of response.data.pageResponses[0].pageRequest.url that matchest targetUrl", { targetUrl, gotTargetUrl: response.data.pageResponses[0].pageRequest.url, response });
// }, (err) => {
// const axiosErr = err as _axiosDTs.AxiosErrorResponse<void>;
// throw log.error("did not expect an axiosErr", { err });
// });
// });
// // set timeout increase (default=2000ms) https://mochajs.org/#timeouts
// test.timeout(5000);
// });
// describe("fail cases", () => {
// let test: any = it("basic retry, 429 error", () => {
// const testEzEndpoint = new EzEndpoint<void, void>({ origin: "http://phantomjscloud.com", path: "/examples/helpers/statusCode/429" }, { timeout: 1000, interval: 100, backoff: 3 }, {}, );
// return testEzEndpoint.post()
// .then((response) => {
// throw log.errorAndThrowIfFalse(response.status === 429, "should have failed with 429 response", { response });
// }, (err) => {
// const axiosErr = err as _axiosDTs.AxiosErrorResponse<void>;
// if (axiosErr.response != null) {
// log.assert(axiosErr.response.status === 429, "should have failed with 429 response", { axiosErr });
// } else {
// throw log.error("expected a axiosErr but didn't get one", { err })
// }
// });
// })
// // set timeout increase (default=2000ms) https://mochajs.org/#timeouts
// test.timeout(5000);
// test = it("invalid domain", () => {
// const testEzEndpoint = new EzEndpoint<void, void>({ origin: "http://asdfasdfasdfasetasgoud.com", path: "/examples/helpers/statusCode/429" }, { timeout: 1000, interval: 100, backoff: 3 }, {}, );
// return testEzEndpoint.post()
// .then((response) => {
// throw log.errorAndThrowIfFalse(response.status === 429, "should have failed with 429 response", { response });
// }, (err) => {
// //TODO: describe EzEndpoint fail error type, and add error definitions to bluebird
// // // // // export interface AxiosErrorResponse<T> extends Error {
// // // // // /** inherited from the Error object*/
// // // // // name: "Error";
// // // // // /**human readable error message, such as ```getaddrinfo ENOTFOUND moo moo:443``` or ```Request failed with status code 401``` */
// // // // // message: string;
// // // // // /**
// // // // // * config that was provided to `axios` for the request
// // // // // */
// // // // // config: AxiosXHRConfig<T>;
// // // // // /** The server response. ```undefined``` if no response from server (such as invalid url or network timeout */
// // // // // response?: AxiosXHR<T>;
// // // // // /** example ```ETIMEDOUT```, but only set if unable to get response from server. otherwise does not exist (not even undefined!). */
// // // // // code?: string;
// // // // // /** only set if unable to get response from server. otherwise does not exist (not even undefined!). */
// // // // // failure?:{
// // // // // name:string;
// // // // // /**human readable error message, such as ```getaddrinfo ENOTFOUND moo moo:443``` or ```Request failed with status code 401``` */
// // // // // message: string;
// // // // // /** example ```ENOTFOUND```, but only set if unable to get response from server. otherwise does not exist (not even undefined!). */
// // // // // code: string;
// // // // // /** example ```ENOTFOUND```, but only set if unable to get response from server. otherwise does not exist (not even undefined!). */
// // // // // errno: string;
// // // // // /** example ```getaddrinfo```, but only set if unable to get response from server. otherwise does not exist (not even undefined!). */
// // // // // syscall: string;
// // // // // /** only set if unable to get response from server. otherwise does not exist (not even undefined!). */
// // // // // hostname: string;
// // // // // /** only set if unable to get response from server. otherwise does not exist (not even undefined!). */
// // // // // host: string;
// // // // // /** only set if unable to get response from server. otherwise does not exist (not even undefined!). */
// // // // // port: number;
// // // // // };
// });
// })
// // set timeout increase (default=2000ms) https://mochajs.org/#timeouts
// test.timeout(5000);
// });
// });
// describe("axios", () => {
// const targetUrl = "http://phantomjscloud.com/examples/helpers/requestdata";
// const samplePostPayload1 = { hi: 1, bye: "two", inner: { three: 4 } };
// const sampleHeader1 = { head1: "val1" };
// describe("success cases", () => {
// it("basic e2e", () => {
// return axios.post(targetUrl, samplePostPayload1, { headers: sampleHeader1, responseType: "json" })
// .then((axiosResponse) => {
// log.assert(axiosResponse.config != null, "missing property", { axiosResponse });
// log.assert(axiosResponse.data != null, "missing property", { axiosResponse });
// log.assert(axiosResponse.headers != null, "missing property", { axiosResponse });
// log.assert(axiosResponse.status != null, "missing property", { axiosResponse });
// log.assert(axiosResponse.status != null, "missing property", { axiosResponse });
// log.assert(axiosResponse.statusText != null, "missing property", { axiosResponse });
// log.assert(axiosResponse.status === 200, "status code wrong", { axiosResponse });
// return Promise.resolve();
// });
// });
// });
// describe("fail cases", () => {
// it("basic fail e2e", () => {
// return axios.post("http://phantomjscloud.com/examples/helpers/statusCode/400", samplePostPayload1, { headers: sampleHeader1, responseType: "json" })
// .then((axiosResponse) => {
// throw log.error("should have failed with 400 error", { badUrl, axiosResponse });
// })
// .catch((err: _axiosDTs.AxiosErrorResponse<any>) => {
// if (err.response == null) {
// throw log.error("response should be defined", { err });
// }
// log.assert(err.config != null, "missing property config", { err });
// log.assert(err.message != null, "missing property message", { err });
// log.assert(err.name != null, "missing property name", { err });
// log.assert(err.response != null, "missing property response", { err });
// log.assert(err.stack != null, "missing property stack", { err });
// log.assert(err.response.config != null, "missing property response.config", { err });
// log.assert(err.response.data != null, "missing property response.data", { err });
// log.assert(err.response.headers != null, "missing property response.headers", { err });
// log.assert(err.response.status != null, "missing property response.status ", { err });
// log.assert(err.response.statusText != null, "missing property response.statusText", { err });
// log.assert(err.response.status === 400, "wrong status code.", { err });
// return Promise.resolve();
// });
// });
// const badUrl = "http://moo";
// let test: any = it("invlid url", () => {
// return axios.post(badUrl, samplePostPayload1, { headers: sampleHeader1, responseType: "json" })
// .then((axiosResponse) => {
// throw log.error("should have failed with invalid url", { badUrl, axiosResponse });
// })
// .catch((err: _axiosDTs.AxiosErrorResponse<any>) => {
// //log.info("got error as expected", { err });
// return Promise.resolve();
// });
// });
// // set timeout increase (default=2000ms) https://mochajs.org/#timeouts
// test.timeout(5000);
// it("status 401 response", () => {
// return axios.post("http://phantomjscloud.com/examples/helpers/statusCode/401", samplePostPayload1, { headers: sampleHeader1, responseType: "json" })
// .then((axiosResponse) => {
// throw log.error("should have failed with 401 error", { badUrl, axiosResponse });
// })
// .catch((err: _axiosDTs.AxiosErrorResponse<any>) => {
// if (err.response == null) {
// throw log.error("response should be defined", { err });
// }
// log.assert(err.response.status === 401, "wrong status code.", { err });
// return Promise.resolve();
// });
// });
// it("status 429 response", () => {
// return axios.post("http://phantomjscloud.com/examples/helpers/statusCode/429", samplePostPayload1, { headers: sampleHeader1, responseType: "json" })
// .then((axiosResponse) => {
// throw log.error("should have failed with 429 error", { badUrl, axiosResponse });
// })
// .catch((err: _axiosDTs.AxiosErrorResponse<any>) => {
// if (err.response == null) {
// throw log.error("response should be defined", { err });
// }
// log.assert(err.response.status === 429, "wrong status code.", { err });
// return Promise.resolve();
// });
// });
// it("status 500 response", () => {
// return axios.post("http://phantomjscloud.com/examples/helpers/statusCode/500", samplePostPayload1, { headers: sampleHeader1, responseType: "json" })
// .then((axiosResponse) => {
// throw log.error("should have failed with 500 error", { badUrl, axiosResponse });
// })
// .catch((err: _axiosDTs.AxiosErrorResponse<any>) => {
// if (err.response == null) {
// throw log.error("response should be defined", { err });
// }
// log.assert(err.response.status === 500, "wrong status code.", { err });
// return Promise.resolve();
// });
// });
// it("status 503 response", () => {
// return axios.post("http://phantomjscloud.com/examples/helpers/statusCode/503", samplePostPayload1, { headers: sampleHeader1, responseType: "json" })
// .then((axiosResponse) => {
// throw log.error("should have failed with 503 error", { badUrl, axiosResponse });
// })
// .catch((err: _axiosDTs.AxiosErrorResponse<any>) => {
// if (err.response == null) {
// throw log.error("response should be defined", { err });
// }
// log.assert(err.response.status === 503, "wrong status code.", { err });
// return Promise.resolve();
// });
// });
// //it("network timeout", () => {
// // return axios.post("https://localhost:827", samplePostPayload1, { headers: sampleHeader1, responseType: "json" })
// // .then((axiosResponse) => {
// // throw log.error("should have failed with 500 error", { badUrl, axiosResponse });
// // })
// // .catch((err: _axiosDTs.AxiosErrorResponse<any>) => {
// // if (err.response == null) {
// // throw log.error("response should be defined", { err });
// // }
// // log.assert(err.response.status === 500, "wrong status code.", { err });
// // return Promise.resolve();
// // });
// //});
// });
// });
// });
//}
//# sourceMappingURL=net.js.map | Novaleaf/xlib | _obsolete/xlib-v17/built/core/net.js | JavaScript | apache-2.0 | 12,529 |
import {fromJS} from 'immutable';
import MAP_STYLE from '../assets/map-style-basic-v8.json';
// export multi object..
export const polyLayer = fromJS({
id: 'polyLayer',
source: 'polyLayer',
type: 'fill',
interactive: true,
paint: {
'fill-color': '#ffeb3b',
'fill-opacity': 0.8
}
});
export const pointLayer = fromJS({
id: 'point',
source: 'point',
type: 'circle',
paint: {
'circle-radius': 10,
'circle-color': '#ffeb3b'
}
});
export const rasterStyle = fromJS({
"version": 8,
"name": "customRas",
"sources": {
"stamen": {
// "tiles": ["https://stamen-tiles.a.ssl.fastly.net/toner/{z}/{x}/{y}.png"],
"tiles": ["https://huangyixiu.co:3003/proxy/?proxyURI=http://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineStreetPurplishBlue/MapServer/tile/{z}/{y}/{x}"],
// "tiles": ["http://www.google.cn/maps/vt?lyrs=s@702&gl=cn&x={x}&y={y}&z={z}"],
"type": "raster",
'tileSize': 256
}
},
"layers": [
{
'id': 'custom-tms',
'type': 'raster',
'source': 'stamen',
'paint': {}
},
]
})
export const defaultMapStyle = fromJS(MAP_STYLE);
| alex2wong/react-mapglDemo | src/map-style.js | JavaScript | apache-2.0 | 1,235 |
describe('Controller: EditorCtrl', function () {
var $rootScope, $scope, $controller;
beforeEach( module( 'PMTViewer' ) );
beforeEach(inject(function (_$rootScope_, _$controller_) {
$rootScope = _$rootScope_;
$scope = $rootScope.$new();
$controller = _$controller_;
$controller('EditorCtrl', { '$rootScope' : $rootScope, '$scope': $scope });
}));
it('should have a defined title', function () {
expect($scope.page.title).toBeDefined();
});
it('should have a defined sub-title', function () {
expect($scope.page.subtitle).toBeDefined();
});
});
| spatialdev/PMT | Viewer/Application/src/app/editor/editor.spec.js | JavaScript | apache-2.0 | 646 |
/*
* /MathJax/extensions/TeX/noUndefined.js
*
* Copyright (c) 2010 Design Science, Inc.
*
* Part of the MathJax library.
* See http://www.mathjax.org for details.
*
* Licensed under the Apache License, Version 2.0;
* you may not use this file except in compliance with the License.
*
* http://www.apache.org/licenses/LICENSE-2.0
*/
MathJax.Extension["TeX/noUndefined"]={version:"1.1",config:MathJax.Hub.CombineConfig("TeX.noUndefined",{attributes:{mathcolor:"red"}})};MathJax.Hub.Register.StartupHook("TeX Jax Ready",function(){var b=MathJax.Extension["TeX/noUndefined"].config;var a=MathJax.ElementJax.mml;MathJax.InputJax.TeX.Parse.Augment({csUndefined:function(c){this.Push(a.mtext(c).With(b.attributes))}});MathJax.Hub.Startup.signal.Post("TeX noUndefined Ready")});MathJax.Ajax.loadComplete("[MathJax]/extensions/TeX/noUndefined.js");
| AKSW/SlideWiki | slidewiki/libraries/frontend/MathJax/extensions/TeX/noUndefined.js | JavaScript | apache-2.0 | 884 |
exports.setProperty =function(_args){
Ti.App.Properties.setString(_args.name, _args.value)
};
exports.getProperty = function(_args){
return Ti.App.Properties.getString(_args.name)
};
| romanmartinp/CampusApps | Resources/LocalStorage.js | JavaScript | apache-2.0 | 195 |
module.exports = function(config) {
config.set({
files: [
// Each file acts as entry point for the webpack configuration
{ pattern: 'test/*.test.js', watched: false },
{ pattern: 'test/**/*.test.js', watched: false }
],
preprocessors: {
// Add webpack as preprocessor
'test/*.test.js': ['webpack'],
'test/**/*.test.js': ['webpack']
},
webpack: {
// Karma watches the test entry points
// (you don't need to specify the entry option)
// webpack watches dependencies
},
webpackMiddleware: {
stats: 'errors-only'
},
// Which frameworks to use for testing
frameworks: ['jasmine'],
// Reporting strategy
reporters: ['progress'],
// Which browser to use for running tests
browsers: ['Chrome']
});
}; | andry-tino/flowable | karma.config.js | JavaScript | apache-2.0 | 939 |
/* jshint strict: false */
/* global assertTrue, assertFalse, assertEqual, fail,
AQL_EXECUTE, AQL_PARSE, AQL_EXPLAIN, AQL_EXECUTEJSON */
// //////////////////////////////////////////////////////////////////////////////
// / @brief aql test helper functions
// /
// / @file
// /
// / DISCLAIMER
// /
// / Copyright 2011-2012 triagens GmbH, Cologne, Germany
// /
// / Licensed under the Apache License, Version 2.0 (the "License")
// / you may not use this file except in compliance with the License.
// / You may obtain a copy of the License at
// /
// / http://www.apache.org/licenses/LICENSE-2.0
// /
// / Unless required by applicable law or agreed to in writing, software
// / distributed under the License is distributed on an "AS IS" BASIS,
// / WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// / See the License for the specific language governing permissions and
// / limitations under the License.
// /
// / Copyright holder is triAGENS GmbH, Cologne, Germany
// /
// / @author Jan Steemann
// / @author Copyright 2013, triAGENS GmbH, Cologne, Germany
// //////////////////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////////////////
// / @brief normalize a single row result
// //////////////////////////////////////////////////////////////////////////////
let isEqual = require("@arangodb/test-helper").isEqual;
exports.isEqual = isEqual;
function normalizeRow (row, recursive) {
if (row !== null &&
typeof row === 'object' &&
!Array.isArray(row)) {
var keys = Object.keys(row);
keys.sort();
var i, n = keys.length, out = { };
for (i = 0; i < n; ++i) {
var key = keys[i];
if (key[0] !== '_') {
out[key] = row[key];
}
}
return out;
}
if (recursive && Array.isArray(row)) {
row = row.map(normalizeRow);
}
return row;
}
// //////////////////////////////////////////////////////////////////////////////
// / @brief return the parse results for a query
// //////////////////////////////////////////////////////////////////////////////
function getParseResults (query) {
return AQL_PARSE(query);
}
// //////////////////////////////////////////////////////////////////////////////
// / @brief assert a specific error code when parsing a query
// //////////////////////////////////////////////////////////////////////////////
function assertParseError (errorCode, query) {
try {
getParseResults(query);
fail();
} catch (e) {
assertTrue(e.errorNum !== undefined, 'unexpected error format');
assertEqual(errorCode, e.errorNum, 'unexpected error code (' + e.errorMessage + '): ');
}
}
// //////////////////////////////////////////////////////////////////////////////
// / @brief return the results of a query explanation
// //////////////////////////////////////////////////////////////////////////////
function getQueryExplanation (query, bindVars) {
return AQL_EXPLAIN(query, bindVars);
}
// //////////////////////////////////////////////////////////////////////////////
// / @brief return the results of a modify-query
// //////////////////////////////////////////////////////////////////////////////
function getModifyQueryResults (query, bindVars, options = {}) {
var queryResult = AQL_EXECUTE(query, bindVars, options);
return queryResult.stats;
}
// //////////////////////////////////////////////////////////////////////////////
// / @brief return the results of a modify-query
// //////////////////////////////////////////////////////////////////////////////
function getModifyQueryResultsRaw (query, bindVars, options = {}) {
var queryResult = AQL_EXECUTE(query, bindVars, options);
return queryResult;
}
// //////////////////////////////////////////////////////////////////////////////
// / @brief return the results of a query, version
// //////////////////////////////////////////////////////////////////////////////
function getRawQueryResults (query, bindVars, options = {}) {
var finalOptions = Object.assign({ count: true, batchSize: 3000 }, options);
var queryResult = AQL_EXECUTE(query, bindVars, finalOptions);
return queryResult.json;
}
// //////////////////////////////////////////////////////////////////////////////
// / @brief return the results of a query in a normalized way
// //////////////////////////////////////////////////////////////////////////////
function getQueryResults (query, bindVars, recursive, options = {}) {
var result = getRawQueryResults(query, bindVars, options);
if (Array.isArray(result)) {
result = result.map(function (row) {
return normalizeRow(row, recursive);
});
}
return result;
}
// //////////////////////////////////////////////////////////////////////////////
// / @brief assert a specific error code when running a query
// //////////////////////////////////////////////////////////////////////////////
function assertQueryError (errorCode, query, bindVars, options = {}) {
try {
getQueryResults(query, bindVars, options);
fail();
} catch (e) {
assertFalse(e === "fail", "no exception thrown by query");
assertTrue(e.errorNum !== undefined, 'unexpected error format while calling [' + query + ']');
assertEqual(errorCode, e.errorNum, 'unexpected error code (' + e.errorMessage +
" while executing: '" + query + "' expecting: " + errorCode + '): ');
}
}
// //////////////////////////////////////////////////////////////////////////////
// / @brief assert a specific warning running a query
// //////////////////////////////////////////////////////////////////////////////
function assertQueryWarningAndNull (errorCode, query, bindVars) {
var result = AQL_EXECUTE(query, bindVars), i, found = { };
for (i = 0; i < result.warnings.length; ++i) {
found[result.warnings[i].code] = true;
}
assertTrue(found[errorCode]);
assertEqual([ null ], result.json);
}
// //////////////////////////////////////////////////////////////////////////////
// / @brief get a linearized version of an execution plan
// //////////////////////////////////////////////////////////////////////////////
function getLinearizedPlan (explainResult) {
var nodes = explainResult.plan.nodes, i;
var lookup = { }, deps = { };
for (i = 0; i < nodes.length; ++i) {
var node = nodes[i];
lookup[node.id] = node;
var dependency = -1;
if (node.dependencies.length > 0) {
dependency = node.dependencies[0];
}
deps[dependency] = node.id;
}
var current = -1;
var out = [];
while (true) {
if (!deps.hasOwnProperty(current)) {
break;
}
var n = lookup[deps[current]];
current = n.id;
out.push(n);
}
return out;
}
function getCompactPlan (explainResult) {
var out = [];
function buildExpression (node) {
var out = node.type;
if (node.hasOwnProperty('name')) {
out += '[' + node.name + ']';
}
if (node.hasOwnProperty('value')) {
out += '[' + node.value + ']';
}
if (Array.isArray(node.subNodes)) {
out += '(';
node.subNodes.forEach(function (node, i) {
if (i > 0) {
out += ', ';
}
out += buildExpression(node);
});
out += ')';
}
return out;
}
getLinearizedPlan(explainResult).forEach(function (node) {
var data = { type: node.type };
if (node.expression) {
data.expression = buildExpression(node.expression);
}
if (node.outVariable) {
data.outVariable = node.outVariable.name;
}
out.push(data);
});
return out;
}
function findExecutionNodes (plan, nodeType) {
let what = plan;
if (plan.hasOwnProperty('plan')) {
what = plan.plan;
}
return what.nodes.filter((node) => nodeType === undefined || node.type === nodeType);
}
function findReferencedNodes (plan, testNode) {
var matches = [];
if (testNode.elements) {
testNode.elements.forEach(function (element) {
plan.plan.nodes.forEach(function (node) {
if (node.hasOwnProperty('outVariable') &&
node.outVariable.id ===
element.inVariable.id) {
matches.push(node);
}
});
});
} else {
plan.plan.nodes.forEach(function (node) {
if (node.outVariable.id === testNode.inVariable.id) {
matches.push(node);
}
});
}
return matches;
}
function getQueryMultiplePlansAndExecutions (query, bindVars, testObject, debug) {
var printYaml = function (plan) {
require('internal').print(require('js-yaml').safeDump(plan));
};
var i;
var plans = [];
var allPlans = [];
var results = [];
var resetTest = false;
var paramNone = { optimizer: { rules: [ '-all' ]}, verbosePlans: true};
var paramAllPlans = { allPlans: true, verbosePlans: true};
if (testObject !== undefined) {
resetTest = true;
}
if (debug === undefined) {
debug = false;
}
// first fetch the unmodified version
if (debug) {
require('internal').print('Analyzing Query unoptimized: ' + query);
}
plans[0] = AQL_EXPLAIN(query, bindVars, paramNone);
// then all of the ones permuted by by the optimizer.
if (debug) {
require('internal').print('Unoptimized Plan (0):');
printYaml(plans[0]);
}
allPlans = AQL_EXPLAIN(query, bindVars, paramAllPlans);
for (i = 0; i < allPlans.plans.length; i++) {
if (debug) {
require('internal').print('Optimized Plan [' + (i + 1) + ']:');
printYaml(allPlans.plans[i]);
}
plans[i + 1] = { plan: allPlans.plans[i]};
}
// Now execute each of these variations.
for (i = 0; i < plans.length; i++) {
if (debug) {
require('internal').print('Executing Plan No: ' + i + '\n');
}
if (resetTest) {
if (debug) {
require('internal').print('\nFLUSHING\n');
}
testObject.tearDown();
testObject.setUp();
if (debug) {
require('internal').print('\n' + i + ' FLUSH DONE\n');
}
}
results[i] = AQL_EXECUTEJSON(plans[i].plan, paramNone);
// ignore these statistics for comparisons
delete results[i].stats.scannedFull;
delete results[i].stats.scannedIndex;
delete results[i].stats.cursorsCreated;
delete results[i].stats.cursorsRearmed;
delete results[i].stats.filtered;
delete results[i].stats.executionTime;
delete results[i].stats.httpRequests;
delete results[i].stats.peakMemoryUsage;
delete results[i].stats.fullCount;
if (debug) {
require('internal').print('\n' + i + ' DONE\n');
}
}
if (debug) {
require('internal').print('done\n');
}
return {'plans': plans, 'results': results};
}
function removeAlwaysOnClusterRules (rules) {
return rules.filter(function (rule) {
return ([ 'distribute-filtercalc-to-cluster', 'scatter-in-cluster', 'distribute-in-cluster', 'remove-unnecessary-remote-scatter', 'parallelize-gather' ].indexOf(rule) === -1);
});
}
function removeClusterNodes (nodeTypes) {
return nodeTypes.filter(function (nodeType) {
return ([ 'ScatterNode', 'GatherNode', 'DistributeNode', 'RemoteNode' ].indexOf(nodeType) === -1);
});
}
function removeClusterNodesFromPlan (nodes) {
return nodes.filter(function (node) {
return ([ 'ScatterNode', 'GatherNode', 'DistributeNode', 'RemoteNode' ].indexOf(node.type) === -1);
});
}
/// @brief recursively removes keys named "estimatedCost" or "selectivityEstimate" of a given object
/// used in tests where we do not want to test those values because of floating-point values used in "AsserEqual"
/// This method should only be used where we explicitly don't want to test those values.
function removeCost (obj) {
if (Array.isArray(obj)) {
return obj.map(removeCost);
} else if (typeof obj === 'object') {
let result = {};
for (var key in obj) {
if (obj.hasOwnProperty(key) &&
key !== "estimatedCost" && key !== "selectivityEstimate") {
result[key] = removeCost(obj[key]);
}
}
return result;
} else {
return obj;
}
}
exports.getParseResults = getParseResults;
exports.assertParseError = assertParseError;
exports.getQueryExplanation = getQueryExplanation;
exports.getModifyQueryResults = getModifyQueryResults;
exports.getModifyQueryResultsRaw = getModifyQueryResultsRaw;
exports.getRawQueryResults = getRawQueryResults;
exports.getQueryResults = getQueryResults;
exports.assertQueryError = assertQueryError;
exports.assertQueryWarningAndNull = assertQueryWarningAndNull;
exports.getLinearizedPlan = getLinearizedPlan;
exports.getCompactPlan = getCompactPlan;
exports.findExecutionNodes = findExecutionNodes;
exports.findReferencedNodes = findReferencedNodes;
exports.getQueryMultiplePlansAndExecutions = getQueryMultiplePlansAndExecutions;
exports.removeAlwaysOnClusterRules = removeAlwaysOnClusterRules;
exports.removeClusterNodes = removeClusterNodes;
exports.removeClusterNodesFromPlan = removeClusterNodesFromPlan;
exports.removeCost = removeCost;
| arangodb/arangodb | js/server/modules/@arangodb/aql-helper.js | JavaScript | apache-2.0 | 12,946 |
var Pagination = Pagination || function(container, goto) {
"use strict";
var $pg = $(container);
var span = 5;
$pg.on("click", "a", function() {
event.preventDefault();
var page = $(this).prop("id");
goto(page);
});
this.render = function(pageInfo) {
var pageCount = pageInfo.pageCount;
var page = pageInfo.page;
var html = [];
if (page > 1) {
html.push("<a href='#' id='{0}'><span class='glyphicon glyphicon-chevron-left'></span></a>".build(page-1));
}
var start = page - span < 1 ? 1 : page - span;
var end = page + span > pageCount ? pageCount : page + span;
for (var i = start; i <= end; i++) {
if (i === page) {
html.push("<b>{0}</b>".build(i));
} else {
html.push("<a href='#' id='{0}'>{1}</a>".build(i, i));
}
}
if (page < pageCount) {
html.push("<a href='#' id='{0}'><span class='glyphicon glyphicon-chevron-right'></span></a>".build(page+1));
}
$pg.html(html.join(""));
$pg.show();
};
this.hide = function() {
$pg.hide();
};
};
| idf/DocumentMiner | km-web/src/main/webapp/js/km_v2/pagination.js | JavaScript | apache-2.0 | 1,225 |
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// ** This file is automatically generated by gapic-generator-typescript. **
// ** https://github.com/googleapis/gapic-generator-typescript **
// ** All changes to this file may be overwritten. **
'use strict';
const path = require('path');
const {assert} = require('chai');
const cp = require('child_process');
const {describe, it} = require('mocha');
const execSync = cmd => cp.execSync(cmd, {encoding: 'utf-8'});
const cwd = path.join(__dirname, '..');
const project = process.env.GCLOUD_PROJECT;
describe('Quickstart', () => {
it('should run quickstart', async () => {
const output = execSync(`node ./quickstart.js ${project} us-west1-b`, {
cwd,
});
assert.match(output, /instance: projects/);
});
});
| googleapis/nodejs-notebooks | samples/test/quickstart.js | JavaScript | apache-2.0 | 1,296 |
/**
* Created by BlueX on 6/11/16.
*/
angular
.module('TK-WEB-PITCH')
.factory('ConstantFactory', function(){
//var API_URL = 'http://127.0.0.1:8888/TK-API/';
var API_URL = 'http://api-test.tarangkhmer.com/';
// return $http.get('http://192.168.1.100:8888/TK-API/sportclubs.json', config);
return {
API_URL: API_URL
}
}); | TKSite-KH/TK-WEB-PITCH | js/factories/ConstantFactory.js | JavaScript | apache-2.0 | 404 |
๏ปฟdefine(
({
addLayer: "ใฌใคใคใผใฎ่ฟฝๅ ",
layerName: "ใฌใคใคใผ",
layerRefresh: "ๆดๆฐ",
layerLabel: "ใฉใใซ",
actions: "ๆไฝ",
popupOk: "OK",
popupCancel: "ใญใฃใณใปใซ",
mainPanelTextPlaceholder: "ไพ: ้ซ้้่ทฏใฎ็ถๆ
",
invalidInterval: "ๆฐๅญใฎใฟใใตใใผใใใใฆใใพใใ",
uploadImage: "็ปๅใฎใขใใใญใผใ",
iconColumnText: "ใขใคใณใณ",
refreshInterval: "1 \'ๅๅไฝใฎๆ้ใจใใฆ่ฉไพกใใใพใใ\'",
refreshIntervalTitle: "ๅๅไฝใฎๆ้ใจใใฆ่ฉไพกใใใพใใ",
mainPanelText: "ใกใคใณ ใใใซใฎใใญในใ",
mainPanelIcon: "ใกใคใณ ใใใซใฎ็ปๅ",
refreshIntervalInstruction: "ๆดๆฐ้้",
optionsText: "ใชใใทใงใณ",
symbolOptionsText: "ใทใณใใซใฎใชใใทใงใณ",
iconOptionsText: "ใขใคใณใณใฎใชใใทใงใณ",
sympolPopupTitle: "ใทใณใใซใฎ่จญๅฎ",
rdoLayer: "ใฌใคใคใผ ใทใณใใซ",
rdoCustom: "ใซในใฟใ ใทใณใใซ",
chkCluster: "ใฏใฉในใฟใชใณใฐใฎๆๅนๅ",
defineClusterSymbol: "ใฏใฉในใฟใผ ใทใณใใซ",
defineThemeClusterSymbol: "ใใผใใฎใฏใฉในใฟใผ ใทใณใใซ",
rdoEsri: "Esri ใทใณใใซ",
rdoLayerIcon: "ใทใณใใซใใขใคใณใณใจใใฆไฝฟ็จ",
rdoCustomIcon: "ใซในใฟใ ใขใคใณใณใฎใขใใใญใผใ",
editCustomSymbol: "ใซในใฟใ ใทใณใใซใฎ็ทจ้",
editCustomIcon: "ใซในใฟใ ใขใคใณใณใฎ็ทจ้",
missingRefreshValue: "ๆดๆฐ้้ใฎๅคใๅ
ฅๅใใฆใใ ใใใ",
panelIconOption: "ใใใซใฎใใใใผใฎ่กจ็คบ",
enableRefresh: "ใฌใคใคใผใฎๆดๆฐใฎๆๅนๅ",
disableRefresh: "ใฌใคใคใผใฎๆดๆฐใฏใใฃใผใใฃ ใณใฌใฏใทใงใณใงใฎใฟใตใใผใใใใฆใใพใ",
layer_type_not_supported: "ใฌใคใคใผ ใฟใคใใฏใตใใผใใใใฆใใพใใ: "
})
);
| fiskinator/WAB2.0_JBox_MutualAid | widgets/InfoSummary/setting/nls/ja/strings.js | JavaScript | apache-2.0 | 1,955 |
/* Copyright (C) 2016 R&D Solutions Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
var path = require('path');
var gulp = require('gulp');
var conf = require('./conf');
var $ = require('gulp-load-plugins')();
var wiredep = require('wiredep').stream;
var _ = require('lodash');
var browserSync = require('browser-sync');
gulp.task('inject-reload', ['inject'], function () {
browserSync.reload();
});
gulp.task('inject', ['scripts'], function () {
var injectStyles = gulp.src([
path.join(conf.paths.src, '/app/**/*.css')
], {read: false});
var injectScripts = gulp.src([
path.join(conf.paths.src, '/app/**/*.main.js'),
path.join(conf.paths.src, '/app/**/*.js'),
path.join('!' + conf.paths.src, '/app/dataTables/*.js'),
path.join('!' + conf.paths.src, '/app/**/bootstrap.js'),
path.join('!' + conf.paths.src, '/app/**/quick-sidebar.js'),
path.join('!' + conf.paths.src, '/app/**/app.js'),
path.join('!' + conf.paths.src, '/app/**/layout.js'),
path.join('!' + conf.paths.src, '/app/**/*.spec.js'),
path.join('!' + conf.paths.src, '/app/**/*.mock.js'),
path.join('!' + conf.paths.src, '/app/**/jstree.min.js'),
path.join('!' + conf.paths.src, '/app/**/ngJsTree.min.js'),
path.join('!' + conf.paths.src, '/app/**/ng-infinite-scroll.min.js'),
path.join('!' + conf.paths.src, '/app/**/bootstrap-switch.js')
])
.pipe($.angularFilesort()).on('error', conf.errorHandler('AngularFilesort'));
// var injectCustomScripts = gulp.src([
// path.join(conf.paths.src, '/app/js/app.js'),
// path.join(conf.paths.src, '/app/js/layout.js'),
// path.join(conf.paths.src, '/app/js/quick-sidebar.js')
// ]).pipe($.angularFilesort()).on('error', conf.errorHandler('AngularFilesort'));
var injectOptions = {
ignorePath: [conf.paths.src, path.join(conf.paths.tmp, '/serve')],
addRootSlash: false
};
return gulp.src(path.join(conf.paths.src, '/*.html'))
.pipe($.inject(injectStyles, injectOptions))
.pipe($.inject(injectScripts, injectOptions))
.pipe(wiredep(_.extend({}, conf.wiredep)))
.pipe(gulp.dest(path.join(conf.paths.tmp, '/serve')));
});
| rndsolutions/hawkcd | Server/ui/gulp/inject.js | JavaScript | apache-2.0 | 2,701 |
๏ปฟdefine(
({
map: {
error: "Karte kann nicht erstellt werden",
mouseToolTip: "Klicken Sie auf die Karte, um den Service zu รผberprรผfen"
},
geocoder: {
defaultText: "Geben Sie eine Adresse oder einen Point of Interest ein"
},
error: {
layerNotFound: "Layer ist nicht in der Webkarte enthalten",
fieldNotFound: "Feld nicht gefunden",
popupNotSet: "Pop-up ist fรผr diesen Layer nicht aktiviert",
noLayersSet: "In der Konfiguration wurden keine Layer definiert; das Suchfeld funktioniert nicht"
},
page: {
title: "Informationssuche",
},
splashscreen: {
buttonText: "OK",
},
ui:{
basemapButton: "Grundkarte"
},
popup: {
urlMoreInfo: "Weitere Informationen"
}
})
); | MikeMillerGIS/information-lookup | js/nls/de/resources.js | JavaScript | apache-2.0 | 916 |
/**
* @license
* Copyright 2019 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
goog.provide('Main');
// Core
// Either require 'Blockly.requires', or just the components you use:
goog.require('Blockly');
goog.require('Blockly.geras.Renderer');
goog.require('Blockly.VerticalFlyout');
// Blocks
goog.require('Blockly.libraryBlocks');
goog.require('Blockly.libraryBlocks.testBlocks');
Main.init = function() {
Blockly.inject('blocklyDiv', {
'toolbox': document.getElementById('toolbox')
});
};
window.addEventListener('load', Main.init);
| rachel-fenichel/blockly | tests/compile/main.js | JavaScript | apache-2.0 | 555 |
/*
* Sample Window
*/
function SampleWindow(navController){
/*
* essentials
*/
var win = Titanium.UI.createWindow({
top: ULA_WIN_TOP,
title: 'Sample Window',
backgroundColor: 'red'
});
var rootView = Titanium.UI.createView({
top: 10, bottom: 10, left: 10, right: 10,
backgroundColor: 'blue',
layout: 'vertical'
});
/*
* components
*/
var lblTitle = Titanium.UI.createLabel({
text: 'This is Sample window',
color: 'black',
font: ULA_FONT_A,
top: 100
});
var btnClose =Titanium.UI.createButton({
title: 'Close',
color: 'black',
height: 60,
width: 100,
top: 20,
});
btnClose.addEventListener('click',function(e){
_c('btnClosed clicked');
navController.back(1);
});
/*
* heirarchy
*/
rootView.add(lblTitle);
win.add(rootView);
win.rightNavButton = btnClose;
return win;
}
module.exports = SampleWindow;
| trs-mark/ula | Resources/ui/SampleWindow.js | JavaScript | apache-2.0 | 881 |
'use strict';
angular.module('footierepoApp').controller('FixtureDialogController',
['$scope', '$stateParams', '$uibModalInstance', 'entity', 'Fixture',
function($scope, $stateParams, $uibModalInstance, entity, Fixture) {
entity.kickOff = Date.parse(entity.kickOff);
$scope.fixture = entity;
$scope.load = function(id) {
Fixture.get({id : id}, function(result) {
result.kickOff = Date.parse(result.kickOff);
$scope.fixture = result;
});
};
$scope.$watch('fixture.kickOff', function(newval, oldval) {
if (! (newval instanceof Date)) {
$scope.fixture.kickOff = new Date(Date.parse(newval));
}
})
var onSaveSuccess = function (result) {
$scope.$emit('footierepoApp:fixtureUpdate', result);
$uibModalInstance.close(result);
$scope.isSaving = false;
};
var onSaveError = function (result) {
$scope.isSaving = false;
};
$scope.save = function () {
$scope.isSaving = true;
$scope.fixture.kickOff = $scope.fixture.kickOff.getTime()/1000;
if ($scope.fixture.id != null) {
Fixture.update($scope.fixture, onSaveSuccess, onSaveError);
} else {
Fixture.save($scope.fixture, onSaveSuccess, onSaveError);
}
};
$scope.clear = function() {
$uibModalInstance.dismiss('cancel');
};
$scope.datePickerForKickOff = {};
$scope.datePickerForKickOff.status = {
opened: false
};
$scope.datePickerForKickOffOpen = function($event) {
$scope.datePickerForKickOff.status.opened = true;
};
}]);
| alex-charos/footie-predictions | src/main/webapp/scripts/app/entities/fixture/fixture-dialog.controller.js | JavaScript | apache-2.0 | 1,857 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import angular from 'angular';
export class IgniteFormField {
static animName = 'ignite-form-field__error-blink';
static eventName = 'webkitAnimationEnd oAnimationEnd msAnimationEnd animationend';
static $inject = ['$element', '$scope'];
constructor($element, $scope) {
Object.assign(this, {$element});
this.$scope = $scope;
}
$postLink() {
this.onAnimEnd = () => this.$element.removeClass(IgniteFormField.animName);
this.$element.on(IgniteFormField.eventName, this.onAnimEnd);
}
$onDestroy() {
this.$element.off(IgniteFormField.eventName, this.onAnimEnd);
this.$element = this.onAnimEnd = null;
}
notifyAboutError() {
if (this.$element) this.$element.addClass(IgniteFormField.animName);
}
/**
* Exposes control in $scope
* @param {ng.INgModelController} control
*/
exposeControl(control, name = '$input') {
this.$scope[name] = control;
this.$scope.$on('$destroy', () => this.$scope[name] = null);
}
}
export default angular.module('ignite-console.page-configure.validation', [])
.directive('pcNotInCollection', function() {
class Controller {
/** @type {ng.INgModelController} */
ngModel;
/** @type {Array} */
items;
$onInit() {
this.ngModel.$validators.notInCollection = (item) => {
if (!this.items) return true;
return !this.items.includes(item);
};
}
$onChanges() {
this.ngModel.$validate();
}
}
return {
controller: Controller,
require: {
ngModel: 'ngModel'
},
bindToController: {
items: '<pcNotInCollection'
}
};
})
.directive('pcInCollection', function() {
class Controller {
/** @type {ng.INgModelController} */
ngModel;
/** @type {Array} */
items;
/** @type {string} */
pluck;
$onInit() {
this.ngModel.$validators.inCollection = (item) => {
if (!this.items) return false;
const items = this.pluck ? this.items.map((i) => i[this.pluck]) : this.items;
return Array.isArray(item)
? item.every((i) => items.includes(i))
: items.includes(item);
};
}
$onChanges() {
this.ngModel.$validate();
}
}
return {
controller: Controller,
require: {
ngModel: 'ngModel'
},
bindToController: {
items: '<pcInCollection',
pluck: '@?pcInCollectionPluck'
}
};
})
.directive('pcPowerOfTwo', function() {
class Controller {
/** @type {ng.INgModelController} */
ngModel;
$onInit() {
this.ngModel.$validators.powerOfTwo = (value) => {
return !value || ((value & -value) === value);
};
}
}
return {
controller: Controller,
require: {
ngModel: 'ngModel'
},
bindToController: true
};
})
.directive('bsCollapseTarget', function() {
return {
require: {
bsCollapse: '^^bsCollapse'
},
bindToController: true,
controller: ['$element', '$scope', function($element, $scope) {
this.open = function() {
const index = this.bsCollapse.$targets.indexOf($element);
const isActive = this.bsCollapse.$targets.$active.includes(index);
if (!isActive) this.bsCollapse.$setActive(index);
};
this.$onDestroy = () => this.open = $element = null;
}]
};
})
.directive('ngModel', ['$timeout', function($timeout) {
return {
require: ['ngModel', '?^^bsCollapseTarget', '?^^igniteFormField', '?^^panelCollapsible'],
link(scope, el, attr, [ngModel, bsCollapseTarget, igniteFormField, panelCollapsible]) {
const off = scope.$on('$showValidationError', (e, target) => {
if (target !== ngModel) return;
ngModel.$setTouched();
bsCollapseTarget && bsCollapseTarget.open();
panelCollapsible && panelCollapsible.open();
$timeout(() => {
if (el[0].scrollIntoViewIfNeeded)
el[0].scrollIntoViewIfNeeded();
else
el[0].scrollIntoView();
if (!attr.bsSelect) $timeout(() => el[0].focus());
igniteFormField && igniteFormField.notifyAboutError();
});
});
}
};
}])
.directive('igniteFormField', function() {
return {
restrict: 'C',
controller: IgniteFormField,
scope: true
};
})
.directive('isValidJavaIdentifier', ['IgniteLegacyUtils', function(LegacyUtils) {
return {
link(scope, el, attr, ngModel) {
ngModel.$validators.isValidJavaIdentifier = (value) => LegacyUtils.VALID_JAVA_IDENTIFIER.test(value);
},
require: 'ngModel'
};
}])
.directive('notJavaReservedWord', ['IgniteLegacyUtils', function(LegacyUtils) {
return {
link(scope, el, attr, ngModel) {
ngModel.$validators.notJavaReservedWord = (value) => !LegacyUtils.JAVA_KEYWORDS.includes(value);
},
require: 'ngModel'
};
}]);
| endian675/ignite | modules/web-console/frontend/app/components/page-configure/components/pcValidation.js | JavaScript | apache-2.0 | 6,803 |
Template.addComment.events({
// press enter on input
'keyup #addcomment': function(event) {
if (event.which === 13) {
event.stopPropagation();
const comment = event.target.value;
if (comment) {
event.target.value = '';
const userName = Meteor.users.findOne().username;
const pageId = Pages.findOne().slug;
Meteor.call('addComment', comment, userName, pageId, function(err, res) {
if (err) {
alert(err);
}
});
}
return false;
}
},
'click #submitcomment': function() {
const commentBox = document.querySelector('#addcomment');
if (commentBox.value) {
const comment = commentBox.value;
commentBox.value = '';
const userName = Meteor.users.findOne().username;
const pageId = Pages.findOne().slug;
Meteor.call('addComment', comment, userName, pageId, function(err, res) {
if (err) {
alert(err);
}
});
}
return false;
}
}); | metroidhq/metroidhq | client/templates/discussion/addComment/addComment.js | JavaScript | apache-2.0 | 1,026 |
(function (w) {
var MIN_LENGTH = 4;
if (w.self != w.top) {
return;
}
function colorize(config) {
if ((config.enabled && config.disallowed && config.disallowed.indexOf(w.location.hostname)!== -1) ||
(!config.enabled && (!config.allowed || config.allowed.indexOf(w.location.hostname)=== -1))) return;
var freqRus = {}, freqEng = {};
var rus = config.charsets.indexOf("rus")!==-1;
var eng = config.charsets.indexOf("eng")!==-1;
var maxFreq = (config.status == 3 ? 1:2);
var patternRus = /[^ะฐ-ัั]/g
var patternEng = /[^a-z]/g
var patternBoth = /[^a-zะฐ-ัั]/g
if (!rus && !eng) return;
if (rus && !eng) patternCurrent = patternRus;
else if (!rus && eng) patternCurrent = patternEng;
else patternCurrent = patternBoth;
function collect(text, frequences, pattern) {
var words = text.split(/\s+/);
for (var j = 0; j < words.length; j++) {
var current = words[j].toLowerCase().replace(pattern,'');
if (!current || current.length < MIN_LENGTH) continue;
if (!frequences[current]) frequences[current] = 1;
else frequences[current] += 1;
}
return frequences;
}
function remove(o, max) {
var n = {};
for (var key in o) if (o[key] <= max) n[key] = o[key];
return n;
}
function removeUseless() {
freqRus = remove(freqRus, maxFreq);
freqEng = remove(freqEng, maxFreq);
}
function stat(element) {
if (/(script|style)/i.test(element.tagName)) return;
if (element.nodeType === Node.ELEMENT_NODE && element.childNodes.length > 0)
for (var i = 0; i < element.childNodes.length; i++)
stat(element.childNodes[i]);
if (element.nodeType === Node.TEXT_NODE && (/\S/.test(element.nodeValue))) {
if (rus) collect(element.nodeValue, freqRus, patternRus);
if (eng) collect(element.nodeValue, freqEng, patternEng);
}
}
function newNode(code) { // code here is total count of the word, only 1 and 2 are used for Russian alphabet and 1+10 and 2+10 for English
var node = w.document.createElement(config.status == 3 ? 'strong' : 'span');
node.className = 'nlc47';
if (config.status == 2 && code !== 1 && code !== 11) node.style.color = '#999';
if (config.status == 2 || (config.status == 1 && (code === 1 || code === 11))) node.style.fontWeight = '700';
if (config.status == 1) node.style.color = code > 2 ? '#449' : '#494';
return node;
}
function markup(element, initial, pattern) {
if (/(script|style)/i.test(element.tagName)) return;
if (element.nodeType === Node.ELEMENT_NODE && element.childNodes.length > 0) {
var freq = {};
for (var i = 0; i < element.childNodes.length; i++) {
freq = markup(element.childNodes[i], freq, pattern);
}
if (freq && freq.length !== 0) {
var efreq = [];
var total = 0;
for (var key in freq) {
if (freqRus[key]) efreq.push([key, freqRus[key]]);
if (freqEng[key]) efreq.push([key, freqEng[key] + 10]);
}
efreq.sort(function(a, b) {return a[0].length - b[0].length});
var max = element.childNodes.length*efreq.length*2;
for (var i = 0; i < element.childNodes.length; i++) {
if (total++ > max) break;
if (element.childNodes[i].nodeType === Node.TEXT_NODE) {
var minPos = -1, minJ = -1;
for (var j in efreq) {
key = efreq[j][0];
var pos = element.childNodes[i].nodeValue.toLowerCase().indexOf(key);
if (pos >= 0 && (minJ === -1 || minPos>pos)) { minPos = pos; minJ = j; }
}
if (minPos !== -1) {
key = efreq[minJ][0]; val = efreq[minJ][1];
var spannode = newNode(val);
var middlebit = element.childNodes[i].splitText(minPos);
var endbit = middlebit.splitText(key.length);
var middleclone = middlebit.cloneNode(true);
spannode.appendChild(middleclone);
element.replaceChild(spannode, middlebit);
}
}
}
}
}
if (element.nodeType === Node.TEXT_NODE && (/\S/.test(element.nodeValue))) {
return collect(element.nodeValue, initial, pattern);
}
return initial;
}
stat(w.document.getElementsByTagName('html')[0]);
removeUseless();
markup(w.document.getElementsByTagName('html')[0], {}, patternCurrent);
}
function clean() {
var affected = w.document.querySelectorAll(".nlc47");
if (!affected.length) return;
for (var i=0;i<affected.length;i++) {
affected[i].outerHTML = affected[i].innerHTML;
}
}
function loadAndColorize() {
chrome.storage.sync.get(['status', 'enabled', 'charsets', 'allowed', 'disallowed'], colorize);
}
chrome.runtime.onMessage.addListener(function(msg, sender, response) {
if (msg.action && msg.action == "refresh") {clean(); loadAndColorize(); }
if (msg.action && msg.action == "getHost") response({host:w.location.hostname});
});
loadAndColorize();
})(window); | parsifal-47/nalacol | source/content.js | JavaScript | bsd-2-clause | 4,868 |
/**
* Copyright 2016 Telerik AD
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
(function(f){
if (typeof define === 'function' && define.amd) {
define(["kendo.core"], f);
} else {
f();
}
}(function(){
(function( window, undefined ) {
kendo.cultures["tg-Cyrl"] = {
name: "tg-Cyrl",
numberFormat: {
pattern: ["-n"],
decimals: 2,
",": "ย ",
".": ",",
groupSize: [3],
percent: {
pattern: ["-n%","n%"],
decimals: 2,
",": "ย ",
".": ",",
groupSize: [3],
symbol: "%"
},
currency: {
name: "",
abbr: "",
pattern: ["-n $","n $"],
decimals: 2,
",": "ย ",
".": ",",
groupSize: [3],
symbol: "ัะผะฝ"
}
},
calendars: {
standard: {
days: {
names: ["ัะบัะฐะฝะฑะต","ะดััะฐะฝะฑะต","ัะตัะฐะฝะฑะต","ัะพััะฐะฝะฑะต","ะฟะฐะฝาทัะฐะฝะฑะต","าทัะผัะฐ","ัะฐะฝะฑะต"],
namesAbbr: ["ะฟะบั","ะดัะฑ","ััะฑ","ััะฑ","ะฟัะฑ","าทัะผ","ัะฝะฑ"],
namesShort: ["ัั","ะดั","ัั","ัั","ะฟั","าทะผ","ัะฑ"]
},
months: {
names: ["ัะฝะฒะฐั","ัะตะฒัะฐะป","ะผะฐัั","ะฐะฟัะตะป","ะผะฐะน","ะธัะฝ","ะธัะป","ะฐะฒะณััั","ัะตะฝััะฑั","ะพะบััะฑั","ะฝะพัะฑั","ะดะตะบะฐะฑั"],
namesAbbr: ["ัะฝะฒ","ัะตะฒ","ะผะฐั","ะฐะฟั","ะผะฐะน","ะธัะฝ","ะธัะป","ะฐะฒะณ","ัะตะฝ","ะพะบั","ะฝะพั","ะดะตะบ"]
},
AM: [""],
PM: [""],
patterns: {
d: "dd.MM.yyyy",
D: "d MMMM yyyy' ั.'",
F: "d MMMM yyyy' ั.' HH:mm:ss",
g: "dd.MM.yyyy HH:mm",
G: "dd.MM.yyyy HH:mm:ss",
m: "dd MMMM",
M: "dd MMMM",
s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss",
t: "HH:mm",
T: "HH:mm:ss",
u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'",
y: "MMMM yyyy",
Y: "MMMM yyyy"
},
"/": ".",
":": ":",
firstDay: 1
}
}
}
})(this);
})); | gngeorgiev/platform-friends | friends-hybrid/bower_components/kendo-ui/src/js/cultures/kendo.culture.tg-Cyrl.js | JavaScript | bsd-2-clause | 6,673 |
// This file was procedurally generated from the following sources:
// - src/dstr-assignment/array-elem-trlg-iter-list-nrml-close-skip.case
// - src/dstr-assignment/default/for-of.template
/*---
description: IteratorClose is not invoked when evaluation of AssignmentElementList exhausts the iterator (For..of statement)
esid: sec-for-in-and-for-of-statements-runtime-semantics-labelledevaluation
es6id: 13.7.5.11
features: [Symbol.iterator, destructuring-binding]
flags: [generated]
info: |
IterationStatement :
for ( LeftHandSideExpression of AssignmentExpression ) Statement
1. Let keyResult be the result of performing ? ForIn/OfHeadEvaluation(ยซ ยป,
AssignmentExpression, iterate).
2. Return ? ForIn/OfBodyEvaluation(LeftHandSideExpression, Statement,
keyResult, assignment, labelSet).
13.7.5.13 Runtime Semantics: ForIn/OfBodyEvaluation
[...]
4. If destructuring is true and if lhsKind is assignment, then
a. Assert: lhs is a LeftHandSideExpression.
b. Let assignmentPattern be the parse of the source text corresponding to
lhs using AssignmentPattern as the goal symbol.
[...]
ArrayAssignmentPattern :
[ AssignmentElementList , Elisionopt AssignmentRestElementopt ]
[...]
3. Let iteratorRecord be Record {[[iterator]]: iterator, [[done]]: false}.
4. Let status be the result of performing
IteratorDestructuringAssignmentEvaluation of AssignmentElementList using
iteratorRecord as the argument.
5. If status is an abrupt completion, then
a. If iteratorRecord.[[done]] is false, return IteratorClose(iterator,
status).
b. Return Completion(status).
---*/
var nextCount = 0;
var returnCount = 0;
var iterable = {};
var thrower = function() {
throw new Test262Error();
};
var x;
var iterator = {
next: function() {
nextCount += 1;
return { done: true };
},
return: function() {
returnCount += 1;
}
};
iterable[Symbol.iterator] = function() {
return iterator;
};
var counter = 0;
for ([ x , ] of [iterable]) {
assert.sameValue(nextCount, 1);
assert.sameValue(returnCount, 0);
counter += 1;
}
assert.sameValue(counter, 1);
| sebastienros/jint | Jint.Tests.Test262/test/language/statements/for-of/dstr-array-elem-trlg-iter-list-nrml-close-skip.js | JavaScript | bsd-2-clause | 2,200 |
// ## twig.core.js
//
// This file handles template level tokenizing, compiling and parsing.
module.exports = function (Twig) {
"use strict";
Twig.trace = false;
Twig.debug = false;
// Default caching to true for the improved performance it offers
Twig.cache = true;
Twig.placeholders = {
parent: "{{|PARENT|}}"
};
/**
* Fallback for Array.indexOf for IE8 et al
*/
Twig.indexOf = function (arr, searchElement /*, fromIndex */ ) {
if (Array.prototype.hasOwnProperty("indexOf")) {
return arr.indexOf(searchElement);
}
if (arr === void 0 || arr === null) {
throw new TypeError();
}
var t = Object(arr);
var len = t.length >>> 0;
if (len === 0) {
return -1;
}
var n = 0;
if (arguments.length > 0) {
n = Number(arguments[1]);
if (n !== n) { // shortcut for verifying if it's NaN
n = 0;
} else if (n !== 0 && n !== Infinity && n !== -Infinity) {
n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
}
if (n >= len) {
// console.log("indexOf not found1 ", JSON.stringify(searchElement), JSON.stringify(arr));
return -1;
}
var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
for (; k < len; k++) {
if (k in t && t[k] === searchElement) {
return k;
}
}
if (arr == searchElement) {
return 0;
}
// console.log("indexOf not found2 ", JSON.stringify(searchElement), JSON.stringify(arr));
return -1;
}
Twig.forEach = function (arr, callback, thisArg) {
if (Array.prototype.forEach ) {
return arr.forEach(callback, thisArg);
}
var T, k;
if ( arr == null ) {
throw new TypeError( " this is null or not defined" );
}
// 1. Let O be the result of calling ToObject passing the |this| value as the argument.
var O = Object(arr);
// 2. Let lenValue be the result of calling the Get internal method of O with the argument "length".
// 3. Let len be ToUint32(lenValue).
var len = O.length >>> 0; // Hack to convert O.length to a UInt32
// 4. If IsCallable(callback) is false, throw a TypeError exception.
// See: http://es5.github.com/#x9.11
if ( {}.toString.call(callback) != "[object Function]" ) {
throw new TypeError( callback + " is not a function" );
}
// 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
if ( thisArg ) {
T = thisArg;
}
// 6. Let k be 0
k = 0;
// 7. Repeat, while k < len
while( k < len ) {
var kValue;
// a. Let Pk be ToString(k).
// This is implicit for LHS operands of the in operator
// b. Let kPresent be the result of calling the HasProperty internal method of O with argument Pk.
// This step can be combined with c
// c. If kPresent is true, then
if ( k in O ) {
// i. Let kValue be the result of calling the Get internal method of O with argument Pk.
kValue = O[ k ];
// ii. Call the Call internal method of callback with T as the this value and
// argument list containing kValue, k, and O.
callback.call( T, kValue, k, O );
}
// d. Increase k by 1.
k++;
}
// 8. return undefined
};
Twig.merge = function(target, source, onlyChanged) {
Twig.forEach(Object.keys(source), function (key) {
if (onlyChanged && !(key in target)) {
return;
}
target[key] = source[key]
});
return target;
};
/**
* Exception thrown by twig.js.
*/
Twig.Error = function(message) {
this.message = message;
this.name = "TwigException";
this.type = "TwigException";
};
/**
* Get the string representation of a Twig error.
*/
Twig.Error.prototype.toString = function() {
var output = this.name + ": " + this.message;
return output;
};
/**
* Wrapper for logging to the console.
*/
Twig.log = {
trace: function() {if (Twig.trace && console) {console.log(Array.prototype.slice.call(arguments));}},
debug: function() {if (Twig.debug && console) {console.log(Array.prototype.slice.call(arguments));}}
};
if (typeof console !== "undefined") {
if (typeof console.error !== "undefined") {
Twig.log.error = function() {
console.error.apply(console, arguments);
}
} else if (typeof console.log !== "undefined") {
Twig.log.error = function() {
console.log.apply(console, arguments);
}
}
} else {
Twig.log.error = function(){};
}
/**
* Wrapper for child context objects in Twig.
*
* @param {Object} context Values to initialize the context with.
*/
Twig.ChildContext = function(context) {
var ChildContext = function ChildContext() {};
ChildContext.prototype = context;
return new ChildContext();
};
/**
* Container for methods related to handling high level template tokens
* (for example: {{ expression }}, {% logic %}, {# comment #}, raw data)
*/
Twig.token = {};
/**
* Token types.
*/
Twig.token.type = {
output: 'output',
logic: 'logic',
comment: 'comment',
raw: 'raw',
output_whitespace_pre: 'output_whitespace_pre',
output_whitespace_post: 'output_whitespace_post',
output_whitespace_both: 'output_whitespace_both',
logic_whitespace_pre: 'logic_whitespace_pre',
logic_whitespace_post: 'logic_whitespace_post',
logic_whitespace_both: 'logic_whitespace_both'
};
/**
* Token syntax definitions.
*/
Twig.token.definitions = [
{
type: Twig.token.type.raw,
open: '{% raw %}',
close: '{% endraw %}'
},
{
type: Twig.token.type.raw,
open: '{% verbatim %}',
close: '{% endverbatim %}'
},
// *Whitespace type tokens*
//
// These typically take the form `{{- expression -}}` or `{{- expression }}` or `{{ expression -}}`.
{
type: Twig.token.type.output_whitespace_pre,
open: '{{-',
close: '}}'
},
{
type: Twig.token.type.output_whitespace_post,
open: '{{',
close: '-}}'
},
{
type: Twig.token.type.output_whitespace_both,
open: '{{-',
close: '-}}'
},
{
type: Twig.token.type.logic_whitespace_pre,
open: '{%-',
close: '%}'
},
{
type: Twig.token.type.logic_whitespace_post,
open: '{%',
close: '-%}'
},
{
type: Twig.token.type.logic_whitespace_both,
open: '{%-',
close: '-%}'
},
// *Output type tokens*
//
// These typically take the form `{{ expression }}`.
{
type: Twig.token.type.output,
open: '{{',
close: '}}'
},
// *Logic type tokens*
//
// These typically take a form like `{% if expression %}` or `{% endif %}`
{
type: Twig.token.type.logic,
open: '{%',
close: '%}'
},
// *Comment type tokens*
//
// These take the form `{# anything #}`
{
type: Twig.token.type.comment,
open: '{#',
close: '#}'
}
];
/**
* What characters start "strings" in token definitions. We need this to ignore token close
* strings inside an expression.
*/
Twig.token.strings = ['"', "'"];
Twig.token.findStart = function (template) {
var output = {
position: null,
close_position: null,
def: null
},
i,
token_template,
first_key_position,
close_key_position;
for (i=0;i<Twig.token.definitions.length;i++) {
token_template = Twig.token.definitions[i];
first_key_position = template.indexOf(token_template.open);
close_key_position = template.indexOf(token_template.close);
Twig.log.trace("Twig.token.findStart: ", "Searching for ", token_template.open, " found at ", first_key_position);
//Special handling for mismatched tokens
if (first_key_position >= 0) {
//This token matches the template
if (token_template.open.length !== token_template.close.length) {
//This token has mismatched closing and opening tags
if (close_key_position < 0) {
//This token's closing tag does not match the template
continue;
}
}
}
// Does this token occur before any other types?
if (first_key_position >= 0 && (output.position === null || first_key_position < output.position)) {
output.position = first_key_position;
output.def = token_template;
output.close_position = close_key_position;
} else if (first_key_position >= 0 && output.position !== null && first_key_position === output.position) {
/*This token exactly matches another token,
greedily match to check if this token has a greater specificity*/
if (token_template.open.length > output.def.open.length) {
//This token's opening tag is more specific than the previous match
output.position = first_key_position;
output.def = token_template;
output.close_position = close_key_position;
} else if (token_template.open.length === output.def.open.length) {
if (token_template.close.length > output.def.close.length) {
//This token's opening tag is as specific as the previous match,
//but the closing tag has greater specificity
if (close_key_position >= 0 && close_key_position < output.close_position) {
//This token's closing tag exists in the template,
//and it occurs sooner than the previous match
output.position = first_key_position;
output.def = token_template;
output.close_position = close_key_position;
}
} else if (close_key_position >= 0 && close_key_position < output.close_position) {
//This token's closing tag is not more specific than the previous match,
//but it occurs sooner than the previous match
output.position = first_key_position;
output.def = token_template;
output.close_position = close_key_position;
}
}
}
}
delete output['close_position'];
return output;
};
Twig.token.findEnd = function (template, token_def, start) {
var end = null,
found = false,
offset = 0,
// String position variables
str_pos = null,
str_found = null,
pos = null,
end_offset = null,
this_str_pos = null,
end_str_pos = null,
// For loop variables
i,
l;
while (!found) {
str_pos = null;
str_found = null;
pos = template.indexOf(token_def.close, offset);
if (pos >= 0) {
end = pos;
found = true;
} else {
// throw an exception
throw new Twig.Error("Unable to find closing bracket '" + token_def.close +
"'" + " opened near template position " + start);
}
// Ignore quotes within comments; just look for the next comment close sequence,
// regardless of what comes before it. https://github.com/justjohn/twig.js/issues/95
if (token_def.type === Twig.token.type.comment) {
break;
}
// Ignore quotes within raw tag
// Fixes #283
if (token_def.type === Twig.token.type.raw) {
break;
}
l = Twig.token.strings.length;
for (i = 0; i < l; i += 1) {
this_str_pos = template.indexOf(Twig.token.strings[i], offset);
if (this_str_pos > 0 && this_str_pos < pos &&
(str_pos === null || this_str_pos < str_pos)) {
str_pos = this_str_pos;
str_found = Twig.token.strings[i];
}
}
// We found a string before the end of the token, now find the string's end and set the search offset to it
if (str_pos !== null) {
end_offset = str_pos + 1;
end = null;
found = false;
while (true) {
end_str_pos = template.indexOf(str_found, end_offset);
if (end_str_pos < 0) {
throw "Unclosed string in template";
}
// Ignore escaped quotes
if (template.substr(end_str_pos - 1, 1) !== "\\") {
offset = end_str_pos + 1;
break;
} else {
end_offset = end_str_pos + 1;
}
}
}
}
return end;
};
/**
* Convert a template into high-level tokens.
*/
Twig.tokenize = function (template) {
var tokens = [],
// An offset for reporting errors locations in the template.
error_offset = 0,
// The start and type of the first token found in the template.
found_token = null,
// The end position of the matched token.
end = null;
while (template.length > 0) {
// Find the first occurance of any token type in the template
found_token = Twig.token.findStart(template);
Twig.log.trace("Twig.tokenize: ", "Found token: ", found_token);
if (found_token.position !== null) {
// Add a raw type token for anything before the start of the token
if (found_token.position > 0) {
tokens.push({
type: Twig.token.type.raw,
value: template.substring(0, found_token.position)
});
}
template = template.substr(found_token.position + found_token.def.open.length);
error_offset += found_token.position + found_token.def.open.length;
// Find the end of the token
end = Twig.token.findEnd(template, found_token.def, error_offset);
Twig.log.trace("Twig.tokenize: ", "Token ends at ", end);
tokens.push({
type: found_token.def.type,
value: template.substring(0, end).trim()
});
if (template.substr( end + found_token.def.close.length, 1 ) === "\n") {
switch (found_token.def.type) {
case "logic_whitespace_pre":
case "logic_whitespace_post":
case "logic_whitespace_both":
case "logic":
// Newlines directly after logic tokens are ignored
end += 1;
break;
}
}
template = template.substr(end + found_token.def.close.length);
// Increment the position in the template
error_offset += end + found_token.def.close.length;
} else {
// No more tokens -> add the rest of the template as a raw-type token
tokens.push({
type: Twig.token.type.raw,
value: template
});
template = '';
}
}
return tokens;
};
Twig.compile = function (tokens) {
try {
// Output and intermediate stacks
var output = [],
stack = [],
// The tokens between open and close tags
intermediate_output = [],
token = null,
logic_token = null,
unclosed_token = null,
// Temporary previous token.
prev_token = null,
// Temporary previous output.
prev_output = null,
// Temporary previous intermediate output.
prev_intermediate_output = null,
// The previous token's template
prev_template = null,
// Token lookahead
next_token = null,
// The output token
tok_output = null,
// Logic Token values
type = null,
open = null,
next = null;
var compile_output = function(token) {
Twig.expression.compile.apply(this, [token]);
if (stack.length > 0) {
intermediate_output.push(token);
} else {
output.push(token);
}
};
var compile_logic = function(token) {
// Compile the logic token
logic_token = Twig.logic.compile.apply(this, [token]);
type = logic_token.type;
open = Twig.logic.handler[type].open;
next = Twig.logic.handler[type].next;
Twig.log.trace("Twig.compile: ", "Compiled logic token to ", logic_token,
" next is: ", next, " open is : ", open);
// Not a standalone token, check logic stack to see if this is expected
if (open !== undefined && !open) {
prev_token = stack.pop();
prev_template = Twig.logic.handler[prev_token.type];
if (Twig.indexOf(prev_template.next, type) < 0) {
throw new Error(type + " not expected after a " + prev_token.type);
}
prev_token.output = prev_token.output || [];
prev_token.output = prev_token.output.concat(intermediate_output);
intermediate_output = [];
tok_output = {
type: Twig.token.type.logic,
token: prev_token
};
if (stack.length > 0) {
intermediate_output.push(tok_output);
} else {
output.push(tok_output);
}
}
// This token requires additional tokens to complete the logic structure.
if (next !== undefined && next.length > 0) {
Twig.log.trace("Twig.compile: ", "Pushing ", logic_token, " to logic stack.");
if (stack.length > 0) {
// Put any currently held output into the output list of the logic operator
// currently at the head of the stack before we push a new one on.
prev_token = stack.pop();
prev_token.output = prev_token.output || [];
prev_token.output = prev_token.output.concat(intermediate_output);
stack.push(prev_token);
intermediate_output = [];
}
// Push the new logic token onto the logic stack
stack.push(logic_token);
} else if (open !== undefined && open) {
tok_output = {
type: Twig.token.type.logic,
token: logic_token
};
// Standalone token (like {% set ... %}
if (stack.length > 0) {
intermediate_output.push(tok_output);
} else {
output.push(tok_output);
}
}
};
while (tokens.length > 0) {
token = tokens.shift();
prev_output = output[output.length - 1];
prev_intermediate_output = intermediate_output[intermediate_output.length - 1];
next_token = tokens[0];
Twig.log.trace("Compiling token ", token);
switch (token.type) {
case Twig.token.type.raw:
if (stack.length > 0) {
intermediate_output.push(token);
} else {
output.push(token);
}
break;
case Twig.token.type.logic:
compile_logic.call(this, token);
break;
// Do nothing, comments should be ignored
case Twig.token.type.comment:
break;
case Twig.token.type.output:
compile_output.call(this, token);
break;
//Kill whitespace ahead and behind this token
case Twig.token.type.logic_whitespace_pre:
case Twig.token.type.logic_whitespace_post:
case Twig.token.type.logic_whitespace_both:
case Twig.token.type.output_whitespace_pre:
case Twig.token.type.output_whitespace_post:
case Twig.token.type.output_whitespace_both:
if (token.type !== Twig.token.type.output_whitespace_post && token.type !== Twig.token.type.logic_whitespace_post) {
if (prev_output) {
//If the previous output is raw, pop it off
if (prev_output.type === Twig.token.type.raw) {
output.pop();
//If the previous output is not just whitespace, trim it
if (prev_output.value.match(/^\s*$/) === null) {
prev_output.value = prev_output.value.trim();
//Repush the previous output
output.push(prev_output);
}
}
}
if (prev_intermediate_output) {
//If the previous intermediate output is raw, pop it off
if (prev_intermediate_output.type === Twig.token.type.raw) {
intermediate_output.pop();
//If the previous output is not just whitespace, trim it
if (prev_intermediate_output.value.match(/^\s*$/) === null) {
prev_intermediate_output.value = prev_intermediate_output.value.trim();
//Repush the previous intermediate output
intermediate_output.push(prev_intermediate_output);
}
}
}
}
//Compile this token
switch (token.type) {
case Twig.token.type.output_whitespace_pre:
case Twig.token.type.output_whitespace_post:
case Twig.token.type.output_whitespace_both:
compile_output.call(this, token);
break;
case Twig.token.type.logic_whitespace_pre:
case Twig.token.type.logic_whitespace_post:
case Twig.token.type.logic_whitespace_both:
compile_logic.call(this, token);
break;
}
if (token.type !== Twig.token.type.output_whitespace_pre && token.type !== Twig.token.type.logic_whitespace_pre) {
if (next_token) {
//If the next token is raw, shift it out
if (next_token.type === Twig.token.type.raw) {
tokens.shift();
//If the next token is not just whitespace, trim it
if (next_token.value.match(/^\s*$/) === null) {
next_token.value = next_token.value.trim();
//Unshift the next token
tokens.unshift(next_token);
}
}
}
}
break;
}
Twig.log.trace("Twig.compile: ", " Output: ", output,
" Logic Stack: ", stack,
" Pending Output: ", intermediate_output );
}
// Verify that there are no logic tokens left in the stack.
if (stack.length > 0) {
unclosed_token = stack.pop();
throw new Error("Unable to find an end tag for " + unclosed_token.type +
", expecting one of " + unclosed_token.next);
}
return output;
} catch (ex) {
Twig.log.error("Error compiling twig template " + this.id + ": ");
if (ex.stack) {
Twig.log.error(ex.stack);
} else {
Twig.log.error(ex.toString());
}
if (this.options.rethrow) throw ex;
}
};
/**
* Parse a compiled template.
*
* @param {Array} tokens The compiled tokens.
* @param {Object} context The render context.
*
* @return {string} The parsed template.
*/
Twig.parse = function (tokens, context) {
try {
var output = [],
// Track logic chains
chain = true,
that = this;
Twig.forEach(tokens, function parseToken(token) {
Twig.log.debug("Twig.parse: ", "Parsing token: ", token);
switch (token.type) {
case Twig.token.type.raw:
output.push(Twig.filters.raw(token.value));
break;
case Twig.token.type.logic:
var logic_token = token.token,
logic = Twig.logic.parse.apply(that, [logic_token, context, chain]);
if (logic.chain !== undefined) {
chain = logic.chain;
}
if (logic.context !== undefined) {
context = logic.context;
}
if (logic.output !== undefined) {
output.push(logic.output);
}
break;
case Twig.token.type.comment:
// Do nothing, comments should be ignored
break;
//Fall through whitespace to output
case Twig.token.type.output_whitespace_pre:
case Twig.token.type.output_whitespace_post:
case Twig.token.type.output_whitespace_both:
case Twig.token.type.output:
Twig.log.debug("Twig.parse: ", "Output token: ", token.stack);
// Parse the given expression in the given context
output.push(Twig.expression.parse.apply(that, [token.stack, context]));
break;
}
});
return Twig.output.apply(this, [output]);
} catch (ex) {
Twig.log.error("Error parsing twig template " + this.id + ": ");
if (ex.stack) {
Twig.log.error(ex.stack);
} else {
Twig.log.error(ex.toString());
}
if (this.options.rethrow) throw ex;
if (Twig.debug) {
return ex.toString();
}
}
};
/**
* Tokenize and compile a string template.
*
* @param {string} data The template.
*
* @return {Array} The compiled tokens.
*/
Twig.prepare = function(data) {
var tokens, raw_tokens;
// Tokenize
Twig.log.debug("Twig.prepare: ", "Tokenizing ", data);
raw_tokens = Twig.tokenize.apply(this, [data]);
// Compile
Twig.log.debug("Twig.prepare: ", "Compiling ", raw_tokens);
tokens = Twig.compile.apply(this, [raw_tokens]);
Twig.log.debug("Twig.prepare: ", "Compiled ", tokens);
return tokens;
};
/**
* Join the output token's stack and escape it if needed
*
* @param {Array} Output token's stack
*
* @return {string|String} Autoescaped output
*/
Twig.output = function(output) {
if (!this.options.autoescape) {
return output.join("");
}
var strategy = 'html';
if(typeof this.options.autoescape == 'string')
strategy = this.options.autoescape;
// [].map would be better but it's not supported by IE8-
var escaped_output = [];
Twig.forEach(output, function (str) {
if (str && (str.twig_markup !== true && str.twig_markup != strategy)) {
str = Twig.filters.escape(str, [ strategy ]);
}
escaped_output.push(str);
});
return Twig.Markup(escaped_output.join(""));
}
// Namespace for template storage and retrieval
Twig.Templates = {
/**
* Registered template loaders - use Twig.Templates.registerLoader to add supported loaders
* @type {Object}
*/
loaders: {},
/**
* Registered template parsers - use Twig.Templates.registerParser to add supported parsers
* @type {Object}
*/
parsers: {},
/**
* Cached / loaded templates
* @type {Object}
*/
registry: {}
};
/**
* Is this id valid for a twig template?
*
* @param {string} id The ID to check.
*
* @throws {Twig.Error} If the ID is invalid or used.
* @return {boolean} True if the ID is valid.
*/
Twig.validateId = function(id) {
if (id === "prototype") {
throw new Twig.Error(id + " is not a valid twig identifier");
} else if (Twig.cache && Twig.Templates.registry.hasOwnProperty(id)) {
throw new Twig.Error("There is already a template with the ID " + id);
}
return true;
}
/**
* Register a template loader
*
* @example
* Twig.extend(function(Twig) {
* Twig.Templates.registerLoader('custom_loader', function(location, params, callback, error_callback) {
* // ... load the template ...
* params.data = loadedTemplateData;
* // create and return the template
* var template = new Twig.Template(params);
* if (typeof callback === 'function') {
* callback(template);
* }
* return template;
* });
* });
*
* @param {String} method_name The method this loader is intended for (ajax, fs)
* @param {Function} func The function to execute when loading the template
* @param {Object|undefined} scope Optional scope parameter to bind func to
*
* @throws Twig.Error
*
* @return {void}
*/
Twig.Templates.registerLoader = function(method_name, func, scope) {
if (typeof func !== 'function') {
throw new Twig.Error('Unable to add loader for ' + method_name + ': Invalid function reference given.');
}
if (scope) {
func = func.bind(scope);
}
this.loaders[method_name] = func;
};
/**
* Remove a registered loader
*
* @param {String} method_name The method name for the loader you wish to remove
*
* @return {void}
*/
Twig.Templates.unRegisterLoader = function(method_name) {
if (this.isRegisteredLoader(method_name)) {
delete this.loaders[method_name];
}
};
/**
* See if a loader is registered by its method name
*
* @param {String} method_name The name of the loader you are looking for
*
* @return {boolean}
*/
Twig.Templates.isRegisteredLoader = function(method_name) {
return this.loaders.hasOwnProperty(method_name);
};
/**
* Register a template parser
*
* @example
* Twig.extend(function(Twig) {
* Twig.Templates.registerParser('custom_parser', function(params) {
* // this template source can be accessed in params.data
* var template = params.data
*
* // ... custom process that modifies the template
*
* // return the parsed template
* return template;
* });
* });
*
* @param {String} method_name The method this parser is intended for (twig, source)
* @param {Function} func The function to execute when parsing the template
* @param {Object|undefined} scope Optional scope parameter to bind func to
*
* @throws Twig.Error
*
* @return {void}
*/
Twig.Templates.registerParser = function(method_name, func, scope) {
if (typeof func !== 'function') {
throw new Twig.Error('Unable to add parser for ' + method_name + ': Invalid function regerence given.');
}
if (scope) {
func = func.bind(scope);
}
this.parsers[method_name] = func;
};
/**
* Remove a registered parser
*
* @param {String} method_name The method name for the parser you wish to remove
*
* @return {void}
*/
Twig.Templates.unRegisterParser = function(method_name) {
if (this.isRegisteredParser(method_name)) {
delete this.parsers[method_name];
}
};
/**
* See if a parser is registered by its method name
*
* @param {String} method_name The name of the parser you are looking for
*
* @return {boolean}
*/
Twig.Templates.isRegisteredParser = function(method_name) {
return this.parsers.hasOwnProperty(method_name);
};
/**
* Save a template object to the store.
*
* @param {Twig.Template} template The twig.js template to store.
*/
Twig.Templates.save = function(template) {
if (template.id === undefined) {
throw new Twig.Error("Unable to save template with no id");
}
Twig.Templates.registry[template.id] = template;
};
/**
* Load a previously saved template from the store.
*
* @param {string} id The ID of the template to load.
*
* @return {Twig.Template} A twig.js template stored with the provided ID.
*/
Twig.Templates.load = function(id) {
if (!Twig.Templates.registry.hasOwnProperty(id)) {
return null;
}
return Twig.Templates.registry[id];
};
/**
* Load a template from a remote location using AJAX and saves in with the given ID.
*
* Available parameters:
*
* async: Should the HTTP request be performed asynchronously.
* Defaults to true.
* method: What method should be used to load the template
* (fs or ajax)
* parser: What method should be used to parse the template
* (twig or source)
* precompiled: Has the template already been compiled.
*
* @param {string} location The remote URL to load as a template.
* @param {Object} params The template parameters.
* @param {function} callback A callback triggered when the template finishes loading.
* @param {function} error_callback A callback triggered if an error occurs loading the template.
*
*
*/
Twig.Templates.loadRemote = function(location, params, callback, error_callback) {
var loader;
// Default to async
if (params.async === undefined) {
params.async = true;
}
// Default to the URL so the template is cached.
if (params.id === undefined) {
params.id = location;
}
// Check for existing template
if (Twig.cache && Twig.Templates.registry.hasOwnProperty(params.id)) {
// A template is already saved with the given id.
if (typeof callback === 'function') {
callback(Twig.Templates.registry[params.id]);
}
// TODO: if async, return deferred promise
return Twig.Templates.registry[params.id];
}
//if the parser name hasn't been set, default it to twig
params.parser = params.parser || 'twig';
// Assume 'fs' if the loader is not defined
loader = this.loaders[params.method] || this.loaders.fs;
return loader.apply(this, arguments);
};
// Determine object type
function is(type, obj) {
var clas = Object.prototype.toString.call(obj).slice(8, -1);
return obj !== undefined && obj !== null && clas === type;
}
/**
* Create a new twig.js template.
*
* Parameters: {
* data: The template, either pre-compiled tokens or a string template
* id: The name of this template
* blocks: Any pre-existing block from a child template
* }
*
* @param {Object} params The template parameters.
*/
Twig.Template = function ( params ) {
var data = params.data,
id = params.id,
blocks = params.blocks,
macros = params.macros || {},
base = params.base,
path = params.path,
url = params.url,
name = params.name,
method = params.method,
// parser options
options = params.options;
// # What is stored in a Twig.Template
//
// The Twig Template hold several chucks of data.
//
// {
// id: The token ID (if any)
// tokens: The list of tokens that makes up this template.
// blocks: The list of block this template contains.
// base: The base template (if any)
// options: {
// Compiler/parser options
//
// strict_variables: true/false
// Should missing variable/keys emit an error message. If false, they default to null.
// }
// }
//
this.id = id;
this.method = method;
this.base = base;
this.path = path;
this.url = url;
this.name = name;
this.macros = macros;
this.options = options;
this.reset(blocks);
if (is('String', data)) {
this.tokens = Twig.prepare.apply(this, [data]);
} else {
this.tokens = data;
}
if (id !== undefined) {
Twig.Templates.save(this);
}
};
Twig.Template.prototype.reset = function(blocks) {
Twig.log.debug("Twig.Template.reset", "Reseting template " + this.id);
this.blocks = {};
this.importedBlocks = [];
this.originalBlockTokens = {};
this.child = {
blocks: blocks || {}
};
this.extend = null;
};
Twig.Template.prototype.render = function (context, params) {
params = params || {};
var output,
url;
this.context = context || {};
// Clear any previous state
this.reset();
if (params.blocks) {
this.blocks = params.blocks;
}
if (params.macros) {
this.macros = params.macros;
}
output = Twig.parse.apply(this, [this.tokens, this.context]);
// Does this template extend another
if (this.extend) {
var ext_template;
// check if the template is provided inline
if ( this.options.allowInlineIncludes ) {
ext_template = Twig.Templates.load(this.extend);
if ( ext_template ) {
ext_template.options = this.options;
}
}
// check for the template file via include
if (!ext_template) {
url = Twig.path.parsePath(this, this.extend);
ext_template = Twig.Templates.loadRemote(url, {
method: this.getLoaderMethod(),
base: this.base,
async: false,
id: url,
options: this.options
});
}
this.parent = ext_template;
return this.parent.render(this.context, {
blocks: this.blocks
});
}
if (params.output == 'blocks') {
return this.blocks;
} else if (params.output == 'macros') {
return this.macros;
} else {
return output;
}
};
Twig.Template.prototype.importFile = function(file) {
var url, sub_template;
if (!this.url && this.options.allowInlineIncludes) {
file = this.path ? this.path + '/' + file : file;
sub_template = Twig.Templates.load(file);
if (!sub_template) {
sub_template = Twig.Templates.loadRemote(url, {
id: file,
method: this.getLoaderMethod(),
async: false,
options: this.options
});
if (!sub_template) {
throw new Twig.Error("Unable to find the template " + file);
}
}
sub_template.options = this.options;
return sub_template;
}
url = Twig.path.parsePath(this, file);
// Load blocks from an external file
sub_template = Twig.Templates.loadRemote(url, {
method: this.getLoaderMethod(),
base: this.base,
async: false,
options: this.options,
id: url
});
return sub_template;
};
Twig.Template.prototype.importBlocks = function(file, override) {
var sub_template = this.importFile(file),
context = this.context,
that = this,
key;
override = override || false;
sub_template.render(context);
// Mixin blocks
Twig.forEach(Object.keys(sub_template.blocks), function(key) {
if (override || that.blocks[key] === undefined) {
that.blocks[key] = sub_template.blocks[key];
that.importedBlocks.push(key);
}
});
};
Twig.Template.prototype.importMacros = function(file) {
var url = Twig.path.parsePath(this, file);
// load remote template
var remoteTemplate = Twig.Templates.loadRemote(url, {
method: this.getLoaderMethod(),
async: false,
id: url
});
return remoteTemplate;
};
Twig.Template.prototype.getLoaderMethod = function() {
if (this.path) {
return 'fs';
}
if (this.url) {
return 'ajax';
}
return this.method || 'fs';
};
Twig.Template.prototype.compile = function(options) {
// compile the template into raw JS
return Twig.compiler.compile(this, options);
};
/**
* Create safe output
*
* @param {string} Content safe to output
*
* @return {String} Content wrapped into a String
*/
Twig.Markup = function(content, strategy) {
if(typeof strategy == 'undefined') {
strategy = true;
}
if (typeof content === 'string' && content.length > 0) {
content = new String(content);
content.twig_markup = strategy;
}
return content;
};
return Twig;
};
| dave-irvine/twig.js | src/twig.core.js | JavaScript | bsd-2-clause | 46,210 |
Ext.form.BasicForm.override({
resetDirty: function() {
this.items.each(function(field) {
field.resetDirty();
});
},
setDefaultValues: function() {
this.items.each(function(field) {
field.setDefaultValue();
}, this);
},
clearValues: function() {
this.items.each(function(field) {
if (field.rendered) field.clearValue();
}, this);
},
//override stupid Ext behavior
//better to ask the individual form fields
//needed for: Checkbox, ComboBox, SwfUpload, Date...
getValues: function() {
var ret = {};
this.items.each(function(field) {
if (field.getName && field.getName()) {
ret[field.getName()] = field.getValue();
}
}, this);
return ret;
}
});
Ext.apply(Ext.form.VTypes, {
//E-Mail Validierung darf ab Ext 2.2 keine Bindestriche mehr haben, jetzt schon wieder
email: function(v) {
return /^([a-zA-Z0-9_.+-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/.test(v);
},
emailMask : /[a-z0-9_\.\-@+]/i, //include +
urltel: function(v) {
return /^(tel:\/\/[\d\s]+|(((https?)|(ftp)):\/\/([\-\w]+\.)+\w{2,3}(\/[%\-\w]+(\.\w{2,})?)*(([\w\-\.\?\\\/+@&#;`~=%!]*)(\.\w{2,})?)*\/?))+$/.test(v);
},
urltelTest: trlKwf('This field should be a URL in the format "http://www.domain.com" or tel://0043 1234'),
//Ersetzt alles auรer a-z, 0-9 - durch _. So wie Kwf_Filter_Ascii
//standard-ext implementierung รผberschrieben um den - zu erlauben
alphanum: function(v) {
return /^[a-zA-Z0-9_\-]+$/.test(v);
},
alphanumText : trlKwf('This field should only contain letters, numbers, - and _'),
alphanumMask : /[a-z0-9_\-]/i,
num: function(v) {
return /^[0-9]+$/.test(v);
},
numText : trlKwf('This field should only contain numbers'),
numMask : /[0-9]/,
time: function(val, field) {
return /^([0-9]{2}):([0-9]{2}):([0-9]{2})$/i.test(val);
},
timeText: trlKwf('Not a valid time. Must be in the format "12:34:00".'),
timeMask: /[\d:]/i
});
| mike-tuxedo/koala-framework | Kwf_js/Form/BasicForm.js | JavaScript | bsd-2-clause | 2,143 |
/*
Just Journal JavaScript Library
author: Lucas Holt
date created: June 10, 2007
*/
function follow(friend) {
'use strict';
var request = jQuery.ajax({
url: "/api/friend/" + friend,
type: "PUT",
data: {}
});
request.done(function () {
window.alert('Now following ' + friend);
});
request.fail(function (jqXHR, textStatus) {
window.alert("Could not follow friend. Request failed: " + textStatus);
});
}
function unfollow(friend) {
'use strict';
var request = jQuery.ajax({
url: "/api/friend/" + friend,
type: "DELETE",
data: {}
});
request.done(function () {
window.alert('Unfollowing ' + friend);
});
request.fail(function (jqXHR, textStatus) {
window.alert("Could not unfollow friend. Request failed: " + textStatus);
});
}
function addFavorite(entryId) {
'use strict';
var request = jQuery.ajax({
url: "/api/favorite/" + entryId,
type: "POST",
data: {}
});
request.done(function () {
window.alert('Favorite saved.');
});
request.fail(function (jqXHR, textStatus) {
window.alert("Favorite not saved. Request failed: " + textStatus);
});
}
function deleteFavorite(entryId) {
'use strict';
var request = jQuery.ajax({
url: "/api/favorite/" + entryId,
type: "DELETE",
data: {}
});
request.done(function () {
window.alert('Favorite removed.');
});
request.fail(function (jqXHR, textStatus) {
window.alert("Favorite not removed. Request failed: " + textStatus);
});
}
function deleteEntry(entryId) {
'use strict';
if (confirmDelete()) {
var request = jQuery.ajax({
url: "/api/entry/" + entryId,
type: "DELETE",
data: {}
});
request.done(function() {
window.alert('Removed Entry');
});
request.fail(function(jqXHR, textStatus) {
window.alert("Request failed: " + textStatus);
});
}
}
function deleteComment(commentId) {
'use strict';
if (confirmDelete()) {
var request = jQuery.ajax({
url: "/api/comment/" + commentId,
type: "DELETE",
data: {}
});
request.done(function() {
window.alert('Removed Comment');
});
request.fail(function(jqXHR, textStatus) {
window.alert("Request failed: " + textStatus);
});
}
}
function confirmDelete() {
'use strict';
return window.confirm("Are you sure you want to delete this?");
}
function showbox(boxId) {
'use strict';
var box = document.getElementById(boxId);
var parentBox = document.getElementById(boxId + "parent");
box.style.top = getAbsY(parentBox) + "px";
box.style.left = getAbsX(parentBox) + "px";
box.style.visibility='visible';
}
function hidebox(boxId) {
'use strict';
var box = document.getElementById(boxId);
box.style.visibility='hidden';
}
// get the true X offset of anything on NS4, IE4/5 &
// NS6, even if it's in a table!
function getAbsX(elt) {
'use strict';
return (elt.x) ? elt.x : getAbsPos(elt,"Left");
}
// get the true Y offset of anything on NS4, IE4/5 &
// NS6, even if it's in a table!
function getAbsY(elt) {
'use strict';
return (elt.y) ? elt.y : getAbsPos(elt,"Top");
}
function getAbsPos(elt,which) {
'use strict';
var iPos = 0;
while (elt !== null) {
iPos += elt["offset" + which];
elt = elt.offsetParent;
}
return iPos;
}
| laffer1/justjournal | src/main/resources/static/js/jj.js | JavaScript | bsd-2-clause | 3,728 |
'use strict';
var ok = require('assert').ok;
const esprima = require('esprima');
function parseExpression(src, builder, isExpression) {
ok(typeof src === 'string', '"src" should be a string expression');
ok(builder, '"builder" is required');
function convert(node) {
if (Array.isArray(node)) {
let nodes = node;
for (let i=0; i<nodes.length; i++) {
var converted = convert(nodes[i]);
if (converted == null) {
return null;
}
nodes[i] = converted;
}
return nodes;
}
switch(node.type) {
case 'ArrayExpression': {
let elements = convert(node.elements);
if (!elements) {
return null;
}
return builder.arrayExpression(elements);
}
case 'AssignmentExpression': {
let left = convert(node.left);
if (!left) {
return null;
}
let right = convert(node.right);
if (!right) {
return null;
}
return builder.assignment(left, right, node.operator);
}
case 'BinaryExpression': {
let left = convert(node.left);
if (!left) {
return null;
}
let right = convert(node.right);
if (!right) {
return null;
}
return builder.binaryExpression(left, node.operator, right);
}
case 'CallExpression': {
let callee = convert(node.callee);
if (!callee) {
return null;
}
let args = convert(node.arguments);
if (!args) {
return null;
}
return builder.functionCall(callee, args);
}
case 'ConditionalExpression': {
let test = convert(node.test);
if (!test) {
return null;
}
let consequent = convert(node.consequent);
if (!consequent) {
return null;
}
let alternate = convert(node.alternate);
if (!alternate) {
return null;
}
return builder.conditionalExpression(test, consequent, alternate);
}
case 'ExpressionStatement': {
return convert(node.expression);
}
case 'FunctionDeclaration':
case 'FunctionExpression': {
let name = null;
if (node.id) {
name = convert(node.id);
if (name == null) {
return null;
}
}
let params = convert(node.params);
if (!params) {
return null;
}
let body = convert(node.body);
if (!body) {
return null;
}
return builder.functionDeclaration(name, params, body);
}
case 'Identifier': {
return builder.identifier(node.name);
}
case 'Literal': {
let literalValue;
if (node.regex) {
literalValue = new RegExp(node.regex.pattern, 'gi');
} else {
literalValue = node.value;
}
return builder.literal(literalValue);
}
case 'LogicalExpression': {
let left = convert(node.left);
if (!left) {
return null;
}
let right = convert(node.right);
if (!right) {
return null;
}
return builder.logicalExpression(left, node.operator, right);
}
case 'MemberExpression': {
let object = convert(node.object);
if (!object) {
return null;
}
let property = convert(node.property);
if (!property) {
return null;
}
return builder.memberExpression(object, property, node.computed);
}
case 'NewExpression': {
let callee = convert(node.callee);
if (!callee) {
return null;
}
let args = convert(node.arguments);
if (!args) {
return null;
}
return builder.newExpression(callee, args);
}
case 'Program': {
if (node.body && node.body.length === 1) {
return convert(node.body[0]);
}
return null;
}
case 'ObjectExpression': {
let properties = convert(node.properties);
if (!properties) {
return null;
}
return builder.objectExpression(properties);
}
case 'Property': {
let key = convert(node.key);
if (!key) {
return null;
}
let value = convert(node.value);
if (!value) {
return null;
}
return builder.property(key, value);
}
case 'ThisExpression': {
return builder.thisExpression();
}
case 'UnaryExpression': {
let argument = convert(node.argument);
if (!argument) {
return null;
}
return builder.unaryExpression(argument, node.operator, node.prefix);
}
case 'UpdateExpression': {
let argument = convert(node.argument);
if (!argument) {
return null;
}
return builder.updateExpression(argument, node.operator, node.prefix);
}
default:
return null;
}
}
let jsAST;
try {
if (isExpression) {
src = '(' + src + ')';
}
jsAST = esprima.parse(src);
} catch(e) {
if (e.index == null) {
// Doesn't look like an Esprima parse error... just rethrow the exception
throw e;
}
var errorIndex = e.index;
var errorMessage = '\n' + e.description;
if (errorIndex != null && errorIndex >= 0) {
if (isExpression) {
errorIndex--; // Account for extra paren added to start
}
errorMessage += ': ';
errorMessage += src + '\n'+ new Array(errorMessage.length + errorIndex + 1).join(" ") + '^';
}
var wrappedError = new Error(errorMessage);
wrappedError.index = errorIndex;
wrappedError.src = src;
wrappedError.code = 'ERR_INVALID_JAVASCRIPT_EXPRESSION';
throw wrappedError;
}
var converted = convert(jsAST);
if (converted == null) {
converted = builder.expression(src);
}
return converted;
}
module.exports = parseExpression;
| ticolucci/dotfiles | atom/packages/atom-beautify/node_modules/marko/compiler/util/parseJavaScript.js | JavaScript | bsd-2-clause | 7,632 |
/**
* Created by Primoz on 20.7.2016.
*/
let renderingController = function($scope, SettingsService, InputService, TaskManagerService, Annotations, PublicRenderData, SharingService) {
// Context
let self = this;
// Required programs
this.requiredPrograms = ['basic', 'phong', 'custom_overlayTextures', 'custom_drawOnTexture', 'custom_copyTexture', 'custom_redrawOnTexture'];
$scope.annotations = Annotations;
// Private renderer components
this.renderer = null;
this.renderQueue = null;
this.redrawQueue = null;
this.cameraManager = PublicRenderData.cameraManager;
this.raycaster = null;
this.scene = null;
// This ID is used for stopping and starting animation loop
this.animationRequestId = null;
// Public rendering data (used in scene collaboration)
PublicRenderData.contentRenderGroup = new M3D.Group();
let offsetDir = new THREE.Vector3(0.577, 0.577, 0.577);
/**
* Make function to replace content on the scene publicly available in the PublicRenderData
* @param objects
*/
PublicRenderData.replaceRenderContent = function (...objects) {
$scope.stopRenderLoop();
PublicRenderData.contentRenderGroup.clear();
self.renderer.clearCachedAttributes();
$scope.$apply(Annotations.clear);
// Add new render content
for (let i = 0; i < objects.length; i++) {
PublicRenderData.contentRenderGroup.add(objects[i]);
}
// Calculate content bounding sphere
let contentSphere = PublicRenderData.contentRenderGroup.computeBoundingSphere();
// Focus all of the cameras on the newly added object
self.cameraManager.focusCamerasOn(contentSphere, offsetDir);
$scope.startRenderLoop();
};
/**
* Initializes and stores the renderer instance created by the canvas directive.
* @param renderer {M3D.Renderer} Mesh renderer created by the canvasDirective
* @param width {number} canvas width
* @param height {number} canvas height
*/
$scope.init = function (renderer, canvas) {
PublicRenderData.canvasDimensions = {width: canvas.clientWidth, height: canvas.clientHeight};
InputService.setMouseSourceObject(canvas);
// Store reference to renderer
self.renderer = renderer;
// Pre-download the programs that will likely be used
self.renderer.preDownloadPrograms(self.requiredPrograms);
// Initialize raycaster
self.raycaster = new M3D.Raycaster();
// Camera initialization
let camera = new M3D.PerspectiveCamera(60, PublicRenderData.canvasDimensions.width / PublicRenderData.canvasDimensions.height, 0.1, 2000);
camera.position = new THREE.Vector3(0, 0, 200);
// Add camera to public render data
//self.cameraManager.addRegularCamera(camera);
self.cameraManager.addOrbitCamera(camera, new THREE.Vector3(0, 0, 0));
self.cameraManager.setActiveCamera(camera);
self.initializeRenderQueues();
};
/**
* Handle function used to propagate canvas resize event from canvas directive to the renderer so that viewport and camera
* aspect ratio can be corrected.
* @param width New width of the canvas.
* @param height New height of the canvas
*/
$scope.resizeCanvas = function (width, height) {
PublicRenderData.canvasDimensions = {width: width, height: height};
self.cameraManager.aspectRatio = width/height;
};
// region Annotations
this.annotationRenderGroup = new M3D.Group();
this.createMarker = function () {
var marker = {};
marker.point = new M3D.Circle(0.35, 40);
marker.point.setVerticesColors(new THREE.Color("#FFFFFF"), new THREE.Color("#FFFFFF"), 0.3, 0);
marker.point.material.useVertexColors = true;
marker.point.material.transparent = true;
marker.point.material.side = M3D.FRONT_AND_BACK;
marker.point.position.set(0, 0, 0);
marker.line = new M3D.Line([]);
marker.line.frustumCulled = false;
return marker;
};
$scope.newAnnotationClick = function () {
let intersectionNormal = new THREE.Vector3();
return function() {
// Set raycaster parameters
self.raycaster.setFromCamera(InputService.getInputData().mouse.position, self.cameraManager.activeCamera);
// Fetch object intersections
let intersects = self.raycaster.intersectObjects(PublicRenderData.contentRenderGroup.children, true);
// Do not continue if there aren't any intersects
if (intersects.length > 0) {
// Check if marker needs to be created
if (Annotations.newAnnotation.marker === undefined) {
Annotations.newAnnotation.marker = self.createMarker();
}
let marker = Annotations.newAnnotation.marker;
// Calculate intersected triangle normal
intersectionNormal = intersectionNormal.crossVectors((new THREE.Vector3()).subVectors(intersects[0].triangle[1], intersects[0].triangle[0]), (new THREE.Vector3()).subVectors(intersects[0].triangle[2], intersects[0].triangle[0])).normalize();
// Store marker position and normal
Annotations.newAnnotation.markerMeta = { position: marker.point.position, normal: intersectionNormal.clone() };
// Look at intersected triangle normal
marker.point.position = new THREE.Vector3(0, 0, 0);
marker.point.lookAt(intersectionNormal, new THREE.Vector3(0, 0, 1));
marker.point.position = intersects[0].point.add(intersectionNormal.multiplyScalar(0.1));
}
}
}();
this.updateAnnotations = function () {
let updateMarker = function (annItem) {
let activeCamera = self.cameraManager.activeCamera;
// Update camera matrix so we can correctly un-project the modal position
activeCamera.updateMatrixWorld();
// Calculate modal 3D position
let modalPos = new THREE.Vector3(
(annItem.windowPosition.offset.left / window.innerWidth) * 2 - 1, //x
-(annItem.windowPosition.offset.top / window.innerHeight) * 2 + 1, //y
0.5);
modalPos.unproject(activeCamera);
let dir = modalPos.sub(activeCamera.position).normalize();
let distance = -0.2 / -Math.abs(dir.z);
let pos = activeCamera.position.clone().add(dir.multiplyScalar(distance));
// Check if marker exists
if (annItem.marker === undefined) {
annItem.marker = self.createMarker();
// Setup marker parameters
annItem.marker.point.lookAt(annItem.markerMeta.normal, new THREE.Vector3(0, 0, 1));
annItem.marker.point.position = annItem.markerMeta.position.clone();
}
// Setup line
annItem.marker.line.setPoints([annItem.marker.point.position.x, annItem.marker.point.position.y, annItem.marker.point.position.z, pos.x, pos.y, pos.z]);
// Add pins to draw group
self.annotationRenderGroup.add(annItem.marker.point);
self.annotationRenderGroup.add(annItem.marker.line);
};
return function() {
self.annotationRenderGroup.clear();
// New annotation
if (Annotations.newAnnotation && Annotations.newAnnotation.marker) {
updateMarker(Annotations.newAnnotation);
}
// Own annotations
for (let i = 0; i < Annotations.list.length; i++) {
let annItem = Annotations.list[i];
if (annItem.active && annItem.markerMeta !== undefined) {
updateMarker(annItem);
}
}
// Shared annotations
for (let userId in Annotations.sharedList) {
let annList = Annotations.sharedList[userId].list;
for (let i = 0; i < annList.length; i++) {
if (annList[i].active && annList[i].markerMeta !== undefined) {
updateMarker(annList[i]);
}
}
}
}
}();
/**
* Animates and locks the camera in place to align with the selected drawn annotation.
*/
$scope.$watch(function(){ return Annotations.selectedDrawnAnnotation; },
function (selectedAnnotation) {
let activeCamera = self.cameraManager.activeCamera;
self.cameraManager.cancelAnimation(activeCamera, "drawnAnnotationAnimation");
if (selectedAnnotation != null) {
// If the camera is already in position just lock it
if (self.cameraManager.isActiveCameraInPosition(selectedAnnotation._cameraPosition, selectedAnnotation._cameraRotation)) {
self.cameraManager.lockCamera(activeCamera);
}
else {
// Animate the camera in place
self.cameraManager.animateCameraTo(activeCamera, "drawnAnnotationAnimation",
selectedAnnotation._cameraPosition, selectedAnnotation._cameraRotation, 1500,
function () {
self.cameraManager.lockCamera(activeCamera);
})
}
}
else if (self.cameraManager.isCameraLocked(activeCamera)) {
// Unlock the camera if no annotation is selected
self.cameraManager.unlockCamera(activeCamera);
}
});
// endregion
// region RENDER QUEUE
// region MAIN RENDER PASS
let MainRenderPass = new M3D.RenderPass(
// Rendering pass type
M3D.RenderPass.BASIC,
// Initialize function
function(textureMap, additionalData) {
// Create new scene
self.scene = new M3D.Scene();
// Initialize lights and add them to the scene
let aLight = new M3D.AmbientLight(new THREE.Color("#444444"), 1);
let dLightFirst = new M3D.DirectionalLight(new THREE.Color("#FFFFFF"), 0.6);
let dLightSecond = new M3D.DirectionalLight(new THREE.Color("#FFFFFF"), 0.6);
let dLightThird = new M3D.DirectionalLight(new THREE.Color("#FFFFFF"), 0.6);
dLightFirst.position = new THREE.Vector3(0, -1, 0);
dLightSecond.position = new THREE.Vector3(0.333, 0.333, -0.334);
dLightThird.position = new THREE.Vector3(-0.333, 0.333, 0.334);
self.scene.add(aLight);
self.scene.add(dLightFirst);
self.scene.add(dLightSecond);
self.scene.add(dLightThird);
self.scene.add(PublicRenderData.contentRenderGroup);
self.scene.add(self.annotationRenderGroup);
},
// Preprocess function
function (textureMap, additionalData) {
// Update renderer viewport
this.viewport = PublicRenderData.canvasDimensions;
self.renderer.clearColor = "#C8C7C7FF";
// Annotation render group update
self.updateAnnotations();
return {scene: self.scene, camera: self.cameraManager.activeCamera};
},
// Target
M3D.RenderPass.TEXTURE,
// Viewport
PublicRenderData.canvasDimensions,
// Bind depth texture to this ID
"MainRenderDepth",
[{id: "MainRenderTex", textureConfig: M3D.RenderPass.DEFAULT_RGBA_TEXTURE_CONFIG}]
);
// endregion
// region DRAWING RENDER PASS
let DrawingRenderPass = new M3D.RenderPass(
M3D.RenderPass.TEXTURE_MERGE,
// Initialize function
function(textureMap, additionalData) {
additionalData['DrawingShaderMaterial'] = new M3D.CustomShaderMaterial("drawOnTexture");
// Mouse start and end position
additionalData['prevMouseState'] = false;
additionalData['mousePrevTex'] = new THREE.Vector2();
additionalData['mouseCurrTex'] = new THREE.Vector2();
additionalData['mouseTexNorm'] = new THREE.Vector2();
additionalData['drawnAnnCamInPosition'] = false;
textureMap['HelperTexture'] = new M3D.Texture();
textureMap['HelperTexture'].applyConfig(M3D.RenderPass.DEFAULT_RGBA_TEXTURE_CONFIG);
textureMap['OutTexture'] = null;
},
// Preprocess function
function (textureMap, additionalData) {
// Render pass self reference
let passSelf = this;
// Fetch the currently selected drawn annotation
let selectedAnnotation = Annotations.selectedDrawnAnnotation;
// Reset textures
textureMap.OutTexture = null;
textureMap.TargetTexture = null;
if (selectedAnnotation != null) {
additionalData.drawnAnnCamInPosition = self.cameraManager.isActiveCameraInPosition(selectedAnnotation._cameraPosition, selectedAnnotation._cameraRotation);
// Do the animation
if (!additionalData.drawnAnnCamInPosition) {
return null;
}
// If the drawing is enabled setup the textures otherwise skip this pass
if (selectedAnnotation.drawLayer != null) {
textureMap.OutTexture = textureMap.HelperTexture;
textureMap.TargetTexture = selectedAnnotation.drawLayer.texture;
}
else {
return null;
}
}
else {
additionalData.drawnAnnCamInPosition = false;
return null;
}
// Fetch the drawing CustomShaderMaterial
let drawingShaderMaterial = additionalData['DrawingShaderMaterial'];
// Fetch mouse input data
let mouseInput = InputService.getInputData().mouse;
if (mouseInput.buttons.left) {
// Check if the left button was pressed in the previous pass
$scope.$apply(function () {
if (additionalData.prevMouseState) {
additionalData.mousePrevTex.copy(additionalData.mouseCurrTex);
additionalData.mouseCurrTex.set((mouseInput.position.x + 1) / 2, (mouseInput.position.y + 1) / 2);
// Normalize mouse position for storage
additionalData.mouseTexNorm.copy(additionalData.mouseCurrTex);
additionalData.mouseTexNorm.x = (additionalData.mouseTexNorm.x - 0.5) / passSelf.viewport.height * passSelf.viewport.width;
selectedAnnotation.drawLayer.addLinePoint(additionalData.mouseTexNorm);
}
else {
additionalData.mouseCurrTex.set((mouseInput.position.x + 1) / 2, (mouseInput.position.y + 1) / 2);
additionalData.mousePrevTex.copy(additionalData.mouseCurrTex);
// Normalize mouse position for storage
additionalData.mouseTexNorm.copy(additionalData.mouseCurrTex);
additionalData.mouseTexNorm.x = (additionalData.mouseTexNorm.x - 0.5) / passSelf.viewport.height * passSelf.viewport.width;
selectedAnnotation.drawLayer.createNewLineEntry(additionalData.mouseTexNorm, PublicRenderData.lineThickness, PublicRenderData.lineHardness, PublicRenderData.lineColor);
}
});
}
// Update prev mouse state for the next pass
additionalData.prevMouseState = mouseInput.buttons.left;
// Make line thickness resolution independent
let normalisedThickness = (PublicRenderData.lineThickness / this.viewport.width);
// Update the viewport
this.viewport = PublicRenderData.canvasDimensions;
self.renderer.clearColor = "#00000000";
// Set uniforms
drawingShaderMaterial.setUniform("draw", mouseInput.buttons.left);
drawingShaderMaterial.setUniform("thickness", normalisedThickness);
drawingShaderMaterial.setUniform("hardness", PublicRenderData.lineHardness);
drawingShaderMaterial.setUniform("brushColor", PublicRenderData.lineColor.toArray());
drawingShaderMaterial.setUniform("mouseA", additionalData.mousePrevTex.toArray());
drawingShaderMaterial.setUniform("mouseB", additionalData.mouseCurrTex.toArray());
return {material: drawingShaderMaterial, textures: [textureMap['TargetTexture']]};
},
M3D.RenderPass.TEXTURE,
PublicRenderData.canvasDimensions,
null,
[{id: "OutTexture", textureConfig: M3D.RenderPass.DEFAULT_RGBA_TEXTURE_CONFIG}]
);
// endregion
// region COPY TEXTURE PASS
let CopyDrawingTexturePass = new M3D.RenderPass(
M3D.RenderPass.TEXTURE_MERGE,
// Initialize function
function(textureMap, additionalData) {
additionalData['CopyTextureMaterial'] = new M3D.CustomShaderMaterial("copyTexture");
},
// Preprocess function
function (textureMap, additionalData) {
// Set the viewport to match the desired resolution
this.viewport = PublicRenderData.canvasDimensions;
// Do not copy texture if there was nothing drawn
if (textureMap["OutTexture"] == null) {
return null;
}
return {material: additionalData['CopyTextureMaterial'] , textures: [textureMap["OutTexture"]]};
},
M3D.RenderPass.TEXTURE,
PublicRenderData.canvasDimensions,
null,
[{id: "TargetTexture", textureConfig: M3D.RenderPass.DEFAULT_RGBA_TEXTURE_CONFIG}]
);
// endregion
// region OVERLAY TEXTURES PASS
let OverlayRenderPass = new M3D.RenderPass(
M3D.RenderPass.TEXTURE_MERGE,
// Initialize function
function(textureMap, additionalData) {
/**
* TEXTURE BLENDING glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
*/
additionalData['OverlayTextureMaterial'] = new M3D.CustomShaderMaterial("overlayTextures");
},
// Preprocess function
function (textureMap, additionalData) {
let selectedAnnotation = Annotations.selectedDrawnAnnotation;
// If the viewport had changed significantly redraw the lines
let canvasDim = PublicRenderData.canvasDimensions;
// Redraw on canvas resize
if (Math.abs(this.viewport.width - canvasDim.width) > 10 || Math.abs(this.viewport.height - canvasDim.height) > 10) {
let selectedAnnotation = Annotations.selectedDrawnAnnotation;
this.viewport = canvasDim;
if (selectedAnnotation != null) {
for (let i = 0; i < selectedAnnotation.layers.length; i++) {
let layer = selectedAnnotation.layers[i];
if (layer.lines.length <= 0) {
continue;
}
self.redrawQueue.addTexture("RedrawTexture", layer.texture);
self.redrawQueue.setDataValue("lines", layer.lines);
self.redrawQueue.setDataValue("viewport", canvasDim);
// Redraw all of the lines
let data;
do {
data = self.redrawQueue.render();
} while (!data.additionalData["finished"]);
layer.dirty = false;
}
textureMap['OutTexture'] = null;
textureMap['TargetTexture'] = null;
}
}
// Redraw dirty layers
if (selectedAnnotation != null) {
for (let i = 0; i < selectedAnnotation.layers.length; i++) {
let layer = selectedAnnotation.layers[i];
if (!layer.dirty) {
continue;
}
self.redrawQueue.addTexture("RedrawTexture", layer.texture);
self.redrawQueue.setDataValue("lines", layer.lines);
self.redrawQueue.setDataValue("viewport", canvasDim);
// Redraw all of the lines
let data;
do {
data = self.redrawQueue.render();
} while (!data.additionalData["finished"]);
layer.dirty = false;
}
}
let textures = [textureMap["MainRenderTex"]];
// Add draw layers if the camera is in position
if (selectedAnnotation != null && additionalData.drawnAnnCamInPosition) {
for (let i = selectedAnnotation.layers.length - 1; i >= 0; i--) {
let layer = selectedAnnotation.layers[i];
if (layer.isDisplayed && layer.lines.length > 0) {
textures.push(layer.texture);
}
}
}
return {material: additionalData['OverlayTextureMaterial'], textures: textures};
},
M3D.RenderPass.SCREEN,
PublicRenderData.canvasDimensions
);
// endregion
// endregion
// region REDRAW QUEUE
const MAX_POINTS = 500;
// region REDRAW RENDER PASS
let RedrawRenderPass = new M3D.RenderPass(
M3D.RenderPass.TEXTURE_MERGE,
// Initialize function
function(textureMap, additionalData) {
additionalData['RedrawingShaderMaterial'] = new M3D.CustomShaderMaterial("redrawOnTexture");
textureMap['HelperTexture'] = new M3D.Texture();
textureMap['HelperTexture'].applyConfig(M3D.RenderPass.DEFAULT_RGBA_TEXTURE_CONFIG);
additionalData['indices'] = {line: 0, points: 0}
},
// Preprocess function
function (textureMap, additionalData) {
// Reset finished flag
additionalData['finished'] = false;
// Set the viewport to match the desired resolution
this.viewport = additionalData['viewport'];
// Set clear color to transparent
self.renderer.clearColor = "#00000000";
// Fetch line colors
let lines = additionalData['lines'];
let indices = additionalData['indices'];
// Current line
let currentLine = lines[indices.line];
let normalisedThickness = 0,
hardness = 0,
color = [0, 0, 0],
firstRender = indices.line === 0 && indices.points === 0,
selectedPoints = [0, 0],
numPoints = 0;
if (currentLine != null) {
// Calculate normalised thicknes
normalisedThickness = (currentLine.thickness / this.viewport.width);
hardness = lines[indices.line].hardness;
color = lines[indices.line].color;
// Points
let upperBoundary = Math.min(indices.points + MAX_POINTS * 2, currentLine.points.length);
selectedPoints = currentLine.points.slice(indices.points, upperBoundary);
numPoints = selectedPoints.length / 2; // Each point is represented by two values
// Check if line is fully drawn
if (upperBoundary === currentLine.points.length) {
indices.points = 0;
indices.line++;
// If we have drawn all of the lines set the finished flag.
if (indices.line >= lines.length) {
additionalData['finished'] = true;
// Reset values for the next redraw
indices.points = 0;
indices.line = 0;
}
}
else {
// Move starting point forward
indices.points = upperBoundary - 2;
}
}
else {
additionalData['finished'] = true;
}
let redrawingShaderMaterial = additionalData['RedrawingShaderMaterial'];
// Set uniforms
redrawingShaderMaterial.setUniform("thickness", normalisedThickness);
redrawingShaderMaterial.setUniform("hardness", hardness);
redrawingShaderMaterial.setUniform("linePoints[0]", selectedPoints);
redrawingShaderMaterial.setUniform("numPoints", numPoints);
redrawingShaderMaterial.setUniform("brushColor", color);
redrawingShaderMaterial.setUniform("canvasWidth", this.viewport.width);
redrawingShaderMaterial.setUniform("canvasHeight", this.viewport.height);
let textures = [];
// If this is not a first render input the previous texture to use it as a base
if (!firstRender) {
textures.push(textureMap['RedrawTexture'])
}
return {material: redrawingShaderMaterial, textures: textures};
},
M3D.RenderPass.TEXTURE,
PublicRenderData.canvasDimensions,
null,
[{id: "HelperTexture", textureConfig: M3D.RenderPass.DEFAULT_RGBA_TEXTURE_CONFIG}]
);
// endregion
// region COPY RENDER PASS
let RedrawCopyTexturePass = new M3D.RenderPass(
M3D.RenderPass.TEXTURE_MERGE,
// Initialize function
function(textureMap, additionalData) {
additionalData['CopyTextureMaterial'] = new M3D.CustomShaderMaterial("copyTexture");
},
// Preprocess function
function (textureMap, additionalData) {
// Set the viewport to match the desired resolution
this.viewport = additionalData['viewport'];
return {material: additionalData['CopyTextureMaterial'] , textures: [textureMap["HelperTexture"]]};
},
M3D.RenderPass.TEXTURE,
PublicRenderData.canvasDimensions,
null,
[{id: "RedrawTexture", textureConfig: M3D.RenderPass.DEFAULT_RGBA_TEXTURE_CONFIG}]
);
// endregion
// endregion
this.initializeRenderQueues = function () {
self.renderQueue = new M3D.RenderQueue(self.renderer);
self.redrawQueue = new M3D.RenderQueue(self.renderer);
self.renderQueue.pushRenderPass(MainRenderPass);
self.renderQueue.pushRenderPass(DrawingRenderPass);
self.renderQueue.pushRenderPass(CopyDrawingTexturePass);
self.renderQueue.pushRenderPass(OverlayRenderPass);
self.redrawQueue.pushRenderPass(RedrawRenderPass);
self.redrawQueue.pushRenderPass(RedrawCopyTexturePass);
};
// region RENDER LOOP
/**
* Starts rendering loop if it's not running already.
*/
$scope.startRenderLoop = function () {
if (!animationRequestId) {
self.renderLoop();
}
$scope.$apply(function () {
PublicRenderData.renderingInProgress = true;
});
};
/**
* Stops rendering loop.
*/
$scope.stopRenderLoop = function () {
if (self.animationRequestId) {
cancelAnimationFrame(self.animationRequestId);
self.animationRequestId = null;
}
prevTime = -1;
$scope.$apply(function () {
PublicRenderData.renderingInProgress = false;
});
};
/**
* Main animation loop.
*/
let prevTime = -1, currTime;
this.renderLoop = function() {
self.animationRequestId = requestAnimationFrame(self.renderLoop);
// Update input data
let inputData = InputService.update();
// Calculate delta time and update timestamps
currTime = new Date();
let deltaT = (prevTime !== -1) ? currTime - prevTime : 0;
prevTime = currTime;
// Update the camera
self.cameraManager.update(inputData, deltaT);
// Render the scene
self.renderQueue.render();
// Update scene collaboration
SharingService.update();
};
// endregion
TaskManagerService.addResultCallback("ObjLoader", PublicRenderData.replaceRenderContent);
TaskManagerService.addResultCallback("MHDLoader", PublicRenderData.replaceRenderContent);
// endregion
};
app.controller('RenderingController', renderingController); | UL-FRI-LGM/Med3D | web/app/components/rendering/renderingController.js | JavaScript | bsd-2-clause | 28,938 |
"use strict";
module.exports = {
tagName: "div",
className: "",
defaults: {
content: "default content"
},
render: function() {
},
client: function(options) {
var result = options.client_options.result;
var session = result.data.session;
var total = session.count;
var cell_count;
var cells = $("<div/>");
var index;
var helpers = this.helpers;
var color_picker = this.helpers['vendor/jquery.colors'].get_color;
for (index = 0; index < total; index++) {
cell_count = session[index] || 0;
var opacity = Math.round(cell_count / parseFloat(session.active) * 100.0) / 100;
var color = color_picker(result.sid);
var div = $("<div />")
.html("<div style='width: 10px; height: 20px' />")
.css("background-color", color)
.css("opacity", opacity || "0.001");
cells.append(div);
}
this.$el.find(".viz").append(cells);
}
};
| logV/superfluous | superfluous/app/plugins/mars/components/paragraph_viz/paragraph_viz.js | JavaScript | bsd-2-clause | 948 |
var NN = NN || {};
NN.InstructionsState = NN.InstructionsState || {};
NN.InstructionsState.init = function(levelnum) {
this.game.stage.backgroundColor = '#00f';
this.levelnum = levelnum;
this.GAMEX = this.game.world.width;
this.GAMEY = this.game.world.height;
};
NN.InstructionsState.preload = function() {
};
NN.InstructionsState.create = function() {
var background = this.game.add.sprite(0,0,'instructions');
background.inputEnabled = true;
background.x = 0;
background.y = 0;
background.height = this.GAMEY;
background.width = this.GAMEX;
// background.scaleX = (0.5);
// background.scaleY = (0.2);
// background.scaleX = (this.GAMEX / background.width);
// background.scaleY = (this.GAMEY / background.height);
var style = {font: 'bold 24pt Arial', fill: '#0f0'};
var words1 = this.game.add.text(this.GAMEX/2, this.GAMEY / 3, 'Text', style);
var words2 = this.game.add.text(this.GAMEX/2, this.GAMEY / 2, 'Text', style);
var words3 = this.game.add.text(this.GAMEX/2, this.GAMEY * 2 / 3, 'Text', style);
words1.anchor.setTo(0.5);
words2.anchor.setTo(0.5);
words3.anchor.setTo(0.5);
if ( this.levelnum == 1 ) {
words1.text = 'Swipe to move';
words2.text = 'and tap to nab';
words3.text = 'all the answers';
}
if ( this.levelnum == 2 ) {
words1.text = 'The answers are';
words2.text = 'multiples of the';
words3.text = 'current level';
}
if ( this.levelnum == 3 ) {
words1.text = 'Enjoy your last';
words2.text = 'level without';
words3.text = 'enemies!';
}
background.events.onInputDown.add(function() {
this.startGameState();
}, this);
};
NN.InstructionsState.startGameState = function(button) {
this.state.start('GameState', true, false, this.levelnum, true);
};
| elegantelephant/NumberNabber | js/states/Instructions.js | JavaScript | bsd-2-clause | 1,888 |
MessagesStore | kristijan-pajtasev/ChatBOx | dev/js/.module-cache/de6546b2c9685657e1a6a668adbc9d9f63aaa6bd.js | JavaScript | bsd-2-clause | 13 |
/*jslint node: true*/
/*jslint expr: true*/
/*global describe, it*/
"use strict";
var irc = require('../..');
var Stream = require('stream').PassThrough;
describe('mode.js', function () {
describe('on MODE', function () {
it('should parse usermode', function (done) {
var stream = new Stream(),
client = irc(stream, false);
client.on('mode', function (err, event) {
event.by.getNick().should.equal('foo');
event.adding.should.equal(true);
event.mode.should.equal('x');
done();
});
stream.write(':foo!bar@baz.com MODE test +x\r\n');
});
it('should parse usermode aswell', function (done) {
var stream = new Stream(),
client = irc(stream, false);
client.once('mode', function (err, event) {
event.by.should.equal('foo');
event.adding.should.equal(true);
event.mode.should.equal('Z');
client.once('mode', function (err, event) {
event.by.should.equal('foo');
event.adding.should.equal(true);
event.mode.should.equal('i');
done();
});
});
stream.write(':foo MODE foo :+Zi\r\n');
});
it('should parse channelmode', function (done) {
var stream = new Stream(),
client = irc(stream, false);
client.once('mode', function (err, event) {
event.channel.getName().should.equal('#foo');
event.by.getNick().should.equal('foo');
event.argument.should.equal('bar');
event.adding.should.equal(false);
event.mode.should.equal('o');
client.once('mode', function (err, event) {
event.channel.getName().should.equal('#foo');
event.by.getNick().should.equal('foo');
event.argument.should.equal('baz');
event.adding.should.equal(true);
event.mode.should.equal('v');
client.once('mode', function (err, event) {
event.channel.getName().should.equal('#foo');
event.by.getNick().should.equal('op');
event.argument.should.equal('badguy');
event.adding.should.equal(true);
event.mode.should.equal('b');
done();
});
});
});
stream.write(':foo!bar@baz.com MODE #foo -o+v bar baz\r\n');
stream.write(':op!bar@baz.com MODE #foo +b badguy\r\n');
});
});
});
| sagax/fgbot_coffea | test/plugins/mode.js | JavaScript | bsd-2-clause | 2,812 |
"use strict";
var antlr4 = require('antlr4/index');
var LambdaCalculusLexer = require("../antlr/generated/LambdaCalculusLexer");
var LambdaCalculusParser = require("../antlr/generated/LambdaCalculusParser");
var AstCreator = require("./ParseTreeListeningAstCreator").AstCreator;
var Immutable = require('immutable');
module.exports.AntlrParser = function () {
var self = {};
self.parse = function (input) {
var chars = new antlr4.InputStream(input);
var lexer = new LambdaCalculusLexer.LambdaCalculusLexer(chars);
var tokens = new antlr4.CommonTokenStream(lexer);
var parser = new LambdaCalculusParser.LambdaCalculusParser(tokens);
parser.buildParseTrees = true;
var tree = parser.expression();
var astCreator = new AstCreator();
var result = tree.accept(astCreator);
// todo - implement error handling
return Immutable.fromJS({
value: result,
status: true
});
};
return self;
}(); | supersven/lambda-core | lib/AntlrParser.js | JavaScript | bsd-2-clause | 1,018 |
/* */
"use strict";
var __extends = (this && this.__extends) || function(d, b) {
for (var p in b)
if (b.hasOwnProperty(p))
d[p] = b[p];
function __() {
this.constructor = d;
}
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var ArrayObservable_1 = require('../observable/ArrayObservable');
var isArray_1 = require('../util/isArray');
var Subscriber_1 = require('../Subscriber');
var OuterSubscriber_1 = require('../OuterSubscriber');
var subscribeToResult_1 = require('../util/subscribeToResult');
var iterator_1 = require('../symbol/iterator');
function zipProto() {
var observables = [];
for (var _i = 0; _i < arguments.length; _i++) {
observables[_i - 0] = arguments[_i];
}
return this.lift.call(zipStatic.apply(void 0, [this].concat(observables)));
}
exports.zipProto = zipProto;
function zipStatic() {
var observables = [];
for (var _i = 0; _i < arguments.length; _i++) {
observables[_i - 0] = arguments[_i];
}
var project = observables[observables.length - 1];
if (typeof project === 'function') {
observables.pop();
}
return new ArrayObservable_1.ArrayObservable(observables).lift(new ZipOperator(project));
}
exports.zipStatic = zipStatic;
var ZipOperator = (function() {
function ZipOperator(project) {
this.project = project;
}
ZipOperator.prototype.call = function(subscriber, source) {
return source.subscribe(new ZipSubscriber(subscriber, this.project));
};
return ZipOperator;
}());
exports.ZipOperator = ZipOperator;
var ZipSubscriber = (function(_super) {
__extends(ZipSubscriber, _super);
function ZipSubscriber(destination, project, values) {
if (values === void 0) {
values = Object.create(null);
}
_super.call(this, destination);
this.iterators = [];
this.active = 0;
this.project = (typeof project === 'function') ? project : null;
this.values = values;
}
ZipSubscriber.prototype._next = function(value) {
var iterators = this.iterators;
if (isArray_1.isArray(value)) {
iterators.push(new StaticArrayIterator(value));
} else if (typeof value[iterator_1.$$iterator] === 'function') {
iterators.push(new StaticIterator(value[iterator_1.$$iterator]()));
} else {
iterators.push(new ZipBufferIterator(this.destination, this, value));
}
};
ZipSubscriber.prototype._complete = function() {
var iterators = this.iterators;
var len = iterators.length;
this.active = len;
for (var i = 0; i < len; i++) {
var iterator = iterators[i];
if (iterator.stillUnsubscribed) {
this.add(iterator.subscribe(iterator, i));
} else {
this.active--;
}
}
};
ZipSubscriber.prototype.notifyInactive = function() {
this.active--;
if (this.active === 0) {
this.destination.complete();
}
};
ZipSubscriber.prototype.checkIterators = function() {
var iterators = this.iterators;
var len = iterators.length;
var destination = this.destination;
for (var i = 0; i < len; i++) {
var iterator = iterators[i];
if (typeof iterator.hasValue === 'function' && !iterator.hasValue()) {
return;
}
}
var shouldComplete = false;
var args = [];
for (var i = 0; i < len; i++) {
var iterator = iterators[i];
var result = iterator.next();
if (iterator.hasCompleted()) {
shouldComplete = true;
}
if (result.done) {
destination.complete();
return;
}
args.push(result.value);
}
if (this.project) {
this._tryProject(args);
} else {
destination.next(args);
}
if (shouldComplete) {
destination.complete();
}
};
ZipSubscriber.prototype._tryProject = function(args) {
var result;
try {
result = this.project.apply(this, args);
} catch (err) {
this.destination.error(err);
return;
}
this.destination.next(result);
};
return ZipSubscriber;
}(Subscriber_1.Subscriber));
exports.ZipSubscriber = ZipSubscriber;
var StaticIterator = (function() {
function StaticIterator(iterator) {
this.iterator = iterator;
this.nextResult = iterator.next();
}
StaticIterator.prototype.hasValue = function() {
return true;
};
StaticIterator.prototype.next = function() {
var result = this.nextResult;
this.nextResult = this.iterator.next();
return result;
};
StaticIterator.prototype.hasCompleted = function() {
var nextResult = this.nextResult;
return nextResult && nextResult.done;
};
return StaticIterator;
}());
var StaticArrayIterator = (function() {
function StaticArrayIterator(array) {
this.array = array;
this.index = 0;
this.length = 0;
this.length = array.length;
}
StaticArrayIterator.prototype[iterator_1.$$iterator] = function() {
return this;
};
StaticArrayIterator.prototype.next = function(value) {
var i = this.index++;
var array = this.array;
return i < this.length ? {
value: array[i],
done: false
} : {
value: null,
done: true
};
};
StaticArrayIterator.prototype.hasValue = function() {
return this.array.length > this.index;
};
StaticArrayIterator.prototype.hasCompleted = function() {
return this.array.length === this.index;
};
return StaticArrayIterator;
}());
var ZipBufferIterator = (function(_super) {
__extends(ZipBufferIterator, _super);
function ZipBufferIterator(destination, parent, observable) {
_super.call(this, destination);
this.parent = parent;
this.observable = observable;
this.stillUnsubscribed = true;
this.buffer = [];
this.isComplete = false;
}
ZipBufferIterator.prototype[iterator_1.$$iterator] = function() {
return this;
};
ZipBufferIterator.prototype.next = function() {
var buffer = this.buffer;
if (buffer.length === 0 && this.isComplete) {
return {
value: null,
done: true
};
} else {
return {
value: buffer.shift(),
done: false
};
}
};
ZipBufferIterator.prototype.hasValue = function() {
return this.buffer.length > 0;
};
ZipBufferIterator.prototype.hasCompleted = function() {
return this.buffer.length === 0 && this.isComplete;
};
ZipBufferIterator.prototype.notifyComplete = function() {
if (this.buffer.length > 0) {
this.isComplete = true;
this.parent.notifyInactive();
} else {
this.destination.complete();
}
};
ZipBufferIterator.prototype.notifyNext = function(outerValue, innerValue, outerIndex, innerIndex, innerSub) {
this.buffer.push(innerValue);
this.parent.checkIterators();
};
ZipBufferIterator.prototype.subscribe = function(value, index) {
return subscribeToResult_1.subscribeToResult(this, this.observable, this, index);
};
return ZipBufferIterator;
}(OuterSubscriber_1.OuterSubscriber));
| poste9/crud | deps/npm/rxjs@5.0.3/operator/zip.js | JavaScript | bsd-2-clause | 6,928 |
/*
* Copyright (C) 2012 Google Inc. All rights reserved.
* Copyright (C) 2012 Zan Dobersek <zandobersek@gmail.com>
* Copyright (C) 2015 University of Washington.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
var WK = WK || {};
WK.BuilderHistoryDataSource = function(delegate, serverURL)
{
console.assert(serverURL);
this._serverURL = serverURL;
this._resultsCache = new Map;
this._delegate = delegate; // Used to get the testIndex.
}
WK.BuilderHistoryDataSource.prototype = {
// Public
fetchHistoryForBuilder: function(builder)
{
console.assert(builder instanceof WK.Builder, builder);
if (this._resultsCache.has(builder))
return this._resultsCache.get(builder);
var result = new Promise(function(resolve, reject) {
JSON.load(this.resultsURLForBuilder(builder), resolve, reject);
}.bind(this))
.then(this._processResultsPayloadForBuilder.bind(this, builder));
this._resultsCache.set(builder, result);
return result;
},
resultsURLForBuilder: function(builder)
{
console.assert(builder instanceof WK.Builder, builder);
const magicMasterString = "webkit.org";
const magicTestTypeString = "layout-tests";
const resultsFilename = "results-small.json"; // results.json?
return this._serverURL + 'testfile' +
'?builder=' + builder.name +
'&master=' + magicMasterString +
'&testtype=' + magicTestTypeString +
'&name=' + resultsFilename;
},
// Private
_processResultsPayloadForBuilder: function(builder, payload)
{
recursivelyFlattenObjectTrie = function(objectTrie, prefix) {
var resultsByTestName = new Map;
for (var part in objectTrie) {
var fullName = prefix ? prefix + "/" + part : part;
var data = objectTrie[part];
if ("results" in data) {
resultsByTestName.set(fullName, data);
continue;
}
recursivelyFlattenObjectTrie(data, fullName)
.forEach(function(value, key) {
resultsByTestName.set(key, value);
});
}
return resultsByTestName;
}
console.log(payload);
if (!_.has(payload, builder.name)) {
console.error("Mismatch between builder and payload: ", builder, payload);
throw new Error("Mismatch between builder and payload.");
}
if (!_.has(payload, "version") || parseInt(payload.version) < 4) {
console.error("Missing or unknown payload version: ", payload.version);
throw new Error("Missing or unknown payload version.");
}
var builderPayload = payload[builder.name];
var buildCount = builderPayload.buildNumbers.length;
builderRuns = [];
for (var i = 0; i < buildCount; ++i) {
var timestamp = builderPayload.secondsSinceEpoch[i];
var buildNumber = builderPayload.buildNumbers[i];
var revision = builderPayload.webkitRevision[i];
builderRuns.push(new WK.BuilderRun(builder, buildNumber, revision, timestamp));
}
// The data is returned as newest-first, but this is awkward for our
// time-series style visualizations. Reverse this and take care to reverse
// any congruent arrays.
builderRuns.reverse();
var testResults = recursivelyFlattenObjectTrie(builderPayload.tests);
return WK.BuilderHistory.fromPayload(builder, builderRuns, this._delegate.testIndex, testResults);
},
};
(function() {
loader = {}; // Kill me.
loader.Loader = function() {} // now.
loader.Loader.prototype = {
_processResultsJSONData: function(builderName, fileData)
{
var builds = JSON.parse(fileData);
var json_version = builds['version'];
for (var builderName in builds) {
if (builderName == 'version')
continue;
// If a test suite stops being run on a given builder, we don't want to show it.
// Assume any builder without a run in two weeks for a given test suite isn't
// running that suite anymore.
// FIXME: Grab which bots run which tests directly from the buildbot JSON instead.
var lastRunSeconds = builds[builderName].secondsSinceEpoch[0];
if ((Date.now() / 1000) - lastRunSeconds > ONE_WEEK_SECONDS)
continue;
if ((Date.now() / 1000) - lastRunSeconds > ONE_DAY_SECONDS)
this._staleBuilders.push(builderName);
if (json_version >= 4)
builds[builderName][TESTS_KEY] = loader.Loader._flattenTrie(builds[builderName][TESTS_KEY]);
g_resultsByBuilder[builderName] = builds[builderName];
}
},
_loadExpectationsFiles: function()
{
if (!isFlakinessDashboard() && !this._history.crossDashboardState.useTestData) {
this._loadNext();
return;
}
var expectationsFilesToRequest = {};
traversePlatformsTree(function(platform, platformName) {
if (platform.fallbackPlatforms)
platform.fallbackPlatforms.forEach(function(fallbackPlatform) {
var fallbackPlatformObject = platformObjectForName(fallbackPlatform);
if (fallbackPlatformObject.expectationsDirectory && !(fallbackPlatform in expectationsFilesToRequest))
expectationsFilesToRequest[fallbackPlatform] = EXPECTATIONS_URL_BASE_PATH + fallbackPlatformObject.expectationsDirectory + '/TestExpectations';
});
if (platform.expectationsDirectory)
expectationsFilesToRequest[platformName] = EXPECTATIONS_URL_BASE_PATH + platform.expectationsDirectory + '/TestExpectations';
});
for (platformWithExpectations in expectationsFilesToRequest)
loader.request(expectationsFilesToRequest[platformWithExpectations],
partial(function(loader, platformName, xhr) {
g_expectationsByPlatform[platformName] = getParsedExpectations(xhr.responseText);
delete expectationsFilesToRequest[platformName];
if (!Object.keys(expectationsFilesToRequest).length)
loader._loadNext();
}, this, platformWithExpectations),
partial(function(platformName, xhr) {
console.error('Could not load expectations file for ' + platformName);
}, platformWithExpectations));
},
}
})();
| CSE512-15S/fp-burg | dashboard/Models/BuilderHistoryDataSource.js | JavaScript | bsd-2-clause | 8,030 |
// This file was procedurally generated from the following sources:
// - src/dstr-binding/obj-ptrn-id-init-throws.case
// - src/dstr-binding/error/for-of-let.template
/*---
description: Error thrown when evaluating the initializer (for-of statement)
esid: sec-for-in-and-for-of-statements-runtime-semantics-labelledevaluation
es6id: 13.7.5.11
features: [destructuring-binding]
flags: [generated]
info: |
IterationStatement :
for ( ForDeclaration of AssignmentExpression ) Statement
[...]
3. Return ForIn/OfBodyEvaluation(ForDeclaration, Statement, keyResult,
lexicalBinding, labelSet).
13.7.5.13 Runtime Semantics: ForIn/OfBodyEvaluation
[...]
3. Let destructuring be IsDestructuring of lhs.
[...]
5. Repeat
[...]
h. If destructuring is false, then
[...]
i. Else
i. If lhsKind is assignment, then
[...]
ii. Else if lhsKind is varBinding, then
[...]
iii. Else,
1. Assert: lhsKind is lexicalBinding.
2. Assert: lhs is a ForDeclaration.
3. Let status be the result of performing BindingInitialization
for lhs passing nextValue and iterationEnv as arguments.
[...]
13.3.3.7 Runtime Semantics: KeyedBindingInitialization
SingleNameBinding : BindingIdentifier Initializeropt
[...]
6. If Initializer is present and v is undefined, then
a. Let defaultValue be the result of evaluating Initializer.
b. Let v be GetValue(defaultValue).
c. ReturnIfAbrupt(v).
---*/
function thrower() {
throw new Test262Error();
}
assert.throws(Test262Error, function() {
for (let { x = thrower() } of [{}]) {
return;
}
});
| sebastienros/jint | Jint.Tests.Test262/test/language/statements/for-of/dstr-let-obj-ptrn-id-init-throws.js | JavaScript | bsd-2-clause | 1,759 |
define(["mobile-detect"], function(MobileDetect){
function Factory(){
var md = new MobileDetect(window.navigator.userAgent);
return {
isMobile : function(){
return md.mobile();
}
};
}
return [Factory];
}); | Calculingua/cali-app | src/ng-corp/service/mobile-detect.js | JavaScript | bsd-2-clause | 309 |
module.exports = {
plugins: [
require('autoprefixer'),
require('postcss-nested')
]
}
| mshossain110/LaravelAdmin | postcss.config.js | JavaScript | bsd-2-clause | 109 |
var searchData=
[
['cdx_2dcompute_2dmultipath_2dspread_2dand_2denergy',['cdx-compute-multipath-spread-and-energy',['../cdx-compute-multipath-spread-and-energy.html',1,'']]],
['cdx_2dcompute_2dmultipath_2dto_2dline_2dof_2dsight_2dcomponents_2dpower_2dratio',['cdx-compute-multipath-to-line-of-sight-components-power-ratio',['../cdx-compute-multipath-to-line-of-sight-components-power-ratio.html',1,'']]],
['cdx_2dcompute_2dpower_2ddelay_2dprofile',['cdx-compute-power-delay-profile',['../cdx-compute-power-delay-profile.html',1,'']]],
['cdx_2dconvert_2dcontinuous_2dto_2ddiscrete_2ecpp',['cdx-convert-continuous-to-discrete.cpp',['../cdx-convert-continuous-to-discrete_8cpp.html',1,'']]],
['cdx_2ddisplay',['cdx-display',['../cdx-display.html',1,'']]],
['cdx_2dplot_2ddiscrete_2ddelay_2dfile',['cdx-plot-discrete-delay-file',['../cdx-plot-discrete-delay-file.html',1,'']]],
['cdxreadfile_2em',['CDXReadFile.m',['../CDXReadFile_8m.html',1,'']]],
['cdxwritefile_2em',['CDXWriteFile.m',['../CDXWriteFile_8m.html',1,'']]],
['convert_5fcontinuous_5fto_5fdiscrete_5fdelay_2em',['convert_continuous_to_discrete_delay.m',['../convert__continuous__to__discrete__delay_8m.html',1,'']]],
['create_5fnew_5fhdf5_5ffile_5fcontinuous_5fdelay_2em',['create_new_hdf5_file_continuous_delay.m',['../create__new__hdf5__file__continuous__delay_8m.html',1,'']]]
];
| fms13/cdx | documentation/html/search/files_1.js | JavaScript | bsd-2-clause | 1,362 |
/*
* repl.js
* Copyright (C) 2015 Kovid Goyal <kovid at kovidgoyal.net>
*
* Distributed under terms of the BSD license.
*/
"use strict"; /*jshint node:true */
var fs = require('fs');
var path = require('path');
var vm = require('vm');
var util = require('util');
var utils = require('./utils');
var completelib = require('./completer');
var colored = utils.safe_colored;
var RapydScript = (typeof create_rapydscript_compiler === 'function') ? create_rapydscript_compiler() : require('./compiler').create_compiler();
var has_prop = Object.prototype.hasOwnProperty.call.bind(Object.prototype.hasOwnProperty);
function create_ctx(baselib, show_js, console) {
var ctx = vm.createContext({'console':console, 'show_js': !!show_js, 'RapydScript':RapydScript, 'require':require});
vm.runInContext(baselib, ctx, {'filename':'baselib-plain-pretty.js'});
vm.runInContext('var __name__ = "__repl__";', ctx);
return ctx;
}
var homedir = process.env[(process.platform == 'win32') ? 'USERPROFILE' : 'HOME'];
var cachedir = expanduser(process.env.XDG_CACHE_HOME || '~/.cache');
function expanduser(x) {
if (!x) return x;
if (x === '~') return homedir;
if (x.slice(0, 2) != '~/') return x;
return path.join(homedir, x.slice(2));
}
function repl_defaults(options) {
options = options || {};
if (!options.input) options.input = process.stdin;
if (!options.output) options.output = process.stdout;
if (options.show_js === undefined) options.show_js = true;
if (!options.ps1) options.ps1 = '>>> ';
if (!options.ps2) options.ps2 = '... ';
if (!options.console) options.console = console;
if (!options.readline) options.readline = require('readline');
if (options.terminal === undefined) options.terminal = options.output.isTTY;
if (options.histfile === undefined) options.histfile = path.join(cachedir, 'rapydscript-repl.history');
options.colored = (options.terminal) ? colored : (function (string) { return string; });
options.historySize = options.history_size || 1000;
return options;
}
function read_history(options) {
if (options.histfile) {
try {
return fs.readFileSync(options.histfile, 'utf-8').split('\n');
} catch (e) { return []; }
}
}
function write_history(options, history) {
if (options.histfile) {
history = history.join('\n');
try {
return fs.writeFileSync(options.histfile, history, 'utf-8');
} catch (e) {}
}
}
module.exports = function(options) {
options = repl_defaults(options);
options.completer = completer;
var rl = options.readline.createInterface(options);
var ps1 = options.colored(options.ps1, 'green');
var ps2 = options.colored(options.ps2, 'yellow');
var ctx = create_ctx(print_ast(RapydScript.parse('(def ():\n yield 1\n)'), true), options.show_js, options.console);
var buffer = [];
var more = false;
var LINE_CONTINUATION_CHARS = ':\\';
var toplevel;
var import_dirs = utils.get_import_dirs();
var find_completions = completelib(RapydScript, options);
options.console.log(options.colored('Welcome to the RapydScript REPL! Press Ctrl+C then Ctrl+D to quit.', 'green', true));
if (options.show_js)
options.console.log(options.colored('Use show_js=False to stop the REPL from showing the compiled JavaScript.', 'green', true));
else
options.console.log(options.colored('Use show_js=True to have the REPL show the compiled JavaScript before executing it.', 'green', true));
options.console.log();
function print_ast(ast, keep_baselib) {
var output_options = {omit_baselib:!keep_baselib, write_name:false, private_scope:false, beautify:true, keep_docstrings:true};
if (keep_baselib) output_options.baselib_plain = fs.readFileSync(path.join(options.lib_path, 'baselib-plain-pretty.js'), 'utf-8');
var output = new RapydScript.OutputStream(output_options);
ast.print(output);
return output.get();
}
function resetbuffer() { buffer = []; }
function completer(line) {
return find_completions(line, ctx);
}
function prompt() {
var lw = '';
if (more && buffer.length) {
var prev_line = buffer[buffer.length - 1];
if (prev_line.trimRight().substr(prev_line.length - 1) == ':') lw = ' ';
prev_line = prev_line.match(/^\s+/);
if (prev_line) lw += prev_line;
}
rl.setPrompt((more) ? ps2 : ps1);
if (rl.sync_prompt) rl.prompt(lw);
else {
rl.prompt();
if (lw) rl.write(lw);
}
}
function runjs(js) {
var result;
if (vm.runInContext('show_js', ctx)) {
options.console.log(options.colored('---------- Compiled JavaScript ---------', 'green', true));
options.console.log(js);
options.console.log(options.colored('---------- Running JavaScript ---------', 'green', true));
}
try {
// Despite what the docs say node does not actually output any errors by itself
// so, in case this bug is fixed later, we turn it off explicitly.
result = vm.runInContext(js, ctx, {'filename':'<repl>', 'displayErrors':false});
} catch(e) {
if (e.stack) options.console.error(e.stack);
else options.console.error(e.toString());
}
if (result !== undefined) {
options.console.log(util.inspect(result, {'colors':options.terminal}));
}
}
function compile_source(source) {
var classes = (toplevel) ? toplevel.classes : undefined;
var scoped_flags = (toplevel) ? toplevel.scoped_flags: undefined;
try {
toplevel = RapydScript.parse(source, {
'filename':'<repl>',
'basedir': process.cwd(),
'libdir': options.imp_path,
'import_dirs': import_dirs,
'classes': classes,
'scoped_flags': scoped_flags,
});
} catch(e) {
if (e.is_eof && e.line == buffer.length && e.col > 0) return true;
if (e.message && e.line !== undefined) options.console.log(e.line + ':' + e.col + ':' + e.message);
else options.console.log(e.stack || e.toString());
return false;
}
var output = print_ast(toplevel);
if (classes) {
var exports = {};
toplevel.exports.forEach(function (name) { exports[name] = true; });
Object.getOwnPropertyNames(classes).forEach(function (name) {
if (!has_prop(exports, name) && !has_prop(toplevel.classes, name))
toplevel.classes[name] = classes[name];
});
}
scoped_flags = toplevel.scoped_flags;
runjs(output);
return false;
}
function push(line) {
buffer.push(line);
var ll = line.trimRight();
if (ll && LINE_CONTINUATION_CHARS.indexOf(ll.substr(ll.length - 1)) > -1)
return true;
var source = buffer.join('\n');
if (!source.trim()) { resetbuffer(); return false; }
var incomplete = compile_source(source);
if (!incomplete) resetbuffer();
return incomplete;
}
rl.on('line', function(line) {
if (more) {
// We are in a block
var line_is_empty = !line.trimLeft();
if (line_is_empty && buffer.length && !buffer[buffer.length - 1].trimLeft()) {
// We have two empty lines, evaluate the block
more = push(line.trimLeft());
} else buffer.push(line);
} else more = push(line); // Not in a block, evaluate line
prompt();
})
.on('close', function() {
options.console.log('Bye!');
if (rl.history) write_history(options, rl.history);
process.exit(0);
})
.on('SIGINT', function() {
rl.clearLine();
options.console.log('Keyboard Interrupt');
resetbuffer();
more = false;
prompt();
})
.on('SIGCONT', function() {
prompt();
});
rl.history = read_history(options);
prompt();
};
| kovidgoyal/rapydscript-ng | tools/repl.js | JavaScript | bsd-2-clause | 8,168 |
var debugProtocol = require('debug')('node-inspector:protocol:devtools');
var RuntimeAgent = require('./RuntimeAgent').RuntimeAgent,
PageAgent = require('./PageAgent').PageAgent,
NetworkAgent = require('./NetworkAgent').NetworkAgent,
DebuggerAgent = require('./DebuggerAgent').DebuggerAgent,
ProfilerAgent = require('./ProfilerAgent').ProfilerAgent;
/**
* @param {Object} config
* @param {FrontendClient} frontendClient
* @param {DebuggerClient} debuggerClient
* @param {BreakEventHandler} breakEventHandler
* @param {ScriptManager} scriptManager
* @param {InjectorClient} injectorClient
*/
function FrontendCommandHandler(config,
frontendClient,
debuggerClient,
breakEventHandler,
scriptManager,
injectorClient) {
this._config = config;
this._agents = {};
this._specialCommands = {};
this._frontendClient = frontendClient;
this._debuggerClient = debuggerClient;
this._breakEventHandler = breakEventHandler;
this._scriptManager = scriptManager;
this._injectorClient = injectorClient;
this._initializeRegistry();
this._registerEventHandlers();
this._pauseInitialEvents();
}
FrontendCommandHandler.prototype = {
_initializeRegistry: function() {
this._registerAgent(
'Debugger',
new DebuggerAgent(
this._config,
this._frontendClient,
this._debuggerClient,
this._breakEventHandler,
this._scriptManager,
this._injectorClient)
);
this._registerAgent('Runtime', new RuntimeAgent(this._config, this._debuggerClient));
this._registerAgent(
'Page',
new PageAgent(
this._config,
this._debuggerClient,
this._scriptManager)
);
this._registerAgent('Network', new NetworkAgent());
this._registerAgent(
'Profiler',
new ProfilerAgent(
this._config,
this._debuggerClient,
this._injectorClient,
this._frontendClient)
);
//TODO(3y3):
// Remove next from noop before closing #341:
// - DOMDebugger.setXHRBreakpoint
// - DOMDebugger.removeXHRBreakpoint
this._registerNoopCommands(
'Network.enable',
'Network.setCacheDisabled',
'Console.enable',
'Console.clearMessages',
'Console.setMonitoringXHREnabled',
'Database.enable',
'DOMDebugger.setXHRBreakpoint',
'DOMDebugger.removeXHRBreakpoint',
'DOMDebugger.setInstrumentationBreakpoint',
'DOMDebugger.removeInstrumentationBreakpoint',
'DOMStorage.enable',
'DOM.hideHighlight',
'Inspector.enable',
'Page.addScriptToEvaluateOnLoad',
'Page.removeScriptToEvaluateOnLoad',
'Page.setDeviceOrientationOverride',
'Page.clearDeviceOrientationOverride',
'Page.setGeolocationOverride',
'Page.clearGeolocationOverride',
'Page.setContinuousPaintingEnabled',
'Page.setEmulatedMedia',
'Page.setDeviceMetricsOverride',
'Page.setScriptExecutionDisabled',
'Page.setShowDebugBorders',
'Page.setShowFPSCounter',
'Page.setShowScrollBottleneckRects',
'Page.setShowViewportSizeOnResize',
'Page.setShowPaintRects',
'Page.setForceCompositingMode',
'Profiler.enable',
'CSS.enable',
'HeapProfiler.getProfileHeaders'
);
this._registerQuery('CSS.getSupportedCSSProperties', { cssProperties: []});
this._registerQuery('Worker.canInspectWorkers', { result: false });
this._registerQuery('Page.getScriptExecutionStatus', { result: 'enabled' });
},
_registerAgent: function(name, agent) {
this._agents[name] = agent;
},
_registerNoopCommands: function() {
var i, fullMethodName;
for (i = 0; i < arguments.length; i++) {
fullMethodName = arguments[i];
this._specialCommands[fullMethodName] = {};
}
},
_registerQuery: function(fullMethodName, result) {
this._specialCommands[fullMethodName] = { result: result };
},
_registerEventHandlers: function() {
this._frontendClient.on(
'message',
this._handleFrontendMessage.bind(this));
},
_handleFrontendMessage: function(message) {
debugProtocol('frontend: ' + message);
var command = JSON.parse(message);
this.handleCommand(command);
},
_pauseInitialEvents: function() {
this._frontendClient.pauseEvents();
this._agents.Page.on('resource-tree', function() {
this._frontendClient.resumeEvents();
}.bind(this));
},
handleCommand: function(messageObject) {
var fullMethodName = messageObject.method,
domainAndMethod = fullMethodName.split('.'),
domainName = domainAndMethod[0],
methodName = domainAndMethod[1],
requestId = messageObject.id,
agent,
method;
if (this._specialCommands[fullMethodName]) {
this._handleMethodResult(
requestId,
fullMethodName,
null,
this._specialCommands[fullMethodName].result);
return;
}
agent = this._agents[domainName];
if (!agent) {
this._sendNotImplementedResponse(requestId, fullMethodName);
return;
}
method = agent[methodName];
if (!method || typeof method !== 'function') {
this._sendNotImplementedResponse(requestId, fullMethodName);
return;
}
method.call(agent, messageObject.params, function(error, result) {
this._handleMethodResult(messageObject.id, fullMethodName, error, result);
}.bind(this));
},
_sendNotImplementedResponse: function(requestId, fullMethodName) {
console.log(
'Received request for a method not implemented:',
fullMethodName
);
this._handleMethodResult(
requestId,
fullMethodName,
new Error('Not implemented.')
);
},
_handleMethodResult: function(requestId, fullMethodName, error, result) {
var response;
if (!requestId) {
if (response !== undefined)
console.log('Warning: discarded result of ' + fullMethodName);
return;
}
this._frontendClient.sendResponse(requestId, fullMethodName, error, result);
}
};
exports.FrontendCommandHandler = FrontendCommandHandler;
| charany1/node-inspector | lib/FrontendCommandHandler.js | JavaScript | bsd-2-clause | 6,245 |
/**
* Created with JetBrains WebStorm.
* User: Dieter Beelaert
* Date: 23/08/13
* Time: 11:42
* To change this template use File | Settings | File Templates.
*/
$(document).ready(function(){
localize();
});
function localize(){
$(".newEvent").html(localization.event);
$(".weekname").html(localization.week);
$(".monthname").html(localization.month);
$(".yearname").html(localization.yearName);
$(".exportCal").html(localization.exportCal);
$(".exportmsg").html(localization.locExportMessage);
$(".sunname").html(localization.sun);
$(".monname").html(localization.mon);
$(".tuename").html(localization.tue);
$(".wedname").html(localization.wed);
$(".thurname").html(localization.thur);
$(".friname").html(localization.fri);
$(".satname").html(localization.sat);
$(".locShow").html(localization.locShow);
$(".noschedule").html(localization.noschedule);
$(".getMonthName").each(function(){var index = $(this).attr("mi"); $(this).html(localization.locFullMonthNames[index]);})
$(".locTitle").html(localization.locTitle);
$(".locDesc").html(localization.locDesc);
$(".locDate").html(localization.locDate);
$(".locFrom").html(localization.locFrom);
$(".locUntil").html(localization.locUntil);
$(".locLocation").html(localization.locLocation);
$(".locOccurrence").html(localization.locOccurrence);
$(".locOnce").html(localization.locOnce);
$(".locEveryDay").html(localization.locEveryDay);
$(".locEveryWeek").html(localization.locEveryWeek);
$(".locEveryMonth").html(localization.locEveryMonth);
$(".locEveryYear").html(localization.locEveryYear);
$(".locDelete").html(localization.locDelete);
$(".locSave").html(localization.locSave);
$(".locNoComments").html(localization.locNoComments);
$(".locComment").html(localization.locComment);
$(".locSend").html(localization.locSend);
var i =0;
$(".locMonth").each(function(){
$(this).html(localization.locFullMonthNames[i]);
i++;
});
var i =0;
$(".dayName").each(function(){
$(this).html(localization.dayNames[i]);
i++;
});
var i=0;
$(".yearCalHeader").each(function(){
$(this).html(localization.monthNames[i]);
i++;
})
}
| jcoppieters/cody-samples | bok/static/js/localizer.js | JavaScript | bsd-2-clause | 2,293 |
var express = require('express');
var router = express.Router();
const env = require('env2')('./env.json');
var Tag = require('../mongo/tags')
var IssueTag = require('../mongo/Issue')
router.post('/removeTag', function (req, res, next) {
var userID = req.body.userID;
var repoID = req.body.repoID;
var name = req.body.name;
var tagID = req.body.tagID;
Tag.remove({
userID: userID,
repoID: repoID,
tagID: tagID
}, function (err, data) {
res.send(data);
});
});
router.post('/getTag', function (req, res, next) {
var userID = req.body.userID;
var repoID = req.body.repoID;
Tag.find({ userID: userID, repoID: repoID }, function (err, docs) {
res.send(docs);
});
});
router.post('/addTag', function (req, res, next) {
var userID = req.body.userID;
var repoID = req.body.repoID;
var tagID = req.body.tagID;
var name = req.body.name;
var color = req.body.color;
var selected = req.body.selected;
var tag = new Tag({
tagID: tagID,
userID: userID,
repoID: repoID,
name: name,
color: color,
selected: selected
});
tag.save(function (err, resp) {
if (err) {
console.log("Error:" + err);
}
else {
res.send(resp);
};
});
});
router.post('/updateIssueTag', function (req, res, next) {
var userID = req.body.userID;
var repoID = req.body.repoID;
var number = req.body.number;
var tagIDs = req.body.tagIDs;
var query = {
userID: userID,
repoID: repoID,
number: number
};
IssueTag.update(query, { tagIDs: tagIDs }, { upsert: true }, function (err, docs) {
res.send(docs);
});
});
router.post('/updateIssueNote', function (req, res, next) {
var userID = req.body.userID;
var repoID = req.body.repoID;
var number = req.body.number;
var note = req.body.note;
var query = {
userID: userID,
repoID: repoID,
number: number
};
IssueTag.update(query, { note: note }, { upsert: true }, function (err, docs) {
res.send(docs);
});
});
module.exports = router; | Mignon-han/issue-processing | server/routes/tag.js | JavaScript | bsd-2-clause | 2,197 |
/*!
* CanJS - 1.1.4 (2013-02-05)
* http://canjs.us/
* Copyright (c) 2013 Bitovi
* Licensed MIT
*/
define(['can/util/can', 'zepto', 'can/util/object/isplain', 'can/util/event', 'can/util/fragment', 'can/util/deferred', 'can/util/array/each'], function (can) {
var $ = Zepto;
// data.js
// ---------
// _jQuery-like data methods._
var data = {},
dataAttr = $.fn.data,
uuid = $.uuid = +new Date(),
exp = $.expando = 'Zepto' + uuid;
function getData(node, name) {
var id = node[exp],
store = id && data[id];
return name === undefined ? store || setData(node) : (store && store[name]) || dataAttr.call($(node), name);
}
function setData(node, name, value) {
var id = node[exp] || (node[exp] = ++uuid),
store = data[id] || (data[id] = {});
if (name !== undefined) store[name] = value;
return store;
};
$.fn.data = function (name, value) {
return value === undefined ? this.length == 0 ? undefined : getData(this[0], name) : this.each(function (idx) {
setData(this, name, $.isFunction(value) ? value.call(this, idx, getData(this, name)) : value);
});
};
$.cleanData = function (elems) {
for (var i = 0, elem;
(elem = elems[i]) !== undefined; i++) {
can.trigger(elem, "destroyed", [], false)
var id = elem[exp]
delete data[id];
}
}
// zepto.js
// ---------
// _Zepto node list._
var oldEach = can.each;
// Extend what you can out of Zepto.
$.extend(can, Zepto);
can.each = oldEach;
var arrHas = function (obj, name) {
return obj[0] && obj[0][name] || obj[name]
}
// Do what's similar for jQuery.
can.trigger = function (obj, event, args, bubble) {
if (obj.trigger) {
obj.trigger(event, args)
} else if (arrHas(obj, "dispatchEvent")) {
if (bubble === false) {
$([obj]).triggerHandler(event, args)
} else {
$([obj]).trigger(event, args)
}
} else {
if (typeof event == "string") {
event = {
type: event
}
}
event.target = event.target || obj;
event.data = args;
can.dispatch.call(obj, event)
}
}
can.$ = Zepto;
can.bind = function (ev, cb) {
// If we can bind to it...
if (this.bind) {
this.bind(ev, cb)
} else if (arrHas(this, "addEventListener")) {
$([this]).bind(ev, cb)
} else {
can.addEvent.call(this, ev, cb)
}
return this;
}
can.unbind = function (ev, cb) {
// If we can bind to it...
if (this.unbind) {
this.unbind(ev, cb)
} else if (arrHas(this, "addEventListener")) {
$([this]).unbind(ev, cb)
} else {
can.removeEvent.call(this, ev, cb)
}
return this;
}
can.delegate = function (selector, ev, cb) {
if (this.delegate) {
this.delegate(selector, ev, cb)
} else {
$([this]).delegate(selector, ev, cb)
}
}
can.undelegate = function (selector, ev, cb) {
if (this.undelegate) {
this.undelegate(selector, ev, cb)
} else {
$([this]).undelegate(selector, ev, cb)
}
}
$.each(["append", "filter", "addClass", "remove", "data"], function (i, name) {
can[name] = function (wrapped) {
return wrapped[name].apply(wrapped, can.makeArray(arguments).slice(1))
}
})
can.makeArray = function (arr) {
var ret = []
can.each(arr, function (a, i) {
ret[i] = a
})
return ret;
};
can.proxy = function (f, ctx) {
return function () {
return f.apply(ctx, arguments)
}
}
// Make ajax.
var XHR = $.ajaxSettings.xhr;
$.ajaxSettings.xhr = function () {
var xhr = XHR()
var open = xhr.open;
xhr.open = function (type, url, async) {
open.call(this, type, url, ASYNC === undefined ? true : ASYNC)
}
return xhr;
}
var ASYNC;
var AJAX = $.ajax;
var updateDeferred = function (xhr, d) {
for (var prop in xhr) {
if (typeof d[prop] == 'function') {
d[prop] = function () {
xhr[prop].apply(xhr, arguments)
}
} else {
d[prop] = prop[xhr]
}
}
}
can.ajax = function (options) {
var success = options.success,
error = options.error;
var d = can.Deferred();
options.success = function (data) {
updateDeferred(xhr, d);
d.resolve.call(d, data);
success && success.apply(this, arguments);
}
options.error = function () {
updateDeferred(xhr, d);
d.reject.apply(d, arguments);
error && error.apply(this, arguments);
}
if (options.async === false) {
ASYNC = false
}
var xhr = AJAX(options);
ASYNC = undefined;
updateDeferred(xhr, d);
return d;
};
// Make destroyed and empty work.
$.fn.empty = function () {
return this.each(function () {
$.cleanData(this.getElementsByTagName('*'))
this.innerHTML = ''
})
}
$.fn.remove = function () {
$.cleanData(this);
this.each(function () {
if (this.parentNode != null) {
// might be a text node
this.getElementsByTagName && $.cleanData(this.getElementsByTagName('*'))
this.parentNode.removeChild(this);
}
});
return this;
}
can.trim = function (str) {
return str.trim();
}
can.isEmptyObject = function (object) {
var name;
for (name in object) {};
return name === undefined;
}
// Make extend handle `true` for deep.
can.extend = function (first) {
if (first === true) {
var args = can.makeArray(arguments);
args.shift();
return $.extend.apply($, args)
}
return $.extend.apply($, arguments)
}
can.get = function (wrapped, index) {
return wrapped[index];
}
return can;
}); | kdar/morphgen | public/js/vendor/canjs/amd/can/util/zepto.js | JavaScript | bsd-2-clause | 5,290 |
/*global Ext*/
/*jshint strict: false*/
Ext.define('Demo.view.portal.PortletsPanel', {
extend: 'Ext.panel.Panel',
alias: 'widget.portletspanel',
uses: [
'Demo.view.app.Portlet'
]
});
| liberborn/extapp | app/portal/view/portal/PortletsPanel.js | JavaScript | bsd-2-clause | 208 |
'use strict';
// https://github.com/jambit/eslint-plugin-typed-redux-saga
module.exports = {
rules: {
'use-typed-effects': require('./rules/use-typed-effects'),
'delegate-effects': require('./rules/delegate-effects'),
},
};
| edrlab/readium-desktop | scripts/eslint-plugin-typed-redux-saga/index.js | JavaScript | bsd-3-clause | 250 |
/*jslint browser: true, devel: true, node: true, ass: true, nomen: true, unparam: true, indent: 4 */
/**
* @license
* Copyright (c) 2015 The ExpandJS authors. All rights reserved.
* This code may only be used under the BSD style license found at https://expandjs.github.io/LICENSE.txt
* The complete set of authors may be found at https://expandjs.github.io/AUTHORS.txt
* The complete set of contributors may be found at https://expandjs.github.io/CONTRIBUTORS.txt
*/
(function () {
"use strict";
var assertArgument = require('../assert/assertArgument'),
isVoid = require('../tester/isVoid'),
isFinite = require('../tester/isFinite'),
isIndex = require('../tester/isIndex');
/**
* Rounds up a number to the nearest integet. If a second parameter is
* specified the number can be rounded using digits after the decimal point.
*
* ```js
* XP.round(1.2)
* // => 1
*
* XP.round(1.5)
* // => 2
*
* XP.fixed(1.49, 1)
* // => 1.5
*
* XP.round(1.492, 2)
* // => 1.49
*
* XP.round(1.499, 2)
* // => 1.5
* ```
*
* @function round
* @param {number} number The reference number to format
* @param {number} [precision = 0] The number of digits to be shown after the decimal point
* @returns {number} Returns the number rounded up
*/
module.exports = function round(number, precision) {
assertArgument(isFinite(number), 1, 'number');
assertArgument(isVoid(precision) || isIndex(precision), 2, 'number');
return Math.round(number * (precision = Math.pow(10, precision || 0))) / precision;
};
}()); | MassiveZergInc/MassiveZergInc.github.io | everHomev2/bower_components/expandjs/lib/number/round.js | JavaScript | bsd-3-clause | 1,756 |
/* ************************************************************************
Copyright:
License:
Authors:
************************************************************************ */
qx.Theme.define("soap.theme.classic.Color",
{
colors :
{
}
}); | arskom/qxsoap | source/class/soap/theme/classic/Color.js | JavaScript | bsd-3-clause | 263 |
const certificationUrl = '/certification/developmentuser/responsive-web-design';
const projects = {
superBlock: 'responsive-web-design',
block: 'responsive-web-design-projects',
challenges: [
{
slug: 'build-a-tribute-page',
solution: 'https://codepen.io/moT01/pen/ZpJpKp'
},
{
slug: 'build-a-survey-form',
solution: 'https://codepen.io/moT01/pen/LrrjGz?editors=1010'
},
{
slug: 'build-a-product-landing-page',
solution: 'https://codepen.io/moT01/full/qKyKYL/'
},
{
slug: 'build-a-technical-documentation-page',
solution: 'https://codepen.io/moT01/full/JBvzNL/'
},
{
slug: 'build-a-personal-portfolio-webpage',
solution: 'https://codepen.io/moT01/pen/vgOaoJ'
}
]
};
describe('A certification,', function () {
before(() => {
cy.exec('npm run seed');
cy.login();
// submit projects for certificate
const { superBlock, block, challenges } = projects;
challenges.forEach(({ slug, solution }) => {
const url = `/learn/${superBlock}/${block}/${slug}`;
cy.visit(url);
cy.get('#dynamic-front-end-form')
.get('#solution')
.type(solution, { force: true, delay: 0 });
cy.contains("I've completed this challenge")
.should('not.be.disabled')
.click();
cy.contains('Submit and go to next challenge').click().wait(1000);
});
cy.get('.donation-modal').should('be.visible');
cy.visit('/settings');
// set user settings to public to claim a cert
cy.get('label:contains(Public)>input').each(el => {
if (!/toggle-active/.test(el[0].parentElement.className)) {
cy.wrap(el).click({ force: true });
cy.wait(1000);
}
});
// if honest policy not accepted
cy.get('.honesty-policy button').then(btn => {
if (btn[0].innerText === 'Agree') {
btn[0].click({ force: true });
cy.wait(1000);
}
});
// claim certificate
cy.get('a[href*="developmentuser/responsive-web-design"]').click({
force: true
});
});
describe('while viewing your own,', function () {
before(() => {
cy.login();
cy.visit(certificationUrl);
});
it('should render a LinkedIn button', function () {
cy.contains('Add this certification to my LinkedIn profile')
.should('have.attr', 'href')
.and(
'match',
// eslint-disable-next-line max-len
/https:\/\/www\.linkedin\.com\/profile\/add\?startTask=CERTIFICATION_NAME&name=Responsive Web Design&organizationId=4831032&issueYear=\d\d\d\d&issueMonth=\d\d?&certUrl=https:\/\/freecodecamp\.org\/certification\/developmentuser\/responsive-web-design/
);
});
it('should render a Twitter button', function () {
cy.contains('Share this certification on Twitter').should(
'have.attr',
'href',
'https://twitter.com/intent/tweet?text=I just earned the Responsive Web Design certification @freeCodeCamp! Check it out here: https://freecodecamp.org/certification/developmentuser/responsive-web-design'
);
});
it("should be issued with today's date", () => {
const date = new Date();
const issued = `Issued\xa0${new Intl.DateTimeFormat('en-US', {
month: 'long'
}).format(date)} ${date.getDate()}, ${date.getFullYear()}`;
cy.get('[data-cy=issue-date]').should('have.text', issued);
});
});
describe("while viewing someone else's,", function () {
before(() => {
cy.visit(certificationUrl);
});
it('should display certificate', function () {
cy.contains('has successfully completed the freeCodeCamp.org').should(
'exist'
);
cy.contains('Responsive Web Design').should('exist');
});
it('should not render a LinkedIn button', function () {
cy.contains('Add this certification to my LinkedIn profile').should(
'not.exist'
);
});
it('should not render a Twitter button', function () {
cy.contains('Share this certification on Twitter').should('not.exist');
});
});
});
| raisedadead/FreeCodeCamp | cypress/integration/ShowCertification.js | JavaScript | bsd-3-clause | 4,115 |
const pathModule = require('path');
const expect = require('../../unexpected-with-plugins');
const AssetGraph = require('../../../lib/AssetGraph');
describe('relations/HtmlAlternateLink', function () {
it('should handle a simple test case', async function () {
const assetGraph = new AssetGraph({
root: pathModule.resolve(
__dirname,
'../../../testdata/relations/Html/HtmlAlternateLink/'
),
});
await assetGraph.loadAssets('index.html');
await assetGraph.populate();
expect(assetGraph, 'to contain relations', 'HtmlAlternateLink', 4);
expect(assetGraph, 'to contain assets', 'Rss', 2);
expect(assetGraph, 'to contain asset', 'Atom');
expect(assetGraph, 'to contain asset', 'Xml');
});
});
| assetgraph/assetgraph | test/relations/Html/HtmlAlternateLink.js | JavaScript | bsd-3-clause | 756 |
var gulp = require('gulp');
var del = require('del');
var plumber = require('gulp-plumber');
var replace = require('gulp-replace');
// lib
gulp.task('lib-clean', function () {
return del('./lib/*');
});
gulp.task('lib-assets', ['lib-clean'], function () {
return gulp.src(['./src/**/*.*', '!./src/**/*.js'])
.pipe(gulp.dest('./lib'));
});
gulp.task('lib-compile', ['lib-clean'], function () {
return gulp.src(['./src/**/*.js'])
.pipe(plumber())
.pipe(replace('require(\'zrender\')', 'require(\'zrenderjs\')'))
.pipe(replace('require(\'zrender/', 'require(\'zrenderjs/'))
.pipe(gulp.dest('./lib'));
});
gulp.task('lib', ['lib-clean', 'lib-assets', 'lib-compile']);
// dist
gulp.task('dist-clean', function () {
return del('./dist/*');
});
gulp.task('dist-assets', ['dist-clean'], function () {
return gulp.src(['./src/**/*.*', '!./src/**/*.js'])
.pipe(gulp.dest('./dist'));
});
gulp.task('dist-compile', ['dist-clean'], function () {
return gulp.src(['./src/**/*.js'])
.pipe(plumber())
.pipe(replace('require(\'zrender\')', 'require(\'zrenderjs\')'))
.pipe(replace('require(\'zrender/', 'require(\'zrenderjs/'))
// .pipe(replace('require(\'text!', 'require(\''))
.pipe(gulp.dest('./dist'));
});
gulp.task('dist-x', ['dist-clean'], function () {
return gulp.src(['./package.json', './README.md', './LICENSE'])
.pipe(gulp.dest('./dist'));
});
gulp.task('dist', ['dist-clean', 'dist-assets', 'dist-compile', 'dist-x']);
gulp.task('default', ['dist']);
| uooo/echarts-x | gulpfile.js | JavaScript | bsd-3-clause | 1,582 |
var NAVTREEINDEX5 =
{
"structcrossbow_1_1serializer__into__array.html#a055a25fc545818f211721c9c1897e710":[2,0,0,58,0],
"structcrossbow_1_1serializer__into__array.html#a0df5a581aa43a0e27b9a198959273f3f":[2,0,0,58,1],
"structcrossbow_1_1serializer__into__array.html#a4f29e036e5a0ef00d4e4eeec2849c139":[2,0,0,58,3],
"structcrossbow_1_1serializer__into__array.html#ab1b38b795d0c87338445978c2ddf11cc":[2,0,0,58,2],
"structcrossbow_1_1serializer__into__array.html#ae624f6e6ac43b4ca5bb269f464b4538d":[2,0,0,58,4],
"structcrossbow_1_1size__policy.html":[2,0,0,61],
"structcrossbow_1_1size__policy.html#ac5b0cd01a3fb2c8a90eecffea13c60ef":[2,0,0,61,0],
"structcrossbow_1_1size__policy_3_01_archiver_00_01bool_01_4.html":[2,0,0,62],
"structcrossbow_1_1size__policy_3_01_archiver_00_01bool_01_4.html#ac6d217b4360feea1007718e4491a019b":[2,0,0,62,0],
"structcrossbow_1_1size__policy_3_01_archiver_00_01boost_1_1optional_3_01_t_01_4_01_4.html":[2,0,0,63],
"structcrossbow_1_1size__policy_3_01_archiver_00_01boost_1_1optional_3_01_t_01_4_01_4.html#a9cdec7610e2ce4cb28cf57a3a6303cdc":[2,0,0,63,0],
"structcrossbow_1_1size__policy_3_01_archiver_00_01crossbow_1_1basic__string_3_01_char_00_01_traits_00_01_allocator_01_4_01_4.html":[2,0,0,64],
"structcrossbow_1_1size__policy_3_01_archiver_00_01crossbow_1_1basic__string_3_01_char_00_01_traits_00_01_allocator_01_4_01_4.html#a84636f49200747f1464ccd676a21c177":[2,0,0,64,0],
"structcrossbow_1_1size__policy_3_01_archiver_00_01crossbow_1_1basic__string_3_01_char_00_01_traits_00_01_allocator_01_4_01_4.html#a8e9407397d4683e1d9e05f874d49ebba":[2,0,0,64,1],
"structcrossbow_1_1size__policy_3_01_archiver_00_01std_1_1basic__string_3_01_char_00_01_traits_00_01_allocator_01_4_01_4.html":[2,0,0,65],
"structcrossbow_1_1size__policy_3_01_archiver_00_01std_1_1basic__string_3_01_char_00_01_traits_00_01_allocator_01_4_01_4.html#acc064aafb8c9d9b8ae292c993811b813":[2,0,0,65,0],
"structcrossbow_1_1size__policy_3_01_archiver_00_01std_1_1basic__string_3_01_char_00_01_traits_00_01_allocator_01_4_01_4.html#af5e5009193f50d478d63f8c98a34ad2b":[2,0,0,65,1],
"structcrossbow_1_1size__policy_3_01_archiver_00_01std_1_1map_3_01_key_00_01_value_00_01_predicate_00_01_allocator_01_4_01_4.html":[2,0,0,66],
"structcrossbow_1_1size__policy_3_01_archiver_00_01std_1_1map_3_01_key_00_01_value_00_01_predicate_00_01_allocator_01_4_01_4.html#a917d9fcefae943c7d756853003ed2b9f":[2,0,0,66,0],
"structcrossbow_1_1size__policy_3_01_archiver_00_01std_1_1map_3_01_key_00_01_value_00_01_predicate_00_01_allocator_01_4_01_4.html#aa2000d662ad4c39bdffc06d3ed028c1f":[2,0,0,66,1],
"structcrossbow_1_1size__policy_3_01_archiver_00_01std_1_1multimap_3_01_key_00_01_value_00_01_predcacc846b11af875dd5b8f45452b0b90.html":[2,0,0,67],
"structcrossbow_1_1size__policy_3_01_archiver_00_01std_1_1multimap_3_01_key_00_01_value_00_01_predcacc846b11af875dd5b8f45452b0b90.html#a0b077f206cd9787ec881f4c7a131c3da":[2,0,0,67,1],
"structcrossbow_1_1size__policy_3_01_archiver_00_01std_1_1multimap_3_01_key_00_01_value_00_01_predcacc846b11af875dd5b8f45452b0b90.html#a563a900efd7e187f615f04751aa70c4a":[2,0,0,67,0],
"structcrossbow_1_1size__policy_3_01_archiver_00_01std_1_1pair_3_01_u_00_01_v_01_4_01_4.html":[2,0,0,68],
"structcrossbow_1_1size__policy_3_01_archiver_00_01std_1_1pair_3_01_u_00_01_v_01_4_01_4.html#aa1cd4ded10cb92c48c1b13a0a50a626b":[2,0,0,68,0],
"structcrossbow_1_1size__policy_3_01_archiver_00_01std_1_1tuple_3_01_t_8_8_8_01_4_01_4.html":[2,0,0,69],
"structcrossbow_1_1size__policy_3_01_archiver_00_01std_1_1tuple_3_01_t_8_8_8_01_4_01_4.html#aa25716a6ccddb0c9776cb93f099a079d":[2,0,0,69,0],
"structcrossbow_1_1size__policy_3_01_archiver_00_01std_1_1unordered__map_3_01_key_00_01_value_00_24255cc159f0c25d71be6931ba8319ef.html":[2,0,0,70],
"structcrossbow_1_1size__policy_3_01_archiver_00_01std_1_1unordered__map_3_01_key_00_01_value_00_24255cc159f0c25d71be6931ba8319ef.html#a0fc570c6a4d4c65c40f6e9cbfba6c709":[2,0,0,70,1],
"structcrossbow_1_1size__policy_3_01_archiver_00_01std_1_1unordered__map_3_01_key_00_01_value_00_24255cc159f0c25d71be6931ba8319ef.html#a2d83741fbbf629f8a617642896213def":[2,0,0,70,0],
"structcrossbow_1_1size__policy_3_01_archiver_00_01std_1_1vector_3_01_t_00_01_allocator_01_4_01_4.html":[2,0,0,71],
"structcrossbow_1_1size__policy_3_01_archiver_00_01std_1_1vector_3_01_t_00_01_allocator_01_4_01_4.html#ada6785b9244dbf4759fbed98907ca204":[2,0,0,71,0],
"structcrossbow_1_1size__policy__tuple__impl.html":[2,0,0,72],
"structcrossbow_1_1size__policy__tuple__impl.html#a0f591022109ea21455473d2c8962b078":[2,0,0,72,0],
"structcrossbow_1_1size__policy__tuple__impl_3_01_archiver_00_01_tuple_00-1_01_4.html":[2,0,0,73],
"structcrossbow_1_1size__policy__tuple__impl_3_01_archiver_00_01_tuple_00-1_01_4.html#a26955a0fab80c53dce288f9c80c871b8":[2,0,0,73,0],
"structcrossbow_1_1sizer.html":[2,0,0,74],
"structcrossbow_1_1sizer.html#a0704e550b62cb80ecbff9a25398609da":[2,0,0,74,4],
"structcrossbow_1_1sizer.html#a440cc392c34d275c53c5016bcaf85ebd":[2,0,0,74,3],
"structcrossbow_1_1sizer.html#a8dc0b4d342b31a42188f8a4627f719cd":[2,0,0,74,2],
"structcrossbow_1_1sizer_1_1other__impl.html":[2,0,0,74,0],
"structcrossbow_1_1sizer_1_1visit__impl.html":[2,0,0,74,1],
"structstd_1_1hash_3_01crossbow_1_1basic__string_3_01_char_t_00_01_traits_00_01_allocator_01_4_01_4.html":[2,0,1,0],
"structstd_1_1hash_3_01crossbow_1_1basic__string_3_01_char_t_00_01_traits_00_01_allocator_01_4_01_4.html#a8353d207930348872e41c03120e17b70":[2,0,1,0,0],
"structstd_1_1hash_3_01tell_1_1db_1_1key__t_01_4.html":[2,0,1,1],
"structstd_1_1hash_3_01tell_1_1db_1_1key__t_01_4.html#a1fcefa112035a1850838804062db8397":[2,0,1,1,2],
"structstd_1_1hash_3_01tell_1_1db_1_1key__t_01_4.html#a2f0b7036da47cbcb846eada9bbf67eab":[2,0,1,1,0],
"structstd_1_1hash_3_01tell_1_1db_1_1key__t_01_4.html#a4ce763bf1cc45f2cc986e7418667fd08":[2,0,1,1,1],
"structstd_1_1hash_3_01tell_1_1db_1_1key__t_01_4.html#a7bf3c99a4cb9decb62cf5684dd86a03a":[2,0,1,1,3],
"structstd_1_1hash_3_01tell_1_1db_1_1table__t_01_4.html":[2,0,1,2],
"structstd_1_1hash_3_01tell_1_1db_1_1table__t_01_4.html#a25119e629605e975694cf81a0d20fece":[2,0,1,2,1],
"structstd_1_1hash_3_01tell_1_1db_1_1table__t_01_4.html#a36386273830933d459353ee4bda15e59":[2,0,1,2,3],
"structstd_1_1hash_3_01tell_1_1db_1_1table__t_01_4.html#abb5f67501ad8c1fb0abe94fba2d046a7":[2,0,1,2,2],
"structstd_1_1hash_3_01tell_1_1db_1_1table__t_01_4.html#abf7f004c781d79ac2f484aef716061b1":[2,0,1,2,0],
"structstd_1_1is__error__code__enum_3_01crossbow_1_1infinio_1_1error_1_1network__errors_01_4.html":[2,0,1,3],
"structstd_1_1is__error__code__enum_3_01crossbow_1_1infinio_1_1error_1_1rpc__errors_01_4.html":[2,0,1,4],
"structstd_1_1is__error__code__enum_3_01ibv__wc__status_01_4.html":[2,0,1,5],
"structtell_1_1db_1_1impl_1_1_fiber_context.html":[2,0,2,0,0,1],
"structtell_1_1db_1_1impl_1_1_fiber_context.html#a0a4a58df2e2fbabab8e93be85d84aeb7":[2,0,2,0,0,1,3],
"structtell_1_1db_1_1impl_1_1_fiber_context.html#a39e455b6f6747da27bd76c08048a5ce2":[2,0,2,0,0,1,2],
"structtell_1_1db_1_1impl_1_1_fiber_context.html#ad9d201c4932d6f42c3b11aa6710ad277":[2,0,2,0,0,1,1],
"structtell_1_1db_1_1impl_1_1_fiber_context.html#ae17ea873afa41ff2616791f99b6e82b2":[2,0,2,0,0,1,4],
"structtell_1_1db_1_1impl_1_1_fiber_context.html#aea2c8bfe880a3bfb0d7aafb92a466ebe":[2,0,2,0,0,1,0],
"structtell_1_1db_1_1impl_1_1_tell_d_b_context.html":[2,0,2,0,0,2],
"structtell_1_1db_1_1impl_1_1_tell_d_b_context.html#a18663c2bed060d1fb6e187690cc69862":[2,0,2,0,0,2,5],
"structtell_1_1db_1_1impl_1_1_tell_d_b_context.html#a31b67911b42b58a9e8c9a18890af456b":[2,0,2,0,0,2,1],
"structtell_1_1db_1_1impl_1_1_tell_d_b_context.html#a59e9dd717abbcefdc9bfbd30e7bc5888":[2,0,2,0,0,2,2],
"structtell_1_1db_1_1impl_1_1_tell_d_b_context.html#a708d44617d7e5198083e1a41135e6120":[2,0,2,0,0,2,6],
"structtell_1_1db_1_1impl_1_1_tell_d_b_context.html#a89065c018df6584600f4ac2101b8a770":[2,0,2,0,0,2,4],
"structtell_1_1db_1_1impl_1_1_tell_d_b_context.html#a8eded3051c4bd79749e8334bc1f900e6":[2,0,2,0,0,2,3],
"structtell_1_1db_1_1impl_1_1_tell_d_b_context.html#ac74ca78ad5e12ba083579776c96baac6":[2,0,2,0,0,2,0],
"structtell_1_1db_1_1key__t.html":[2,0,2,0,9],
"structtell_1_1db_1_1key__t.html#a038d9fe53e62fe5fd15539a3f4fbcee6":[2,0,2,0,9,0],
"structtell_1_1db_1_1key__t.html#a6108a1f43c1a2d0c343ba675f6a95216":[2,0,2,0,9,1],
"structtell_1_1db_1_1table__t.html":[2,0,2,0,12],
"structtell_1_1db_1_1table__t.html#a2fcec24ad06421ecf656014d0d069b5c":[2,0,2,0,12,1],
"structtell_1_1db_1_1table__t.html#a66ad05049599d3be07ac4c6ada904935":[2,0,2,0,12,0],
"structtell_1_1db_1_1tuple__set.html":[2,0,2,0,16],
"structtell_1_1db_1_1tuple__set_3_010_00_01_t_8_8_8_01_4.html":[2,0,2,0,17],
"type__printer_8hpp.html":[3,0,0,0,0,0,2],
"type__printer_8hpp_source.html":[3,0,0,0,0,0,2],
"unioncrossbow_1_1create__static_1_1max__align.html":[2,0,0,12,0],
"unioncrossbow_1_1create__static_1_1max__align.html#a291bf311ca64d4576958b438e23d4fa1":[2,0,0,12,0,7],
"unioncrossbow_1_1create__static_1_1max__align.html#a518bb434a3840cdca9c913a56414f58f":[2,0,0,12,0,3],
"unioncrossbow_1_1create__static_1_1max__align.html#a5fa90a71ce4fd9cf5861967fa93ea2d2":[2,0,0,12,0,5],
"unioncrossbow_1_1create__static_1_1max__align.html#a673716f37954b53de20c5052ef76b333":[2,0,0,12,0,4],
"unioncrossbow_1_1create__static_1_1max__align.html#a6784729b7537a397e63c03be5f87a13e":[2,0,0,12,0,6],
"unioncrossbow_1_1create__static_1_1max__align.html#a945dddc1131afb0a8132660402298f88":[2,0,0,12,0,2],
"unioncrossbow_1_1create__static_1_1max__align.html#ad8e468eae49d0e0f4092f9ff23da294a":[2,0,0,12,0,1],
"unioncrossbow_1_1create__static_1_1max__align.html#adb60127249f8dd5f45862a90e2ec6a71":[2,0,0,12,0,0],
"unordered__map_8hpp.html":[3,0,0,0,0,1,5],
"unordered__map_8hpp_source.html":[3,0,0,0,0,1,5],
"vector_8hpp.html":[3,0,0,0,0,1,6],
"vector_8hpp_source.html":[3,0,0,0,0,1,6]
};
| tellproject/homepage-generator | api/navtreeindex5.js | JavaScript | bsd-3-clause | 9,777 |
import camelize from "./camelize";
const msPattern = /^-ms-/;
function camelizeStyle(string) {
return camelize(string.replace(msPattern, "ms-"));
}
export default camelizeStyle;
| teasim/helpers | source/camelizeStyle.js | JavaScript | bsd-3-clause | 182 |
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule DraftFeatureFlags-core
*
*/
'use strict';
var DraftFeatureFlags = {
draft_accept_selection_after_refocus: false,
draft_killswitch_allow_nontextnodes: false,
draft_segmented_entities_behavior: false
};
module.exports = DraftFeatureFlags; | wmill/draft-js-npm | lib/DraftFeatureFlags-core.js | JavaScript | bsd-3-clause | 571 |
(function () {
'use strict';
angular.module('metronome.services.http', ['angular-jwt'])
.factory('http', ['$http', 'CONFIG', 'jwtHelper', function($http, CONFIG, jwtHelper) {
var token = Cookies.get('token');
var now = moment();
var expirationdate = moment(jwtHelper.getTokenExpirationDate(token)).subtract(1, 'm');
if (now.isAfter(expirationdate)) {
$http({
method: 'POST',
url: CONFIG.api + "/auth",
data: JSON.stringify({
type: "access",
refreshToken: Cookies.get("refreshToken")
})
}).then(function successCallback(response) {
Cookies.set('token', response.data.token);
}, function errorCallback(response) {
console.log("Error on call to renew accessToken:", response)
});
}
token = Cookies.get('token');
return function(config) {
return $http(angular.extend({
headers: {
'Authorization': token
},
url: CONFIG.api + config.path
}, config));
};
}]);
})();
| runabove/metronome-ui | src/dash/services/http.js | JavaScript | bsd-3-clause | 1,098 |
define(
//begin v1.x content
{
"dateFormatItem-yyyyMMMEd": "E, d MMM y G",
"dateFormatItem-MMMEd": "E, d MMM",
"dateFormatItem-hms": "hh:mm:ss a",
"days-standAlone-wide": [
"niedziela",
"poniedziaลek",
"wtorek",
"ลroda",
"czwartek",
"piฤ
tek",
"sobota"
],
"months-standAlone-narrow": [
"s",
"l",
"m",
"k",
"m",
"c",
"l",
"s",
"w",
"p",
"l",
"g"
],
"dateTimeFormat-short": "{1}, {0}",
"dateFormatItem-Gy": "y G",
"dateTimeFormat-medium": "{1}, {0}",
"quarters-standAlone-abbr": [
"1 kw.",
"2 kw.",
"3 kw.",
"4 kw."
],
"dateFormatItem-y": "y G",
"dateFormatItem-yyyy": "y G",
"months-standAlone-abbr": [
"sty",
"lut",
"mar",
"kwi",
"maj",
"cze",
"lip",
"sie",
"wrz",
"paลบ",
"lis",
"gru"
],
"dateFormatItem-Ed": "E, d",
"days-standAlone-narrow": [
"N",
"P",
"W",
"ล",
"C",
"P",
"S"
],
"eraAbbr": [
"BE"
],
"dateFormatItem-GyMMMd": "d MMM y G",
"dateFormat-long": "d MMMM y G",
"dateFormat-medium": "d MMM y G",
"quarters-standAlone-wide": [
"I kwartaล",
"II kwartaล",
"III kwartaล",
"IV kwartaล"
],
"dateFormatItem-yyyyQQQQ": "QQQQ y G",
"quarters-standAlone-narrow": [
"K1",
"K2",
"K3",
"K4"
],
"months-standAlone-wide": [
"styczeล",
"luty",
"marzec",
"kwiecieล",
"maj",
"czerwiec",
"lipiec",
"sierpieล",
"wrzesieล",
"paลบdziernik",
"listopad",
"grudzieล"
],
"dateFormatItem-yyyyMd": "d.MM.y G",
"dateFormatItem-yyyyMMMd": "d MMM y G",
"dateFormatItem-yyyyMEd": "E, d.MM.y G",
"dateFormatItem-MMMd": "d MMM",
"months-format-abbr": [
"sty",
"lut",
"mar",
"kwi",
"maj",
"cze",
"lip",
"sie",
"wrz",
"paลบ",
"lis",
"gru"
],
"quarters-format-abbr": [
"K1",
"K2",
"K3",
"K4"
],
"days-format-abbr": [
"niedz.",
"pon.",
"wt.",
"ลr.",
"czw.",
"pt.",
"sob."
],
"days-format-narrow": [
"N",
"P",
"W",
"ล",
"C",
"P",
"S"
],
"dateFormatItem-GyMMMEd": "E, d MMM y G",
"dateFormatItem-GyMMM": "LLL y G",
"dateFormatItem-yyyyQQQ": "QQQ y G",
"dateFormatItem-MEd": "E, d.MM",
"months-format-narrow": [
"s",
"l",
"m",
"k",
"m",
"c",
"l",
"s",
"w",
"p",
"l",
"g"
],
"days-standAlone-short": [
"niedz.",
"pon.",
"wt.",
"ลr.",
"czw.",
"pt.",
"sob."
],
"dateFormatItem-hm": "hh:mm a",
"days-standAlone-abbr": [
"niedz.",
"pon.",
"wt.",
"ลr.",
"czw.",
"pt.",
"sob."
],
"dateFormat-short": "dd.MM.y G",
"dateFormatItem-yyyyM": "MM.y G",
"dateFormat-full": "EEEE, d MMMM y G",
"dateFormatItem-Md": "d.MM",
"months-format-wide": [
"stycznia",
"lutego",
"marca",
"kwietnia",
"maja",
"czerwca",
"lipca",
"sierpnia",
"wrzeลnia",
"paลบdziernika",
"listopada",
"grudnia"
],
"days-format-short": [
"niedz.",
"pon.",
"wt.",
"ลr.",
"czw.",
"pt.",
"sob."
],
"dateFormatItem-yyyyMMM": "LLL y G",
"quarters-format-wide": [
"I kwartaล",
"II kwartaล",
"III kwartaล",
"IV kwartaล"
],
"days-format-wide": [
"niedziela",
"poniedziaลek",
"wtorek",
"ลroda",
"czwartek",
"piฤ
tek",
"sobota"
],
"dateFormatItem-h": "hh a"
}
//end v1.x content
); | kitsonk/expo | src/dojo/cldr/nls/pl/buddhist.js | JavaScript | bsd-3-clause | 3,188 |
var dir_4627380db2f0c36581ca02ea208a64c6 =
[
[ "support", "dir_2e2aa096c82c7fb5ccae4b9643632450.html", "dir_2e2aa096c82c7fb5ccae4b9643632450" ]
]; | sthWrong/PaasACL | docs/generated documentation/html/dir_4627380db2f0c36581ca02ea208a64c6.js | JavaScript | bsd-3-clause | 150 |
import 'whatwg-fetch';
import { getBaseURL } from 'new-dashboard/utils/base-url';
/*
DEV CREDENTIALS:
https://connreg.carto-staging.com/api/v4
c96add2d9d67ec784ebec742e2ea4cecdedfdf53
*/
async function __createNewConnection (context, payload) {
const baseURL = getBaseURL(context.rootState);
const apiKey = context.rootState.user.api_key;
const url = `${baseURL}/connections?api_key=${apiKey}`;
const response = await fetch(url, { method: 'POST',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify(payload) });
if (!response.ok) {
const message = await response.json();
throw new Error(message.errors);
}
const data = await response.json();
return data;
}
export async function fetchConnectionsList (context) {
if (!context.rootState.user) {
return;
}
context.commit('setLoadingConnections');
const baseURL = getBaseURL(context.rootState);
const apiKey = context.rootState.user.api_key;
const url = `${baseURL}/connections?api_key=${apiKey}`;
try {
const response = await fetch(url);
const data = await response.json();
context.commit('setConnections', data || []);
} catch (error) {
console.error(`ERROR: ${error}`);
}
}
export async function fetchConnectionById (context, id) {
if (!context.rootState.user) {
return;
}
const baseURL = getBaseURL(context.rootState);
const apiKey = context.rootState.user.api_key;
const url = `${baseURL}/connections/${id}?api_key=${apiKey}`;
try {
const response = await fetch(url);
return await response.json();
} catch (error) {
console.error(`ERROR: ${error}`);
}
}
export async function deleteConnection (context, id) {
if (!context.rootState.user) {
return;
}
const baseURL = getBaseURL(context.rootState);
const apiKey = context.rootState.user.api_key;
const url = `${baseURL}/connections/${id}?api_key=${apiKey}`;
try {
await fetch(url, { method: 'DELETE' });
context.dispatch('fetchConnectionsList');
} catch (error) {
console.error(`ERROR: ${error}`);
}
}
export async function checkOauthConnection (context, connector) {
if (!context.rootState.user) {
return;
}
const baseURL = getBaseURL(context.rootState);
const apiKey = context.rootState.user.api_key;
const url = `${baseURL}/connections/check_oauth/${connector}?api_key=${apiKey}`;
const response = await fetch(url);
const data = await response.json();
if (!response.ok) {
throw new Error(data.errors);
}
context.commit('setLoadingConnections');
context.dispatch('fetchConnectionsList');
return data;
}
export async function fetchOAuthFileList (context, connector) {
if (!context.rootState.user) {
return;
}
const baseURL = getBaseURL(context.rootState, 'v1');
const apiKey = context.rootState.user.api_key;
const url = `${baseURL}/imports/service/${connector}/list_files?api_key=${apiKey}`;
const response = await fetch(url);
const data = await response.json();
if (!response.ok) {
throw new Error(data.errors);
}
return data;
}
export async function createNewOauthConnection (context, connector) {
if (!context.rootState.user) {
return;
}
const data = await __createNewConnection(context, {
connector: connector,
type: 'oauth-service'
});
context.dispatch('fetchConnectionsList');
return data && data.auth_url;
}
export async function createNewConnection (context, { name, connector, ...parameters }) {
if (!context.rootState.user) {
return;
}
const data = await __createNewConnection(context, { name, connector, parameters });
context.dispatch('fetchConnectionsList');
return data && data.id;
}
export async function editExistingConnection (context, { id, name, connector, ...parameters }) {
if (!context.rootState.user) {
return;
}
const baseURL = getBaseURL(context.rootState);
const apiKey = context.rootState.user.api_key;
const url = `${baseURL}/connections/${id}?api_key=${apiKey}`;
const response = await fetch(url, { method: 'PUT',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify({ name, parameters }) });
if (!response.ok) {
const message = await response.json();
throw new Error(message.errors);
}
context.dispatch('fetchConnectionsList');
return id;
}
export async function connectionDryrun (context, { connector, id, sql_query, import_as }) {
if (!context.rootState.user) {
return;
}
const baseURL = getBaseURL(context.rootState, 'v1');
const apiKey = context.rootState.user.api_key;
const url = `${baseURL}/connectors/${connector}/dryrun?api_key=${apiKey}`;
const response = await fetch(url, { method: 'POST',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify({ connection_id: id, sql_query, import_as }) });
if (!response.ok) {
const message = await response.json();
throw new Error(message.errors);
}
const data = await response.json();
context.dispatch('fetchConnectionsList');
return data && data.id;
}
export function requestConnector (context, { user, connector }) {
/* Using V3 hubspot API
https://api.hsforms.com/submissions/v3/integration/submit/:portalId/:formGuid */
const hubspot_id = '474999';
const form_id = '1644a76c-4876-45ae-aa85-2420cd3fb3ff';
const CONFIG_PATH = [`submissions/v3/integration/submit/${hubspot_id}/${form_id}`];
const data = getFormData(user, connector);
const opts = {
data,
baseUrl: 'https://api.hsforms.com'
};
return new Promise((resolve, reject) => {
context.rootState.client.post([CONFIG_PATH], opts, err => {
if (err) {
resolve(false);
} else {
resolve(true);
}
});
});
}
function getFormData (user, connector) {
return JSON.stringify({
fields: [
{
name: 'email',
value: user.email
},
{
name: 'lastname',
value: user.last_name || 'no_last_name'
},
{
name: 'firstname',
value: user.name || 'no_firstname'
},
{
name: 'jobtitle',
value: user.job_role || 'no_jobtitle'
},
{
name: 'company',
value:
user.company ||
(user.organization
? user.organization.display_name || user.organization.name
: 'no_company')
},
{
name: 'phone',
value: user.phone || 'no_phone'
},
{
name: 'connector_request_type',
value: 'request'
},
{
name: 'connector_request_name',
value: connector
}
],
context: {
pageUri: window.location.href,
pageName: document.title
}
});
}
// ------------------------- BIGQUERY -------------------------
export async function createNewBQConnection (context, { name, billing_project, default_project, ...payload }) {
if (!context.rootState.user) {
return;
}
const baseURL = getBaseURL(context.rootState);
const apiKey = context.rootState.user.api_key;
const url = `${baseURL}/connections?api_key=${apiKey}`;
const response = await fetch(url, { method: 'POST',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify({ name, connector: 'bigquery', parameters: { billing_project, default_project, service_account: JSON.stringify(payload) } }) });
if (!response.ok) {
let data;
try {
data = await response.json();
} catch (e) {
// Do nothing
}
throw new Error(JSON.stringify({
status: response.status,
message: data ? data.errors : null
}));
}
const data = await response.json();
return data;
}
export async function createNewBQConnectionThroughOAuth (context) {
if (!context.rootState.user) {
return;
}
const baseURL = getBaseURL(context.rootState);
const apiKey = context.rootState.user.api_key;
const url = `${baseURL}/connections?api_key=${apiKey}`;
const response = await fetch(url, { method: 'POST',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify({ connector: 'bigquery' })
});
if (!response.ok) {
let data;
try {
data = await response.json();
} catch (e) {
// Do nothing
}
throw new Error(JSON.stringify({
status: response.status,
message: data ? data.errors : null
}));
}
const data = await response.json();
return data;
}
export async function checkBQConnectionThroughOAuth (context) {
if (!context.rootState.user) {
return;
}
const baseURL = getBaseURL(context.rootState);
const apiKey = context.rootState.user.api_key;
const url = `${baseURL}/connections/check_oauth/bigquery?api_key=${apiKey}`;
const response = await fetch(url);
if (!response.ok) {
let data;
try {
data = await response.json();
} catch (e) {
// Do nothing
}
throw new Error(JSON.stringify({
status: response.status,
message: data ? data.errors : null
}));
}
const data = await response.json();
return data;
}
export async function editBQConnection (context, { bqConnectionId, name, billing_project, default_project, ...payload }) {
if (!context.rootState.user) {
return;
}
const baseURL = getBaseURL(context.rootState);
const apiKey = context.rootState.user.api_key;
const url = `${baseURL}/connections/${bqConnectionId}?api_key=${apiKey}`;
const response = await fetch(url, { method: 'PUT',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify({ name, connector: 'bigquery', parameters: { billing_project, default_project, service_account: JSON.stringify(payload) } }) });
if (!response.ok) {
let data;
try {
data = await response.json();
} catch (e) {
// Do nothing
}
throw new Error(JSON.stringify({
status: response.status,
message: data ? data.errors : null
}));
}
return { id: bqConnectionId };
}
export async function updateBQConnectionBillingProject (context, { id: bqConnectionId, billing_project }) {
if (!context.rootState.user) {
return;
}
const baseURL = getBaseURL(context.rootState);
const apiKey = context.rootState.user.api_key;
const url = `${baseURL}/connections/${bqConnectionId}?api_key=${apiKey}`;
const response = await fetch(url, { method: 'PUT',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify({ parameters: { billing_project } }) });
if (!response.ok) {
let data;
try {
data = await response.json();
} catch (e) {
// Do nothing
}
throw new Error(JSON.stringify({
status: response.status,
message: data ? data.errors : null
}));
}
return { id: bqConnectionId };
}
export async function checkServiceAccount (context, payload) {
const baseURL = getBaseURL(context.rootState, 'v1');
const apiKey = context.rootState.user.api_key;
const url = `${baseURL}/connectors/bigquery/projects?api_key=${apiKey}`;
const response = await fetch(url, { method: 'POST',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify({ service_account: payload }) });
if (!response.ok) {
const message = await response.json();
throw new Error(message.errors);
}
const data = await response.json();
return data;
}
export async function fetchBQProjectsList (context, connectionId) {
if (!context.rootState.user) {
return;
}
context.commit('setLoadingProjects');
const baseURL = getBaseURL(context.rootState);
const apiKey = context.rootState.user.api_key;
const url = `${baseURL}/connections/${connectionId}/projects?api_key=${apiKey}`;
const response = await fetch(url);
if (!response.ok) {
context.commit('setProjects', []);
throw new Error(JSON.stringify({
status: response.status,
message: (await response.json()).errors
}));
}
const data = await response.json();
context.commit('setProjects', data || []);
return data;
}
export async function fetchBQDatasetsList (context, { connectionId, projectId }) {
if (!context.rootState.user) {
return;
}
context.commit('setLoadingDatasets');
const baseURL = getBaseURL(context.rootState);
const apiKey = context.rootState.user.api_key;
const url = `${baseURL}/bigquery/datasets?api_key=${apiKey}&connection_id=${connectionId}&project_id=${projectId}`;
const response = await fetch(url);
if (!response.ok) {
context.commit('setBQDatasets', []);
throw new Error(JSON.stringify({
status: response.status,
message: (await response.json()).errors
}));
}
const data = await response.json();
context.commit('setBQDatasets', data || []);
}
| CartoDB/cartodb | lib/assets/javascripts/new-dashboard/store/actions/connector.js | JavaScript | bsd-3-clause | 12,726 |
var webpack = require('webpack');
var path = require('path');
module.exports = {
entry: './main.jsx',
output: {
path: './output',
publicPath: '/output',
filename: 'bundle.js'
},
module: {
loaders: [
{ test: /\.jsx/, loader: 'jsx-loader' }
]
},
watch: true
};
| comlewod/document | pages/tests/webpack.config.js | JavaScript | bsd-3-clause | 279 |
var http = require('http');
var fs = require('fs');
var url = require('url');
http.createServer( function (req, res) {
var pathname = url.parse(req.url).pathname;
if (pathname == '/data' && req.method == "POST") {
req.setEncoding('utf8');
var t = new Date();
var body = '';
req.on('data', function(chunk){ body += chunk; console.log('data!');});
req.on('end', function () {
var entry = { ts: t, d: body };
fs.appendFile('data.json', JSON.stringify(entry));
console.log("Recorded entry to data.json: " + JSON.stringify(entry));
});
res.writeHead(200);
res.end();
} else {
var fn = pathname.substr(1);
var extn = pathname.slice (pathname.lastIndexOf('.'));
var mimetype = 'none';
switch(pathname.slice( pathname.lastIndexOf('.'))) {
case ".js":
mimetype = "application/javascript";
break;
case ".png":
mimetype = "image/png";
break;
case ".jpg":
mimetype = "image/jpeg";
break;
case ".html":
mimetype = "text/html";
break;
case ".css":
mimetype = "text/css";
break;
}
fs.readFile(fn, function (err,data) {
if (err) {
console.log(err);
res.writeHead(404,{'Content-Type':'text/html'});
res.end();
} else {
res.writeHead(200, {'Content-Type':mimetype});
res.write(data);
res.end();
}
});
}
}).listen(80);
| imalsogreg/retrospective | server.js | JavaScript | bsd-3-clause | 1,676 |
/* Copyright (c) 2006 Patrick Fitzgerald */
/* Modified on 2009-02-04 by Jits, based on: http://groups.google.com/group/barelyfitz/browse_thread/thread/03e8b0672238391a */
function tabberObj(argsObj)
{ if ( window.location.hash && window.location.hash.match( /^#/ ) ) { var el = document.getElementById(window.location.hash.substr(2)); if (el) { el.className = "tabbertab tabbertabdefault" } }
var arg;this.div=null;this.classMain="tabber";this.classMainLive="tabberlive";this.classTab="tabbertab";this.classTabDefault="tabbertabdefault";this.classNav="tabbernav";this.classTabHide="tabbertabhide";this.classNavActive="tabberactive";this.titleElements=['h2','h3','h4','h5','h6'];this.titleElementsStripHTML=true;this.removeTitle=true;this.addLinkId=false;this.linkIdFormat='<tabberid>nav<tabnumberone>';for(arg in argsObj){this[arg]=argsObj[arg];}
this.REclassMain=new RegExp('\\b'+this.classMain+'\\b','gi');this.REclassMainLive=new RegExp('\\b'+this.classMainLive+'\\b','gi');this.REclassTab=new RegExp('\\b'+this.classTab+'\\b','gi');this.REclassTabDefault=new RegExp('\\b'+this.classTabDefault+'\\b','gi');this.REclassTabHide=new RegExp('\\b'+this.classTabHide+'\\b','gi');this.tabs=new Array();if(this.div){this.init(this.div);this.div=null;}}
tabberObj.prototype.init=function(e)
{var
childNodes,i,i2,t,defaultTab=0,DOM_ul,DOM_li,DOM_a,aId,headingElement;if(!document.getElementsByTagName){return false;}
if(e.id){this.id=e.id;}
this.tabs.length=0;childNodes=e.childNodes;for(i=0;i<childNodes.length;i++){if(childNodes[i].className&&childNodes[i].className.match(this.REclassTab)){t=new Object();t.div=childNodes[i];this.tabs[this.tabs.length]=t;if(childNodes[i].className.match(this.REclassTabDefault)){defaultTab=this.tabs.length-1;}}}
DOM_ul=document.createElement("ul");DOM_ul.className=this.classNav;for(i=0;i<this.tabs.length;i++){t=this.tabs[i];t.headingText=t.div.title;if(this.removeTitle){t.div.title='';}
if(!t.headingText){for(i2=0;i2<this.titleElements.length;i2++){headingElement=t.div.getElementsByTagName(this.titleElements[i2])[0];if(headingElement){t.headingText=headingElement.innerHTML;if(this.titleElementsStripHTML){t.headingText.replace(/<br>/gi," ");t.headingText=t.headingText.replace(/<[^>]+>/g,"");}
break;}}}
if(!t.headingText){t.headingText=i+1;}
DOM_li=document.createElement("li");t.li=DOM_li;DOM_a=document.createElement("a");DOM_a.appendChild(document.createTextNode(t.headingText));DOM_a.href="javascript:void(null);";DOM_a.title=t.headingText;DOM_a.onclick=this.navClick;DOM_a.tabber=this;DOM_a.tabberIndex=i;if(this.addLinkId&&this.linkIdFormat){aId=this.linkIdFormat;aId=aId.replace(/<tabberid>/gi,this.id);aId=aId.replace(/<tabnumberzero>/gi,i);aId=aId.replace(/<tabnumberone>/gi,i+1);aId=aId.replace(/<tabtitle>/gi,t.headingText.replace(/[^a-zA-Z0-9\-]/gi,''));DOM_a.id=aId;}
DOM_li.appendChild(DOM_a);DOM_ul.appendChild(DOM_li);}
e.insertBefore(DOM_ul,e.firstChild);e.className=e.className.replace(this.REclassMain,this.classMainLive);this.tabShow(defaultTab);if(typeof this.onLoad=='function'){this.onLoad({tabber:this});}
return this;};tabberObj.prototype.navClick=function(event)
{var
rVal,a,self,tabberIndex,onClickArgs;a=this;if(!a.tabber){return false;}
self=a.tabber;tabberIndex=a.tabberIndex;a.blur();if(typeof self.onClick=='function'){onClickArgs={'tabber':self,'index':tabberIndex,'event':event};if(!event){onClickArgs.event=window.event;}
rVal=self.onClick(onClickArgs);if(rVal===false){return false;}}
self.tabShow(tabberIndex);return false;};tabberObj.prototype.tabHideAll=function()
{var i;for(i=0;i<this.tabs.length;i++){this.tabHide(i);}};tabberObj.prototype.tabHide=function(tabberIndex)
{var div;if(!this.tabs[tabberIndex]){return false;}
div=this.tabs[tabberIndex].div;if(!div.className.match(this.REclassTabHide)){div.className+=' '+this.classTabHide;}
this.navClearActive(tabberIndex);return this;};tabberObj.prototype.tabShow=function(tabberIndex)
{var div;if(!this.tabs[tabberIndex]){return false;}
this.tabHideAll();div=this.tabs[tabberIndex].div;div.className=div.className.replace(this.REclassTabHide,'');this.navSetActive(tabberIndex);if(typeof this.onTabDisplay=='function'){this.onTabDisplay({'tabber':this,'index':tabberIndex});}
return this;};tabberObj.prototype.navSetActive=function(tabberIndex)
{this.tabs[tabberIndex].li.className=this.classNavActive;return this;};tabberObj.prototype.navClearActive=function(tabberIndex)
{this.tabs[tabberIndex].li.className='';return this;};function tabberAutomatic(tabberArgs)
{var
tempObj,divs,i;if(!tabberArgs){tabberArgs={};}
tempObj=new tabberObj(tabberArgs);divs=document.getElementsByTagName("div");for(i=0;i<divs.length;i++){if(divs[i].className&&divs[i].className.match(tempObj.REclassMain)){tabberArgs.div=divs[i];divs[i].tabber=new tabberObj(tabberArgs);}}
return this;}
function tabberAutomaticOnLoad(tabberArgs)
{var oldOnLoad;if(!tabberArgs){tabberArgs={};}
oldOnLoad=window.onload;if(typeof window.onload!='function'){window.onload=function(){tabberAutomatic(tabberArgs);};}else{window.onload=function(){oldOnLoad();tabberAutomatic(tabberArgs);};}}
if(typeof tabberOptions=='undefined'){tabberAutomaticOnLoad();}else{if(!tabberOptions['manualStartup']){tabberAutomaticOnLoad(tabberOptions);}} | myGrid/methodbox | public/javascripts/tabber-minimized.js | JavaScript | bsd-3-clause | 5,227 |
(function() {
'use strict';
var module = angular.module('offerFormDirective');
module.factory('requestSuggestions', ['$http', function($http) {
return function(args) {
return Rx.Observable.fromPromise(
$http.post('/api/v1/restaurants/' + args.restaurantID + '/offer_suggestions', {
title: args.title,
})
);
};
}]);
// Can be used to avoid showing the single suggestion after the user has
// selected a suggestion and the title field is filled with the selected
// offer.
function onlySuggestionSelected(args) {
var suggestions = args.suggestions;
var title = args.title;
return suggestions.length == 1 && suggestions[0].title === title;
}
module.factory('suggestionsObservable', ['requestSuggestions', function(requestSuggestions) {
return function(args) {
var titleObservable = args.titleObservable;
var restaurantID = args.restaurantID;
var scheduler = args.scheduler || Rx.Scheduler.default;
return titleObservable
.filter(function(title) {
// Test for self-equality, to avoid calling for NaN values
return title !== null && (typeof title !== 'undefined') && title === title;
})
.skip(1) // We don't want to show suggestions for the initial value
.debounce(500, scheduler)
.filter(R.compose(
R.lt(2),
R.length
))
.flatMapLatest(function(title) {
return requestSuggestions({
title: title,
restaurantID: restaurantID,
}).map(R.prop('data'))
.map(function(suggestions) {
return {
suggestions: suggestions,
title: title,
};
});
})
.filter(R.propSatisfies(R.complement(R.isNil), 'suggestions'))
.filter(R.complement(onlySuggestionSelected))
.map(R.prop('suggestions'));
};
}]);
})();
| Lunchr/luncher-client | public/src/restaurantAdminView/offerForm/suggestionsObservable.js | JavaScript | bsd-3-clause | 1,955 |
/*
Copyright (c) 2011, Claus Augusti <claus@formatvorlage.de>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the <organization> nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
"use strict";
/**
* Main server.
* Handles a very simple kind of dependency injection, to be refactored to some service
* registry ting.
*
*/
var mod_connect = require('connect')
, mod_sys = require('sys')
, mod_path = require('path')
, mod_resourceservice = null
, mod_resourcemanager = null
, mod_componentcontainer = null
, componentcontainer = null
, mod_cache = require('./cache.js')
, mod_socketio = require('./socketio.js')
, mod_socketmothership = require('./socket_mothership')
, mod_session_store = require('./session_store')
, socket_client = null
, mod_frontcontroller = null
, mod_fs = require('fs')
, cache = null
, redisclient = null
, errorHandler = null
, sessionParser = null
, logger = require('./logger.js').getLogger(mod_path.basename(module.filename))
module.exports = function (options, callback) {
// [TBD] dynamic configServer service (requires dependency management first)
var configServer = null,
configModules = null;
if (!options.conf) {
logger.error('error reading server configuration');
process.exit();
}
configServer = options.conf;
if(!configServer.default_language){
throw logger.error("You must define a default locale e.g. 'en_US' !");
}
configServer.server.serverRoot = mod_path.resolve(configServer.server.serverRoot);
configServer.server.documentRoot = mod_path.resolve(configServer.server.documentRoot);
configServer.server.componentPath = mod_path.resolve(configServer.server.componentPath);
//make server configuration global
global.Server = {
conf : configServer,
UUID : '',
root : configServer.server.serverRoot
};
logger.info('server configuration loaded');
configureServer(configServer);
function configureServer (configServer) {
mod_cache.configure(configServer);
mod_resourcemanager = require('./resourcemanager.js')(configServer, mod_cache);
mod_componentcontainer = require('./componentcontainer.js');
componentcontainer = new mod_componentcontainer.ComponentContainer(mod_resourcemanager);
mod_resourceservice = require('./resourceservice.js')(configServer, mod_resourcemanager, mod_cache, componentcontainer);
mod_frontcontroller = require('./frontcontroller.js')(mod_resourcemanager, componentcontainer);
sessionParser = require('./sessionParser');
errorHandler = require('./errorHandler.js')({
showStack : true,
showMessage : true,
dumpExceptions : false
});
if (configServer.remotecontrol) {
logger.info('setting up remote control');
redisclient = require('./redisclient.js');
redisclient.init(mod_tagmanager);
}
createServer(configServer);
logger.info('server started on port ' + configServer.server.port + ', ' + new Date());
callback();
}
function createServer(configServer) {
//connect to mothership
if (Server.conf.mothership && Server.conf.mothership.connect){
mod_socketmothership.init({
components : componentcontainer.componentMap
});
socket_client = mod_socketmothership.client;
};
var sessionStore = new mod_session_store(socket_client);
var server = mod_connect.createServer(
mod_connect.logger('dev')
, mod_connect.favicon()
, mod_connect.cookieParser()
, mod_connect.session({ key : 'rain.sid', store : sessionStore,
secret: 'let it rain baby ;)',
cookie: {path: "/", httpOnly: false}})
, mod_connect.bodyParser()
, mod_connect.query()
, mod_connect.router(function (app) {
app.get(/^\/.+\/([^\/]*)(\/htdocs\/.*\.html)$/, mod_frontcontroller.handleViewRequest);
app.get(/^\/[^\/]+\/([^\/]*)\/controller\/(.*)$/, mod_frontcontroller.handleControllerRequest);
app.put(/^\/[^\/]\/([^\/]*)\/controller\/(.*)$/, mod_frontcontroller.handleControllerRequest);
app.post(/^\/[^\/]\/([^\/]*)\/controller\/(.*)$/, mod_frontcontroller.handleControllerRequest);
app.delete(/^\/[^\/]\/([^\.]*)\/controller\/(.*)$/, mod_frontcontroller.handleControllerRequest);
app.get(/^\/resources(.*)$/, mod_resourceservice.handleRequest);
//app.get(/instances\/(.*)/, mod_instances.handleInstanceRequest);
}
)
, mod_connect.static(configServer.server.documentRoot)
, sessionParser()
, mod_frontcontroller.handleResourceNotFound
, errorHandler
);
if (configServer.websockets) {
logger.info('starting websockets');
var io = require('socket.io').listen(server);
mod_socketio.init(io);
}
server.listen(configServer.server.port);
};
}
// process.on('SIGINT', function () {
// process.exit();
// });
| juxtapos/Rain | lib/server_new.js | JavaScript | bsd-3-clause | 6,789 |
import WebSocket from 'ws';
import querystring from 'querystring';
import Socket from './Socket.js';
/**
* Websocket server that creates and host all {@link server.Socket} instance.
*
* (@note - could be usefull for broadcasting messages, creating rooms, etc.
*
* @memberof server
*/
class Sockets {
constructor() {
/**
* Store sockets per room. The romm `'*'` store all current connections.
* @private
*/
this._rooms = new Map();
this._initializationCache = new Map();
}
/**
* Initialize sockets, all sockets are added by default added to two rooms:
* - to the room corresponding to the client `clientType`
* - to the '*' that holds all connected sockets
*
* @private
*/
start(httpServer, config, onConnectionCallback) {
const path = config.path;
// init global room
this._rooms.set('*', new Set());
this.wss = new WebSocket.Server({
server: httpServer,
path: `/${path}`, // @note - update according to existing config files (aka cosima-apps)
});
this.wss.on('connection', (ws, req) => {
const queryString = querystring.decode(req.url.split('?')[1]);
const { clientType, key } = queryString;
const binary = !!(parseInt(queryString.binary));
if (binary) {
ws.binaryType = 'arraybuffer';
}
if (!this._initializationCache.has(key)) {
this._initializationCache.set(key, { ws, binary });
} else {
const cached = this._initializationCache.get(key);
this._initializationCache.delete(key);
// should be in order, but just to be sure
const stringWs = cached.binary ? ws : cached.ws;
const binaryWs = cached.binary ? cached.ws : ws;
const socket = new Socket(stringWs, binaryWs, this._rooms, this, config);
socket.addToRoom('*');
socket.addToRoom(clientType);
onConnectionCallback(clientType, socket);
}
});
}
/** @private */
_broadcast(binary, roomIds, excludeSocket, channel, ...args) {
const method = binary ? 'sendBinary' : 'send';
let targets = new Set();
if (typeof roomIds === 'string' || Array.isArray(roomIds)) {
if (typeof roomIds === 'string') {
roomIds = [roomIds];
}
roomIds.forEach(roomId => {
if (this._rooms.has(roomId)) {
const room = this._rooms.get(roomId);
room.forEach(socket => targets.add(socket));
}
});
} else {
targets = this._rooms.get('*');
}
targets.forEach(socket => {
if (socket.ws.readyState === WebSocket.OPEN) {
if (excludeSocket !== null) {
if (socket !== excludeSocket) {
socket[method](channel, ...args);
}
} else {
socket[method](channel, ...args);
}
}
});
}
/**
* Add a socket to a room
*
* @param {server.Socket} socket - Socket to add to the room.
* @param {String} roomId - Id of the room
*/
addToRoom(socket, roomId) {
socket.addToRoom(roomId);
}
/**
* Remove a socket from a room
*
* @param {server.Socket} socket - Socket to remove from the room.
* @param {String} [roomId=null] - Id of the room
*/
removeFromRoom(socket, roomId) {
socket.removeFromRoom(roomId);
}
/**
* Send a string message to all client of given room(s). If no room
* not specified, the message is sent to all clients
*
* @param {String|Array} roomsIds - Ids of the rooms that must receive
* the message. If null the message is sent to all clients
* @param {server.Socket} excludeSocket - Optionnal
* socket to ignore when broadcasting the message, typically the client
* at the origin of the message
* @param {String} channel - Channel of the message
* @param {...*} args - Arguments of the message (as many as needed, of any type)
*/
broadcast(roomIds, excludeSocket, channel, ...args) {
this._broadcast(false, roomIds, excludeSocket, channel, ...args);
}
/**
* Send a binary message (TypedArray) to all client of given room(s). If no room
* not specified, the message is sent to all clients
*
* @param {String|Array} roomsIds - Ids of the rooms that must receive
* the message. If null the message is sent to all clients
* @param {server.Socket} excludeSocket - Optionnal
* socket to ignore when broadcasting the message, typically the client
* at the origin of the message
* @param {String} channel - Channel of the message
* @param {...*} args - Arguments of the message (as many as needed, of any type)
*/
broadcastBinary(roomIds, excludeSocket, channel, typedArray) {
this._broadcast(true, roomIds, excludeSocket, channel, typedArray);
}
};
export default Sockets;
| collective-soundworks/soundworks | src/server/Sockets.js | JavaScript | bsd-3-clause | 4,762 |
var path = require("path");
var fs = require("fs");
var wt = require("./walk-tree");
function createEvent(dirs, event, dir, fileName) {
var fullPath = path.join(dir, fileName);
var exists = dirs.some(function (d) { return d === fullPath; });
var statObj;
function stat() {
if (statObj) { return statObj; }
if (!fullPath) {
statObj = { isDirectory: function () { return false; } };
} else {
try {
statObj = fs.statSync(fullPath);
} catch (e) {
statObj = {
isDirectory: function () { return false; },
deleted: true
};
}
}
return statObj;
}
return {
name: fullPath,
isDirectory: function () {
return stat().isDirectory();
},
isMkdir: function () {
return this.isDirectory() && !exists;
},
isDelete: function () {
return !!stat().deleted;
},
isModify: function () {
return !this.isDelete() && !this.isMkdir();
}
};
}
var addWatch;
function watch(state, dir, options, callback) {
return fs.watch(dir, function (event, fileName) {
var e = createEvent(state.dirs, event, dir, fileName);
if (e.isDirectory() && e.isMkdir()) {
addWatch(state, e.name, options, callback);
}
if (!wt.isExcluded(e.name, options.exclude) &&
typeof callback === "function") {
callback(e);
}
});
}
function addWatch(state, dir, options, callback) {
state.dirs = state.dirs || [];
state.dirs.push(dir);
state.watches = state.watches || [];
state.watches.push(watch(state, dir, options, callback));
}
function watchTree(dir, options, callback) {
var opt = options, cb = callback;
if (arguments.length === 2 && typeof opt === "function") {
cb = opt;
opt = {};
}
var state = {};
opt = opt || {};
opt.exclude = wt.excludeRegExes(opt.exclude);
addWatch(state, dir, opt, cb);
wt.walkTree(dir, opt, function (err, dir) {
if (err) { return; }
addWatch(state, dir, opt, cb);
});
return {
end: function () {
state.watches.forEach(function (w) { w.close(); });
}
};
}
exports.watchTree = watchTree;
| busterjs/fs-watch-tree | lib/watch-tree-unix.js | JavaScript | bsd-3-clause | 2,405 |
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @emails react-core
*/
'use strict';
var OrderedMap;
/**
* Shared, reusable objects.
*/
var hasEmptyStringKey = {
'thisKeyIsFine': {data: []},
'': {thisShouldCauseAFailure: []},
'thisKeyIsAlsoFine': {data: []}
};
/**
* Used as map/forEach callback.
*/
var duplicate = function(itm, key, count) {
return {
uniqueID: itm.uniqueID,
val: itm.val + key + count + this.justToTestScope
};
};
// Should not be allowed - because then null/'null' become impossible to
// distinguish. Every key MUST be a string period!
var hasNullAndUndefStringKey = [
{uniqueID: 'undefined', val: 'thisIsUndefined'},
{uniqueID: 'null', val: 'thisIsNull'}
];
var hasNullKey = [
{uniqueID: 'thisKeyIsFine', data: []},
{uniqueID: 'thisKeyIsAlsoFine', data: []},
{uniqueID: null, data: []}
];
var hasObjectKey = [
{uniqueID: 'thisKeyIsFine', data: []},
{uniqueID: 'thisKeyIsAlsoFine', data: []},
{uniqueID: {}, data: []}
];
var hasArrayKey = [
{uniqueID: 'thisKeyIsFine', data: []},
{uniqueID: 'thisKeyIsAlsoFine', data: []},
{uniqueID: [], data: []}
];
// This should be allowed
var hasNullStringKey = [
{uniqueID: 'thisKeyIsFine', data: []},
{uniqueID: 'thisKeyIsAlsoFine', data: []},
{uniqueID: 'null', data: []}
];
var hasUndefinedKey = [
{uniqueID: 'thisKeyIsFine', data: []},
{uniqueID: 'thisKeyIsAlsoFine', data: []},
{uniqueID: undefined, data: []}
];
var hasUndefinedStringKey = [
{uniqueID: 'thisKeyIsFine', data: []},
{uniqueID: 'thisKeyIsAlsoFine', data: []},
{uniqueID: 'undefined', data: []}
];
var hasPositiveNumericKey = [
{uniqueID: 'notANumber', data: []},
{uniqueID: '5', data: []},
{uniqueID: 'notAnotherNumber', data: []}
];
var hasZeroStringKey = [
{uniqueID: 'greg', data: 'grego'},
{uniqueID: '0', data: '0o'},
{uniqueID: 'tom', data: 'tomo'}
];
var hasZeroNumberKey = [
{uniqueID: 'greg', data: 'grego'},
{uniqueID: 0, data: '0o'},
{uniqueID: 'tom', data: 'tomo'}
];
var hasAllNumericStringKeys = [
{uniqueID: '0', name: 'Gregory'},
{uniqueID: '2', name: 'James'},
{uniqueID: '1', name: 'Tom'}
];
var hasAllNumericKeys = [
{uniqueID: 0, name: 'Gregory'},
{uniqueID: 2, name: 'James'},
{uniqueID: 1, name: 'Tom'}
];
var hasAllValidKeys = [
{uniqueID: 'keyOne', value: 'valueOne'},
{uniqueID: 'keyTwo', value: 'valueTwo'}
];
var hasDuplicateKeys = [
{uniqueID: 'keyOne', value: 'valueOne'},
{uniqueID: 'keyTwo', value: 'valueTwo'},
{uniqueID: 'keyOne', value: 'valueThree'}
];
var idEntities = [
{uniqueID: 'greg', name: 'Gregory'},
{uniqueID: 'james', name: 'James'},
{uniqueID: 'tom', name: 'Tom'}
];
var hasEmptyKey = [
{uniqueID: 'greg', name: 'Gregory'},
{uniqueID: '', name: 'James'},
{uniqueID: 'tom', name: 'Tom'}
];
var extractUniqueID = function(entity) {
return entity.uniqueID;
};
describe('OrderedMap', function() {
beforeEach(function() {
require('mock-modules').dumpCache();
OrderedMap = require('OrderedMap');
});
it('should create according to simple object with keys', function() {
OrderedMap.fromArray(hasAllValidKeys, extractUniqueID);
// Iterate over and ensure key order.
});
it('should create from array when providing an identity CB', function() {
expect(function() {
OrderedMap.fromArray(idEntities, extractUniqueID);
}).not.toThrow();
});
it('should throw if constructing from Array without identity CB', function() {
OrderedMap.fromArray(idEntities, extractUniqueID);
// Iterate and ensure key order
});
it('should not throw when fromArray extracts a numeric key', function() {
expect(function() {
OrderedMap.fromArray(hasPositiveNumericKey, extractUniqueID);
}).not.toThrow();
});
it('should throw when any key is the empty string', function() {
expect(function() {
OrderedMap.fromArray(hasEmptyKey, extractUniqueID);
}).toThrow();
});
it('should not throw when a key is the string "undefined" or "null"',
function() {
var om = OrderedMap.fromArray(hasNullAndUndefStringKey, extractUniqueID);
expect(om.length).toBe(2);
expect(om.indexOfKey('undefined')).toBe(0);
expect(om.indexOfKey('null')).toBe(1);
expect(om.keyAfter('undefined')).toBe('null');
expect(om.keyAfter('null')).toBe(undefined);
expect(om.keyBefore('undefined')).toBe(undefined);
expect(om.has('undefined')).toBe(true);
expect(om.has('null')).toBe(true);
expect(om.get('undefined').val).toBe('thisIsUndefined');
expect(om.get('null').val).toBe('thisIsNull');
});
/**
* Numeric keys are cast to strings.
*/
it('should not throw when a key is the number zero', function() {
var om = OrderedMap.fromArray(hasZeroNumberKey, extractUniqueID);
expect(om.length).toBe(3);
expect(om.indexOfKey('0')).toBe(1);
expect(om.indexOfKey(0)).toBe(1);
});
it('should throw when any key is falsey', function() {
expect(function() {
OrderedMap.fromArray(hasEmptyStringKey, extractUniqueID);
}).toThrow();
expect(function() {
OrderedMap.fromArray(hasNullKey, extractUniqueID);
}).toThrow();
expect(function() {
OrderedMap.fromArray(hasUndefinedKey, extractUniqueID);
}).toThrow();
});
it('should not throw on string keys "undefined/null"', function() {
expect(function() {
OrderedMap.fromArray(hasNullStringKey, extractUniqueID);
}).not.toThrow();
expect(function() {
OrderedMap.fromArray(hasUndefinedStringKey, extractUniqueID);
}).not.toThrow();
});
it('should throw on extracting keys that are not strings/nums', function() {
expect(function() {
OrderedMap.fromArray(hasObjectKey, extractUniqueID);
}).toThrow();
expect(function() {
OrderedMap.fromArray(hasArrayKey, extractUniqueID);
}).toThrow();
});
it('should throw if instantiating with duplicate key', function() {
expect(function() {
OrderedMap.fromArray(hasDuplicateKeys, extractUniqueID);
}).toThrow();
});
it('should not throw when a key is the string "0"', function() {
var verifyOM = function(om) {
expect(om.length).toBe(3);
expect(om.indexOfKey('greg')).toBe(0);
expect(om.indexOfKey('0')).toBe(1);
expect(om.indexOfKey(0)).toBe(1); // Casts on writes and reads.
expect(om.indexOfKey('tom')).toBe(2);
expect(om.keyAfter('greg')).toBe('0');
expect(om.keyAfter('0')).toBe('tom');
expect(om.keyAfter(0)).toBe('tom');
expect(om.keyAfter('tom')).toBe(undefined);
expect(om.keyBefore('greg')).toBe(undefined);
expect(om.keyBefore(0)).toBe('greg');
expect(om.keyBefore('0')).toBe('greg');
expect(om.keyBefore('tom')).toBe('0');
expect(om.has('undefined')).toBe(false);
expect(om.has(0)).toBe(true);
expect(om.has('0')).toBe(true);
};
verifyOM(OrderedMap.fromArray(hasZeroStringKey, extractUniqueID));
verifyOM(OrderedMap.fromArray(hasZeroNumberKey, extractUniqueID));
});
it('should throw when getting invalid public key', function() {
var om = OrderedMap.fromArray(hasAllValidKeys, extractUniqueID);
expect(function() {
om.has(undefined);
}).toThrow();
expect(function() {
om.get(undefined);
}).toThrow();
expect(function() {
om.has(null);
}).toThrow();
expect(function() {
om.get(null);
}).toThrow();
expect(function() {
om.has('');
}).toThrow();
expect(function() {
om.get('');
}).toThrow();
});
it('should throw when any key is falsey', function() {
expect(function() {
OrderedMap.fromArray(hasEmptyStringKey, extractUniqueID);
}).toThrow();
expect(function() {
OrderedMap.fromArray(hasNullKey, extractUniqueID);
}).toThrow();
expect(function() {
OrderedMap.fromArray(hasUndefinedKey, extractUniqueID);
}).toThrow();
});
it('should throw when fromArray is passed crazy args', function() {
// Test passing another OrderedMap (when it expects a plain object.)
// This is probably not what you meant to do! We should error.
var validOM = OrderedMap.fromArray(hasAllValidKeys, extractUniqueID);
expect(function() {
OrderedMap.fromArray({uniqueID: 'asdf'}, extractUniqueID);
}).toThrow();
expect(function() {
OrderedMap.fromArray(validOM, extractUniqueID);
}).toThrow();
});
it('should throw when fromArray is passed crazy things', function() {
expect(function() {
OrderedMap.fromArray(null, extractUniqueID);
}).toThrow();
expect(function() {
OrderedMap.fromArray('stringgg', extractUniqueID);
}).toThrow();
expect(function() {
OrderedMap.fromArray(undefined, extractUniqueID);
}).toThrow();
expect(function() {
OrderedMap.fromArray(new Date(), extractUniqueID);
}).toThrow();
expect(function() {
OrderedMap.fromArray({}, extractUniqueID);
}).toThrow();
// Test failure without extractor
expect(function() {
OrderedMap.fromArray(idEntities);
}).toThrow();
expect(function() {
OrderedMap.fromArray(idEntities, extractUniqueID);
}).not.toThrow();
});
// Testing methods that accept other `OrderedMap`s.
it('should throw when from/merge is passed an non-OrderedMap.', function() {
// Test passing an array to construction.
expect(function() {
OrderedMap.from(idEntities, extractUniqueID);
}).toThrow();
// Test passing an array to merge.
expect(function() {
OrderedMap.fromArray(idEntities, extractUniqueID)
.merge(idEntities, extractUniqueID);
}).toThrow();
// Test passing a plain object to merge.
expect(function() {
OrderedMap.fromArray(
idEntities,
extractUniqueID
).merge({blah: 'willFail'});
}).toThrow();
});
it('should throw when accessing key before/after of non-key', function() {
var om = OrderedMap.fromArray([
{uniqueID: 'first'},
{uniqueID: 'two'}], extractUniqueID
);
expect(function() {
om.keyBefore('dog');
}).toThrow();
expect(function() {
om.keyAfter('cat');
}).toThrow();
expect(function() {
om.keyAfter(null);
}).toThrow();
expect(function() {
om.keyAfter(undefined);
}).toThrow();
});
it('should throw passing invalid/not-present-keys to before/after',
function() {
var om = OrderedMap.fromArray([
{uniqueID: 'one', val: 'first'},
{uniqueID: 'two', val: 'second'},
{uniqueID: 'three', val: 'third'},
{uniqueID: 'four', val: 'fourth'}
], extractUniqueID);
expect(function() {
om.keyBefore('');
}).toThrow();
expect(function() {
om.keyBefore(null);
}).toThrow();
expect(function() {
om.keyBefore(undefined);
}).toThrow();
expect(function() {
om.keyBefore('notInTheOrderedMap!');
}).toThrow();
expect(function() {
om.keyAfter('');
}).toThrow();
expect(function() {
om.keyAfter(null);
}).toThrow();
expect(function() {
om.keyAfter(undefined);
}).toThrow();
expect(function() {
om.keyAfter('notInTheOrderedMap!');
}).toThrow();
expect(function() {
om.nthKeyAfter('', 1);
}).toThrow();
expect(function() {
om.nthKeyAfter(null, 1);
}).toThrow();
expect(function() {
om.nthKeyAfter(undefined, 1);
}).toThrow();
expect(function() {
om.nthKeyAfter('notInTheOrderedMap!', 1);
}).toThrow();
expect(function() {
om.nthKeyBefore('', 1);
}).toThrow();
expect(function() {
om.nthKeyBefore(null, 1);
}).toThrow();
expect(function() {
om.nthKeyBefore(undefined, 1);
}).toThrow();
expect(function() {
om.nthKeyBefore('notInTheOrderedMap!', 1);
}).toThrow();
});
it('should correctly determine the nth key after before', function() {
var om = OrderedMap.fromArray([
{uniqueID: 'one', val: 'first'},
{uniqueID: 'two', val: 'second'},
{uniqueID: 'three', val: 'third'},
{uniqueID: 'four', val: 'fourth'}
], extractUniqueID);
expect(om.keyBefore('one')).toBe(undefined); // first key
expect(om.keyBefore('two')).toBe('one');
expect(om.keyBefore('three')).toBe('two');
expect(om.keyBefore('four')).toBe('three');
expect(om.keyAfter('one')).toBe('two'); // first key
expect(om.keyAfter('two')).toBe('three');
expect(om.keyAfter('three')).toBe('four');
expect(om.keyAfter('four')).toBe(undefined);
expect(om.nthKeyBefore('one', 0)).toBe('one'); // first key
expect(om.nthKeyBefore('one', 1)).toBe(undefined);
expect(om.nthKeyBefore('one', 2)).toBe(undefined);
expect(om.nthKeyBefore('two', 0)).toBe('two');
expect(om.nthKeyBefore('two', 1)).toBe('one');
expect(om.nthKeyBefore('four', 0)).toBe('four');
expect(om.nthKeyBefore('four', 1)).toBe('three');
expect(om.nthKeyAfter('one', 0)).toBe('one');
expect(om.nthKeyAfter('one', 1)).toBe('two');
expect(om.nthKeyAfter('one', 2)).toBe('three');
expect(om.nthKeyAfter('two', 0)).toBe('two');
expect(om.nthKeyAfter('two', 1)).toBe('three');
expect(om.nthKeyAfter('four', 0)).toBe('four');
expect(om.nthKeyAfter('four', 1)).toBe(undefined);
});
it('should compute key indices correctly', function() {
var om = OrderedMap.fromArray([
{uniqueID: 'one', val: 'first'},
{uniqueID: 'two', val: 'second'}
], extractUniqueID);
expect(om.keyAtIndex(0)).toBe('one');
expect(om.keyAtIndex(1)).toBe('two');
expect(om.keyAtIndex(2)).toBe(undefined);
expect(om.indexOfKey('one')).toBe(0);
expect(om.indexOfKey('two')).toBe(1);
expect(om.indexOfKey('nope')).toBe(undefined);
expect(function() {
om.indexOfKey(null);
}).toThrow();
expect(function() {
om.indexOfKey(undefined);
}).toThrow();
expect(function() {
om.indexOfKey(''); // Empty key is not allowed
}).toThrow();
});
it('should compute indices on array that extracted numeric ids', function() {
var som = OrderedMap.fromArray(hasZeroStringKey, extractUniqueID);
expect(som.keyAtIndex(0)).toBe('greg');
expect(som.keyAtIndex(1)).toBe('0');
expect(som.keyAtIndex(2)).toBe('tom');
expect(som.indexOfKey('greg')).toBe(0);
expect(som.indexOfKey('0')).toBe(1);
expect(som.indexOfKey('tom')).toBe(2);
var verifyNumericKeys = function(nom) {
expect(nom.keyAtIndex(0)).toBe('0');
expect(nom.keyAtIndex(1)).toBe('2');
expect(nom.keyAtIndex(2)).toBe('1');
expect(nom.indexOfKey('0')).toBe(0);
expect(nom.indexOfKey('2')).toBe(1); // Prove these are not ordered by
expect(nom.indexOfKey('1')).toBe(2); // their keys
};
var omStringNumberKeys =
OrderedMap.fromArray(hasAllNumericStringKeys, extractUniqueID);
verifyNumericKeys(omStringNumberKeys);
var omNumericKeys =
OrderedMap.fromArray(hasAllNumericKeys, extractUniqueID);
verifyNumericKeys(omNumericKeys);
});
it('should compute indices on mutually exclusive merge', function() {
var om = OrderedMap.fromArray([
{uniqueID: 'one', val: 'first'},
{uniqueID: 'two', val: 'second'}
], extractUniqueID);
var om2 = OrderedMap.fromArray([
{uniqueID: 'three', val: 'third'}
], extractUniqueID);
var res = om.merge(om2);
expect(res.length).toBe(3);
expect(res.keyAtIndex(0)).toBe('one');
expect(res.keyAtIndex(1)).toBe('two');
expect(res.keyAtIndex(2)).toBe('three');
expect(res.keyAtIndex(3)).toBe(undefined);
expect(res.indexOfKey('one')).toBe(0);
expect(res.indexOfKey('two')).toBe(1);
expect(res.indexOfKey('three')).toBe(2);
expect(res.indexOfKey('dog')).toBe(undefined);
expect(res.has('one')).toBe(true);
expect(res.has('two')).toBe(true);
expect(res.has('three')).toBe(true);
expect(res.has('dog')).toBe(false);
expect(res.get('one').val).toBe('first');
expect(res.get('two').val).toBe('second');
expect(res.get('three').val).toBe('third');
expect(res.get('dog')).toBe(undefined);
});
it('should compute indices on intersected merge', function() {
var oneTwo = OrderedMap.fromArray([
{uniqueID: 'one', val: 'first'},
{uniqueID: 'two', val: 'secondOM1'}
], extractUniqueID);
var testOneTwoMergedWithTwoThree = function(res) {
expect(res.length).toBe(3);
expect(res.keyAtIndex(0)).toBe('one');
expect(res.keyAtIndex(1)).toBe('two');
expect(res.keyAtIndex(2)).toBe('three');
expect(res.keyAtIndex(3)).toBe(undefined);
expect(res.indexOfKey('one')).toBe(0);
expect(res.indexOfKey('two')).toBe(1);
expect(res.indexOfKey('three')).toBe(2);
expect(res.indexOfKey('dog')).toBe(undefined);
expect(res.has('one')).toBe(true);
expect(res.has('two')).toBe(true);
expect(res.has('three')).toBe(true);
expect(res.has('dog')).toBe(false);
expect(res.get('one').val).toBe('first');
expect(res.get('two').val).toBe('secondOM2');
expect(res.get('three').val).toBe('third');
expect(res.get('dog')).toBe(undefined);
};
var result =
oneTwo.merge(OrderedMap.fromArray([
{uniqueID: 'two', val: 'secondOM2'},
{uniqueID: 'three', val: 'third'}
], extractUniqueID));
testOneTwoMergedWithTwoThree(result);
// Everything should be exactly as before, since the ordering of `two` was
// already determined by `om`.
result = oneTwo.merge(
OrderedMap.fromArray([
{uniqueID: 'three', val: 'third'},
{uniqueID: 'two', val:'secondOM2'}
], extractUniqueID)
);
testOneTwoMergedWithTwoThree(result);
var testTwoThreeMergedWithOneTwo = function(res) {
expect(res.length).toBe(3);
expect(res.keyAtIndex(0)).toBe('two');
expect(res.keyAtIndex(1)).toBe('three');
expect(res.keyAtIndex(2)).toBe('one');
expect(res.keyAtIndex(3)).toBe(undefined);
expect(res.indexOfKey('two')).toBe(0);
expect(res.indexOfKey('three')).toBe(1);
expect(res.indexOfKey('one')).toBe(2);
expect(res.indexOfKey('cat')).toBe(undefined);
expect(res.has('two')).toBe(true);
expect(res.has('three')).toBe(true);
expect(res.has('one')).toBe(true);
expect(res.has('dog')).toBe(false);
expect(res.get('one').val).toBe('first');
expect(res.get('two').val).toBe('secondOM1');
expect(res.get('three').val).toBe('third');
expect(res.get('dog')).toBe(undefined);
};
result = OrderedMap.fromArray([
{uniqueID: 'two', val: 'secondOM2'},
{uniqueID: 'three', val: 'third'}
], extractUniqueID).merge(oneTwo);
testTwoThreeMergedWithOneTwo(result);
});
it('should merge mutually exclusive keys to the end.', function() {
var om = OrderedMap.fromArray([
{uniqueID: 'one', val: 'first'},
{uniqueID: 'two', val: 'second'}
], extractUniqueID);
var om2 = OrderedMap.fromArray([
{uniqueID: 'three', val: 'first'},
{uniqueID: 'four', val: 'second'}
], extractUniqueID);
var res = om.merge(om2);
expect(res.length).toBe(4);
});
it('should map correctly', function() {
var om = OrderedMap.fromArray([
{uniqueID: 'x', val: 'xx'},
{uniqueID: 'y', val: 'yy'},
{uniqueID: 'z', val: 'zz'}
], extractUniqueID);
var scope = {justToTestScope: 'justTestingScope'};
var verifyResult = function(omResult) {
expect(omResult.length).toBe(3);
expect(omResult.keyAtIndex(0)).toBe('x');
expect(omResult.keyAtIndex(1)).toBe('y');
expect(omResult.keyAtIndex(2)).toBe('z');
expect(omResult.get('x').val).toBe('xxx0justTestingScope');
expect(omResult.get('y').val).toBe('yyy1justTestingScope');
expect(omResult.get('z').val).toBe('zzz2justTestingScope');
};
var resultOM = om.map(function(itm, key, count) {
return {
uniqueID: itm.uniqueID,
val: itm.val + key + count + this.justToTestScope
};
}, scope);
verifyResult(resultOM);
var resArray = [];
om.forEach(function(itm, key, count) {
resArray.push({
uniqueID: itm.uniqueID,
val: itm.val + key + count + this.justToTestScope
});
}, scope);
resultOM = OrderedMap.fromArray(resArray, extractUniqueID);
verifyResult(resultOM);
});
it('should filter correctly', function() {
var om = OrderedMap.fromArray([
{uniqueID: 'x', val: 'xx'},
{uniqueID: 'y', val: 'yy'},
{uniqueID: 'z', val: 'zz'}
], extractUniqueID);
var scope = {justToTestScope: 'justTestingScope'};
var filteringCallback = function(item, key, indexInOriginal) {
expect(this).toBe(scope);
expect(key === 'x' || key === 'y' || key === 'z').toBe(true);
if (key === 'x') {
expect(item.val).toBe('xx');
expect(indexInOriginal).toBe(0);
return false;
} else if (key === 'y') {
expect(item.val).toBe('yy');
expect(indexInOriginal).toBe(1);
return true;
} else {
expect(item.val).toBe('zz');
expect(indexInOriginal).toBe(2);
return true;
}
};
var verifyResult = function(omResult) {
expect(omResult.length).toBe(2);
expect(omResult.keyAtIndex(0)).toBe('y');
expect(omResult.keyAtIndex(1)).toBe('z');
expect(omResult.has('x')).toBe(false);
expect(omResult.has('z')).toBe(true);
expect(omResult.get('z').val).toBe('zz');
expect(omResult.has('y')).toBe(true);
expect(omResult.get('y').val).toBe('yy');
};
var resultOM = om.filter(filteringCallback, scope);
verifyResult(resultOM);
});
it('should throw when providing invalid ranges to ranging', function() {
var om = OrderedMap.fromArray([
{uniqueID: 'x', val: 'xx'},
{uniqueID: 'y', val: 'yy'},
{uniqueID: 'z', val: 'zz'}
], extractUniqueID);
var scope = {justToTestScope: 'justTestingScope'};
expect(function() {
om.mapRange(duplicate, 0, 3, scope);
}).not.toThrow();
expect(function() {
om.filterRange(duplicate, 0, 3, scope);
}).not.toThrow();
expect(function() {
om.forEachRange(duplicate, 0, 3, scope);
}).not.toThrow();
expect(function() {
om.mapKeyRange(duplicate, 'x', 3, scope);
}).toThrow(
'Invariant Violation: mapKeyRange must be given keys ' +
'that are present.'
);
expect(function() {
om.forEachKeyRange(duplicate, 'x', 3, scope);
}).toThrow(
'Invariant Violation: forEachKeyRange must be given keys ' +
'that are present.'
);
expect(function() {
om.mapRange(duplicate, 0, 4, scope);
}).toThrow();
expect(function() {
om.filterRange(duplicate, 0, 4, scope);
}).toThrow();
expect(function() {
om.forEachRange(duplicate, 0, 4, scope);
}).toThrow();
expect(function() {
om.mapKeyRange(duplicate, 'x', null, scope);
}).toThrow();
expect(function() {
om.forEachKeyRange(duplicate, 'x', null, scope);
}).toThrow();
expect(function() {
om.mapRange(duplicate, -1, 1, scope);
}).toThrow();
expect(function() {
om.filterRange(duplicate, -1, 1, scope);
}).toThrow();
expect(function() {
om.forEachRange(duplicate, -1, 1, scope);
}).toThrow();
expect(function() {
om.mapKeyRange(duplicate, null, 'y', scope);
}).toThrow();
expect(function() {
om.forEachKeyRange(duplicate, null, 'y', scope);
}).toThrow();
expect(function() {
om.mapRange(duplicate, 0, 0, scope);
}).not.toThrow();
expect(function() {
om.filterRange(duplicate, 0, 0, scope);
}).not.toThrow();
expect(function() {
om.forEachRange(duplicate, 0, 0, scope);
}).not.toThrow();
expect(function() {
om.mapKeyRange(duplicate, 'x', 'x', scope);
}).not.toThrow();
expect(function() {
om.forEachKeyRange(duplicate, 'x', 'x', scope);
}).not.toThrow();
expect(function() {
om.mapRange(duplicate, 0, -1, scope);
}).toThrow();
expect(function() {
om.filterRange(duplicate, 0, -1, scope);
}).toThrow();
expect(function() {
om.forEachRange(duplicate, 0, -1, scope);
}).toThrow();
expect(function() {
om.mapKeyRange(duplicate, 'x', null, scope);
}).toThrow();
expect(function() {
om.forEachKeyRange(duplicate, 'x', null, scope);
}).toThrow();
expect(function() {
om.mapRange(duplicate, 2, 1, scope);
}).not.toThrow();
expect(function() {
om.filterRange(duplicate, 2, 1, scope);
}).not.toThrow();
expect(function() {
om.forEachRange(duplicate, 2, 1, scope);
}).not.toThrow();
expect(function() {
om.mapKeyRange(duplicate, 'z', 'z', scope);
}).not.toThrow();
expect(function() {
om.forEachKeyRange(duplicate, 'z', 'z', scope);
}).not.toThrow();
expect(function() {
om.mapRange(duplicate, 2, 2, scope);
}).toThrow();
expect(function() {
om.filterRange(duplicate, 2, 2, scope);
}).toThrow();
expect(function() {
om.forEachRange(duplicate, 2, 2, scope);
}).toThrow();
expect(function() {
om.mapKeyRange(duplicate, 'z', null, scope);
}).toThrow();
expect(function() {
om.forEachKeyRange(duplicate, 'z', null, scope);
}).toThrow();
// Provide keys in reverse order - should throw.
expect(function() {
om.mapKeyRange(duplicate, 'y', 'x', scope);
}).toThrow();
expect(function() {
om.forEachKeyRange(duplicate, 'y', 'x', scope);
}).toThrow();
});
// TEST length zero map, or keyrange start===end
it('should map range correctly', function() {
var om = OrderedMap.fromArray([
{uniqueID: 'x', val: 'xx'},
{uniqueID: 'y', val: 'yy'},
{uniqueID: 'z', val: 'zz'}
], extractUniqueID);
var scope = {justToTestScope: 'justTestingScope'};
var verifyThreeItems = function(omResult) {
expect(omResult.length).toBe(3);
expect(omResult.keyAtIndex(0)).toBe('x');
expect(omResult.keyAtIndex(1)).toBe('y');
expect(omResult.keyAtIndex(2)).toBe('z');
expect(omResult.get('x').val).toBe('xxx0justTestingScope');
expect(omResult.get('y').val).toBe('yyy1justTestingScope');
expect(omResult.get('z').val).toBe('zzz2justTestingScope');
};
var verifyFirstTwoItems = function(omResult) {
expect(omResult.length).toBe(2);
expect(omResult.keyAtIndex(0)).toBe('x');
expect(omResult.keyAtIndex(1)).toBe('y');
expect(omResult.get('x').val).toBe('xxx0justTestingScope');
expect(omResult.get('y').val).toBe('yyy1justTestingScope');
};
var verifyLastTwoItems = function(omResult) {
expect(omResult.length).toBe(2);
expect(omResult.keyAtIndex(0)).toBe('y');
expect(omResult.keyAtIndex(1)).toBe('z');
expect(omResult.get('y').val).toBe('yyy1justTestingScope');
expect(omResult.get('z').val).toBe('zzz2justTestingScope');
};
var verifyMiddleItem = function(omResult) {
expect(omResult.length).toBe(1);
expect(omResult.keyAtIndex(0)).toBe('y');
expect(omResult.get('y').val).toBe('yyy1justTestingScope');
};
var verifyEmpty = function(omResult) {
expect(omResult.length).toBe(0);
};
var omResultThree = om.mapRange(duplicate, 0, 3, scope);
verifyThreeItems(omResultThree);
var resArray = [];
var pushToResArray = function(itm, key, count) {
resArray.push({
uniqueID: itm.uniqueID,
val: itm.val + key + count + this.justToTestScope
});
};
om.forEachRange(pushToResArray, 0, 3, scope);
omResultThree = OrderedMap.fromArray(resArray, extractUniqueID);
verifyThreeItems(omResultThree);
var omResultFirstTwo = om.mapRange(duplicate, 0, 2, scope);
verifyFirstTwoItems(omResultFirstTwo);
resArray = [];
om.forEachRange(pushToResArray, 0, 2, scope);
omResultFirstTwo = OrderedMap.fromArray(resArray, extractUniqueID);
verifyFirstTwoItems(omResultFirstTwo);
var omResultLastTwo = om.mapRange(duplicate, 1, 2, scope);
verifyLastTwoItems(omResultLastTwo);
resArray = [];
om.forEachRange(pushToResArray, 1, 2, scope);
omResultLastTwo = OrderedMap.fromArray(resArray, extractUniqueID);
verifyLastTwoItems(omResultLastTwo);
var omResultMiddle = om.mapRange(duplicate, 1, 1, scope);
verifyMiddleItem(omResultMiddle);
resArray = [];
om.forEachRange(pushToResArray, 1, 1, scope);
omResultMiddle = OrderedMap.fromArray(resArray, extractUniqueID);
verifyMiddleItem(omResultMiddle);
var omResultNone = om.mapRange(duplicate, 1, 0, scope);
verifyEmpty(omResultNone);
});
it('should extract the original array correctly', function() {
var sourceArray = [
{uniqueID: 'x', val: 'xx'},
{uniqueID: 'y', val: 'yy'},
{uniqueID: 'z', val: 'zz'}
];
var om = OrderedMap.fromArray(sourceArray, extractUniqueID);
expect(om.toArray()).toEqual(sourceArray);
});
});
| silkapp/react | src/shared/utils/__tests__/OrderedMap-test.js | JavaScript | bsd-3-clause | 29,510 |
$('.ui.dropdown').dropdown();
$(document).ready(function() {
$('#test-form').on('submit', function(e) {
e.preventDefault();
var format = document.getElementsByName('test-format')[0].value;
var email = document.getElementsByName('test-email')[0].value;
// Verify the parameters were passed
if (format === '' || email === '') {
return;
}
$('#test-button').addClass('loading');
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://trumail.io/' + format + '/' + email, true);
xhr.onload = function(e) {
var results;
if (format === 'json') {
results = vkbeautify.json(xhr.responseText, 4);
}
if (format === 'xml') {
results = vkbeautify.xml(xhr.responseText, 4);
}
document.getElementsByName('test-results')[0].textContent = results;
$('.ui.modal').modal({
closable: false,
transition: 'flip vertical'
}).modal('show');
$('#test-button').removeClass('loading');
};
xhr.onerror = function(e) {
console.error(xhr.statusText);
};
xhr.send(null);
});
}); | helielson/trumail | web/assets/js/trumail.js | JavaScript | bsd-3-clause | 1,268 |
'use strict';
const Assert = require('chai').assert;
const request = require('../support/request');
const { Before, Given, Then, When, After } = require('cucumber');
// Timeout of 15 seconds
const TIMEOUT = 15 * 1000;
/**
* Helper function to create a collection
* @method createCollection
* @param {Object} body The body of the request
* @returns {Promise}
*/
function createCollection(body) {
return this.getJwt(this.apiToken)
.then((response) => {
this.jwt = response.body.token;
return request({
uri: `${this.instance}/${this.namespace}/collections`,
method: 'POST',
auth: {
bearer: this.jwt
},
body,
json: true
});
});
}
/**
* Helper function to delete a collection
* @method deleteCollection
* @param {Number} [id] Id of the collection to delete
* @returns {Promise}
*/
function deleteCollection(id) {
if (!id) {
return Promise.resolve();
}
return request({
uri: `${this.instance}/${this.namespace}/collections/${id}`,
method: 'DELETE',
auth: {
bearer: this.jwt
},
json: true
}).then((response) => {
Assert.strictEqual(response.statusCode, 204);
});
}
Before('@collections', function hook() {
this.repoOrg = this.testOrg;
this.repoName = 'functional-collections';
this.pipelineId = null;
this.firstCollectionId = null;
this.secondCollectionId = null;
});
When(/^they check the default collection$/, { timeout: TIMEOUT }, function step() {
return this.ensurePipelineExists({ repoName: this.repoName })
.then(() => request({
uri: `${this.instance}/${this.namespace}/collections`,
method: 'GET',
auth: {
bearer: this.jwt
},
json: true
})
.then((response) => {
Assert.strictEqual(response.statusCode, 200);
this.defaultCollectionId = response.body.find(collection =>
collection.type === 'default'
).id;
Assert.notEqual(this.defaultCollectionId, undefined);
})
);
});
Then(/^they can see the default collection contains that pipeline$/, { timeout: TIMEOUT },
function step() {
const pipelineId = parseInt(this.pipelineId, 10);
return request({
uri: `${this.instance}/${this.namespace}/collections/${this.defaultCollectionId}`,
method: 'GET',
auth: {
bearer: this.jwt
},
json: true
}).then((response) => {
Assert.strictEqual(response.statusCode, 200);
// TODO: May need to change back
// Assert.deepEqual(response.body.pipelineIds, [pipelineId]);
Assert.include(response.body.pipelineIds, pipelineId);
});
});
When(/^they create a new collection "myCollection" with that pipeline$/,
{ timeout: TIMEOUT }, function step() {
return this.ensurePipelineExists({ repoName: this.repoName })
.then(() => {
const requestBody = {
name: 'myCollection',
pipelineIds: [this.pipelineId]
};
return createCollection.call(this, requestBody);
})
.then((response) => {
Assert.strictEqual(response.statusCode, 201);
this.firstCollectionId = response.body.id;
});
});
Then(/^they can see that collection$/, { timeout: TIMEOUT }, function step() {
return request({
uri: `${this.instance}/${this.namespace}/collections/${this.firstCollectionId}`,
method: 'GET',
auth: {
bearer: this.jwt
},
json: true
}).then((response) => {
Assert.strictEqual(response.statusCode, 200);
Assert.strictEqual(response.body.name, 'myCollection');
});
});
Then(/^the collection contains that pipeline$/, { timeout: TIMEOUT }, function step() {
const pipelineId = parseInt(this.pipelineId, 10);
return request({
uri: `${this.instance}/${this.namespace}/collections/${this.firstCollectionId}`,
method: 'GET',
auth: {
bearer: this.jwt
},
json: true
}).then((response) => {
Assert.strictEqual(response.statusCode, 200);
Assert.deepEqual(response.body.pipelineIds, [pipelineId]);
});
});
When(/^they create a new collection "myCollection"$/, { timeout: TIMEOUT }, function step() {
return createCollection.call(this, { name: 'myCollection' })
.then((response) => {
Assert.strictEqual(response.statusCode, 201);
this.firstCollectionId = response.body.id;
});
});
Then(/^the collection is empty$/, { timeout: TIMEOUT }, function step() {
return request({
uri: `${this.instance}/${this.namespace}/collections/${this.firstCollectionId}`,
method: 'GET',
auth: {
bearer: this.jwt
},
json: true
}).then((response) => {
Assert.strictEqual(response.statusCode, 200);
Assert.deepEqual(response.body.pipelineIds, []);
});
});
When(/^they update the collection "myCollection" with that pipeline$/,
{ timeout: TIMEOUT }, function step() {
return this.ensurePipelineExists({ repoName: this.repoName })
.then(() => {
const pipelineId = parseInt(this.pipelineId, 10);
return request({
uri: `${this.instance}/${this.namespace}/collections/` +
`${this.firstCollectionId}`,
method: 'PUT',
auth: {
bearer: this.jwt
},
body: {
pipelineIds: [pipelineId]
},
json: true
}).then((response) => {
Assert.strictEqual(response.statusCode, 200);
});
});
});
Given(/^they have a collection "myCollection"$/, { timeout: TIMEOUT }, function step() {
return createCollection.call(this, { name: 'myCollection' })
.then((response) => {
Assert.oneOf(response.statusCode, [409, 201]);
if (response.statusCode === 201) {
this.firstCollectionId = response.body.id;
} else {
const str = response.body.message;
[, this.firstCollectionId] = str.split(': ');
}
});
});
Given(/^they have a collection "anotherCollection"$/, { timeout: TIMEOUT }, function step() {
return createCollection.call(this, { name: 'anotherCollection' })
.then((response) => {
Assert.oneOf(response.statusCode, [409, 201]);
if (response.statusCode === 201) {
this.secondCollectionId = response.body.id;
} else {
const str = response.body.message;
[, this.secondCollectionId] = str.split(': ');
}
});
});
When(/^they fetch all their collections$/, { timeout: TIMEOUT }, function step() {
return request({
uri: `${this.instance}/${this.namespace}/collections`,
method: 'GET',
auth: {
bearer: this.jwt
},
json: true
}).then((response) => {
Assert.strictEqual(response.statusCode, 200);
this.collections = response.body;
});
});
Then(/^they can see those collections and the default collection$/, function step() {
const normalCollectionNames = this.collections.filter(c => c.type === 'normal')
.map(c => c.name);
const defaultCollection = this.collections.filter(c => c.type === 'default');
Assert.strictEqual(normalCollectionNames.length, 2);
Assert.strictEqual(defaultCollection.length, 1);
Assert.ok(normalCollectionNames.includes('myCollection'));
Assert.ok(normalCollectionNames.includes('anotherCollection'));
});
When(/^they delete that collection$/, { timeout: TIMEOUT }, function step() {
return request({
uri: `${this.instance}/${this.namespace}/collections/${this.firstCollectionId}`,
method: 'DELETE',
auth: {
bearer: this.jwt
},
json: true
})
.then((response) => {
Assert.strictEqual(response.statusCode, 204);
});
});
Then(/^that collection no longer exists$/, { timeout: TIMEOUT }, function step() {
return request({
uri: `${this.instance}/${this.namespace}/collections/${this.firstCollectionId}`,
method: 'GET',
auth: {
bearer: this.jwt
},
json: true
}).then((response) => {
Assert.strictEqual(response.statusCode, 404);
this.firstCollectionId = null;
});
});
When(/^they create another collection with the same name "myCollection"$/,
{ timeout: TIMEOUT }, function step() {
return createCollection.call(this, { name: 'myCollection' })
.then((response) => {
Assert.ok(response);
this.lastResponse = response;
});
});
Then(/^they receive an error regarding unique collections$/, function step() {
Assert.strictEqual(this.lastResponse.statusCode, 409);
Assert.strictEqual(this.lastResponse.body.message,
`Collection already exists with the ID: ${this.firstCollectionId}`);
});
After('@collections', function hook() {
// Delete the collections created in the functional tests if they exist
return Promise.all([
deleteCollection.call(this, this.firstCollectionId),
deleteCollection.call(this, this.secondCollectionId)
]);
});
| screwdriver-cd/api | features/step_definitions/collection.js | JavaScript | bsd-3-clause | 9,865 |
describe("module:ng.input:input[url]",function(){var a;beforeEach(function(){a=browser.rootEl,browser.get("./examples/example-url-input-directive/index.html")});var b=element(by.binding("text")),c=element(by.binding("myForm.input.$valid")),d=element(by.model("text"));it("should initialize to model",function(){expect(b.getText()).toContain("http://google.com"),expect(c.getText()).toContain("true")}),it("should be invalid if empty",function(){d.clear(),d.sendKeys(""),expect(b.getText()).toEqual("text ="),expect(c.getText()).toContain("false")}),it("should be invalid if not url",function(){d.clear(),d.sendKeys("box"),expect(c.getText()).toContain("false")})});
//# sourceMappingURL=..\..\..\..\debug\angular\docs\ptore2e\example-url-input-directive\jqlite_test.min.map | infrabel/docs-gnap | node_modules/gnap-theme-gnap-angular/js/angular/docs/ptore2e/example-url-input-directive/jqlite_test.min.js | JavaScript | bsd-3-clause | 773 |
var Highlight = function() {
/* Utility functions */
function escape(value) {
return value.replace(/&/gm, '&').replace(/</gm, '<').replace(/>/gm, '>');
}
function tag(node) {
return node.nodeName.toLowerCase();
}
function testRe(re, lexeme) {
var match = re && re.exec(lexeme);
return match && match.index == 0;
}
function blockLanguage(block) {
var classes = (block.className + ' ' + (block.parentNode ? block.parentNode.className : '')).split(/\s+/);
classes = classes.map(function(c) {return c.replace(/^lang(uage)?-/, '');});
return classes.filter(function(c) {return getLanguage(c) || /no(-?)highlight/.test(c);})[0];
}
function inherit(parent, obj) {
var result = {};
for (var key in parent)
result[key] = parent[key];
if (obj)
for (var key in obj)
result[key] = obj[key];
return result;
};
/* Stream merging */
function nodeStream(node) {
var result = [];
(function _nodeStream(node, offset) {
for (var child = node.firstChild; child; child = child.nextSibling) {
if (child.nodeType == 3)
offset += child.nodeValue.length;
else if (child.nodeType == 1) {
result.push({
event: 'start',
offset: offset,
node: child
});
offset = _nodeStream(child, offset);
result.push({
event: 'stop',
offset: offset,
node: child
});
}
}
return offset;
})(node, 0);
return result;
}
function mergeStreams(original, highlighted, value) {
var processed = 0;
var result = '';
var nodeStack = [];
function selectStream() {
if (!original.length || !highlighted.length) {
return original.length ? original : highlighted;
}
if (original[0].offset != highlighted[0].offset) {
return (original[0].offset < highlighted[0].offset) ? original : highlighted;
}
/*
To avoid starting the stream just before it should stop the order is
ensured that original always starts first and closes last:
if (event1 == 'start' && event2 == 'start')
return original;
if (event1 == 'start' && event2 == 'stop')
return highlighted;
if (event1 == 'stop' && event2 == 'start')
return original;
if (event1 == 'stop' && event2 == 'stop')
return highlighted;
... which is collapsed to:
*/
return highlighted[0].event == 'start' ? original : highlighted;
}
function open(node) {
function attr_str(a) {return ' ' + a.nodeName + '="' + escape(a.value) + '"';}
result += '<' + tag(node) + Array.prototype.map.call(node.attributes, attr_str).join('') + '>';
}
function close(node) {
result += '</' + tag(node) + '>';
}
function render(event) {
(event.event == 'start' ? open : close)(event.node);
}
while (original.length || highlighted.length) {
var stream = selectStream();
result += escape(value.substr(processed, stream[0].offset - processed));
processed = stream[0].offset;
if (stream == original) {
/*
On any opening or closing tag of the original markup we first close
the entire highlighted node stack, then render the original tag along
with all the following original tags at the same offset and then
reopen all the tags on the highlighted stack.
*/
nodeStack.reverse().forEach(close);
do {
render(stream.splice(0, 1)[0]);
stream = selectStream();
} while (stream == original && stream.length && stream[0].offset == processed);
nodeStack.reverse().forEach(open);
} else {
if (stream[0].event == 'start') {
nodeStack.push(stream[0].node);
} else {
nodeStack.pop();
}
render(stream.splice(0, 1)[0]);
}
}
return result + escape(value.substr(processed));
}
/* Initialization */
function compileLanguage(language) {
function reStr(re) {
return (re && re.source) || re;
}
function langRe(value, global) {
return RegExp(
reStr(value),
'm' + (language.case_insensitive ? 'i' : '') + (global ? 'g' : '')
);
}
function compileMode(mode, parent) {
if (mode.compiled)
return;
mode.compiled = true;
mode.keywords = mode.keywords || mode.beginKeywords;
if (mode.keywords) {
var compiled_keywords = {};
var flatten = function(className, str) {
if (language.case_insensitive) {
str = str.toLowerCase();
}
str.split(' ').forEach(function(kw) {
var pair = kw.split('|');
compiled_keywords[pair[0]] = [className, pair[1] ? Number(pair[1]) : 1];
});
};
if (typeof mode.keywords == 'string') { // string
flatten('keyword', mode.keywords);
} else {
Object.keys(mode.keywords).forEach(function (className) {
flatten(className, mode.keywords[className]);
});
}
mode.keywords = compiled_keywords;
}
mode.lexemesRe = langRe(mode.lexemes || /\b[A-Za-z0-9_]+\b/, true);
if (parent) {
if (mode.beginKeywords) {
mode.begin = '\\b(' + mode.beginKeywords.split(' ').join('|') + ')\\b';
}
if (!mode.begin)
mode.begin = /\B|\b/;
mode.beginRe = langRe(mode.begin);
if (!mode.end && !mode.endsWithParent)
mode.end = /\B|\b/;
if (mode.end)
mode.endRe = langRe(mode.end);
mode.terminator_end = reStr(mode.end) || '';
if (mode.endsWithParent && parent.terminator_end)
mode.terminator_end += (mode.end ? '|' : '') + parent.terminator_end;
}
if (mode.illegal)
mode.illegalRe = langRe(mode.illegal);
if (mode.relevance === undefined)
mode.relevance = 1;
if (!mode.contains) {
mode.contains = [];
}
var expanded_contains = [];
mode.contains.forEach(function(c) {
if (c.variants) {
c.variants.forEach(function(v) {expanded_contains.push(inherit(c, v));});
} else {
expanded_contains.push(c == 'self' ? mode : c);
}
});
mode.contains = expanded_contains;
mode.contains.forEach(function(c) {compileMode(c, mode);});
if (mode.starts) {
compileMode(mode.starts, parent);
}
var terminators =
mode.contains.map(function(c) {
return c.beginKeywords ? '\\.?(' + c.begin + ')\\.?' : c.begin;
})
.concat([mode.terminator_end, mode.illegal])
.map(reStr)
.filter(Boolean);
mode.terminators = terminators.length ? langRe(terminators.join('|'), true) : {exec: function(s) {return null;}};
}
compileMode(language);
}
/*
Core highlighting function. Accepts a language name, or an alias, and a
string with the code to highlight. Returns an object with the following
properties:
- relevance (int)
- value (an HTML string with highlighting markup)
*/
function highlight(name, value, ignore_illegals, continuation) {
function subMode(lexeme, mode) {
for (var i = 0; i < mode.contains.length; i++) {
if (testRe(mode.contains[i].beginRe, lexeme)) {
return mode.contains[i];
}
}
}
function endOfMode(mode, lexeme) {
if (testRe(mode.endRe, lexeme)) {
return mode;
}
if (mode.endsWithParent) {
return endOfMode(mode.parent, lexeme);
}
}
function isIllegal(lexeme, mode) {
return !ignore_illegals && testRe(mode.illegalRe, lexeme);
}
function keywordMatch(mode, match) {
var match_str = language.case_insensitive ? match[0].toLowerCase() : match[0];
return mode.keywords.hasOwnProperty(match_str) && mode.keywords[match_str];
}
function buildSpan(classname, insideSpan, leaveOpen, noPrefix) {
var classPrefix = noPrefix ? '' : options.classPrefix,
openSpan = '<span class="' + classPrefix,
closeSpan = leaveOpen ? '' : '</span>';
openSpan += classname + '">';
return openSpan + insideSpan + closeSpan;
}
function processKeywords() {
if (!top.keywords)
return escape(mode_buffer);
var result = '';
var last_index = 0;
top.lexemesRe.lastIndex = 0;
var match = top.lexemesRe.exec(mode_buffer);
while (match) {
result += escape(mode_buffer.substr(last_index, match.index - last_index));
var keyword_match = keywordMatch(top, match);
if (keyword_match) {
relevance += keyword_match[1];
result += buildSpan(keyword_match[0], escape(match[0]));
} else {
result += escape(match[0]);
}
last_index = top.lexemesRe.lastIndex;
match = top.lexemesRe.exec(mode_buffer);
}
return result + escape(mode_buffer.substr(last_index));
}
function processSubLanguage() {
if (top.subLanguage && !languages[top.subLanguage]) {
return escape(mode_buffer);
}
var result = top.subLanguage ? highlight(top.subLanguage, mode_buffer, true, subLanguageTop) : highlightAuto(mode_buffer);
// Counting embedded language score towards the host language may be disabled
// with zeroing the containing mode relevance. Usecase in point is Markdown that
// allows XML everywhere and makes every XML snippet to have a much larger Markdown
// score.
if (top.relevance > 0) {
relevance += result.relevance;
}
if (top.subLanguageMode == 'continuous') {
subLanguageTop = result.top;
}
return buildSpan(result.language, result.value, false, true);
}
function processBuffer() {
return top.subLanguage !== undefined ? processSubLanguage() : processKeywords();
}
function startNewMode(mode, lexeme) {
var markup = mode.className? buildSpan(mode.className, '', true): '';
if (mode.returnBegin) {
result += markup;
mode_buffer = '';
} else if (mode.excludeBegin) {
result += escape(lexeme) + markup;
mode_buffer = '';
} else {
result += markup;
mode_buffer = lexeme;
}
top = Object.create(mode, {parent: {value: top}});
}
function processLexeme(buffer, lexeme) {
mode_buffer += buffer;
if (lexeme === undefined) {
result += processBuffer();
return 0;
}
var new_mode = subMode(lexeme, top);
if (new_mode) {
result += processBuffer();
startNewMode(new_mode, lexeme);
return new_mode.returnBegin ? 0 : lexeme.length;
}
var end_mode = endOfMode(top, lexeme);
if (end_mode) {
var origin = top;
if (!(origin.returnEnd || origin.excludeEnd)) {
mode_buffer += lexeme;
}
result += processBuffer();
do {
if (top.className) {
result += '</span>';
}
relevance += top.relevance;
top = top.parent;
} while (top != end_mode.parent);
if (origin.excludeEnd) {
result += escape(lexeme);
}
mode_buffer = '';
if (end_mode.starts) {
startNewMode(end_mode.starts, '');
}
return origin.returnEnd ? 0 : lexeme.length;
}
if (isIllegal(lexeme, top))
throw new Error('Illegal lexeme "' + lexeme + '" for mode "' + (top.className || '<unnamed>') + '"');
/*
Parser should not reach this point as all types of lexemes should be caught
earlier, but if it does due to some bug make sure it advances at least one
character forward to prevent infinite looping.
*/
mode_buffer += lexeme;
return lexeme.length || 1;
}
var language = getLanguage(name);
if (!language) {
throw new Error('Unknown language: "' + name + '"');
}
compileLanguage(language);
var top = continuation || language;
var subLanguageTop;
var result = '';
for(var current = top; current != language; current = current.parent) {
if (current.className) {
result = buildSpan(current.className, '', true) + result;
}
}
var mode_buffer = '';
var relevance = 0;
try {
var match, count, index = 0;
while (true) {
top.terminators.lastIndex = index;
match = top.terminators.exec(value);
if (!match)
break;
count = processLexeme(value.substr(index, match.index - index), match[0]);
index = match.index + count;
}
processLexeme(value.substr(index));
for(var current = top; current.parent; current = current.parent) { // close dangling modes
if (current.className) {
result += '</span>';
}
};
return {
relevance: relevance,
value: result,
language: name,
top: top
};
} catch (e) {
if (e.message.indexOf('Illegal') != -1) {
return {
relevance: 0,
value: escape(value)
};
} else {
throw e;
}
}
}
/*
Highlighting with language detection. Accepts a string with the code to
highlight. Returns an object with the following properties:
- language (detected language)
- relevance (int)
- value (an HTML string with highlighting markup)
- second_best (object with the same structure for second-best heuristically
detected language, may be absent)
*/
function highlightAuto(text, languageSubset) {
languageSubset = languageSubset || options.languages || Object.keys(languages);
var result = {
relevance: 0,
value: escape(text)
};
var second_best = result;
languageSubset.forEach(function(name) {
if (!getLanguage(name)) {
return;
}
var current = highlight(name, text, false);
current.language = name;
if (current.relevance > second_best.relevance) {
second_best = current;
}
if (current.relevance > result.relevance) {
second_best = result;
result = current;
}
});
if (second_best.language) {
result.second_best = second_best;
}
return result;
}
/*
Post-processing of the highlighted markup:
- replace TABs with something more useful
- replace real line-breaks with '<br>' for non-pre containers
*/
function fixMarkup(value) {
if (options.tabReplace) {
value = value.replace(/^((<[^>]+>|\t)+)/gm, function(match, p1, offset, s) {
return p1.replace(/\t/g, options.tabReplace);
});
}
if (options.useBR) {
value = value.replace(/\n/g, '<br>');
}
return value;
}
/*
Applies highlighting to a DOM node containing code. Accepts a DOM node and
two optional parameters for fixMarkup.
*/
function highlightBlock(block) {
var language = blockLanguage(block);
if (/no(-?)highlight/.test(language))
return;
var node;
if (options.useBR) {
node = document.createElementNS('http://www.w3.org/1999/xhtml', 'div');
node.innerHTML = block.innerHTML.replace(/\n/g, '').replace(/<br[ \/]*>/g, '\n');
} else {
node = block;
}
var text = node.textContent;
var result = language ? highlight(language, text, true) : highlightAuto(text);
var originalStream = nodeStream(node);
if (originalStream.length) {
var resultNode = document.createElementNS('http://www.w3.org/1999/xhtml', 'div');
resultNode.innerHTML = result.value;
result.value = mergeStreams(originalStream, nodeStream(resultNode), text);
}
result.value = fixMarkup(result.value);
block.innerHTML = result.value;
block.className += ' hljs ' + (!language && result.language || '');
block.result = {
language: result.language,
re: result.relevance
};
if (result.second_best) {
block.second_best = {
language: result.second_best.language,
re: result.second_best.relevance
};
}
}
var options = {
classPrefix: 'hljs-',
tabReplace: null,
useBR: false,
languages: undefined
};
/*
Updates highlight.js global options with values passed in the form of an object
*/
function configure(user_options) {
options = inherit(options, user_options);
}
/*
Applies highlighting to all <pre><code>..</code></pre> blocks on a page.
*/
function initHighlighting() {
if (initHighlighting.called)
return;
initHighlighting.called = true;
var blocks = document.querySelectorAll('pre code');
Array.prototype.forEach.call(blocks, highlightBlock);
}
/*
Attaches highlighting to the page load event.
*/
function initHighlightingOnLoad() {
addEventListener('DOMContentLoaded', initHighlighting, false);
addEventListener('load', initHighlighting, false);
}
var languages = {};
var aliases = {};
function registerLanguage(name, language) {
var lang = languages[name] = language(this);
if (lang.aliases) {
lang.aliases.forEach(function(alias) {aliases[alias] = name;});
}
}
function listLanguages() {
return Object.keys(languages);
}
function getLanguage(name) {
return languages[name] || languages[aliases[name]];
}
/* Interface definition */
this.highlight = highlight;
this.highlightAuto = highlightAuto;
this.fixMarkup = fixMarkup;
this.highlightBlock = highlightBlock;
this.configure = configure;
this.initHighlighting = initHighlighting;
this.initHighlightingOnLoad = initHighlightingOnLoad;
this.registerLanguage = registerLanguage;
this.listLanguages = listLanguages;
this.getLanguage = getLanguage;
this.inherit = inherit;
// Common regexps
this.IDENT_RE = '[a-zA-Z][a-zA-Z0-9_]*';
this.UNDERSCORE_IDENT_RE = '[a-zA-Z_][a-zA-Z0-9_]*';
this.NUMBER_RE = '\\b\\d+(\\.\\d+)?';
this.C_NUMBER_RE = '(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)'; // 0x..., 0..., decimal, float
this.BINARY_NUMBER_RE = '\\b(0b[01]+)'; // 0b...
this.RE_STARTERS_RE = '!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~';
// Common modes
this.BACKSLASH_ESCAPE = {
begin: '\\\\[\\s\\S]', relevance: 0
};
this.APOS_STRING_MODE = {
className: 'string',
begin: '\'', end: '\'',
illegal: '\\n',
contains: [this.BACKSLASH_ESCAPE]
};
this.QUOTE_STRING_MODE = {
className: 'string',
begin: '"', end: '"',
illegal: '\\n',
contains: [this.BACKSLASH_ESCAPE]
};
this.PHRASAL_WORDS_MODE = {
begin: /\b(a|an|the|are|I|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such)\b/
};
this.C_LINE_COMMENT_MODE = {
className: 'comment',
begin: '//', end: '$',
contains: [this.PHRASAL_WORDS_MODE]
};
this.C_BLOCK_COMMENT_MODE = {
className: 'comment',
begin: '/\\*', end: '\\*/',
contains: [this.PHRASAL_WORDS_MODE]
};
this.HASH_COMMENT_MODE = {
className: 'comment',
begin: '#', end: '$',
contains: [this.PHRASAL_WORDS_MODE]
};
this.NUMBER_MODE = {
className: 'number',
begin: this.NUMBER_RE,
relevance: 0
};
this.C_NUMBER_MODE = {
className: 'number',
begin: this.C_NUMBER_RE,
relevance: 0
};
this.BINARY_NUMBER_MODE = {
className: 'number',
begin: this.BINARY_NUMBER_RE,
relevance: 0
};
this.CSS_NUMBER_MODE = {
className: 'number',
begin: this.NUMBER_RE + '(' +
'%|em|ex|ch|rem' +
'|vw|vh|vmin|vmax' +
'|cm|mm|in|pt|pc|px' +
'|deg|grad|rad|turn' +
'|s|ms' +
'|Hz|kHz' +
'|dpi|dpcm|dppx' +
')?',
relevance: 0
};
this.REGEXP_MODE = {
className: 'regexp',
begin: /\//, end: /\/[gim]*/,
illegal: /\n/,
contains: [
this.BACKSLASH_ESCAPE,
{
begin: /\[/, end: /\]/,
relevance: 0,
contains: [this.BACKSLASH_ESCAPE]
}
]
};
this.TITLE_MODE = {
className: 'title',
begin: this.IDENT_RE,
relevance: 0
};
this.UNDERSCORE_TITLE_MODE = {
className: 'title',
begin: this.UNDERSCORE_IDENT_RE,
relevance: 0
};
};
module.exports = Highlight; | gitterHQ/highlight.js | build/lib/highlight.js | JavaScript | bsd-3-clause | 20,434 |
import React from "react";
import { View } from "react-native";
import styles from "./styles";
import { ListItemSeparator } from "./styles/responsive";
const ArticleListItemSeparator = () => (
<ListItemSeparator>
<View style={styles.listItemSeparator} />
</ListItemSeparator>
);
export default ArticleListItemSeparator;
| newsuk/times-components | packages/article-list/src/article-list-item-separator.js | JavaScript | bsd-3-clause | 330 |
/* This is a generated file */
const React = require('React');
const JestIndex = require('JestIndex');
const index = React.createClass({
render() {
return <JestIndex language={
'en'} />;
},
});
module.exports = index;
| mpontus/jest | website/src/jest/en/index.js | JavaScript | bsd-3-clause | 226 |
import React from 'react';
import { Icon } from 'design-react-kit';
import { createUseStyles } from 'react-jss';
import { SearchProvider } from '../../contexts/searchContext.js';
import { ALL_SITE } from '../../utils/constants.js';
import { useModal } from '../../hooks/useModal.js';
import { l10NLabels } from '../../utils/l10n.js';
import { SearchModal } from './SearchModal.js';
const useStyles = createUseStyles({
icon: {
composes: 'd-none d-lg-inline',
backgroundColor: 'var(--white)',
borderRadius: '100%',
fill: 'var(--primary)',
height: '2.6rem',
padding: '0.8rem',
width: '2.6rem',
},
});
export const SearchContainer = () => {
const classes = useStyles();
const [isModalOpen, closeModal, openModal] = useModal();
return (
<>
<div onClick={openModal} className="d-flex align-items-center pr-2" role="button" data-testid="search-button">
<span className="text-white mr-3 d-none d-lg-inline">{l10NLabels.search_form_label}</span>
<Icon className={classes.icon} icon="it-search"></Icon>
<Icon className="d-inline d-lg-none" icon="it-search" color="white"></Icon>
</div>
{isModalOpen && (
<SearchProvider initialType={ALL_SITE}>
<SearchModal onClose={closeModal} />
</SearchProvider>
)}
</>
);
};
| italia/developers.italia.it | assets/js/components/Search/SearchContainer.js | JavaScript | bsd-3-clause | 1,327 |
Tinytest.add('peerdb - defined', function (test) {
var isDefined = false;
try {
Document;
isDefined = true;
}
catch (e) {
}
test.isTrue(isDefined, "Document is not defined");
test.isTrue(Package['peerlibrary:peerdb'].Document, "Package.peerlibrary:peerdb.Document is not defined");
});
| peerlibrary/meteor-peerdb | tests_defined.js | JavaScript | bsd-3-clause | 308 |
function redrawFromSelection(obj, url, current_selection) {
/* Create the selection */
var new_selection = {};
$.each(obj.exp_selection, function(ekey,evalue) {
$.each(evalue.exp_data, function(dkey,dvalue) {
if (dvalue.selected) {
new_selection[ekey + "-" + dkey] = true;
}
});
});
var load_selection = [];
$.each(new_selection, function(key,value) {
if (!(key in current_selection)) {
sel_key = key.split('-');
load_selection.push([
parseInt(sel_key[0], 10),
parseInt(sel_key[1], 10),
parseInt(sel_key[2], 10)
]);
}
/* Needed to update current_selection */
//current_selection[key] = value;
});
/* Maybe nothing was selected ?! */
if (Object.keys(new_selection).length === 0) {
obj.clearPlot();
return new_selection;
}
/* Nothing to reload, but we should trigger a redraw */
if (load_selection.length === 0) {
changeDisplay(obj, obj.getDBData());
return new_selection;
}
/* Trigger the AJAX request to receive the data */
overlayToggle(null, 'Data request pending.');
var xhr = $.ajax({
type: 'POST',
url: url,
dataType: 'json',
data: { sel: load_selection },
async: true,
success: obj.redrawFromSelectionCallback
});
return new_selection;
};
function createExpSelection(obj) {
obj.exp_selection = {}; // Re-Initialize experiments object
var exp = experiments;
var exp_selection = obj.exp_selection;
var exp_to_load = 0;
var exp_loaded = 0;
$.ajax({
type: 'GET',
url: '/get_experiments',
dataType: 'json',
data: { db: obj.db },
async: true,
success: function(data) {
exp_to_load = data.result.length;
$.each(data.result, function(index, value) {
var exp_id = value[0];
exp_selection[exp_id] = {
'exp_date': new Date(value[1] * 1000),
'exp_name': value[2],
'exp_start': value[3],
'exp_stop': value[4],
'exp_data': {}
};
// Call to get details of experiments
$.ajax({
type: 'GET',
url: '/get_experiment_overview',
dataType: 'json',
data: { id: exp_id },
async: true,
success: function(data) {
$.each(data.result, function(index, value) {
exp_selection[exp_id].exp_data[value[0] + '-' + value[2]] = {
'kname': value[1],
'dname': value[3],
'selected': false
};
});
exp_loaded++;
if (exp_loaded == exp_to_load) {
redraw(exp, exp_selection);
resizeDocument(e);
overlayToggle('hide');
}
}
});
});
}
});
};
| sdressler/elapsd | analyzer/static/js/ajax.js | JavaScript | bsd-3-clause | 3,418 |
const gulp = require('gulp'),
eslint = require('gulp-eslint'),
mocha = require('gulp-mocha');
const SOURCE = './src',
TEST_SOURCE = './test',
UNIT_TEST_SOURCE = './test/unit';
gulp.task('lint', function(){
return gulp
.src([SOURCE + '/*.js', SOURCE + '/**/*.js'])
.pipe(eslint())
.pipe(eslint.format());
});
gulp.task('lint-test', function(){
return gulp
.src([TEST_SOURCE + '/*.js', TEST_SOURCE + '/**/*.js'] )
.pipe(eslint())
.pipe(eslint.format());
});
/** run unit tests */
gulp.task('test', ['lint-test'], function(){
return gulp
.src([UNIT_TEST_SOURCE + '/*.js', UNIT_TEST_SOURCE + '/**/*.js'])
.pipe(mocha({reporter: 'spec'}));
});
| SquadInTouch/propz | gulpfile.js | JavaScript | bsd-3-clause | 786 |
/*jslint indent: 2 */
/*global $: false, document: false, togglbutton: false*/
'use strict';
togglbutton.render('section.task-actions:not(.toggl)', {observe: true}, function (elem) {
var link,
linkAction = document.createElement("LI"),
taskTitle = $("p.task-title"),
firstAction = $('.task-actions ul li:first-child', elem),
actionList = firstAction.parentNode;
link = togglbutton.createTimerLink({
className: 'kanbanery',
description: taskTitle.textContent
});
linkAction.appendChild(link);
actionList.insertBefore(linkAction, firstAction);
});
| eatskolnikov/toggl-button | src/scripts/content/kanbanery.js | JavaScript | bsd-3-clause | 585 |
๏ปฟ/**
* jQuery ligerUI 1.1.9
*
* http://ligerui.com
*
* Author daomi 2012 [ gd_star@163.com ]
*
*/
(function ($)
{
$.fn.ligerForm = function ()
{
return $.ligerui.run.call(this, "ligerForm", arguments);
};
$.ligerDefaults = $.ligerDefaults || {};
$.ligerDefaults.Form = {
//ๆงไปถๅฎฝๅบฆ
inputWidth: 180,
//ๆ ็ญพๅฎฝๅบฆ
labelWidth: 90,
//้ด้ๅฎฝๅบฆ
space: 40,
rightToken: '๏ผ',
//ๆ ็ญพๅฏน้ฝๆนๅผ
labelAlign: 'left',
//ๆงไปถๅฏน้ฝๆนๅผ
align: 'left',
//ๅญๆฎต
fields: [],
//ๅๅปบ็่กจๅๅ
็ด ๆฏๅฆ้ๅ ID
appendID: true,
//็ๆ่กจๅๅ
็ด ID็ๅ็ผ
prefixID: "",
//json่งฃๆๅฝๆฐ
toJSON: $.ligerui.toJSON
};
//@description ้ป่ฎค่กจๅ็ผ่พๅจๆ้ ๅจๆฉๅฑ(ๅฆๆๅๅปบ็่กจๅๆๆไธๆปกๆ ๅปบ่ฎฎ้่ฝฝ)
//@param {jinput} ่กจๅๅ
็ด jQueryๅฏน่ฑก ๆฏๅฆinputใselectใtextarea
$.ligerDefaults.Form.editorBulider = function (jinput)
{
//่ฟ้thisๅฐฑๆฏform็ligeruiๅฏน่ฑก
var g = this, p = this.options;
var inputOptions = {};
if (p.inputWidth) inputOptions.width = p.inputWidth;
if (jinput.is("select"))
{
jinput.ligerComboBox(inputOptions);
}
else if (jinput.is(":text") || jinput.is(":password"))
{
var ltype = jinput.attr("ltype");
switch (ltype)
{
case "select":
case "combobox":
jinput.ligerComboBox(inputOptions);
break;
case "spinner":
jinput.ligerSpinner(inputOptions);
break;
case "date":
jinput.ligerDateEditor(inputOptions);
break;
case "float":
case "number":
inputOptions.number = true;
jinput.ligerTextBox(inputOptions);
break;
case "int":
case "digits":
inputOptions.digits = true;
default:
jinput.ligerTextBox(inputOptions);
break;
}
}
else if (jinput.is(":radio"))
{
jinput.ligerRadio(inputOptions);
}
else if (jinput.is(":checkbox"))
{
jinput.ligerCheckBox(inputOptions);
}
else if (jinput.is("textarea"))
{
jinput.ligerTextarea(inputOptions);
//jinput.addClass("l-textarea");
}
}
//่กจๅ็ปไปถ
$.ligerui.controls.Form = function (element, options)
{
$.ligerui.controls.Form.base.constructor.call(this, element, options);
};
$.ligerui.controls.Form.ligerExtend($.ligerui.core.UIComponent, {
__getType: function ()
{
return 'Form'
},
__idPrev: function ()
{
return 'Form';
},
_init: function ()
{
$.ligerui.controls.Form.base._init.call(this);
},
_render: function ()
{
var g = this, p = this.options;
var jform = $(this.element);
//่ชๅจๅๅปบ่กจๅ
if (p.fields && p.fields.length)
{
if (!jform.hasClass("l-form"))
jform.addClass("l-form");
var out = [];
var appendULStartTag = false;
$(p.fields).each(function (index, field)
{
var name = field.name || field.id;
if (!name) return;
if (field.type == "hidden")
{
out.push('<input type="hidden" id="' + name + '" name="' + name + '" />');
return;
}
var newLine = field.renderToNewLine || field.newline;
if (newLine == null) newLine = true;
if (field.merge) newLine = false;
if (field.group) newLine = true;
if (newLine)
{
if (appendULStartTag)
{
out.push('</ul>');
appendULStartTag = false;
}
if (field.group)
{
out.push('<div class="l-group');
if (field.groupicon)
out.push(' l-group-hasicon');
out.push('">');
if (field.groupicon)
out.push('<img src="' + field.groupicon + '" />');
out.push('<span>' + field.group + '</span></div>');
}
out.push('<ul>');
appendULStartTag = true;
}
//append label
out.push(g._buliderLabelContainer(field));
//append input
out.push(g._buliderControlContainer(field));
//append space
out.push(g._buliderSpaceContainer(field));
});
if (appendULStartTag)
{
out.push('</ul>');
appendULStartTag = false;
}
jform.append(out.join(''));
}
//็ๆligerui่กจๅๆ ทๅผ
$("input,select,textarea", jform).each(function ()
{
p.editorBulider.call(g, $(this));
});
},
//ๆ ็ญพ้จๅ
_buliderLabelContainer: function (field)
{
var g = this, p = this.options;
var label = field.label || field.display;
var labelWidth = field.labelWidth || field.labelwidth || p.labelWidth;
var labelAlign = field.labelAlign || p.labelAlign;
if (label) label += p.rightToken;
var out = [];
out.push('<li style="');
if (labelWidth)
{
out.push('width:' + labelWidth + 'px;');
}
if (labelAlign)
{
out.push('text-align:' + labelAlign + ';');
}
out.push('">');
if (label)
{
out.push(label);
}
out.push('</li>');
return out.join('');
},
//ๆงไปถ้จๅ
_buliderControlContainer: function (field)
{
var g = this, p = this.options;
var width = field.width || p.inputWidth;
var align = field.align || field.textAlign || field.textalign || p.align;
var out = [];
out.push('<li style="');
if (width)
{
out.push('width:' + width + 'px;');
}
if (align)
{
out.push('text-align:' + align + ';');
}
out.push('">');
out.push(g._buliderControl(field));
out.push('</li>');
return out.join('');
},
//้ด้้จๅ
_buliderSpaceContainer: function (field)
{
var g = this, p = this.options;
var spaceWidth = field.space || field.spaceWidth || p.space;
var out = [];
out.push('<li style="');
if (spaceWidth)
{
out.push('width:' + spaceWidth + 'px;');
}
out.push('">');
out.push('</li>');
return out.join('');
},
_buliderControl: function (field)
{
var g = this, p = this.options;
var width = field.width || p.inputWidth;
var name = field.name || field.id;
var out = [];
if (field.comboboxName && field.type == "select")
{
out.push('<input type="hidden" id="' + p.prefixID + name + '" name="' + name + '" />');
}
if (field.textarea || field.type == "textarea")
{
out.push('<textarea ');
}
else if (field.type == "checkbox")
{
out.push('<input type="checkbox" ');
}
else if (field.type == "radio")
{
out.push('<input type="radio" ');
}
else if (field.type == "password")
{
out.push('<input type="password" ');
}
else if (field.type == "span")
{
out.push('<div style="border-bottom:2px solid;text-align:center;height:18px;" id="'+field.name+'" />');
return out;
}
else if (field.type == "spanarea")
{
out.push('<p><span style="border-bottom:2px solid;text-align:left;" id="'+field.name+'" /></p>');
return out;
}
else
{
out.push('<input type="text" ');
}
if (field.cssClass)
{
out.push('class="' + field.cssClass + '" ');
}
if (field.type)
{
out.push('ltype="' + field.type + '" ');
}
if (field.attr)
{
for (var attrp in field.attr)
{
out.push(attrp + '="' + field.attr[attrp] + '" ');
}
}
if (field.comboboxName && field.type == "select")
{
out.push('name="' + field.comboboxName + '"');
if (p.appendID)
{
out.push(' id="' + p.prefixID + field.comboboxName + '" ');
}
}
else
{
out.push('name="' + name + '"');
if (p.appendID)
{
out.push(' id="' + name + '" ');
}
}
//ๅๆฐ
var fieldOptions = $.extend({
width: width - 2
}, field.options || {});
out.push(" ligerui='" + p.toJSON(fieldOptions) + "' ");
//้ช่ฏๅๆฐ
if (field.validate)
{
out.push(" validate='" + p.toJSON(field.validate) + "' ");
}
out.push(' />');
return out.join('');
}
});
})(jQuery); | wei1224hf/wei1224hf-myapp | WebContent/libs/liger/plugins/ligerForm.js | JavaScript | bsd-3-clause | 10,745 |
/**
* Created by praba on 2/13/2016.
*/
//JS page for outwardslip page
Polymer({
is: "outwardslip-page",
ready:function()
{
//Showing customerinfo page as the initial page in outwardslip page
localStorage.setItem("curr_sess_saveflag","false");
if(sessionStorage.getItem("curr_sess_roleflag")=="0")
{
localStorage.setItem("curr_sess_showpage","Out Vehicle Info");
//document.querySelector("webcomponent-service").callWebcomponentService();
this.page="Out Vehicle Info";
}
},
setPage:function(page)
{
//Setting current page in local storage to fetch the labels dynamically
localStorage.setItem("curr_sess_showpage",page);
//Calling web component service to fetch label and errro label info from config file
document.querySelector("webcomponent-service").callWebcomponentService();
//Changing page view in Outwardslip page
this.page=page;
}
});
| ZenCodes/erpworkflow | app/scripts/outwardslip-page.js | JavaScript | bsd-3-clause | 921 |
var Lang = Y.Lang,
getCN = Y.ClassNameManager.getClassName,
//HTML5 Data Attributes
DATA_CONTENT = 'data-content',
DATA_PLACEMENT = 'data-placement',
//Classes
TIPSY = 'tipsy',
FADE = 'fade',
IN = 'in',
CLASSES = {
fade: getCN(TIPSY, FADE),
fadeIn: getCN(TIPSY, IN)
};
Y.Tipsy = Y.Base.create("tipsy", Y.Widget, [Y.WidgetPointer, Y.WidgetPosition, Y.WidgetPositionAlign, Y.WidgetStack], {
_handles : [],
_timer : null,
//constructor
initializer : function(config) {
},
//clean up on destruction
destructor : function() {
Y.each(this._handles, function(v, k, o) {
v.detach();
});
},
renderUI : function () {
this.get('boundingBox').addClass(CLASSES.fade).setAttribute('role', 'tooltip');
},
bindUI : function () {
var del = this.get('delegate'),
selector = this.get('selector'),
showOn = this.get('showOn');
//showOn = ['event1', 'event2']
if (Lang.isArray(showOn) || Lang.isString(showOn)) {
this._handles.push(del.delegate(showOn, this._handleDelegateStart, selector, this));
}
//showOn = { events: ['event1', 'event2'] }
else if (Lang.isObject(showOn) && !showOn.node) {
this._handles.push(del.delegate(showOn.events, this._handleDelegateStart, selector, this));
}
//showOn = { node: '#selector', events: ['event1', 'event2'] }
else if (Lang.isObject(showOn) && showOn.node && showOn.events) {
this._handles.push(Y.one(showOn.selector).on(showOn.events, this._handleDelegateStart, this));
}
else {
Y.log('The showOn attribute should contain an array of events, or an object with keys "selector" (string), and "events" (array of events)');
}
},
_handleDelegateStart : function (e) {
var del = this.get('delegate'),
delay = this.get('delay' ),
selector = this.get('selector'),
hideOn = this.get('hideOn'),
node = e.currentTarget;
if (Lang.isArray(hideOn) || Lang.isString(hideOn)) {
this._handles.push(del.delegate(hideOn, this._handleDelegateEnd, selector, this));
}
//hideOn = { events: ['event1', 'event2'] }
else if (Lang.isObject(hideOn) && !hideOn.selector) {
this._handles.push(del.delegate(hideOn.events, this._handleDelegateEnd, selector, this));
}
//hideOn = { node: '#selector', events: ['event1', 'event2'] }
else if (Lang.isObject(hideOn) && hideOn.selector && hideOn.events) {
this._handles.push(Y.one(hideOn.selector).on(hideOn.events, this._handleDelegateEnd, this));
}
else {
Y.log('The hideOn attribute should contain an array of events, or an object with keys "selector" (string), and "events" (array of events)');
}
if (delay) {
this._timer = Y.later(delay*1000, this, 'showTooltip', node);
} else {
this.showTooltip(node);
}
},
_handleDelegateEnd: function (e) {
this.hideTooltip();
if (this._timer) {
this._timer.cancel();
this._timer = null;
}
},
showTooltip : function (node) {
this._setTooltipContent(node);
this._alignTooltip(node);
this.alignPointer(node);
this._showTooltip();
this.get('boundingBox').addClass(CLASSES.fadeIn).setAttribute('aria-hidden', 'false');
node.setAttribute('aria-describedby', this.get('boundingBox').getAttribute('id'));
},
_showTooltip: function () {
this.set('visible', true);
},
hideTooltip : function () {
this.get('boundingBox').removeClass(CLASSES.fadeIn).setAttrs({
'aria-hidden': 'true',
//clear out all inline styles
'styles': ''
});
this._hideTooltip();
},
_hideTooltip: function () {
this.set('visible', false);
},
_setTooltipContent: function (node) {
var content = (node.hasAttribute(DATA_CONTENT)) ? node.getAttribute(DATA_CONTENT) : this.get('content'),
contentBox = this.get('contentBox');
contentBox.setHTML(content);
},
_alignTooltip : function (node) {
var placement = (node.hasAttribute(DATA_PLACEMENT)) ? node.getAttribute(DATA_PLACEMENT) : this.get('placement');
switch (placement) {
case "above":
this.align(node, ["bc", "tc"]);
break;
case "left":
this.align(node, ["rc", "lc"]);
break;
case "below":
this.align(node, ["tc", "bc"]);
break;
case "right":
this.align(node, ["lc", "rc"]);
break;
default:
break;
}
}
},
{
NS : "tipsy",
ATTRS : {
content : {
value : ''
},
selector: {
value: null
},
zIndex: {
value: 2
},
delay: {
value: 0
},
showOn: {
value: ['mouseover', 'touchstart', 'focus']
},
hideOn: {
value: ['mouseout', 'touchend', 'blur']
},
delegate: {
value: null,
setter: function(val) {
return Y.one(val) || Y.one("document");
}
}
}
});
| tilomitra/tipsy | js/gallery-tipsy.js | JavaScript | bsd-3-clause | 5,604 |
/*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @flow
*/
import parseJsDoc from '../utils/parseJsDoc';
import type Documentation from '../Documentation';
// Merges two objects ignoring null/undefined.
function merge(obj1, obj2) {
if (obj1 == null && obj2 == null) {
return null;
}
const merged = {...obj1};
for (const prop in obj2) {
if (obj2[prop] != null) {
merged[prop] = obj2[prop];
}
}
return merged;
}
/**
* Extract info from the methods jsdoc blocks. Must be run after
* flowComponentMethodsHandler.
*/
export default function componentMethodsJsDocHandler(
documentation: Documentation
) {
let methods = documentation.get('methods');
if (!methods) {
return;
}
methods = methods.map(method => {
if (!method.docblock) {
return method;
}
const jsDoc = parseJsDoc(method.docblock);
const returns = merge(jsDoc.returns, method.returns);
const params = method.params.map(param => {
const jsDocParam = jsDoc.params.find(p => p.name === param.name);
return merge(jsDocParam, param);
});
return {
...method,
description: jsDoc.description || null,
returns,
params,
};
});
documentation.set('methods', methods);
}
| janicduplessis/react-docgen | src/handlers/componentMethodsJsDocHandler.js | JavaScript | bsd-3-clause | 1,499 |
/**
* Regex patterns used through keigai
*
* `url` was authored by Diego Perini
*
* @namespace regex
* @private
* @type {Object}
*/
let regex = {
after_space: /\s+.*/,
allow: /^allow$/i,
allow_cors: /^access-control-allow-methods$/i,
and: /^&/,
args: /\((.*)\)/,
auth: /\/\/(.*)\@/,
bool: /^(true|false)?$/,
boolean_number_string: /boolean|number|string/,
caps: /[A-Z]/,
cdata: /\&|<|>|\"|\'|\t|\r|\n|\@|\$/,
checked_disabled: /checked|disabled/i,
complete_loaded: /^(complete|loaded)$/i,
csv_quote: /^\s|\"|\n|,|\s$/,
del: /^del/,
domain: /^[\w.-_]+\.[A-Za-z]{2,}$/,
down: /down/,
endslash: /\/$/,
eol_nl: /\n$/,
element_update: /id|innerHTML|innerText|textContent|type|src/,
get_headers: /^(head|get|options)$/,
get_remove_set: /get|remove|set/,
hash: /^\#/,
header_replace: /:.*/,
header_value_replace: /.*:\s+/,
html: /^<.*>$/,
http_body: /200|201|202|203|206/,
http_ports: /80|443/,
host: /\/\/(.*)\//,
ie: /msie|ie|\.net|windows\snt/i,
ip: /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/,
is_xml: /^<\?xml.*\?>/,
json_maybe: /json|plain|javascript/,
json_wrap: /^[\[\{]/,
klass: /^\./,
no: /no-store|no-cache/i,
not_dotnotation: /-|\s/,
not_endpoint: /.*\//,
null_undefined: /null|undefined/,
number: /(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)|number/,
number_format_1: /.*\./,
number_format_2: /\..*/,
number_present: /\d{1,}/,
number_string: /number|string/i,
number_string_object: /number|object|string/i,
object_type: /\[object Object\]/,
patch: /^patch$/,
primitive: /^(boolean|function|number|string)$/,
priv: /private/,
protocol: /^(.*)\/\//,
put_post: /^(post|put)$/i,
question: /(\?{1,})/,
radio_checkbox: /^(radio|checkbox)$/i,
root: /^\/[^\/]/,
select: /select/i,
selector_is: /^:/,
selector_complex: /\s+|\>|\+|\~|\:|\[/,
set_del: /^(set|del|delete)$/,
space_hyphen: /\s|-/,
string_object: /string|object/i,
svg: /svg/,
top_bottom: /top|bottom/i,
trick: /(\%3F{1,})/,
url: /^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/i,
word: /^\w+$/,
xdomainrequest: /^(get|post)$/i,
xml: /xml/i
};
| avoidwork/keigai | src/regex.js | JavaScript | bsd-3-clause | 2,560 |
/* medea.js - Open Source, High-Performance 3D Engine based on WebGL.
*
* (c) 2011-2013, Alexander C. Gessler
* https://github.com/acgessler/medea.js
*
* Made available under the terms and conditions of a 3-clause BSD license.
*
*/
medealib.define('light', ['entity', 'renderer'],function(medealib, undefined) {
"use strict";
var medea = this, gl = medea.gl;
// class LightJob
medea.LightJob = medea.RenderJob.extend({
distance : null,
light : null,
init : function(light, node, camera) {
this._super(light, node, camera);
this.light = light;
},
Draw : function(renderer, statepool) {
renderer.DrawLight(this, statepool);
},
});
// class Light
this.Light = medea.Entity.extend(
{
cast_shadows : false,
shadowmap_res_bias : 0,
rq_idx : -1,
init : function(color, rq) {
this.color = color || [1,1,1];
this.rq_idx = rq === undefined ? medea.RENDERQUEUE_LIGHT : rq;
},
Render : function(camera, node, rqmanager) {
// Construct a renderable capable of drawing this light later
rqmanager.Push(this.rq_idx, new medea.LightJob(this, node, camera));
},
CastShadows : medealib.Property('cast_shadows'),
ShadowMapResolutionBias : medealib.Property('shadowmap_res_bias'),
});
// class DirectionalLight
this.DirectionalLight = medea.Light.extend(
{
dir : null,
init : function(color, dir) {
this._super(color);
this.dir = vec3.create(dir || [0,-1,0]);
vec3.normalize(this.dir);
},
Direction : function(dir) {
if (dir === undefined) {
return this.dir;
}
this.dir = vec3.create(dir);
vec3.normalize(this.dir);
},
});
medea.CreateDirectionalLight = function(color, dir) {
return new medea.DirectionalLight(color, dir);
};
}); | acgessler/medea.js | medea/medea.light.js | JavaScript | bsd-3-clause | 1,748 |
module.exports = {
clientCheckin: function(req, res, sockets) {
console.log("clientnameee:", req.body);
req.body.alert.expiresAt = new Date(new Date().getTime() + 10000); //FIVE SECS DURATION HARD CODED! NOT COOL!!
sockets.emit("client-checkin", req.body.alert);
res.end();
},
clearAlerts: function(req, res, sockets) {
sockets.emit("alert-deleted");
res.end("clear alerts!");
}
};
| vitorismart/ChromeCast | target/server/controllers/ChromecastMessagingController.js | JavaScript | bsd-3-clause | 448 |
import React, {Component} from 'react';
import {connect} from 'react-redux';
import Button from "../../../../../components/buttons/button";
import {Link} from "react-router-dom";
import {firebaseResetPasswordRequest} from "../../../../../redux/firebase/actions/reset-password.action";
class ResetPasswordForm extends Component{
componentDidMount(){
document.title = "Restore Password";
}
handleResetPassword = (e) =>{
e.preventDefault();
const {resetPassword, resetPass_email} = this.props;
resetPassword(resetPass_email);
};
render() {
const {handleInputChange, resetPass_email} = this.props;
return (
<form action="">
<div className="input-wrapper">
<label htmlFor="resetPass_email">E-mail:</label>
<input id="resetPass_email"
type="text"
onChange={handleInputChange}
value={resetPass_email}/>
</div>
<div className="button-wrapper">
<Button text="Reset password"
handleClick={(e) => this.handleResetPassword(e, resetPass_email)}
requiresAuth={false}
type="submit--light"/>
<Link to="/sign-in">Cancel</Link>
</div>
</form>
)
}
}
const mapStateToProps = state => {
const {resetPass_email} = state.entry;
return {resetPass_email};
};
const mapDispatchToProps = dispatch => {
return {
resetPassword: payload => dispatch(firebaseResetPasswordRequest(payload))
}
};
export default connect(mapStateToProps, mapDispatchToProps)(ResetPasswordForm); | vFujin/HearthLounge | src/containers/pages/entry/right-container/sign-in/reset-password-form.js | JavaScript | bsd-3-clause | 1,592 |
๏ปฟfunction ReportRowProvider()
{
var that = this;
var mXHR = new XHR();
var mFetchListeners = [];
var mReportId = "";
var mCriteriaText = "";
this.addFetchListener = function(address) { mFetchListeners.push(address); };
this.getReportId = function() { return mReportId; };
this.setReportId = function(value) { mReportId = value; };
this.getCriteriaText = function() { return mCriteriaText; };
this.setCriteriaText = function(value) { mCriteriaText = value; };
function getAddress()
{
var timeNow = new Date();
var result = "ReportRows.json?rep=" + mReportId; // time parameter no longer required, server now sends cache-control header
if(mCriteriaText !== null && mCriteriaText.length > 0) result += mCriteriaText;
return result;
};
this.startFetchingRows = function()
{
mXHR.beginSend("get", getAddress(), null, null, 60000, fetchHandler);
};
function fetchHandler(status, responseText)
{
var response = null;
if (status !== 200) response = { errorText: "ADS-B Radar Server ่ฟๅ็ถๆ " + status };
else {
responseText = replaceDateConstructors(responseText);
response = eval('(' + responseText + ')');
}
for(var i = 0;i < mFetchListeners.length;++i) mFetchListeners[i](response);
};
} | VincentFortuneDeng/VirtualRadarSource2.0.2 | VirtualRadar.WebSite/Site/Reports/ReportRowProvider.js | JavaScript | bsd-3-clause | 1,374 |
/**
* Objects implementing the NamedNodeMap interface are used to represent collections of nodes that can be accessed by name. Note that NamedNodeMap does not inherit from NodeList; NamedNodeMaps are not maintained in any particular order. Objects contained in an object implementing NamedNodeMap may also be accessed by an ordinal index, but this is simply to allow convenient enumeration of the contents of a NamedNodeMap, and does not imply that the DOM specifies an order to these Nodes.
* NamedNodeMap objects in the DOM are live.
* used for attributes or DocumentType entities
*
* @class tesla.xml.NamedNodeMap
* @extends tesla.xml.NodeList
* @createTime 2012-01-18
* @author louis.tru <louis.tru@gmail.com>
* @copyright (C) 2011 louis.tru, http://mooogame.com
* Released under MIT license, http://license.mooogame.com
* @version 1.0
*/
include('tesla/xml/DOMException.js');
var DOMException = tesla.xml.DOMException;
var NodeList = tesla.xml.NodeList;
function findNodeIndex(_this, node) {
var i = _this.length;
while (i--) {
if (_this[i] == node) { return i }
}
}
function add(_this, node, old) {
if (old) {
_this[findNodeIndex(_this, old)] = node;
} else {
_this[_this.length++] = node;
}
var el = _this._ownerElement;
var doc = el && el.ownerDocument;
if (doc)
node.ownerElement = el;
return old || null;
}
Class('tesla.xml.NamedNodeMap', NodeList, {
getNamedItem: function(key) {
var i = this.length;
while (i--) {
var node = this[i];
if (node.nodeName == key)
return node;
}
},
setNamedItem: function(node) {
var old = this.getNamedItem(node.nodeName);
return add(this, node, old);
},
/* returns Node */
setNamedItemNS: function(node) {// raises: WRONG_DOCUMENT_ERR,NO_MODIFICATION_ALLOWED_ERR,INUSE_ATTRIBUTE_ERR
var old = this.getNamedItemNS(node.namespaceURI, node.localName);
return add(_this, node, old);
},
_removeItem: function(node) {
var i = this.length;
var lastIndex = i - 1;
while (i--) {
var c = this[i];
if (node === c) {
var old = c;
while (i < lastIndex) {
this[i] = this[++i]
}
this.length = lastIndex;
node.ownerElement = null;
var el = this._ownerElement;
var doc = el && el.ownerDocument;
return old;
}
}
},
/* returns Node */
removeNamedItem: function(key) {
var node = this.getNamedItem(key);
if (node) {
this._removeItem(node);
} else {
throw DOMException(DOMException.NOT_FOUND_ERR, new Error())
}
}, // raises: NOT_FOUND_ERR,NO_MODIFICATION_ALLOWED_ERR
//for level2
getNamedItemNS: function(namespaceURI, localName) {
var i = this.length;
while (i--) {
var node = this[i];
if (node.localName == localName && node.namespaceURI == namespaceURI) {
return node;
}
}
return null;
},
removeNamedItemNS: function(namespaceURI, localName) {
var node = this.getNamedItemNS(namespaceURI, localName);
if (node) {
this._removeItem(node);
} else {
throw DOMException(DOMException.NOT_FOUND_ERR, new Error())
}
}
});
| louis-tru/touch_code | server/tesla/xml/NamedNodeMap.js | JavaScript | bsd-3-clause | 3,030 |
"use strict";
var mapnik = require('../');
var assert = require('assert');
var path = require('path');
mapnik.register_datasource(path.join(mapnik.settings.paths.input_plugins,'geojson.input'));
mapnik.register_datasource(path.join(mapnik.settings.paths.input_plugins,'ogr.input'));
mapnik.register_datasource(path.join(mapnik.settings.paths.input_plugins,'shape.input'));
mapnik.register_datasource(path.join(mapnik.settings.paths.input_plugins,'gdal.input'));
describe('mapnik.Datasource', function() {
it('should throw with invalid usage', function() {
assert.throws(function() { mapnik.Datasource('foo'); });
assert.throws(function() { mapnik.Datasource({ 'foo': 1 }); });
assert.throws(function() { mapnik.Datasource({ 'type': 'foo' }); });
assert.throws(function() { mapnik.Datasource({ 'type': 'shape' }); });
assert.throws(function() { new mapnik.Datasource('foo'); },
/Must provide an object, eg \{type: 'shape', file : 'world.shp'\}/);
assert.throws(function() { new mapnik.Datasource(); });
assert.throws(function() { new mapnik.Datasource({ 'foo': 1 }); });
assert.throws(function() { new mapnik.Datasource({ 'type': 'foo' }); });
assert.throws(function() { new mapnik.Datasource({ 'type': 'shape' }); },
/Shape Plugin: missing <file> parameter/);
});
it('should validate with known shapefile - ogr', function() {
var options = {
type: 'ogr',
file: './test/data/world_merc.shp',
layer: 'world_merc'
};
var ds = new mapnik.Datasource(options);
assert.ok(ds);
assert.deepEqual(ds.parameters(), options);
var features = [];
var featureset = ds.featureset();
var feature;
while ((feature = featureset.next())) {
features.push(feature);
}
assert.equal(features.length, 245);
assert.deepEqual(features[244].attributes(), {
AREA: 1638094,
FIPS: 'RS',
ISO2: 'RU',
ISO3: 'RUS',
LAT: 61.988,
LON: 96.689,
NAME: 'Russia',
POP2005: 143953092,
REGION: 150,
SUBREGION: 151,
UN: 643
});
var expected = {
type: 'vector',
extent: [
-20037508.342789248,
-8283343.693882697,
20037508.342789244,
18365151.363070473
],
encoding: 'utf-8',
fields: {
FIPS: 'String',
ISO2: 'String',
ISO3: 'String',
UN: 'Number',
NAME: 'String',
AREA: 'Number',
POP2005: 'Number',
REGION: 'Number',
SUBREGION: 'Number',
LON: 'Number',
LAT: 'Number'
},
geometry_type: 'polygon',
proj4:'+proj=merc +lon_0=0 +lat_ts=0 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs'
};
var actual = ds.describe();
assert.equal(actual.proj4, expected.proj4);
assert.deepEqual(actual.type, expected.type);
assert.deepEqual(actual.encoding, expected.encoding);
assert.deepEqual(actual.fields, expected.fields);
assert.deepEqual(actual.geometry_type, expected.geometry_type);
assert.deepEqual(ds.extent(), expected.extent);
assert.deepEqual(ds.fields(), expected.fields);
});
it('should validate with known shapefile', function() {
var options = {
type: 'shape',
file: './test/data/world_merc.shp'
};
var ds = new mapnik.Datasource(options);
assert.ok(ds);
assert.deepEqual(ds.parameters(), options);
var features = [];
var featureset = ds.featureset();
var feature;
while ((feature = featureset.next())) {
features.push(feature);
}
assert.equal(features.length, 245);
assert.deepEqual(features[244].attributes(), {
AREA: 1638094,
FIPS: 'RS',
ISO2: 'RU',
ISO3: 'RUS',
LAT: 61.988,
LON: 96.689,
NAME: 'Russia',
POP2005: 143953092,
REGION: 150,
SUBREGION: 151,
UN: 643
});
var expected = {
type: 'vector',
extent: [
-20037508.342789248,
-8283343.693882697,
20037508.342789244,
18365151.363070473
],
encoding: 'utf-8',
fields: {
FIPS: 'String',
ISO2: 'String',
ISO3: 'String',
UN: 'Number',
NAME: 'String',
AREA: 'Number',
POP2005: 'Number',
REGION: 'Number',
SUBREGION: 'Number',
LON: 'Number',
LAT: 'Number'
},
geometry_type: 'polygon'
};
var actual = ds.describe();
assert.deepEqual(actual.type, expected.type);
assert.deepEqual(actual.encoding, expected.encoding);
assert.deepEqual(actual.fields, expected.fields);
assert.deepEqual(actual.geometry_type, expected.geometry_type);
assert.deepEqual(ds.extent(), expected.extent);
assert.deepEqual(ds.fields(), expected.fields);
});
it('test invalid use of memory datasource', function() {
var ds = new mapnik.MemoryDatasource({'extent': '-180,-90,180,90'});
assert.throws(function() { ds.add(); });
assert.throws(function() { ds.add(null); });
assert.throws(function() { ds.add({}, null); });
assert.throws(function() { ds.add({'wkt': '1234'}); });
assert.equal(false, ds.add({}));
});
it('test empty memory datasource', function() {
var ds = new mapnik.MemoryDatasource({'extent': '-180,-90,180,90'});
var empty_fs = ds.featureset();
assert.equal(typeof(empty_fs),'undefined');
assert.equal(empty_fs, null);
});
it('test empty geojson datasource', function() {
var input = {
"type": "Feature",
"properties": {
"something": []
},
"geometry": {
"type": "Point",
"coordinates": [ 1, 1 ]
}
};
var ds = new mapnik.Datasource({ type:'geojson', inline: JSON.stringify(input) });
var fs = ds.featureset()
var feat = fs.next();
var feature = JSON.parse(feat.toJSON());
// pass invalid extent to filter all features out
// resulting in empty featureset that should be returned
// as a null object
var empty_fs = ds.featureset({extent:[-1,-1,0,0]});
assert.equal(typeof(empty_fs),'undefined');
assert.equal(empty_fs, null);
});
it('test empty geojson datasource due to invalid json string', function() {
var input = "{ \"type\": \"FeatureCollection\", \"features\": [{ \"oofda\" } ] }";
// from string will fail to parse
assert.throws(function() { new mapnik.Datasource({ type:'geojson', inline: inline, cache_features: false }); });
assert.throws(function() { new mapnik.Datasource({ type:'geojson', inline: fs.readFileSync('./test/data/parse.error.json').toString(), cache_features: false }); });
});
it('test empty geojson datasource due to invalid json file', function() {
assert.throws(function() { new mapnik.Datasource({ type:'geojson', file: './test/data/parse.error.json', cache_features: true }); });
});
it('test valid use of memory datasource', function() {
var ds = new mapnik.MemoryDatasource({'extent': '-180,-90,180,90'});
assert.equal(true, ds.add({ 'x': 0, 'y': 0 }));
assert.equal(true, ds.add({ 'x': 0.23432, 'y': 0.234234 }));
assert.equal(true, ds.add({ 'x': 1, 'y': 1 , 'properties': {'a':'b', 'c':1, 'd':0.23 }}));
var expected_describe = {
type: 'vector',
encoding: 'utf-8',
fields: {},
geometry_type: 'collection'
};
assert.deepEqual(expected_describe, ds.describe());
// Currently descriptors can not be added to memory datasource so will always be empty object
assert.deepEqual({},ds.fields());
});
it('should validate with raster', function() {
var options = {
type: 'gdal',
file: './test/data/images/sat_image.tif'
};
var ds = new mapnik.Datasource(options);
assert.ok(ds);
assert.deepEqual(ds.parameters(), options);
var describe = ds.describe();
var expected = { type: 'raster',
encoding: 'utf-8',
fields: { nodata: 'Number' },
geometry_type: 'raster'
};
assert.deepEqual(expected,describe);
// Test that if added to layer, can get datasource back
var layer = new mapnik.Layer('foo', '+init=epsg:4326');
layer.datasource = ds;
var ds2 = layer.datasource;
assert.ok(ds2);
assert.deepEqual(ds2.parameters(), options);
});
});
| CartoDB/node-mapnik | test/datasource.test.js | JavaScript | bsd-3-clause | 9,384 |