text
stringlengths 2
6.14k
|
|---|
/**
* @license
* Copyright 2016 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the license.
*/
'use strict';
const amphtmlValidator = require('amphtml-validator');
const colors = require('ansi-colors');
const log = require('fancy-log');
const through = require('through2');
const PLUGIN_NAME = 'gulp-amphtml-validator';
const PluginError = require('plugin-error');
const STATUS_FAIL = 'FAIL';
const STATUS_PASS = 'PASS';
const STATUS_UNKNOWN = 'UNKNOWN';
/**
* Validates AMP files and attaches the validation result to the file object.
*
* @param {?Object} validator - amphtml validator
* @return {!stream} gulp file stream
*/
module.exports.validate = function(validator) {
if (!validator) {
validator = amphtmlValidator;
}
function runValidation(file, encoding, callback) {
if (file.isNull()) {
return callback(null, file);
}
if (file.isStream()) {
this.emit('error', new PluginError(PLUGIN_NAME,
'Streams not supported!'));
}
if (file.isBuffer()) {
validator.getInstance()
.then(function(validatorInstance) {
const inputString = file.contents.toString();
file.ampValidationResult =
validatorInstance.validateString(inputString);
return callback(null, file);
})
.catch(function(err) {
// This happens if the validator download failed. We don't fail the
// build, but map the exception to an validation error instead. This
// makes it possible to configure via failAfterError whether this
// should fail the build or not.
log(colors.red(err.message));
file.ampValidationResult = {
status: STATUS_UNKNOWN,
};
return callback(null, file);
});
}
}
return through.obj(runValidation);
};
/**
* Formats and prints the validation results to the console.
*
* @param {?Object} logger - logger used for printing the results (optional)
* @return {!stream} gulp file stream
*/
module.exports.format = function(logger) {
const results = [];
if (!logger) {
logger = log;
}
function collectResults(file, encoding, callback) {
if (!file.isNull() && file.ampValidationResult) {
results.push(file);
}
return callback(null, file);
}
function formatResults(callback) {
logger.log('AMP Validation results:\n\n' +
results.map(printResult).join('\n'));
return callback();
}
function printResult(file) {
const validationResult = file.ampValidationResult;
let report = file.relative + ': ';
if (validationResult.status === STATUS_PASS) {
report += colors.green(validationResult.status);
report += '\nReview our \'publishing checklist\' to ensure '
+ 'successful AMP document distribution. '
+ 'See https://bit.ly/2D54tM9';
} else if (validationResult.status === STATUS_UNKNOWN) {
report += colors.red(validationResult.status);
} else {
report += colors.red(validationResult.status);
for (let ii = 0; ii < validationResult.errors.length; ii++) {
const error = validationResult.errors[ii];
let msg = file.relative + ':' + error.line + ':' + error.col + ' ' +
colors.red(error.message);
if (error.specUrl) {
msg += ' (see ' + error.specUrl + ')';
}
report += '\n' + msg;
}
}
return report;
}
return through.obj(collectResults, formatResults);
};
/**
* Fail when the stream ends if for any AMP validation results,
* isFailure(ampValidationResult) returns true.
*
* @param {function(amphtmlValidator.ValidationResult): boolean} isFailure
* @return {!stream} gulp file stream
*/
function failAfter(isFailure) {
let failedFiles = 0;
function collectFailedFiles(file, encoding, callback) {
if (file.isNull() || !file.ampValidationResult) {
return callback(null, file);
}
if (isFailure(file.ampValidationResult)) {
failedFiles++;
}
return callback(null, file);
}
function failOnError(callback) {
if (failedFiles > 0) {
this.emit('error', new PluginError(PLUGIN_NAME,
'\nAMPHTML Validation failed for ' + failedFiles + ' files.'));
}
callback();
}
return through.obj(collectFailedFiles, failOnError);
}
/**
* Fail when the stream ends if any AMP validation error(s) occurred.
*
* @return {!stream} gulp file stream
*/
module.exports.failAfterError = function() {
return failAfter(function(ampValidationResult) {
return ampValidationResult.status === STATUS_FAIL ||
ampValidationResult.status === STATUS_UNKNOWN;
});
};
/**
* Fail when the stream ends if any AMP validation warning(s) or
* error(s) occurred.
*
* @return {!stream} gulp file stream
*/
module.exports.failAfterWarningOrError = function() {
return failAfter(function(ampValidationResult) {
return ampValidationResult.errors.length > 0 ||
ampValidationResult.status === STATUS_FAIL ||
ampValidationResult.status === STATUS_UNKNOWN;
});
};
|
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"\u4e0a\u5348",
"\u4e0b\u5348"
],
"DAY": [
"\u661f\u671f\u65e5",
"\u661f\u671f\u4e00",
"\u661f\u671f\u4e8c",
"\u661f\u671f\u4e09",
"\u661f\u671f\u56db",
"\u661f\u671f\u4e94",
"\u661f\u671f\u516d"
],
"ERANAMES": [
"\u897f\u5143\u524d",
"\u897f\u5143"
],
"ERAS": [
"\u897f\u5143\u524d",
"\u897f\u5143"
],
"FIRSTDAYOFWEEK": 6,
"MONTH": [
"1\u6708",
"2\u6708",
"3\u6708",
"4\u6708",
"5\u6708",
"6\u6708",
"7\u6708",
"8\u6708",
"9\u6708",
"10\u6708",
"11\u6708",
"12\u6708"
],
"SHORTDAY": [
"\u9031\u65e5",
"\u9031\u4e00",
"\u9031\u4e8c",
"\u9031\u4e09",
"\u9031\u56db",
"\u9031\u4e94",
"\u9031\u516d"
],
"SHORTMONTH": [
"1\u6708",
"2\u6708",
"3\u6708",
"4\u6708",
"5\u6708",
"6\u6708",
"7\u6708",
"8\u6708",
"9\u6708",
"10\u6708",
"11\u6708",
"12\u6708"
],
"STANDALONEMONTH": [
"1\u6708",
"2\u6708",
"3\u6708",
"4\u6708",
"5\u6708",
"6\u6708",
"7\u6708",
"8\u6708",
"9\u6708",
"10\u6708",
"11\u6708",
"12\u6708"
],
"WEEKENDRANGE": [
5,
6
],
"fullDate": "y\u5e74M\u6708d\u65e5 EEEE",
"longDate": "y\u5e74M\u6708d\u65e5",
"medium": "y\u5e74M\u6708d\u65e5 ah:mm:ss",
"mediumDate": "y\u5e74M\u6708d\u65e5",
"mediumTime": "ah:mm:ss",
"short": "y/M/d ah:mm",
"shortDate": "y/M/d",
"shortTime": "ah:mm"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "NT$",
"DECIMAL_SEP": ".",
"GROUP_SEP": ",",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "-\u00a4",
"negSuf": "",
"posPre": "\u00a4",
"posSuf": ""
}
]
},
"id": "zh-tw",
"localeID": "zh_TW",
"pluralCat": function(n, opt_precision) { return PLURAL_CATEGORY.OTHER;}
});
}]);
|
/* global angular, document, window */
'use strict';
var URL = "http://192.168.112.97:3000";
var DRIVER_REG_NO = "565ae51db039c3b227b2cf35";
angular.module('bluecross.controllers', ['ngCordova.plugins.localStorage'])
.controller('utils', function($scope, $location, $ionicHistory){
$scope.go = function ( path ) {
if( path == 'back') {
$ionicHistory.goBack();
}
else {
$location.path( path );
}
};
})
.controller('homeController', function($scope, $state, $ionicPopup, $http, $cordovaLocalStorage) {
$scope.isRideAssigned = false;
$scope.URL = URL;
$scope.ambulanceData = {};
$scope.destinationAddress = "";
function loadMaps() {
var myCenter=new google.maps.LatLng($scope.ambulanceData.assignedToOrdinate.lat, $scope.ambulanceData.assignedToOrdinate.lon);
function initialize()
{
console.log(myCenter)
var mapProp = {
center:myCenter,
zoom:13,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("googleMaps"),mapProp);
var marker = new google.maps.Marker({
position:myCenter
});
marker.setMap(map);
var infowindow = new google.maps.InfoWindow({
content: $scope.destinationAddress
});
infowindow.open(map,marker);
}
setTimeout(function () {
initialize();
},2000)
}
function loadAddress () {
console.log("LOADING ADDRESS")
$http({
method: 'GET',
url: "http://maps.googleapis.com/maps/api/geocode/json?latlng="+$scope.ambulanceData.assignedToOrdinate.lat+","+$scope.ambulanceData.assignedToOrdinate.lon+"&sensor=true"
})
.then(function(res) {
$scope.destinationAddress = res.data.results[0].formatted_address;
})
}
function getAmbulanceInfo() {
if(! $scope.isRideAssigned) {
$http({
method: 'GET',
url: URL + '/ambulance/getAmbulance',
params: {
_id: DRIVER_REG_NO
}
})
.then(function(res){
$scope.ambulanceData = res.data;
if( $scope.ambulanceData.assignedTo ) {
console.log("RETRIEVING ADDRESS")
$scope.destinationAddress = "RETRIEVING ADDRESS..";
$scope.isRideAssigned = true;
loadMaps();
loadAddress();
}
})
}
}
setInterval(getAmbulanceInfo,1000);
})
|
$( document ).ready(function() {
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');
function onOff(element, state){
$("#" + element).attr("disabled", state);
}
function onOffGroup(elementArray, itemsObject, state){
for(var i=0; i<elementArray.length; i++){
onOff(itemsObject[elementArray[i]], state);
}
}
function onOffStatus(status){
try{
onOffGroup(statuses.states[status]["disabled"], statuses.buttons, true);
onOffGroup(statuses.states[status]["enabled"], statuses.buttons, false);
}catch(err){
console.log("ERROR: Crawl dashboard failed to regcognize status \"" + status + "\"");
}
}
function statusCall(){
return $.ajax({
type: "POST",
data: {"action": "status"},
success: function(response){
$( '#status' ).text(response.status);
onOffStatus(response.status);
$( '#roundsLeft' ).text(response.rounds_left);
$( '#stats-pages' ).text(response.pages_crawled);
if ('harvest_rate' in response) {
$( '#stats-harvest' ).text(response.harvest_rate);
if (response.harvest_rate > 0) {
$('#getSeeds').attr("disabled", false);
}
}
onOffStatus(response.status);
}
});
}
statusCall();
setInterval(function(){
statusCall();
}, 5000);
$( document ).ready(function() {
$('[data-toggle="tooltip"]').tooltip();
});
$("#dumpImages").attr("disabled", true);
$('#common-crawl-dump').on('click', function() {
$( '#status' ).text( "DUMPING" );
this.disabled = true;
$('#playButton').attr("disabled", true);
$('#stopButton').attr("disabled", true);
$('#common-crawl-dump').attr("disabled", false);
$("#nutchButtons").append('<i id="imageSpinner" class="fa fa-refresh fa-spin" style="font-size:20;"></i>')
$.ajax({
type: "POST",
data: {"action": "ccadump"},
success: function(response) {
sweetAlert("Success", "Crawled data has been successfully dumped in CCA format!", "success");
$("#imageSpinner").remove()
$('#playButton').attr("disabled", false);
},
failure: function() {
sweetAlert("Error", "Dump in CCA format has failed.", "error");
$("#imageSpinner").remove()
}
});
});
$('#playButton').on('click', function() {
$( '#status' ).text( "STARTING" );
onOffStatus("STARTING");
this.disabled = true;
$('#stopButton').attr("disabled", false);
$('#rounds').attr("disabled", true);
val = $("#rounds")? $("#rounds").val() : 0,
$.ajax({
type: "POST",
data: {
"action": "start",
"rounds": val,
},
success: function(response) {
$( '#status' ).text(response.status);
onOffStatus(response.status);
},
failure: function() {
$( '#status' ).text( "Error (could not start crawl)" );
}
});
});
$('#stopButton').on('click', function() {
$( '#status' ).text( "STOPPING" );
onOffStatus("STOPPING");
this.disabled = true;
$.ajax({
type: "POST",
data: {
"action": "stop",
},
success: function(response) {
$( '#status' ).text(response.status);
onOffStatus(response.status);
},
failure: function() {
$( '#status' ).text( "Error (could not stop crawl)" );
}
});
});
$('#restartButton').on('click', function() {
$( '#status' ).text( "RESTARTING" );
onOffStatus("RESTARTING");
this.disabled = true;
val = $("#rounds")? $("#rounds").val() : 0,
$.ajax({
type: "POST",
data: {
"action": "start",
"rounds": val,
},
success: function(response) {
$( '#status' ).text(response.status);
onOffStatus(response.status);
},
failure: function() {
$( '#status' ).text( "Error (could not restart crawl)" );
}
});
});
$("#dumpImages").on('click', function(){
$("#nutchButtons").append('<i id="imageSpinner" class="fa fa-refresh fa-spin" style="font-size:20;"></i>')
$.ajax({
type: "POST",
data: {"action": "dump"},
success: function(response) {
sweetAlert("Success", "Images have been successfully dumped!", "success");
$("#imageSpinner").remove()
},
failure: function() {
sweetAlert("Error", "Image dump has failed.", "error");
$("#imageSpinner").remove()
}
});
});
});
|
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
info: String.fromCharCode has not [[construct]] method
es5id: 15.5.3.2_A4
description: Checking if creating "new String.fromCharCode" fails
---*/
var __fcc__func = String.fromCharCode;
delete String.fromCharCode;
//////////////////////////////////////////////////////////////////////////////
//CHECK#1
try {
var __obj = new __fcc__func(65, 66, 66, 65);
$ERROR('#1: __fcc__func = String.fromCharCode; var __obj = new __fcc__func(65,66,66,65) lead to throwing exception');
} catch (e) {
if (e instanceof Test262Error) throw e;
}
//
//////////////////////////////////////////////////////////////////////////////
|
var browserify = require('browserify');
var gulp = require('gulp');
var source = require('vinyl-source-stream');
var pkg = require('./package.json');
gulp.task('browserify', function() {
return browserify(['./src/ImageResolver.js'])
.bundle({
'standalone':'ImageResolver',
'debug': false,
})
.pipe(source('ImageResolver.' + pkg.version + '.js' ))
.pipe(gulp.dest('./dist/'));
});
gulp.task('watch', function(){
gulp.watch('src/**', ['browserify']);
});
gulp.task('default', ['browserify']);
|
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
info: the length property has the attributes { ReadOnly }
es5id: 15.3.5.1_A3_T2
description: >
Checking if varying the length property of
Function("arg1,arg2,arg3", null) fails
includes: [propertyHelper.js]
---*/
var f = Function("arg1,arg2,arg3", null);
//CHECK#1
if (!(f.hasOwnProperty('length'))) {
$ERROR('#1: the function has length property.');
}
var flength = f.length;
verifyNotWritable(f, "length", null, function() {});
//CHECK#2
if (f.length !== flength) {
$ERROR('#2: the function.length property has the attributes ReadOnly');
}
//CHECK#3
try {
f.length();
$ERROR('#3: the function.length property has the attributes ReadOnly');
} catch (e) {
if (e instanceof Test262Error) throw e;
}
//CHECK#4
if (f.length !== 3) {
$ERROR('#4: the length property has the attributes { ReadOnly }');
}
|
// ## twig.compiler.js
//
// This file handles compiling templates into JS
module.exports = function (Twig) {
/**
* Namespace for compilation.
*/
Twig.compiler = {
module: {}
};
// Compile a Twig Template to output.
Twig.compiler.compile = function (template, options) {
// Get tokens
const tokens = JSON.stringify(template.tokens);
const {id} = template;
let output = null;
if (options.module) {
if (Twig.compiler.module[options.module] === undefined) {
throw new Twig.Error('Unable to find module type ' + options.module);
}
output = Twig.compiler.module[options.module](id, tokens, options.twig);
} else {
output = Twig.compiler.wrap(id, tokens);
}
return output;
};
Twig.compiler.module = {
amd(id, tokens, pathToTwig) {
return 'define(["' + pathToTwig + '"], function (Twig) {\n\tvar twig, templates;\ntwig = Twig.twig;\ntemplates = ' + Twig.compiler.wrap(id, tokens) + '\n\treturn templates;\n});';
},
node(id, tokens) {
return 'var twig = require("twig").twig;\nexports.template = ' + Twig.compiler.wrap(id, tokens);
},
cjs2(id, tokens, pathToTwig) {
return 'module.declare([{ twig: "' + pathToTwig + '" }], function (require, exports, module) {\n\tvar twig = require("twig").twig;\n\texports.template = ' + Twig.compiler.wrap(id, tokens) + '\n});';
}
};
Twig.compiler.wrap = function (id, tokens) {
return 'twig({id:"' + id.replace('"', '\\"') + '", data:' + tokens + ', precompiled: true});\n';
};
return Twig;
};
|
'use strict';
var recursive = require('recursive-readdir');
module.exports = function findFiles(path, suffix, cb) {
recursive(path, function(err, files) {
if (err) { return cb ? cb(err) : null; }
var routers = files.filter(function(f) {
var len = suffix.length;
return f.substr(f.length - len, len) === suffix;
});
return cb(null, routers);
});
};
|
// describe creates a test
describe("Iteration test suite", function() {
// it creates a spec (expectations within are conjoined)
it("some simple example of iteration working", function() {
// iteration stuff
expect(true).toBe(true);
});
});
|
"use strict";
var webpack = require('webpack');
var WebpackDevServer = require('webpack-dev-server');
var config = require('./webpack.config');
startWebpackDevServer();
function startWebpackDevServer() {
new WebpackDevServer(webpack(config), {
publicPath: config.output.publicPath,
hot: true
}).listen(3002, function (err, result) {
if (err) return console.log(err);
console.log("Webpack dev server listening on port 3002.");
});
}
|
var Location = require("./location"),
Promise = require("bluebird"),
values = require('object.values');
module.exports = write;
function write(appPackage, config) {
return Promise.each(values(config.files), function (file) {
if (file.remove) {
return;
}
var buildPath = Location.toPath(file.buildLocation);
config.out.status("Writing", buildPath);
var buildDirectory = config.fs.directory(buildPath);
return config.fs.makeTree(buildDirectory)
.then(function () {
return file.write(buildPath)
.catch(function (error) {
config.out.log("Can't write " + buildPath, error.stack);
throw error;
});
})
.catch(function (error) {
console.error(error);
});
})
.then(function () {
config.out.status();
});
}
|
'use strict';
switch(process.env.NODE_ENV){
case "development":
default:
exports.port = process.env.PORT || 8080;
exports.sslPort = process.env.PORT || 8443;
exports.enforceSSL = false;
break;
case "production":
exports.port = process.env.PORT || 80;
exports.sslPort = process.env.PORT || 443;
exports.enforceSSL = true;
break;
}
exports.db = {
uri: process.env.MONGOLAB_URI || process.env.MONGOHQ_URL || 'mongodb://localhost/openbiz'
};
exports.cryptoKey = 'YOUR_SECRET_KEY';
exports.storage={
type : 'GridFS',
path : "/storage", //require('path').join(require('path').dirname(__filename),'storage'),
url: "/storage",
tmpPath: require('path').join(require('path').dirname(__filename),'storage','tmp'),
}
exports.requireAccountVerification = false;
exports.smtp = {
from: {
name: process.env.SMTP_FROM_NAME || 'Openbiz Platform',
address: process.env.SMTP_FROM_ADDRESS || 'no-reply@gmail.com'
},
credentials: {
user: process.env.SMTP_USERNAME || 'no-reply@gmail.com',
password: process.env.SMTP_PASSWORD || 'YOUR_SECRET_PASSWORD',
host: process.env.SMTP_HOST || 'smtp.gmail.com',
ssl: true
}
};
exports.oauth = {
twitter: {
key: process.env.TWITTER_OAUTH_KEY || '',
secret: process.env.TWITTER_OAUTH_SECRET || ''
},
facebook: {
key: process.env.FACEBOOK_OAUTH_KEY || '',
secret: process.env.FACEBOOK_OAUTH_SECRET || ''
},
github: {
key: process.env.GITHUB_OAUTH_KEY || '',
secret: process.env.GITHUB_OAUTH_SECRET || ''
}
};
|
const openAboutWindow = require('about-window').default;
const join = require('path').join;
module.exports = {
label: 'About Arctic Viewer',
click: () => openAboutWindow({
icon_path: join(__dirname, 'icon.png'),
package_json_dir: join(__dirname, '../'),
}),
};
|
function ResetValidator(){
// modal window to allow users to reset their password //
this.setPassword = $('#set-password');
this.setPassword.modal({ show : false, keyboard : false, backdrop : 'static' });
this.setPasswordAlert = $('#set-password .alert');
}
ResetValidator.prototype.validatePassword = function(s)
{
if (s.length >= 6){
return true;
} else{
this.showAlert('Password Should Be At Least 6 Characters');
return false;
}
}
ResetValidator.prototype.showAlert = function(m)
{
this.setPasswordAlert.attr('class', 'alert alert-error');
this.setPasswordAlert.html(m);
this.setPasswordAlert.show();
}
ResetValidator.prototype.hideAlert = function()
{
this.setPasswordAlert.hide();
}
ResetValidator.prototype.showSuccess = function(m)
{
this.setPasswordAlert.attr('class', 'alert alert-success');
this.setPasswordAlert.html(m);
this.setPasswordAlert.fadeIn(500);
}
|
/* Copyright (c) 2006-2013 by OpenLayers Contributors (see authors.txt for
* full list of contributors). Published under the 2-clause BSD license.
* See license.txt in the OpenLayers distribution or repository for the
* full text of the license. */
/**
* @requires OpenLayers/Control.js
*/
/**
* Class: OpenLayers.Control.Attribution
* The attribution control adds attribution from layers to the map display.
* It uses 'attribution' property of each layer.
*
* Inherits from:
* - <OpenLayers.Control>
*/
OpenLayers.Control.Attribution =
OpenLayers.Class(OpenLayers.Control, {
/**
* APIProperty: separator
* {String} String used to separate layers.
*/
separator: ", ",
/**
* APIProperty: template
* {String} Template for the attribution. This has to include the substring
* "${layers}", which will be replaced by the layer specific
* attributions, separated by <separator>. The default is "${layers}".
*/
template: "${layers}",
/**
* Constructor: OpenLayers.Control.Attribution
*
* Parameters:
* options - {Object} Options for control.
*/
/**
* Method: destroy
* Destroy control.
*/
destroy: function () {
this.map.events.un({
"removelayer": this.updateAttribution,
"addlayer": this.updateAttribution,
"changelayer": this.updateAttribution,
"changebaselayer": this.updateAttribution,
scope: this
});
OpenLayers.Control.prototype.destroy.apply(this, arguments);
},
/**
* Method: draw
* Initialize control.
*
* Returns:
* {DOMElement} A reference to the DIV DOMElement containing the control
*/
draw: function () {
OpenLayers.Control.prototype.draw.apply(this, arguments);
this.map.events.on({
'changebaselayer': this.updateAttribution,
'changelayer': this.updateAttribution,
'addlayer': this.updateAttribution,
'removelayer': this.updateAttribution,
scope: this
});
this.updateAttribution();
return this.div;
},
/**
* Method: updateAttribution
* Update attribution string.
*/
updateAttribution: function () {
var attributions = [];
if (this.map && this.map.layers) {
for (var i = 0, len = this.map.layers.length; i < len; i++) {
var layer = this.map.layers[i];
if (layer.attribution && layer.getVisibility()) {
// add attribution only if attribution text is unique
if (OpenLayers.Util.indexOf(
attributions, layer.attribution) === -1) {
attributions.push(layer.attribution);
}
}
}
this.div.innerHTML = OpenLayers.String.format(this.template, {
layers: attributions.join(this.separator)
});
}
},
CLASS_NAME: "OpenLayers.Control.Attribution"
});
|
/*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";
/**
* The readable validation regex.
*
* @object readableRegex
*/
module.exports = /^[A-Z]\s{0,1}(([a-z])+\s{1}|([0-9])+\s{1})*[a-z0-9]$|^$/;
}());
|
/*
* Copyright (c) 2012-2013. Telecom ParisTech/TSI/MM/GPAC Cyril Concolato
* License: BSD-3-Clause (see LICENSE file)
*/
var VTTin4Parser = function() {
}
VTTin4Parser.prototype.parseSample = function(data) {
var cues, cue;
var stream = new MP4BoxStream(data.buffer);
cues = [];
BoxParser.parseForWrite = false;
while (!stream.isEos()) {
cue = BoxParser.parseOneBox(stream, false);
if (cue.code === BoxParser.OK && cue.box.type === "vttc") {
cues.push(cue.box);
}
}
return cues;
}
var XMLSubtitlein4Parser = function() {
}
XMLSubtitlein4Parser.prototype.parseSample = function(sample) {
var res = {};
var i;
res.resources = [];
var stream = new MP4BoxStream(sample.data.buffer);
if (!sample.subsamples || sample.subsamples.length === 0) {
res.documentString = stream.readString(sample.data.length);
} else {
res.documentString = stream.readString(sample.subsamples[0].size);
if (sample.subsamples.length > 1) {
for (i = 1; i < sample.subsamples.length; i++) {
res.resources[i] = stream.readUint8Array(sample.subsamples[i].size);
}
}
}
res.document = (new DOMParser()).parseFromString(res.documentString, "application/xml");
return res;
}
var Textin4Parser = function() {
}
Textin4Parser.prototype.parseSample = function(sample) {
var textString;
var stream = new MP4BoxStream(sample.data.buffer);
textString = stream.readString(sample.data.length);
return textString;
}
|
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict-local
* @format
*/
'use strict';
const React = require('react');
const StyleSheet = require('../../StyleSheet/StyleSheet');
const invariant = require('invariant');
const processColor = require('../../StyleSheet/processColor');
const nullthrows = require('nullthrows');
const setAndForwardRef = require('../../Utilities/setAndForwardRef');
import AndroidCheckBoxNativeComponent, {
Commands as AndroidCheckBoxCommands,
} from './AndroidCheckBoxNativeComponent';
import type {ViewProps} from '../View/ViewPropTypes';
import type {SyntheticEvent} from '../../Types/CoreEventTypes';
import type {ColorValue} from '../../StyleSheet/StyleSheetTypes';
type CheckBoxEvent = SyntheticEvent<
$ReadOnly<{|
target: number,
value: boolean,
|}>,
>;
type CommonProps = $ReadOnly<{|
...ViewProps,
/**
* Used in case the props change removes the component.
*/
onChange?: ?(event: CheckBoxEvent) => mixed,
/**
* Invoked with the new value when the value changes.
*/
onValueChange?: ?(value: boolean) => mixed,
/**
* Used to locate this view in end-to-end tests.
*/
testID?: ?string,
|}>;
type Props = $ReadOnly<{|
...CommonProps,
/**
* The value of the checkbox. If true the checkbox will be turned on.
* Default value is false.
*/
value?: ?boolean,
/**
* If true the user won't be able to toggle the checkbox.
* Default value is false.
*/
disabled?: ?boolean,
/**
* Used to get the ref for the native checkbox
*/
forwardedRef?: ?React.Ref<typeof AndroidCheckBoxNativeComponent>,
/**
* Controls the colors the checkbox has in checked and unchecked states.
*/
tintColors?: {|true?: ?ColorValue, false?: ?ColorValue|},
|}>;
/**
* Renders a boolean input (Android only).
*
* This is a controlled component that requires an `onValueChange` callback that
* updates the `value` prop in order for the component to reflect user actions.
* If the `value` prop is not updated, the component will continue to render
* the supplied `value` prop instead of the expected result of any user actions.
*
* ```
* import React from 'react';
* import { AppRegistry, StyleSheet, Text, View, CheckBox } from 'react-native';
*
* export default class App extends React.Component {
* constructor(props) {
* super(props);
* this.state = {
* checked: false
* }
* }
*
* toggle() {
* this.setState(({checked}) => {
* return {
* checked: !checked
* };
* });
* }
*
* render() {
* const {checked} = this.state;
* return (
* <View style={styles.container}>
* <Text>Checked</Text>
* <CheckBox value={checked} onChange={this.toggle.bind(this)} />
* </View>
* );
* }
* }
*
* const styles = StyleSheet.create({
* container: {
* flex: 1,
* flexDirection: 'row',
* alignItems: 'center',
* justifyContent: 'center',
* },
* });
*
* // skip this line if using Create React Native App
* AppRegistry.registerComponent('App', () => App);
* ```
*
* @keyword checkbox
* @keyword toggle
*/
class CheckBox extends React.Component<Props> {
_nativeRef: ?React.ElementRef<typeof AndroidCheckBoxNativeComponent> = null;
_setNativeRef = setAndForwardRef({
getForwardedRef: () => this.props.forwardedRef,
setLocalRef: ref => {
this._nativeRef = ref;
},
});
_onChange = (event: CheckBoxEvent) => {
const value = this.props.value ?? false;
AndroidCheckBoxCommands.setNativeValue(nullthrows(this._nativeRef), value);
// Change the props after the native props are set in case the props
// change removes the component
this.props.onChange && this.props.onChange(event);
this.props.onValueChange &&
this.props.onValueChange(event.nativeEvent.value);
};
_getTintColors(tintColors) {
if (tintColors) {
const processedTextColorTrue = processColor(tintColors.true);
invariant(
processedTextColorTrue == null ||
typeof processedTextColorTrue === 'number',
'Unexpected color given for tintColors.true',
);
const processedTextColorFalse = processColor(tintColors.true);
invariant(
processedTextColorFalse == null ||
typeof processedTextColorFalse === 'number',
'Unexpected color given for tintColors.false',
);
return {
true: processedTextColorTrue,
false: processedTextColorFalse,
};
} else {
return undefined;
}
}
render() {
const {
disabled: _,
value: __,
tintColors,
style,
forwardedRef,
...props
} = this.props;
const disabled = this.props.disabled ?? false;
const value = this.props.value ?? false;
const nativeProps = {
...props,
onStartShouldSetResponder: () => true,
onResponderTerminationRequest: () => false,
enabled: !disabled,
on: value,
tintColors: this._getTintColors(tintColors),
style: [styles.rctCheckBox, style],
};
return (
<AndroidCheckBoxNativeComponent
{...nativeProps}
ref={this._setNativeRef}
onChange={this._onChange}
/>
);
}
}
const styles = StyleSheet.create({
rctCheckBox: {
height: 32,
width: 32,
},
});
type CheckBoxType = React.AbstractComponent<
Props,
React.ElementRef<typeof AndroidCheckBoxNativeComponent>,
>;
const CheckBoxWithRef = React.forwardRef<
Props,
React.ElementRef<typeof AndroidCheckBoxNativeComponent>,
>(function CheckBoxWithRef(props, ref) {
return <CheckBox {...props} forwardedRef={ref} />;
});
module.exports = (CheckBoxWithRef: CheckBoxType);
|
'use strict';
var client = require('./client');
var paypal = require('./paypal');
var hostedFields = require('./hosted-fields');
var dataCollector = require('./data-collector');
var americanExpress = require('./american-express');
var unionpay = require('./unionpay');
var applePay = require('./apple-pay');
var threeDSecure = require('./three-d-secure');
module.exports = {
client: client,
paypal: paypal,
hostedFields: hostedFields,
threeDSecure: threeDSecure,
dataCollector: dataCollector,
americanExpress: americanExpress,
unionpay: unionpay,
applePay: applePay,
VERSION: '3.0.1'
};
|
describe('@Replication - Schemas', function() {
"use strict";
var replUtil = require("../fixtures/repl-util");
var servers = replUtil.loadReplicationServers();
var should = require('should');
var async = require('async');
var schema = {
name : "test_repl_schema",
_sis : { owner : ["sistest"] },
track_history : false,
definition : {
name : { type : "String", required : true, unique : true },
test : "Number"
}
};
var BASE_URL = '/api/v1.1/schemas';
var ITEM_URL = BASE_URL + '/' + schema.name;
servers.forEach(function(server, idx) {
describe("Replication from " + server.host, function() {
before(function(done) {
// auth and delete
server.becomeSuperUser(function(e, r) {
if (e) { return done(e); }
server.del(ITEM_URL).end(done);
});
});
it("should create/replicate the schema", function(done) {
server.post(BASE_URL).send(schema)
.expect(201, function(err, res) {
if (err) { return done(err); }
var opts = {
url : ITEM_URL,
status : 200,
data : res.body
};
replUtil.verifyExpected(servers, opts, done);
});
});
it("should update/replicate the schema", function(done) {
schema.definition.foo = "String";
delete schema.definition.test;
server.put(ITEM_URL).send(schema)
.expect(200, function(err, res) {
if (err) { return done(err); }
var opts = {
url : ITEM_URL,
status : 200,
data : res.body
};
replUtil.verifyExpected(servers, opts, done);
});
});
it("should delete/replicate the schema", function(done) {
server.del(ITEM_URL).expect(200)
.end(function(err, res) {
if (err) { return done(err); }
var opts = {
url : ITEM_URL,
status : 404
};
replUtil.verifyExpected(servers, opts, done);
});
});
});
});
});
|
'use strict';
var isImplemented = require('../../../../string/#/@@iterator/is-implemented');
module.exports = function (a) { a(isImplemented(), true); };
|
version https://git-lfs.github.com/spec/v1
oid sha256:2a5fe71dfb3727e1ea221863ab51f98455038d820908b7b852dae29bd84d2c62
size 9114
|
import Ember from 'ember';
export default Ember.Component.extend({
classNames: ['button-bar']
});
|
const should = require('should');
const errors = require('@tryghost/errors');
const {hbs, templates} = require('../../../../../../core/frontend/services/rendering');
describe('Helpers Template', function () {
it('can execute a template', function () {
hbs.registerPartial('test', '<h1>Hello {{name}}</h1>');
const safeString = templates.execute('test', {name: 'world'});
should.exist(safeString);
safeString.should.have.property('string').and.equal('<h1>Hello world</h1>');
});
it('will throw an IncorrectUsageError if the partial does not exist', function () {
should.throws(() => {
templates.execute('non-existent');
}, errors.IncorrectUsageError);
});
});
|
//
// adding export statements to the all.js file
//
// FIXME: not clear this is how we want to do it
//
exports.BigInteger = BigInteger;
exports.sjcl = sjcl;
exports.hex2b64 = hex2b64;
exports.b64tohex = b64tohex;
exports.int2char = int2char;
// sha1 exports, no hmac for now
exports.hex_sha1 = hex_sha1;
exports.b64_sha1 = b64_sha1;
// this is so we can export the faked window and navigator
// objects and not write the code for base64 twice
exports.window = window;
exports.navigator = navigator;
|
import React from 'react';
import ReactDOM from 'react-dom';
import JqxTabs from '../../../jqwidgets-react/react_jqxtabs.js';
class App extends React.Component {
componentDidMount() {
let index = 0;
this.refs.myTabs.on('tabclick', (event) => {
let allLiTags = document.getElementById('unorderedList').getElementsByTagName('li');
let length = allLiTags.length;
if (event.args.item == length - 1) {
this.refs.myTabs.addAt(event.args.item, 'Sample title ' + index, 'Sample content number: ' + index);
index++;
}
});
}
render () {
let tabsHTML = `
<ul style="margin-left: 30px;" id="unorderedList">
<li>Node.js</li>
<li>Active Server Pages</li>
<li canselect='false' hasclosebutton='false'>Add New Tab</li>
</ul>
<div>
Node.js is an event-driven I/O server-side JavaScript environment based on V8. It
is intended for writing scalable network programs such as web servers. It was created
by Ryan Dahl in 2009, and its growth is sponsored by Joyent, which employs Dahl.
Similar environments written in other programming languages include Twisted for
Python, Perl Object Environment for Perl, libevent for C and EventMachine for Ruby.
Unlike most JavaScript, it is not executed in a web browser, but is instead a form
of server-side JavaScript. Node.js implements some CommonJS specifications. Node.js
includes a REPL environment for interactive testing.
</div>
<div>
ASP.NET is a web application framework developed and marketed by Microsoft to allow
programmers to build dynamic web sites, web applications and web services. It was
first released in January 2002 with version 1.0 of the .NET Framework, and is the
successor to Microsoft's Active Server Pages (ASP) technology. ASP.NET is built
on the Common Language Runtime (CLR), allowing programmers to write ASP.NET code
using any supported .NET language. The ASP.NET SOAP extension framework allows ASP.NET
components to process SOAP messages.
</div>
<div>
</div>
`;
return (
<JqxTabs ref='myTabs' template={tabsHTML} style={{ float: 'left' }}
width={500} height={250} showCloseButtons={true}
/>
)
}
}
ReactDOM.render(<App />, document.getElementById('app'));
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = {
// Definitions
ArrayExpression: 20,
TaggedTemplateExpression: 20,
ThisExpression: 20,
Identifier: 20,
Literal: 18,
TemplateLiteral: 20,
Super: 20,
SequenceExpression: 20,
// Operations
MemberExpression: 19,
CallExpression: 19,
NewExpression: 19,
ArrowFunctionExpression: 18,
// Other definitions
// Value 17 enables parenthesis in an `ExpressionStatement` node
ClassExpression: 17,
FunctionExpression: 17,
ObjectExpression: 17,
// Other operations
UpdateExpression: 16,
UnaryExpression: 15,
BinaryExpression: 14,
LogicalExpression: 13,
ConditionalExpression: 4,
AssignmentExpression: 3,
YieldExpression: 2,
RestElement: 1,
// Babylon AST nodes ---------------------------------------------------------------------------------------------
BooleanLiteral: 18,
DirectiveLiteral: 18,
NullLiteral: 18,
NumericLiteral: 18,
StringLiteral: 18
};
module.exports = exports["default"];
|
/*
decodes a key binding token to a JavaScript structure
returns an array of objects:
{
// key name translated to keyCode (possibly more than one)
keyCodes: [<number>],
// translated modifiers
modifiers: {
altKey: null, // ignore
ctrKey: false, // expect not pressed
metaKey: true, // expect pressed
shiftKey: true, // expect pressed
},
// callback that returns true if event's
// modifier keys match the expected state
matchModifiers: function(event){},
}
*/
import keycode from '../map/keycode';
const modifier = {
alt: 'altKey',
ctrl: 'ctrlKey',
meta: 'metaKey',
shift: 'shiftKey',
};
const modifierSequence = Object.keys(modifier).map(name => modifier[name]);
function createExpectedModifiers(ignoreModifiers) {
const value = ignoreModifiers ? null : false;
return {
altKey: value,
ctrlKey: value,
metaKey: value,
shiftKey: value,
};
}
function resolveModifiers(modifiers) {
const ignoreModifiers = modifiers.indexOf('*') !== -1;
const expected = createExpectedModifiers(ignoreModifiers);
modifiers.forEach(function(token) {
if (token === '*') {
// we've already covered the all-in operator
return;
}
// we want the modifier pressed
let value = true;
const operator = token.slice(0, 1);
if (operator === '?') {
// we don't care if the modifier is pressed
value = null;
} else if (operator === '!') {
// we do not want the modifier pressed
value = false;
}
if (value !== true) {
// compensate for the modifier's operator
token = token.slice(1);
}
const propertyName = modifier[token];
if (!propertyName) {
throw new TypeError('Unknown modifier "' + token + '"');
}
expected[propertyName] = value;
});
return expected;
}
function resolveKey(key) {
const code = keycode[key] || parseInt(key, 10);
if (!code || typeof code !== 'number' || isNaN(code)) {
throw new TypeError('Unknown key "' + key + '"');
}
return [code].concat(keycode._alias[code] || []);
}
function matchModifiers(expected, event) {
// returns true on match
return !modifierSequence.some(function(prop) {
// returns true on mismatch
return typeof expected[prop] === 'boolean' && Boolean(event[prop]) !== expected[prop];
});
}
export default function(text) {
return text.split(/\s+/).map(function(_text) {
const tokens = _text.split('+');
const _modifiers = resolveModifiers(tokens.slice(0, -1));
const _keyCodes = resolveKey(tokens.slice(-1));
return {
keyCodes: _keyCodes,
modifiers: _modifiers,
matchModifiers: matchModifiers.bind(null, _modifiers),
};
});
}
|
"use strict";
const { getPacked } = require("..");
describe("@lerna/get-packed", () => {
it("needs tests", () => {
expect(getPacked).toBeDefined();
});
});
|
/*
Copyright (c) 2004-2009, The Dojo Foundation All Rights Reserved.
Available via Academic Free License >= 2.1 OR the modified BSD license.
see: http://dojotoolkit.org/license for details
*/
if(!dojo._hasResource["dojox.editor.plugins.ShowBlockNodes"]){
dojo._hasResource["dojox.editor.plugins.ShowBlockNodes"]=true;
dojo.provide("dojox.editor.plugins.ShowBlockNodes");
dojo.require("dijit._editor._Plugin");
dojo.require("dijit.form.Button");
dojo.require("dojo.i18n");
dojo.requireLocalization("dojox.editor.plugins","ShowBlockNodes",null,"ROOT,cs,de,es,fr,hu,it,ja,ko,pl,pt,ru,zh,zh-tw");
dojo.declare("dojox.editor.plugins.ShowBlockNodes",dijit._editor._Plugin,{useDefaultCommand:false,iconClassPrefix:"dijitAdditionalEditorIcon",_styled:false,_initButton:function(){
var _1=dojo.i18n.getLocalization("dojox.editor.plugins","ShowBlockNodes");
this.button=new dijit.form.ToggleButton({label:_1["showBlockNodes"],showLabel:false,iconClass:this.iconClassPrefix+" "+this.iconClassPrefix+"ShowBlockNodes",tabIndex:"-1",onChange:dojo.hitch(this,"_showBlocks")});
this.editor.addKeyHandler(dojo.keys.F9,true,true,dojo.hitch(this,this.toggle));
},setEditor:function(_2){
this.editor=_2;
this._initButton();
},toggle:function(){
this.button.attr("checked",!this.button.attr("checked"));
},_showBlocks:function(_3){
var _4=this.editor.document;
if(!this._styled){
try{
this._styled=true;
var _5="";
var _6=["div","p","ul","ol","table","h1","h2","h3","h4","h5","h6","pre","dir","center","blockquote","form","fieldset","address","object","pre","hr","ins","noscript","li","map","button","dd","dt"];
var _7="@media screen {\n"+"\t.editorShowBlocks {TAG} {\n"+"\t\tbackground-image: url({MODURL}/images/blockelems/{TAG}.gif);\n"+"\t\tbackground-repeat: no-repeat;\n"+"\t\tbackground-position: top left;\n"+"\t\tborder-width: 1px;\n"+"\t\tborder-style: dashed;\n"+"\t\tborder-color: #D0D0D0;\n"+"\t\tpadding-top: 15px;\n"+"\t\tpadding-left: 15px;\n"+"\t}\n"+"}\n";
dojo.forEach(_6,function(_8){
_5+=_7.replace(/\{TAG\}/gi,_8);
});
var _9=dojo.moduleUrl(dojox._scopeName,"editor/plugins/resources").toString();
if(!(_9.match(/^https?:\/\//i))&&!(_9.match(/^file:\/\//i))){
var _a;
if(_9.charAt(0)==="/"){
var _b=dojo.doc.location.protocol;
var _c=dojo.doc.location.host;
_a=_b+"//"+_c;
}else{
_a=this._calcBaseUrl(dojo.global.location.href);
}
if(_a[_a.length-1]!=="/"&&_9.charAt(0)!=="/"){
_a+="/";
}
_9=_a+_9;
}
_5=_5.replace(/\{MODURL\}/gi,_9);
if(!dojo.isIE){
var _d=_4.createElement("style");
_d.appendChild(_4.createTextNode(_5));
_4.getElementsByTagName("head")[0].appendChild(_d);
}else{
var ss=_4.createStyleSheet("");
ss.cssText=_5;
}
}
catch(e){
console.warn(e);
}
}
if(_3){
dojo.addClass(this.editor.editNode,"editorShowBlocks");
}else{
dojo.removeClass(this.editor.editNode,"editorShowBlocks");
}
},_calcBaseUrl:function(_e){
var _f=null;
if(_e!==null){
var _10=_e.indexOf("?");
if(_10!=-1){
_e=_e.substring(0,_10);
}
_10=_e.lastIndexOf("/");
if(_10>0&&_10<_e.length){
_f=_e.substring(0,_10);
}else{
_f=_e;
}
}
return _f;
}});
dojo.subscribe(dijit._scopeName+".Editor.getPlugin",null,function(o){
if(o.plugin){
return;
}
var _11=o.args.name.toLowerCase();
if(_11==="showblocknodes"){
o.plugin=new dojox.editor.plugins.ShowBlockNodes();
}
});
}
|
/**
* Compiles SCSS to CSS
**/
'use strict';
var paths = require('./config.js').paths;
var gulp = require('gulp');
var sass = require('gulp-sass');
var autoprefixer = require('gulp-autoprefixer');
var runSequence = require('run-sequence');
var plumber = require('gulp-plumber');
var onError = require('./on-error.js');
// Paths
var watchPath = paths.src_styles + '/**/*.scss';
var destPath = paths.dest_styles;
gulp.task('styles', function() {
return gulp.src([watchPath])
.pipe(plumber({
errorHandler: onError
}))
.pipe(sass({
errLogToConsole: true
}))
.pipe(autoprefixer())
.pipe(gulp.dest(destPath));
});
gulp.task('styles:watch', ['styles'], function() {
return gulp.watch(watchPath).on('change', function() {
runSequence('styles', 'browser-sync-reload');
});
});
|
/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'forms', 'bs', {
button: {
title: 'Button Properties',
text: 'Text (Value)',
type: 'Type',
typeBtn: 'Button',
typeSbm: 'Submit',
typeRst: 'Reset'
},
checkboxAndRadio: {
checkboxTitle: 'Checkbox Properties',
radioTitle: 'Radio Button Properties',
value: 'Value',
selected: 'Selected'
},
form: {
title: 'Form Properties',
menu: 'Form Properties',
action: 'Action',
method: 'Method',
encoding: 'Encoding'
},
hidden: {
title: 'Hidden Field Properties',
name: 'Name',
value: 'Value'
},
select: {
title: 'Selection Field Properties',
selectInfo: 'Select Info',
opAvail: 'Available Options',
value: 'Value',
size: 'Size',
lines: 'lines',
chkMulti: 'Allow multiple selections',
opText: 'Text',
opValue: 'Value',
btnAdd: 'Add',
btnModify: 'Modify',
btnUp: 'Up',
btnDown: 'Down',
btnSetValue: 'Set as selected value',
btnDelete: 'Delete'
},
textarea: {
title: 'Textarea Properties',
cols: 'Columns',
rows: 'Rows'
},
textfield: {
title: 'Text Field Properties',
name: 'Name',
value: 'Value',
charWidth: 'Character Width',
maxChars: 'Maximum Characters',
type: 'Type',
typeText: 'Text',
typePass: 'Password',
typeEmail: 'Email', // MISSING
typeSearch: 'Search', // MISSING
typeTel: 'Telephone Number', // MISSING
typeUrl: 'URL'
}
});
|
var express = require('express');
var app = express();
app.get('/', function(req, res) {
res.send('Hello');
});
var songs = express.Router(); //<co id="callout-web-express4-restful-1" />
songs.get('/', function(req, res) { //<co id="callout-web-express4-restful-2" />
res.send('A list of songs');
});
songs.get('/:id', function(req, res) {
res.send('A specific song');
});
app.use('/songs', songs); //<co id="callout-web-express4-restful-3" />
app.listen(3000);
|
app.controller('CustomCenterUrlHashController', [ '$scope', '$location', function($scope, $location) {
angular.extend($scope, {
london: {
lat: 51.505,
lng: -0.09,
zoom: 4
}
});
$scope.$on("centerUrlHash", function(event, centerHash) {
console.log("url", centerHash);
$location.search({ center: centerHash });
});
$scope.changeLocation = function(centerHash) {
$location.search({ center: centerHash });
};
}]);
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _invariant = require('invariant');
var _invariant2 = _interopRequireDefault(_invariant);
var _ExecutionEnvironment = require('./ExecutionEnvironment');
var _BrowserProtocol = require('./BrowserProtocol');
var BrowserProtocol = _interopRequireWildcard(_BrowserProtocol);
var _RefreshProtocol = require('./RefreshProtocol');
var RefreshProtocol = _interopRequireWildcard(_RefreshProtocol);
var _DOMUtils = require('./DOMUtils');
var _createHistory = require('./createHistory');
var _createHistory2 = _interopRequireDefault(_createHistory);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Creates and returns a history object that uses HTML5's history API
* (pushState, replaceState, and the popstate event) to manage history.
* This is the recommended method of managing history in browsers because
* it provides the cleanest URLs.
*
* Note: In browsers that do not support the HTML5 history API full
* page reloads will be used to preserve clean URLs. You can force this
* behavior using { forceRefresh: true } in options.
*/
var createBrowserHistory = function createBrowserHistory() {
var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
!_ExecutionEnvironment.canUseDOM ? process.env.NODE_ENV !== 'production' ? (0, _invariant2.default)(false, 'Browser history needs a DOM') : (0, _invariant2.default)(false) : void 0;
var useRefresh = options.forceRefresh || !(0, _DOMUtils.supportsHistory)();
var Protocol = useRefresh ? RefreshProtocol : BrowserProtocol;
var getUserConfirmation = Protocol.getUserConfirmation;
var getCurrentLocation = Protocol.getCurrentLocation;
var pushLocation = Protocol.pushLocation;
var replaceLocation = Protocol.replaceLocation;
var go = Protocol.go;
var history = (0, _createHistory2.default)(_extends({
getUserConfirmation: getUserConfirmation }, options, {
getCurrentLocation: getCurrentLocation,
pushLocation: pushLocation,
replaceLocation: replaceLocation,
go: go
}));
var listenerCount = 0,
stopListener = void 0;
var startListener = function startListener(listener, before) {
if (++listenerCount === 1) stopListener = BrowserProtocol.startListener(history.transitionTo);
var unlisten = before ? history.listenBefore(listener) : history.listen(listener);
return function () {
unlisten();
if (--listenerCount === 0) stopListener();
};
};
var listenBefore = function listenBefore(listener) {
return startListener(listener, true);
};
var listen = function listen(listener) {
return startListener(listener, false);
};
return _extends({}, history, {
listenBefore: listenBefore,
listen: listen
});
};
exports.default = createBrowserHistory;
|
/* Blob.js
* A Blob implementation.
* 2013-12-27
*
* By Eli Grey, http://eligrey.com
* By Devin Samarin, https://github.com/eboyjr
* License: X11/MIT
* See LICENSE.md
*/
/*global self, unescape */
/*jslint bitwise: true, regexp: true, confusion: true, es5: true, vars: true, white: true,
plusplus: true */
/*! @source http://purl.eligrey.com/github/Blob.js/blob/master/Blob.js */
if (!(typeof Blob === "function" || typeof Blob === "object") || typeof URL === "undefined")
if ((typeof Blob === "function" || typeof Blob === "object") && typeof webkitURL !== "undefined") self.URL = webkitURL;
else var Blob = (function (view) {
"use strict";
var BlobBuilder = view.BlobBuilder || view.WebKitBlobBuilder || view.MozBlobBuilder || view.MSBlobBuilder || (function(view) {
var
get_class = function(object) {
return Object.prototype.toString.call(object).match(/^\[object\s(.*)\]$/)[1];
}
, FakeBlobBuilder = function BlobBuilder() {
this.data = [];
}
, FakeBlob = function Blob(data, type, encoding) {
this.data = data;
this.size = data.length;
this.type = type;
this.encoding = encoding;
}
, FBB_proto = FakeBlobBuilder.prototype
, FB_proto = FakeBlob.prototype
, FileReaderSync = view.FileReaderSync
, FileException = function(type) {
this.code = this[this.name = type];
}
, file_ex_codes = (
"NOT_FOUND_ERR SECURITY_ERR ABORT_ERR NOT_READABLE_ERR ENCODING_ERR "
+ "NO_MODIFICATION_ALLOWED_ERR INVALID_STATE_ERR SYNTAX_ERR"
).split(" ")
, file_ex_code = file_ex_codes.length
, real_URL = view.URL || view.webkitURL || view
, real_create_object_URL = real_URL.createObjectURL
, real_revoke_object_URL = real_URL.revokeObjectURL
, URL = real_URL
, btoa = view.btoa
, atob = view.atob
, ArrayBuffer = view.ArrayBuffer
, Uint8Array = view.Uint8Array
;
FakeBlob.fake = FB_proto.fake = true;
while (file_ex_code--) {
FileException.prototype[file_ex_codes[file_ex_code]] = file_ex_code + 1;
}
if (!real_URL.createObjectURL) {
URL = view.URL = {};
}
URL.createObjectURL = function(blob) {
var
type = blob.type
, data_URI_header
;
if (type === null) {
type = "application/octet-stream";
}
if (blob instanceof FakeBlob) {
data_URI_header = "data:" + type;
if (blob.encoding === "base64") {
return data_URI_header + ";base64," + blob.data;
} else if (blob.encoding === "URI") {
return data_URI_header + "," + decodeURIComponent(blob.data);
} if (btoa) {
return data_URI_header + ";base64," + btoa(blob.data);
} else {
return data_URI_header + "," + encodeURIComponent(blob.data);
}
} else if (real_create_object_URL) {
return real_create_object_URL.call(real_URL, blob);
}
};
URL.revokeObjectURL = function(object_URL) {
if (object_URL.substring(0, 5) !== "data:" && real_revoke_object_URL) {
real_revoke_object_URL.call(real_URL, object_URL);
}
};
FBB_proto.append = function(data/*, endings*/) {
var bb = this.data;
// decode data to a binary string
if (Uint8Array && (data instanceof ArrayBuffer || data instanceof Uint8Array)) {
var
str = ""
, buf = new Uint8Array(data)
, i = 0
, buf_len = buf.length
;
for (; i < buf_len; i++) {
str += String.fromCharCode(buf[i]);
}
bb.push(str);
} else if (get_class(data) === "Blob" || get_class(data) === "File") {
if (FileReaderSync) {
var fr = new FileReaderSync;
bb.push(fr.readAsBinaryString(data));
} else {
// async FileReader won't work as BlobBuilder is sync
throw new FileException("NOT_READABLE_ERR");
}
} else if (data instanceof FakeBlob) {
if (data.encoding === "base64" && atob) {
bb.push(atob(data.data));
} else if (data.encoding === "URI") {
bb.push(decodeURIComponent(data.data));
} else if (data.encoding === "raw") {
bb.push(data.data);
}
} else {
if (typeof data !== "string") {
data += ""; // convert unsupported types to strings
}
// decode UTF-16 to binary string
bb.push(unescape(encodeURIComponent(data)));
}
};
FBB_proto.getBlob = function(type) {
if (!arguments.length) {
type = null;
}
return new FakeBlob(this.data.join(""), type, "raw");
};
FBB_proto.toString = function() {
return "[object BlobBuilder]";
};
FB_proto.slice = function(start, end, type) {
var args = arguments.length;
if (args < 3) {
type = null;
}
return new FakeBlob(
this.data.slice(start, args > 1 ? end : this.data.length)
, type
, this.encoding
);
};
FB_proto.toString = function() {
return "[object Blob]";
};
return FakeBlobBuilder;
}(view));
return function Blob(blobParts, options) {
var type = options ? (options.type || "") : "";
var builder = new BlobBuilder();
if (blobParts) {
for (var i = 0, len = blobParts.length; i < len; i++) {
builder.append(blobParts[i]);
}
}
return builder.getBlob(type);
};
}(typeof self !== "undefined" && self || typeof window !== "undefined" && window || this.content || this));
|
it("should bailout when reading whole exports object from this", () => {
var test = require("./reading-this").test;
expect(test().abc).toBe("abc");
});
it("should bailout when reading whole exports object from exports", () => {
var test = require("./reading-exports").test;
expect(test().abc).toBe("abc");
});
it("should bailout when reading whole exports object from module.exports", () => {
var test = require("./reading-module-exports").test;
expect(test().abc).toBe("abc");
});
it("should reassigning exports (assign values)", () => {
expect(require("./assign-exports-assign?1").abc).toBe("abc");
expect(require("./assign-exports-assign?2").def).toBe(undefined);
});
it("should reassigning exports (define values)", () => {
expect(require("./assign-exports-define").abc).toBe("abc");
expect(require("./assign-exports-define").def).toBe(undefined);
});
it("should not mangle or remove nested properties", () => {
expect(require("./nested-property").abc).toBe("abc");
});
it("should be able to access the exports via call context", () => {
expect(require("./accessing-call-context?1").func().abc).toBe("abc");
var cc = require("./accessing-call-context?2");
expect(cc.func().abc).toBe("abc");
var func = require("./accessing-call-context?3").func;
expect(func()).toBe(undefined);
});
it("should be able to define an exports property on module (property)", () => {
expect(require("./define-module-property?2").abc).toBe("abc");
expect(require("./define-module-property?1").def).toBe("def");
});
it("should be able to define an exports property on module (properties)", () => {
expect(require("./define-module-properties?2").abc).toBe("abc");
expect(require("./define-module-properties?1").def).toBe("def");
});
it("should be able to do stuff with the module object", () => {
expect(require("./accessing-module?2").abc).toBe("abc");
expect(require("./accessing-module?1").def).toBe("def");
});
it("should be able to use AMD to define exports", () => {
expect(require("./using-amd?2").abc).toBe("abc");
expect(require("./using-amd?1").def).toBe("def");
});
|
"use strict";
var mixin = require('./helpers').mixin;
mixin(exports, {
Client: require('./Client'),
News: require('./News'),
App: require('./App'),
User: require('./User'),
Player: require('./Player'),
UserStats: require('./User/Stats'),
Community: require('./Community'),
Inventory: require('./Inventory'),
Items: require('./Items')
});
|
function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
var _jsxWrapper = function _jsxWrapper(func, args) {
return {
__jsxDOMWrapper: true,
func: func,
args: args
};
};
var _hasOwn = Object.prototype.hasOwnProperty;
var _renderArbitrary = function _renderArbitrary(child) {
var type = _typeof(child);
if (type === "number" || type === "string" || type === "object" && child instanceof String) {
text(child);
} else if (Array.isArray(child)) {
for (var i = 0; i < child.length; i++) {
_renderArbitrary(child[i]);
}
} else if (type === "object") {
if (child.__jsxDOMWrapper) {
var func = child.func,
args = child.args;
if (args) {
func.apply(this, args);
} else {
func();
}
} else if (String(child) === "[object Object]") {
for (var prop in child) {
if (_hasOwn.call(child, i)) _renderArbitrary(child[i]);
}
}
}
};
var _test$wrapper = function _test$wrapper(_attr, _first, _child, _child2, _second, _child3) {
elementOpen("div", null, null, "attr", _attr);
elementOpen("div", null, null, "first", _first);
_renderArbitrary(_child);
elementClose("div");
_renderArbitrary(_child2);
elementOpen("div", null, null, "second", _second);
_renderArbitrary(_child3);
elementClose("div");
return elementClose("div");
};
function render() {
var test = _jsxWrapper(_test$wrapper, [i++, i++, i++, i++, i++, i++]);
elementOpen("root");
_renderArbitrary(test);
return elementClose("root");
}
|
/** This module defines a express.Router() instance
* - supporting offset=<number> and limit=<number>*
* - calls next with error if a impossible offset and/or limit value is given
*
* Note: it expects to be called BEFORE any data fetched from DB
* Note: it sets an object { limit: 0, skip: 0 } with the proper number values in req.locals.limitskip
* Note: it sets an Error-Object to next with error.status set to HTTP status code 400
*
* @author Johannes Konert
* @licence CC BY-SA 4.0
*
* @module restapi/limitoffset-middleware-mongo
* @type {Router}
*/
// remember: in modules you have 3 variables given by CommonJS
// 1.) require() function
// 2.) module.exports
// 3.) exports (which is module.exports)
"use strict";
var router = require('express').Router();
var logger = require('debug')('me2:offsetlimit');
// the exported router with handler
router.use(function(req, res, next) {
var offset = undefined;
var limit = undefined;
var offsetString = req.query.offset;
var limitString = req.query.limit;
var err = null;
if (offsetString) {
if (!isNaN(offsetString)) {
offset = parseInt(offsetString);
if (offset < 0) { err = new Error('offset is negative')}
}
else {
err = new Error('given offset is not a valid number '+ offsetString);
}
}
if (limitString) {
if (!isNaN(limitString)) {
limit = parseInt(limitString);
if (limit < 1 ) { err = new Error('limit is zero or negative')}
}
else {
err = new Error('given limit is not a valid number ' + limitString);
}
}
if (err) {
logger('problem occurred with limit/offset values');
err.status = 400;
next(err)
} else {
res.locals.limitskip = { }; // mongoDB uses parameter object for skip/limit
if (limit) res.locals.limitskip.limit = limit;
if (offset) res.locals.limitskip.skip = offset;
next()
}
});
module.exports = router;
|
var tap = require('tap');
var tape = require('../');
var concat = require('concat-stream');
var common = require('./common');
var stripFullStack = common.stripFullStack;
tap.test('tape todo test', function (assert) {
var test = tape.createHarness({ exit: false });
assert.plan(1);
test.createStream().pipe(concat(function (body) {
assert.equal(
stripFullStack(body.toString('utf8')),
'TAP version 13\n'
+ '# success\n'
+ 'ok 1 this test runs\n'
+ '# TODO failure\n'
+ 'not ok 2 should never happen # TODO\n'
+ ' ---\n'
+ ' operator: fail\n'
+ ' at: Test.<anonymous> ($TEST/todo.js:$LINE:$COL)\n'
+ ' ...\n'
+ '\n'
+ '1..2\n'
+ '# tests 2\n'
+ '# pass 2\n'
+ '\n'
+ '# ok\n'
);
}));
test('success', function (t) {
t.equal(true, true, 'this test runs');
t.end();
});
test('failure', { todo: true }, function (t) {
t.fail('should never happen');
t.end();
});
});
|
$(function() {
$('#getKey').click(function(e) {
$.get('/users/apikey', function(data) {
$('#api').html(data);
});
});
});
|
/* */
"format global";
/**
* Copyright 2015 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, define){
define([], f);
})(function(){
(function( window, undefined ) {
var kendo = window.kendo || (window.kendo = { cultures: {} });
kendo.cultures["af"] = {
name: "af",
numberFormat: {
pattern: ["-n"],
decimals: 2,
",": " ",
".": ",",
groupSize: [3],
percent: {
pattern: ["-n%","n%"],
decimals: 2,
",": " ",
".": ",",
groupSize: [3],
symbol: "%"
},
currency: {
pattern: ["$-n","$ n"],
decimals: 2,
",": " ",
".": ",",
groupSize: [3],
symbol: "R"
}
},
calendars: {
standard: {
days: {
names: ["Sondag","Maandag","Dinsdag","Woensdag","Donderdag","Vrydag","Saterdag"],
namesAbbr: ["Son","Maan","Dins","Woen","Dond","Vry","Sat"],
namesShort: ["So","Ma","Di","Wo","Do","Vr","Sa"]
},
months: {
names: ["Januarie","Februarie","Maart","April","Mei","Junie","Julie","Augustus","September","Oktober","November","Desember"],
namesAbbr: ["Jan","Feb","Mar","Apr","Mei","Jun","Jul","Aug","Sep","Okt","Nov","Des"]
},
AM: ["VM.","vm.","VM."],
PM: ["NM.","nm.","NM."],
patterns: {
d: "yyyy/MM/dd",
D: "dd MMMM yyyy",
F: "dd MMMM yyyy hh:mm:ss tt",
g: "yyyy/MM/dd hh:mm tt",
G: "yyyy/MM/dd hh:mm:ss tt",
m: "d MMMM",
M: "d MMMM",
s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss",
t: "hh:mm tt",
T: "hh:mm:ss tt",
u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'",
y: "MMMM yyyy",
Y: "MMMM yyyy"
},
"/": "/",
":": ":",
firstDay: 0
}
}
}
})(this);
return window.kendo;
}, typeof define == 'function' && define.amd ? define : function(_, f){ f(); });
|
var os = require('os')
var tape = require('tape')
var execspawn = require('./')
var concat = require('concat-stream')
tape('echo', function(t) {
execspawn('echo $0 $1 and $2', ['a', 'b', 'c']).stdout.pipe(concat(function(data) {
t.same(data.toString(), 'a b and c'+os.EOL)
t.end()
}))
})
tape('npm deps', function(t) {
execspawn('tape').on('exit', function(code) {
t.same(code, 0)
t.end()
})
})
|
// test eval
var assert = require('assert');
var approx = require('../../../tools/approx');
var error = require('../../../lib/error/index');
var math = require('../../../index');
var Complex = math.type.Complex;
var Matrix = math.type.Matrix;
var Unit = math.type.Unit;
var ResultSet = math.type.ResultSet;
describe('eval', function() {
it('should evaluate expressions', function() {
approx.equal(math.eval('(2+3)/4'), 1.25);
assert.deepEqual(math.eval('sqrt(-4)'), new Complex(0, 2));
});
it('should eval a list of expressions', function() {
assert.deepEqual(math.eval(['1+2', '3+4', '5+6']), [3, 7, 11]);
assert.deepEqual(math.eval(['a=3', 'b=4', 'a*b']), [3, 4, 12]);
assert.deepEqual(math.eval(math.matrix(['a=3', 'b=4', 'a*b'])), math.matrix([3, 4, 12]));
assert.deepEqual(math.eval(['a=3', 'b=4', 'a*b']), [3, 4, 12]);
});
it('should eval a series of expressions', function() {
assert.deepEqual(math.eval('a=3\nb=4\na*b'), new ResultSet([3, 4, 12]));
assert.deepEqual(math.eval('f(x) = a * x; a=2; f(4)'), new ResultSet([8]));
assert.deepEqual(math.eval('b = 43; b * 4'), new ResultSet([172]));
});
it('should throw an error if wrong number of arguments', function() {
assert.throws(function () {math.eval()}, error.ArgumentsError);
assert.throws(function () {math.eval(1,2,3)}, error.ArgumentsError);
});
it('should throw an error with a number', function() {
assert.throws(function () {math.eval(23)}, TypeError);
});
it('should throw an error with a unit', function() {
assert.throws(function () {math.eval(new Unit(5, 'cm'))}, TypeError);
});
it('should throw an error with a complex number', function() {
assert.throws(function () {math.eval(new Complex(2,3))}, TypeError);
});
it('should throw an error with a boolean', function() {
assert.throws(function () {math.eval(true)}, TypeError);
});
it('should handle the given scope', function() {
var scope = {
a: 3,
b: 4
};
assert.deepEqual(math.eval('a*b', scope), 12);
assert.deepEqual(math.eval('c=5', scope), 5);
assert.deepEqual(math.format(math.eval('f(x) = x^a', scope)), 'f(x)');
assert.deepEqual(Object.keys(scope).length, 4);
assert.deepEqual(scope.a, 3);
assert.deepEqual(scope.b, 4);
assert.deepEqual(scope.c, 5);
assert.deepEqual(typeof scope.f, 'function');
assert.equal(scope.f(3), 27);
scope.a = 2;
assert.equal(scope.f(3), 9);
scope.hello = function (name) {
return 'hello, ' + name + '!';
};
assert.deepEqual(math.eval('hello("jos")', scope), 'hello, jos!');
});
});
|
var path = require('path')
var fs = require('fs')
var os = require('os')
var glob = require('glob')
var findRoot = require('find-root')
var Minimatch = require('minimatch').Minimatch
var formatter = require('esformatter')
var ESFORMATTER_CONFIG = require(path.join(__dirname, 'rc', 'esformatter.json'))
var DEFAULT_IGNORE = [
'node_modules/**',
'.git/**',
'**/*.min.js',
'**/bundle.js'
]
var MULTI_NEWLINE = /((?:\r?\n){3,})/g
var EOL_SEMICOLON = /;\r?\n/g
var SOF_NEWLINES = /^(\r?\n)+/g
var EOL = os.EOL
module.exports.transform = function (file) {
file = file
.replace(MULTI_NEWLINE, EOL + EOL)
var formatted = formatter.format(file, ESFORMATTER_CONFIG)
.replace(EOL_SEMICOLON, EOL)
.replace(SOF_NEWLINES, '')
return formatted
}
module.exports.load = function (opts, cb) {
if (typeof opts === 'function') {
cb = opts
opts = {}
}
if (!opts) opts = {}
var root
try {
root = findRoot(process.cwd())
} catch (e) {}
var ignore = [].concat(DEFAULT_IGNORE) // globs to ignore
if (root) {
var packageOpts = require(path.join(root, 'package.json')).standard
if (packageOpts) ignore = ignore.concat(packageOpts.ignore)
}
if (opts.ignore) ignore = ignore.concat(opts.ignore)
ignore = ignore.map(function (pattern) {
return new Minimatch(pattern)
})
glob('**/*.js', {
cwd: opts.cwd || process.cwd()
}, function (err, files) {
if (err) return cb(err)
files = files.filter(function (file) {
return !ignore.some(function (mm) {
return mm.match(file)
})
}).map(function (f) {
return { name: f, data: fs.readFileSync(f).toString() } // assume utf8
})
cb(null, files)
})
}
|
// A $( document ).ready() block.
$( document ).ready(function() {
console.log( "ready!" );
// $('#startQuiz').addClass('dl-layout__tab mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button--colored"');
// if($('input[name=answer]:checked').length){
//a radio button was checked
// $(dialog).show();
//}else{
//there was no radio button checked
// $(dialog).hide();
//}
$('.startQuiz').on('click', function ( ) {
$('#meSsage').hide();
})
$('ul.answers > li, .responses').addClass('animated fadeInLeftBig options fast');
$('.button').addClass('animated fadeInUpBig options fast');
});
|
'use strict';
const packageData = require('../../package.json');
const shared = require('../shared');
/**
* Generates a Transport object for Sendmail
*
* Possible options can be the following:
*
* * **path** optional path to sendmail binary
* * **newline** either 'windows' or 'unix'
* * **args** an array of arguments for the sendmail binary
*
* @constructor
* @param {Object} optional config parameter for the AWS Sendmail service
*/
class JSONTransport {
constructor(options) {
options = options || {};
this.options = options || {};
this.name = 'JSONTransport';
this.version = packageData.version;
this.logger = shared.getLogger(this.options, {
component: this.options.component || 'json-transport'
});
}
/**
* <p>Compiles a mailcomposer message and forwards it to handler that sends it.</p>
*
* @param {Object} emailMessage MailComposer object
* @param {Function} callback Callback function to run when the sending is completed
*/
send(mail, done) {
// Sendmail strips this header line by itself
mail.message.keepBcc = true;
let envelope = mail.data.envelope || mail.message.getEnvelope();
let messageId = mail.message.messageId();
let recipients = [].concat(envelope.to || []);
if (recipients.length > 3) {
recipients.push('...and ' + recipients.splice(2).length + ' more');
}
this.logger.info(
{
tnx: 'send',
messageId
},
'Composing JSON structure of %s to <%s>',
messageId,
recipients.join(', ')
);
setImmediate(() => {
mail.resolveAll((err, data) => {
if (err) {
this.logger.error(
{
err,
tnx: 'send',
messageId
},
'Failed building JSON structure for %s. %s',
messageId,
err.message
);
return done(err);
}
data.messageId = messageId;
['html', 'text', 'watchHtml'].forEach(key => {
if (data[key] && data[key].content) {
if (typeof data[key].content === 'string') {
data[key] = data[key].content;
} else if (Buffer.isBuffer(data[key].content)) {
data[key] = data[key].content.toString();
}
}
});
if (data.icalEvent && Buffer.isBuffer(data.icalEvent.content)) {
data.icalEvent.content = data.icalEvent.content.toString('base64');
data.icalEvent.encoding = 'base64';
}
if (data.alternatives && data.alternatives.length) {
data.alternatives.forEach(alternative => {
if (alternative && alternative.content && Buffer.isBuffer(alternative.content)) {
alternative.content = alternative.content.toString('base64');
alternative.encoding = 'base64';
}
});
}
if (data.attachments && data.attachments.length) {
data.attachments.forEach(attachment => {
if (attachment && attachment.content && Buffer.isBuffer(attachment.content)) {
attachment.content = attachment.content.toString('base64');
attachment.encoding = 'base64';
}
});
}
return done(null, {
envelope: mail.data.envelope || mail.message.getEnvelope(),
messageId,
message: JSON.stringify(data)
});
});
});
}
}
module.exports = JSONTransport;
|
'use strict';
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _lodash = require('lodash');
var _lodash2 = _interopRequireDefault(_lodash);
var _mapping_overrides = require('./mapping_overrides');
var _mapping_overrides2 = _interopRequireDefault(_mapping_overrides);
module.exports = function initDefaultFieldProps(fields) {
if (fields === undefined || !_lodash2['default'].isArray(fields)) {
throw new Error('requires an array argument');
}
var results = [];
_lodash2['default'].forEach(fields, function (field) {
var newField = _lodash2['default'].cloneDeep(field);
results.push(newField);
if (newField.type === 'string') {
_lodash2['default'].defaults(newField, {
indexed: true,
analyzed: true,
doc_values: false,
scripted: false,
count: 0
});
results.push({
name: newField.name + '.keyword',
type: 'string',
indexed: true,
analyzed: false,
doc_values: true,
scripted: false,
count: 0
});
} else {
_lodash2['default'].defaults(newField, {
indexed: true,
analyzed: false,
doc_values: true,
scripted: false,
count: 0
});
}
if (_mapping_overrides2['default'][newField.name]) {
_lodash2['default'].assign(newField, _mapping_overrides2['default'][newField.name]);
}
});
return results;
};
|
function changeQuantity(counter){
var price = document.getElementById("item_price_"+counter).value;
var quantity = document.getElementById("item_quantity_"+counter).value;
var subtotal_price = price*quantity;
document.getElementById("subtotal_field_"+counter).innerHTML = formatNumber(subtotal_price,0,".","","","","","");
recalculateTotal();
}
function recalculateTotal(){
var total_price=0;
for (counter=0;document.getElementById("item_price_"+counter)!=null;counter++){
temporary_price=document.getElementById("item_price_"+counter).value;
temporary_quantity=document.getElementById("item_quantity_"+counter).value;
total_price = total_price*1+ temporary_price*temporary_quantity;
}
if (total_price==0){
document.getElementById("shopping_bag_content").innerHTML = '<div class="empty_row">You currently don\'t have any item in the shopping bag.</div>';
document.getElementById("submit_button").disabled = true;
$("#submit_button").animate({"opacity":"0.4"},100);
}
else{
document.getElementById("submit_button").disabled = false;
$("#submit_button").animate({"opacity":"1"},100);
}
document.getElementById("purchase_amount").value = total_price;
document.getElementById("order_footer_price").innerHTML = formatNumber(total_price,0,".","","","","","");
}
function deleteRow(counter){
$("#table_row_"+counter).animate({"height":0},300,function(){
$("#table_row_"+counter).css({"display":"none"});
var select = document.getElementById("item_quantity_"+counter);
select.options[select.options.length] = new Option('0', '0');
document.getElementById("item_quantity_"+counter).value=0;
recalculateTotal();
});
}
function formatNumber(num,dec,thou,pnt,curr1,curr2,n1,n2) {var x = Math.round(num * Math.pow(10,dec));if (x >= 0) n1=n2='';var y = (''+Math.abs(x)).split('');var z = y.length - dec; if (z<0) z--; for(var i = z; i < 0; i++) y.unshift('0'); if (z<0) z = 1; y.splice(z, 0, pnt); if(y[0] == pnt) y.unshift('0'); while (z > 3) {z-=3; y.splice(z,0,thou);}var r = curr1+n1+y.join('')+n2+curr2;return r;}
|
'use strict';
var Compiler = require('./compiler');
var EventEmitter = require('events').EventEmitter;
var util = require('util');
var directTransport = require('nodemailer-direct-transport');
var smtpTransport = require('nodemailer-smtp-transport');
var packageData = require('../package.json');
// Export createTransport method
module.exports.createTransport = function(transporter) {
transporter = transporter || directTransport({
debug: true
});
if (typeof transporter.send !== 'function') {
transporter = smtpTransport(transporter);
}
return new Nodemailer(transporter);
};
/**
* Creates an object for exposing the Nodemailer API
*
* @constructor
* @param {Object} transporter Transport object instance to pass the mails to
*/
function Nodemailer(transporter) {
EventEmitter.call(this);
this._plugins = {
compile: [],
stream: []
};
this.transporter = transporter;
if (typeof transporter.on === 'function') {
this.transporter.on('log', function() {
var args = Array.prototype.slice.call(arguments);
args.unshift('log');
this.emit.apply(this, args);
}.bind(this));
this.transporter.on('error', function(err) {
this.emit('error', err);
}.bind(this));
}
}
util.inherits(Nodemailer, EventEmitter);
Nodemailer.prototype.use = function(step, plugin) {
step = (step || '').toString();
if (!this._plugins.hasOwnProperty(step)) {
this._plugins[step] = [plugin];
} else {
this._plugins[step].push(plugin);
}
};
/**
* Optional close method, passed to the underlying transport object
*/
Nodemailer.prototype.close = function( /* possible arguments */ ) {
var args = Array.prototype.slice.call(arguments);
if (typeof this.transporter.close === 'function') {
this.transporter.close.apply(this.transporter, args);
}
};
/**
* Sends an email using the preselected transport object
*
* @param {Object} data E-data description
* @param {Function} callback Callback to run once the sending succeeded or failed
*/
Nodemailer.prototype.sendMail = function(data, callback) {
data = data || {};
data.headers = data.headers || {};
callback = callback || function() {};
var mail = {
data: data,
message: null
};
this._processPlugins('compile', mail, function(err) {
if (err) {
return callback(err);
}
mail.message = new Compiler(mail.data).compile();
if (mail.data.xMailer !== false) {
mail.message.setHeader('X-Mailer', mail.data.xMailer || this._getVersionString());
}
this._processPlugins('stream', mail, function(err) {
if (err) {
return callback(err);
}
this.transporter.send(mail, callback);
}.bind(this));
}.bind(this));
};
Nodemailer.prototype._getVersionString = function() {
return util.format(
'%s (%s; +%s; %s/%s)',
packageData.name,
packageData.version,
packageData.homepage,
this.transporter.name,
this.transporter.version
);
};
Nodemailer.prototype._processPlugins = function(step, mail, callback) {
step = (step || '').toString();
if (!this._plugins.hasOwnProperty(step) || !this._plugins[step].length) {
return callback(null);
}
var plugins = Array.prototype.slice.call(this._plugins[step]);
var processPlugins = function() {
if (!plugins.length) {
return callback(null);
}
var plugin = plugins.shift();
plugin(mail, function(err) {
if (err) {
return callback(err);
}
processPlugins();
});
}.bind(this);
processPlugins();
};
|
function getAjaxResponse(target,followurl){
target.innerHTML="We are working ... Please wait...";
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
target.innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET",followurl,true);
xmlhttp.send();
}
function validateNumeric(obj){
var re = /^\d*$/;
if(obj.value!=obj.value.match(re)){
obj.value='';
alert('Please enter only numeric values');
}
}
function validateDate(obj){
if(obj.value==''){
return;
}
var re = /^\d\d\/\d\d\/\d\d\d\d$/;
if(obj.value!=obj.value.match(re)){
obj.value='';
alert('Please enter date in proper format.(dd/mm/YYYY)');
}
}
function validateDecimal(obj){
var re = /^\d*\.?\d*$/;
if(obj.value!=obj.value.match(re)){
obj.value='';
alert('Please enter only numeric values');
}
}
|
define("dojox/lang/functional/fold", ["dojo/_base/lang", "dojo/_base/array", "dojo/_base/kernel", "./lambda"],
function(lang, arr, kernel, df){
// This module adds high-level functions and related constructs:
// - "fold" family of functions
// Notes:
// - missing high-level functions are provided with the compatible API:
// foldl, foldl1, foldr, foldr1
// - missing JS standard functions are provided with the compatible API:
// reduce, reduceRight
// - the fold's counterpart: unfold
// Defined methods:
// - take any valid lambda argument as the functional argument
// - operate on dense arrays
// - take a string as the array argument
// - take an iterator objects as the array argument (only foldl, foldl1, and reduce)
var empty = {};
lang.mixin(df, {
// classic reduce-class functions
foldl: function(/*Array|String|Object*/ a, /*Function*/ f, /*Object*/ z, /*Object?*/ o){
// summary:
// repeatedly applies a binary function to an array from left
// to right using a seed value as a starting point; returns the final
// value.
if(typeof a == "string"){ a = a.split(""); }
o = o || kernel.global; f = df.lambda(f);
var i, n;
if(lang.isArray(a)){
// array
for(i = 0, n = a.length; i < n; z = f.call(o, z, a[i], i, a), ++i);
}else if(typeof a.hasNext == "function" && typeof a.next == "function"){
// iterator
for(i = 0; a.hasNext(); z = f.call(o, z, a.next(), i++, a));
}else{
// object/dictionary
for(i in a){
if(!(i in empty)){
z = f.call(o, z, a[i], i, a);
}
}
}
return z; // Object
},
foldl1: function(/*Array|String|Object*/ a, /*Function|String|Array*/ f, /*Object?*/ o){
// summary:
// repeatedly applies a binary function to an array from left
// to right; returns the final value.
if(typeof a == "string"){ a = a.split(""); }
o = o || kernel.global; f = df.lambda(f);
var z, i, n;
if(lang.isArray(a)){
// array
z = a[0];
for(i = 1, n = a.length; i < n; z = f.call(o, z, a[i], i, a), ++i);
}else if(typeof a.hasNext == "function" && typeof a.next == "function"){
// iterator
if(a.hasNext()){
z = a.next();
for(i = 1; a.hasNext(); z = f.call(o, z, a.next(), i++, a));
}
}else{
// object/dictionary
var first = true;
for(i in a){
if(!(i in empty)){
if(first){
z = a[i];
first = false;
}else{
z = f.call(o, z, a[i], i, a);
}
}
}
}
return z; // Object
},
foldr: function(/*Array|String*/ a, /*Function|String|Array*/ f, /*Object*/ z, /*Object?*/ o){
// summary:
// repeatedly applies a binary function to an array from right
// to left using a seed value as a starting point; returns the final
// value.
if(typeof a == "string"){ a = a.split(""); }
o = o || kernel.global; f = df.lambda(f);
for(var i = a.length; i > 0; --i, z = f.call(o, z, a[i], i, a));
return z; // Object
},
foldr1: function(/*Array|String*/ a, /*Function|String|Array*/ f, /*Object?*/ o){
// summary:
// repeatedly applies a binary function to an array from right
// to left; returns the final value.
if(typeof a == "string"){ a = a.split(""); }
o = o || kernel.global; f = df.lambda(f);
var n = a.length, z = a[n - 1], i = n - 1;
for(; i > 0; --i, z = f.call(o, z, a[i], i, a));
return z; // Object
},
// JS 1.8 standard array functions, which can take a lambda as a parameter.
reduce: function(/*Array|String|Object*/ a, /*Function|String|Array*/ f, /*Object?*/ z){
// summary:
// apply a function simultaneously against two values of the array
// (from left-to-right) as to reduce it to a single value.
return arguments.length < 3 ? df.foldl1(a, f) : df.foldl(a, f, z); // Object
},
reduceRight: function(/*Array|String*/ a, /*Function|String|Array*/ f, /*Object?*/ z){
// summary:
// apply a function simultaneously against two values of the array
// (from right-to-left) as to reduce it to a single value.
return arguments.length < 3 ? df.foldr1(a, f) : df.foldr(a, f, z); // Object
},
// the fold's counterpart: unfold
unfold: function(/*Function|String|Array*/ pr, /*Function|String|Array*/ f,
/*Function|String|Array*/ g, /*Object*/ z, /*Object?*/ o){
// summary:
// builds an array by unfolding a value
o = o || kernel.global; f = df.lambda(f); g = df.lambda(g); pr = df.lambda(pr);
var t = [];
for(; !pr.call(o, z); t.push(f.call(o, z)), z = g.call(o, z));
return t; // Array
}
});
});
|
var group__rcm =
[
[ "RCM HAL driver", "group__rcm__hal.html", "group__rcm__hal" ]
];
|
define(function (require) {
var zrUtil = require('zrender/core/util');
require('../coord/cartesian/Grid');
require('./bar/BarSeries');
require('./bar/BarView');
var barLayoutGrid = require('../layout/barGrid');
var echarts = require('../echarts');
echarts.registerLayout(zrUtil.curry(barLayoutGrid, 'bar'));
// Visual coding for legend
echarts.registerVisualCoding('chart', function (ecModel) {
ecModel.eachSeriesByType('bar', function (seriesModel) {
var data = seriesModel.getData();
data.setVisual('legendSymbol', 'roundRect');
});
});
});
|
/**
* @ngdoc service
* @name Bastion.hosts.factory:Host
*
* @requires BastionResource
*
* @description
* Provides a BastionResource for one or more hosts.
*/
angular.module('Bastion.hosts').factory('Host',
['BastionResource', function (BastionResource) {
var resource = BastionResource('/api/v2/hosts/:id/:action', {id: '@id'}, {
postIndex: {method: 'POST', params: {action: 'post_index'}},
update: {method: 'PUT'},
updateHostCollections: {method: 'PUT', params: {action: 'host_collections'}},
autocomplete: {method: 'GET', isArray: true, params: {id: 'auto_complete_search'}}
});
resource.prototype.hasContent = function () {
return angular.isDefined(this.content_facet_attributes) && angular.isDefined(this.content_facet_attributes.uuid);
};
resource.prototype.hasSubscription = function () {
return angular.isDefined(this.subscription_facet_attributes) && angular.isDefined(this.subscription_facet_attributes.uuid);
};
return resource;
}]
);
/**
* @ngdoc service
* @name Bastion.hosts.factory:HostBulkAction
*
* @requires BastionResource
*
* @description
* Provides a BastionResource for bulk actions on hosts.
*/
angular.module('Bastion.hosts').factory('HostBulkAction',
['BastionResource', function (BastionResource) {
return BastionResource('/api/v2/hosts/bulk/:action', {}, {
addHostCollections: {method: 'PUT', params: {action: 'add_host_collections'}},
installableErrata: {method: 'POST', params: {action: 'installable_errata'}},
removeHostCollections: {method: 'PUT', params: {action: 'remove_host_collections'}},
installContent: {method: 'PUT', params: {action: 'install_content'}},
updateContent: {method: 'PUT', params: {action: 'update_content'}},
removeContent: {method: 'PUT', params: {action: 'remove_content'}},
destroyHosts: {method: 'PUT', params: {action: 'destroy'}},
environmentContentView: {method: 'PUT', params: {action: 'environment_content_view'}},
availableIncrementalUpdates: {method: 'POST', isArray: true, params: {action: 'available_incremental_updates'}}
});
}]
);
|
scnShortcodeMeta={
attributes:[
{
label:"Alert content",
id:"content",
isRequired:true
},
{
label:"Title",
id:"title",
},
{
label:"Style",
id:"style",
help:"",
controlType:"select-control",
selectValues:['default','success', 'error', 'info', 'warning', 'grey']
},
],
shortcode:"alert"
};
|
goog.require('ol.Map');
goog.require('ol.Overlay');
goog.require('ol.Sphere');
goog.require('ol.View');
goog.require('ol.geom.LineString');
goog.require('ol.geom.Polygon');
goog.require('ol.interaction.Draw');
goog.require('ol.layer.Tile');
goog.require('ol.layer.Vector');
goog.require('ol.proj');
goog.require('ol.source.MapQuest');
goog.require('ol.source.Vector');
goog.require('ol.style.Circle');
goog.require('ol.style.Fill');
goog.require('ol.style.Stroke');
goog.require('ol.style.Style');
|
var dotclear = {};
dotclear.img_plus_src = '../../admin/images/expand.png';
dotclear.img_plus_alt = 'uncover';
dotclear.img_minus_src = '../../admin/images/hide.png';
dotclear.img_minus_alt = 'hide';
jQuery.fn.toggleWithLegend = function(target,s) {
var defaults = {
img_on_src: dotclear.img_plus_src,
img_on_alt: dotclear.img_plus_alt,
img_off_src: dotclear.img_minus_src,
img_off_alt: dotclear.img_minus_alt,
hide: true,
speed: 0,
legend_click: false,
fn: false, // A function called on first display,
cookie: false,
reverse_cookie: false // Reverse cookie behavior
};
var p = jQuery.extend(defaults,s);
if (!target) { return this; }
var set_cookie = p.hide ^ p.reverse_cookie;
if (p.cookie && jQuery.cookie(p.cookie)) {
p.hide = p.reverse_cookie;
}
var toggle = function(i,speed) {
speed = speed || 0;
if (p.hide) {
$(i).get(0).src = p.img_on_src;
$(i).get(0).alt = p.img_on_alt;
target.hide(speed);
} else {
$(i).get(0).src = p.img_off_src;
$(i).get(0).alt = p.img_off_alt;
target.show(speed);
if (p.fn) {
p.fn.apply(target);
p.fn = false;
}
}
if (p.cookie && set_cookie) {
if (p.hide ^ p.reverse_cookie) {
jQuery.cookie(p.cookie,'',{expires: -1});
} else {
jQuery.cookie(p.cookie,1,{expires: 30});
}
}
p.hide = !p.hide;
};
return this.each(function() {
var i = document.createElement('img');
i.src = p.img_off_src;
i.alt = p.img_off_alt;
var a = document.createElement('a');
a.href= '#';
$(a).append(i);
$(a).css({
border: 'none',
outline: 'none'
});
var ctarget = p.legend_click ? this : a;
$(ctarget).css('cursor','pointer');
if (p.legend_click) {
$(ctarget).find('label').css('cursor','pointer');
}
$(ctarget).click(function() {
toggle(i,p.speed);
return false;
});
toggle($(i).get(0));
$(this).prepend(' ').prepend(a);
});
};
|
/*jshint strict:true, browser:true, curly:true, eqeqeq:true, expr:true, forin:true, latedef:true, newcap:true, noarg:true, trailing: true, undef:true, unused:true */
/*global Drupal: true, jQuery: true*/
/**
* @file
* Decimal comma validator.
*/
(function($, document, Drupal, window) {
"use strict";
//Define a Drupal behaviour with a custom name
Drupal.behaviors.cvFAPIRegexMatchPCRE = {
attach: function(context) {
var fn = Drupal.cvHelpers.debounce(function(value, element, param, validator) {
$.ajax({
'url': Drupal.settings.basePath + 'clientside_validation/regex-pcre',
'type': "POST",
'data': {
'value': value,
'param': param
},
'dataType': 'json',
'success': function(response) {
var valid = response.result === true || response.result === "true",
errors, message, submitted;
if (valid) {
submitted = validator.formSubmitted;
validator.prepareElement(element);
validator.formSubmitted = submitted;
validator.successList.push(element);
delete validator.invalid[element.name];
validator.showErrors();
} else {
errors = {};
message = response.message || validator.defaultMessage(element, "regexMatchPCRE");
errors[element.name] = $.isFunction(message) ? message(value) : message;
validator.invalid[element.name] = true;
validator.showErrors(errors);
validator.submitted[element.name] = message;
}
validator.stopRequest(element, valid);
}
});
}, 200);
// Default regular expression support
var ajaxPCREfn = function(value, element, param) {
if ( this.optional(element) ) {
return "dependency-mismatch";
}
var validator = this;
this.startRequest(element);
fn(value, element, param, validator);
return 'pending';
};
// Regular expression support using XRegExp
var xregexPCREfn = function(value, element, param) {
if (window.XRegExp && window.XRegExp.version) {
try {
var result = true;
for (var i in param.expressions) {
if (!param.expressions.hasOwnProperty(i)) {
continue;
}
var reg = param.expressions[i];
var delim = reg.lastIndexOf(reg.charAt(0));
// Only allow supported modifiers
var modraw = reg.substr(delim + 1) || '';
var mod = '';
if (mod !== '') {
for (var l = 0; l < 6; l++) {
if (modraw.indexOf('gimnsx'[l]) !== -1) {
mod += 'gimnsx'[l];
}
}
}
reg = reg.substring(1, delim);
if (!(new XRegExp(reg, mod).test(value))) {
result = false;
if (param.messages[i].length) {
$.extend($.validator.messages, {
"regexMatchPCRE": param.messages[i]
});
}
}
}
return result;
}
catch (e) {
return ajaxPCREfn.call(this, value, element, param);
}
}
else {
return ajaxPCREfn.call(this, value, element, param);
}
};
// Add an eventlistener to the document reacting on the
// 'clientsideValidationAddCustomRules' event.
$(document).bind('clientsideValidationAddCustomRules', function(event) {
// Decide which one to use
if (Drupal.settings.clientsideValidation.general.usexregxp) {
$.validator.addMethod("regexMatchPCRE", xregexPCREfn, $.validator.format('The value does not match the expected format.'));
}
else {
$.validator.addMethod("regexMatchPCRE", ajaxPCREfn, $.validator.format('The value does not match the expected format.'));
}
});
}
};
})(jQuery, document, Drupal, window);
|
/*
* currentTarget polyfill by Jonathan Neal
* https://gist.github.com/jonathantneal/3748027#file-eventlistener-polyfill-js
*/
!window.addEventListener && (function (WindowPrototype, DocumentPrototype, ElementPrototype, addEventListener, removeEventListener, dispatchEvent, registry) {
WindowPrototype[addEventListener] = DocumentPrototype[addEventListener] = ElementPrototype[addEventListener] = function (type, listener) {
var target = this;
registry.unshift([target, type, listener, function (event) {
event.currentTarget = target;
event.preventDefault = function () { event.returnValue = false };
event.stopPropagation = function () { event.cancelBubble = true };
event.target = event.srcElement || target;
listener.call(target, event);
}]);
this.attachEvent("on" + type, registry[0][3]);
};
WindowPrototype[removeEventListener] = DocumentPrototype[removeEventListener] = ElementPrototype[removeEventListener] = function (type, listener) {
for (var index = 0, register; register = registry[index]; ++index) {
if (register[0] == this && register[1] == type && register[2] == listener) {
return this.detachEvent("on" + type, registry.splice(index, 1)[0][3]);
}
}
};
WindowPrototype[dispatchEvent] = DocumentPrototype[dispatchEvent] = ElementPrototype[dispatchEvent] = function (eventObject) {
return this.fireEvent("on" + eventObject.type, eventObject);
};
})(Window.prototype, HTMLDocument.prototype, Element.prototype, "addEventListener", "removeEventListener", "dispatchEvent", []);
/*
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice
*/
/**
* Shim for "fixing" IE's lack of support (IE < 9) for applying slice
* on host objects like NamedNodeMap, NodeList, and HTMLCollection
* (technically, since host objects have been implementation-dependent,
* at least before ES6, IE hasn't needed to work this way).
* Also works on strings, fixes IE < 9 to allow an explicit undefined
* for the 2nd argument (as in Firefox), and prevents errors when
* called on other DOM objects.
*/
(function () {
'use strict';
var _slice = Array.prototype.slice;
try {
// Can't be used with DOM elements in IE < 9
_slice.call(document.documentElement);
} catch (e) { // Fails in IE < 9
// This will work for genuine arrays, array-like objects,
// NamedNodeMap (attributes, entities, notations),
// NodeList (e.g., getElementsByTagName), HTMLCollection (e.g., childNodes),
// and will not fail on other DOM objects (as do DOM elements in IE < 9)
Array.prototype.slice = function(begin, end) {
// IE < 9 gets unhappy with an undefined end argument
end = (typeof end !== 'undefined') ? end : this.length;
// For native Array objects, we use the native slice function
if (Object.prototype.toString.call(this) === '[object Array]'){
return _slice.call(this, begin, end);
}
// For array like object we handle it ourselves.
var i, cloned = [],
size, len = this.length;
// Handle negative value for "begin"
var start = begin || 0;
start = (start >= 0) ? start : Math.max(0, len + start);
// Handle negative value for "end"
var upTo = (typeof end == 'number') ? Math.min(end, len) : len;
if (end < 0) {
upTo = len + end;
}
// Actual expected size of the slice
size = upTo - start;
if (size > 0) {
cloned = new Array(size);
if (this.charAt) {
for (i = 0; i < size; i++) {
cloned[i] = this.charAt(start + i);
}
} else {
for (i = 0; i < size; i++) {
cloned[i] = this[start + i];
}
}
}
return cloned;
};
}
}());
|
'use strict';
var cluster = require('cluster');
if (cluster.isMaster) {
// Count the machine's CPUs
var cpuCount = require('os').cpus().length;
if(cpuCount>1)
cpuCount=cpuCount-1;
console.log("Forking "+cpuCount+" albumart workers");
// Create a worker for each CPU
for (var i = 0; i < cpuCount; i += 1) {
cluster.fork();
}
}
else {
var express = require('express');
console.log("Starting albumart workers");
var albumart = require(__dirname + '/albumart.js');
var app = express();
albumart.setFolder(process.argv[3]);
app.get('/albumart', albumart.processExpressRequest);
app.use(function (err, req, res, next) {
/**
* Replace with Winston logging
**/
console.log('An internal error occurred while serving an albumart. Details: ' + err.stack);
/**
* Sending back error code 500
**/
try{
res.sendFile(__dirname + '/default.jpg');
} catch(e) {
res.sendFile(__dirname + '/default.png');
}
});
app.listen(process.argv[2]);
}
cluster.on('exit', function (worker) {
// Replace the dead worker,
// we're not sentimental
console.log('Worker %d died :(', worker.id);
cluster.fork();
});
|
module.exports = elementorModules.ViewModule.extend( {
$element: null,
editorListeners: null,
onElementChange: null,
onEditSettingsChange: null,
onPageSettingsChange: null,
isEdit: null,
__construct: function( settings ) {
if ( ! this.isActive( settings ) ) {
return;
}
this.$element = settings.$element;
this.isEdit = this.$element.hasClass( 'elementor-element-edit-mode' );
if ( this.isEdit ) {
this.addEditorListeners();
}
},
isActive: function() {
return true;
},
findElement: function( selector ) {
var $mainElement = this.$element;
return $mainElement.find( selector ).filter( function() {
return jQuery( this ).closest( '.elementor-element' ).is( $mainElement );
} );
},
getUniqueHandlerID: function( cid, $element ) {
if ( ! cid ) {
cid = this.getModelCID();
}
if ( ! $element ) {
$element = this.$element;
}
return cid + $element.attr( 'data-element_type' ) + this.getConstructorID();
},
initEditorListeners: function() {
var self = this;
self.editorListeners = [
{
event: 'element:destroy',
to: elementor.channels.data,
callback: function( removedModel ) {
if ( removedModel.cid !== self.getModelCID() ) {
return;
}
self.onDestroy();
},
},
];
if ( self.onElementChange ) {
const elementType = self.getWidgetType() || self.getElementType();
let eventName = 'change';
if ( 'global' !== elementType ) {
eventName += ':' + elementType;
}
self.editorListeners.push( {
event: eventName,
to: elementor.channels.editor,
callback: function( controlView, elementView ) {
var elementViewHandlerID = self.getUniqueHandlerID( elementView.model.cid, elementView.$el );
if ( elementViewHandlerID !== self.getUniqueHandlerID() ) {
return;
}
self.onElementChange( controlView.model.get( 'name' ), controlView, elementView );
},
} );
}
if ( self.onEditSettingsChange ) {
self.editorListeners.push( {
event: 'change:editSettings',
to: elementor.channels.editor,
callback: function( changedModel, view ) {
if ( view.model.cid !== self.getModelCID() ) {
return;
}
self.onEditSettingsChange( Object.keys( changedModel.changed )[ 0 ] );
},
} );
}
[ 'page' ].forEach( function( settingsType ) {
var listenerMethodName = 'on' + settingsType[ 0 ].toUpperCase() + settingsType.slice( 1 ) + 'SettingsChange';
if ( self[ listenerMethodName ] ) {
self.editorListeners.push( {
event: 'change',
to: elementor.settings[ settingsType ].model,
callback: function( model ) {
self[ listenerMethodName ]( model.changed );
},
} );
}
} );
},
getEditorListeners: function() {
if ( ! this.editorListeners ) {
this.initEditorListeners();
}
return this.editorListeners;
},
addEditorListeners: function() {
var uniqueHandlerID = this.getUniqueHandlerID();
this.getEditorListeners().forEach( function( listener ) {
elementorFrontend.addListenerOnce( uniqueHandlerID, listener.event, listener.callback, listener.to );
} );
},
removeEditorListeners: function() {
var uniqueHandlerID = this.getUniqueHandlerID();
this.getEditorListeners().forEach( function( listener ) {
elementorFrontend.removeListeners( uniqueHandlerID, listener.event, null, listener.to );
} );
},
getElementType: function() {
return this.$element.data( 'element_type' );
},
getWidgetType: function() {
const widgetType = this.$element.data( 'widget_type' );
if ( ! widgetType ) {
return;
}
return widgetType.split( '.' )[ 0 ];
},
getID: function() {
return this.$element.data( 'id' );
},
getModelCID: function() {
return this.$element.data( 'model-cid' );
},
getElementSettings: function( setting ) {
let elementSettings = {};
const modelCID = this.getModelCID();
if ( this.isEdit && modelCID ) {
const settings = elementorFrontend.config.elements.data[ modelCID ],
attributes = settings.attributes;
let type = attributes.widgetType || attributes.elType;
if ( attributes.isInner ) {
type = 'inner-' + type;
}
let settingsKeys = elementorFrontend.config.elements.keys[ type ];
if ( ! settingsKeys ) {
settingsKeys = elementorFrontend.config.elements.keys[ type ] = [];
jQuery.each( settings.controls, ( name, control ) => {
if ( control.frontend_available ) {
settingsKeys.push( name );
}
} );
}
jQuery.each( settings.getActiveControls(), function( controlKey ) {
if ( -1 !== settingsKeys.indexOf( controlKey ) ) {
let value = attributes[ controlKey ];
if ( value.toJSON ) {
value = value.toJSON();
}
elementSettings[ controlKey ] = value;
}
} );
} else {
elementSettings = this.$element.data( 'settings' ) || {};
}
return this.getItems( elementSettings, setting );
},
getEditSettings: function( setting ) {
var attributes = {};
if ( this.isEdit ) {
attributes = elementorFrontend.config.elements.editSettings[ this.getModelCID() ].attributes;
}
return this.getItems( attributes, setting );
},
getCurrentDeviceSetting: function( settingKey ) {
return elementorFrontend.getCurrentDeviceSetting( this.getElementSettings(), settingKey );
},
onInit: function() {
if ( this.isActive( this.getSettings() ) ) {
elementorModules.ViewModule.prototype.onInit.apply( this, arguments );
}
},
onDestroy: function() {
if ( this.isEdit ) {
this.removeEditorListeners();
}
if ( this.unbindEvents ) {
this.unbindEvents();
}
},
} );
|
/*
* Copyright (C) 2012 Krawler Information Systems Pvt Ltd
* All rights reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
Wtf.ChartNode = function(config){
Wtf.ChartNode.superclass.constructor.call(this, config);
};
Wtf.extend(Wtf.ChartNode, Wtf.Component, {
bodyStyle : "",
blankString: String.fromCharCode(160),
blockId: "block_",
detailsIcon: "details_icon",
editIcon: "edit_icon",
handleclass: " handle",
idprefix: "tree_",
mainDivStyle : "block",
mapIcon: "map_icon",
nodeClass : "blocknode",
nodeid : "",
parentid: "",
treeclass: "tree",
unmapIcon: "unmap_icon",
initComponent: function(){
Wtf.ChartNode.superclass.initComponent.call(this);
this.addEvents({
"dblclick": true // fired when double clicked for adding the unmapped node to the node in the chart [displays the mapped nodes grid]
});
},
onRender: function(config){
Wtf.ChartNode.superclass.onRender.call(this,config);
// cls keyword is used instead of class keyword to show chat window in IE
this.elDom = Wtf.DomHelper.append(this.renderTo,{
tag: "div", id: this.idprefix + this.nodeid, cls: this.treeclass, children: [{
tag: "div", id: "node_" + this.nodeid, cls: this.nodeClass, children: [{
tag: "div", cls: "leftlink", html: this.blankString
}, {
tag: "div", cls: "rightlink", html: this.blankString
}, {
tag: 'div', id: this.blockId + this.nodeid, cls: this.mainDivStyle, children: [{
tag : "div", cls : "blocktop " + this.handleclass, children : [{
tag : "span", id: "name_" + this.handleclass, html : "<div wtf:qtip=\""+this.nodeNameTip+"\"wtf:qtitle='"+WtfGlobal.getLocaleText("hrms.common.node.title")+"'>"+this.nodeName+"</div>"
}]
}, {
tag : "div", cls : "blockbottom", children : [{
tag : "span", id: "desc_" + this.nodeid, html : "<div wtf:qtip=\""+this.nodeDesignationTip+"\"wtf:qtitle='"+WtfGlobal.getLocaleText("hrms.common.node.role.title")+"'>"+this.nodeDesignation+"</div>"
}, {
tag : "a" , title : WtfGlobal.getLocaleText("hrms.common.EditUser"), cls : this.detailsIcon, children : [{
tag : "span", html : ""
}]
}, {
tag : "a" , title : WtfGlobal.getLocaleText("hrms.common.map.node"), cls : this.mapIcon, children : [{
tag : "span", html : ""
}]
}, {
tag : "a" , title : WtfGlobal.getLocaleText("hrms.common.edit.parent"), cls : this.editIcon, children : [{
tag : "span", html : ""
}]
}, {
tag : "a" , title : WtfGlobal.getLocaleText("hrms.common.unmap.node"), cls : this.unmapIcon, children : [{
tag : "span", html : ""
}]
}]
}]
}, {
tag: "div", cls: "bottomlink", html: this.blankString
}]
}]
},true);
this.elDom.on('dblclick',this.onDblClick,this);
this.elDom.on('click',this.onClick,this);
},
onClick: function(e, el, opt) {
if(e) {
var className = e.target.className;
switch(className) {
case "details_icon" :
this.fireEvent("editUserClicked", this, e);
break;
case "map_icon" :
this.fireEvent("mapClicked", this, e);
break;
case "edit_icon" :
this.fireEvent("editClicked", this, e);
break;
case "unmap_icon" :
this.fireEvent("unmapClicked", this, e);
break;
}
}
},
onDblClick : function(e) {
if(e) {
this.fireEvent("unMappedNodeDblClick", this, e, true);
}
}
});
Wtf.reg('ChartNode', Wtf.ChartNode);
|
define('ghost-admin/initializers/trailing-history', ['exports', 'ember-locations/history'], function (exports, _emberLocationsHistory) {
var trailingHistory = _emberLocationsHistory['default'].extend({
formatURL: function formatURL() {
var url = this._super.apply(this, arguments);
if (url.indexOf('?') > 0) {
return url.replace(/([^\/])\?/, '$1/?');
} else {
return url.replace(/\/?$/, '/');
}
}
});
exports['default'] = {
name: 'registerTrailingLocationHistory',
initialize: function initialize(application) {
application.register('location:trailing-history', trailingHistory);
}
};
});
|
/* -*- tab-width: 2; indent-tabs-mode: nil; js-indent-level: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/**
File Name: 15.9.5.23-3-n.js
ECMA Section: 15.9.5.23
Description: Date.prototype.setTime
1. If the this value is not a Date object, generate a runtime error.
2. Call ToNumber(time).
3. Call TimeClip(Result(1)).
4. Set the [[Value]] property of the this value to Result(2).
5. Return the value of the [[Value]] property of the this value.
Author: christine@netscape.com
Date: 12 november 1997
*/
var SECTION = "15.9.5.23-3-n";
var VERSION = "ECMA_1";
startTest();
var TITLE = "Date.prototype.setTime()";
writeHeaderToLog( SECTION + " "+ TITLE);
var MYDATE = new MyDate(TIME_1970);
DESCRIPTION = "MYDATE.setTime(TIME_2000)";
EXPECTED = "error";
new TestCase( SECTION,
"MYDATE.setTime(TIME_2000)",
"error",
eval("MYDATE.setTime(TIME_2000)") );
test();
function MyDate(value) {
this.value = value;
this.setTime = Date.prototype.setTime;
return this;
}
|
import React from 'react';
import Analyzer from 'parser/core/Analyzer';
import SPELLS from 'common/SPELLS/index';
import TalentStatisticBox from 'interface/others/TalentStatisticBox';
import STATISTIC_ORDER from 'interface/others/STATISTIC_ORDER';
import { formatNumber, formatPercentage } from 'common/format';
//WCL: https://www.warcraftlogs.com/reports/7DNACRhnaKzBfHLM/#fight=1&source=19
class FeastOfSouls extends Analyzer {
heal = 0;
overHeal = 0;
constructor(...args) {
super(...args);
this.active = this.selectedCombatant.hasTalent(SPELLS.FEAST_OF_SOULS_TALENT.id);
}
on_byPlayer_heal(event) {
const spellID = event.ability.guid;
if (spellID !== SPELLS.FEAST_OF_SOULS_HEAL.id) {
return;
}
this.heal += event.amount;
this.overHeal += event.overheal || 0;
}
statistic() {
const overHealPercent = this.overHeal/(this.overHeal + this.heal);
return (
<TalentStatisticBox
talent={SPELLS.FEAST_OF_SOULS_TALENT.id}
position={STATISTIC_ORDER.CORE(8)}
value={this.owner.formatItemHealingDone(this.heal)}
tooltip={(
<>
This shows the extra hps that the talent provides.<br />
<strong>Effective healing:</strong> {formatNumber(this.heal)}<br />
<strong>Overhealing:</strong> {formatNumber(this.overHeal)} | {formatPercentage(overHealPercent)}%
</>
)}
/>
);
}
}
export default FeastOfSouls;
|
/*
* Copyright (C) 2016 - present Instructure, Inc.
*
* This file is part of Canvas.
*
* Canvas is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, version 3 of the License.
*
* Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import reducer from 'jsx/course_settings/reducer'
QUnit.module('Course Settings Reducer')
test('Unknown action types return initialState', () => {
const initialState = {
courseImage: 'abc'
}
const action = {
type: 'I_AM_NOT_A_REAL_ACTION'
}
const newState = reducer(initialState, action)
deepEqual(initialState, newState, 'state is unchanged')
})
test('sets the modal visibility properly', () => {
const action = {
type: 'MODAL_VISIBILITY',
payload: {
showModal: true
}
}
const initialState = {
showModal: false
}
const newState = reducer(initialState, action)
equal(newState.showModal, true, 'state is updated to show the modal')
})
test('sets uploading image properly', () => {
const action = {
type: 'UPLOADING_IMAGE'
}
const initialState = {
uploadingImage: false
}
const newState = reducer(initialState, action)
equal(newState.uploadingImage, true, 'state is updated to indicate image uploading')
})
test('sets course image properly', () => {
const action = {
type: 'GOT_COURSE_IMAGE',
payload: {
imageString: '123',
imageUrl: 'http://imageUrl'
}
}
const initialState = {
courseImage: 'abc',
imageUrl: ''
}
const newState = reducer(initialState, action)
equal(newState.courseImage, '123', 'state has the course image set')
equal(newState.imageUrl, 'http://imageUrl', 'state has the image url set')
})
test('SET_COURSE_IMAGE_ID', () => {
const action = {
type: 'SET_COURSE_IMAGE_ID',
payload: {
imageUrl: 'http://imageUrl',
imageId: 42
}
}
const initialState = {
imageUrl: '',
courseImage: '',
showModal: true
}
const newState = reducer(initialState, action)
equal(newState.imageUrl, 'http://imageUrl', 'image url gets set')
equal(newState.courseImage, '42', 'image id gets set')
equal(newState.showModal, false, 'modal gets closed')
})
test('sets removing image properly', () => {
const action = {
type: 'REMOVING_IMAGE'
}
const initialState = {
removingImage: false
}
const newState = reducer(initialState, action)
equal(newState.removingImage, true, 'state is updated to indicate removing image')
})
test('sets removed image properly', () => {
const action = {
type: 'REMOVED_IMAGE'
}
const initialState = {
imageUrl: 'http://imageUrl',
courseImage: '24',
removingImage: true
}
const newState = reducer(initialState, action)
equal(newState.imageUrl, '', 'image url gets removed')
equal(newState.courseImage, 'abc', 'course image gets cleared')
equal(newState.removingImage, false, 'no longer removing image')
})
test('sets removing image to false on error', () => {
const action = {
type: 'ERROR_REMOVING_IMAGE'
}
const initialState = {
removingImage: true
}
const newState = reducer(initialState, action)
equal(newState.removingImage, false, 'removing image set to false after error')
})
|
(function(define) {
'use strict';
define(['jquery', 'js/student_account/utils', 'jquery.cookie'], function($, Utils) {
var MultipleEnterpriseInterface = {
urls: {
learners: '/enterprise/api/v1/enterprise-learner/',
multipleEnterpriseUrl: '/enterprise/select/active/?success_url=',
enterpriseActivationUrl: '/enterprise/select/active'
},
headers: {
'X-CSRFToken': $.cookie('csrftoken')
},
/**
* Fetch the learner data, then redirect the user to a enterprise selection page if multiple
* enterprises were found.
* @param {string} nextUrl The URL to redirect to after multiple enterprise selection or incase
* the selection page is bypassed e.g. when dealing with direct enrolment urls.
*/
check: function(nextUrl, edxUserInfoCookieName) {
var view = this;
var selectionPageUrl = this.urls.multipleEnterpriseUrl + encodeURIComponent(nextUrl);
var username = Utils.userFromEdxUserCookie(edxUserInfoCookieName).username;
var next = nextUrl || '/';
var enterpriseInUrl = this.getEnterpriseFromUrl(nextUrl);
var userInEnterprise = false;
var userWithMultipleEnterprises = false;
$.ajax({
url: this.urls.learners + '?username=' + username,
type: 'GET',
contentType: 'application/json; charset=utf-8',
headers: this.headers,
context: this
}).fail(function() {
view.redirect(next);
}).done(function(response) {
userWithMultipleEnterprises = (response.count > 1);
if (userWithMultipleEnterprises) {
if (enterpriseInUrl) {
userInEnterprise = view.checkEnterpriseExists(response, enterpriseInUrl);
if (userInEnterprise) {
view.activate(enterpriseInUrl).fail(function() {
view.redirect(selectionPageUrl);
}).done(function() {
view.redirect(next);
});
} else {
view.redirect(selectionPageUrl);
}
} else {
view.redirect(selectionPageUrl);
}
} else {
view.redirect(next);
}
});
},
redirect: function(url) {
window.location.href = url;
},
activate: function(enterprise) {
return $.ajax({
url: this.urls.enterpriseActivationUrl,
method: 'POST',
headers: {'X-CSRFToken': $.cookie('csrftoken')},
data: {enterprise: enterprise}
});
},
getEnterpriseFromUrl: function(url) {
var regex;
regex = RegExp('/enterprise/.*/course/.*/enroll');
if (typeof url !== 'string' || !regex.test(url)) {
return void(0);
}
return url.split('/')[2];
},
checkEnterpriseExists: function(response, enterprise) {
return response.results.some(function(item) {
return item.enterprise_customer.uuid === enterprise;
});
}
};
return MultipleEnterpriseInterface;
});
}).call(this, define || RequireJS.define);
|
casper.echo( "OC-71: Tekstiä editoitaessa, highlightboksit jakautuvat oikein sanoja splitatessa / mergetessä" );
var settings = require('./settings');
var mytests = require('./mytests');
casper.start(settings.defaultPageUrl);
casper.then(function() {
this.test.assertExists('#editor');
});
casper.waitForText( "Pienet");
casper.then(function() {
// place cursor on 'kultahanhet'
var newCursor = this.evaluate( function () {
require('editor').view.cMirror.setCursor(6,9);
return require('editor').view.cMirror.getCursor();
});
this.test.assertEqual(newCursor.line,6, "cursor move line");
this.test.assertEqual(newCursor.ch,9, "cursor move ch");
});
casper.waitForHighlight( [ { left:215, top:552, width:178, height:34 } ] );
casper.then(function () {
this.page.sendEvent('keypress',' ');
});
casper.waitForHighlight( [ { left:375, top:552, width:17, height:34 } ] );
casper.then(function() {
// place cursor on 'kultahanhet'
var newCursor = this.evaluate( function () {
require('editor').view.cMirror.setCursor(6,9);
return require('editor').view.cMirror.getCursor();
});
this.test.assertEqual(newCursor.line,6, "cursor move line");
this.test.assertEqual(newCursor.ch,9, "cursor move ch");
});
casper.waitForHighlight( [ { left:215, top:552, width:160, height:34 } ] );
casper.then(function () {
// combine this and following words
this.page.sendEvent('keypress',this.page.event.key.Delete);
this.page.sendEvent('keypress',this.page.event.key.Right);
this.page.sendEvent('keypress',this.page.event.key.Delete);
});
casper.waitForHighlight( [ { left:164, top:552, width:287, height:34 } ],
null, function() {casper.capture('failed.png');}, 4000 );
casper.run(function() {
this.test.done();
});
|
/*******************************************************************************
* loklak-fetcher-client
* by Yago González (C) 2016 - Under MIT license
* Bugs? Questions? Don't know what's the meaning of life?
* Take a look at: github.com/YagoGG/loklak-fetcher-client
* Please, keep this header if you want to use this code. Thank you ;)
******************************************************************************/
window.loklakFetcher = (function() {
var script = null;
var loklakFetcher = {
/**
* Fetches tweets from the public loklak API, with the options provided
* @param {object} options Object with allowed GET-attributes, see
* loklak.org/api.html
* @param {function} callback Function called after getting the results.
* These are passed as first argument
*/
getTweets: function(options, callback) {
if(typeof options === 'function') { // A callback has been provided as 2nd
// argument (no options)
callback = options;
options = {};
} else if(callback === undefined) { // No callback has been provided, even
// as 2nd argument
throw new Error('[LOKLAK-FETCHER] No callback provided');
}
var settings = [ 'count', 'source', 'fields', 'limit', 'tzOffset',
'minified' ]; // Field names for all the possible parameters
var defaults = [ 100, 'cache', '', '', 0, true ]; // Default values
// Check if no options have been provided
if(typeof options === 'undefined') {
options = {}; // Create 'options' to avoid ReferenceErrors later
}
//Check if there are any data elements set
var tweetsEl = document.getElementById("tweets");
var dataset = tweetsEl.dataset;
if(dataset.count) {
options[settings[0]] = dataset.count; //count is index 0
}
var query;
if(dataset.query) {
query = dataset.query.replace(/\s/gi, '&').replace(/#/gi, '%23'); //replace spaces and hashtags in URL
} else {
query = "fossasia";
}
if(dataset.start) {
query = query + "&since:" + dataset.start;
}
if(dataset.end) {
query = query + "&until:" + dataset.end;
}
if(dataset.from) {
query = query + "&from:" + dataset.from;
}
// Write unset options as their default
for(var index in settings) {
if(options[settings[index]] === undefined) {
options[settings[index]] = defaults[index];
}
}
// Create the URL with all the parameters
var url = 'http://api.loklak.org/api/search.json' +
'?callback=loklakFetcher.handleData' +
'&q=' + query +
'&count=' + options.count +
'&source=' + options.source +
'&fields=' + options.fields +
'&limit=' + options.limit +
'&timezoneOffset=' + options.tzOffset +
'&minified=' + options.minified;
// If the script element for JSONP already exists, remove it
if(script !== null) {
document.head.removeChild(script);
}
/**
* Invokes the callback function, passing the data from the server as the
* first and only argument.
* @param {object} data JSON coming from loklak's API
*/
this.handleData = function(data) {
callback(data);
};
// Create the script tag for JSONP
script = document.createElement("script");
script.src = url;
document.head.appendChild(script);
}
};
return loklakFetcher;
}());
|
import helper from '../../src/main/js/components/source-viewer/helpers/code-with-issue-locations-helper';
let expect = require('chai').expect;
describe('Source Viewer', function () {
describe('Code With Issue Locations Helper', function () {
it('should be a function', function () {
expect(helper).to.be.a('function');
});
it('should mark one location', function () {
var code = '<span class="k">if</span> (<span class="sym-2 sym">a</span> + <span class="c">1</span>) {',
locations = [{ from: 1, to: 5 }],
result = helper(code, locations, 'x');
expect(result).to.equal([
'<span class="k">i</span>',
'<span class="k x">f</span>',
'<span class=" x"> (</span>',
'<span class="sym-2 sym x">a</span>',
'<span class=""> + </span>',
'<span class="c">1</span>',
'<span class="">) {</span>'
].join(''));
});
it('should mark two locations', function () {
var code = 'abcdefghijklmnopqrst',
locations = [
{ from: 1, to: 6 },
{ from: 11, to: 16 }
],
result = helper(code, locations, 'x');
expect(result).to.equal([
'<span class="">a</span>',
'<span class=" x">bcdef</span>',
'<span class="">ghijk</span>',
'<span class=" x">lmnop</span>',
'<span class="">qrst</span>'
].join(''));
});
it('should mark one locations', function () {
var code = '<span class="cppd"> * Copyright (C) 2008-2014 SonarSource</span>',
locations = [{ from: 15, to: 20 }],
result = helper(code, locations, 'x');
expect(result).to.equal([
'<span class="cppd"> * Copyright (C</span>',
'<span class="cppd x">) 200</span>',
'<span class="cppd">8-2014 SonarSource</span>'
].join(''));
});
it('should mark two locations', function () {
var code = '<span class="cppd"> * Copyright (C) 2008-2014 SonarSource</span>',
locations = [
{ from: 24, to: 29 },
{ from: 15, to: 20 }
],
result = helper(code, locations, 'x');
expect(result).to.equal([
'<span class="cppd"> * Copyright (C</span>',
'<span class="cppd x">) 200</span>',
'<span class="cppd">8-20</span>',
'<span class="cppd x">14 So</span>',
'<span class="cppd">narSource</span>'
].join(''));
});
it('should parse line with < and >', function () {
var code = '<span class="j">#include <stdio.h></span>',
result = helper(code, []);
expect(result).to.equal('<span class="j">#include <stdio.h></span>');
});
});
});
|
describe('HatoholNavi', function() {
var adminUser = new HatoholUserProfile({
"userId": 1,
"name": "admin",
"flags": hatohol.ALL_PRIVILEGES
});
var guestUser = new HatoholUserProfile({
"userId": 23,
"name": "guest",
"flags": 0
});
beforeEach(function() {
var nav = $("<ul/>").addClass("nav");
$("body").append(nav);
});
afterEach(function() {
$(".nav").remove();
});
it('show users against admin', function() {
var nav = new HatoholNavi(adminUser);
var links = $("a[href = 'ajax_users']");
expect(links).to.have.length(1);
expect(links[0].text).to.be(gettext("Users"));
});
it('do not show users against guest', function() {
var nav = new HatoholNavi(guestUser);
var links = $("a[href = 'ajax_users']");
expect(links).to.be.empty();
});
it('with no current page', function() {
var userProfile = new HatoholUserProfile(guestUser);
var nav = new HatoholNavi(userProfile);
var expected = '';
expected += '<li><a href="ajax_dashboard">' +
gettext('Dashboard') + '</a></li>';
expected += '<li><a href="ajax_overview_triggers">' +
gettext('Overview : Triggers') + '</a></li>';
expected += '<li><a href="ajax_overview_items">' +
gettext('Overview : Items') + '</a></li>';
expected += '<li><a href="ajax_latest">' +
gettext("Latest data") + '</a></li>';
expected += '<li><a href="ajax_triggers">' +
gettext('Triggers') + '</a></li>';
expected += '<li><a href="ajax_events">' +
gettext('Events') + '</a></li>';
expected += '<li class="dropdown">';
expected += '<a href="#" class="dropdown-toggle" data-toggle="dropdown">' +
'Settings<span class="caret"></span></a>';
expected += '<ul class="dropdown-menu">';
expected += '<li><a href="ajax_servers">' +
gettext('Monitoring Servers') + '</a></li>';
expected += '<li><a href="ajax_actions">' +
gettext('Actions') + '</a></li>';
expected += '<li><a href="ajax_graphs">' +
gettext('Graphs') + '</a></li>';
expected += '<li><a href="ajax_log_search_systems">' +
gettext('Log search systems') + '</a></li>';
expected += '</ul></li>';
expected += '<li class="dropdown">';
expected += '<a href="#" class="dropdown-toggle" data-toggle="dropdown">' +
'Help<span class="caret"></span></a>';
expected += '<ul class="dropdown-menu">';
expected += '<li><a href="http://www.hatohol.org/docs">' +
gettext('Online Documents') + '</a></li>';
expected += '<li><a href="#">' +
gettext('Hatohol version: ') + HATOHOL_VERSION + '</a></li>';
expected += '</ul></li>';
expect($("ul.nav")[0].innerHTML).to.be(expected);
});
it('with a current page argument', function() {
var nav = new HatoholNavi(guestUser, "ajax_latest");
var expected = '';
expected += '<li><a href="ajax_dashboard">' +
gettext('Dashboard') + '</a></li>';
expected += '<li><a href="ajax_overview_triggers">' +
gettext('Overview : Triggers') + '</a></li>';
expected += '<li><a href="ajax_overview_items">' +
gettext('Overview : Items') + '</a></li>';
expected += '<li class="active"><a>' +
gettext('Latest data') + '</a></li>';
expected += '<li><a href="ajax_triggers">' +
gettext('Triggers') + '</a></li>';
expected += '<li><a href="ajax_events">' +
gettext('Events') + '</a></li>';
expected += '<li class="dropdown">';
expected += '<a href="#" class="dropdown-toggle" data-toggle="dropdown">' +
'Settings<span class="caret"></span></a>';
expected += '<ul class="dropdown-menu">';
expected += '<li><a href="ajax_servers">' +
gettext('Monitoring Servers') + '</a></li>';
expected += '<li><a href="ajax_actions">' +
gettext('Actions') + '</a></li>';
expected += '<li><a href="ajax_graphs">' +
gettext('Graphs') + '</a></li>';
expected += '<li><a href="ajax_log_search_systems">' +
gettext('Log search systems') + '</a></li>';
expected += '</ul></li>';
expected += '<li class="dropdown">';
expected += '<a href="#" class="dropdown-toggle" data-toggle="dropdown">' +
'Help<span class="caret"></span></a>';
expected += '<ul class="dropdown-menu">';
expected += '<li><a href="http://www.hatohol.org/docs">' +
gettext('Online Documents') + '</a></li>';
expected += '<li><a href="#">' +
gettext('Hatohol version: ') + HATOHOL_VERSION + '</a></li>';
expected += '</ul></li>';
expect($("ul.nav")[0].innerHTML).to.be(expected);
});
});
|
'use strict';
var gulp = require('gulp'),
runSequence = require('run-sequence'),
browserifyTask = require('./browserify');
gulp.task('build', ['clean', 'test'], function() {
global.runmode = 'prod';
global.location = undefined;
runSequence(
['sass', 'images'],
['browserify', 'concatEncryption'],
'modernizr',
'version',
'zip'
);
});
|
// Copyright (C) 2015 the V8 project authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
es6id: 25.3.1.3
description: >
When a generator is paused within a `try` block of a `try..finally`
statement, `return` should interrupt control flow as if a `return`
statement had appeared at that location in the function body.
---*/
var inTry = false;
var inFinally = false;
function* g() {
try {
inTry = true;
yield;
$ERROR('This code is unreachable (within `try` block)');
} finally {
inFinally = true;
}
$ERROR('This code is unreachable (following `try` statement)');
}
var iter = g();
var result;
iter.next();
assert.sameValue(inTry, true, '`try` block code path executed');
assert.sameValue(inFinally, false, '`finally` code path not executed');
result = iter.return(45);
assert.sameValue(result.value, 45, 'Result `value` following `return`');
assert.sameValue(result.done, true, 'Result `done` flag following `return`');
assert.sameValue(inFinally, true, '`finally` code path executed');
result = iter.next();
assert.sameValue(
result.value, undefined, 'Result `value` is undefined when complete'
);
assert.sameValue(
result.done, true, 'Result `done` flag is `true` when complete'
);
|
var hasExcape = /~/
var escapeMatcher = /~[01]/g
function escapeReplacer(m) {
switch (m) {
case '~1':
return '/'
case '~0':
return '~'
}
throw new Error('Invalid tilde escape: ' + m)
}
function untilde(str) {
if (!hasExcape.test(str)) return str
return str.replace(escapeMatcher, escapeReplacer)
}
function setter(obj, pointer, value) {
var part
var hasNextPart
for (var p = 1, len = pointer.length; p < len;) {
part = untilde(pointer[p++])
hasNextPart = len > p
if (typeof obj[part] === 'undefined') {
// support setting of /-
if (Array.isArray(obj) && part === '-') {
part = obj.length
}
// support nested objects/array when setting values
if (hasNextPart) {
if ((pointer[p] !== '' && pointer[p] < Infinity) || pointer[p] === '-') obj[part] = []
else obj[part] = {}
}
}
if (!hasNextPart) break
obj = obj[part]
}
var oldValue = obj[part]
if (value === undefined) delete obj[part]
else obj[part] = value
return oldValue
}
function compilePointer(pointer) {
if (typeof pointer === 'string') {
pointer = pointer.split('/')
if (pointer[0] === '') return pointer
throw new Error('Invalid JSON pointer.')
} else if (Array.isArray(pointer)) {
return pointer
}
throw new Error('Invalid JSON pointer.')
}
function get(obj, pointer) {
if (typeof obj !== 'object') throw new Error('Invalid input object.')
pointer = compilePointer(pointer)
var len = pointer.length
if (len === 1) return obj
for (var p = 1; p < len;) {
obj = obj[untilde(pointer[p++])]
if (len === p) return obj
if (typeof obj !== 'object') return undefined
}
}
function set(obj, pointer, value) {
if (typeof obj !== 'object') throw new Error('Invalid input object.')
pointer = compilePointer(pointer)
if (pointer.length === 0) throw new Error('Invalid JSON pointer for set.')
return setter(obj, pointer, value)
}
function compile(pointer) {
var compiled = compilePointer(pointer)
return {
get: function (object) {
return get(object, compiled)
},
set: function (object, value) {
return set(object, compiled, value)
}
}
}
exports.get = get
exports.set = set
exports.compile = compile
|
"use strict";
const test = require('tape')
const android = require('..')
test('get specific version by API level', (t) => {
t.plan(1)
t.equal(android.get(24).name, "Nougat")
})
test('getAll versions by API level', (t) => {
t.plan(1)
t.equal(android.getAll(24)[0].name, "Nougat")
})
test('get specific version by predicate', (t) => {
t.plan(2)
let actual = android.get((version) => {
return version.name.indexOf("on") !== -1
})
t.equal(actual.name, "Donut")
actual = android.get((version) => {
return version.ndk > 5 && version.api < 15
})
t.equal(actual.versionCode, "HONEYCOMB_MR1")
})
test('getAll versions by predicate', (t) => {
t.plan(3)
let actual = android.getAll((version) => {
return version.name.indexOf("on") !== -1
}).map((version) => version.name)
t.deepEqual(actual, ["Donut", "Honeycomb", "Honeycomb", "Honeycomb"])
actual = android.getAll((version) => {
return version.ndk > 5 && version.api < 15
}).map((version) => version.versionCode)
t.deepEqual(actual, ["HONEYCOMB_MR1", "HONEYCOMB_MR2", "ICE_CREAM_SANDWICH"])
actual = android.getAll((version) => {
return version.api > 22
}).map((version) => version.versionCode)
t.deepEqual(actual, ["M", "N", "N_MR1", "O", "O_MR1", "P", "Q"])
})
test('get version by semantic version', (t) => {
t.plan(4)
t.equal(android.get("6.0").versionCode, android.M.versionCode)
t.equal(android.get("6.0.0").versionCode, android.M.versionCode)
t.equal(android.get("2.3").versionCode, android.GINGERBREAD.versionCode)
t.equal(android.get("2.3.3").versionCode, android.GINGERBREAD_MR1.versionCode)
})
test('support major version only', (t) => {
t.plan(2)
t.equal(android.get("9.0").versionCode, android.P.versionCode)
t.equal(android.get("9.0.0").versionCode, android.P.versionCode)
})
test('support version ranges', (t) => {
t.plan(7)
let tests = [ "4.4", "4.4.0", "4.4.1", "4.4.2", "4.4.3", "4.4.4" ]
tests.forEach((versionCode) => {
t.equal(android.get(versionCode).versionCode, android.KITKAT.versionCode)
})
t.equal(android.get("4.4.5"), null)
})
test('support x-ranges', (t) => {
t.plan(12)
let tests = [
"4.1", "4.1.0", "4.1.1", "4.1.2", "4.1.3", "4.1.4",
"4.1.5", "4.1.6", "4.1.7", "4.1.8", "4.1.9", "4.1.10"
]
tests.forEach((versionCode) => {
t.equal(android.get(versionCode).versionCode, android.JELLY_BEAN.versionCode)
})
})
test('access version codes object', (t) => {
t.plan(1)
t.ok(android.VERSIONS)
})
test('access specific versions directly', (t) => {
t.plan(29)
t.ok(android.BASE)
t.ok(android.BASE_1_1)
t.ok(android.CUPCAKE)
t.ok(android.DONUT)
t.ok(android.ECLAIR)
t.ok(android.ECLAIR_0_1)
t.ok(android.ECLAIR_MR1)
t.ok(android.FROYO)
t.ok(android.GINGERBREAD)
t.ok(android.GINGERBREAD_MR1)
t.ok(android.HONEYCOMB)
t.ok(android.HONEYCOMB_MR1)
t.ok(android.HONEYCOMB_MR2)
t.ok(android.ICE_CREAM_SANDWICH)
t.ok(android.ICE_CREAM_SANDWICH_MR1)
t.ok(android.JELLY_BEAN)
t.ok(android.JELLY_BEAN_MR1)
t.ok(android.JELLY_BEAN_MR2)
t.ok(android.KITKAT)
t.ok(android.KITKAT_WATCH)
t.ok(android.LOLLIPOP)
t.ok(android.LOLLIPOP_MR1)
t.ok(android.M)
t.ok(android.N)
t.ok(android.N_MR1)
t.ok(android.O)
t.ok(android.O_MR1)
t.ok(android.P)
t.ok(android.Q)
})
|
// @flow
import type { Dispatch } from 'redux';
import { APP_WILL_MOUNT, APP_WILL_UNMOUNT } from './actionTypes';
declare var APP;
/**
* Signals that a specific App will mount (in the terms of React).
*
* @param {App} app - The App which will mount.
* @returns {{
* type: APP_WILL_MOUNT,
* app: App
* }}
*/
export function appWillMount(app: Object) {
return (dispatch: Dispatch<any>) => {
// TODO There was a redux action creator appInit which I did not like
// because we already had the redux action creator appWillMount and,
// respectively, the redux action APP_WILL_MOUNT. So I set out to remove
// appInit and managed to move everything it was doing but the
// following. Which is not extremely bad because we haven't moved the
// API module into its own feature yet so we're bound to work on that in
// the future.
typeof APP === 'object' && APP.API.init();
dispatch({
type: APP_WILL_MOUNT,
app
});
};
}
/**
* Signals that a specific App will unmount (in the terms of React).
*
* @param {App} app - The App which will unmount.
* @returns {{
* type: APP_WILL_UNMOUNT,
* app: App
* }}
*/
export function appWillUnmount(app: Object) {
return {
type: APP_WILL_UNMOUNT,
app
};
}
|
// Copyright (c) 2012 Ecma International. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
es5id: 15.3.2.1-11-4-s
description: >
Function constructor call from strict code with formal parameter
named 'eval' does not throws SyntaxError if function body is not
strict mode
flags: [onlyStrict]
---*/
Function('eval', 'return;');
|
/*
* Copyright 2016 IBM Corp.
*
* 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.
*/
module.exports = function(kernelP) {
return (function() {
var Utils = require('../../utils.js');
var gKernelP = kernelP;
/**
* @classdesc
* Model from k-fold cross validation.
*
* @param bestModel The best model selected from k-fold cross validation.
* @param avgMetrics Average cross-validation metrics for each paramMap in
* {@link estimatorParamMaps}, in the corresponding order.
* @class
* @memberof module:eclairjs/ml/tuning
* @extends module:eclairjs/ml.Model
*/
function CrossValidatorModel() {
Utils.handleConstructor(this, arguments, gKernelP);
};
/**
* @param {module:eclairjs/sql.Dataset} dataset
* @returns {Dataset}
*/
CrossValidatorModel.prototype.transform = function(dataset) {
var Dataset = require('../../sql/Dataset.js');
var args ={
target: this,
method: 'transform',
args: Utils.wrapArguments(arguments),
returnType: Dataset
};
return Utils.generate(args);
};
/**
* @param {module:eclairjs/sql/types.StructType} schema
* @returns {StructType}
*/
CrossValidatorModel.prototype.transformSchema = function(schema) {
var StructType = require('../../sql/types/StructType.js')();
var args ={
target: this,
method: 'transformSchema',
args: Utils.wrapArguments(arguments),
returnType: StructType
};
return Utils.generate(args);
};
/**
* @param {module:eclairjs/ml/param.ParamMap} extra
* @returns {CrossValidatorModel}
*/
CrossValidatorModel.prototype.copy = function(extra) {
var args ={
target: this,
method: 'copy',
args: Utils.wrapArguments(arguments),
returnType: CrossValidatorModel
};
return Utils.generate(args);
};
/**
* @returns {MLWriter}
*/
CrossValidatorModel.prototype.write = function() {
var MLWriter = require('../../ml/util/MLWriter.js')();
var args ={
target: this,
method: 'write',
returnType: MLWriter
};
return Utils.generate(args);
};
//
// static methods
//
/**
* @returns {MLReader}
*/
CrossValidatorModel.read = function() {
var MLReader = require('../../ml/util/MLReader.js')();
var args ={
target: CrossValidatorModel,
method: 'read',
static: true,
returnType: MLReader
};
return Utils.generate(args);
};
/**
* @param {string} path
* @returns {CrossValidatorModel}
*/
CrossValidatorModel.load = function(path) {
var args ={
target: CrossValidatorModel,
method: 'load',
args: Utils.wrapArguments(arguments),
static: true,
returnType: CrossValidatorModel
};
return Utils.generate(args);
};
CrossValidatorModel.moduleLocation = '/ml/tuning/CrossValidatorModel';
return CrossValidatorModel;
})();
};
|
// (C) Copyright 2015 Martin Dougiamas
//
// 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.
angular.module('mm.core')
/**
* Directive to show a loading spinner and message while data is being loaded.
*
* @module mm.core
* @ngdoc directive
* @name mmLoading
* @description
* Usage:
* <mm-loading message="{{loadingMessage}}" hide-until="dataLoaded">
* <!-- CONTENT TO HIDE UNTIL LOADED -->
* </mm-loading>
* This directive will show a ion-spinner with a message and hide all the content until 'dataLoaded' variable is set to true.
* If 'message' attribute is not set, default message "Loading" is shown.
* 'message' attribute accepts hardcoded strings, variables, filters, etc. E.g. message="{{ 'mm.core.loading' | translate}}".
*/
.directive('mmLoading', function($translate) {
/**
* Set message to '.mm-loading-message' element.
*
* @param {Object} el DOM element to search '.mm-loading-message' in.
* @param {String} message Message to show.
*/
function setMessage(el, message) {
var messageEl = angular.element(el.querySelector('.mm-loading-message'));
if (messageEl) {
messageEl.html(message);
}
}
return {
restrict: 'E',
templateUrl: 'core/templates/loading.html',
transclude: true,
link: function(scope, element, attrs) {
var el = element[0],
loading,
content;
if (attrs.message) {
setMessage(el, attrs.message);
} else {
// Default loading message.
$translate('mm.core.loading').then(function(loadingString) {
setMessage(el, loadingString);
});
}
if (attrs.hideUntil) {
loading = angular.element(el.querySelector('.mm-loading-container'));
content = angular.element(el.querySelector('.mm-loading-content'));
scope.$watch(attrs.hideUntil, function(newValue) {
if (newValue) {
loading.addClass('hide');
content.removeClass('hide');
} else {
content.addClass('hide');
loading.removeClass('hide');
}
});
}
}
};
});
|
'use strict';
// Testing to send an handle twice to the parent process.
var common = require('../common');
var assert = require('assert');
var cluster = require('cluster');
var net = require('net');
var workers = {
toStart: 1
};
if (cluster.isMaster) {
for (var i = 0; i < workers.toStart; ++i) {
var worker = cluster.fork();
worker.on('exit', function(code, signal) {
assert.equal(code, 0, 'Worker exited with an error code');
assert(!signal, 'Worker exited by a signal');
});
}
} else {
var server = net.createServer(function(socket) {
process.send('send-handle-1', socket);
process.send('send-handle-2', socket);
});
server.listen(common.PORT, function() {
var client = net.connect({ host: 'localhost', port: common.PORT });
client.on('close', function() { cluster.worker.disconnect(); });
setTimeout(function() { client.end(); }, 50);
}).on('error', function(e) {
console.error(e);
assert(false, 'server.listen failed');
cluster.worker.disconnect();
});
}
|
// Copyright (c) 2012 Ecma International. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
es5id: 15.2.3.7-6-a-27
description: >
Object.defineProperties - 'P' doesn't exist in 'O', test [[Value]]
of 'P' is set as undefined value if absent in data descriptor
'desc' (8.12.9 step 4.a.i)
---*/
var obj = {};
Object.defineProperties(obj, {
prop: {
writable: true
}
});
var desc = Object.getOwnPropertyDescriptor(obj, "prop");
assert(desc.hasOwnProperty("value"), 'desc.hasOwnProperty("value") !== true');
assert.sameValue(typeof desc.value, "undefined", 'typeof desc.value');
assert(desc.hasOwnProperty("writable"), 'desc.hasOwnProperty("writable") !== true');
assert.sameValue(desc.writable, true, 'desc.writable');
assert(desc.hasOwnProperty("configurable"), 'desc.hasOwnProperty("configurable") !== true');
assert.sameValue(desc.configurable, false, 'desc.configurable');
assert(desc.hasOwnProperty("enumerable"), 'desc.hasOwnProperty("enumerable") !== true');
assert.sameValue(desc.enumerable, false, 'desc.enumerable');
|
module.exports = require('./' + (process.env.NODE_ENV || 'development') + '.json');
|
/*{
"options": {
"preserveCompletionValue": true
}
}*/
100 % 42
|
var cdb = require('cartodb.js-v3');
var CreateDataModel = require('../../../../../../javascripts/cartodb/common/dialogs/create/create_dataset_model');
var sharedForCreateListingViewModel = require('./shared_for_create_listing_view_model');
var sharedForCreateListingImportViewModel = require('./listing/shared_for_import_view_model');
describe('common/dialogs/create/create_dataset_model', function() {
beforeEach(function() {
this.user = new cdb.admin.User({
username: 'paco',
base_url: 'http://url.com'
});
this.model = new CreateDataModel({
}, {
user: this.user
});
});
sharedForCreateListingViewModel.call(this);
sharedForCreateListingImportViewModel.call(this);
it('should have default values', function() {
expect(this.model.get('type')).toBeDefined();
expect(this.model.get('option')).toBeDefined();
});
it('should define several local models', function() {
expect(this.model.upload).toBeDefined();
});
describe('.createFromScratch', function() {
it('should change state when dataset creation starts', function() {
spyOn(cdb.admin.CartoDBTableMetadata.prototype, 'save');
this.model.createFromScratch();
expect(this.model.get('option')).toBe('loading');
});
it('should trigger datasetCreated when it is created', function() {
spyOn(cdb.admin.CartoDBTableMetadata.prototype, 'save').and.callFake(function(a, opts){
opts.success();
});
var called = false;
this.model.bind('datasetCreated', function(){ called = true });
this.model.createFromScratch();
expect(called).toBeTruthy();
});
it('should trigger datasetError when it fails', function() {
spyOn(cdb.admin.CartoDBTableMetadata.prototype, 'save').and.callFake(function(a, opts){
opts.error();
});
var called = false;
this.model.bind('datasetError', function(){ called = true });
this.model.createFromScratch();
expect(called).toBeTruthy();
});
});
});
|
/**
* @file
*
* @brief this exports a function that defines routes for the express app
*
* @copyright BSD License (see LICENSE.md or https://www.libelektra.org)
*/
import makeLog from "../log";
const { error } = makeLog("routes:clusters");
import { successResponse, errorResponse } from "./utils";
import {
getClusters,
createCluster,
getCluster,
updateCluster,
deleteCluster,
getClusterInstances,
addInstanceToCluster,
removeInstanceFromCluster,
getInstance,
virtualKdb,
} from "../db";
import remoteKdb from "../connector";
import kdb from "../kdb";
// execute `fn` on all instances in the specified cluster
const applyToAllInstances = (res, clusterId, fn) =>
getClusterInstances(clusterId)
.then((instanceIds) => Promise.all(instanceIds.map(getInstance)))
.then((instances) => Promise.all(instances.map(fn)))
.then((output) => successResponse(res, output))
.catch((err) => {
error("error while applying to all instances:", err);
return errorResponse(res, err);
});
export default function initClusterRoutes(app) {
app
.route("/api/clusters")
.get((req, res) =>
getClusters()
.then((output) => successResponse(res, output))
.catch((err) => errorResponse(res, err))
)
.post((req, res) =>
createCluster(req.body)
.then((output) => successResponse(res, output))
.catch((err) => errorResponse(res, err))
);
app
.route("/api/clusters/:id")
.get((req, res) =>
getCluster(req.params.id)
.then((output) => successResponse(res, output))
.catch((err) => errorResponse(res, err))
)
.put((req, res) =>
updateCluster(req.params.id, req.body)
.then((output) => successResponse(res, output))
.catch((err) => errorResponse(res, err))
)
.delete((req, res) =>
deleteCluster(req.params.id)
.then((output) => successResponse(res, output))
.catch((err) => errorResponse(res, err))
);
app
.route("/api/clusters/:id/instances")
.get((req, res) =>
applyToAllInstances(res, req.params.id, (instance) => instance)
)
.post((req, res) =>
addInstanceToCluster(req.params.id, req.body && req.body.instanceId)
.then((output) => successResponse(res, output))
.catch((err) => errorResponse(res, err))
);
app.delete("/api/clusters/:id/instances/:instanceId", (req, res) =>
removeInstanceFromCluster(req.params.id, req.params.instanceId)
.then((output) => successResponse(res, output))
.catch((err) => errorResponse(res, err))
);
app.get("/api/clusters/:id/version", (req, res) =>
applyToAllInstances(res, req.params.id, (instance) =>
remoteKdb.version(instance.host)
)
);
// cluster kdb
const stripVirtualPath = (clusterId) => (output) => {
const strippedLs =
Array.isArray(output.ls) &&
output.ls.map(
(path) => path.replace(virtualKdb(clusterId) + "/", "") // strip virtual kdb root from path
);
return { ...output, ls: strippedLs };
};
// TODO: check if cluster id actually exists
app.get("/api/clusters/:id/kdb", (req, res) =>
kdb
.getAndLs(virtualKdb(req.params.id))
.then(stripVirtualPath(req.params.id))
.then((output) => successResponse(res, output))
.catch((err) => errorResponse(res, err))
);
// TODO: what if an instance isn't online? -> send later
app
.route("/api/clusters/:id/kdb/*")
.get((req, res) =>
kdb
.getAndLs(virtualKdb(req.params.id, req.params[0]))
.then(stripVirtualPath(req.params.id))
.then((output) => successResponse(res, output))
.catch((err) => errorResponse(res, err))
)
.put((req, res) => {
const clusterId = req.params.id;
const path = req.params[0];
// set key in virtual kdb on webd server
kdb
.set(virtualKdb(clusterId, path), req.body)
.then((output) =>
// set key on all instances in the cluster
applyToAllInstances(res, clusterId, (instance) =>
remoteKdb.set(instance.host, path, req.body)
)
)
.catch((err) => errorResponse(res, err));
})
.delete((req, res) => {
const clusterId = req.params.id;
const path = req.params[0];
kdb
.rm(virtualKdb(clusterId, path))
.then((output) =>
// set key on all instances in the cluster
applyToAllInstances(res, clusterId, (instance) =>
remoteKdb.rm(instance.host, path)
)
)
.catch((err) => errorResponse(res, err));
});
}
|
define('test/mods/query',function(require,exports,module){
module.exports = 'test/mods/query';
});
|
/* global it, history, describe, location, expect */
var jsdom = require('../index')
describe('simple', function () {
jsdom()
it('has document', function () {
var div = document.createElement('div')
expect(div.nodeName).eql('DIV')
})
it('has history', function () {
history.pushState({}, null, '/a/b/c')
expect(location.href).eql('file:///a/b/c')
})
})
|
export class ResourceLoadContext {
constructor(){
this.dependencies = {};
}
addDependency(url:string):void{
this.dependencies[url] = true;
}
doesNotHaveDependency(url:string):boolean{
return !(url in this.dependencies);
}
}
export class ViewCompileInstruction {
static normal = new ViewCompileInstruction();
constructor(targetShadowDOM?:boolean=false, compileSurrogate?:boolean=false, beforeCompile?:boolean=null){
this.targetShadowDOM = targetShadowDOM;
this.compileSurrogate = compileSurrogate;
this.associatedModuleId = null;
this.beforeCompile = beforeCompile; //this will be replaced soon
}
}
interface ViewCreateInstruction {
suppressBind?:boolean;
systemControlled?:boolean;
enhance?:boolean;
partReplacements?:Object;
initiatedByBehavior?:boolean;
}
export class BehaviorInstruction {
static normal = new BehaviorInstruction();
static contentSelector = new BehaviorInstruction(true);
static element(node:Node, type:HtmlBehaviorResource):BehaviorInstruction{
let instruction = new BehaviorInstruction(true);
instruction.type = type;
instruction.attributes = {};
instruction.anchorIsContainer = !(node.hasAttribute('containerless') || type.containerless);
instruction.initiatedByBehavior = true;
return instruction;
}
static attribute(attrName:string, type?:HtmlBehaviorResource):BehaviorInstruction{
let instruction = new BehaviorInstruction(true);
instruction.attrName = attrName;
instruction.type = type || null;
instruction.attributes = {};
return instruction;
}
static dynamic(host, executionContext, viewFactory){
let instruction = new BehaviorInstruction(true);
instruction.host = host;
instruction.executionContext = executionContext;
instruction.viewFactory = viewFactory;
return instruction;
}
constructor(suppressBind?:boolean=false){
this.suppressBind = suppressBind;
this.initiatedByBehavior = false;
this.systemControlled = false;
this.enhance = false;
this.partReplacements = null;
this.viewFactory = null;
this.originalAttrName = null;
this.skipContentProcessing = false;
this.contentFactory = null;
this.executionContext = null;
this.anchorIsContainer = false;
this.host = null;
this.attributes = null;
this.type = null;
this.attrName = null;
}
}
export class TargetInstruction {
static noExpressions = Object.freeze([]);
static contentSelector(node:Node, parentInjectorId:number):TargetInstruction{
let instruction = new TargetInstruction();
instruction.parentInjectorId = parentInjectorId;
instruction.contentSelector = true;
instruction.selector = node.getAttribute('select');
instruction.suppressBind = true
return instruction;
}
static contentExpression(expression):TargetInstruction{
let instruction = new TargetInstruction();
instruction.contentExpression = expression;
return instruction;
}
static lifting(parentInjectorId:number, liftingInstruction:BehaviorInstruction):TargetInstruction{
let instruction = new TargetInstruction();
instruction.parentInjectorId = parentInjectorId;
instruction.expressions = TargetInstruction.noExpressions;
instruction.behaviorInstructions = [liftingInstruction];
instruction.viewFactory = liftingInstruction.viewFactory;
instruction.providers = [liftingInstruction.type.target];
return instruction;
}
static normal(injectorId, parentInjectorId, providers, behaviorInstructions, expressions, elementInstruction):TargetInstruction{
let instruction = new TargetInstruction();
instruction.injectorId = injectorId;
instruction.parentInjectorId = parentInjectorId;
instruction.providers = providers;
instruction.behaviorInstructions = behaviorInstructions;
instruction.expressions = expressions;
instruction.anchorIsContainer = elementInstruction ? elementInstruction.anchorIsContainer : true;
instruction.elementInstruction = elementInstruction;
return instruction;
}
static surrogate(providers, behaviorInstructions, expressions, values):TargetInstruction{
let instruction = new TargetInstruction();
instruction.expressions = expressions;
instruction.behaviorInstructions = behaviorInstructions;
instruction.providers = providers;
instruction.values = values;
return instruction;
}
constructor(){
this.injectorId = null;
this.parentInjectorId = null;
this.contentSelector = false;
this.selector = null;
this.suppressBind = false;
this.contentExpression = null;
this.expressions = null;
this.behaviorInstructions = null;
this.providers = null;
this.viewFactory = null;
this.anchorIsContainer = false;
this.elementInstruction = null;
this.values = null;
}
}
|
module.exports = function (req) {
'use strict';
var encoded = req.headers.authorization.split(' ')[1];
var decoded = new Buffer(encoded, 'base64').toString('utf8');
var username = decoded.split(':')[0];
var password = decoded.split(':')[1];
return {name: username, password: password};
};
|
// ##### Random Command
//
// The [random command](http://jquery-jkit.com/commands/random.html) can be used to randomly select a
// specific amount of elements from a collection of elements. All not selected ones will either be hidden
// or completely removed from the DOM.
plugin.commands.random = (function(){
// Create an object that contains all of our data and functionality.
var command = {};
// This are the command defaults:
plugin.addCommandDefaults('random', {
'count': 1,
'remove': 'yes'
});
// The execute function is launched whenever this command is executed:
command.execute = function($that, options){
var childs = $that.children().size();
var shownrs = [];
// Create an array of index numbers of our randomly selected elements:
while(shownrs.length < options.count){
var shownr = Math.floor(Math.random() * childs);
if ($.inArray(shownr, shownrs) == -1){
shownrs.push(shownr);
}
}
// Now loop through all elements and only show those we just slected:
var i = 0;
$that.children().each( function(){
if ($.inArray(i, shownrs) == -1){
if (options.remove == 'yes'){
$(this).remove();
} else {
$(this).hide();
}
} else {
$(this).show();
}
i++;
});
};
return command;
}());
|
version https://git-lfs.github.com/spec/v1
oid sha256:ba152786dccc5ae1656ce9481341e2c082b0d2530200799c7200bd4b7e09ee8f
size 1023
|
import { client } from './client'
const pokemonQuery = `
query firstTwentyPokemons($name: String!) {
pokemon(name: $name) {
name
image
}
}
`
export const getPokemon = async (name) => {
const {
data: { pokemon },
} = await client.query(pokemonQuery, { name }).toPromise()
return pokemon
}
|
export class Header {
type = 'header';
name = 'Report header';
icon = 'fa-header';
}
|
import Ember from 'ember';
import {
moduleForComponent,
test
} from 'ember-qunit';
moduleForComponent('yebo-auth', {
// specify the other units that are required for this test
needs: [
'component:yebo-input'
]
});
test('it renders', function(assert) {
assert.expect(2);
var component = this.subject();
assert.equal(component._state, 'preRender');
this.render();
assert.equal(component._state, 'inDOM');
});
test('it renders password confirmation if it isSignup is true', function(assert) {
assert.expect(4);
var matches;
var component = this.subject();
assert.equal(component._state, 'preRender');
this.render();
assert.equal(component._state, 'inDOM');
matches = this.$().find('input[placeholder="Password Confirmation"]');
assert.equal(matches.length, 0);
Ember.run(function() {
component.set('isSignup', true);
});
matches = this.$().find('input[placeholder="Password Confirmation"]');
assert.equal(matches.length, 1);
});
|
var React = require('react-native');
var Util = require('./../util');
var Service = require('../service');
var {
View,
Text,
ScrollView,
StyleSheet,
TouchableOpacity,
TextInput,
AlertIOS,
AsyncStorage,
} = React;
var DeleteUser = React.createClass({
render: function(){
return (
<ScrollView>
<View style={{height:35, marginTop:30,}}>
<TextInput style={styles.input} placeholder="请输入用户的邮箱" onChangeText={this._getEmail}/>
</View>
<View>
<TouchableOpacity onPress={this._deleteUser}>
<View style={styles.btn}>
<Text style={{color:'#FFF'}}>删除用户</Text>
</View>
</TouchableOpacity>
</View>
</ScrollView>
);
},
_getEmail: function(val){
this.setState({
email: val
});
},
_deleteUser: function(){
var that = this;
AlertIOS.alert('提示', '确认删除该用户?', [
{text: '删除', onPress: function(){
var path = Service.host + Service.deleteUser;
AsyncStorage.getItem('token', function(err, data){
if(!err){
Util.post(path,{
token: data,
email: that.state.email
}, function(data){
if(data.status){
AlertIOS.alert('成功', '删除成功');
}else{
AlertIOS.alert('失败', '删除失败');
}
});
}else{
AlertIOS.alert('提示', '没有权限');
}
});
}
},
{text: '取消', onPress: ()=>null},
]);
}
});
var styles = StyleSheet.create({
input:{
flex:1,
marginLeft:20,
marginRight:20,
height:35,
borderWidth:1,
borderColor:'#ddd',
borderRadius:4,
paddingLeft:5,
fontSize:13,
},
btn:{
justifyContent:'center',
alignItems:'center',
marginTop:20,
backgroundColor:'#1DB8FF',
height:38,
marginLeft:20,
marginRight:20,
borderRadius:4,
}
});
module.exports = DeleteUser;
|
const prettyURLs = require('../../shared/middlewares/pretty-urls');
const cors = require('../../shared/middlewares/api/cors');
const urlRedirects = require('../../shared/middlewares/url-redirects');
const auth = require('../../../services/auth');
/**
* Auth Middleware Packages
*
* IMPORTANT
* - cors middleware MUST happen before pretty urls, because otherwise cors header can get lost on redirect
* - cors middleware MUST happen after authenticateClient, because authenticateClient reads the trusted domains
* - url redirects MUST happen after cors, otherwise cors header can get lost on redirect
*/
/**
* Authentication for public endpoints
*/
module.exports.authenticatePublic = [
auth.authenticate.authenticateClient,
auth.authenticate.authenticateUser,
// This is a labs-enabled middleware
auth.authorize.requiresAuthorizedUserPublicAPI,
cors,
urlRedirects,
prettyURLs
];
/**
* Authentication for private endpoints
*/
module.exports.authenticatePrivate = [
auth.authenticate.authenticateClient,
auth.authenticate.authenticateUser,
auth.authorize.requiresAuthorizedUser,
cors,
urlRedirects,
prettyURLs
];
/**
* Authentication for client endpoints
*/
module.exports.authenticateClient = function authenticateClient(client) {
return [
auth.authenticate.authenticateClient,
auth.authenticate.authenticateUser,
auth.authorize.requiresAuthorizedClient(client),
cors,
urlRedirects,
prettyURLs
];
};
|
'use strict';
var gulp = require('gulp');
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var browserifyShim = require('browserify-shim');
module.exports = gulp.task('browserify', function () {
return browserify({
entries: [config.paths.src.modules]
})
.transform(browserifyShim)
.bundle()
.pipe(source(config.filenames.release.scripts))
.pipe(gulp.dest(config.paths.dest.release.scripts));
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.