code
stringlengths 2
1.05M
|
|---|
describe("Tests existence of family tree", function(){
it("Family tree exists", function(){
expect(familyTree).toBeTruthy();
});
it("Family tree contains 14 members", function(){
expect(familyTree.members.length).toBe(14);
});
});
describe("Tests creation and associations of people", function(){
var nancy = new Person("Nancy");
nancy.addChild("Adam");
nancy.addChild("Jill");
nancy.addChild("Carl");
familyTree.find("Carl").addChild("Joseph");
familyTree.find("Carl").addChild("Catherine");
familyTree.find("Jill").addChild("Kevin");
familyTree.find("Kevin").addChild("Samuel");
familyTree.find("Kevin").addChild("George");
familyTree.find("Kevin").addChild("James");
familyTree.find("Kevin").addChild("Aaron");
familyTree.find("James").addChild("Mary");
familyTree.find("George").addChild("Patrick");
familyTree.find("George").addChild("Robert");
it("Creates people objects", function(){
expect(nancy.name).toBe("Nancy");
});
it("Child and parent association", function(){
expect(familyTree.find("George").parent.name).toBe("Kevin");
});
})
describe("Tests expected results from given functions", function(){
it("Returns the appropriate grandparent association(Kevin => Nancy)", function(){
expect(familyTree.find("Kevin").grandparent.name).toBe("Nancy");
});
it("Returns all members with no siblings(Nancy, Kevin, Mary)", function(){
expect(familyTree.siblingLess()).toContain("Nancy", "Kevin", "Mary");
});
it("Returns all members with no children(Adam, Catherine Joseph, Samuel, Aaron, Mary, Patrick, Robert)", function(){
expect(familyTree.childLess()).toContain("Adam", "Catherine", "Joseph", "Samuel", "Aaron", "Mary", "Patrick", "Robert");
});
it("Returns the most plentiful grandmother(Jill)", function(){
expect(familyTree.mostGrandchildren().name).toBe("Jill");
});
});
|
import config from '../config'
import server from '../server/main.js'
import _debug from 'debug'
const debug = _debug('app:bin:server')
const port = config.server_port
const host = config.server_host
server.listen(port)
debug(`Server is now running at http://${host}:${port}.`)
debug(`Server accessible via localhost:${port} if you are using the project defaults.`)
|
function DateFormat( d ) {
if ( d < 3600 ) {
return d / 60 + " mins"
} else if ( d < 3600 * 24 ) {
return d / 3600 + " hours";
} else {
return d / ( 3600 * 24 ) + " days";
}
}
var typeRaffle = [ "Public Raffle", "Secret Link", "Secret Link & Password",
"My Friend Only", "Password Per Entry", "Twitch Followers Only", "Twitch Subscribers Only",
"Puzzle Raffle", "Steam Group Only"
];
var coloredType = [ "btn-success", "btn-info", "btn-info", "btn-primary", "btn-info", "btn-primary", "btn-primary", "btn-success", "btn-primary" ];
var raffleSelect = {}; // OpenRaffleEdit()
/* Load All saved raffles */
chrome.storage.local.get( [ "savedCreateRaffle" ], function ( res ) {
if ( res.savedCreateRaffle && res.savedCreateRaffle[ 0 ] ) {
// Append The load Box
document.querySelector( '.panel.panel-info' ).insertAdjacentHTML( 'afterend',
'<div class="panel panel-info" id="PonyPanel">' +
' <div class="panel-heading">' +
' <h3 class="panel-title"><i18n>Load Raffle</i18n></h3>' +
' </div>' +
' <div class="panel-body">' +
' <div class="col-md-12" id="appendHere">' +
' ' +
' </div>' +
' </div>' +
'</div>'
);
// Append saved conf
var appendBox = document.getElementById( 'appendHere' );
var DOMFrag = BuildDOM.NewDocFrag();
for ( let i = 0, len = res.savedCreateRaffle.length; i < len; i++ ) {
let nextStep = ( res.savedCreateRaffle[ i ].privateRaffle == 0 || res.savedCreateRaffle[ i ].privateRaffle == 7 ) ? false : true;
nextStep = 'ScrapTF.Raffles.NextStep(' + nextStep + ')';
// Yup it's ugly
DOMFrag.appendChild(
BuildDOM.Create( {
tag: 'div',
classList: [ 'form-group' ],
dataset: {
k: res.savedCreateRaffle[ i ].raffleID
},
childrens: [ {
tag: 'div',
classList: [ 'form-control' ],
attributes: {
onclick: nextStep
},
childrens: [ {
tag: 'span',
classList: [ 'form-control-static' ],
childrens: [ {
tag: 'i',
classList: [ 'fa', ( res.savedCreateRaffle[ i ].type ? 'fa-users' : 'fa-user' ) ]
}, {
tag: 'i18n',
textContent: res.savedCreateRaffle[ i ].savedName
} ]
}, {
tag: 'div',
classList: [ 'pull-right' ],
childrens: [ {
tag: 'span',
classList: [ 'btn', 'btn-xs', ( res.savedCreateRaffle[ i ].nocmt ? 'btn-danger' : 'btn-default' ) ],
innerHTML: '<i class="fa fa-comments-o"></i></span>'
}, {
tag: 'span',
classList: [ 'btn', 'btn-xs', coloredType[ res.savedCreateRaffle[ i ].privateRaffle ] ],
textContent: typeRaffle[ res.savedCreateRaffle[ i ].privateRaffle ]
}, {
tag: 'span',
classList: [ 'btn', 'btn-xs', 'btn-default' ],
textContent: DateFormat( res.savedCreateRaffle[ i ].length )
}, {
tag: 'span',
classList: [ 'btn', 'btn-xs', 'btn-default' ],
childrens: [ {
tag: 'i',
classList: [ 'fa', 'fa-users' ]
}, {
tag: 'span',
classList: [ 'entries' ],
textContent: res.savedCreateRaffle[ i ].maxentries
} ]
} ]
} ]
}, {
tag: 'div',
classList: [ 'pull-right', 'btnDel' ],
innerHTML: '<button class="btn btn-xs btn-danger rm"><i class="fa fa-remove rm"></i></button>'
} ]
} )
);
} // End for
appendBox.appendChild( DOMFrag );
// Event Add and Delete
function MakeMilshake( ev ) {
// Search the main div
var target = ev.target;
for ( let i = 0, c, len = appendBox.children.length; i < len; i++ ) {
if ( appendBox.children[ i ].contains( target ) ) {
target = appendBox.children[ i ];
break;
}
}
/* Remove from the save list the element */
if ( ev.target.matches( '.rm' ) ) {
chrome.storage.local.get( [ "savedCreateRaffle" ], function ( res ) {
// First configuration
if ( !res.savedCreateRaffle ) {
res.savedCreateRaffle = [];
}
for ( let i = 0, dataset = target.dataset.k, len = res.savedCreateRaffle.length; i < len; i++ ) {
if ( res.savedCreateRaffle[ i ].raffleID == dataset ) {
res.savedCreateRaffle.splice( i, 1 );
break;
}
}
// Remove the element
target.remove();
// Save the new config
chrome.storage.local.set( {
savedCreateRaffle: res.savedCreateRaffle
} );
} );
}
/* Or open this element */
else {
// And ... continue
chrome.storage.local.get( [ "savedCreateRaffle" ], function ( res ) {
if ( res.savedCreateRaffle ) {
// load configuration
let conf;
for ( let i = 0, dataset = target.dataset.k, len = res.savedCreateRaffle.length; i < len; i++ ) {
if ( res.savedCreateRaffle[ i ].raffleID == dataset ) {
conf = res.savedCreateRaffle[ i ];
break;
}
}
/* Display saved informations */
if ( conf ) {
OpenRaffleEdit();
/* Puzzle panel */
if ( conf.privateRaffle == 7 ) {
var prefix = 'puzzle-';
document.getElementById( 'puzzlesolution' ).value = ( conf.solution ) ? conf.solution : "";
// Raffle time
document.getElementById( 'select2-chosen-4' ).textContent = DateFormat( conf.length );
// Number of winners
document.getElementById( 'select2-chosen-5' ).textContent = conf.type ? "Multiple winners" : "One winner";
}
/* Public or private */
else {
var prefix = '';
// Raffle time
document.getElementById( 'select2-chosen-1' ).textContent = DateFormat( conf.length );
// Number of winners
document.getElementById( 'select2-chosen-2' ).textContent = conf.type ? "Multiple winners" : "One winner";
}
// Spawn raffleSelect
GenRaffleSelect( prefix );
/* Inject values on inputs */
// Name content & enter msgs
raffleSelect.name.value = conf.name;
Exec( 'LoadRaffle', {
message: conf.message,
enterMessage: conf.entmsg,
target: prefix
} );
// raffleSelect.message.value = conf.message;
// raffleSelect.enteredmessage.value = conf.entmsg;
// Poll entries solution & password
raffleSelect.poll.value = conf.poll;
raffleSelect.maxentries.value = conf.maxentries;
raffleSelect.password.value = conf.pwd;
// Display the password box
if ( conf.privateRaffle == 2 || conf.privateRaffle == 8 ) {
document.getElementById( 'raffle-password-out' ).style.display = "block";
}
// Raffle time
raffleSelect.length.value = conf.length;
// Number of winners
raffleSelect.method.value = conf.type ? "2" : "1";
// Append also the save button
if ( conf.privateRaffle != 7 && conf.privateRaffle != 0 ) {
raffleSelect.privateRaffle.value = conf.privateRaffle;
document.getElementById( 'select2-chosen-3' ).textContent = typeRaffle[ conf.privateRaffle ];
document.getElementById( 'select2-chosen-4' ).textContent = typeRaffle[ conf.privateRaffle ];
AppendSaveBtn( "true" );
} else {
// Complicated for nothing ...
raffleSelect.privateRaffle.appendChild(
BuildDOM.Create( {
tag: 'option',
attributes: {
value: conf.privateRaffle
}
} )
);
raffleSelect.privateRaffle.value = conf.privateRaffle;
// Remove the private raffle inputs
let privateInputs = Array.from( document.querySelectorAll( '.raffle-private-field' ) );
for ( let i = 0, len = privateInputs.length; i < len; i++ ) {
privateInputs[ i ].style.display = "none";
}
AppendSaveBtn( "false" );
}
// Disable comments
raffleSelect.comments.checked = conf.nocmt;
/* Only privates raffle */
if ( conf.isPrivate ) {
// Twitch Raffle
raffleSelect.twitch.checked = conf.twitch;
if ( conf.twitch ) {
raffleSelect.subluck.value = ( conf.subluck != 1 ) ? conf.subluck : "";
raffleSelect.subluck.parentElement.style.display = "block";
raffleSelect.subluck.parentElement.previousElementSibling.style.display = "block";
}
}
// Display the correct panel
document.getElementById( 'raffle-' + prefix + 'form' ).style.display = "";
}
}
} );
}
}
// Append the event
appendBox.addEventListener( 'click', MakeMilshake );
}
} );
|
// Page specific js code
/*global
msos: false,
jQuery: false,
Modernizr: false
*/
msos.provide("demo.siteos.detect");
msos.require("msos.detection");
msos.require("msos.site.detect");
msos.require("msos.browser");
// Don't translate these...
msos.config.google.no_translate.by_id =
msos.config.google.no_translate.by_id.concat(
['#plugin_detect', '#user_agent', '#msos_detection', '#modernizr_detect', '#font_size_test']
);
msos.onload_functions.push(
function () {
"use strict";
var browser_env = {},
dump_out = '',
answer = 'no response',
uagent = navigator.userAgent,
output = '',
gen_detect_ul = jQuery('<ul class="msos_list"><\/ul>'),
msos_detect_ul = jQuery('<ul class="msos_list"><\/ul>'),
modzr_detect_ul = jQuery('<ul class="msos_list"><\/ul>'),
view_size = {},
props = '',
kind = '',
type = '',
detect = '',
root_page = /^[^?#]*\//.exec(location.href)[0],
root_domain = /^\w+\:\/\/\/?[^\/]+/.exec(root_page)[0];
function add_li_element(elem, str) {
var new_li = jQuery('<li>').text(str);
elem.append(new_li);
}
msos.console.info('Content: detect.html loaded!');
// User Agent
jQuery('#user_agent').html("<div style='bold'>" + uagent + "</div>");
// Browser Environment
output += '<ul class="msos_list">';
output += '<li>MSOS Language : ' + msos.config.locale + '<\/li>';
if (msos.browser.is.Browser) { answer = 'true'; }
else { answer = 'false'; }
output += '<li>Client is a browser : ' + answer + '<\/li>';
if (msos.config.browser.current) { answer = 'true'; }
else { answer = 'false'; }
output += '<li>Browser is current : ' + answer + '<\/li>';
if (msos.config.browser.editable) { answer = 'true'; }
else { answer = 'false'; }
output += '<li>Browser is editable : ' + answer + '<\/li>';
if (msos.config.browser.advanced) { answer = 'true'; }
else { answer = 'false'; }
output += '<li>Browser is advanced : ' + answer + '<\/li>';
if (msos.config.browser.mobile) { answer = 'true'; }
else { answer = 'false'; }
output += '<li>Browser is mobile : ' + answer + '<\/li>';
if (msos.config.browser.touch) { answer = 'true'; }
else { answer = 'false'; }
output += '<li>Browser is touch : ' + answer + '<\/li>';
if (msos.browser.is.FF) { answer = 'Ver. ' + msos.browser.is.FF; }
else { answer = 'false'; }
output += '<li>Browser is FF : ' + answer + '<\/li>';
if (msos.browser.is.IE) { answer = 'Ver. ' + msos.browser.is.IE; }
else { answer = 'false'; }
output += '<li>Browser is MSIE : ' + answer + '<\/li>';
if (msos.browser.is.Opera) { answer = 'Ver. ' + msos.browser.is.Opera; }
else { answer = 'false'; }
output += '<li>Browser is Opera : ' + answer + '<\/li>';
if (msos.browser.is.Khtml) { answer = 'Ver. ' + msos.browser.is.Khtml; }
else { answer = 'false'; }
output += '<li>Browser is KHTML : ' + answer + '<\/li>';
if (msos.browser.is.Safari) { answer = 'Ver. ' + msos.browser.is.Safari; }
else { answer = 'false'; }
output += '<li>Browser is Safari : ' + answer + '<\/li>';
if (msos.browser.is.Mozilla) { answer = 'Ver. ' + msos.browser.is.Mozilla; }
else { answer = 'false'; }
output += '<li>Browser is Mozilla : ' + answer + '<\/li>';
if (msos.browser.is.Chrome) { answer = 'Ver. ' + msos.browser.is.Chrome; }
else { answer = 'false'; }
output += '<li>Browser is Chrome : ' + answer + '<\/li>';
if (msos.browser.is.WebKit) { answer = 'Ver. ' + msos.browser.is.WebKit; }
else { answer = 'false'; }
output += '<li>Browser is WebKit : ' + answer + '<\/li>';
if (msos.browser.is.Quirks) { answer = 'true'; }
else { answer = 'false'; }
output += '<li>Quirks mode : ' + answer + '<\/li>';
if (msos.browser.is.AIR) { answer = 'true'; }
else { answer = 'false'; }
output += '<li>Adobe Air : ' + answer + '<\/li>';
output += '<\/ul>';
jQuery('#browser_detection').html(output);
// Plugin detection
view_size = msos.config.view_port;
add_li_element(gen_detect_ul, 'java : ' + navigator.javaEnabled());
for (props in msos.detection.plugins) {
add_li_element(gen_detect_ul, props + ' : ' + msos.detection.plugins[props]);
}
jQuery('#plugin_detect').append(gen_detect_ul);
// Device specific detection;
add_li_element(msos_detect_ul, 'view_port.height : ' + view_size.height);
add_li_element(msos_detect_ul, 'view_port.width : ' + view_size.width);
for (kind in msos.config.file) {
add_li_element(msos_detect_ul, 'file.' + kind + ' : ' + msos.config.file[kind]);
}
for (type in msos.config.touch) {
add_li_element(msos_detect_ul, 'touch.' + type + ' : ' + msos.config.touch[type]);
}
add_li_element(msos_detect_ul, 'orientation : ' + msos.config.orientation);
jQuery('#msos_detection').append(msos_detect_ul);
// Modernizr output
for (detect in Modernizr) {
if (typeof Modernizr[detect] === 'boolean') {
add_li_element(modzr_detect_ul, 'Modernizr.' + detect + ' : ' + Modernizr[detect]);
}
}
jQuery('#modernizr_detect').append(modzr_detect_ul);
if (msos.debug) {
// msos.site.detect bundles all user profile output
browser_env = msos.site.detect.browser();
dump_out = JSON.stringify(browser_env, null, '\t');
setTimeout(function () { msos.debug.write(dump_out, true); }, 2000);
}
// Clean-up
jQuery('#font_size_test').css('display', 'none');
msos.console.info('Content: detect.html -> root_page: ' + root_page + ', root_domain: ' + root_domain);
}
);
|
//此check()函式在最後的「傳送」案鈕會用到
function check()
{
//若<form>屬性name值為reg裡的文字方塊值為空字串,則顯示「未輸入姓名」
if(reg.key.value == "")
{
alert("未輸入股票代碼");
}
// //若<form>屬性name值為reg裡的文字方塊與下拉式選單值為空字串或是沒有選擇月或日,則顯示「未輸入完整生日日期」
// else if(reg.year.value == "" || reg.month.value == "00" || reg.day.value == "00")
// {
// alert("未輸入完整生日日期");
// }
// //若<form>屬性name值為reg裡的核取方塊沒有選擇,則顯示「未選擇性別」
// else if(!reg.sex[0].checked && !reg.sex[1].checked)
// {
// alert("未選擇性別");
// }
// //若以上條件皆不符合,也就是表單資料皆有填寫的話,則將資料送出
else reg.submit();
}
function check2()
{
//若<form>屬性name值為reg裡的文字方塊值為空字串,則顯示「未輸入姓名」
if(reg2.key.value == "")
{
alert("未輸入股票代碼");
}else if(reg2.startDate.value == "")
{
alert("未輸入開始日期");
}else if(reg2.endDate.value == "")
{
alert("未輸入結束日期");
}
else reg2.submit();
}
|
var includes = require('../');
var test = require('tape');
test('as a function', function (t) {
t.test('bad array/this value', function (st) {
st.throws(includes.bind(null, undefined, 'a'), TypeError, 'undefined is not an object');
st.throws(includes.bind(null, null, 'a'), TypeError, 'null is not an object');
st.end();
});
require('./tests')(includes, t);
t.end();
});
|
var mongo = require('mongodb');
var RouteBase = require('./route-base');
var _ = require('underscore');
var Place = function(app, db, middleware) {
RouteBase.call(this, app, db, middleware, this.modelName, this.backboneModelPath);
};
_.extend(Place.prototype, RouteBase.prototype, {
modelName: 'places',
backboneModelPath: 'models/place.js',
attributesFindable: [
{
name: 'name',
uniq: false
}
],
additionalRoutes: [
{
method: 'post',
url: '/places/new',
callback: function(req, res) {
var processed = 0;
var newlyCreated = [];
if(!req.body.placeList) return;
console.log('Nombre a traiter: ' + req.body.placeList.length);
req.body.placeList.forEach(function(place) {
this.db.collection('places', function(err, collection) {
collection.findOne( { 'place_id': place.place_id }, function(err, resultFind) {
if(!resultFind) {
var model = {
place_id: place.place_id,
name: place.display_name.match(/[^,]*/)[0],
lat: place.lat,
lon: place.lon
};
console.log(model);
collection.insert( model, {safe: true}, function(err, resultInsert) {
if(err) { res.send(err, 500); }
else {
processed += 1;
newlyCreated.push(resultInsert[0]);
console.log('processed: ' + processed);
if(processed == req.body.placeList.length) {
res.send(newlyCreated, 200);
}
}
});
}
else {
processed += 1;
if(processed == req.body.placeList.length) {
res.send(newlyCreated, 200);
}
}
});
});
}, this);
}
}
]
});
module.exports = Place;
|
'use strict';
require.config({
paths: {
angular: '../lib/angular/angular.min',
ngCookies: '../lib/angular/angular-cookies.min',
upload: '../lib/upload/angular-file-upload.min',
uploadShim: '../lib/upload/angular-file-upload-shim.min',
ngSanitize: '../lib/angular/angular-sanitize',
breadcrumbs: '../lib/angular/ng-breadcrumbs',
routeResolver: '../js/routeResolver',
directives: '../js/directives',
services: '../js/services',
filters: '../js/filters',
jquery: '../lib/jquery/jquery',
tinymce: '../lib/tinymce/tinymce.min',
angularRoute: '../lib/angular/angular-route',
angularMocks: '../lib/angular/angular-mocks',
text: '../lib/requirejs-text/text',
bootstrap: '../lib/bootstrap/ui-bootstrap',
css: '../lib/css/css.min',
modules: '../modules',
},
shim: {
'angular' : {'exports' : 'angular'},
'routeResolver': { "deps": ['angular', 'angularRoute'] },
'breadcrumbs': { "deps": ['angular', 'angularRoute'] },
'bootstrap': { "deps": ['angular'] },
'filters': { "deps": ['angular'] },
'services': { "deps": ['angular'] },
'directives': { "deps": ['angular'] },
'upload': { "deps": ['angular'] },
'uploadShim': { "deps": ['angular'] },
'angularRoute': ['angular'],
'ngCookies': ['angular'],
'ngSanitize': ['angular'],
'angularMocks': {
deps:['angular'],
'exports':'angular.mock'
}
},
priority: [
"angular"
],
});
require([
'angular',
'app'
], function(angular, angularRoute, app) {
var $html = angular.element(document.getElementsByTagName('html')[0]);
angular.element().ready(function() {
// bootstrap the app manually
angular.bootstrap(document, ['apnasitePortal']);
});
}
);
|
export default function Ear(v0, v1, v2) {
return [v0, v1, v2];
}
|
var request = require('request');
//新增
request.post({
url: 'http://127.0.0.1:3000/classify/add',
form: {
"description": "添加数据,父级",
"parent": "57221816fde0e2f818cbce61",
"other_data": "other data"
}
}, function(err, res, body) {
console.log(body);
});
|
$(function() {
// 开始结束时间
var dates = $("#start,#end");
dates.datepicker({
dateFormat: "yy-mm-dd",
minDate: new Date(),
onSelect: function(selectedDate){
var option = this.id == "start" ? "minDate" : "maxDate";
dates.not(this).datepicker("option", option, selectedDate);
}
});
// 广告图上传
UPLOAD_URL = "/v2admin/ghost/avatarUpload";
IMAGE_URL = "/";
$('#avatarUpload').fileupload({
url: UPLOAD_URL,
dataType: 'json',
done: function (e, data) {
$.each(data.result.files, function (index, file) {
$('#files').html('');
var text = '<p><img style="margin:5px; float: left; width=80px;" src="'+IMAGE_URL+file.link+'"><d class="close"></d><input type="hidden" name="avatar" value="'+file.link+'"></p>';
$('#files').append(text);
});
},
}).prop('disabled', !$.support.fileInput).parent().addClass($.support.fileInput ? undefined : 'disabled');
// 删除图片
$(document).on('click', '.close', function(){
$(this).parent().remove();
});
/*var UPLOAD_PATH = "upload/avatar/";
var WH = '?imageView2/1/w/80/h/80';//缩略
$("#avatarUpload").change(function(){
var f = $(this).prop("files")[0];
var token = $("#token").val();
var res = Qiniu_upload(f, token, '', UPLOAD_PATH);
res.done(function( msg ) {
console && console.log(msg);
//$('#files').html('');
//var link = msg['x:album'];
//var text = '<p><img style="margin:5px; float: left; width:80px;" src="'+link+WH+'"><d class="close"></d><input type="hidden" name="avatar" value="'+msg.key+'"></p>';
//$('#files').append(text);
});
res.fail(function( jqXHR, textStatus ) {
alert("图片上传失败,请刷新页面再上传");
});
});*/
});
|
// Amazon s3-based backend for uploadfs. See also
// local.js.
var fs = require('fs');
var knox = require('knox');
var extname = require('path').extname;
var contentTypes;
var client;
var https;
var bucket;
var self = module.exports = {
init: function(options, callback) {
client = knox.createClient(options);
if (options.contentTypes) {
contentTypes = options.contentTypes;
} else {
contentTypes = require(__dirname + '/contentTypes.js');
}
bucket = options.bucket;
https = options.https;
return callback(null);
},
copyIn: function(localPath, path, options, callback) {
var ext = extname(path);
if (ext.length) {
ext = ext.substr(1);
}
var contentType = contentTypes[ext];
if (!contentType) {
contentType = 'application/octet-stream';
}
client.putFile(localPath, path, { 'x-amz-acl': 'public-read', 'Content-Type': contentType }, callback);
},
// getFile does not copy to a local file, it fetches the whole thing into memory.
// Since we don't want that, implement streaming with client.get()
copyOut: function(path, localPath, options, callback) {
client.get(path).on('response', function(res) {
if ((res.statusCode < 200) || (res.statusCode >= 300)) {
return callback(res.statusCode);
}
var out = fs.createWriteStream(localPath);
res.pipe(out);
var dead = false;
function die(err) {
if (!dead) {
dead = true;
res.end();
out.end();
return callback(err);
}
}
res.on('error', function(err) {
return die(err);
});
out.on('error', function(err) {
return die(err);
});
out.on('close', function() {
if (!dead) {
return callback(null);
}
});
}).on('error', function(err) {
return callback(err);
}).end();
},
remove: function(path, callback) {
client.deleteFile(path, function(err, res) {
callback(err);
});
},
enable: function(path, callback) {
var req = client.request('PUT', path + '?acl', {
'x-amz-acl': 'public-read'
}).on('response', function(res) {
if (res.statusCode === 200) {
return callback(null);
} else {
return callback(res.statusCode);
}
});
req.end();
},
disable: function(path, callback) {
var req = client.request('PUT', path + '?acl', {
'x-amz-acl': 'private'
}).on('response', function(res) {
if (res.statusCode === 200) {
return callback(null);
} else {
return callback(res.statusCode);
}
});
req.end();
},
getUrl: function(path) {
return (https ? 'https://' : 'http://') + bucket + '.s3.amazonaws.com';
}
};
|
'use strict';
/* eslint-disable no-unused-vars */
const readFile = require('fs').readFileSync;
const writeFile = require('fs').writeFileSync;
const should = require('should');
const cli = require('../lib');
const pathJoin = require('path').join;
const pathSeparator = require('path').sep;
const packageName = require('./utils/publish-please-version-under-test');
const nodeInfos = require('../lib/utils/get-node-infos').getNodeInfosSync();
const fileExists = require('fs').existsSync;
const lineSeparator = '----------------------------------';
/** !!!!!!!!!!!!!!!!!!!!!! WARNING !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
* These tests runs publish-please code on publish-please repo itself
* These tests relies on the content of the .publishrc file located in the project root folder
* Modifying this .publishrc file might create a test that loops for eternity
* The publishing tests MUST always fail to ensure there will never be a real publish to npm during a test run
*/
describe('Publish-please CLI Options', () => {
let originalWorkingDirectory;
let nativeExit;
let nativeConsoleLog;
let exitCode;
let output;
let originalConfiguration;
let originalArgv;
before(() => {
originalWorkingDirectory = process.cwd();
originalConfiguration = JSON.parse(readFile('.publishrc').toString());
});
after(() => {
writeFile('.publishrc', JSON.stringify(originalConfiguration, null, 2));
console.log(`cwd is restored to: ${process.cwd()}`);
});
beforeEach(() => {
console.log(`${lineSeparator} begin test ${lineSeparator}`);
process.env.PUBLISH_PLEASE_TEST_MODE = false;
delete process.env.TEAMCITY_VERSION;
exitCode = undefined;
output = '';
nativeExit = process.exit;
nativeConsoleLog = console.log;
process.exit = (val) => {
// nativeConsoleLog(val);
if (exitCode === undefined) exitCode = val;
};
console.log = (p1, p2, p3) => {
if (p1 === undefined) {
return;
}
// prettier-ignore
// eslint-disable-next-line no-nested-ternary
p2 === undefined
? nativeConsoleLog(p1)
: p3 === undefined
? nativeConsoleLog(p1, p2)
: nativeConsoleLog(p1, p2, p3);
output = `${output}${p1 === undefined ? '' : p1}${
p2 === undefined ? '' : p2
}${p3 === undefined ? '' : p3}`;
};
originalArgv = process.argv.map((arg) => arg);
// patch the .publishrc file to make sure publishing will fail
const publishrc = JSON.parse(readFile('.publishrc').toString());
publishrc.prePublishScript =
"echo 'npm test started by publish-please'";
writeFile('.publishrc', JSON.stringify(publishrc, null, 2));
});
afterEach(() => {
process.exit = nativeExit;
console.log = nativeConsoleLog;
delete process.env.PUBLISH_PLEASE_TEST_MODE;
process.argv = originalArgv;
writeFile('.publishrc', JSON.stringify(originalConfiguration, null, 2));
process.chdir(originalWorkingDirectory);
console.log(`${lineSeparator} end test ${lineSeparator}\n`);
});
it('Should execute dry-run workflow on `npm run publish-please --dry-run`', () => {
// Given
process.env['npm_config_argv'] =
'{"remain":[],"cooked":["run","publish-please","--dry-run"],"original":["run","publish-please","--dry-run"]}';
// When
return (
cli()
// Then
.catch((err) => {
output.should.containEql('ERRORS');
output.should.containEql('dry mode activated');
(exitCode || 0).should.be.equal(1);
})
);
});
it('Should execute dry-run workflow with no errors on `npm run publish-please --dry-run`', () => {
// Given
process.env['npm_config_argv'] =
'{"remain":[],"cooked":["run","publish-please","--dry-run"],"original":["run","publish-please","--dry-run"]}';
const publishrc = JSON.parse(readFile('.publishrc').toString());
publishrc.confirm = false;
publishrc.validations.vulnerableDependencies = false;
// prettier-ignore
nodeInfos.npmPackHasJsonReporter
? publishrc.validations.sensitiveData = true
: publishrc.validations.sensitiveData = false;
publishrc.validations.uncommittedChanges = false;
publishrc.validations.untrackedFiles = false;
publishrc.validations.gitTag = false;
publishrc.validations.branch = false;
publishrc.publishCommand = "echo 'npm publish'";
writeFile('.publishrc', JSON.stringify(publishrc, null, 2));
// When
return (
cli()
// Then
.then(() => {
output.should.not.containEql('ERRORS');
output.should.containEql('dry mode activated');
output.should.containEql('Running pre-publish script');
nodeInfos.npmPackHasJsonReporter
? output.should.containEql('Running validations')
: output.should.not.containEql('Running validations');
output.should.containEql('Release info');
(exitCode || 0).should.be.equal(0);
// prettier-ignore
const packageFilename = `${packageName.replace('@','-')}.tgz`;
fileExists(packageFilename).should.be.false();
})
);
});
it('Should execute dry-run workflow with no errors on `npm run publish-please --dry-run --ci`', () => {
// Given
process.env['npm_config_argv'] =
'{"remain":[],"cooked":["run","publish-please","--dry-run", "--ci"],"original":["run","publish-please","--dry-run", "--ci"]}';
const publishrc = JSON.parse(readFile('.publishrc').toString());
publishrc.confirm = false;
publishrc.validations.vulnerableDependencies = false;
// prettier-ignore
nodeInfos.npmPackHasJsonReporter
? publishrc.validations.sensitiveData = true
: publishrc.validations.sensitiveData = false;
publishrc.validations.uncommittedChanges = false;
publishrc.validations.untrackedFiles = false;
publishrc.validations.gitTag = false;
publishrc.validations.branch = false;
publishrc.publishCommand = "echo 'npm publish'";
writeFile('.publishrc', JSON.stringify(publishrc, null, 2));
const projectName = process
.cwd()
.split(pathSeparator)
.pop();
// When
return (
cli()
// Then
.then(() => {
output.should.not.containEql('ERRORS');
output.should.containEql('dry mode activated');
output.should.containEql('Running pre-publish script');
nodeInfos.npmPackHasJsonReporter
? output.should.containEql('Running validations')
: output.should.not.containEql('Running validations');
output.should.containEql('Release info');
output.should.containEql(
`${projectName} is safe to be published`
);
(exitCode || 0).should.be.equal(0);
// prettier-ignore
const packageFilename = `${packageName.replace('@','-')}.tgz`;
fileExists(packageFilename).should.be.false();
})
);
});
it('Should execute dry-run workflow with no errors on `npm run publish-please --dry-run --ci` (TeamCity env)', () => {
// Given
process.env.TEAMCITY_VERSION = '1.0.0';
process.env['npm_config_argv'] =
'{"remain":[],"cooked":["run","publish-please","--dry-run", "--ci"],"original":["run","publish-please","--dry-run", "--ci"]}';
const publishrc = JSON.parse(readFile('.publishrc').toString());
publishrc.confirm = false;
publishrc.validations.vulnerableDependencies = false;
// prettier-ignore
nodeInfos.npmPackHasJsonReporter
? publishrc.validations.sensitiveData = true
: publishrc.validations.sensitiveData = false;
publishrc.validations.uncommittedChanges = false;
publishrc.validations.untrackedFiles = false;
publishrc.validations.gitTag = false;
publishrc.validations.branch = false;
publishrc.publishCommand = "echo 'npm publish'";
writeFile('.publishrc', JSON.stringify(publishrc, null, 2));
const projectName = process
.cwd()
.split(pathSeparator)
.pop();
// When
return (
cli()
// Then
.then(() => {
output.should.not.containEql('ERRORS');
output.should.containEql('dry mode activated');
output.should.containEql('Running pre-publish script');
nodeInfos.npmPackHasJsonReporter
? output.should.containEql('Running validations')
: output.should.not.containEql('Running validations');
if (nodeInfos.npmPackHasJsonReporter) {
output.should.containEql(
'[v] Checking for the sensitive and non-essential data in the npm package'
);
}
output.should.containEql('Release info');
output.should.containEql(
`${projectName} is safe to be published`
);
(exitCode || 0).should.be.equal(0);
// prettier-ignore
const packageFilename = `${packageName.replace('@','-')}.tgz`;
fileExists(packageFilename).should.be.false();
})
);
});
it('Should execute publish workflow with no errors on `npm run publish-please --ci`', () => {
// Given
process.env['npm_config_argv'] =
'{"remain":[],"cooked":["run","publish-please", "--ci"],"original":["run","publish-please", "--ci"]}';
const publishrc = JSON.parse(readFile('.publishrc').toString());
publishrc.confirm = false;
publishrc.validations.vulnerableDependencies = false;
// prettier-ignore
nodeInfos.npmPackHasJsonReporter
? publishrc.validations.sensitiveData = true
: publishrc.validations.sensitiveData = false;
publishrc.validations.uncommittedChanges = false;
publishrc.validations.untrackedFiles = false;
publishrc.validations.gitTag = false;
publishrc.validations.branch = false;
publishrc.publishCommand = "echo 'npm publish'";
writeFile('.publishrc', JSON.stringify(publishrc, null, 2));
const projectName = process
.cwd()
.split(pathSeparator)
.pop();
// When
return (
cli()
// Then
.then(() => {
output.should.not.containEql('ERRORS');
output.should.not.containEql('dry mode activated');
output.should.containEql('Running pre-publish script');
nodeInfos.npmPackHasJsonReporter
? output.should.containEql('Running validations')
: output.should.not.containEql('Running validations');
output.should.containEql('Release info');
output.should.containEql(
`${projectName} has been successfully published`
);
(exitCode || 0).should.be.equal(0);
// prettier-ignore
const packageFilename = `${packageName.replace('@','-')}.tgz`;
fileExists(packageFilename).should.be.false();
})
);
});
it('Should execute dry-run workflow with errors on `npx publish-please --dry-run`', () => {
// Given
process.env['npm_config_argv'] = undefined;
// [ '/usr/local/bin/node',
// '/Users/HDO/.npm/_npx/97852/bin/publish-please',
// '--dry-run'
// ]
process.argv = [
pathJoin('usr', 'local', 'bin', 'node'),
pathJoin(
'Users',
'xxx',
'.npm',
'_npx',
'97852',
'bin',
'publish-please'
),
'--dry-run',
];
// When
return (
cli()
// Then
.catch((err) => {
output.should.containEql('dry mode activated');
output.should.containEql('ERRORS');
(exitCode || 0).should.be.equal(1);
})
);
});
it('Should execute dry-run workflow with errors on `npx publish-please --dry-run --ci` (TeamCity env)', () => {
// Given
process.env.TEAMCITY_VERSION = '1.0.0';
process.env['npm_config_argv'] = undefined;
// [ '/usr/local/bin/node',
// '/Users/HDO/.npm/_npx/97852/bin/publish-please',
// '--dry-run'
// '--ci'
// ]
process.argv = [
pathJoin('usr', 'local', 'bin', 'node'),
pathJoin(
'Users',
'xxx',
'.npm',
'_npx',
'97852',
'bin',
'publish-please'
),
'--dry-run',
'--ci',
];
// When
return (
cli()
// Then
.catch((err) => {
output.should.containEql('dry mode activated');
output.should.containEql('ERRORS');
output.should.containEql('[x] ');
(exitCode || 0).should.be.equal(1);
})
);
});
it('Should execute dry-run workflow with no errors on `npx publish-please --dry-run`', () => {
// Given
process.env['npm_config_argv'] = undefined;
// [ '/usr/local/bin/node',
// '/Users/HDO/.npm/_npx/97852/bin/publish-please',
// '--dry-run'
// ]
process.argv = [
pathJoin('usr', 'local', 'bin', 'node'),
pathJoin(
'Users',
'xxx',
'.npm',
'_npx',
'97852',
'bin',
'publish-please'
),
'--dry-run',
];
const publishrc = JSON.parse(readFile('.publishrc').toString());
publishrc.confirm = false;
publishrc.validations.vulnerableDependencies = false;
// prettier-ignore
nodeInfos.npmPackHasJsonReporter
? publishrc.validations.sensitiveData = true
: publishrc.validations.sensitiveData = false;
publishrc.validations.uncommittedChanges = false;
publishrc.validations.untrackedFiles = false;
publishrc.validations.gitTag = false;
publishrc.validations.branch = false;
writeFile('.publishrc', JSON.stringify(publishrc, null, 2));
// When
return (
cli()
// Then
.then(() => {
output.should.not.containEql('ERRORS');
output.should.containEql('dry mode activated');
output.should.containEql('Running pre-publish script');
nodeInfos.npmPackHasJsonReporter
? output.should.containEql('Running validations')
: output.should.not.containEql('Running validations');
output.should.containEql('Release info');
(exitCode || 0).should.be.equal(0);
// prettier-ignore
const packageFilename = `${packageName.replace('@','-')}.tgz`;
fileExists(packageFilename).should.be.false();
})
);
});
it('Should execute dry-run workflow with no errors on `npx publish-please --dry-run --ci`', () => {
// Given
process.env['npm_config_argv'] = undefined;
// [ '/usr/local/bin/node',
// '/Users/HDO/.npm/_npx/97852/bin/publish-please',
// '--dry-run'
// '--ci'
// ]
process.argv = [
pathJoin('usr', 'local', 'bin', 'node'),
pathJoin(
'Users',
'xxx',
'.npm',
'_npx',
'97852',
'bin',
'publish-please'
),
'--dry-run',
'--ci',
];
const publishrc = JSON.parse(readFile('.publishrc').toString());
publishrc.confirm = false;
publishrc.validations.vulnerableDependencies = false;
// prettier-ignore
nodeInfos.npmPackHasJsonReporter
? publishrc.validations.sensitiveData = true
: publishrc.validations.sensitiveData = false;
publishrc.validations.uncommittedChanges = false;
publishrc.validations.untrackedFiles = false;
publishrc.validations.gitTag = false;
publishrc.validations.branch = false;
writeFile('.publishrc', JSON.stringify(publishrc, null, 2));
const projectName = process
.cwd()
.split(pathSeparator)
.pop();
// When
return (
cli()
// Then
.then(() => {
output.should.not.containEql('ERRORS');
output.should.containEql('dry mode activated');
output.should.containEql('Running pre-publish script');
nodeInfos.npmPackHasJsonReporter
? output.should.containEql('Running validations')
: output.should.not.containEql('Running validations');
output.should.containEql('Release info');
output.should.containEql(
`${projectName} is safe to be published`
);
(exitCode || 0).should.be.equal(0);
// prettier-ignore
const packageFilename = `${packageName.replace('@','-')}.tgz`;
fileExists(packageFilename).should.be.false();
})
);
});
it('Should execute publishing workflow on `npx publish-please`', () => {
// Given
process.env['npm_config_argv'] = undefined;
// [ '/usr/local/bin/node',
// '/Users/HDO/.npm/_npx/97852/bin/publish-please',
// '--dry-run'
// ]
process.argv = [
pathJoin('usr', 'local', 'bin', 'node'),
pathJoin(
'Users',
'xxx',
'.npm',
'_npx',
'97852',
'bin',
'publish-please'
),
];
// When
return (
cli()
// Then
.catch((err) => {
output.should.not.containEql('dry mode activated');
output.should.containEql('Running pre-publish script');
output.should.containEql('Running validations');
output.should.containEql('ERRORS');
(exitCode || 0).should.be.equal(1);
})
);
});
it('Should execute publish workflow with no errors on `npx publish-please --ci`', () => {
// Given
process.env['npm_config_argv'] = undefined;
// [ '/usr/local/bin/node',
// '/Users/HDO/.npm/_npx/97852/bin/publish-please',
// '--ci'
// ]
process.argv = [
pathJoin('usr', 'local', 'bin', 'node'),
pathJoin(
'Users',
'xxx',
'.npm',
'_npx',
'97852',
'bin',
'publish-please'
),
'--ci',
];
const publishrc = JSON.parse(readFile('.publishrc').toString());
publishrc.confirm = false;
publishrc.validations.vulnerableDependencies = false;
// prettier-ignore
nodeInfos.npmPackHasJsonReporter
? publishrc.validations.sensitiveData = true
: publishrc.validations.sensitiveData = false;
publishrc.validations.uncommittedChanges = false;
publishrc.validations.untrackedFiles = false;
publishrc.validations.gitTag = false;
publishrc.validations.branch = false;
publishrc.publishCommand = "echo 'npm publish'";
writeFile('.publishrc', JSON.stringify(publishrc, null, 2));
const projectName = process
.cwd()
.split(pathSeparator)
.pop();
// When
return (
cli()
// Then
.then(() => {
output.should.not.containEql('ERRORS');
output.should.not.containEql('dry mode activated');
output.should.containEql('Running pre-publish script');
nodeInfos.npmPackHasJsonReporter
? output.should.containEql('Running validations')
: output.should.not.containEql('Running validations');
output.should.containEql('Release info');
output.should.containEql(
`${projectName} has been successfully published`
);
(exitCode || 0).should.be.equal(0);
// prettier-ignore
const packageFilename = `${packageName.replace('@','-')}.tgz`;
fileExists(packageFilename).should.be.false();
})
);
});
it('Should execute configuration workflow on `npx publish-please config`', () => {
// Given
process.env.PUBLISH_PLEASE_TEST_MODE = true;
process.env['npm_config_argv'] = undefined;
// [ '/usr/local/bin/node',
// '/Users/HDO/.npm/_npx/97852/bin/publish-please',
// 'config'
// ]
process.argv = [
pathJoin('usr', 'local', 'bin', 'node'),
pathJoin(
'Users',
'xxx',
'.npm',
'_npx',
'97852',
'bin',
'publish-please'
),
'config',
];
// When
return cli().then(() => {
output.should.containEql('Configuring option "prePublishScript":');
output.should.containEql('Configuring option "postPublishScript":');
output.should.containEql('Configuring option "publishCommand":');
output.should.containEql('Configuring option "publishTag"');
output.should.containEql('Configuring option "confirm":');
output.should.containEql(
'Configuring validation "vulnerableDependencies"'
);
output.should.containEql(
'Configuring validation "uncommittedChanges":'
);
output.should.containEql(
'Configuring validation "untrackedFiles":'
);
output.should.containEql('Configuring validation "sensitiveData":');
output.should.containEql('Configuring validation "branch":');
output.should.containEql('Configuring validation "gitTag"');
output.should.containEql('Current configuration:');
output.should.containEql(
'Configuration has been successfully saved.'
);
});
});
it('Should execute guard on `publish-please guard`', () => {
// Given
process.env['npm_config_argv'] =
'{"remain":[],"cooked":["publish"],"original":["publish"]}';
process.argv.push('guard');
// When
cli();
// Then
exitCode.should.be.equal(1);
output.should.containEql("'npm publish' is forbidden for this package");
});
/**
* This test executes against the .publishrc file in publish-please root project
* It verifies that when you run the configuration wizard and choose all default values
* you got the same exact configuration.
* So be aware that changing any values in the .publishrc file will make this test fails
*/
it('Should execute configuration wizard on `npm run publish-please config`', () => {
// Given
process.env.PUBLISH_PLEASE_TEST_MODE = true;
process.env['npm_config_argv'] =
'{"remain":["config"],"cooked":["run","publish-please","config"],"original":["run","publish-please","config"]}';
// When
cli();
// Then
(exitCode || 0).should.be.equal(0);
const publishrc = JSON.parse(readFile('.publishrc').toString());
publishrc.confirm.should.be.true();
publishrc.prePublishScript.should.equal(
"echo 'npm test started by publish-please'"
);
publishrc.postPublishScript.should.equal('');
publishrc.publishCommand.should.equal('npm publish');
publishrc.publishTag.should.equal('latest');
publishrc.validations.branch.should.equal('master');
publishrc.validations.uncommittedChanges.should.be.true();
publishrc.validations.untrackedFiles.should.be.true();
publishrc.validations.vulnerableDependencies.should.be.true();
publishrc.validations.sensitiveData.should.be.true();
publishrc.validations.gitTag.should.be.true();
publishrc.validations.branch.should.equal('master');
});
});
|
/* eslint no-console:0 */
// This file is automatically compiled by Webpack, along with any other files
// present in this directory. You're encouraged to place your actual application logic in
// a relevant structure within app/javascript and only use these pack files to reference
// that code so it'll be compiled.
//
// To reference this file, add <%= javascript_pack_tag 'application' %> to the appropriate
// layout file, like app/views/layouts/application.html.erb
// Uncomment to copy all static images under ../images to the output folder and reference
// them with the image_pack_tag helper in views (e.g <%= image_pack_tag 'rails.png' %>)
// or the `imagePath` JavaScript helper below.
//
// const images = require.context('../images', true)
// const imagePath = (name) => images(name, true)
import "core-js/stable";
import "regenerator-runtime/runtime";
import IMask from 'imask';
import jQuery from 'jquery'
window.$ = jQuery;
window.jQuery = jQuery;
require('popup');
require('select2');
require('jquery-migrate');
require('jquery.history');
require('jquery-next-id/jquery.nextid');
require('jquery-roving-tabindex/jquery.rovingtabindex');
require('jquery-tabs/jquery.tabs');
require('mark.js/dist/jquery.mark');
require('alphagov-static/app/assets/javascripts/analytics/pii');
require('alphagov-static/app/assets/javascripts/analytics_toolkit/google-analytics-universal-tracker');
require('alphagov-static/app/assets/javascripts/analytics_toolkit/analytics');
require('alphagov-static/app/assets/javascripts/analytics_toolkit/govuk-tracker');
require('alphagov-static/app/assets/javascripts/analytics_toolkit/print-intent');
require('alphagov-static/app/assets/javascripts/analytics_toolkit/error-tracking');
// console.log('popup');
// console.log(BetaPopup);
// BetaPopup.popup('title', 'tariff-info');
// console.log(
// require('jquery-debouncedresize')
// );
// console.log(
// import('jquery-debouncedresize')
// );
// require('./node_modules/jquery-history/dist/jquery.history');
// require('../../../node_modules/jquery-history/dist/jquery.history');
// require('jquery-history/dist/jquery.history');
require('../src/javascripts/datepicker-day.js');
require('../src/javascripts/calendar-button.js');
require('../src/javascripts/datepicker.js');
window.accessibleAutocomplete = require('../src/javascripts/accessible-autocomplete.min.js');
require('../src/javascripts/analytics-init.js');
require('../src/javascripts/analytics-search-queries.js');
require('../src/javascripts/commodities.js');
// TODO test:
require('../src/javascripts/exchange_rate.js');
require('../src/javascripts/feedback.js');
require('../src/javascripts/quota-search.js');
require('../src/javascripts/stop-scrolling-at-footer.js');
import { initAll } from 'govuk-frontend';
initAll();
$(function(){
GOVUK.tariff.onLoad();
});
|
function HTMLActuator() {
this.tileContainer = document.querySelector(".tile-container");
this.scoreContainer = document.querySelector(".score-container");
this.bestContainer = document.querySelector(".best-container");
this.messageContainer = document.querySelector(".game-message");
this.score = 0;
}
HTMLActuator.prototype.actuate = function (grid, metadata) {
var self = this;
window.requestAnimationFrame(function () {
self.clearContainer(self.tileContainer);
grid.cells.forEach(function (column) {
column.forEach(function (cell) {
if (cell) {
self.addTile(cell);
}
});
});
self.updateScore(metadata.score);
self.updateBestScore(metadata.bestScore);
if (metadata.terminated) {
if (metadata.over) {
self.message(false); // You lose
} else if (metadata.won) {
self.message(true); // You win!
}
}
});
};
// Continues the game (both restart and keep playing)
HTMLActuator.prototype.continue = function () {
this.clearMessage();
};
HTMLActuator.prototype.clearContainer = function (container) {
while (container.firstChild) {
container.removeChild(container.firstChild);
}
};
HTMLActuator.prototype.addTile = function (tile) {
var self = this;
var wrapper = document.createElement("div");
var inner = document.createElement("div");
var position = tile.previousPosition || { x: tile.x, y: tile.y };
var positionClass = this.positionClass(position);
// We can't use classlist because it somehow glitches when replacing classes
var classes = ["tile", "tile-" + tile.value, positionClass];
if (tile.value > 2048) classes.push("tile-super");
this.applyClasses(wrapper, classes);
inner.classList.add("tile-inner");
inner.textContent = tile.value;
if (tile.previousPosition) {
// Make sure that the tile gets rendered in the previous position first
window.requestAnimationFrame(function () {
classes[2] = self.positionClass({ x: tile.x, y: tile.y });
self.applyClasses(wrapper, classes); // Update the position
});
} else if (tile.mergedFrom) {
classes.push("tile-merged");
this.applyClasses(wrapper, classes);
// Render the tiles that merged
tile.mergedFrom.forEach(function (merged) {
self.addTile(merged);
});
} else {
classes.push("tile-new");
this.applyClasses(wrapper, classes);
}
// Add the inner part of the tile to the wrapper
wrapper.appendChild(inner);
// Put the tile on the board
this.tileContainer.appendChild(wrapper);
};
HTMLActuator.prototype.applyClasses = function (element, classes) {
element.setAttribute("class", classes.join(" "));
};
HTMLActuator.prototype.normalizePosition = function (position) {
return { x: position.x + 1, y: position.y + 1 };
};
HTMLActuator.prototype.positionClass = function (position) {
position = this.normalizePosition(position);
return "tile-position-" + position.x + "-" + position.y;
};
HTMLActuator.prototype.updateScore = function (score) {
this.clearContainer(this.scoreContainer);
var difference = score - this.score;
this.score = score;
this.scoreContainer.textContent = this.score;
if (difference > 0) {
var addition = document.createElement("div");
addition.classList.add("score-addition");
addition.textContent = "+" + difference;
this.scoreContainer.appendChild(addition);
}
};
HTMLActuator.prototype.updateBestScore = function (bestScore) {
this.bestContainer.textContent = bestScore;
};
HTMLActuator.prototype.message = function (won) {
var type = won ? "game-won" : "game-over";
var message = won ? "Gagné!" : "Perdu!";
this.messageContainer.classList.add(type);
this.messageContainer.getElementsByTagName("p")[0].textContent = message;
};
HTMLActuator.prototype.clearMessage = function () {
// IE only takes one value to remove at a time.
this.messageContainer.classList.remove("game-won");
this.messageContainer.classList.remove("game-over");
};
|
class imekeyeventhandler1041_1 {
constructor() {
}
// System.Runtime.Remoting.ObjRef CreateObjRef(type requestedType)
CreateObjRef() {
}
// bool Equals(System.Object obj)
Equals() {
}
// int GetHashCode()
GetHashCode() {
}
// System.Object GetLifetimeService()
GetLifetimeService() {
}
// type GetType()
GetType() {
}
// System.Object InitializeLifetimeService()
InitializeLifetimeService() {
}
// string ToString()
ToString() {
}
}
module.exports = imekeyeventhandler1041_1;
|
var Monitor = require('../../models/Monitor.js');
function monitorAction (req, res) {
function success () {
res.redirect('/monitor');
}
function fail () {
res.send(500);
}
switch (req.body.action) {
case 'delete':
Monitor
.remove(req.body.selected)
.then(success, fail);
break;
default:
success();
}
}
module.exports = monitorAction;
|
import React, {PropTypes} from 'react'
import _ from 'lodash'
export class KeyPressInput extends React.Component {
static propTypes = {
header: PropTypes.object.isRequired,
queryChange: PropTypes.func.isRequired
}
handleChange(ev) {
const { header } = this.props
this.props.queryChange(header, ev.target.value)
}
render() {
return (
<input {...this.props} ref={this.props.update} className="form-control" type="text" onChange={::this.handleChange} />
)
}
}
export class CompletedInput extends React.Component {
static propTypes = {
header: PropTypes.object.isRequired,
queryChange: PropTypes.func.isRequired
}
handleChange(ev) {
const { header } = this.props
this.props.queryChange(header, ev.target.value)
}
submit(ev) {
if (ev.key === 'Enter')
this.handleChange(ev)
}
render() {
return (
<input {...this.props} ref={this.props.update} className="form-control" type="text" onKeyPress={::this.submit} onBlur={::this.handleChange} />
)
}
}
export default class QueryInput extends React.Component {
static propTypes = {
header: PropTypes.object.isRequired,
queryChange: PropTypes.func.isRequired
}
debounced() {
return _.debounce(this.props.queryChange, 1000)
}
updateRef() {
const noop = () => { }
return this.props.update || noop
}
render() {
if (this.props.updateOnKeyPress)
return <KeyPressInput {...this.props} update={this.updateRef()} queryChange={this.debounced()} />
return <CompletedInput {...this.props} update={this.updateRef()} />
}
}
|
import {Observable} from 'rxjs'
export const createSocketIoChannel = requestTransform => socket => {
const $data = Observable.fromEvent(socket, 'data')
requestTransform($data).subscribe(data => socket.emit(data))
}
|
function dist2(p1, p2) {
var dx = p1[0] - p2[0];
var dy = p1[1] - p2[1];
return dx * dx + dy * dy;
}
window.onload = function() {
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
function draw_marker(x, y, r) {
context.beginPath();
context.arc(x, y, r, 0, Math.PI*2);
context.closePath();
context.fillStyle = "#00F";
context.fill();
}
function draw_segment(x1, y1, x2, y2) {
context.beginPath();
context.moveTo(x1, y1);
context.lineTo(x2, y2);
context.strokeStyle = "#0F0";
context.stroke();
context.closePath();
}
function simplify_spline(spold, tolerance) {
// Simplifies the source spline by trying to find a smaller set of points
// which fit within @tolerance.
var tolerance2 = tolerance ? tolerance * tolerance : 10;
//var subdivide = [ 1./4, 3./8, 1./2, 5./8, 3./4 ];
var ts = [ 0, 1 ];
var spnew = numeric.spline(ts, spold.at(ts));
for (var j=0; j<6; j++) {
for (var i=ts.length-1; i>0; i--) {
var mt;
var mdd = 0;
for (var k in subdivide) {
var t = ts[i] * subdivide[k] + ts[i-1] * (1 - subdivide[k]);
var po = spold.at(t);
var pn = spnew.at(t);
var dd = dist2(po, pn);
if (dd > mdd) {
mt = t;
mdd = dd;
}
}
if (mdd > tolerance2) {
ts.splice(i, 0, mt);
}
}
spnew = numeric.spline(ts, spold.at(ts));
}
for (var i=0; i<ts.length; i++) {
var xy = spnew.at(ts[i]);
//draw_marker(xy[0], xy[1], 5);
}
return spnew;
}
function draw_spline(spline, style) {
var xys = spline.at(numeric.linspace(0,1,100));
context.beginPath();
context.moveTo(xys[0][0], xys[0][1]);
for (var i=1; i<xys.length; i++) {
context.lineTo(xys[i][0], xys[i][1]);
}
context.strokeStyle = style;
context.stroke();
context.closePath();
}
canvas.onmousedown = canvas.ontouchstart = function (e) {
var td = 0;
var ox = e.clientX || e.touches[0].pageX;
var oy = e.clientY || e.touches[0].pageY;
var xys = [ [ox, oy] ];
var dds = [ 0 ];
canvas.onmousemove = canvas.ontouchmove = function (e) {
e.preventDefault();
var nx = e.clientX || e.touches[0].pageX;
var ny = e.clientY || e.touches[0].pageY;
var dx = nx - ox;
var dy = ny - oy;
var dd = Math.sqrt(dx*dx + dy*dy);
if (dd > 10) {
draw_segment(ox, oy, nx, ny);
xys.push([nx, ny]);
td += dd;
dds.push(td);
ox = nx;
oy = ny;
}
}
canvas.onmouseup = canvas.onmouseout = canvas.ontouchend = function (e) {
canvas.onmousemove = canvas.ontouchmove = null;
if (dds.length > 1) {
var ts = [];
for (var i in dds) {
ts.push(dds[i]/td);
}
var ss = numeric.spline(ts, xys);
draw_spline(ss, "#F00");
var ss2 = simplify_spline(ss);
draw_spline(ss2, "#00F");
}
};
}
};
|
//! moment-holiday.js locale configuration
//! locale : UK
//! author : Kodie Grantham : https://github.com/kodie
//! locale-author: DMCooper : https://github.com/SilentGamelan
//
/* regions :
EN : England
SL : Scotland
WL : Wales
NI : Northern Island
*/
(function() {
var moment = (typeof require !== 'undefined' && require !== null) && !require.amd ? require('moment') : this.moment;
moment.holidays.united_kingdom = {
"New Year's Day": {
date: '1/1',
keywords_n: ['eve']
},
"Saint David's Day": {
date: '3/1',
keywords:['David', 'st[\\s\\.]'],
regions: ['WL']
},
"Saint Patrick's Day": {
date: '3/17',
keywords:['paddy', 'st[\\s\\.]'],
regions: ['NI']
},
"Good Friday": {
date: 'easter-2',
keywords_y: ['good', 'friday'],
},
"Easter Sunday": {
date: 'easter',
keywords_y: ['easter'],
keywords:['sunday']
},
"Easter Monday": {
date: 'easter+1)',
keywords_y: ['easter'],
keywords: ['monday'],
regions: ['EN', 'NI', 'WL']
},
"Mothering Sunday": {
date: 'easter-21',
keywords_y:['mother'],
keywords: ['sunday', 'day']
},
"Saint George's Day": {
date: '4/24',
keywords: ['st[\\s\\.]', 'george'],
regions: ['EN']
},
"May Day": {
date: '5/1'
},
"Early May Bank Holiday" : {
date: '5/(1,1)',
keywords_y: ['may'],
keywords: ['spring', 'early', 'may']
},
"Spring Bank Holiday": {
date: '5/(1,-1)',
keywords: ['bank', 'spring', 'late']
},
"Queen's Birthday": {
date: '6/(6,2)',
keywords: ['queen']
},
"Father's Day": {
date: '6/(0,3)',
keywords: ['dad', 'father']
},
"Battle of the Boyne": {
date: '6/12',
keywords: ['battle', 'boyne'],
regions: ['NI']
},
"Summer Bank Holiday (Scotland)": {
date: '8/(1,1)',
keywords: ['summer', 'bank'],
regions: ['SC']
},
"Summer Bank Holiday": {
date: '8/(1,-1)',
keywords: ['summer', 'bank'],
keywords_n: ['scottish', 'scotland'],
regions: ['EN', 'WL', 'NI']
},
"Halloween": {
date: '10/31',
},
"Guy Fawks Day": {
date: '10/5',
keywords: ['guy', 'fawks', 'bonfire']
},
"Remembrance Day": {
date: '1/(0,2)',
keywords: ['poppy', 'remembrance']
},
"Saint Andrews Day": {
date: '10/30',
keywords: ['andrew', 'saint', 'st[\\s\\.]'],
regions: ['SL']
},
"Christmas Day": {
date: '12/25',
keywords: ['christ', 'x-?mas'],
keywords_n: ['eve']
},
"Boxing Day": {
date: '12/26',
keywords: ['box']
}
};
if ((typeof module !== 'undefined' && module !== null ? module.exports : void 0) != null) { module.exports = moment; }
}).call(this);
|
/* eslint-disable */
/** pulled from remark-parse
*
* critical change is that blockquotes require a newline to be continued, see
* the `if(!prefixed) conditional
*/
'use strict'
var trim = require('trim')
var interrupt = require('remark-parse/lib/util/interrupt')
module.exports = blockquote
var lineFeed = '\n'
var tab = '\t'
var space = ' '
var greaterThan = '>'
function blockquote(eat, value, silent) {
var self = this
var offsets = self.offset
var tokenizers = self.blockTokenizers
var interruptors = self.interruptBlockquote
var now = eat.now()
var currentLine = now.line
var length = value.length
var values = []
var contents = []
var indents = []
var add
var index = 0
var character
var rest
var nextIndex
var content
var line
var startIndex
var prefixed
var exit
while (index < length) {
character = value.charAt(index)
if (character !== space && character !== tab) {
break
}
index++
}
if (value.charAt(index) !== greaterThan) {
return
}
if (silent) {
return true
}
index = 0
while (index < length) {
nextIndex = value.indexOf(lineFeed, index)
startIndex = index
prefixed = false
if (nextIndex === -1) {
nextIndex = length
}
while (index < length) {
character = value.charAt(index)
if (character !== space && character !== tab) {
break
}
index++
}
if (value.charAt(index) === greaterThan) {
index++
prefixed = true
if (value.charAt(index) === space) {
index++
}
} else {
index = startIndex
}
content = value.slice(index, nextIndex)
if (!prefixed && !trim(content)) {
index = startIndex
break
}
if (!prefixed) {
break;
}
line = startIndex === index ? content : value.slice(startIndex, nextIndex)
indents.push(index - startIndex)
values.push(line)
contents.push(content)
index = nextIndex + 1
}
const trailingNewline = value.charAt(nextIndex) === '\n';
index = -1
length = indents.length
add = eat(values.join(lineFeed))
while (++index < length) {
offsets[currentLine] = (offsets[currentLine] || 0) + indents[index]
currentLine++
}
exit = self.enterBlock()
contents = self.tokenizeBlock(contents.join(lineFeed), now)
console.log(values);
exit()
const added = add({type: 'blockquote', children: contents})
return trailingNewline ? add({ type: 'paragraph', children: [] }) : added;
}
|
import Icon from '../components/Icon.vue'
Icon.register({"firefox":{"width":1792,"height":1792,"paths":[{"d":"M903 1792q-283 0-504.5-150.5t-329.5-398.5q-58-131-67-301t26-332.5 111-312 179-242.5l-11 281q11-14 68-15.5t70 15.5q42-81 160.5-138t234.5-59q-54 45-119.5 148.5t-58.5 163.5q25 8 62.5 13.5t63 7.5 68 4 50.5 3q15 5 9.5 45.5t-30.5 75.5q-5 7-16.5 18.5t-56.5 35.5-101 34l15 189-139-67q-18 43-7.5 81.5t36 66.5 65.5 41.5 81 6.5q51-9 98-34.5t83.5-45 73.5-17.5q61 4 89.5 33t19.5 65q-1 2-2.5 5.5t-8.5 12.5-18 15.5-31.5 10.5-46.5 1q-60 95-144.5 135.5t-209.5 29.5q74 61 162.5 82.5t168.5 6 154.5-52 128-87.5 80.5-104q43-91 39-192.5t-37.5-188.5-78.5-125q87 38 137 79.5t77 112.5q15-170-57.5-343t-209.5-284q265 77 412 279.5t151 517.5q2 127-40.5 255t-123.5 238-189 196-247.5 135.5-288.5 49.5z"}]}})
|
var mongoose = require('mongoose');
var bcrypt = require('bcrypt-nodejs');
var crypto = require('crypto');
var stripeCustomer = require('./plugins/stripe-customer');
var secrets = require('../../config/secrets');
var timestamps = require('mongoose-timestamp');
var userSchema = new mongoose.Schema({
email: { type: String, unique: true, lowercase: true },
password: String,
profile: {
name: { type: String, default: '' },
gender: { type: String, default: '' },
location: { type: String, default: '' },
website: { type: String, default: '' },
picture: { type: String, default: '' }
},
emailConfirmToken: String,
emailConfirmed: {type: Boolean, default: false},
resetPasswordToken: String,
resetPasswordExpires: Date
});
var stripeOptions = secrets.stripeOptions;
userSchema.plugin(timestamps);
userSchema.plugin(stripeCustomer, stripeOptions);
/**
* Hash the password for security.
* "Pre" is a Mongoose middleware that executes before each user.save() call.
*/
userSchema.pre('save', function(next) {
var user = this;
if (!user.isModified('password')) return next();
bcrypt.genSalt(10, function(err, salt) {
if (err) return next(err);
bcrypt.hash(user.password, salt, null, function(err, hash) {
if (err) return next(err);
user.password = hash;
next();
});
});
});
/**
* Validate user's password.
* Used by Passport-Local Strategy for password validation.
*/
userSchema.methods.comparePassword = function(candidatePassword, cb) {
bcrypt.compare(candidatePassword, this.password, function(err, isMatch) {
if (err) return cb(err);
cb(null, isMatch);
});
};
/**
* Get URL to a user's gravatar.
* Used in Navbar and Account Management page.
*/
userSchema.methods.gravatar = function(size) {
if (!size) size = 200;
if (!this.email) {
return 'https://gravatar.com/avatar/?s=' + size + '&d=retro';
}
var md5 = crypto.createHash('md5').update(this.email).digest('hex');
return 'https://gravatar.com/avatar/' + md5 + '?s=' + size + '&d=retro';
};
module.exports = mongoose.model('User', userSchema);
|
define(function(require, exports, module) {
"use strict";
var cc = require("./cc");
var fn = require("./fn");
var ops = require("../common/ops");
var slice = [].slice;
// common methods
fn.defineProperty(Boolean.prototype, "copy", function() {
return this;
});
fn.defineProperty(Boolean.prototype, "clone", fn(function() {
return this;
}).defaults(ops.COMMONS.clone).build());
fn.defineProperty(Boolean.prototype, "dup", fn(function(n) {
var a = new Array(n|0);
for (var i = 0, imax = a.length; i < imax; ++i) {
a[i] = this;
}
return a;
}).defaults(ops.COMMONS.dup).build());
fn.defineProperty(Boolean.prototype, "value", function() {
return this;
});
fn.defineProperty(Boolean.prototype, "valueArray", function() {
return this;
});
fn.defineProperty(Boolean.prototype, "do", function(func) {
if (this) {
if (cc.instanceOfSyncBlock(func)) {
if (cc.currentSyncBlockHandler) {
cc.currentSyncBlockHandler.__sync__(func, cc.createTaskArgumentsOnce(this));
return this;
}
}
func(this, 0);
}
return this;
});
fn.defineProperty(Boolean.prototype, "wait", function() {
var flag = this;
if (flag && cc.currentTask) {
cc.currentTask.__wait__(cc.createTaskWaitTokenBoolean(flag));
}
return this;
});
fn.defineProperty(Boolean.prototype, "asUGenInput", function() {
return this ? 1 : 0;
});
fn.defineProperty(Boolean.prototype, "asString", function() {
return this ? "true" : "false";
});
// unary operator methods
["__plus__","__minus__"].concat(Object.keys(ops.UNARY_OPS)).forEach(function(selector) {
fn.defineProperty(Boolean.prototype, selector, function() {
return (this ? 1 : 0)[selector]();
});
});
// binary operator methods
["__add__","__sub__","__mul__","__div__","__mod__"].concat(Object.keys(ops.BINARY_OPS)).forEach(function(selector) {
fn.defineProperty(Boolean.prototype, selector, function(b) {
return (this ? 1 : 0)[selector](b);
});
});
// arity operators
Object.keys(ops.ARITY_OPS).forEach(function(selector) {
fn.defineProperty(Boolean.prototype, selector, fn(function() {
var args = slice.call(arguments);
return (0)[selector].apply(this ? 1 : 0, args);
}).defaults(ops.ARITY_OPS[selector]).multiCall().build());
});
module.exports = {};
});
|
module.exports = {
// the port express listens on
port: 3000,
// public address to access the server from the outside
address: 'http://localhost:3000',
// mongodb configuration
mongodb: {
host: 'localhost',
port: 27017
},
// session related information
session: {
// name of the session cookie
name: 'express.sid',
// the key used to encrypt the cookie
secret: '5b26243c6e69b09810268009f094c536590bf3c63f2f69bed47acd68178be2b0'
},
// oauth
facebook: {
id: '723348891027933',
secret: 'b82698180e06348651c4cf1a8285f54b'
},
google: {
id: '179733906984-b3cg0psdbp97ou2th4689o7ia4qt34lg.apps.googleusercontent.com',
secret: 'S8IkqL0X3uWnSFOMxFQw2VMe'
}
};
|
// The Store where all color Palette instances are stored.
Ext.define('Flux.store.Palettes', {
extend: 'Ext.data.Store',
model: 'Flux.model.Palette',
storeId: 'palettes',
requires: [
'Flux.model.Palette'
]
});
|
Ui.CanvasElement.extend('Ui.Loading', {
fill: 'black',
clock: undefined,
ease: undefined,
constructor: function(config) {
if('fill' in config) {
this.setFill(config.fill);
delete(config.fill);
}
else
this.setFill(this.fill);
this.ease = new Anim.PowerEase({ mode: 'inout' });
this.clock = new Anim.Clock({ repeat: 'forever', duration: 2 });
this.connect(this.clock, 'timeupdate', this.onTick);
},
setFill: function(fill) {
this.fill = Ui.Color.create(fill);
this.invalidateDraw();
},
onTick: function(clock, progress) {
this.invalidateDraw();
}
}, {
onVisible: function() {
Ui.Loading.base.onVisible.apply(this, arguments);
this.clock.begin();
},
onHidden: function() {
Ui.Loading.base.onHidden.apply(this, arguments);
this.clock.stop();
},
updateCanvas: function(ctx) {
var p = this.clock.getProgress();
if(p === undefined)
p = 0;
var p2 = (p > 0.8) ? (1 - ((p - 0.8)*5)) : (p / 0.8);
var w = this.getLayoutWidth();
var h = this.getLayoutHeight();
var x = w / 2;
var y = h / 2;
var lineWidth = Math.max(2, Math.min(5, Math.min(w, h) * 5 / 60));
var radius = ((Math.min(w, h) - lineWidth) / 2) - 5;
var startAngle = Math.PI * 2 * p;
if(p > 0.8)
startAngle = Math.PI * 2 * p - (Math.PI * 2 * 5 * this.ease.ease(p2) / 6);
var endAngle = startAngle + (Math.PI / 4) + (Math.PI * 2 * 5 * this.ease.ease(p2) / 6);
ctx.strokeStyle = this.getStyleProperty('color').getCssRgba();
ctx.beginPath();
ctx.arc(x, y, radius, startAngle, endAngle, false);
ctx.lineWidth = lineWidth;
ctx.stroke();
},
measureCore: function(width, height) {
return { width: 30, height: 30 };
}
}, {
style: {
color: new Ui.Color({ r: 0.27, g: 0.52, b: 0.9 })
}
});
|
// ****************************************
// get the year(s) for each metric
// ****************************************
function getYear(m) {
switch(metricConfig[m].type) {
case 'sum': case 'normalize':
// console.log('metricConfig[m].metric = '+JSON.stringify(metricConfig[m].metric));
// console.log("theData['r' + metricConfig[m].metric][0] = "+JSON.stringify(theData['r' + metricConfig[m].metric][0]));
// console.log(m +" "+"metricConfig[m].type = "+metricConfig[m].type);
// console.log("_.without(_.keys(theData['r' + metricConfig[m].metric][0]), 'id' = "+_.without(_.keys(theData['r' + metricConfig[m].metric][0]), 'id'));
return _.without(_.keys(theData['r' + metricConfig[m].metric][0]), 'id');
break;
case 'mean':
//console.log(m +" "+"metricConfig[m].type = "+metricConfig[m].type);
return _.without(_.keys(theData['n' + metricConfig[m].metric][0]), 'id');
break;
}
}
// ****************************************
// set model variable as needed from data type
// ****************************************
function setModel(m) {
model.metricId = m;
if (!(m in metricConfig)) {
console.log("Error: metricConfig is undefined for " + m);
return;
}
switch(metricConfig[m].type) {
case 'sum':
model.metric = theData['r' + metricConfig[m].metric];
break;
case 'mean':
model.metric = theData['n' + metricConfig[m].metric];
if (metricConfig[m].raw_label) {
model.metricRaw = theData['r' + metricConfig[m].metric];
}
break;
case 'normalize':
model.metricRaw = theData['r' + metricConfig[m].metric];
model.metricDenominator = theData['d' + metricConfig[m].metric];
if (model.metricRaw.length != model.metricDenominator.length) {
console.log("Error: Misconfigured metric " + metricConfig[m].metric + ". Length mismatch between r and d arrays.");
return;
}
var calcMetric = $.extend(true, {}, model.metricRaw);
var keys = _.without(_.keys(model.metricRaw[0]), "id");
// this next bit can get taken out when the normalize capabilities are complete
_.each(calcMetric, function(theval, i) {
_.each(keys, function(key) {
theRaw = model.metricRaw[i][key];
theDemoninator = model.metricDenominator[i][key];
theval[key] = theRaw / theDemoninator;
});
});
//console.log("calcMetric = "+JSON.stringify(calcMetric));
model.metric = calcMetric;
// end bit
break;
}
}
// ****************************************
// Return the nth instance of a substring
// ****************************************
function GetSubstringIndex(str, substring, n) {
var times = 0, index = null;
while (times < n && index !== -1) {
index = str.indexOf(substring, index+1);
times++;
}
return index;
}
// ****************************************
// Create the metric blocks and table values
// ****************************************
function createData(featureSet) {
var template = _.template($("script.template-metric").html()), categories = _.uniq(_.pluck(metricConfig, 'category'));
model.selected = featureSet;
_.each(featureSet, function(featureRaw) {
var feature = featureRaw.replace(/ /g,'-');
_.each(categories, function(dim) {
var theTable = $(".table-" + feature + "-" + dim.toLowerCase().replace(/\s+/g, "-") + " tbody");
var theMetrics = _.filter(metricConfig, function(el) {
return el.category.toLowerCase() === dim.toLowerCase();
});
_.each(theMetrics, function(val) {
// Check that metric is in data file before continuing.
if (!('r' + val.metric in theData)) {
return;
}
var m = 'm' + val.metric;
var lineChartObject = {
"id" : m,
"feature" : feature,
"prefix": getPrefix(m),
"suffix": getSuffix(m),
"years" : "",
"featurevalues" : "",
"selectedvalues" : "",
"countyvalues" : ""
};
setModel(m);
var aboutHTML;
var importance;
var metricTitle;
var additionalResourcesLinks;
var additionalResourcesHTML;
$.ajax({
url : 'data/meta/' + m + '.html',
type : 'GET',
dataType : 'text',
success : function(data) {
if (!(m in metricConfig)) {
console.log("Error: metricConfig is undefined for " + m);
return;
}
setModel(m);
model.metricID = m;
model.prefix = getPrefix(m);
model.suffix = getSuffix(m);
var keys = getYear(m);
var year = keys[keys.length - 1];
var yearTDs = "";
var types = [];
var theYear;
var yeariii;
var iii;
var years = [];
var featureValue;
var featureNValue;
var featureValues = [];
var selectedValues = [];
var countyValues = [];
var lineCharts = [];
// Get metric metadata from metadata HTML file.
var metricTitle = data.substring(GetSubstringIndex(data, '</p>', 1), GetSubstringIndex(data, '<p', 1) + 3);
var aboutHTML = data.substring(GetSubstringIndex(data, '</h3>', 2) + 5, GetSubstringIndex(data, '<h3', 3));
var importance = data.substring(GetSubstringIndex(data, '</p>', 2), GetSubstringIndex(data, '<p', 2) + 3);
var additionalResourcesHTML = "<table><thead></thead>" + data.substring(GetSubstringIndex(data, '</tbody>', 1) + 8, GetSubstringIndex(data, '<tbody', 1)) + "</body>";
var parser = new DOMParser();
var parserDoc = parser.parseFromString(additionalResourcesHTML, "text/html");
var tableTRs = parserDoc.getElementsByTagName("tr");
var trTDs;
var additionalResourcesLinks = "";
for (var i = 0; i < tableTRs.length; i++) {
parserDoc = parser.parseFromString("<table><tr>" + tableTRs[i].innerHTML + "</tr></table>", "text/html");
trTDs = parserDoc.getElementsByTagName("td");
var linkTitle = "";
if (trTDs.length == 2) {
linkTitle = trTDs[1].innerHTML;
}
additionalResourcesLinks += "<div>" + [trTDs[0].innerHTML.slice(0, 3), 'title="' + linkTitle + '"', trTDs[0].innerHTML.slice(3)].join('') + "</div>";;
}
var tdata = {
"id" : m,
"feature" : feature,
"title" : metricTitle,
"year" : "",
"typeValues" : "",
"about" : aboutHTML,
"important" : importance,
"additionalResources" : additionalResourcesLinks,
"selectedVal" : "",
"selectedRaw" : "",
"selectedNVal" : "",
"countyVal" : "",
"countyRaw" : "",
"countyNVal" : ""
};
for (iii = 0; iii < keys.length; iii++) {
theYear = keys[iii];
model.years = keys;
featureNValue = metricValuesByIDYear(model.metric, feature.replace(/-/g,' '), theYear, m);
featureValue = dataPretty(featureNValue, m);
yeariii = keys[iii].replace('y_', '');
tdata.countyNVal = dataCrunch('y_' + yeariii);
tdata.selectedNVal = dataCrunch('y_' + yeariii, theFilter);
model.suffix = val.suffix;
if (model.suffix == "%") {
featureValue = dataPretty(featureNValue * 100, m);
featureNValue = featureNValue * 100;
tdata.selectedNVal = tdata.selectedNVal * 100;
tdata.countyNVal = tdata.countyNVal * 100;
}
tdata.selectedVal = dataPretty(tdata.selectedNVal, m);
tdata.countyVal = dataPretty(tdata.countyNVal, m);
years.push(yeariii);
featureValues.push(dataRound(featureNValue, metricConfig[m].decimals));
selectedValues.push(dataRound(tdata.selectedNVal, metricConfig[m].decimals));
countyValues.push(dataRound(tdata.countyNVal, metricConfig[m].decimals));
types.push([featureValue, yeariii, tdata.selectedVal, tdata.countyVal]);
tdata.typeValues = types;
$(".dataValues").innerHTML = yearTDs;
if (metricConfig[m].raw_label) {
tdata.countyRaw = '<br>' + dataSum(model.metricRaw, year).toFixed(0).commafy();
theStat = dataSum(model.metricRaw, year, theFilter);
if ($.isNumeric(theStat)) {
theStat = theStat.toFixed(0).commafy();
}
tdata.selectedRaw = '<br>' + theStat;
}
// front page
if ($('[data-metric="' + m + '"]').length > 0) {
$('[data-metric="' + m + '"]').text(tdata.selectedVal);
}
if ($('[data-metric="r' + val.metric + '"]').length > 0) {
$('[data-metric="r' + val.metric + '"]').text(tdata.selectedRaw.replace('<br>', ''));
}
}
if (years.length > 1) {
lineChartObject.years = years;
lineChartObject.featurevalues = featureValues;
if (theFilter.length > 1) {
lineChartObject.selectedvalues = selectedValues;
}
lineChartObject.countyvalues = countyValues;
lineCharts.push(lineChartObject);
}
// Write out stuff
theTable.append(template(tdata));
// Hide "Selected features" if there is only one feature selected.
if (theFilter.length == 1) {
_.each(document.querySelectorAll(".metric-table__selection-average"), function (el, i) {
el.style.display = "none";
});
}
// Create line charts if they exist.
if (lineCharts.length > 0) {
console.log("Creating line chart for " + m)
lineChartCreate(lineCharts);
}
// Otherwise hide the linechart div.
else {
document.getElementById("lineChart"+lineChartObject.id+lineChartObject.feature).style.display = "none";
}
},
error : function(error, status, desc) {
},
});
});
});
});
}
// ****************************************
// Initialize the map
// Neighborhoods labled with leaflet.label
// ****************************************
function createMap(data){
// set up map
L.Icon.Default.imagePath = './images';
var smallMap = L.map("smallmap", {
attributionControl: false,
zoomControl: false,
touchZoom: false
}).setView(mapGeography.center, mapGeography.defaultZoom - 1);
// Disable drag and zoom handlers.
smallMap.dragging.disable();
smallMap.touchZoom.disable();
smallMap.doubleClickZoom.disable();
smallMap.scrollWheelZoom.disable();
var selectedFeatures = [],
selectedIDs = [];
// add data filtering by passed neighborhood id's
geom = L.geoJson(topojson.feature(data, data.objects[neighborhoods]), {
style: {
"color": "#FFA400",
"fillColor": "#FFA400",
"weight": 2,
"opacity": 1
},
filter: function(feature, layer) {
return theFilter.indexOf(feature.id.toString()) !== -1;
},
onEachFeature: function(feature, layer) {
selectedFeatures.push(feature);
selectedIDs.push(feature.id);
}
}).addTo(smallMap);
// add base tiles at the end so no extra image grabs/FOUC
L.tileLayer(baseTilesURL).addTo(smallMap);
// scaffold in category pages
pageTemplates(geom,selectedFeatures,selectedIDs);
}
// ****************************************
// get pages in for data categories
// ****************************************
function pageTemplates(layer,geoms,IDs) {
var template = _.template($("#template-category").html()),
categories = _.uniq(_.pluck(metricConfig, 'category')),
pages = $(".category-pages");
var mapEle;
var ticker = 0;
_.each(geoms, function(geom){
var geomID = geom.id;
var poly = L.polygon(geom.geometry.coordinates);
var polyBounds = poly.getBounds();
var swLng = polyBounds._southWest.lat,
swLat = polyBounds._southWest.lng,
neLng = polyBounds._northEast.lat,
neLat = polyBounds._northEast.lng;
mapEle = document.createElement('div');
mapEle = document.createElement('div');
mapEle.setAttribute("class", "page page-category");
mapEle.innerHTML = '<div><h3>'+geomID+'</h3></div><div class="row text-center"><div id="bigMap'+ticker+'"></div></div>';
pages.append(mapEle);
var bigMap = document.getElementById('bigMap'+ticker);
bigMap.style.width = '670px';
bigMap.style.height = '900px';
bigMap.style.margin = 'auto';
var largeMap = L.map('bigMap'+ticker,{
attributionControl: false,
zoomControl: false,
touchZoom: false
});
largeMap.fitBounds([[swLat,swLng],[neLat,neLng]]);
largeMap.dragging.disable();
largeMap.touchZoom.disable();
largeMap.doubleClickZoom.disable();
largeMap.scrollWheelZoom.disable();
var feature = L.geoJson(geom, {
style: {
"color": "#FFA400",
"fillColor": "rgba(255,164,0,0.3)",
"weight": 2,
"opacity": 1
},
filter: function(feature, layer) {
return theFilter.indexOf(feature.id.toString()) !== -1;
},
onEachFeature: function(feature, layer) {
var pt = L.geoJson(feature).getBounds().getCenter();
label = new L.Label();
label.setContent(feature.id.toString());
label.setLatLng(pt);
largeMap.showLabel(label);
}
}).addTo(largeMap);
L.tileLayer(baseTilesURL).addTo(largeMap);
ticker ++;
_.each(categories, function(el) {
cat = el.toLowerCase();
// get vis if available
if ($("#template-vis-" + cat).length > 0) {
vis = _.template($("#template-vis-" + cat.replace(/\s+/g, "-")).html());
} else {
vis = "";
}
// drop in category page
pages.append(template({ "vis": vis, "category": cat ,"featureID":geomID.replace(/ /g,'-')}));
});
});
}
function lineChartData(lineChart) {
var featureValues = lineChart.featurevalues,
npaMean = lineChart.selectedvalues,
countyMean = lineChart.countyvalues,
keys = _.without(_.keys(model.metric[0]), "id");
var data = {
labels: [],
datasets: []
};
// Set axis labels.
_.each(lineChart.years, function(el, i) {
data.labels.push(el.replace("y_", ""));
});
// Add feature values (if set).
if (featureValues && featureValues.length > 0) {
var featureValuesData = {
label: 'Feature',
fillColor : "rgba(239,223,0,0.2)",
strokeColor : "rgba(55,110,215,1)",
pointColor : "rgba(55,110,215,1)",
pointStrokeColor : "#fff",
pointHighlightFill : "#fff",
pointHighlightStroke : "rgba(239,223,0,1)",
data :[]
};
_.each(featureValues, function(el, i){
featureValuesData.data.push(el);
});
data.datasets.push(featureValuesData);
}
// Add average for selection (if set).
if (npaMean && npaMean.length > 0) {
var npaMeanData = {
label: 'Selected',
fillColor : "rgba(81,164,75,0.2)",
strokeColor : "rgba(81,164,75,1)",
pointColor : "rgba(81,164,75,1)",
pointStrokeColor : "#fff",
pointHighlightFill : "#fff",
pointHighlightStroke : "rgba(81,164,75,1)",
data :[]
};
_.each(npaMean, function (el, i) {
npaMeanData.data.push(Math.round(el * 10) / 10);
});
data.datasets.push(npaMeanData);
}
// Add county mean (if set).
if (countyMean && countyMean.length > 0) {
var countyMeanData = {
label: "County",
fillColor : "rgba(220,220,220,0.5)",
strokeColor : "rgba(215,215,215,1)",
pointColor : "rgba(215,215,215,1)",
pointStrokeColor : "#fff",
pointHighlightFill : "#fff",
pointHighlightStroke : "rgba(215,215,215,1)",
data : []
};
_.each(countyMean, function (el, i) {
countyMeanData.data.push(Math.round(el * 10) / 10);
});
data.datasets.push(countyMeanData);
}
return data;
}
function lineChartCreate(lineCharts) {
_.each(lineCharts, function(lineChart, i){
thePrefix = lineChart.prefix;
theSuffix = lineChart.suffix;
if (window.myLine) { window.myLine.destroy(); }
var ctx = document.getElementById("lineChart"+lineChart.id+lineChart.feature).getContext("2d");
window.myLine = new Chart(ctx).Line(lineChartData(lineChart), {
responsive: true,
maintainAspectRatio: true,
showTooltips: true,
animation: true,
animationSteps: 1,
tooltipEvents: ["mousemove", "touchstart", "touchmove"],
tooltipTemplate: "<%if (label){%><%=label%>: <%}%><%= value %>",
multiTooltipTemplate: "<%= value %>",
scaleLabel: '<%= thePrefix + value + theSuffix %>',
legendTemplate : '<% for (var i=0; i<datasets.length; i++){%><span class="title" style="background-color:<%=datasets[i].strokeColor%>; margin-right: 5px"> </span><span class="title" style="margin-right: 5px"><%if(datasets[i].label){%><%=datasets[i].label%><%}%></span><%}%>'
});
$("#chartLegend"+lineChart.id+lineChart.feature).html(myLine.generateLegend());
});
}
// ****************************************
// Globals
// ****************************************
var theFilter,
theData,
theMetadata, // global for fetched raw data
thePrefix,
theSuffix,
featureIndex = 0,
model = {};
_.templateSettings.variable = "rc";
// ****************************************
// Document ready kickoff
// ****************************************
$(document).ready(function() {
// grab the neighborhood list from the URL to set the filter
if (getURLParameter("n") !== "null") {
theFilter = getURLParameter("n").split(",");
}
// Get target layer from URL.
if (getURLParameter("t") !== "null") {
loadLayer = getURLParameter("t");
}
setMetricAndNeighborhoodConfig(loadLayer);
// Hide metric summary box unless user is viewing the census blockgroup layer.
// @todo configure different metric summary boxes for neighborhoods/tracts layers.
if (loadLayer != "census") {
document.getElementById("metric-summary-box").style.display = "none";
}
// fetch map data and make map
$.get(activeTOPOJSON, function(data) {
createMap(data);
});
// ye customizable subtitle
$(".subtitle").on("click", function() { $(this).select(); });
// populate the neighborhoods list on the first page
// if too long to fit one one line it lists the number of neighborhoods instead
// @todo this is not working since the template changed.
var theNeighborhoods = theFilter.join(", ");
if (theNeighborhoods.length > 85) {
theNeighborhoods = theFilter.length;
$(".neighborhoods").text(theNeighborhoods.commafy() + " " + neighborhoodDescriptor + "s");
} else {
$(".neighborhoods").text(neighborhoodDescriptor + ": " + theNeighborhoods.commafy());
}
// fetch the metrics and make numbers and charts
$.get(activeMergeJSON, function(data) {
theData = data;
createData(theFilter);
});
});
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = function (filePath) {
// Constructor
var courseZip = new _courseFileScanner2.default(filePath);
var courseFiles = courseZip.getCourseFiles();
var courseDatFiles = courseZip.getDatFiles();
// API
var unusedFileChecker = {
scan: function scan() {
// Return the final response
return new Promise(function (resolve, reject) {
var unusedFiles = courseFiles.filter(unusedFileChecker._isUnusedFile);
resolve(unusedFiles);
});
},
_isUnusedFile: function _isUnusedFile(file) {
var usedInArray = courseDatFiles.filter(function (datFile) {
var fileContent = courseZip.getZipObject().readAsText(datFile);
return fileContent.indexOf(file.courseFileId + '_') !== -1;
});
return usedInArray.length < 1;
}
};
// Return API
return unusedFileChecker;
};
var _courseFileScanner = require('course-file-scanner');
var _courseFileScanner2 = _interopRequireDefault(_courseFileScanner);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
import './sass/main.scss'
class Navbar {
constructor(props) {
this.navbarItems = props.navbarItems
this.sections = props.sections
this.scroll()
}
init() {
let pos = 0
// check window position and set current section
for (let i = 0; i < this.sections.length; i++) {
if (
this.sections[i].offsetTop <= window.pageYOffset &&
this.sections[i].offsetTop + this.sections[i].offsetHeight > window.pageYOffset
) {
pos = i
}
}
// set current navbar items
for (let j = 0; j < this.navbarItems.length; j++) {
if (j === pos) {
this.navbarItems[j].classList.add('current')
} else {
this.navbarItems[j].classList.remove('current')
}
// onclick event for navbar link
let link = this.navbarItems[j].getElementsByTagName('a')
// link[0].onclick = (e) => {
// this.handleClick(e, link[0])
// }
link[0].onclick = (e) => {
for (let k = 0; k < this.navbarItems.length; k++) {
this.navbarItems[k].classList.remove('current')
}
this.navbarItems[j].classList.add('current')
this.handleClick(e, link[0])
}
}
}
scroll() {
document.addEventListener('wheel', () => {
this.init()
})
}
handleClick(e, elem) {
e.preventDefault()
// animation scroll
const scrollTo = ((elem, to, duration) => {
if (duration <= 0) return
let difference = to - elem.scrollTop
let perTick = difference / duration * 10
setTimeout(() => {
elem.scrollTop = elem.scrollTop + perTick
if (elem.scrollTop === to) return
scrollTo(elem, to, duration - 10)
}, 10)
})
// call scroll to selected element
const documentElem = (document.scrollingElement === undefined) ? document.documentElement : document.body
scrollTo(documentElem, document.getElementById(elem.innerHTML.toLowerCase()).offsetTop, 600)
}
}
let N = new Navbar({
navbarItems: document.getElementsByClassName('navbar-item'),
sections: document.getElementsByClassName('section')
})
N.init()
|
// Regular expression that matches all symbols in the `Takri` script as per Unicode v10.0.0:
/\uD805[\uDE80-\uDEB7\uDEC0-\uDEC9]/;
|
/**
* Define constants to use throughout the application.
*/
angular.module('comrise.shared');
|
'use strict';
/**
* @ngdoc function
* @name learnAngularApp.controller:HomeCtrl
* @description
* # HomeCtrl
* Controller of the learnAngularApp
*/
angular.module('learnAngularApp')
.controller('HomeCtrl', function () {
this.awesomeThings = [
'HTML5 Boilerplate',
'AngularJS',
'Karma'
];
});
|
// ./test/addition.test.js
/* Import modules */
// test-harness modules
var chai = require('chai');
var expect = chai.expect;
// module(s) under test
var Number = require('../src/Number.js');
/* Test logic */
describe('GIVEN: a Number x (x = 5)', function() {
describe('WHEN: Calling the function x.addition(y) (y = 6)', function(){
it('THEN: it should return the sum x + y = 11', function() {
var x = new Number(5);
var y = 6;
var answer = 5+6;
expect(x.addition(y)).to.equal(answer);
});
});
});
|
'use strict';
const path = require('path');
const coffee = require('coffee');
const helper = require('../lib/helper');
const yargs = require('yargs');
const assert = require('assert');
describe('test/my-helper.test.js', () => {
const myBin = require.resolve('./fixtures/my-helper/bin/my-helper.js');
const cwd = path.join(__dirname, 'fixtures/test-files');
it('my-helper --help', done => {
coffee.fork(myBin, [ '--help' ], { cwd })
// .debug()
.expect('stdout', /fork/)
.expect('stdout', /install/)
.expect('stdout', /echo/)
.expect('stdout', /Options:/)
.expect('stdout', /--help/)
.expect('code', 0)
.end(done);
});
it('should `helper.echo`', done => {
coffee.fork(myBin, [ 'echo', 'tz' ], { cwd })
// .debug()
// .coverage(false)
.expect('stdout', /hi, tz/)
.expect('code', 0)
.end(done);
});
it('should `helper.forkNode`', done => {
coffee.fork(myBin, [ 'fork', '--target=test_script' ], { cwd })
// .debug()
// .coverage(false)
.expect('stdout', /task proc: true/)
.expect('stdout', /process.argv: \["--target=test_script","--from=test"]/)
.expect('code', 0)
.end(done);
});
it('should `helper.callFn`', done => {
coffee.fork(myBin, [ 'call' ], { cwd })
// .debug()
// .coverage(false)
.expect('stdout', /undefined, promise, generator/)
.expect('code', 0)
.end(done);
});
it('should `helper.forkNode` with error', done => {
coffee.fork(myBin, [ 'fork', '--target=error_script' ], { cwd })
// .debug()
// .coverage(false)
.expect('stderr', /this is an error/)
.expect('stderr', /Command Error/)
.expect('code', 1)
.end(done);
});
it.skip('should kill child process', done => {
const app = coffee.fork(myBin, [ 'fork', '--target=loop_script' ], { cwd, env: process.env });
app
// .debug()
// .coverage(false);
.expect('stdout', /\[child] echo \d+ 1/)
.expect('stdout', /\[child] echo \d+ 2/);
if (process.platform !== 'win32') {
app
.expect('stdout', /\[child] exit with code 0/)
.expect('stdout', /recieve singal SIGINT/)
.expect('code', 0);
}
app.end(done);
setTimeout(() => {
app.proc.kill('SIGINT');
}, 10000);
});
it('should `helper.npmInstall`', () => {
return coffee.fork(myBin, [ 'install', '--target=egg-init-config' ], { cwd, env: process.env })
.debug()
// .coverage(false);
// npm@5 missing the message
// .expect('stdout', /egg-init-config@\d+\.\d+\.\d+/)
.expect('stdout', /install egg-init-config done/)
.expect('code', 0)
.end();
});
it('should `helper.npmInstall` with error', done => {
coffee.fork(myBin, [ 'install', '--target=common-bin-not-exist' ], { cwd, env: process.env })
// .debug()
// .coverage(false);
.expect('stdout', /npm.* i common-bin-not-exist/)
.expect('stderr', /npm ERR! 404/)
.expect('code', 1)
.end(done);
});
it('helper.unparseArgv', () => {
const args = [
'echo',
'--baseDir=./dist',
'--debug=5555', '--debug-brk',
'--inspect', '6666', '--inspect-brk',
'--es_staging', '--harmony', '--harmony_default_parameters',
];
const argv = yargs.parse(args);
const execArgv = helper.unparseArgv(argv, {
includes: [ 'debug', /^harmony.*/ ],
});
assert.deepEqual(execArgv, [ '--debug=5555', '--harmony', '--harmony_default_parameters' ]);
});
it('helper.extractExecArgv', () => {
const args = [
'echo',
'--baseDir=./dist',
'--debug=5555', '--debug-brk',
'--inspect', '6666', '--inspect-brk=7777',
'--inspect-port', '--debug-port=8888',
'--debug-invalid',
'--es_staging', '--harmony', '--harmony_default_parameters',
];
const argv = yargs.parse(args);
const { debugPort, debugOptions, execArgvObj } = helper.extractExecArgv(argv);
assert(debugPort === 8888);
assert.deepEqual(debugOptions, { debug: 5555, 'debug-brk': true, inspect: 6666, 'inspect-brk': 7777, 'inspect-port': true, 'debug-port': 8888 });
assert.deepEqual(execArgvObj, { debug: 5555, 'debug-brk': true, inspect: 6666, 'inspect-brk': 7777, 'inspect-port': true, 'debug-port': 8888, es_staging: true, harmony: true, harmony_default_parameters: true });
});
});
|
import 'node-fetch';
var getRepoByUser = function(username) {
let url = `https://api.github.com/users/${username}/repos`;
return fetch(url).then(response => response.json());
};
export {getRepoByUser};
|
/**
* Created by hector on 10.11.15.
*/
'use strict';
var webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
//context: './src',
entry: {
CommentBox: "./src/js/components/CommentBox.js",
styleComment: './src/scss/comment.scss'
},
output: {
path: "./build",
filename: "[name].js",
publicPath: '/build/',
library: "app[name]"
},
watch: true,
watchOptions: {
aggregateTimeout: 100
},
devtool: 'source-map',
resolve: {
modulesDirectories: ['node_modules'],
extensions: ['', '.js']
},
resolveLoader: {
modulesDirectories: ['node_modules'],
moduleTemplates: ['*-loader', '* '],
extensions: ['', '.js']
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel',
query: {
presets: ['es2015'],
plugins: ['transform-runtime', "transform-react-jsx"]
}
},
{
test: /\.scss$/,
loader: ExtractTextPlugin.extract(
'style', // backup loader when not building .css file
'css!sass' // loaders to preprocess CSS
)
}
]
},
sassLoader: {
includePaths: ["./build"]
},
plugins: [
//new webpack.ProvidePlugin({}),
new ExtractTextPlugin('[name].css'),
new webpack.NoErrorsPlugin(),
new webpack.optimize.CommonsChunkPlugin({
name: 'common'/*,
minChunks: function(module, count){
return count >= 2;
}*/
}),
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false,
drop_console: true,
unsafe: true
}
})
],
externals: {
react: 'React',
reactDom: 'ReactDom',
rxjs: 'Rx'
}
};
|
/* global module, require */
var config = require('../../app/config');
var co = require('co');
var r = require('rethinkdbdash')(config.rethinkdb);
module.exports = {
load: function (table, data) {
return co(function *() {
yield r.db(config.rethinkdb.db)
.table(table)
.delete();
yield r.db(config.rethinkdb.db)
.table(table)
.insert(data)
.run()
});
}
};
|
/*
* get clientid first
* and get usage bytes through clientId
*/
module.exports = function()
{
var job,
init = function(_job)
{
job = _job;
return this;
},
execute = function(_data, _callback)
{
getCientId(_data,function(rs,data)
{
switch(rs)
{
case -1:
_data._result.message ="get clientId error";
_data._result.result = 0;
break;
case -2:
_data._result.message ="get disk usage error";
_data._result.result = 0;
case 1:
_data._result.message ="get disk usage ok";
_data._result.result = 1;
_data._result.data = data;
break;
}
_callback(false,job);
});
},
getCientId = function(_data,_callback)
{
var token = _data.token,
sql = "select client_id from client_token where token = '"+token+"'";
var cDb = require("../../modules/queryDB.js"),
db = new cDb().queryDB(sql,_data._config,function(err,result)
{
if(err)
{
_callback(-1);
}
else
{
var clientId = result.rows[0].client_id,
i = 0,
rsData = {};
finish = function()
{
if(i == 2)
{
_callback(1,rsData);
}
};
getDiskUsage(_data,clientId,function(rs,data)
{
i++;
if(rs == -2)
{
_callback(rs);
}
else
{
rsData.bytes = parseInt(data);
finish();
}
});
getMaxsize(_data,clientId,function(rs,data)
{
i++;
if(rs == -3)
{
_callback(rs);
}
else
{
rsData.maxsize = parseInt(data);
finish();
}
});
}
});
},
getMaxsize = function(_data,_clientId,_callback)
{
var sql = "select maxsize from client_account where client_id = '"+_clientId+"'";
var cDb = require("../../modules/queryDB.js"),
db = new cDb().queryDB(sql,_data._config,function(err,result)
{
if(err)
{
_callback(-3);
}
else
{
_callback(1,result.rows[0].maxsize);
}
});
},
getDiskUsage = function(_data,_clientId,_callback)
{
var folderName = _data.folderName,
sql = "select sum(bytes) as bytes from file_info where type= 1 and client_id = '"+_clientId+"'";
if(typeof folderName != "undefined")
{
sql += " and file_name like '"+folderName+"%'";
}
var cDb = require("../../modules/queryDB.js"),
db = new cDb().queryDB(sql,_data._config,function(err,result)
{
if(err)
{
_callback(-2);
}
else
{
_callback(1,result.rows[0].bytes);
}
});
},
that =
{
init: init,
getCientId:getCientId,
getDiskUsage:getDiskUsage,
execute: execute
};
return that;
}
|
THREE.CSS2DObject = function ( element ) {
THREE.Object3D.call( this );
this.element = element || document.createElement( 'div' );
this.element.style.position = 'absolute';
this.addEventListener( 'removed', function () {
this.traverse( function ( object ) {
if ( object.element instanceof Element && object.element.parentNode !== null ) {
object.element.parentNode.removeChild( object.element );
}
} );
} );
};
THREE.CSS2DObject.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), {
constructor: THREE.CSS2DObject,
copy: function ( source, recursive ) {
THREE.Object3D.prototype.copy.call( this, source, recursive );
this.element = source.element.cloneNode( true );
return this;
}
} );
//
THREE.CSS2DRenderer = function () {
var _this = this;
var _width, _height;
var _widthHalf, _heightHalf;
var vector = new THREE.Vector3();
var viewMatrix = new THREE.Matrix4();
var viewProjectionMatrix = new THREE.Matrix4();
var cache = {
objects: new WeakMap()
};
var domElement = document.createElement( 'div' );
domElement.style.overflow = 'hidden';
this.domElement = domElement;
this.getSize = function () {
return {
width: _width,
height: _height
};
};
this.setSize = function ( width, height ) {
_width = width;
_height = height;
_widthHalf = _width / 2;
_heightHalf = _height / 2;
domElement.style.width = width + 'px';
domElement.style.height = height + 'px';
};
var renderObject = function ( object, scene, camera ) {
if ( object instanceof THREE.CSS2DObject ) {
object.onBeforeRender( _this, scene, camera );
vector.setFromMatrixPosition( object.matrixWorld );
vector.applyMatrix4( viewProjectionMatrix );
var element = object.element;
element.style.transform = 'translate(-50%,-50%) translate(' + ( vector.x * _widthHalf + _widthHalf ) + 'px,' + ( - vector.y * _heightHalf + _heightHalf ) + 'px)';
element.style.display = ( object.visible && vector.z >= - 1 && vector.z <= 1 ) ? '' : 'none';
var objectData = {
distanceToCameraSquared: getDistanceToSquared( camera, object )
};
cache.objects.set( object, objectData );
if ( element.parentNode !== domElement ) {
domElement.appendChild( element );
}
object.onAfterRender( _this, scene, camera );
}
for ( var i = 0, l = object.children.length; i < l; i ++ ) {
renderObject( object.children[ i ], scene, camera );
}
};
var getDistanceToSquared = function () {
var a = new THREE.Vector3();
var b = new THREE.Vector3();
return function ( object1, object2 ) {
a.setFromMatrixPosition( object1.matrixWorld );
b.setFromMatrixPosition( object2.matrixWorld );
return a.distanceToSquared( b );
};
}();
var filterAndFlatten = function ( scene ) {
var result = [];
scene.traverse( function ( object ) {
if ( object instanceof THREE.CSS2DObject ) result.push( object );
} );
return result;
};
var zOrder = function ( scene ) {
var sorted = filterAndFlatten( scene ).sort( function ( a, b ) {
var distanceA = cache.objects.get( a ).distanceToCameraSquared;
var distanceB = cache.objects.get( b ).distanceToCameraSquared;
return distanceA - distanceB;
} );
var zMax = sorted.length;
for ( var i = 0, l = sorted.length; i < l; i ++ ) {
sorted[ i ].element.style.zIndex = zMax - i;
}
};
this.render = function ( scene, camera ) {
if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
if ( camera.parent === null ) camera.updateMatrixWorld();
viewMatrix.copy( camera.matrixWorldInverse );
viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, viewMatrix );
renderObject( scene, scene, camera );
zOrder( scene );
};
};
|
'use strict'
const api = module.exports = require('express').Router()
api
.get('/heartbeat', (req, res) => res.send({ok: true}))
.use('/auth', require('./auth'))
.use('/users', require('./users'))
.use('/products', require('./products'))
.use('/orders', require('./orders'))
.use('/guests', require('./guests'))
// No routes matched? 404.
api.use((req, res) => res.status(404).end())
|
(function() {
'use strict';
/**
* @name loginCtrl
* @description Controller
*/
function ObserverFactory($http, $filter, ApiConfig) {
var cfg = ApiConfig.observer;
function getObserver(region, id){
region = $filter('regionFilter')(region);
$http.get(ApiConfig.OBSERVER_URL + cfg.urlnext + region + '/' + id + ApiConfig.API_KEY).
success(function(data) {
console.log('success')
}).
error(function(data){
console.log('fail')
});
}
var api = {
getObserver: getObserver
}
return api;
}
function regionFilter(){
return function(region) {
var regions = {
'euw': 'EUW1',
'eune': 'EUN1',
'br': 'BR1',
'kr': 'KR',
'lan': 'LA1',
'las': 'LA2',
'na': 'NA1',
'oce': 'OC1',
'ru': 'RU',
'tr': 'TR1'
}
return regions[region]
};
}
angular.module('observer', [])
.factory('ObserverFactory', ObserverFactory)
.filter('regionFilter', regionFilter)
})();
|
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define('/Plugin/card', ['exports', 'jquery', 'Plugin'], factory);
} else if (typeof exports !== "undefined") {
factory(exports, require('jquery'), require('Plugin'));
} else {
var mod = {
exports: {}
};
factory(mod.exports, global.jQuery, global.Plugin);
global.PluginCard = mod.exports;
}
})(this, function (exports, _jquery, _Plugin2) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery2 = babelHelpers.interopRequireDefault(_jquery);
var _Plugin3 = babelHelpers.interopRequireDefault(_Plugin2);
var NAME = 'card';
var Card = function (_Plugin) {
babelHelpers.inherits(Card, _Plugin);
function Card() {
babelHelpers.classCallCheck(this, Card);
return babelHelpers.possibleConstructorReturn(this, (Card.__proto__ || Object.getPrototypeOf(Card)).apply(this, arguments));
}
babelHelpers.createClass(Card, [{
key: 'getName',
value: function getName() {
return;
}
}, {
key: 'render',
value: function render() {
if (!_jquery2.default.fn.card) {
return;
}
var $el = this.$el,
options = this.options;
if (options.target) {
options.container = (0, _jquery2.default)(options.target);
}
$el.card(options);
}
}], [{
key: 'getDefaults',
value: function getDefaults() {
return {};
}
}]);
return Card;
}(_Plugin3.default);
_Plugin3.default.register(NAME, Card);
exports.default = Card;
});
|
/**
* This file is part of Wizkers.io
*
* The MIT License (MIT)
* Copyright (c) 2016 Edouard Lafargue, ed@wizkers.io
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software
* is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
* IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/*
* A parser for the Fried Circuits OLED Backpack
* This object contains two entries:
* - The low level parser for the serial port driver
* - The high level parser for incoming serial port data
*
* @author Edouard Lafargue, ed@lafargue.name
*/
"use strict";
var serialport = require('serialport'),
events = require('events'),
serialconnection = require('../connections/serial'),
debug = require('debug')('wizkers:parsers:fcoled'),
dbs = require('../pouch-config');
var FCOled = function() {
// Init the EventEmitter
events.EventEmitter.call(this);
/////////
// Public variables
/////////
this.name = "fcoledv1";
/////////
// Private variables
/////////
var port = null;
var isopen = false;
var instrumentid = null;
var port_close_requested = false;
var self = this;
/////////
// Private methods
/////////
var status = function(stat) {
debug('Port status change', stat);
isopen = stat.portopen;
if (isopen) {
// Should run any "onOpen" initialization routine here if
// necessary.
} else {
// We remove the listener so that the serial port can be GC'ed
if (port_close_requested) {
port.removeListener('status', status);
port_close_requested = false;
}
}
};
// How the device is connected on the serial port
var portSettings = function() {
return {
baudRate: 115200,
dataBits: 8,
parity: 'none',
stopBits: 1,
flowControl: false,
// simply pass each line to our JSON streaming parser
// Note: the Onyx outputs json with \n at the end, so
// the default readline parser works fine (it separates on \r)
parser: serialport.parsers.readline('\n'),
}
};
// format should return a JSON structure.
var format = function(data) {
// console.log('FC Oled Backpack - format output');
// Remove any carriage return
data = data.replace('\n','');
var fields = {};
try {
fields = JSON.parse(data);
} catch (e) {
console.log("Error: cannot parse logger data : " + e + " - " + data);
}
self.emit('data',fields);
};
/////////
// Public methods
/////////
// Creates and opens the connection to the instrument.
// for all practical purposes, this is really the init method of the
// driver
this.openPort = function(id) {
instrumentid = id;
dbs.instruments.get(id, function(err,item) {
port = new serialconnection(item.port, portSettings());
port.on('data', format);
port.on('status', status);
});
}
this.closePort = function(data) {
// We need to remove all listeners otherwise the serial port
// will never be GC'ed
port.removeListener('data', format);
port_close_requested = true;
port.close();
}
this.isOpen = function() {
return isopen;
}
this.getInstrumentId = function(format) {
return instrumentid;
};
// Called when the HTML app needs a unique identifier.
// this is a standardized call across all drivers.
// This particular device does not support this concept, so we
// always return the same
this.sendUniqueID = function() {
this.emit('data',{ uniqueID:'00000000 (n.a.)'});
};
this.isStreaming = function() {
return true;
};
// period is in seconds
// The sensor sends data by itself, so those functions are empty...
this.startLiveStream = function(period) {
};
this.stopLiveStream = function(period) {
};
// output should return a string, and is used to format
// the data that is sent on the serial port, coming from the
// HTML interface.
this.output = function(data) {
port.write(data + '\n');
}
};
FCOled.prototype.__proto__ = events.EventEmitter.prototype;
module.exports = FCOled;
|
const { sep } = require("path");
/* GET ARRAY */
module.exports.getArray = function(state) {
return state.paths;
};
module.exports.getArrayGroup = function() {
return [""].slice(0, 0);
};
/** PUSH FILE */
module.exports.pushFileFilterAndCount = function(filters) {
return function(filename, _files, _dir, state) {
if (filters.some((f) => f(filename))) state.counts.files++;
};
};
module.exports.pushFileFilter = function(filters) {
return function(filename, files) {
if (filters.some((f) => f(filename))) files.push(filename);
};
};
module.exports.pushFileCount = function(_filename, _files, _dir, state) {
state.counts.files++;
};
module.exports.pushFile = function(filename, files) {
files.push(filename);
};
/** PUSH DIR */
module.exports.pushDir = function(dirPath, paths) {
paths.push(dirPath);
};
/** JOIN PATH */
module.exports.joinPathWithBasePath = function(filename, dir) {
return `${dir}${sep}${filename}`;
};
module.exports.joinPath = function(filename) {
return filename;
};
/** WALK DIR */
module.exports.walkDirExclude = function(exclude) {
return function(walk, state, path, dir, currentDepth, callback) {
if (!exclude(dir,path,currentDepth)) {
module.exports.walkDir(walk, state, path, dir, currentDepth, callback);
}
};
};
module.exports.walkDir = function(
walk,
state,
path,
_dir,
currentDepth,
callback
) {
state.queue++;
state.counts.dirs++;
walk(state, path, currentDepth, callback);
};
/** GROUP FILES */
module.exports.groupFiles = function(dir, files, state) {
state.counts.files += files.length;
state.paths.push({ dir, files });
};
module.exports.empty = function() {};
/** CALLBACK INVOKER */
module.exports.callbackInvokerOnlyCountsSync = function(state) {
return state.counts;
};
module.exports.callbackInvokerDefaultSync = function(state) {
return state.paths;
};
module.exports.callbackInvokerOnlyCountsAsync = callbackInvokerBuilder(
"counts"
);
module.exports.callbackInvokerDefaultAsync = callbackInvokerBuilder("paths");
function report(err, callback, output, suppressErrors) {
if (err) {
if (!suppressErrors) callback(err, null);
return;
}
callback(null, output);
}
function callbackInvokerBuilder(output) {
return function(err, state) {
report(err, state.callback, state[output], state.options.suppressErrors);
};
}
|
userProject.delByProjectId(projectId);
|
const log = require('loglevel');
const path = require('path');
const fs = require('fs');
const chalk = require('chalk');
const process = require('process');
const addSkipped = require('./rules-util.js').addSkipped;
const processRules = require('./rules-util.js').processRules;
const semver = require('semver');
const rulesConf = {
name: 'package.json',
rules: [
{
desc: 'using public npm version of gfp eslint config',
errorMsg:
'remove "gfp-eslint-config" from package.json and install "eslint eslint-config-gfp" instead, or just run:',
run:
'npm uninstall --save-dev gfp-eslint-config && npm install --save-dev eslint eslint-config-gfp',
fn: notUsingStashGfpEslintConfig
},
{
desc: 'using eslint-config-gfp',
errorMsg: 'Run:',
run: 'npm install --save-dev eslint-config-gfp',
fn: missingEslintConfigGfp
},
{
desc: 'using public npm version of angular-module-no-deps',
errorMsg:
'remove "angular-module-no-deps" from package.json and install "angular-module-no-deps" instead, or just run:',
run:
'npm uninstall --save-dev angular-module-no-deps && npm install --save-dev angular-module-no-deps',
fn: notUsingStashAngularModuleNoDeps
},
{
desc: 'using documentationjs',
errorMsg:
'should be using documentationjs to generate JSDoc to README:\n' +
'add scripts: \n' +
'"docs": "npm run docs:md",\n' +
'"docs:md": "documentation readme <source files>.js --section \'API\'"\n' +
'"and run:',
run: 'npm install --save-dev documentation',
fn: usingDocumentationJs
},
{
desc: 'has npm script lint',
errorMsg:
'should have a npm script lint\n' +
'then add script to package.json: \n' +
'"lint": "eslint *.js"',
fn: hasNpmLintScript
},
{
desc: 'should be using @babel/cli',
errorMsg: 'Run:',
run: 'npm install --save-dev @babel/cli',
fn: shouldUseBabelCli
},
{
desc: 'should be using babel-core',
errorMsg: 'Run:',
run: 'npm install --save-dev babel-core@6.22.1',
fn: shouldUseBabelCore
},
{
desc: 'should be using babel-loader',
errorMsg: 'Run:',
run: 'npm install --save-dev babel-loader@6.2.10',
fn: shouldUseBabelLoader
},
{
desc: 'should be using babel-plugin-istanbul',
errorMsg: 'Run:',
run: 'npm install --save-dev babel-plugin-istanbul@4.1.5',
fn: shouldUseBabelInstanbul
},
{
desc: 'should be using babel-plugin-transform-runtime',
errorMsg: 'Run:',
run:
'npm install --save-dev babel-plugin-transform-runtime@.6.22.0',
fn: shouldUseBabelTransformRuntime
},
{
desc: 'should be using babel-preset-env',
errorMsg: 'Run:',
run: 'npm install --save-dev babel-preset-env@1.6.1',
fn: shouldUseBabelPresetEnv
},
{
desc: 'should be using babel-preprocessor',
errorMsg: 'Run:',
run: 'npm install --save-dev karma-babel-preprocessor@7.0.0',
fn: shouldUseBabelPreprocessor
},
{
desc: 'should be using puppeteer',
errorMsg:
'remove "phantomjs" from package.json and install "puppeteer" instead, or just run:',
run:
'npm uninstall --save-dev phantomjs && npm install --save-dev puppeteer',
fn: shouldUsePuppeteer
},
{
desc: 'should be using headless Chrome',
errorMsg:
'remove "karma-phantomjs-launcher" from package.json and install karma-chrome-launcher instead, or just run:',
run:
'npm uninstall --save-dev karma-phantomjs-launcher && npm install --save-dev karma-chrome-launcher@2.2.0',
fn: shouldUseChromeLauncher
},
{
desc: 'should use prepush hooks',
errorMsg:
'Add the following to npm scripts:\n' +
'"prepush": "npm run lint && karma start --single-run"\n' +
'Run:',
run: 'npm install --save-dev husky',
fn: shouldUsePrepushHooks
},
{
desc: 'should use public require-polyfill',
errorMsg:
'remove "require-polyfill" from package.json and install public version, or just run:',
run:
'npm uninstall --save-dev require-polyfill && npm install --save-dev require-polyfill',
fn: shouldUsePublicRequirePolyfill
},
{
desc: 'should use eslint-config-gfp 4.0.0 and up',
errorMsg:
'set eslint-config-gfp to use version "^4.0.0" in package.json or run:',
run: 'npm install --save-dev eslint-config-gfp@4.0.0',
fn: shouldUseEslintConfigGfp300
},
{
desc: 'should have gfp-doctor > 1.12 installed',
errorMsg: 'Run:',
run: 'npm install --save-dev gfp-doctor',
fn: shouldUseGfpDoctor
},
{
desc: 'should run gfp-doctor after install',
errorMsg:
'add the following to npm scripts:\n' +
'"postinstall": "gfp-doctor"',
fn: shouldRunGfpDoctorPostInstall
},
{
desc: 'should use "karma" 1.7.0 and up',
errorMsg: 'set "karma" to use "^1.7.0" or run',
run: 'npm install --save-dev karma@1.7.0',
fn: shouldUseKarma170
},
{
desc: 'should use "karma-coverage" 1.1.0 and up',
errorMsg: 'set "karma-coverage" to use "^1.1.0" or run:',
run: 'npm install --save-dev karma-coverage@1.1.0',
fn: shouldUseKarmaCoverage110
},
{
desc: 'should use "karma-jasmine" 1.1.0 and up',
errorMsg: 'set "karma-jasmine" to use "^1.1.0" or run:',
run: 'npm install --save-dev karma-jasmine@1.1.0',
fn: shouldUseKarmaJasmine110
},
{
desc: 'should use gff-jira-message and run it on commitmsg',
errorMsg:
'install gff-jira-message and add it to scripts commitmsg',
run: 'npm i gff-jira-message --save-dev',
fn: shouldUseGffJiraMessage
}
]
};
module.exports = function(options) {
'use strict';
const packagePath = path.join(
process.cwd(),
options.packagePath || 'package.json'
);
log.debug(chalk.underline('Examining package.json'), options);
log.debug(`using ${packagePath}`, options);
if (!fs.existsSync(packagePath)) {
log.warn(
chalk.red('ABORTING: No package.json found in ' + process.cwd())
);
return addSkipped(rulesConf);
}
const data = fs.readFileSync(packagePath);
const json = JSON.parse(data);
// work through all rules, setting passed = true/false
rulesConf.rules = processRules(rulesConf, json, options);
return rulesConf;
};
// add more test functions below, should return true if passing the test
function notUsingStashGfpEslintConfig(json) {
if (json.devDependencies && !json.devDependencies['gfp-eslint-config']) {
return true;
}
}
function missingEslintConfigGfp(json) {
if (json.devDependencies && json.devDependencies['eslint-config-gfp']) {
return true;
}
}
function notUsingStashAngularModuleNoDeps(json) {
// bail out if angular-module-no-deps isn't defined at all
if (
json.devDependencies &&
!json.devDependencies['angular-module-no-deps']
) {
return true;
}
if (
json.devDependencies['angular-module-no-deps'].indexOf('.mrgreen.') !==
-1
) {
return false;
}
return true;
}
function usingDocumentationJs(json) {
if (json.devDependencies && json.devDependencies['documentation']) {
return true;
}
}
function hasNpmLintScript(json) {
if (json.scripts && json.scripts.lint) {
return true;
}
}
function shouldUseBabelCli(json) {
if (json.devDependencies['@babel/cli']) {
return true;
}
return false;
}
function shouldUseBabelCore(json) {
if (json.devDependencies['babel-core']) {
return true;
}
return false;
}
function shouldUseBabelLoader(json) {
if (json.devDependencies['babel-loader']) {
return true;
}
return false;
}
function shouldUseBabelInstanbul(json) {
if (json.devDependencies['babel-plugin-istanbul']) {
return true;
}
return false;
}
function shouldUseBabelTransformRuntime(json) {
if (json.devDependencies['babel-plugin-transform-runtime']) {
return true;
}
return false;
}
function shouldUseBabelPresetEnv(json) {
if (json.devDependencies['babel-preset-env']) {
return true;
}
return false;
}
function shouldUseBabelPreprocessor(json) {
if (json.devDependencies['karma-babel-preprocessor']) {
return true;
}
return false;
}
function shouldUsePuppeteer(json) {
if (json.devDependencies) {
if (
json.devDependencies['phantomjs'] ||
json.devDependencies['phantomjs-prebuilt']
) {
return false;
}
if (json.devDependencies['puppeteer']) {
return true;
}
}
}
function shouldUseChromeLauncher(json) {
if (json.devDependencies) {
if (json.devDependencies['karma-phantomjs-launcher']) {
return false;
}
if (json.devDependencies['karma-chrome-launcher']) {
return true;
}
}
}
function shouldUsePrepushHooks(json) {
if (json.devDependencies && json.devDependencies.husky) {
if (json.scripts && json.scripts.prepush) {
return true;
}
}
}
function shouldUsePublicRequirePolyfill(json) {
if (json.devDependencies && json.devDependencies['require-polyfill']) {
if (json.devDependencies['require-polyfill'].includes('ssh://')) {
return false;
}
}
return true;
}
function shouldUseEslintConfigGfp300(json) {
if (json.devDependencies) {
if (json.devDependencies['eslint-config-gfp']) {
if (json.devDependencies['eslint-config-gfp'] === 'latest') {
return false;
}
// tries to see if 2.9.9 is less than the current range specified in package.json
return semver.ltr(
'3.9.9',
json.devDependencies['eslint-config-gfp']
);
}
}
}
function shouldUseGfpDoctor(json) {
if (json.devDependencies && json.devDependencies['gfp-doctor']) {
return (
json.devDependencies['gfp-doctor'] === 'latest' ||
semver.ltr('1.11.9', json.devDependencies['gfp-doctor'])
);
}
}
function shouldRunGfpDoctorPostInstall(json) {
if (
json.scripts &&
json.scripts.postinstall &&
json.scripts.postinstall.includes('gfp-doctor')
) {
return true;
}
}
function shouldUseKarma170(json) {
if (json.devDependencies) {
if (json.devDependencies['karma']) {
if (json.devDependencies['karma'] === 'latest') {
return false;
}
return semver.ltr('1.6.9', json.devDependencies['karma']);
}
}
}
function shouldUseKarmaCoverage110(json) {
if (json.devDependencies) {
if (json.devDependencies['karma-coverage']) {
if (json.devDependencies['karma-coverage'] === 'latest') {
return false;
}
return semver.ltr('1.0.9', json.devDependencies['karma-coverage']);
}
}
}
function shouldUseKarmaJasmine110(json) {
if (json.devDependencies) {
if (json.devDependencies['karma-jasmine']) {
if (json.devDependencies['karma-jasmine'] === 'latest') {
return false;
}
return semver.ltr('1.0.9', json.devDependencies['karma-jasmine']);
}
}
}
function shouldUseGffJiraMessage(json) {
if (
json.scripts &&
json.scripts.commitmsg &&
json.scripts.commitmsg.includes('gff-jira-message') &&
json.devDependencies &&
json.devDependencies['gff-jira-message'] &&
semver.gte(json.devDependencies['gff-jira-message'], '1.1.0')
) {
return true;
} else {
return false;
}
}
|
const iconNames = SVG_ICONS || []; // eslint-disable-line no-undef
const specialIcons = [
'facebook',
'google-plus',
'twitter'
];
const initIconSamples = function () {
const dest = document.querySelectorAll('.js-icon-list')[0];
if (dest && iconNames.length > 0) {
iconNames.forEach(function (k) {
const modifierClassNames = [];
if (specialIcons.includes(k)) {
modifierClassNames.push(`icon--${k}`);
}
dest.insertAdjacentHTML('beforeend', `
<tr class="sg-icon">
<td class="sg-icon__symbol">
<svg class="icon ${modifierClassNames.join(' ')} icon--xlarge"><use xlink:href="#${k}"></use></svg>
<svg class="icon ${modifierClassNames.join(' ')} icon--large"><use xlink:href="#${k}"></use></svg>
<svg class="icon ${modifierClassNames.join(' ')}"><use xlink:href="#${k}"></use></svg>
<svg class="icon ${modifierClassNames.join(' ')} icon--small"><use xlink:href="#${k}"></use></svg>
</td>
<td class="sg-icon__label">${k}</td>
</tr>`);
});
}
};
export default initIconSamples;
|
/**
* Module dependencies.
*/
var mongoose = require('mongoose')
, User = mongoose.model('User')
, env = process.env.NODE_ENV || 'development'
, config = require('../../config/config')[env]
, AWS = require('aws-sdk')
AWS.config.update(config.aws)
var login = function (req, res) {
var redirectTo = req.session.returnTo ? req.session.returnTo : '/'
delete req.session.returnTo
res.redirect(redirectTo)
}
exports.passwordReset = function(req, res) {
User.findOne({ password_reset_key: req.params.key }, function (err, user) {
if (err || !user)
{
res.render('layout', {
errors: ['Unknown user, we can\'t reset your password']
})
}
else
{
var new_pass = User.generateKey(8)
user.password = new_pass
user.save()
var ses = new AWS.SES({apiVersion: '2010-12-01'});
ses.sendEmail({
Source: config.mail_from,
Destination: { ToAddresses: [ user.email ] },
Message: {
Subject: {
Data: 'New password'
}, Body: {
Text: { Data: 'Your new password is : ' + new_pass + '' }
}
}
}, function(err, data) {
if(err)
{
console.log(err)
res.render('layout', {
errors: ['An error occured : we can\'t send email']
})
}
else
{
res.render('layout', {
success: ['An email has been sent with your new password.']
})
}
})
}
})
}
exports.profile = function (req, res) {
User.findOne({ _id: req.user._id }, function (err, user) {
if (err || !user)
res.json({ success: false, message:'An error occured : user do not exists' })
else
{
User.findOne({ email: req.body.email }, function (err, user2) {
if (err || (user2 && !user2._id.equals(req.user._id)))
{
res.json({ success: false, message:'An error occured : this email is already registered' })
}
else
{
if (req.body.password != '')
user.password = req.body.password;
user.email = req.body.email;
user.save();
res.json({ success: true, message:'Profile successfuly updated' })
}
})
}
})
}
exports.signin = function (req, res) {
User.findOne({ email: req.body.email }, function (err, user) {
if (err || !user)
res.json({ success: false, message:'An error occured : user do not exists' })
else
{
if (req.body.login_state == 'reset')
{
var key = User.generateKey(30);
var link = 'http://' + config.host + '/password-reset/' + key;
user.password_reset_key = key;
user.save();
var ses = new AWS.SES({apiVersion: '2010-12-01'});
ses.sendEmail({
Source: config.mail_from,
Destination: { ToAddresses: [ user.email ] },
Message: {
Subject: {
Data: 'Reset your password'
}, Body: {
Text: { Data: 'To reset your password, click this link : ' + link + '' },
Html: { Data: 'To reset your password, click this link : <a href="' + link + '">' + link + '</a>' }
}
}
}, function(err, data) {
if(err)
{
console.log(err)
res.json({ success: false, message:'An error occured : we can\'t send email' })
}
else
res.json({ success: true, message:'An email has been sent.' })
});
}
else if (req.body.login_state == 'signin')
{
if (!user.authenticate(req.body.password))
res.json({ success: false, message:'An error occured : wrong email or password' })
else
{
req.logIn(user, function(err) {
res.json({ success: true })
})
}
}
}
})
}
/**
* Auth callback
*/
exports.authCallback = login
/**
* Show login form
*/
exports.login = function (req, res) {
res.render('users/login', {
title: 'Login',
message: req.flash('error')
})
}
/**
* Logout
*/
exports.logout = function (req, res) {
req.logout()
res.redirect('/')
}
/**
* Session
*/
exports.session = login
/**
* Create user
*/
exports.signup = function (req, res, next) {
var user = new User(req.body)
user.provider = 'local'
user.save(function (err) {
if (err)
{
res.json({ success: false, errors: err.errors })
}
else
{
req.logIn(user, function(err) {
res.json({ success: true })
})
}
})
}
/**
* Show profile
*/
exports.show = function (req, res) {
var user = req.profile
res.render('users/show', {
title: user.name,
user: user
})
}
/**
* Find user by id
*/
exports.user = function (req, res, next, id) {
User
.findOne({ _id : id })
.exec(function (err, user) {
if (err) return next(err)
if (!user) return next(new Error('Failed to load User ' + id))
req.profile = user
next()
})
}
|
(function(app, undef) {
"use strict";
var gettext = app.utils._tr;
app.models.Mission = Backbone.Model.extend({
initialize: function(args) {
var id = args.id;
this.set({
name: gettext('<Mission>mission_name_' + id),
description: gettext('<Mission>mission_description_' + id)
});
}
});
}(App));
|
// Here is where you can define configuration overrides based on the execution environment.
// Supply a key to the default export matching the NODE_ENV that you wish to target, and
// the base configuration will apply your overrides before exporting itself.
module.exports = {
// ======================================================
// Overrides when NODE_ENV === 'dev'
// ======================================================
// NOTE: In development, we use an explicit public path when the assets
// are served webpack by to fix this issue:
// http://stackoverflow.com/questions/34133808/webpack-ots-parsing-error-loading-fonts/34133809#34133809
dev: (config) => ({
compiler_public_path: `http://${config.server_host}:${config.server_port}/`
}),
// ======================================================
// Overrides when NODE_ENV === 'production'
// ======================================================
production: (config) => ({
compiler_public_path: '/',
compiler_fail_on_warning: false,
compiler_hash_type: 'chunkhash',
compiler_devtool: false,
compiler_stats: {
chunks: true,
chunkModules: true,
colors: true
}
})
};
|
App.Models.Introduction = Backbone.Model.extend({
defaults : {
content : null,
file : null
},
initialize : function() {
/*foo*/
},
fetch : function() {
var selfModel = this;
$.get("/docs/"+this.get("file"), function(markdownContent) {
selfModel.set("content",markdown.toHTML(markdownContent));
selfModel.trigger('introIsReady');
})
}
});
App.Collections.Introductions = Backbone.Collection.extend({
model:App.Models.Introduction,
initialize : function() {
this.counter = 0;
},
fetch : function() {
var selfCollection = this;
this.each(function(intro) {
selfCollection.listenTo(intro,'introIsReady', selfCollection.onIntroductionFetched)
intro.fetch()
})
},
onIntroductionFetched : function() {/* called each time an intro fetch is completed */
this.counter+=1;
if(this.counter==this.length) {
console.log("==> All intros have been fetched!")
this.trigger('allIntrosAreReady')
}
}
});
|
import React from 'react';
import { Route, IndexRoute } from 'react-router';
import App from './components/App';
import StarWarsWrapper from './containers/StarWarsWrapper';
import StarWarsDetailsWrapper from './containers/StarWarsDetailsWrapper';
export default (
<Route path="/" component={App}>
<IndexRoute component={StarWarsWrapper} />
<Route path="/details/:personId" component={StarWarsDetailsWrapper} />
<Route path="*" component={StarWarsWrapper} />
</Route>
);
|
/** Classe de distribution optimisée de mobiles
* O876 Raycaster project
* @date 2012-04-04
* @author Raphaël Marandet
*
* Classe gérant une liste de mobile qui seront réutilisé à la demande.
* Cette classe permet de limiter le nom de d'instanciation/destruction
*/
O2.createClass('O876_Raycaster.MobileDispenser', {
aBlueprints: null,
__construct: function() {
this.aBlueprints = {};
},
registerBlueprint: function(sId) {
this.aBlueprints[sId] = [];
},
/** Ajoute un mobile dans sa pile de catégorie
*/
pushMobile: function(sBlueprint, oMobile) {
this.aBlueprints[sBlueprint].push(oMobile);
},
/**
* @return O876_Raycaster.Mobile
*/
popMobile: function(sBlueprint) {
if (!(sBlueprint in this.aBlueprints)) {
throw new Error('no such blueprint : "' + sBlueprint + '"');
}
if (this.aBlueprints[sBlueprint].length) {
return this.aBlueprints[sBlueprint].pop();
} else {
return null;
}
},
render: function() {
var sRender = '';
for (var sBlueprint in this.aBlueprints) {
if (this.aBlueprints[sBlueprint].length) {
sRender += '[' + sBlueprint + ': ' + this.aBlueprints[sBlueprint].length.toString() + ']';
}
}
return sRender;
}
});
|
var mongoose = require('mongoose'),
encryption = require('../utilities/encryption');
module.exports = function(config) {
mongoose.connect(config.db);
var db = mongoose.connection;
db.once('open', function(err){
if(err) {
console.log('Database could not be opened: ' + err);
return;
}
console.log('Database up and running...')
});
db.on('error', function (err) {
console.log('Database error: ' + err);
});
var userSchema = mongoose.Schema({
username: String,
firstName: String,
lastName: String,
salt: String,
hashPass: String,
roles: [String]
});
userSchema.method({
authenticate: function(password){
console.log(encryption.generateHashedPassword(this.salt, password));
console.log(this.hashPass);
if(encryption.generateHashedPassword(this.salt, password) === this.hashPass) {
return true;
}
}
});
var User = mongoose.model('User', userSchema);
User.find({}).exec(function(err, collection){
if(err){
console.log('Cannot find users: ' + err);
return;
}
if(collection.length === 0){
var salt;
var hashedPwd;
salt = encryption.generateSalt();
hashedPwd = encryption.generateHashedPassword(salt, 'Slavi');
User.create({username: 'test', firstName: 'Slavi', lastName: 'Nikolov', salt: salt, hashPass: hashedPwd, roles: ['admin']});
salt = encryption.generateSalt();
hashedPwd = encryption.generateHashedPassword(salt, 'Test');
User.create({username: 'test1', firstName: 'Test', lastName: 'Name', salt: salt, hashPass: hashedPwd, roles: ['standard']});
salt = encryption.generateSalt();
hashedPwd = encryption.generateHashedPassword(salt, 'Test1');
User.create({username: 'test2', firstName: 'Test1', lastName: 'Name1', salt: salt, hashPass: hashedPwd, roles: ['moderator']});
console.log('Users added to DataBase... ')
}
});
};
|
if (process.env.NODE_ENV === 'production') {
module.exports = require('./index.prod').default;
} else {
module.exports = require('./index.dev').default;
}
|
angular.module('Blocker', ['ngMaterial', 'Main', 'MapDrawer']);
|
/**
* Created by oiglesia on 26/06/2015.
*/
/**
* Angulajs bloq main declarations
*/
angular
.module('panelApp',['ngSanitize','chart.js'])
.directive('ngEnter', function() {
return function(scope, element, attrs) {
element.bind("keydown keypress", function(event) {
if(event.which === 13) {
scope.$apply(function(){
scope.$eval(attrs.ngEnter);
});
event.preventDefault();
}
});
};
})
.controller('panelAppCtrl',['$scope','$http','$interval',mainController])
function mainController($scope,$http,$interval) {
// --->> Bloque declaraciones
$scope.datasServer;
$scope.nameModels = [];
$scope.panelCols = false;
$scope.optsNames = [
'Ratio de Entradas',
'Ventas mensuales',
'Importe medio x tiquet',
'Venta media x vendedor',
'Ratio de uso de tarjetas',
'Importe x Tarjetas',
'Otros'
];
$scope.groupType = "";
$scope.grafics = [];
$scope.labels = ["Total por tienda"];
$scope.series = ['Tienda A', 'Tienda B','Tienda C'];
$scope.dataGraphics;
$scope.colors = ['#2ecc71','#3498db','#e74c3c'];
$scope.grafics = [];
//Bloque funciones
$scope.loadPage = function(){
$scope.generatedNamesModels();
$scope.login();
}
$scope.login = function (){
$scope.RequestData();
$interval(function () {
$scope.RequestData();}, 5000);
}
//---->>> Bloque que genera dinámicamente los options del menú
$scope.generatedNamesModels = function () {
for (var i = 1; i <= 3; i++) {
$scope.nameModels.push({
"filedName": "field" + (i),
"datasOptions": $scope.nameOptions(),
"groupType" : $scope.randomTypeGroup(),
"typeDara" : $scope.randomTypeDatas(),
"optSelected": {"namOpt": $scope.optsNames[i], "valOpt": (i)},
"showOpts" : false
});
}
}
$scope.nameOptions = function () {
var opts = "[";
for (var i = 0; i < $scope.optsNames.length; i++) {
opts += '{"namOpt" : "' + $scope.optsNames[i] + '","valOpt" : ' + (i + 1) + '}';
if (i+1 < $scope.optsNames.length)opts += ',';
}
opts += "]";
return JSON.parse(opts);
}
$scope.randomTypeGroup = function(){
var opt = Math.floor((Math.random() * 3) + 1);
switch(opt){
case 1:{
$scope.groupType = "CLIENTES";
return "CLIENTES";
}
case 2:{
$scope.groupType = "VENTAS";
return "VENTAS";
}
case 3:{
$scope.groupType = "FIDELIZACIÓN";
return "FIDELIZACIÓN";
}
}
}
$scope.randomTypeDatas = function(typeGroup){
if($scope.groupType==="CLIENTES"){
return "Ratio de Entradas";
}
else if($scope.groupType==="VENTAS"){
var opt = Math.floor((Math.random() * 3) + 1);
switch(opt){
case 1:{
return "Ventas mensuales";
}
case 2:{
return "Importe medio x tiquet";
}
case 3:{
return "Venta media x vendedor";
}
}
}
else if($scope.groupType==="FIDELIZACIÓN"){
var opt = Math.floor((Math.random() * 2) + 1);
switch(opt){
case 1:{
return "Ratio de uso de tarjetas";
}
case 2:{
return "Impore por Tarjetas";
}
}
}
}
$scope.RequestData = function (index) {
if(index === undefined){
$scope.datasServer = [];
$scope.datasServer.push({
"cells" : [{"id" : Math.round(Math.random()*5000)},{"id" : Math.round(Math.random()*5000)},{"id" : Math.round(Math.random()*5000)}]
},
{
"cells" : [{"id" : Math.round(Math.random()*5000)},{"id" : Math.round(Math.random()*5000)},{"id" : Math.round(Math.random()*5000)}]
},
{
"cells" : [{"id" : Math.round(Math.random()*5000)},{"id" : Math.round(Math.random()*5000)},{"id" : Math.round(Math.random()*5000)}]
});
}
else{
for(var i = 0;i<$scope.datasServer[index].cells.length;i++){
$scope.datasServer[index].cells[i].id = Math.round(Math.random()*5000);
}
}
$scope.valuesGrafics();
}
$scope.valuesGrafics = function() {
$scope.dataGraphics = [[[],[],[]],[[],[],[]],[[],[],[]]];
for(var i =0;i<$scope.datasServer[0].cells.length;i++){
for(var j = 0;j <$scope.datasServer.length;j++){
$scope.dataGraphics[i][j].push($scope.datasServer[i].cells[j].id);
}
}
}
$scope.changeOpts = function (index){
$scope.nameModels[index].showOpts = !$scope.nameModels[index].showOpts;
$scope.RequestData(index);
}
//=========================> Anteriormente se llamaba a un servidor para recuperar los datos, pero la url se cerró. <======================
/*$scope.url = "";
$scope.urlServer = "http://h2228012.stratoserver.net";
$scope.portServer = "8080";
$scope.headers = {headers: {'Content-Type': 'application/x-www-form-urlencoded'}};
$scope.login = function () {
//Function que llamara al servidor para realizar el login.
$scope.url = $scope.urlServer +':'+ $scope.portServer;
$http.post($scope.url,
"cmd=users.login&CCA=999999999&user=Admin&password=ims&lng=10&format=2",
$scope.headers
).success(function (response) {
$scope.sessionICU = response.nna.data.sessionICU;
$scope.RequestData();
$interval(function () {
$scope.RequestData();
}, 10000);
}).error(function () {
alert("Error en la petición de datos");
})
}
$scope.RequestData = function () {
//alert("entra en el intervalo");
$http.post($scope.url,
"cmd=data.getDataRows&NN=9009&" + $scope.geneParams() + "sessionICU=" + $scope.sessionICU + "&lng=10&format=2",
$scope.headers
).success(function (response) {
$scope.datasServer = response.nna.data.rows;
$scope.valuesGrafics();
}).error(function () {
alert("Error en la petición de datos");
})
}
$scope.geneParams = function () {
var params = "";
for (var i = 0; i < 3; i++) {
params += $scope.nameModels[i].filedName + "=" + $scope.nameModels[i].optSelected.valOpt + "&";
}
return params;
}*/
}
|
function Write(color, borderSize, zIndex, borderColor, textSize, textUnderline, textBold,name ){
Text.call(this,name);
this.color = color || 'black';
this.borderSize = borderSize || 'none';
this.zIndex = zIndex || 0;
this.borderColor = borderColor || 'none';
this.name = name || 'write Tool';
this.textSize = textSize || 14;
this.textBold = textBold || false;
this.textUnderline = textUnderline || false;
}
Write.prototype = Object.create(Shape.prototype);
Write.prototype.drawInput = function(elem, increment, pos, color){
console.log('here');
var self = this;
var $elem = elem;
var inputIndex = self.zIndex +1;
var $input = $elem.append("<input class= 'input0' type='text'>");
$input.find('.input0').css({
'position':'absolute',
'left':pos.x+'px',
'top':pos.y+'px',
'z-index': inputIndex,
});
}
Write.prototype.drawText = function(elem, increment,color){
var self = this;
var $elem = elem.find('.input0');
var $content = elem.val();
if(elem.val() !== ''){
elem.before('<div class=\'write-container'+increment+'\' ><p class=\'write'+increment+'\'>'+$content+'</p></div>');
$('.write'+increment).css({
'position':'absolute',
'left':elem.position().left+'px',
'top':elem.position().top+'px',
'z-index': self.zIndex,
'font-size' : self.textSize+'px',
'color':self.color,
});
if(self.textUnderline === true){
$('.write'+increment).css('text-decoration','underline');
}
if(self.textBold === true){
$('.write'+increment).css('font-weight','bold');
}
}
}
Write.prototype.resize = function(elem, increment, mousepos){
var self = this;
// var $elem = elem;
// $elem.find('.round'+increment).css({
// 'width': mousepos.x+'px',
// 'height':mousepos.y+'px',
// });
}
|
import test from 'ava';
import splitArray from './';
test('splits simple array', t => {
t.same(
splitArray(['a', 'b', 'c', 'd', 'e', 'f'], 2),
[['a', 'b'], ['c', 'd'], ['e', 'f']]
);
t.same(
splitArray(['a', 'b', 'c', 'd', 'e', 'f'], 3),
[['a', 'b', 'c'], ['d', 'e', 'f']]
);
t.end();
});
test('handles the last item correctly', t => {
t.same(
splitArray(['a', 'b', 'c', 'd', 'e', 'f', 'foo'], 6),
[['a', 'b', 'c', 'd', 'e', 'f'], ['foo']]
);
t.end();
});
test('Throws on nonsense input', t => {
['foo', function () {}, null, {}].forEach(input => {
t.throws(() => {
splitArray(input, 1);
});
});
t.end();
});
|
// console.log(JSON.stringify(UTILS.getCurrentTemplateData()));
console.log('template data', UTILS.getCurrentTemplateData());
$(document).ready(function () {
var config = UTILS.getCurrentTemplateData();
FORM_HELPER.draw(".new-users-content", config, {
postUrl: "users/form",
callbacks: {
afterSubmit: function () {
MENU_HELPER.menuClick('manageUsers', 'manageUsers');
}
},
});
});
|
;require(['anole'], function (anole){
var sceneQueue;
var baseUrl;
var resourceUrl;
var resource = {
"bridge": "bridge.png",
"gate": "gate.png",
"boat": "boat.png",
"oar": "oar.png",
"marco1": "marco1.png",
"marco2": "marco2.png",
"paperman": "paperman.png",
"font":"SansGBW3_min.ttf",
"sub-block": "subway.png",
"sub-left-gate": "subwayl.png",
"sub-right-gate": "subwayr.png",
"replay": "replay.png",
"tag": "tag.png",
"youtube-logo": "youtube-logo.png",
"profile": "profile.png",
"board_video": "board_video.png",
"v0": "v0.png",
"v1": "v1.png",
"v2": "v2.png",
'like':"like.png",
"worry1": "worry1.png",
"worry2": "worry2.png",
"worry3": "worry3.png",
"worry4": "worry4.png",
"chinese": "chinese.png",
"chinese_smile": "chinese_smile.png",
"bubble_disappear": "bubble_disappear.png",
"marco_nomouth": "marco_nomouth.png",
"mouth": "mouth.png",
"dollar": "dollar.png",
"dollar_big": "dollar_big.png",
"dollar_top": "dollar_top.png",
"dollar_mid": "dollar_mid.png",
"dollar_bottom": "dollar_bottom.png",
"dollar_outer": "dollar_outer.png",
"dollar_outer_big": "dollar_outer_big.png",
"happy": "happy.png",
"shoppingbag": "shoppingbag.png",
"canadian0":"canadian0.png",
"canadian1":"canadian1.png",
"canadian2":"canadian2.png",
"KoreanG":"KoreanG.png",
"KoreanB":"KoreanB.png",
"KoreanR":"KoreanR.png",
"map":"map.png",
"mark1":"mark1.png",
"mark2":"mark2.png",
"mark3":"mark3.png",
"mark4":"mark4.png",
"browsertab":"browstab.png",
"w1d":"wifi1_dark.png",
"w1l":"wifi1_light.png",
"w2d":"wifi2_dark.png",
"w2l":"wifi2_light.png",
"w3d":"wifi3_dark.png",
"w3l":"wifi3_light.png",
"glogo":"googlelogowithshadow.png",
"searchbar":"searchbarwithshadow.png",
"progbar":"progressbar.png",
"nexus":"nexuswithshadow.png",
"tag_blue": "tag_blue.png",
"tag_red": "tag_red.png",
"tag_yellow": "tag_yellow.png",
"chn_food":"chn_food.png",
"west_food":"west_food.png",
"lung_tab":"lung_tab.png",
"plate":"plate.png",
"lung_m":"lung_m.png",
"lung_f":"lung_f.png",
/* Videos */
"french":"french.mp4",
"french_webm": "french.webm",
"food1":"food1.mp4",
"food1_webm":"food1.webm",
"food2":"food2.mp4",
"food2_webm":"food2.webm",
"toilet":"toilet.mp4",
"toilet_webm":"food2.webm",
"gsvg":"g.svg",
"googlelogo": "googlelogo.png",
"video":"a.video"
}
//if(!anole.isMobile()){
sceneQueue = [
{
fileName:'scene1.js',
res: ["video"] //depend resources.
},
{
fileName:'scene2.js',
res: []
},
{
fileName:'scene3.js',
res: []
},
{
fileName:'scene4.js',
res: ["marco1","paperman","sub-block","sub-left-gate","sub-right-gate"]
},
{
fileName:'scene5.js',
res: ["marco1","paperman","sub-block","sub-left-gate","sub-right-gate","replay"]
},
{
fileName:'scene6.js',
res: ["marco1","paperman","sub-block","sub-left-gate","sub-right-gate","replay","like"]
},
{
fileName:'scene7.js',
res: ["profile","youtube-logo","tag","board_video","v0","v1","v2","worry1", "worry2", "worry3", "worry4"]
},
{
fileName:'scene8.js',
res: ["bubble_disappear", "marco_nomouth", "mouth", "chinese", "chinese_smile"]
},
{
fileName:'scene9.js',
res: ["dollar", "dollar_big", "dollar_top", "dollar_mid", "dollar_bottom", "dollar_outer", "dollar_outer_big"]
},
{
fileName:'scene10.js',
res: ["shoppingbag"]
},
{
fileName:'scene11.js',
res: ["canadian0","canadian1","canadian2","KoreanR","KoreanG","KoreanB"]
},
{
fileName: 'scene12.js',
res: ["french","french_webm"]
},
{
fileName:'scene13.js',
res: ["gate","boat","marco2"]
},
{
fileName:'scene14.js',
res: ["map","mark1","mark2","mark3","mark4"]
},
{
fileName:'scene15.js',
res: ["map"]
},
{
fileName:'scene16.js',
res: ["browsertab","w1d","w1l","w2d","w2l","w3d","w3l","glogo","searchbar","progbar"]
},
{
fileName:'scene17.js',
res: ["browsertab","glogo","searchbar","progbar","nexus"]
},
{
fileName:'scene18.js',
res: [""]
},
{
fileName: 'scene19.js',
res: ["food1","food1_webm","food2","food2_webm","tag_blue","tag_yellow","tag_red"]
},
{
fileName:'scene20.js',
res: ["chn_food","west_food"]
},
{
fileName:'scene21.js',
res: ["lung_f","lung_m","lung_tab","plate"]
},
{
fileName: 'scene22.js',
res: ["toilet","toilet_webm"]
},
{
fileName: 'scene23.js',
res: ["gsvg", "googlelogo"]
},
]
// baseUrl = 'http://gtravel.b0.upaiyun.com/scene/';
baseUrl = '/scene/';
// resourceUrl = "http://gtravel.b0.upaiyun.com/resource/";
resourceUrl = "/resource/";
//}
$(function (){
// Push voiceover files to sceneQueue.
for (i=1; i<=sceneQueue.length; i++) {
resource['vo'+i] = 'Sound3/' + i + '.mp3';
(sceneQueue[i-1].res).push('vo'+i);
}
var config = {
baseUrl:baseUrl,// root url
resourceUrl: resourceUrl,// resource url like jpg/mp3
resource: resource,//resource
maxQueueLength: 1,//TODO load serval scenes at first
sceneQueue: sceneQueue,//anime scene queue
autoPlay: false,//auto play with no event
flipType: 'click',//flip type eg:click, swipe, wheel
containerTemplate: '<div class="container"></div>',//scene root container, it will be appended to body.
prevBtnTemplate: '<div class="prev-btn btn J_PrevBtn">prev</div>',//prev button dom
nextBtnTemplate: '<div class="next-btn btn J_NextBtn">next</div>',//next button dom
startBtnTemplate: '<div class="start-btn btn J_StartBtn">start</div>', //start button dom
showLoading: function (){
$(".mask").show();
console.log("loading resource, show loading message.");
},
hideLoading: function (){
$(".mask").hide();
console.log("resource loaded, hide loading message.")
},
showFirstLoading: function() {
$(".opening").show();
console.log("loading first several scenes, show opening animation.");
},
hideFirstLoading: function (){
$(".opening").hide();
console.log("First batch of scencs loaded, hide opening animations.")
},
showError: function (msg){ console.log(msg); }
};
if(anole.isMobile()) {
config.flipType = 'swipe';
config.autoPlay = false;
}
/*
autoBtn.on('click', function(){
config.flipType = 'auto';
config.autoPlay = true;
anole.config(config);
anole.start();
autoBtn.hide();
});
*/
anole.config(config);
anole.start();
var window_w = document.body.clientWidth;
var window_h = document.body.clientHeight;
var canvas = anole.canvas;
var scene_w = canvas.width();
var scene_h = canvas.height();
var loading = $('.mask');
var opening = $('.opening');
loading.appendTo(canvas);
opening.appendTo(canvas);
var canvas_w;
var canvas_h;
var ratio = 0.75;
var scale = 1;
if (window_h / window_w < ratio) {
canvas_h = window_h;
canvas_w = ratio * window_h;
scale = window_h / scene_h + "";
} else {
canvas_w = window_w;
canvas_h = window_w / ratio;
scale = window_w / scene_w + "";
}
function getSupportedPropertyName() {
var properties = ["transform", "msTransform", "webkitTransform", "mozTransform", "oTransform"];
for (var i = 0; i < properties.length; i++) {
if (typeof document.body.style[properties[i]] != "undefined") {
return properties[i];
}
}
return null;
}
var transformProperty = getSupportedPropertyName();
canvas.css(transformProperty,"translate3d(-50%,"+((scale-1)*scene_h/2)+"px,0) scale("+scale+","+scale+")");
// canvas.css(transformProperty,"translate3d(-50%,"+((scale-1)*scene_h/2)+"px,0)");
})
});
|
'use strict';
AppConfig.registerModule('users');
|
function greet(whattosay) {
return function(name) {
console.log(whattosay + ' ' + name);
}
}
var sayHi = greet('Hi');
sayHi('Tony');
|
export default {
prefix: '/link'
};
|
// # Ghost Configuration
// Setup your Ghost install for various [environments](http://support.ghost.org/config/#about-environments).
// Ghost runs in `development` mode by default. Full documentation can be found at http://support.ghost.org/config/
var path = require('path'),
config;
// my app config
var myapp = {
//Uncomment the below if you have cloudinary account at https://cloudinary.com/ created and added credentials to node env
//cloudinary: {},
//Uncomment the below if you have mailgun account at https://www.mailgun.com/ created and added credentials to node env
//mailgun: {},
mysql: {}
};
myapp.port = (process.env.VCAP_APP_PORT || '2368');
myapp.host = (process.env.VCAP_APP_HOST || '127.0.0.1');
myapp.protocol = 'https://';
if (process.env.VCAP_APPLICATION != undefined) {
var vcap_application = JSON.parse(process.env.VCAP_APPLICATION);
myapp.route = vcap_application.application_uris[0];
}
if (process.env.VCAP_SERVICES != undefined) {
var vcap_services = JSON.parse(process.env.VCAP_SERVICES);
/* //uncomment if using experimental mysql service
if (vcap_services.mysql != undefined) {
myapp.mysql = vcap_services.mysql[0].credentials;
} else {
console.error('Cannot find mysql service');
process.exit(1);
}*/
// Default uses ClearDB
if (vcap_services.cleardb != undefined) {
myapp.mysql = vcap_services.cleardb[0].credentials;
} else {
console.error('Cannot find cleardb service');
process.exit(1);
}
}
//Uncomment the below if you have cloudinary account at https://cloudinary.com/ created and added credentials to node env
/*if (process.env.CLOUDINARY != undefined)
myapp.cloudinary = JSON.parse(process.env.CLOUDINARY);
//console.log(myapp.cloudinary);
*/
//Uncomment the below if you have mailgun account at https://www.mailgun.com/ created and added credentials to node env
/*if (process.env.MAILGUN != undefined)
myapp.mailgun = JSON.parse(process.env.MAILGUN);
*/
// end: my app config
config = {
// ### Production
// When running Ghost in the wild, use the production environment.
// Configure your URL and mail settings here
production: {
url: myapp.protocol + myapp.route,
// Uncomment mail block once you have gotten mailgun credentials and added env variables
/*mail: {
transport: 'SMTP',
options: {
service: 'Mailgun',
auth: {
user: myapp.mailgun.user, // mailgun username
pass: myapp.mailgun.pass // mailgun password
}
}
},
*/
database: {
client: 'mysql',
connection: {
host: myapp.mysql.hostname,
port: myapp.mysql.port,
user: myapp.mysql.username,
password: myapp.mysql.password,
database: myapp.mysql.name,
charset: 'utf8'
},
pool: {
min: 2,
max: 2
}
},
//Uncomment the below if you have cloudinary account at https://cloudinary.com/ created and added credentials to node env
// Note that local storage will not persist
/*
storage: {
active: 'ghost-cloudinary-store',
'ghost-cloudinary-store': {
cloud_name: myapp.cloudinary.cloud_name,
api_key: myapp.cloudinary.api_key,
api_secret: myapp.cloudinary.api_secret,
secure: true
}
},
*/
server: {
// Host to be passed to node's `net.Server#listen()`
host: myapp.host,
// Port to be passed to node's `net.Server#listen()`, for iisnode set this to `process.env.PORT`
port: myapp.port
},
forceAdminSSL: true
},
// ### Development **(default)**
development: {
// The url to use when providing links to the site, E.g. in RSS and email.
// Change this to your Ghost blog's published URL.
url: 'http://localhost:2368',
// Example refferer policy
// Visit https://www.w3.org/TR/referrer-policy/ for instructions
// default 'origin-when-cross-origin',
// referrerPolicy: 'origin-when-cross-origin',
// Example mail config
// Visit http://support.ghost.org/mail for instructions
// ```
// mail: {
// transport: 'SMTP',
// options: {
// service: 'Mailgun',
// auth: {
// user: '', // mailgun username
// pass: '' // mailgun password
// }
// }
// },
// ```
// #### Database
// Ghost supports sqlite3 (default), MySQL & PostgreSQL
database: {
client: 'sqlite3',
connection: {
filename: path.join(__dirname, '/content/data/ghost-dev.db')
},
debug: false
},
// #### Server
// Can be host & port (default), or socket
server: {
// Host to be passed to node's `net.Server#listen()`
host: '127.0.0.1',
// Port to be passed to node's `net.Server#listen()`, for iisnode set this to `process.env.PORT`
port: '2368'
},
// #### Paths
// Specify where your content directory lives
paths: {
contentPath: path.join(__dirname, '/content/')
}
},
// **Developers only need to edit below here**
// ### Testing
// Used when developing Ghost to run tests and check the health of Ghost
// Uses a different port number
testing: {
url: 'http://127.0.0.1:2369',
database: {
client: 'sqlite3',
connection: {
filename: path.join(__dirname, '/content/data/ghost-test.db')
},
pool: {
afterCreate: function (conn, done) {
conn.run('PRAGMA synchronous=OFF;' +
'PRAGMA journal_mode=MEMORY;' +
'PRAGMA locking_mode=EXCLUSIVE;' +
'BEGIN EXCLUSIVE; COMMIT;', done);
}
},
useNullAsDefault: true
},
server: {
host: '127.0.0.1',
port: '2369'
},
logging: false
},
// ### Testing MySQL
// Used by Travis - Automated testing run through GitHub
'testing-mysql': {
url: 'http://127.0.0.1:2369',
database: {
client: 'mysql',
connection: {
host : '127.0.0.1',
user : 'root',
password : '',
database : 'ghost_testing',
charset : 'utf8'
}
},
server: {
host: '127.0.0.1',
port: '2369'
},
logging: false
},
// ### Testing pg
// Used by Travis - Automated testing run through GitHub
'testing-pg': {
url: 'http://127.0.0.1:2369',
database: {
client: 'pg',
connection: {
host : '127.0.0.1',
user : 'postgres',
password : '',
database : 'ghost_testing',
charset : 'utf8'
}
},
server: {
host: '127.0.0.1',
port: '2369'
},
logging: false
}
};
module.exports = config;
|
import React from 'react'
import { Table } from 'semantic-ui-react'
const tableData = [
{ name: undefined, status: undefined, notes: undefined },
{ name: 'Jimmy', status: 'Requires Action', notes: undefined },
{ name: 'Jamie', status: undefined, notes: 'Hostile' },
{ name: 'Jill', status: undefined, notes: undefined },
]
const headerRow = ['Name', 'Status', 'Notes']
const renderBodyRow = ({ name, status, notes }, i) => ({
key: name || `row-${i}`,
warning: !!(status && status.match('Requires Action')),
cells: [
name || 'No name specified',
status ? { key: 'status', icon: 'attention', content: status } : 'Unknown',
notes
? { key: 'notes', icon: 'attention', content: notes, warning: true }
: 'None',
],
})
const TableExampleWarningShorthand = () => (
<Table
celled
headerRow={headerRow}
renderBodyRow={renderBodyRow}
tableData={tableData}
/>
)
export default TableExampleWarningShorthand
|
import * as React from 'react';
import PropTypes from 'prop-types';
import { chainPropTypes } from '@material-ui/utils';
import clsx from 'clsx';
import withStyles from '../styles/withStyles';
import InputBase from '../InputBase';
import MenuItem from '../MenuItem';
import Select from '../Select';
import TableCell from '../TableCell';
import Toolbar from '../Toolbar';
import Typography from '../Typography';
import TablePaginationActions from './TablePaginationActions';
import useId from '../utils/unstable_useId';
export const styles = (theme) => ({
/* Styles applied to the root element. */
root: {
color: theme.palette.text.primary,
fontSize: theme.typography.pxToRem(14),
overflow: 'auto',
// Increase the specificity to override TableCell.
'&:last-child': {
padding: 0,
},
},
/* Styles applied to the Toolbar component. */
toolbar: {
minHeight: 52,
paddingRight: 2,
},
/* Styles applied to the spacer element. */
spacer: {
flex: '1 1 100%',
},
/* Styles applied to the caption Typography components if `variant="caption"`. */
caption: {
flexShrink: 0,
},
// TODO v5: `.selectRoot` should be merged with `.input`
/* Styles applied to the Select component root element. */
selectRoot: {
marginRight: 32,
marginLeft: 8,
},
/* Styles applied to the Select component `select` class. */
select: {
paddingLeft: 8,
paddingRight: 24,
textAlign: 'right',
textAlignLast: 'right', // Align <select> on Chrome.
},
// TODO v5: remove
/* Styles applied to the Select component `icon` class. */
selectIcon: {},
/* Styles applied to the `InputBase` component. */
input: {
color: 'inherit',
fontSize: 'inherit',
flexShrink: 0,
},
/* Styles applied to the MenuItem component. */
menuItem: {},
/* Styles applied to the internal `TablePaginationActions` component. */
actions: {
flexShrink: 0,
marginLeft: 20,
},
});
const defaultLabelDisplayedRows = ({ from, to, count }) =>
`${from}-${to} of ${count !== -1 ? count : `more than ${to}`}`;
const defaultRowsPerPageOptions = [10, 25, 50, 100];
/**
* A `TableCell` based component for placing inside `TableFooter` for pagination.
*/
const TablePagination = React.forwardRef(function TablePagination(props, ref) {
const {
ActionsComponent = TablePaginationActions,
backIconButtonProps,
backIconButtonText = 'Previous page',
classes,
className,
colSpan: colSpanProp,
component: Component = TableCell,
count,
labelDisplayedRows = defaultLabelDisplayedRows,
labelRowsPerPage = 'Rows per page:',
nextIconButtonProps,
nextIconButtonText = 'Next page',
onChangePage,
onChangeRowsPerPage,
page,
rowsPerPage,
rowsPerPageOptions = defaultRowsPerPageOptions,
SelectProps = {},
...other
} = props;
let colSpan;
if (Component === TableCell || Component === 'td') {
colSpan = colSpanProp || 1000; // col-span over everything
}
const selectId = useId();
const labelId = useId();
const MenuItemComponent = SelectProps.native ? 'option' : MenuItem;
return (
<Component className={clsx(classes.root, className)} colSpan={colSpan} ref={ref} {...other}>
<Toolbar className={classes.toolbar}>
<div className={classes.spacer} />
{rowsPerPageOptions.length > 1 && (
<Typography color="inherit" variant="body2" className={classes.caption} id={labelId}>
{labelRowsPerPage}
</Typography>
)}
{rowsPerPageOptions.length > 1 && (
<Select
classes={{
select: classes.select,
icon: classes.selectIcon,
}}
input={<InputBase className={clsx(classes.input, classes.selectRoot)} />}
value={rowsPerPage}
onChange={onChangeRowsPerPage}
id={selectId}
labelId={labelId}
{...SelectProps}
>
{rowsPerPageOptions.map((rowsPerPageOption) => (
<MenuItemComponent
className={classes.menuItem}
key={rowsPerPageOption.value ? rowsPerPageOption.value : rowsPerPageOption}
value={rowsPerPageOption.value ? rowsPerPageOption.value : rowsPerPageOption}
>
{rowsPerPageOption.label ? rowsPerPageOption.label : rowsPerPageOption}
</MenuItemComponent>
))}
</Select>
)}
<Typography color="inherit" variant="body2" className={classes.caption}>
{labelDisplayedRows({
from: count === 0 ? 0 : page * rowsPerPage + 1,
to: count !== -1 ? Math.min(count, (page + 1) * rowsPerPage) : (page + 1) * rowsPerPage,
count: count === -1 ? -1 : count,
page,
})}
</Typography>
<ActionsComponent
className={classes.actions}
backIconButtonProps={{
title: backIconButtonText,
'aria-label': backIconButtonText,
...backIconButtonProps,
}}
count={count}
nextIconButtonProps={{
title: nextIconButtonText,
'aria-label': nextIconButtonText,
...nextIconButtonProps,
}}
onChangePage={onChangePage}
page={page}
rowsPerPage={rowsPerPage}
/>
</Toolbar>
</Component>
);
});
TablePagination.propTypes = {
/**
* The component used for displaying the actions.
* Either a string to use a HTML element or a component.
*/
ActionsComponent: PropTypes.elementType,
/**
* Props applied to the back arrow [`IconButton`](/api/icon-button/) component.
*/
backIconButtonProps: PropTypes.object,
/**
* Text label for the back arrow icon button.
*
* For localization purposes, you can use the provided [translations](/guides/localization/).
*/
backIconButtonText: PropTypes.string,
/**
* Override or extend the styles applied to the component.
* See [CSS API](#css) below for more details.
*/
classes: PropTypes.object.isRequired,
/**
* @ignore
*/
className: PropTypes.string,
/**
* @ignore
*/
colSpan: PropTypes.number,
/**
* The component used for the root node.
* Either a string to use a HTML element or a component.
*/
component: PropTypes /* @typescript-to-proptypes-ignore */.elementType,
/**
* The total number of rows.
*
* To enable server side pagination for an unknown number of items, provide -1.
*/
count: PropTypes.number.isRequired,
/**
* Customize the displayed rows label. Invoked with a `{ from, to, count, page }`
* object.
*
* For localization purposes, you can use the provided [translations](/guides/localization/).
*/
labelDisplayedRows: PropTypes.func,
/**
* Customize the rows per page label.
*
* For localization purposes, you can use the provided [translations](/guides/localization/).
*/
labelRowsPerPage: PropTypes.node,
/**
* Props applied to the next arrow [`IconButton`](/api/icon-button/) element.
*/
nextIconButtonProps: PropTypes.object,
/**
* Text label for the next arrow icon button.
*
* For localization purposes, you can use the provided [translations](/guides/localization/).
*/
nextIconButtonText: PropTypes.string,
/**
* Callback fired when the page is changed.
*
* @param {object} event The event source of the callback.
* @param {number} page The page selected.
*/
onChangePage: PropTypes.func.isRequired,
/**
* Callback fired when the number of rows per page is changed.
*
* @param {object} event The event source of the callback.
*/
onChangeRowsPerPage: PropTypes.func,
/**
* The zero-based index of the current page.
*/
page: chainPropTypes(PropTypes.number.isRequired, (props) => {
const { count, page, rowsPerPage } = props;
if (count === -1) {
return null;
}
const newLastPage = Math.max(0, Math.ceil(count / rowsPerPage) - 1);
if (page < 0 || page > newLastPage) {
return new Error(
'Material-UI: The page prop of a TablePagination is out of range ' +
`(0 to ${newLastPage}, but page is ${page}).`,
);
}
return null;
}),
/**
* The number of rows per page.
*/
rowsPerPage: PropTypes.number.isRequired,
/**
* Customizes the options of the rows per page select field. If less than two options are
* available, no select field will be displayed.
*/
rowsPerPageOptions: PropTypes.array,
/**
* Props applied to the rows per page [`Select`](/api/select/) element.
*/
SelectProps: PropTypes.object,
};
export default withStyles(styles, { name: 'MuiTablePagination' })(TablePagination);
|
'use strict';
module.exports = function ( gulp, plugins, config, pkg, bwr ) {
gulp.task( 'copy-base-src', 'Copy basic files in public directory', function () {
var baseFiles = [];
for ( var i = 0, l = config.basesiteList.length; i < l; i++ ) {
baseFiles.push( config.srcPath + '/' + config.basesiteList[ i ] );
}
return gulp
.src( baseFiles )
.pipe( gulp.dest( config.publicPath + '/' ) );
}
);
gulp.task( 'watch-base-src', 'Watch basic files sources', [ 'clean-base-src', 'copy-base-src' ], function () {
var baseFiles = [];
for ( var i = 0, l = config.basesiteList.length; i < l; i++ ) {
baseFiles.push( config.srcPath + '/' + config.basesiteList[ i ] );
}
plugins.tools.watch( baseFiles, [ 'clean-base-src', 'copy-base-src' ] );
}
);
gulp.task( 'add-outdated-browser', 'Copy vendors from bower library "outdated browser" into public directory', function () {
return gulp
.src( [
config.bowerDir + '/outdated-browser/outdatedbrowser/**/*'
]
)
.pipe( gulp.dest( config.publicPath + '/outdatedbrowser' ) );
}
);
};
|
/* eslint-disable camelcase */
import ApplicationSerializer from 'ghost-admin/serializers/application';
import {pluralize} from 'ember-inflector';
export default ApplicationSerializer.extend({
attrs: {
createdAtUTC: {key: 'created_at'},
updatedAtUTC: {key: 'updated_at'}
},
serializeIntoHash(hash, type, record, options) {
options = options || {};
options.includeId = true;
let root = pluralize(type.modelName);
let data = this.serialize(record, options);
// Properties that exist on the model but we don't want sent in the payload
delete data.count;
hash[root] = [data];
},
// if we use `queryRecord` ensure we grab the first record to avoid
// DS.SERIALIZER.REST.QUERYRECORD-ARRAY-RESPONSE deprecations
normalizeResponse(store, primaryModelClass, payload, id, requestType) {
if (requestType === 'queryRecord') {
let singular = primaryModelClass.modelName;
let plural = pluralize(singular);
if (payload[plural]) {
payload[singular] = payload[plural][0];
delete payload[plural];
}
}
return this._super(...arguments);
}
});
|
'use strict';
import Log from './log.model';
import config from '../../config';
import { handleError } from '../../components/errors';
import http from 'http';
function add(time, description) {
var log = new Log({ time: time, description: description });
log.save(function (err, usd) {
if (err) return console.error(err);
console.log('Added new log: ', time, ' ', description);
});
}
function clearAll(callback) {
Log.find({}).removeAsync().then(callback);
}
export function indexReq(req, res) {
Log.findAsync({})
.then(logs => {
let response = [];
logs.forEach((log, index) =>
{
response.push({time: log.time, description: log.description});
});
res.status(200).json(response);
}).catch(handleError(res));
}
export function clearAllReq(req, res) {
clearAll(()=>{
console.log('Logs have been cleaned');
res.status(200).json({error: false});
});
}
export function updateLog() {
var time = new Date(),
description = 'Update Log';
add(time, description);
}
|
/**
Copyright (C) 2014 Meiguro
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/**
* Helper class to load modules on PebbleKitJS apps.
*
* Directly extracted from the PebbleJS project {@link https://github.com/pebble/pebblejs}.
*/
var __loader = (function() {
var loader = {};
loader.packages = {};
loader.packagesLinenoOrder = [{ filename: 'loader.js', lineno: 0 }];
loader.extpaths = ['?', '?.js', '?.json', '?/index.js'];
loader.paths = ['/', 'lib', 'vendor'];
loader.basepath = function(path) {
return path.replace(/[^\/]*$/, '');
};
var replace = function(a, regexp, b) {
var z;
do {
z = a;
} while (z !== (a = a.replace(regexp, b)));
return z;
};
loader.normalize = function(path) {
path = replace(path, /(?:(^|\/)\.?\/)+/g, '$1');
path = replace(path, /[^\/]*\/\.\.\//, '');
return path;
};
loader.require = function(path, requirer) {
var module = loader.getPackage(path, requirer);
if (!module) {
throw new Error("Cannot find module '" + path + "'");
}
if (module.exports) {
return module.exports;
}
var require = function(path) { return loader.require(path, module); };
module.exports = {};
module.loader(module.exports, module, require);
module.loaded = true;
return module.exports;
};
var compareLineno = function(a, b) { return a.lineno - b.lineno; };
loader.define = function(path, lineno, loadfun) {
var module = {
filename: path,
lineno: lineno,
loader: loadfun,
};
loader.packages[path] = module;
loader.packagesLinenoOrder.push(module);
loader.packagesLinenoOrder.sort(compareLineno);
};
loader.getPackage = function(path, requirer) {
var module;
if (requirer) {
module = loader.getPackageAtPath(loader.basepath(requirer.filename) + '/' + path);
}
if (!module) {
module = loader.getPackageAtPath(path);
}
var paths = loader.paths;
for (var i = 0, ii = paths.length; !module && i < ii; ++i) {
var dirpath = paths[i];
module = loader.getPackageAtPath(dirpath + '/' + path);
}
return module;
};
loader.getPackageAtPath = function(path) {
path = loader.normalize(path);
var module;
var extpaths = loader.extpaths;
for (var i = 0, ii = extpaths.length; !module && i < ii; ++i) {
var filepath = extpaths[i].replace('?', path);
module = loader.packages[filepath];
}
return module;
};
loader.getPackageByLineno = function(lineno) {
var packages = loader.packagesLinenoOrder;
var module;
for (var i = 0, ii = packages.length; i < ii; ++i) {
var next = packages[i];
if (next.lineno > lineno) {
break;
}
module = next;
}
return module;
};
return loader;
})();
|
// gulpfile.js
gulp.task('templates', function() {
gulp.src('./frontend/tpl/**/*.html')
.pipe(tap(function(file, t) {
var precompiled = Ractive.parse(file.contents.toString());
precompiled = JSON.stringify(precompiled);
file.contents = new Buffer('module.exports = ' + precompiled);
}))
.pipe(rename(function(path) {
path.extname = '.js';
}))
.pipe(gulp.dest('./frontend/tpl'))
});
|
require("app").directive("viewMeasure", [function () {
return {
restrict : "EAC",
templateUrl: "/app/views/forms/view/view-measure.directive.html",
replace : true,
transclude : false,
scope: {
document : "=ngModel",
locale : "=",
target : "@linkTarget",
allowDrafts : "@"
},
controller : ["$scope", "IStorage", function ($scope, storage)
{
//====================
//
//====================
$scope.$watch("document.amendedMeasures", function(_new)
{
if ($scope.document && $scope.document.amendedMeasures) {
$scope.amendedMeasures = angular.fromJson(angular.toJson($scope.document.amendedMeasures));
if ($scope.amendedMeasures)
$scope.loadReferences($scope.amendedMeasures, true);
}
});
//====================
//
//====================
$scope.$watch("document.registeredMeasures", function (_new) {
if ($scope.document && $scope.document.registeredMeasures) {
$scope.registeredMeasures = angular.fromJson(angular.toJson($scope.document.registeredMeasures));
if ($scope.registeredMeasures)
$scope.loadReferences($scope.registeredMeasures, true);
}
});
//====================
//
//====================
$scope.$watch("document.linkedMeasures", function(_new)
{
if ($scope.document && $scope.document.linkedMeasures) {
$scope.linkedMeasures = angular.fromJson(angular.toJson($scope.document.linkedMeasures));
if ($scope.linkedMeasures)
$scope.loadReferences($scope.linkedMeasures, true);
}
});
//====================
//
//====================
$scope.loadReferences = function(targets, infoOnly) {
angular.forEach(targets, function(ref) {
var oOptions = { cache: true };
if (infoOnly)
oOptions.info = true;
storage.documents.get(ref.identifier, oOptions)
.success(function(data){
ref.document = data;
})
.error(function(error, code){
if (code == 404 && $scope.allowDrafts == "true") {
storage.drafts.get(ref.identifier, oOptions)
.success(function(data){
ref.document = data;
})
.error(function(draftError, draftCode){
ref.document = undefined;
ref.error = error;
ref.errorCode = code;
});
}
ref.document = undefined;
ref.error = error;
ref.errorCode = code;
});
});
};
}]
};
}]);
|
// import resetSelection from '../resetSelection';
Meteor.startup(() => {
RocketChat.TabBar.addButton({
groups: ['channel', 'group', 'direct'],
id: 'mail-messages',
anonymous: true,
i18nTitle: 'Mail_Messages',
icon: 'mail',
template: 'mailMessagesInstructions',
order: 10,
condition: () => RocketChat.authz.hasAllPermission('mail-messages'),
});
// RocketChat.callbacks.add('roomExit', () => resetSelection(false), RocketChat.callbacks.priority.MEDIUM, 'room-exit-mail-messages');
});
|
angular.module('IssueTracker.home.service',[
'IssueTracker.currentProject.service'
])
.factory('homeService',[
'$http',
'$q',
'BASE_URL',
function($http,$q,BASE_URL) {
function getCurrentUserIssues() {
var deferred = $q.defer();
var request = {
method: 'GET',
url: BASE_URL + 'issues/me?orderBy=Project.Name desc, IssueKey&pageSize=4&pageNumber=1',
headers: {'Authorization': 'Bearer ' + sessionStorage.authToken}
};
$http(request)
.then(
function(data) {
deferred.resolve(data);
}, function(err) {
deferred.reject(err);
}
);
return deferred.promise;
}
function getProjectById(id) {
var deferred = $q.defer();
var request = {
method: 'GET',
url: BASE_URL + 'projects/' + id,
headers: {'Authorization' : 'Bearer ' + sessionStorage.authToken}
};
$http(request)
.then(
function(data) {
deferred.resolve(data);
}, function(err) {
deferred.reject(err);
}
);
return deferred.promise;
}
return {
getUserIssues: getCurrentUserIssues,
getProjectById: getProjectById
}
}
]);
|
/* eslint-disable camelcase */
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import { Form } from 'react-redux-form'
import AUpageAlert from '@gov.au/page-alerts/lib/js/react.js'
import AUselect from '@gov.au/select/lib/js/react.js'
import DocumentTitle from 'react-document-title'
import { required, validEmail, validABN } from 'shared/validators'
import { EMAIL_NOT_WHITELISTED, GENERAL_ERROR } from 'marketplace/constants/messageConstants'
import Layout from 'shared/Layout'
import ErrorBox from 'shared/form/ErrorBox'
import Textfield from 'shared/form/Textfield'
import RadioList from 'shared/form/RadioList'
import RadioListBox from 'shared/form/RadioListBox/RadioListBox'
import LoadingButton from 'shared/LoadingButton/LoadingButton'
const getErrorMessageFromServerCode = (code, abn) => {
let message = ''
switch (code) {
case 403:
message = <p>{EMAIL_NOT_WHITELISTED}</p>
break
case 409:
message = (
<React.Fragment>
<p>There is already a seller account with the ABN {abn}. Make sure you:</p>
<ul>
<li>
<a href="#abn">Check the number you entered is correct</a>
</li>
<li>Check if anyone in your organisation has created an account and ask them to add you as a member</li>
</ul>
<p>
If you have any issues, <a href="/contact-us">contact the Marketplace</a>.
</p>
</React.Fragment>
)
break
default:
message = <p>{GENERAL_ERROR}</p>
break
}
return message
}
class SignupForm extends Component {
constructor(props) {
super(props)
this.state = {
isInternational: false
}
this.handleInternationalChange = this.handleInternationalChange.bind(this)
}
handleInternationalChange(e) {
const isIntl = e.target.value
this.setState({
isInternational: isIntl === 'yes'
})
}
render() {
const {
csrf_token,
model,
children,
signupForm,
signupSuccess,
currentlySending,
isBuyer,
userType,
signupErrorCode,
signupABN,
emailValidators,
emailErrorMessages,
submitClicked,
onSubmitClicked,
onSubmitFailed,
handleSubmit
} = this.props
const employmentStatus = signupForm.employment_status
let hasFocused = false
const setFocus = e => {
if (!hasFocused) {
hasFocused = true
e.focus()
}
}
return (
<div className="row">
<DocumentTitle title="Signup - Digital Marketplace">
<div className="col-sm-push-2 col-sm-8 col-xs-12">
<div>
{signupSuccess && (
<div>
<AUpageAlert as="success">
<h4 className="au-display-sm">Signup email sent</h4>
</AUpageAlert>
<article role="main">
<header className="page-heading page-heading-without-breadcrumb">
<span />
<h1 className="au-display-xl">Thanks for requesting access to the Digital Marketplace.</h1>
</header>
{isBuyer && signupForm.employment_status === 'contractor' ? (
<div>
<span />
<p>
An email has been sent to your manager at <strong>{signupForm.line_manager_email}</strong>{' '}
with next steps.
</p>
<p>
If they don’t receive the email within the next 5 minutes or so, check to see if it’s been
classified as spam or
<a href="/contact-us" target="_blank" rel="noopener noreferrer">
{' '}
contact us{' '}
</a>{' '}
for assistance.
</p>
</div>
) : (
<div>
<span />
<p>
An email has been sent to <strong>{signupForm.email_address}</strong> with next steps.
</p>
<p>
If you don’t receive the email within the next 5 minutes or so, check to see if it’s been
classified as spam or
<a href="/contact-us" target="_blank" rel="noopener noreferrer">
{' '}
contact us{' '}
</a>{' '}
for assistance.
</p>
</div>
)}
</article>
</div>
)}
{!signupSuccess && (
<Layout>
<ErrorBox
title="There was a problem with signup"
model={model}
submitClicked={submitClicked}
setFocus={setFocus}
/>
{signupErrorCode && (
<AUpageAlert as="error">
<h4 className="au-display-md">There was a problem with signup</h4>
{getErrorMessageFromServerCode(signupErrorCode, signupABN)}
</AUpageAlert>
)}
<header>
<h1 className="au-display-xl">Let’s get started</h1>
</header>
<article role="main">
<Form
model={model}
method="post"
id="signup"
onSubmit={data => handleSubmit(data)}
onSubmitFailed={onSubmitFailed}
>
{csrf_token && <input type="hidden" name="csrf_token" id="csrf_token" value={csrf_token} />}
<div className="user-type">
<RadioListBox
model={`${model}.user_type`}
name="user_type"
id="user_type"
label="Choose the option that matches your situation."
options={[
{
value: 'buyer',
label: (
<span>
<span>Buyer</span>
<br />
<br />
I want to buy on behalf of
<br />
government.
</span>
)
},
{
value: 'seller',
label: (
<span>
<span>Seller</span>
<br />
<br />
I want to sell digital products or
<br />
services.
</span>
)
}
]}
validators={{
required
}}
messages={{
required: 'You must select a user type'
}}
/>
</div>
{userType && (
<React.Fragment>
{userType === 'buyer' && (
<React.Fragment>Now enter your name and your work email address.</React.Fragment>
)}
{userType === 'seller' && (
<React.Fragment>Now enter your name, your work email address, and your ABN.</React.Fragment>
)}
<Textfield
model={`${model}.name`}
name="name"
id="name"
htmlFor="name"
label="Full name"
validators={{
required
}}
messages={{
required: 'Your name is required'
}}
/>
<Textfield
model={`${model}.email_address`}
name="email_address"
id="email_address"
type="email"
htmlFor="email_address"
label="Email address"
validators={emailValidators}
messages={emailErrorMessages}
/>
</React.Fragment>
)}
{userType === 'seller' && (
<React.Fragment>
<label className="question-heading au-text-input__label" htmlFor="international">
Australian business status
</label>
<AUselect
required
block
id="international"
onChange={this.handleInternationalChange}
value={this.state.isInternational ? 'yes' : 'no'}
options={[
{
value: 'no',
text: 'My business is located inside Australia'
},
{
value: 'yes',
text: 'My business is located outside Australia'
}
]}
/>
{!this.state.isInternational && (
<Textfield
model={`${model}.abn`}
name="abn"
id="abn"
type="text"
htmlFor="abn"
label="ABN"
validators={{
required: v => required(v),
validABN: v => !v || validABN(v)
}}
messages={{
required: 'You must supply an ABN',
validABN: 'The ABN supplied is not valid'
}}
/>
)}
{this.state.isInternational && (
<Textfield
model={`${model}.abn`}
name="abn"
id="abn"
type="text"
htmlFor="abn"
label="International business identifier number"
description="This should be a number that is the equivalent of an ABN for your country of operation"
validators={{
required: v => required(v)
}}
messages={{
required: 'You must supply an International business identifier number'
}}
/>
)}
</React.Fragment>
)}
{isBuyer && (
<div className="employment-status">
<RadioList
model={`${model}.employment_status`}
name="employment_status"
id="employment_status"
label="To create a buyer account you need to be a government employee or be authorised by a government employee. Choose the option below that matches your situation."
options={[
{
value: 'employee',
label:
'I am an employee under the Commonwealth Public Service Act (1999) or under equivalent state or territory legislation and need access to the Digital Marketplace to perform my role.'
},
{
value: 'contractor',
label: 'I am a contractor working in local, state or federal government.'
}
]}
validators={{
required
}}
messages={{
required: 'You must specify your employment status.'
}}
/>
</div>
)}
{employmentStatus && employmentStatus === 'contractor' && isBuyer && (
<div>
<p>To create your account we will also need approval from a line manager who:</p>
<ul>
<li>
Is an employee under the Commonwealth Public Service Act (1999) or under equivalent State
or Territory legislation, and
</li>
<li>is satisfied you need to access the Digital Marketplace.</li>
</ul>
<Textfield
model={`${model}.line_manager_name`}
name="line_manager_name"
id="line_manager_name"
htmlFor="line_manager_name"
label="Your manager's full name"
validators={{
required
}}
messages={{
required: 'You must provide the name of your manager'
}}
/>
<Textfield
model={`${model}.line_manager_email`}
name="line_manager_email"
id="line_manager_email"
htmlFor="line_manager_email"
label="Your manager's email address"
validators={{
required,
validEmail
}}
messages={{
required: "You must provide your manager's email address",
validEmail: 'A validly formatted email is required.'
}}
/>
<AUpageAlert as="info">
<p>
Remember to let this person know we’ll be sending them an email requesting their
authorisation.
</p>
</AUpageAlert>
</div>
)}
{children}
{userType && (
<React.Fragment>
<p>
<small>
By creating an account you confirm your acceptance of our{' '}
<a href="/terms-of-use" target="_blank" rel="noopener noreferrer">
Terms of Use
</a>
</small>
</p>
{currentlySending ? (
<LoadingButton />
) : (
<p>
<input
className="au-btn"
type="submit"
value="Create your account"
onClick={onSubmitClicked}
/>
</p>
)}
</React.Fragment>
)}
</Form>
</article>
</Layout>
)}
</div>
</div>
</DocumentTitle>
</div>
)
}
}
SignupForm.propTypes = {
csrf_token: PropTypes.string,
model: PropTypes.string.isRequired,
signupForm: PropTypes.object.isRequired,
signupSuccess: PropTypes.bool,
currentlySending: PropTypes.bool.isRequired,
isBuyer: PropTypes.bool.isRequired,
userType: PropTypes.string.isRequired,
signupErrorCode: PropTypes.number,
signupABN: PropTypes.string,
emailValidators: PropTypes.object.isRequired,
emailErrorMessages: PropTypes.object.isRequired,
submitClicked: PropTypes.bool.isRequired,
onSubmitClicked: PropTypes.func.isRequired,
onSubmitFailed: PropTypes.func.isRequired,
handleSubmit: PropTypes.func.isRequired
}
SignupForm.defaultProps = {
csrf_token: '',
signupErrorCode: null,
signupABN: '',
signupSuccess: null
}
const mapStateToProps = () => ({})
export default connect(mapStateToProps)(SignupForm)
|
import createSvgIcon from './utils/createSvgIcon';
import { jsx as _jsx } from "react/jsx-runtime";
export default createSvgIcon( /*#__PURE__*/_jsx("path", {
d: "M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm2-10H7v2h7v-2zm0-3H7v2h7V7zm-7 8h3v-2H7v2zm12-2v2h-2v2h-2v-2h-2v-2h2v-2h2v2h2z"
}), 'PlaylistAddCircleOutlined');
|
import inject from 'ember-cli-window-properties/initializers/inject';
export default inject;
|
var class_tempo_1_1_list_cell_changed =
[
[ "ListCellChanged", "class_tempo_1_1_list_cell_changed.html#a1ee3319d7a3fd7c479f7f16aca05c453", null ],
[ "Destroy", "class_tempo_1_1_list_cell_changed.html#a63d434f996f8ac1cffb9ff01a16d19dd", null ],
[ "Action", "class_tempo_1_1_list_cell_changed.html#a520a081c0bfa37a133a0973523a2b8ea", null ],
[ "NewItems", "class_tempo_1_1_list_cell_changed.html#a775e60adbe78f07a4a761fb5602fb8e1", null ],
[ "NewStartingIndex", "class_tempo_1_1_list_cell_changed.html#a42b0f028d7162f85f03332770c8225e0", null ],
[ "OldItemCount", "class_tempo_1_1_list_cell_changed.html#a88f44137f754c80d5f4ae6374c9cf2b9", null ],
[ "OldStartingIndex", "class_tempo_1_1_list_cell_changed.html#ac624e2c6ecd0a46be47a90e9afcb2633", null ]
];
|
(function () {
'use strict';
var addNode = function (node) {
node.isOpen = true;
node.children.push({
name: 'child node ' + node.children.length,
parent: node,
isParent: true,
children: [],
buttons: [
{
title: 'Add',
icon: 'fa fa-plus',
click: addNode
}, {
title: 'Delete',
icon: 'fa fa-trash',
click: function (node) {
node.parent.children.splice(node.parent.children.indexOf(node), 1);
}
}
]
});
};
new Vue({
el: '#demo',
data: {
title: 'Vue Tree Demo',
option: {
root: {
name: 'Root Node',
isParent: true,
isOpen: true,
openedIcon: 'fa fa-folder-open-o',
closedIcon: 'fa fa-folder-o',
children: [
{
name: 'Level1'
},
{
name: 'Level1 with icon',
icon: 'fa fa-cube',
title: '192.168.89.0'
},
{
name: 'Edit node',
buttons: [
{
title: 'Edit',
icon: 'fa fa-edit',
click: function (node) {
node.name = prompt('Editing node name, require string', node.name) || node.name;
}
}
]
},
{
name: 'Level1 has children',
icon: 'fa fa-folder',
openedIcon: 'fa fa-folder-open',
isOpen: false,
isParent: true,
children: [
{
name: 'level2 - 1',
icon: 'fa fa-file'
},
{
name: 'level2 - 2',
icon: 'fa fa-file'
},
{
name: 'level2 - 3',
icon: 'fa fa-file'
}
]
},
{
name: 'Level1 add node',
isParent: true,
children: [],
buttons: [
{
title: 'Add',
icon: 'fa fa-plus',
click: function (node) {
node.isOpen = true;
node.children.push({
name: 'Level2 node ' + node.children.length,
parent: node,
buttons: [
{
title: 'Delete',
icon: 'fa fa-trash',
click: function (node) {
node.parent.children.splice(node.parent.children.indexOf(node), 1);
}
}
]
});
}
}
]
},
{
name: 'Level1-addNode',
isParent: true,
children: [],
buttons: [
{
title: 'Add',
icon: 'fa fa-plus',
click: addNode
}
]
},
{
name: 'Level1 Ajax',
isParent: true,
children: [],
showLoading: true, // if (node.showLoading && node._loading) then show loading icon
onOpened: function (node) {
if (!node._loading) {
Vue.set(node, 'children', []); // Clean old data
node._loading = true; // Start Ajax
setTimeout(function () { //
node._loading = false; //Finish Ajax
for (var i = 1; i < 6; i++) {
node.children.push({name: 'Ajax Node ' + i});
}
}, 2000);
}
},
onClosed: function () {
// NOOP
}
}
]
}
}
}
});
})();
|
import { connect } from 'react-redux'
import List from '../components/List'
import { showNote, showLayer } from '../actions/note'
const mapStateToProps = (state, ownProps) => ({
listData: state.notes,
isShowLayer: state.isShowLayer
})
const mapDispatchToProps = (dispatch, ownProps) => ({
onClick: (id) => {
dispatch(showNote(id))
},
addBtnClick: (isSL) => {
dispatch(showLayer(isSL))
}
})
const ContainerList = connect(
mapStateToProps,
mapDispatchToProps
)(List)
export default ContainerList
|
'use strict';
var torrents = require('torrent-stream')
var path = require('path')
function share(torrent, torrentFile, port, cb) {
var engine = torrents(torrent, {
tracker: false
, dht: false
, path: path.dirname(torrentFile)
})
engine.files.forEach(function(f) {
f.select()
})
engine.listen(port, function() {
cb(null, engine)
})
engine.on('peer', function() {
console.log('new peer!')
})
return engine
}
module.exports = share
|
faulty child
|
var user = require("../public/data.json");
exports.view = function(req, res){
for (var i = 0; i < user["user"].length; i++) {
if(username == user["user"][i].username){
if(req.query.newGoal != null){
user["user"][i].goal = req.query.newGoal;
}
var goal = user["user"][i].goal;
res.render('editGoal', {"goal":goal});
}
}
};
|
// DESCRIPTION = disallow trailing whitespace at the end of lines
// STATUS = 2
// <!START
// END!>
document.window.append('', null);
|
//
// SmoothScroll for websites v1.3.8 (Balazs Galambosi)
// Licensed under the terms of the MIT license.
//
// You may use it in your theme if you credit me.
// It is also free to use on any individual website.
//
// Exception:
// The only restriction would be not to publish any
// extension for browsers or native application
// without getting a written permission first.
//
(function(){
// Scroll Variables (tweakable)
var defaultOptions = {
// Scrolling Core
frameRate : 250, // [Hz]
animationTime : 2000, // [px]
stepSize : 120, // [px]
// Pulse (less tweakable)
// ratio of "tail" to "acceleration"
pulseAlgorithm : true,
pulseScale : 8,
pulseNormalize : 1,
// Acceleration
accelerationDelta : 20, // 20
accelerationMax : 1, // 1
// Keyboard Settings
keyboardSupport : true, // option
arrowScroll : 50, // [px]
// Other
touchpadSupport : true,
fixedBackground : true,
excluded : ''
};
var options = defaultOptions;
// Other Variables
var isExcluded = false;
var isFrame = false;
var direction = { x: 0, y: 0 };
var initDone = false;
var root = document.documentElement;
var activeElement;
var observer;
var deltaBuffer = [];
var scrollRoot;
var isMac = /^Mac/.test(navigator.platform);
var key = { left: 37, up: 38, right: 39, down: 40, spacebar: 32,
pageup: 33, pagedown: 34, end: 35, home: 36 };
/***********************************************
* SETTINGS
***********************************************/
var options = defaultOptions;
/***********************************************
* INITIALIZE
***********************************************/
/**
* Tests if smooth scrolling is allowed. Shuts down everything if not.
*/
function initTest() {
if (options.keyboardSupport) {
addEvent('keydown', keydown);
}
}
/**
* Sets up scrolls array, determines if frames are involved.
*/
function init() {
if (initDone || !document.body) return;
initDone = true;
var body = document.body;
var html = document.documentElement;
var windowHeight = window.innerHeight;
var scrollHeight = body.scrollHeight;
// check compat mode for root element
root = (document.compatMode.indexOf('CSS') >= 0) ? html : body;
activeElement = body;
initTest();
// Checks if this script is running in a frame
if (top != self) {
isFrame = true;
}
/**
* This fixes a bug where the areas left and right to
* the content does not trigger the onmousewheel event
* on some pages. e.g.: html, body { height: 100% }
*/
else if (scrollHeight > windowHeight &&
(body.offsetHeight <= windowHeight ||
html.offsetHeight <= windowHeight)) {
// DOMChange (throttle): fix height
var pending = false;
var refresh = function () {
if (!pending && html.scrollHeight != document.height) {
pending = true; // add a new pending action
setTimeout(function () {
html.style.height = document.height + 'px';
pending = false;
}, 500); // act rarely to stay fast
}
};
html.style.oldHeight = html.style.height;
html.style.height = 'auto';
setTimeout(refresh, 10);
var config = {
attributes: true,
childList: true,
characterData: false
};
observer = new MutationObserver(refresh);
observer.observe(body, config);
// clearfix
if (root.offsetHeight <= windowHeight) {
var underlay = document.createElement('div');
underlay.style.clear = 'both';
body.appendChild(underlay);
}
}
// disable fixed background
if (!options.fixedBackground && !isExcluded) {
body.style.backgroundAttachment = 'scroll';
html.style.backgroundAttachment = 'scroll';
}
}
/**
* Removes event listeners and other traces left on the page.
*/
function cleanup() {
observer && observer.disconnect();
removeEvent(wheelEvent, wheel);
removeEvent('mousedown', mousedown);
removeEvent('keydown', keydown);
var html = document.documentElement;
html.style.height = html.style.oldHeight;
}
/************************************************
* SCROLLING
************************************************/
var que = [];
var pending = false;
var lastScroll = Date.now();
/**
* Pushes scroll actions to the scrolling queue.
*/
function scrollArray(elem, left, top, delay) {
delay || (delay = 1000);
directionCheck(left, top);
if (options.accelerationMax != 1) {
var now = Date.now();
var elapsed = now - lastScroll;
if (elapsed < options.accelerationDelta) {
var factor = (1 + (50 / elapsed)) / 2;
if (factor > 1) {
factor = Math.min(factor, options.accelerationMax);
left *= factor;
top *= factor;
}
}
lastScroll = Date.now();
}
// push a scroll command
que.push({
x: left,
y: top,
lastX: (left < 0) ? 0.99 : -0.99,
lastY: (top < 0) ? 0.99 : -0.99,
start: Date.now()
});
// don't act if there's a pending queue
if (pending) {
return;
}
var scrollWindow = (elem === document.body);
var step = function (time) {
var now = Date.now();
var scrollX = 0;
var scrollY = 0;
for (var i = 0; i < que.length; i++) {
var item = que[i];
var elapsed = now - item.start;
var finished = (elapsed >= options.animationTime);
// scroll position: [0, 1]
var position = (finished) ? 1 : elapsed / options.animationTime;
// easing [optional]
if (options.pulseAlgorithm) {
position = pulse(position);
}
// only need the difference
var x = (item.x * position - item.lastX) >> 0;
var y = (item.y * position - item.lastY) >> 0;
// add this to the total scrolling
scrollX += x;
scrollY += y;
// update last values
item.lastX += x;
item.lastY += y;
// delete and step back if it's over
if (finished) {
que.splice(i, 1); i--;
}
}
// scroll left and top
if (scrollWindow) {
window.scrollBy(scrollX, scrollY);
}
else {
if (scrollX) elem.scrollLeft += scrollX;
if (scrollY) elem.scrollTop += scrollY;
}
// clean up if there's nothing left to do
if (!left && !top) {
que = [];
}
if (que.length) {
requestFrame(step, elem, (delay / options.frameRate + 1));
} else {
pending = false;
}
};
// start a new queue of actions
requestFrame(step, elem, 0);
pending = true;
}
/***********************************************
* EVENTS
***********************************************/
/**
* Mouse wheel handler.
* @param {Object} event
*/
function wheel(event) {
if (!initDone) {
init();
}
var target = event.target;
var overflowing = overflowingAncestor(target);
// use default if there's no overflowing
// element or default action is prevented
// or it's a zooming event with CTRL
if (!overflowing || event.defaultPrevented || event.ctrlKey) {
return true;
}
// leave embedded content alone (flash & pdf)
if (isNodeName(activeElement, 'embed') ||
(isNodeName(target, 'embed') && /\.pdf/i.test(target.src)) ||
isNodeName(activeElement, 'object')) {
return true;
}
var deltaX = -event.wheelDeltaX || event.deltaX || 0;
var deltaY = -event.wheelDeltaY || event.deltaY || 0;
if (isMac) {
if (event.wheelDeltaX && isDivisible(event.wheelDeltaX, 120)) {
deltaX = -120 * (event.wheelDeltaX / Math.abs(event.wheelDeltaX));
}
if (event.wheelDeltaY && isDivisible(event.wheelDeltaY, 120)) {
deltaY = -120 * (event.wheelDeltaY / Math.abs(event.wheelDeltaY));
}
}
// use wheelDelta if deltaX/Y is not available
if (!deltaX && !deltaY) {
deltaY = -event.wheelDelta || 0;
}
// line based scrolling (Firefox mostly)
if (event.deltaMode === 1) {
deltaX *= 40;
deltaY *= 40;
}
// check if it's a touchpad scroll that should be ignored
if (!options.touchpadSupport && isTouchpad(deltaY)) {
return true;
}
// scale by step size
// delta is 120 most of the time
// synaptics seems to send 1 sometimes
if (Math.abs(deltaX) > 1.2) {
deltaX *= options.stepSize / 120;
}
if (Math.abs(deltaY) > 1.2) {
deltaY *= options.stepSize / 120;
}
scrollArray(overflowing, deltaX, deltaY);
event.preventDefault();
scheduleClearCache();
}
/**
* Keydown event handler.
* @param {Object} event
*/
function keydown(event) {
var target = event.target;
var modifier = event.ctrlKey || event.altKey || event.metaKey ||
(event.shiftKey && event.keyCode !== key.spacebar);
// do nothing if user is editing text
// or using a modifier key (except shift)
// or in a dropdown
// or inside interactive elements
if ( /input|textarea|select|embed|object/i.test(target.nodeName) ||
isNodeName(activeElement, 'video') ||
isInsideYoutubeVideo(event) ||
target.isContentEditable ||
event.defaultPrevented ||
modifier ) {
return true;
}
// spacebar should trigger button press
if (isNodeName(target, 'button') &&
event.keyCode === key.spacebar) {
return true;
}
var shift, x = 0, y = 0;
var elem = overflowingAncestor(activeElement);
var clientHeight = elem.clientHeight;
if (elem == document.body) {
clientHeight = window.innerHeight;
}
switch (event.keyCode) {
case key.up:
y = -options.arrowScroll;
break;
case key.down:
y = options.arrowScroll;
break;
case key.spacebar: // (+ shift)
shift = event.shiftKey ? 1 : -1;
y = -shift * clientHeight * 0.9;
break;
case key.pageup:
y = -clientHeight * 0.9;
break;
case key.pagedown:
y = clientHeight * 0.9;
break;
case key.home:
y = -elem.scrollTop;
break;
case key.end:
var damt = elem.scrollHeight - elem.scrollTop - clientHeight;
y = (damt > 0) ? damt+10 : 0;
break;
case key.left:
x = -options.arrowScroll;
break;
case key.right:
x = options.arrowScroll;
break;
default:
return true; // a key we don't care about
}
scrollArray(elem, x, y);
event.preventDefault();
scheduleClearCache();
}
/**
* Mousedown event only for updating activeElement
*/
function mousedown(event) {
activeElement = event.target;
}
/***********************************************
* OVERFLOW
***********************************************/
var uniqueID = (function () {
var i = 0;
return function (el) {
return el.uniqueID || (el.uniqueID = i++);
};
})();
var cache = {}; // cleared out after a scrolling session
var clearCacheTimer;
//setInterval(function () { cache = {}; }, 10 * 1000);
function scheduleClearCache() {
clearTimeout(clearCacheTimer);
clearCacheTimer = setInterval(function () { cache = {}; }, 1*1000);
}
function setCache(elems, overflowing) {
for (var i = elems.length; i--;)
cache[uniqueID(elems[i])] = overflowing;
return overflowing;
}
function overflowingAncestor(el) {
var elems = [];
var body = document.body;
var rootScrollHeight = root.scrollHeight;
do {
var cached = cache[uniqueID(el)];
if (cached) {
return setCache(elems, cached);
}
elems.push(el);
if (rootScrollHeight === el.scrollHeight) {
var isOverflowCSS = (overflowNotHidden(body) && overflowNotHidden(root));
if (isFrame && isContentOverflowing(root) ||
!isFrame && isOverflowCSS) {
return setCache(elems, getScrollRoot());
}
} else if (isContentOverflowing(el) && overflowAutoOrScroll(el)) {
return setCache(elems, el);
}
} while (el = el.parentElement);
}
function isContentOverflowing(el) {
return (el.clientHeight + 10 < el.scrollHeight);
}
// typically for <body> and <html>
function overflowNotHidden(el) {
var overflow = getComputedStyle(el, '').getPropertyValue('overflow-y');
return (overflow !== 'hidden');
}
// for all other elements
function overflowAutoOrScroll(el) {
var overflow = getComputedStyle(el, '').getPropertyValue('overflow-y');
return (overflow === 'scroll' || overflow === 'auto');
}
/***********************************************
* HELPERS
***********************************************/
function addEvent(type, fn, bubble) {
window.addEventListener(type, fn, (bubble||false));
}
function removeEvent(type, fn, bubble) {
window.removeEventListener(type, fn, (bubble||false));
}
function isNodeName(el, tag) {
return (el.nodeName||'').toLowerCase() === tag.toLowerCase();
}
function directionCheck(x, y) {
x = (x > 0) ? 1 : -1;
y = (y > 0) ? 1 : -1;
if (direction.x !== x || direction.y !== y) {
direction.x = x;
direction.y = y;
que = [];
lastScroll = 0;
}
}
var deltaBufferTimer;
if (window.localStorage && localStorage.SS_deltaBuffer) {
deltaBuffer = localStorage.SS_deltaBuffer.split(',');
}
function isTouchpad(deltaY) {
if (!deltaY) return;
if (!deltaBuffer.length) {
deltaBuffer = [deltaY, deltaY, deltaY];
}
deltaY = Math.abs(deltaY)
deltaBuffer.push(deltaY);
deltaBuffer.shift();
clearTimeout(deltaBufferTimer);
deltaBufferTimer = setTimeout(function () {
if (window.localStorage) {
localStorage.SS_deltaBuffer = deltaBuffer.join(',');
}
}, 1000);
return !allDeltasDivisableBy(120) && !allDeltasDivisableBy(100);
}
function isDivisible(n, divisor) {
return (Math.floor(n / divisor) == n / divisor);
}
function allDeltasDivisableBy(divisor) {
return (isDivisible(deltaBuffer[0], divisor) &&
isDivisible(deltaBuffer[1], divisor) &&
isDivisible(deltaBuffer[2], divisor));
}
function isInsideYoutubeVideo(event) {
var elem = event.target;
var isControl = false;
if (document.URL.indexOf ('www.youtube.com/watch') != -1) {
do {
isControl = (elem.classList &&
elem.classList.contains('html5-video-controls'));
if (isControl) break;
} while (elem = elem.parentNode);
}
return isControl;
}
var requestFrame = (function () {
return (window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
function (callback, element, delay) {
window.setTimeout(callback, delay || (1000/60));
});
})();
var MutationObserver = (window.MutationObserver ||
window.WebKitMutationObserver ||
window.MozMutationObserver);
var getScrollRoot = (function() {
var SCROLL_ROOT;
return function() {
if (!SCROLL_ROOT) {
var dummy = document.createElement('div');
dummy.style.cssText = 'height:10000px;width:1px;';
document.body.appendChild(dummy);
var bodyScrollTop = document.body.scrollTop;
var docElScrollTop = document.documentElement.scrollTop;
window.scrollBy(0, 1);
if (document.body.scrollTop != bodyScrollTop)
(SCROLL_ROOT = document.body);
else
(SCROLL_ROOT = document.documentElement);
window.scrollBy(0, -1);
document.body.removeChild(dummy);
}
return SCROLL_ROOT;
};
})();
/***********************************************
* PULSE (by Michael Herf)
***********************************************/
/**
* Viscous fluid with a pulse for part and decay for the rest.
* - Applies a fixed force over an interval (a damped acceleration), and
* - Lets the exponential bleed away the velocity over a longer interval
* - Michael Herf, http://stereopsis.com/stopping/
*/
function pulse_(x) {
var val, start, expx;
// test
x = x * options.pulseScale;
if (x < 1) { // acceleartion
val = x - (1 - Math.exp(-x));
} else { // tail
// the previous animation ended here:
start = Math.exp(-1);
// simple viscous drag
x -= 1;
expx = 1 - Math.exp(-x);
val = start + (expx * (1 - start));
}
return val * options.pulseNormalize;
}
function pulse(x) {
if (x >= 1) return 1;
if (x <= 0) return 0;
if (options.pulseNormalize == 1) {
options.pulseNormalize /= pulse_(1);
}
return pulse_(x);
}
var wheelEvent;
if ('onwheel' in document.createElement('div'))
wheelEvent = 'wheel';
else if ('onmousewheel' in document.createElement('div'))
wheelEvent = 'mousewheel';
if (wheelEvent) {
addEvent(wheelEvent, wheel);
addEvent('mousedown', mousedown);
addEvent('load', init);
}
})();
|
'use strict';
const assert = require('assert');
const jsesc = require('../jsesc.js');
describe('common usage', function() {
it('works correctly for common operations', function() {
assert.equal(
typeof jsesc.version,
'string',
'`jsesc.version` must be a string'
);
assert.equal(
jsesc('\0\x31'),
'\\x001',
'`\\0` followed by `1`'
);
assert.equal(
jsesc('\0\x38'),
'\\x008',
'`\\0` followed by `8`'
);
assert.equal(
jsesc('\0\x39'),
'\\x009',
'`\\0` followed by `9`'
);
assert.equal(
jsesc('\0a'),
'\\0a',
'`\\0` followed by `a`'
);
assert.equal(
jsesc('foo"bar\'baz', {
'quotes': 'LOLWAT' // invalid setting
}),
'foo"bar\\\'baz',
'Invalid `quotes` setting'
);
assert.equal(
jsesc('foo${1+1} `bar`', {
'quotes': 'backtick'
}),
'foo\\${1+1} \\`bar\\`',
'`quotes: \'backtick\'`'
);
assert.equal(
jsesc('foo${1+1} `bar`', {
'quotes': 'backtick',
'wrap': true
}),
'`foo\\${1+1} \\`bar\\``',
'`quotes: \'backtick\'` + `wrap: true`'
);
assert.equal(
jsesc('foo${1+1}</script>', {
'quotes': 'backtick',
'wrap': true,
'isScriptContext': true
}),
'`foo\\${1+1}<\\/script>`',
'`quotes: \'backtick\'` + `wrap: true` + `isScriptContext: true`'
);
assert.equal(
jsesc('\\x00'),
'\\\\x00',
'`\\\\x00` shouldn’t be changed to `\\\\0`'
);
assert.equal(
jsesc('a\\x00'),
'a\\\\x00',
'`a\\\\x00` shouldn’t be changed to `\\\\0`'
);
assert.equal(
jsesc('\\\x00'),
'\\\\\\0',
'`\\\\\\x00` should be changed to `\\\\\\0`'
);
assert.equal(
jsesc('\\\\x00'),
'\\\\\\\\x00',
'`\\\\\\\\x00` shouldn’t be changed to `\\\\\\\\0`'
);
assert.equal(
jsesc('lolwat"foo\'bar', {
'escapeEverything': true
}),
'\\x6C\\x6F\\x6C\\x77\\x61\\x74\\"\\x66\\x6F\\x6F\\\'\\x62\\x61\\x72',
'escapeEverything'
);
assert.equal(
jsesc('\0foo\u2029bar\nbaz\xA9qux\uD834\uDF06flops\uD834_\uDF06_\uDF06\uD834\xA0\u2000', {
'minimal': true
}),
'\\0foo\\u2029bar\\nbaz\xA9qux\uD834\uDF06flops\\uD834_\\uDF06_\\uDF06\\uD834\\xA0\\u2000',
'minimal'
);
assert.equal(
jsesc('foo</script>bar</style>baz</script>qux', {
'isScriptContext': true
}),
'foo<\\/script>bar<\\/style>baz<\\/script>qux',
'isScriptContext'
);
assert.equal(
jsesc('foo</sCrIpT>bar</STYLE>baz</SCRIPT>qux', {
'isScriptContext': true
}),
'foo<\\/sCrIpT>bar<\\/STYLE>baz<\\/SCRIPT>qux',
'isScriptContext'
);
assert.equal(
jsesc('"<!--<script></script>";alert(1);', {
'isScriptContext': true
}),
'"\\x3C!--<script><\\/script>";alert(1);',
'isScriptContext'
);
assert.equal(
jsesc('"<!--<script></script>";alert(1);', {
'isScriptContext': true,
'json': true
}),
'"\\"\\u003C!--<script><\\/script>\\";alert(1);"',
'isScriptContext'
);
assert.equal(
jsesc([0x42, 0x1337], {
'numbers': 'decimal'
}),
'[66,4919]',
'`numbers: \'decimal\'` (default)'
);
assert.equal(
jsesc([0x42, 0x1337], {
'numbers': 'binary'
}),
'[0b1000010,0b1001100110111]',
'`numbers: \'binary\'`'
);
assert.equal(
jsesc([0x42, 0x1337, NaN, Infinity], {
'numbers': 'binary',
'json': true
}),
'[66,4919,null,null]',
'`json: true` takes precedence over `numbers: \'binary\'`'
);
assert.equal(
jsesc([0x42, 0x1337], {
'numbers': 'octal'
}),
'[0o102,0o11467]',
'`numbers: \'octal\'`'
);
assert.equal(
jsesc([0x42, 0x1337], {
'numbers': 'hexadecimal'
}),
'[0x42,0x1337]',
'`numbers: \'hexadecimal\'`'
);
assert.equal(
jsesc('a\uD834\uDF06b', {
'es6': true
}),
'a\\u{1D306}b',
'es6'
);
assert.equal(
jsesc('a\uD834\uDF06b\uD83D\uDCA9c', {
'es6': true
}),
'a\\u{1D306}b\\u{1F4A9}c',
'es6'
);
assert.equal(
jsesc('a\uD834\uDF06b\uD83D\uDCA9c', {
'es6': true,
'escapeEverything': true
}),
'\\x61\\u{1D306}\\x62\\u{1F4A9}\\x63',
'es6 + escapeEverything'
);
assert.equal(
jsesc({}, {
'compact': true
}),
'{}',
'Stringifying an empty object with `compact: true`'
);
assert.equal(
jsesc({}, {
'compact': false
}),
'{}',
'Stringifying an empty object with `compact: false`'
);
assert.equal(
jsesc([], {
'compact': true
}),
'[]',
'Stringifying an empty array with `compact: true`'
);
assert.equal(
jsesc([], {
'compact': false
}),
'[]',
'Stringifying an empty array with `compact: false`'
);
// Stringifying flat objects containing only string values
assert.equal(
jsesc({ 'foo\x00bar\uFFFDbaz': 'foo\x00bar\uFFFDbaz' }),
'{\'foo\\0bar\\uFFFDbaz\':\'foo\\0bar\\uFFFDbaz\'}',
'Stringifying a flat object with default settings`'
);
assert.equal(
jsesc({ 'foo\x00bar\uFFFDbaz': 'foo\x00bar\uFFFDbaz' }, {
'quotes': 'double'
}),
'{"foo\\0bar\\uFFFDbaz":"foo\\0bar\\uFFFDbaz"}',
'Stringifying a flat object with `quotes: \'double\'`'
);
assert.equal(
jsesc({ 'foo\x00bar\uFFFDbaz': 'foo\x00bar\uFFFDbaz' }, {
'compact': false
}),
'{\n\t\'foo\\0bar\\uFFFDbaz\': \'foo\\0bar\\uFFFDbaz\'\n}',
'Stringifying a flat object with `compact: false`'
);
assert.equal(
jsesc(['a', 'b', 'c'], {
'compact': false,
'indentLevel': 1
}),
'[\n\t\t\'a\',\n\t\t\'b\',\n\t\t\'c\'\n\t]',
'`indentLevel: 1`'
);
assert.equal(
jsesc(['a', 'b', 'c'], {
'compact': false,
'indentLevel': 2
}),
'[\n\t\t\t\'a\',\n\t\t\t\'b\',\n\t\t\t\'c\'\n\t\t]',
'`indentLevel: 2`'
);
assert.equal(
jsesc({ 'foo\x00bar\uFFFDbaz': 'foo\x00bar\uFFFDbaz' }, {
'compact': false,
'indent': ' '
}),
'{\n \'foo\\0bar\\uFFFDbaz\': \'foo\\0bar\\uFFFDbaz\'\n}',
'Stringifying a flat object with `compact: false, indent: \' \'`'
);
assert.equal(
jsesc({ 'foo\x00bar\uFFFDbaz': 'foo\x00bar\uFFFDbaz' }, {
'escapeEverything': true
}),
'{\'\\x66\\x6F\\x6F\\0\\x62\\x61\\x72\\uFFFD\\x62\\x61\\x7A\':\'\\x66\\x6F\\x6F\\0\\x62\\x61\\x72\\uFFFD\\x62\\x61\\x7A\'}',
'Stringifying a flat object with `escapeEverything: true`'
);
// Stringifying flat arrays containing only string values
assert.equal(
jsesc(['foo\x00bar\uFFFDbaz', '\xA9'], {
'escapeEverything': true
}),
'[\'\\x66\\x6F\\x6F\\0\\x62\\x61\\x72\\uFFFD\\x62\\x61\\x7A\',\'\\xA9\']',
'Stringifying a flat array with `escapeEverything: true`'
);
assert.equal(
jsesc(['foo\x00bar\uFFFDbaz', '\xA9'], {
'compact': false
}),
'[\n\t\'foo\\0bar\\uFFFDbaz\',\n\t\'\\xA9\'\n]',
'Stringifying a flat array with `compact: false`'
);
assert.equal(
jsesc(
new Map([])
),
'new Map()',
'Stringifying an empty Map'
);
assert.equal(
jsesc(
new Map([
['a', 1],
['b', 2]
]),
{
'compact': true
}
),
'new Map([[\'a\',1],[\'b\',2]])',
'Stringifying a Map with `compact: true`'
);
assert.equal(
jsesc(
new Map([
['a', 1],
['b', 2]
]),
{
'compact': false
}
),
'new Map([\n\t[\'a\', 1],\n\t[\'b\', 2]\n])',
'Stringifying a Map with `compact: false`'
);
assert.equal(
jsesc(
new Map([
['a', 1],
['b', [
'a',
'nested',
'array'
]]
]),
{
'compact': false
}
),
'new Map([\n\t[\'a\', 1],\n\t[\'b\', [\n\t\t\'a\',\n\t\t\'nested\',\n\t\t\'array\'\n\t]]\n])',
'Stringifying a Map with `compact: false`'
);
assert.equal(
jsesc(
new Map([
['a', 1],
['b', new Map([
['x', 2],
['y', 3]
])]
]),
{
'compact': false
}
),
'new Map([\n\t[\'a\', 1],\n\t[\'b\', new Map([\n\t\t[\'x\', 2],\n\t\t[\'y\', 3]\n\t])]\n])',
'Stringifying a Map with `compact: false`'
);
assert.equal(
jsesc(
new Set([])
),
'new Set()',
'Stringifying an empty Set'
);
assert.equal(
jsesc(
new Set([
['a'],
'b',
{}
]),
{
'compact': true
}
),
'new Set([[\'a\'],\'b\',{}])',
'Stringifying a Set with `compact: true`'
);
assert.equal(
jsesc(
new Set([
['a'],
'b',
{}
]),
{
'compact': false
}
),
'new Set([\n\t[\n\t\t\'a\'\n\t],\n\t\'b\',\n\t{}\n])',
'Stringifying a Set with `compact: false`'
);
// Buffer
assert.equal(
jsesc(
Buffer.from([0x13, 0x37, 0x42])
),
'Buffer.from([19,55,66])',
'Stringifying a Buffer'
);
assert.equal(
jsesc(
Buffer.from([0x13, 0x37, 0x42]),
{
'compact': false
}
),
'Buffer.from([\n\t19,\n\t55,\n\t66\n])',
'Stringifying a Buffer with `compact: false`'
);
// JSON
assert.equal(
jsesc('foo\x00bar\xFF\uFFFDbaz', {
'json': true
}),
'"foo\\u0000bar\\u00FF\\uFFFDbaz"',
'JSON-stringifying a string'
);
assert.equal(
jsesc('foo\x00bar\uFFFDbaz', {
'escapeEverything': true,
'json': true
}),
'"\\u0066\\u006F\\u006F\\u0000\\u0062\\u0061\\u0072\\uFFFD\\u0062\\u0061\\u007A"',
'JSON-stringifying a string with `escapeEverything: true`'
);
assert.equal(
jsesc({ 'foo\x00bar\uFFFDbaz': 'foo\x00bar\uFFFDbaz' }, {
'escapeEverything': true,
'json': true
}),
'{"\\u0066\\u006F\\u006F\\u0000\\u0062\\u0061\\u0072\\uFFFD\\u0062\\u0061\\u007A":"\\u0066\\u006F\\u006F\\u0000\\u0062\\u0061\\u0072\\uFFFD\\u0062\\u0061\\u007A"}',
'JSON-stringifying a flat object with `escapeEverything: true`'
);
assert.equal(
jsesc(['foo\x00bar\uFFFDbaz', 'foo\x00bar\uFFFDbaz'], {
'escapeEverything': true,
'json': true
}),
'["\\u0066\\u006F\\u006F\\u0000\\u0062\\u0061\\u0072\\uFFFD\\u0062\\u0061\\u007A","\\u0066\\u006F\\u006F\\u0000\\u0062\\u0061\\u0072\\uFFFD\\u0062\\u0061\\u007A"]',
'JSON-stringifying a flat array with `escapeEverything: true`'
);
assert.equal(
jsesc('foo\x00bar', {
'json': true,
'wrap': false // override default `wrap: true` when `json` is enabled
}),
'foo\\u0000bar',
'Escaping as JSON with `wrap: false`'
);
assert.equal(
jsesc('foo "\x00" bar', {
'json': true,
'wrap': false // override default `wrap: true` when `json` is enabled
}),
'foo \\"\\u0000\\" bar',
'Escaping as JSON with `wrap: false` escapes double quotes correctly'
);
assert.equal(
jsesc('foo "\x00" bar \' qux', {
'json': true,
'quotes': 'single', // override default `quotes: 'double'` when `json` is enabled
'wrap': false // override default `wrap: true` when `json` is enabled
}),
'foo "\\u0000" bar \\\' qux',
'Escaping as JSON with `wrap: false, quotes: \'single\'`'
);
assert.equal(
jsesc('foo\uD834\uDF06bar\xA9baz', {
'json': true,
'es6': true // override default `es6: false` when `json` is enabled
}),
'"foo\\u{1D306}bar\\u00A9baz"',
'Escaping as JSON with `es6: true`'
);
const tmp = {
'shouldn\u2019t be here': 10,
'toJSON': function() {
return {
'hello': 'world',
'\uD83D\uDCA9': 'foo',
'pile': '\uD83D\uDCA9'
};
}
};
assert.equal(
jsesc(tmp, { 'json' : true }),
'{"hello":"world","\\uD83D\\uDCA9":"foo","pile":"\\uD83D\\uDCA9"}',
'`toJSON` methods are called when `json: true`'
);
assert.notEqual(
jsesc(tmp),
'{"hello":"world","\\uD83D\\uDCA9":"foo","pile":"\\uD83D\\uDCA9"}',
'`toJSON` methods are not called when `json: false`'
);
assert.equal(
jsesc(42, {
'numbers': 'hexadecimal',
'lowercaseHex': true
}),
'0x2a',
'Hexadecimal integeral literals are lowercase when `lowercaseHex: true`'
);
assert.equal(
jsesc('\u2192\xE9', {
'lowercaseHex': true
}),
'\\u2192\\xe9',
'Alphabetical hexadecimal digits are lowercase when `lowercaseHex: true`'
);
assert.equal(
jsesc('\u2192\xE9', {
'lowercaseHex': false
}),
'\\u2192\\xE9',
'Alphabetical hexadecimal digits are uppercase when `lowercaseHex: false`'
);
assert.equal(
jsesc('\u2192\xE9', {
'lowercaseHex': true,
'json': true
}),
'"\\u2192\\u00e9"',
'Alphabetical hexadecimal digits are lowercase when `lowercaseHex: false` and `json: true`'
);
assert.equal(
jsesc('\u2192\xe9', {
'lowercaseHex': false,
'json': true
}),
'"\\u2192\\u00E9"',
'Alphabetical hexadecimal digits are uppercase when `lowercaseHex: false` and `json: true`'
);
assert.equal(
jsesc('\xE7\xE7a\xE7\xE7', {
'lowercaseHex': true,
'escapeEverything': true
}),
'\\xe7\\xe7\\x61\\xe7\\xe7',
'Alphabetical hexadecimal digits are lowercase when `lowercaseHex: true` and `escapeEverything: true`'
);
assert.equal(
jsesc('\xE7\xE7a\xE7\xE7', {
'lowercaseHex': false,
'escapeEverything': true
}),
'\\xE7\\xE7\\x61\\xE7\\xE7',
'Alphabetical hexadecimal digits are uppercase when `lowercaseHex: false` and `escapeEverything: true`'
);
assert.equal(
jsesc('\u2192\xE9\uD83D\uDCA9', {
'lowercaseHex': true,
'es6': true
}),
'\\u2192\\xe9\\u{1f4a9}',
'Alphabetical hexadecimal digits are lowercase when `lowercaseHex: true` and `es6: true`'
);
assert.equal(
jsesc('\u2192\xE9\uD83D\uDCA9', {
'lowercaseHex': false,
'es6': true
}),
'\\u2192\\xE9\\u{1F4A9}',
'Alphabetical hexadecimal digits are uppercase when `lowercaseHex: false` and `es6: true`'
);
});
});
describe('advanced tests', function() {
let allSymbols = '';
// Generate strings based on code points. Trickier than it seems:
// https://mathiasbynens.be/notes/javascript-encoding
for (let codePoint = 0x000000; codePoint <= 0x10FFFF; codePoint += 0xF) {
const symbol = String.fromCodePoint(codePoint);
// ok(
// eval('\'' + jsesc(symbol) + '\'') == symbol,
// 'U+' + codePoint.toString(16).toUpperCase()
// );
allSymbols += symbol + ' ';
}
it('works correctly for advanced operations', function() {
assert.ok(
eval('\'' + jsesc(allSymbols) + '\'') == allSymbols,
'All Unicode symbols, space-separated, default quote type (single quotes)'
);
assert.ok(
eval('\'' + jsesc(allSymbols, {
'quotes': 'single'
}) + '\'') == allSymbols,
'All Unicode symbols, space-separated, single quotes'
);
assert.ok(
eval('`' + jsesc(allSymbols, {
'quotes': 'backtick'
}) + '`') == allSymbols,
'All Unicode symbols, space-separated, template literal'
);
assert.ok(
eval(jsesc(allSymbols, {
'quotes': 'single',
'wrap': true
})) == allSymbols,
'All Unicode symbols, space-separated, single quotes, auto-wrap'
);
assert.ok(
eval('"' + jsesc(allSymbols, {
'quotes': 'double'
}) + '"') == allSymbols,
'All Unicode symbols, space-separated, double quotes'
);
assert.ok(
eval(jsesc(allSymbols, {
'quotes': 'double',
'wrap': true
})) == allSymbols,
'All Unicode symbols, space-separated, double quotes, auto-wrap'
);
// Some of these depend on `JSON.parse()`, so only test them in Node
const testArray = [
undefined, Infinity, new Number(Infinity), -Infinity,
new Number(-Infinity), 0, new Number(0), -0, new Number(-0), +0,
new Number(+0), 'str', function zomg() { return 'desu'; }, null,
true, new Boolean(true), false, new Boolean(false), {
"foo": 42, "hah": [ 1, 2, 3, { "foo" : 42 } ]
}
];
assert.equal(
jsesc(testArray, {
'json': false
}),
'[undefined,Infinity,Infinity,-Infinity,-Infinity,0,0,0,0,0,0,\'str\',function zomg() { return \'desu\'; },null,true,true,false,false,{\'foo\':42,\'hah\':[1,2,3,{\'foo\':42}]}]',
'Escaping a non-flat array with all kinds of values'
);
assert.equal(
jsesc(testArray, {
'json': true
}),
'[null,null,null,null,null,0,0,0,0,0,0,"str",null,null,true,true,false,false,{"foo":42,"hah":[1,2,3,{"foo":42}]}]',
'Escaping a non-flat array with all kinds of values, with `json: true`'
);
assert.equal(
jsesc(testArray, {
'json': true,
'compact': false
}),
'[\n\tnull,\n\tnull,\n\tnull,\n\tnull,\n\tnull,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t"str",\n\tnull,\n\tnull,\n\ttrue,\n\ttrue,\n\tfalse,\n\tfalse,\n\t{\n\t\t"foo": 42,\n\t\t"hah": [\n\t\t\t1,\n\t\t\t2,\n\t\t\t3,\n\t\t\t{\n\t\t\t\t"foo": 42\n\t\t\t}\n\t\t]\n\t}\n]',
'Escaping a non-flat array with all kinds of values, with `json: true, compact: false`'
);
});
});
|
"use strict";
const Benchmark = require("benchmark");
function noop() {
// intentional no-op function
}
module.exports = function jsdomBenchmark(optionsArg) {
const options = {
...typeof optionsArg === "function" ? { fn: optionsArg } : optionsArg,
jsdomSetup: optionsArg.setup || noop,
jsdomFn: optionsArg.fn,
jsdomTeardown: optionsArg.teardown || noop
};
if (options.defer) {
// `this` refers to a Benchmark.Deferred
options.setup = "this.benchmark.jsdomSetup();";
options.fn = "this.benchmark.jsdomFn(deferred);";
options.teardown = "this.benchmark.jsdomTeardown();";
} else {
// `this` refers to a Benchmark
options.setup = "this.jsdomSetup();";
options.fn = "this.jsdomFn();";
options.teardown = "this.jsdomTeardown();";
}
return new Benchmark(options);
};
|
var searchData=
[
['news_2edox',['news.dox',['../news_8dox.html',1,'']]]
];
|
// Regular expression that matches all symbols in the Enclosed Alphanumeric Supplement block as per Unicode v10.0.0:
/\uD83C[\uDD00-\uDDFF]/;
|
import './utils/polyfills'; // Import polyfills for IE11
export AppBar from './app_bar';
export Autocomplete from './autocomplete';
export Avatar from './avatar';
export Button from './button/Button';
export IconButton from './button/IconButton';
export * from './card';
export Chip from './chip';
export Checkbox from './checkbox';
export DatePicker from './date_picker';
export Dialog from './dialog';
export Drawer from './drawer';
export Dropdown from './dropdown';
export FontIcon from './font_icon';
export Form from './form';
export Input from './input';
export { Layout, NavDrawer, Panel, Sidebar } from './layout';
export Link from './link';
export List from './list/List';
export ListItem from './list/ListItem';
export ListDivider from './list/ListDivider';
export ListCheckbox from './list/ListCheckbox';
export ListSubHeader from './list/ListSubHeader';
export Menu from './menu/Menu';
export MenuItem from './menu/MenuItem';
export MenuDivider from './menu/MenuDivider';
export IconMenu from './menu/IconMenu';
export Navigation from './navigation';
export ProgressBar from './progress_bar';
export RadioGroup from './radio/RadioGroup';
export RadioButton from './radio/RadioButton';
export Ripple from './ripple';
export Slider from './slider';
export Snackbar from './snackbar';
export Switch from './switch';
export Table from './table';
export Tabs from './tabs/Tabs';
export Tab from './tabs/Tab';
export Tooltip from './tooltip';
export TimePicker from './time_picker';
|
var logger = require('winston');
var datafile = require('../lib/munin-datafile');
exports.homepage = function(req, res){
logger.log("info","homepage rendered");
res.render('index', {
title: 'Goaf Munin Comparison',
lead: 'Compare Munin graphs interactively!'
});
}
exports.graph = function(req, res){
logger.log("info","graph rendered");
res.render('graph', {
nav: {compare: 1},
title: 'Compare'
});
}
|
import './_Background';
import React, { Component } from 'react';
class Background extends Component {
render() {
return (
<div className="background">
</div>
);
}
};
export default Background;
|
export default {
schedule: "Programar una reunión",
prompt: "Autorice a RingCentral a acceder a la información de cuenta.",
saveAsDefault: "Guardar como predeterminado",
launchMeeting: "Iniciar reunión"
};
// @key: @#@"schedule"@#@ @source: @#@"Schedule Meeting"@#@
// @key: @#@"prompt"@#@ @source: @#@"Please authorize RingCentral to access your account information."@#@
// @key: @#@"saveAsDefault"@#@ @source: @#@"Save as default"@#@
// @key: @#@"launchMeeting"@#@ @source: @#@"Launch Meeting"@#@
|
/** @requires BEM */
/** @requires BEM */
(function() {
BEM.DOM.decl('i-menu', {
onElemSetMod : {
'item' : {
'state': {
'current' : function(elem, modName, modVal, oldModVal) {
if (oldModVal == 'disabled') return false;
var prev = this.elem('item', 'state', 'current');
this
.delMod(prev, 'state')
.trigger('current', {
prev : prev,
current : elem
});
}
}
}
},
onItemSelectorClick : function(e) {
var item = this._getItemByEvent(e);
this.setMod(item, 'state', 'current');
},
_getItemByEvent : function(e) {
return e.data.domElem.closest(this.buildSelector('item'));
}
}, {
live : function() {
this.liveBindTo('item-selector', 'leftclick', function(e) {
this.onItemSelectorClick(e);
});
}
});
})();
|
var mqtt = require('mqtt');
var configuration = require('../configuration').mqtt;
function MqttWrapper (mqttClient) {
this._mqttClient = mqttClient || null;
}
MqttWrapper.prototype.publishTransactionValue = function (value) {
if (this._mqttClient === null) {
return;
}
this._mqttClient.publish(configuration.topics.transactionValue, '' + value);
};
module.exports = MqttWrapper;
|
// 1 - Object literal
/*
var fact = {
name: 'Chuck',
rules: 'Noooo!!',
sayToNay: function ()
{
return 'Nay, ' + fact.name + ' rules? ' + fact.rules;
}
};
console.log(fact.name);
console.log(fact.rules);
console.log(fact.sayToNay());
console.log(typeof (fact));
console.log(fact.constructor);
*/
// 2 - Object constructor
/*
var fact = new Object();
fact.name = 'Chuck';
fact.rules = 'Noooo!!';
fact.sayToNay = function() {
return 'Nay, ' + fact.name + ' rules? ' + fact.rules;
};
console.log(fact.name);
console.log(fact.rules);
console.log(fact.sayToNay());
console.log(typeof (fact));
console.log(fact.constructor);
*/
// 3 - Custom constructor
/*
var Movie = function MovieCtr (title, year) {
this.title = title;
this.year = year;
this.summary = function() {
return "The amazing film " + this.title + ' was made in the ' + this.year;
};
};
var clerks = new Movie('clerks', 1994);
console.log(clerks.summary());
var amelie = new Movie('amelie', 2001);
console.log(amelie.summary());
console.log(typeof (clerks));
console.log(clerks.constructor.name);
*/
|
var React = require('react');
/* React组件名:
* Ineo, 我即是唯一
*/
var util = require('../util');
var Ineo = React.createClass({
getInitialState: function() {
return {
content: '',
inputH: '1.5em'
};
},
componentDidMount: function(){
this.input = this.refs['ineo-input'].getDOMNode();
this.sizeGen = this.refs['size-gen'].getDOMNode();
},
componentWillReceiveProps: function(nextProps) {
if(nextProps.manualFocus){
this.input.focus();
}
},
// 高度重新计算.. 逻辑很复杂啊...
componentDidUpdate: function(prevProps, prevState) {
var nowELD = this.props.editLineData, prevELD = prevProps.editLineData;
// 内容不一样时, 尝试更新高度
if( nowELD ){
// editline前后两次不是同一行时 定位鼠标
if( prevELD ){
if( nowELD.id !== prevELD.id ){
this.input.setSelectionRange(nowELD.cursor, nowELD.cursor);
}
}
// 现在edit以前不是edit 要定位
else{
this.input.setSelectionRange(nowELD.cursor, nowELD.cursor);
}
// 只要是新编辑行 就要重新计算高度
this.updateHeight();
return;
}
else{
// 现在没 以前在 也要重新计算
if(prevELD){
this.updateHeight();
return;
}
}
// 前后两次编写的内容有变更 计算
if(this.state.content !== prevState.content ){
this.updateHeight();
}
},
render: function(){
var styleObj = {
height: this.state.inputH
};
var editLineData = this.props.editLineData;
var content = this.state.content||(editLineData? editLineData.raw:'');
var extraClass = editLineData?editLineData.tag:'';
// console.log('render...');
return (
<div className="ineo" style={this.props.style} onClick={this._onClick}>
<textarea
className={"ineo-input "+extraClass}
ref="ineo-input"
style={styleObj}
onKeyDown={this._onKeyDown}
onPaste={this._onPaste}
onChange={this._onChange}
value={content}
>
</textarea>
<div
className={"size-gen "+extraClass}
ref="size-gen"
dangerouslySetInnerHTML={{__html: content.replace(/\ \ /g, ' ')}}
>
</div>
</div>
);
},
_onClick: function(e){
e.stopPropagation();
},
// 同步内容, 控制高度
_onChange: function(e){
// console.time('a change');
var stateObj = {
content: e.target.value
};
this.setState(stateObj);
},
// 监控回车, 删除等键
_onKeyDown: function(e){
if(e.keyCode === 13){
e.preventDefault();
var res = this.props.submitHandler(this.state.content);
// 控制缩进
if(res.tag == 'code-block'){
this.setState({
content: ' '
});
}
else{
this.setState({
content: ''
});
}
return;
}
if(e.keyCode === 8){
// 退格键
}
},
// 粘贴时, 获取内容, 插入在鼠标指针处
_onPaste: function(e){
// 注意 preventDefault 之后, cmd+z就不能回退了... 好麻烦
e.preventDefault();
var self = this;
var pasteData = e.clipboardData;
if(pasteData.files.length > 0){
}
else{
var itemArr = [].slice.call(pasteData.items, 0);
var types = pasteData.types;
itemArr.forEach(function(item, i){
// 只处理文本. 其他text/html之类的就略过了
if(types[i] === 'text/plain'){
item.getAsString(function(data){
self.insertText(data);
});
}
});
}
},
// 将文本插入到鼠标指针/划选区域内, 并定位鼠标指针到插入的尾部
insertText: function(text){
var nowContent = this.state.content;
// 输入框中的selection比较特殊, 不能用window.getSelection获得
var selStart = this.input.selectionStart;
var selEnd = this.input.selectionEnd;
var arr = nowContent.split('');
arr.splice(selStart, selEnd - selStart, text);
var newContent = arr.join('');
this.setState({
content: newContent
});
// 定位鼠标指针
var cursorPos = selStart + text.length;
this.input.setSelectionRange(cursorPos, cursorPos);
},
updateHeight: function(){
var h = util.getStyleValue( window.getComputedStyle(this.sizeGen).height );
// console.log('got H', h);
// console.log('old H', this.state.inputH);
if(h !== this.state.inputH){
this.setState({
inputH: h
});
}
}
});
module.exports = Ineo;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.