text
stringlengths 2
6.14k
|
|---|
var request = require('request')
, qs = require('querystring');
var Uber = require('../index');
var uber = new Uber({
client_id: '5tzqAQx84xIaTjUvxnN3sc86lB82JopV',
client_secret: 'S9uquJpXcXHJSI0easndrMA6yBWLmHMM_tRiSGuk',
server_token: 'Y9M_N84-YS2nHDHZL89q9qyCuRtVhaHc8yTd2QfL',
redirect_uri: 'http://localhost/callback',
name: 'nodejs uber wrapper'
});
//console.log(uber);
var parameters = {
'response_type': 'code',
'redirect_uri': 'http://localhost/callback',
'scope': 'history'
}
console.log(uber.oauth2.getAuthorizeUrl(parameters));
console.log(uber.getAuthorizeUrl(['profile', 'history']));
uber.authorization({ authorization_code: 'gEA0FX57gbF0h217gEuD7fOAwkpSmN' }, function (err, accessToken, refreshToken) {
console.log(err);
console.log(accessToken);
console.log(refreshToken);
uber.user.profile(accessToken, function (err, res) {
console.log(err);
console.log(res);
});
uber.user.activity({
access_token: accessToken
}, function (err, res) {
console.log(err);
console.log(res);
});
});
// uber.authorization({ authorization_code: 'oV1seYCKU9hJdKPQuDM1YI9cf5mR4K' }, function (err, accessToken, refreshToken) {
// console.log(accessToken);
// console.log(refreshToken);
// });
// uber.promotions.list({
// start_latitude: 3.1357,
// start_longitude: 101.6880,
// end_latitude: 3.1357,
// end_longitude: 101.6880
// }, function (err, res) {
// if (err) console.error(err);
// console.log(res);
// });
// uber.authorization({ refresh_token: 'cgFUwb4vns0eygzJGWxBIghOQvFArv' }, function (err, access_token, refresh_token) {
// console.log(err);
// console.log(access_token);
// console.log(refresh_token);
// });
//console.log(uber.defaults.base_url + '/products');
//console.log(qs.stringify({ server_token: uber.defaults.server_token, latitude: 3.1357, longitude: 101.6880 }));
// request.get({
// url: uber.defaults.base_url + '/products' + '?'
// + qs.stringify({ server_token: uber.defaults.server_token, latitude: 3.1357, longitude: 101.6880 }),
// json: true
// }, function (err, res, body) {
// console.log(err);
// //console.log(res);
// console.log(body);
// });
//console.log(uber);
// uber.products.list({ latitude: 3.1357, longitude: 101.6880 }, function (err, res) {
// if (err) console.error(err);
// console.log(res);
// });
//console.log(uber.estimates);
// uber.estimates.price({
// start_latitude: 3.1357, start_longitude: 101.6880,
// end_latitude: 3.0833, end_longitude: 101.6500 }, function (err, res) {
// if (err) console.error(err);
// console.log(res);
// });
// uber.estimates.time({ start_latitude: 3.1357, start_longitude: 101.6880 }, function (err, res) {
// if (err) console.error(err);
// console.log(res);
// });
// uber.oauth2.getOAuthAccessToken('', {'grant_type': 'code'},
// function (e, access_token, refresh_token, results) {
// console.log(e);
// console.log(access_token);
// console.log(refresh_token);
// console.log(results);
// });
|
/**
* Compiles SCSS to CSS
**/
'use strict';
var paths = require('./config.js').paths;
var gulp = require('gulp');
var sass = require('gulp-sass');
var autoprefixer = require('gulp-autoprefixer');
var runSequence = require('run-sequence');
var plumber = require('gulp-plumber');
var onError = require('./on-error.js');
// Paths
var watchPath = paths.src_styles + '/**/*.scss';
var destPath = paths.dest_styles;
gulp.task('styles', function() {
return gulp.src([watchPath])
.pipe(plumber({
errorHandler: onError
}))
.pipe(sass({
errLogToConsole: true,
includePaths: ['./bower_components']
}))
.pipe(autoprefixer())
.pipe(gulp.dest(destPath));
});
gulp.task('styles:watch', ['styles'], function() {
return gulp.watch(watchPath).on('change', function() {
runSequence('styles', 'browser-sync-reload');
});
});
|
const urlParser = require('url'),
PouchDB = require('./db'),
couch2pg = require('couch2pg');
// Removes credentials from couchdb url
// Converts http://admin:pass@localhost:5984/couch1
// to localhost:5984/couch1 -- seq source
const parseSource = url => {
const source = urlParser.parse(url);
return `${source.host}${source.path}`;
};
const replicate = (couchUrl, pgconn, opts) => {
return couch2pg.importer(
pgconn,
new PouchDB(couchUrl),
opts.docLimit,
opts.changesLimit,
parseSource(couchUrl)).importAll();
};
const migrate = (pgUrl) => {
return couch2pg.migrator(pgUrl)();
};
module.exports = {
replicate: (couchUrl, pgconn, opts) => replicate(couchUrl, pgconn, opts),
migrate: (pgUrl) => migrate(pgUrl)
};
|
import Vue from 'vue'
import Vuex from 'vuex'
import mutations from './mutations'
import actions from './action'
import getters from './getters'
Vue.use(Vuex)
const state={
count:0
}
export default new Vuex.Store({
state,
getters,
actions,
mutations
})
|
var interchange__sort__vec__dec__map__real_8f90 =
[
[ "interchange_sort_vec_dec_map_real", "interchange__sort__vec__dec__map__real_8f90.html#ga05758cbd26c20ef2766cfad904571df2", null ]
];
|
var tasks = null;
var setupTaskList = function(){
Ti.API.info("Loading setup Task List")
createAddButton();
tasks = Alloy.createCollection("task")
tasks.fetch()
loadTasks();
tasks.on('change', loadTasks);
}
var loadTasks = function(){
var data = [];
tasks.map(function(task){
var title = task.get("title");
var row = Ti.UI.createTableViewRow({title: title});
row.addEventListener('click', rowClick);
data.push(row);
});
$.task_table.setData(data);
}
var createAddButton = function(){
Ti.API.info("Creating Add Button");
var addButton = Ti.UI.createButton({
title: "Add"
});
addButton.addEventListener('click', addClick);
$.home.rightNavButton = addButton;
}
var rowClick = function(e){
openTask(tasks.at(e.index));
}
var addClick = function(e){
//alert("Ready to Add Task");
var task = Alloy.createModel("task");
tasks.push(task);
openTask(task);
}
var openTask = function(task){
var tc = Alloy.createController("task");
tc.setTask(task);
tc.getView().open({animated:true});
}
$.index.open();
|
'use strict';
exports.saveUserComplete = function(body) {
var examples = {};
if(Object.keys(examples).length > 0)
return examples[Object.keys(examples)[0]];
}
|
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var passportLocalMongoose = require("passport-local-mongoose");
var UserSchema = new Schema({
username: String,
password: String
});
UserSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model("User", UserSchema);
|
(function () {
var defaults = {
context: '/marketplace',
user: {
"isAdmin": false
},
appconfigs: [
{ "code": 'store.amp.search.result.size', "value": 10 },
{ "code": 'free.warning.content', "value": 'free text!' },
{ "code": 'store.insideOutside.behavior', "value": 'ADMIN_SELECTED' },
{ "code": 'store.allow.owner.to.edit.approved.listing', "value": 'false' },
{ "code": 'store.image.allow.upload', "value": 'true' },
{ "code": 'store.amp.search.default.timeout', "value": '3000' }
],
resetConfigDefaults: function () {
window.Marketplace = defaults;
},
defaultState: {
"id": 1,
"title": "Active",
"uuid": "a290db7b-e7b2-433a-ab95-03240c597610"
},
types :[
{
"id": 4,
"title": "type 4 wayne<\/button>",
"description" : "eat it",
"hasLaunchUrl" :true,
"hasIcons" :true,
"uuid" :"c930f384-7dc1-4b1b-98d2-b0da07ac515d",
"ozoneAware": true,
"isPermanent": false
},{
"id": 2,
"title": "App Component",
"description": "app component",
"hasLaunchUrl": true,
"hasIcons": true,
"uuid": "d9735dc0-dede-4176-81d1-2e5a5ee93344",
"ozoneAware": true,
"isPermanent": true
},{
"id": 3,
"title": "OZONE App",
"description": "OZONE app",
"hasLaunchUrl": false,
"hasIcons": false,
"uuid": "dbc6c9ea-114e-4937-aa55-d8d5848929cc",
"ozoneAware": true,
"isPermanent": true
},{
"id": 1,
"title": "Web App",
"description": "web app",
"hasLaunchUrl": true,
"hasIcons": false,
"uuid": "e03a28a2-3a47-46b3-8639-8a6407c64956",
"ozoneAware": false,
"isPermanent": false
}
],
"contactTypes":[
{
"id": 0,
"title": "primary",
"required": true
},
{
"id": 1,
"title": "secondary",
"required": false
}
]
};
window.Marketplace = defaults;
}());
|
/*
Correctly handle PNG transparency in Win IE 5.5 & 6.
http://homepage.ntlworld.com/bobosola. Updated 18-Jan-2006.
Use in <HEAD> with DEFER keyword wrapped in conditional comments:
<!--[if lt IE 7]>
<script defer type="text/javascript" src="/pngfix.js"></script>
<![endif]-->
*/
var arVersion = navigator.appVersion.split("MSIE")
var version = parseFloat(arVersion[1])
if ((version >= 5.5) && (document.body.filters))
{
for(var i=0; i<document.images.length; i++)
{
var img = document.images[i]
var imgName = img.src.toUpperCase()
if (imgName.substring(imgName.length-3, imgName.length) == "PNG")
{
var imgID = (img.id) ? "id='" + img.id + "' " : ""
var imgClass = (img.className) ? "class='" + img.className + "' " : ""
var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
var imgStyle = "display:inline-block;" + img.style.cssText
if (img.align == "left") imgStyle = "float:left;" + imgStyle
if (img.align == "right") imgStyle = "float:right;" + imgStyle
if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
var strNewHTML = "<span " + imgID + imgClass + imgTitle
+ " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
+ "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
+ "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>"
img.outerHTML = strNewHTML
i = i-1
}
}
}
|
function createVertex(posVec, _color, _size) {
_color = _color || new THREE.Color(0x222222);
_size = _size || 1;
var dotGeometry = new THREE.Geometry();
dotGeometry.vertices.push(posVec);
var dotMaterial = new THREE.PointCloudMaterial({
color: _color,
size: _size,
sizeAttenuation: true
});
return new THREE.PointCloud(dotGeometry, dotMaterial);
}
function createEdge(aVec, bVec, _color, _size) {
var edgeGeometry = new THREE.Geometry();
edgeGeometry.vertices.push(aVec);
edgeGeometry.vertices.push(bVec);
//edgeGeometry.vertices.push(new THREE.Vector3(10, 0, 0));
var edgeMaterial = new THREE.LineBasicMaterial({
color: _color,
size: _size
});
return new THREE.Line(edgeGeometry, edgeMaterial);
}
function createCube(posVec, _color, _size) {
_color = _color || new THREE.Color(0x222222);
_size = _size || 1;
var cube =
new THREE.Mesh(
new THREE.BoxGeometry(_size, _size, _size),
new THREE.MeshNormalMaterial({
color: _color
}));
console.log(posVec);
cube.position.set(posVec);
return cube;
}
function GraphRender(_name, _graph, _colorNodes, _colorEdges) {
this.colorNodes = _colorNodes || new THREE.Color(0xFFFF00);
this.colorEdges = _colorEdges || new THREE.Color(0x09ff00);
this.sizeNode = 10;
this.sizeEdge = 0.25;
this.detailedRenderNode = false;
this.obj = new THREE.Object3D();
this.obj.name = _name;
this.parseGraph(_graph);
}
GraphRender.prototype.renderVertex = function(posVec, name) {
var vertex = null
if (!this.detailedRenderNode) {
vertex = createVertex(posVec, this.colorNodes, this.sizeNode);
} else {
vertex = createCube(posVec, this.colorNodes, this.sizeNode);
}
vertex.name = name;
return vertex
};
GraphRender.prototype.parseGraph = function(_graph) {
this.graph = _graph;
this.graph.calculateStats();
// Render root in the center.
this.root = this.graph.getRoot();
this.root.obj = this.renderVertex(CENTER, this.root.name);
this.root.position = CENTER;
this.obj.add(this.root.obj);
this.edgeLength = (RADIUS - 5) / this.graph.depth;
// BFS
var nodesToVisit = [{
to: this.graph.rootId
}];
while (nodesToVisit.length > 0) {
// Get Edge
var currEdge = nodesToVisit[0];
nodesToVisit.shift();
// Get Children of TO Node.
var children = this.graph.getOutEdgesOf(currEdge.to);
if (children.length > 0) {
this.renderLevel(currEdge.to);
nodesToVisit = nodesToVisit.concat(children);
}
}
//this.obj.position.set(x, y, z);
this.obj.updateMatrix();
};
var NODE_INTERVAL = 10;
var MINIMAL_CIR_LENGTH = 100;
GraphRender.prototype.renderLevel = function(ownerId) {
var lvlInfo = this.graph._levels[ownerId];
var owner = this.graph.getNode(ownerId);
var cirLength = (NODE_INTERVAL * 2 * lvlInfo.size);
// TODO: Tune up.
if (cirLength < MINIMAL_CIR_LENGTH) {
cirLength = MINIMAL_CIR_LENGTH;
}
// FLAT circut currently. TODO: Make it 3d
var radius = cirLength / (2 * Math.PI);
var angle = (2 * Math.PI) / lvlInfo.size;
var circutVec = new THREE.Vector3(0, 0, radius);
for (var i in lvlInfo.members) {
var node = this.graph.getNode(lvlInfo.members[i]);
var position = new THREE.Vector3();
position.copy(owner.position);
// Make it different! not only up!
position.add(
(new THREE.Vector3(0, 1, 0)).multiplyScalar(this.edgeLength));
position.add(circutVec);
//console.log("Node: ", node, " pos ", position);
// Render NODE.
node.obj = this.renderVertex(position, node.name);
node.position = position;
this.obj.add(node.obj);
// Render Edge. Save?
edgeObject = createEdge(
owner.position,
node.position,
this.colorEdges,
this.sizeEdge);
// Currently edge contains target name.
edgeObject.name = node.name;
this.obj.add(edgeObject);
// Move cirVec
circutVec.applyAxisAngle(new THREE.Vector3(0, 1, 0), angle);
}
};
GraphRender.prototype.setPos = function(x, y, z) {
this.obj.position.set(x, y, z);
this.obj.updateMatrix();
};
GraphRender.prototype.initScene = function(scene) {
scene.add(this.obj);
};
|
(function($) {
var suite = Echo.Tests.Unit.compatibilityTest = function() {};
suite.prototype.info = {
"suiteName": "Compatibility tests"
};
suite.prototype.tests = {};
suite.prototype.tests.JqueryNoConflict = {
"config": {
"async": true,
"testTimeout": 20000 // 20 secs
},
"check": function() {
var testVersion = "1.4.1";
QUnit.ok(!(window.$ || window.jQuery),
"Checking if jQuery is not defined in the window namespace");
Echo.Loader.download([{"url": "https://ajax.googleapis.com/ajax/libs/jquery/" + testVersion + "/jquery.min.js"}], function () {
QUnit.ok(window.$.fn.jquery === testVersion && $.fn.jquery !== window.$.fn.jquery, "Checking if Echo jQuery lib wasn't overridden after another jQuery version inclusion into the page");
Echo.Loader.download([{"url": "third-party/jquery.pack.js"}], function () {
QUnit.ok(window.$.fn.jquery === testVersion && $.fn.jquery !== window.$.fn.jquery, "Checking if the native jQuery lib on the page is not overridden after Echo jQuery inclusion");
window.jQuery.noConflict(true);
QUnit.start();
});
});
}
};
suite.prototype.tests.V2V3CompatibilityCheck = {
"config": {
"async": true,
"testTimeout": 20000 // 20 secs
},
"check": function() {
var self = this;
var ids = {
"v2": "echo-apps-v2",
"v3": "echo-apps-v3"
};
var Stack = function(callback) {
var counter = 0;
var state = {};
this.init = function(id) {
if( !state.hasOwnProperty(id) ) {
state[id] = false;
counter++;
}
};
this.done = function(id) {
if (state[id] === false) {
state[id] = true;
--counter == 0 && callback();
}
}
};
Echo.Variables.V2V3Test = new Stack(function() {
var res = !$.map(window[ids.v3].Echo, function(val, key) {
return window[ids.v2].Echo[key];
}).length;
QUnit.ok(res, "Check if v3 Echo keys don't match with v2 Echo keys");
QUnit.start();
});
$.each(ids, function(key, val) {
self.config.target.append('<iframe src="unit/compatibility/' + key + '.html" name="' + val + '"></iframe>');
});
}
};
suite.prototype.tests.YepnopeNoConflict = {
"config": {
"async": true,
"testTimeout": 20000 // 20 secs
},
"check": function() {
var origYepnope = window.yepnope;
QUnit.ok(!!Echo.yepnope, "Check if Echo's yepnope is loaded");
Echo.Loader.download([{"url": "https://cdnjs.cloudflare.com/ajax/libs/yepnope/1.5.4/yepnope.min.js"}], function () {
var globalYepnope = window.yepnope;
QUnit.ok(!!window.yepnope, "Check if global yepnope has been loaded");
QUnit.ok(Echo.yepnope !== window.yepnope,
"Check if global yepnope and Echo's yepnope are different objects");
Echo.Loader.download([{"url": "loader.js"}], function () {
QUnit.ok(globalYepnope === window.yepnope,
"Check if global yepnope is not overwritten after Echo's yepnope has been loaded");
window.yepnope = origYepnope;
QUnit.start();
});
});
}
};
})(Echo.jQuery);
|
runset.clear();
var path = "C:/VWorks Workspace/Protocol Files/facility/truseq_pcr-free/";
var form = "truseq_pcr-free.VWForm";
run("C:/VWorks Workspace/Protocol Files/facility/resources/clear_inventory.bat", true);
var runsetMode = false; // Alt settings for library prep runset (true/false)
formColumns = parseInt(formColumns, 10);
var altBeadPlate = true;
var presets = {};
presets["End repair"] = {
tipColumn:1,reagentColumn:1,
sampleVolume:50,
reagentVolume:50,
incubationTemperature:30,
incubationTime:1800,
doOffDeckIncubation:true
};
presets["A-tailing"] = {
tipColumn:2,
reagentColumn:2,
sampleVolume:15,
reagentVolume:15,
incubationTemperature:37,
incubationTime:1800,
doOffDeckIncubation:true
};
presets["Ligation"] = {
tipColumn:3,
reagentColumn:3,
sampleVolume:30,
reagentVolume:5,
bufferVolume:5,
adapterVolume:2.5,
incubationTemperature:30,
incubationTime:600,
doOffDeckIncubation:true
};
presets["Fragmentation cleanup"] = {
sampleVolume:50,
beadVolume:80,
elutionVolume:50
};
presets["Size selection 350 bp"] = {
sampleVolume:100,
beadVolume1:95,
beadVolume2:30,
bindVolume:160,
transferVolume:250,
elutionVolume:15
};
presets["Size selection 550 bp"] = {
sampleVolume:100,
beadVolume1:80,
beadVolume2:30,
bindVolume:160,
transferVolume:250,
elutionVolume:15
};
presets["Ligation cleanup 1"] = {
sampleVolume:42.5,
beadVolume:42.5,
elutionVolume:50
};
presets["Ligation cleanup 2"] = {
sampleVolume:50,
beadVolume:50,
elutionVolume:20
};
presets["qPCR setup"] = {};
var settings = {};
var fileNames = {};
fileNames["End repair"] = "truseq_pcr-free_reaction.pro";
fileNames["A-tailing"] = "truseq_pcr-free_reaction.pro";
fileNames["Ligation"] = "truseq_pcr-free_ligation.pro";
fileNames["Fragmentation cleanup"] = "illumina_spri.pro";
fileNames["Size selection 350 bp"] = "illumina_double-spri.pro";
fileNames["Size selection 550 bp"] = "illumina_double-spri.pro";
fileNames["Ligation cleanup 1"] = "illumina_spri.pro";
fileNames["Ligation cleanup 2"] = "illumina_spri.pro";
fileNames["Library prep"] = "truseq_pcr-free.rst";
fileNames["Ligation cleanup"] = "truseq_pcr-free_cleanup.rst";
fileNames["qPCR setup"] = "../qpcr-384/qpcr-384_setup_ver4.pro";
var runsetOrder = [];
if(formProtocol === "Library prep") {
runsetMode = true;
runsetOrder = ["End repair","Size selection "+formInsertSize,
"A-tailing","Ligation","Ligation cleanup 1","Ligation cleanup 2"];
runset.openRunsetFile(path+fileNames[formProtocol], form);
} else if(formProtocol === "Size selection") {
runsetMode = false;
runset.appendProtocolFileToRunset(path+fileNames[formProtocol+" "+formInsertSize], 1, "", form);
updateSettings(formProtocol+" "+formInsertSize);
} else if(formProtocol === "Ligation cleanup") {
runsetMode = true;
runsetOrder = ["Ligation cleanup 1","Ligation cleanup 2"];
runset.openRunsetFile(path+fileNames[formProtocol], form);
} else {
runsetMode = false;
runset.appendProtocolFileToRunset(path+fileNames[formProtocol], 1, "", form);
updateSettings(formProtocol);
}
function updateSettings(protocol) {
settings = {};
if(protocol in presets) {
for(var s in presets[protocol]) {
settings[s] = presets[protocol][s];
}
} else {
throw "EXCEPTION__UndefinedSetting:"+protocol;
}
print(protocol + " preset loaded");
}
var runsetIndex = 0;
function updateRunset() {
updateSettings(runsetOrder[runsetIndex++]);
}
function dph(vol) {
var v = parseFloat(vol);
if(v > 0 && !isNaN(v)) {
return (0.08*v + 0.2) / v;
} else {
throw "ValueException";
}
}
|
/*!
* ${copyright}
*/
/**
* @fileOverview Application component to test bindings using OData types.
* @version @version@
*/
sap.ui.define([
'jquery.sap.global',
'sap/m/FlexItemData',
'sap/m/HBox',
'sap/m/MessageBox',
'sap/ui/core/mvc/View', // sap.ui.view()
'sap/ui/core/mvc/ViewType',
'sap/ui/core/sample/common/Component',
'sap/ui/model/BindingMode',
'sap/ui/model/json/JSONModel',
'sap/ui/model/odata/AnnotationHelper',
'sap/ui/model/odata/v2/ODataModel',
'sap/ui/model/odata/v4/ODataModel',
'sap/ui/test/TestUtils',
'jquery.sap.script'
], function(jQuery, FlexItemData, HBox, MessageBox, View, ViewType, BaseComponent, BindingMode,
JSONModel, AnnotationHelper, ODataModelV2, ODataModelV4, TestUtils /*, jQuerySapScript*/) {
"use strict";
return BaseComponent.extend("sap.ui.core.sample.ViewTemplate.types.Component", {
metadata : "json",
createContent : function () {
var oModelV2,
oModelV4,
bRealOData = TestUtils.isRealOData(),
oRootView,
sUriV2 = "/sap/opu/odata/sap/ZUI5_EDM_TYPES/",
sUriV4 = "/sap/opu/odata4/sap/zui5_testv4/default/sap/zui5_edm_types_v4/0001/",
mViews = {
"false" : null, // V2 templating view
"true" : null // V4 templating view
},
onError = function (oError) {
MessageBox.alert(oError.message, {
icon : MessageBox.Icon.ERROR,
title : "Error"});
};
if (bRealOData) {
sUriV2 = this.proxy(sUriV2);
sUriV4 = this.proxy(sUriV4);
} else {
TestUtils.useFakeServer(this.oSandbox,
"sap/ui/core/sample/ViewTemplate/types/data", {
"/sap/opu/odata/sap/ZUI5_EDM_TYPES/$metadata" : {
source : "metadataV2.xml"
},
"/sap/opu/odata/sap/ZUI5_EDM_TYPES/EdmTypesCollection(ID='1')" : {
source : "EdmTypesV2.json"
},
"/sap/opu/odata4/sap/zui5_testv4/default/sap/zui5_edm_types_v4/0001/$metadata" : {
source : "metadataV4.xml"
},
"/sap/opu/odata4/sap/zui5_testv4/default/sap/zui5_edm_types_v4/0001/EdmTypesCollection(ID='1')" : {
source : "EdmTypesV4.json"
}
});
}
oModelV2 = new ODataModelV2({
annotationURI : sap.ui.require.toUrl("sap/ui/core/sample/ViewTemplate/types/data/annotationsV2.xml"),
defaultBindingMode : BindingMode.TwoWay,
serviceUrl : sUriV2,
useBatch : bRealOData
});
oModelV4 = new ODataModelV4({
serviceUrl : sUriV4,
synchronizationMode : "None",
updateGroupId : "EDMTypes"
});
oModelV2.getMetaModel().loaded().then(function () {
var oMetaModel = oModelV2.getMetaModel(),
oView = sap.ui.view({
preprocessors : {
xml : {
bindingContexts : {meta : oMetaModel.createBindingContext(
"/dataServices/schema/0/entityType/0")
},
models : {meta : oMetaModel}
}
},
type : ViewType.XML,
viewName : "sap.ui.core.sample.ViewTemplate.types.TemplateV2"
});
oView.setLayoutData(new FlexItemData({growFactor : 1.0, baseSize : "0%"}));
oRootView.byId("identificationBox").addItem(oView);
mViews["false"] = oView;
}, onError);
oModelV4.getMetaModel()
.requestObject("/com.sap.gateway.default.zui5_edm_types_v4.v0001.EdmTypes")
.then(function () {
var oMetaModel = oModelV4.getMetaModel(),
oView = sap.ui.view({
preprocessors : {
xml : {
bindingContexts : {meta : oMetaModel.createBindingContext(
"/com.sap.gateway.default.zui5_edm_types_v4.v0001.EdmTypes")
},
models : {meta : oMetaModel}
}
},
type : ViewType.XML,
viewName : "sap.ui.core.sample.ViewTemplate.types.TemplateV4"
});
oView.setLayoutData(new FlexItemData({growFactor : 1.0, baseSize : "0%"}));
mViews["true"] = oView;
}, onError);
oRootView = sap.ui.view({
models : {
undefined : oModelV2,
ui : new JSONModel({
codeVisible : false,
realOData : bRealOData,
v2 : true,
v4 : false
}),
v2 : oModelV2,
v4 : oModelV4
},
type : ViewType.XML,
viewData : mViews,
viewName : "sap.ui.core.sample.ViewTemplate.types.Types"
});
return oRootView;
}
});
});
|
var layout = require("layout");
var rss = require("rss");
var win = layout.init();
var picker = layout.pickerMenu(win);
picker.addEventListener("change", function(e){
switch(e.row.title){
case "Pagina12":
rss.fetch("pagina12", win);
break;
case "Clarin":
rss.fetch("clarin", win);
break;
}
});
rss.fetch("clarin", win);
|
/**
* Copyright 2019 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const express = require('express');
const request = require('request');
const app = express();
const dialogflowSessionClient =
require('../botlib/dialogflow_session_client.js');
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
//For authenticating dialogflow_session_client.js, create a Service Account and
// download its key file. Set the environmental variable
// GOOGLE_APPLICATION_CREDENTIALS to the key file's location.
//See https://dialogflow.com/docs/reference/v2-auth-setup and
// https://cloud.google.com/dialogflow/docs/setup for details.
const projectId = 'Place your dialogflow projectId here';
const phoneNumber = "Place your twilio phone number here";
const accountSid = 'Place your accountSid here';
const authToken = 'Place your authToken here';
const client = require('twilio')(accountSid, authToken);
const MessagingResponse = require('twilio').twiml.MessagingResponse;
const sessionClient = new dialogflowSessionClient(projectId);
const listener = app.listen(process.env.PORT, function() {
console.log('Your Twilio integration server is listening on port '
+ listener.address().port);
});
app.post('/', async function(req, res) {
const body = req.body;
const text = body.Body;
const id = body.From;
const dialogflowResponse = (await sessionClient.detectIntent(
text, id, body)).fulfillmentText;
const twiml = new MessagingResponse();
const message = twiml.message(dialogflowResponse);
res.send(twiml.toString());
});
process.on('SIGTERM', () => {
listener.close(() => {
console.log('Closing http server.');
process.exit(0);
});
});
|
define(["backbone", "organization"], function(Backbone, Organization) {
var Organizations = Backbone.Collection.extend({
model: Organization,
initialize : function(data){
for(var i =0; i< data.length; i++){
var o = new Organization(data[i]);
this.add(o);
}
}
});
return Organizations;
});
|
/**
* @copyright Copyright (c) 2019 Maxim Khorin <maksimovichu@gmail.com>
*/
'use strict';
const {expect} = require('chai');
const CommonHelper = require('../../../helper/CommonHelper');
describe('CommonHelper', ()=> {
it('isEmpty', ()=> {
expect(CommonHelper.isEmpty(null)).to.eql(true);
expect(CommonHelper.isEmpty(undefined)).to.eql(true);
expect(CommonHelper.isEmpty('')).to.eql(true);
expect(CommonHelper.isEmpty(0)).to.eql(false);
expect(CommonHelper.isEmpty([])).to.eql(false);
expect(CommonHelper.isEmpty('test')).to.eql(false);
});
it('isEqual', ()=> {
expect(CommonHelper.isEqual(2, 2)).to.eql(true);
expect(CommonHelper.isEqual('2', 2)).to.eql(false);
expect(CommonHelper.isEqual([1, 2, 3], [1, 2, 3])).to.eql(true);
expect(CommonHelper.isEqual([3, 2, 1], [1, 2, 3])).to.eql(false);
expect(CommonHelper.isEqual({k: 1, m: 2}, {k: 1, m: 2})).to.eql(true);
expect(CommonHelper.isEqual({m: 2, k: 1}, {k: 1, m: 2})).to.eql(false);
});
it('defineConstantProperty', ()=> {
const res = {};
CommonHelper.defineConstantProperty(res, 'test', 1);
expect(res.test).to.eql(1);
expect(Object.values(res)).to.eql([1]);
try { res.test = 2; } catch {}
expect(res.test).to.eql(1);
try { delete res.test; } catch {}
expect(res.test).to.eql(1);
});
it('parseJson', ()=> {
const res = CommonHelper.parseJson(JSON.stringify({a: 5}));
expect(res.a).to.eql(5);
expect(CommonHelper.parseJson('non-json')).to.eql(undefined);
});
});
|
/*************************************************************
*
* MathJax/localization/lt/FontWarnings.js
*
* Copyright (c) 2009-2017 The MathJax Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
MathJax.Localization.addTranslation("lt","FontWarnings",{
version: "2.7.2-beta.0",
isLoaded: true,
strings: {
webFont: "Matematikos \u017Eenklams rodyti \u201EMathJax\u201C \u0161iame tinklalapyje vartoja tinkle saugomus \u0161riftus, kuri\u0173 \u012Fk\u0117limas reikalauja laiko. \u017Denkl\u0173 rinkim\u0105 galima greitinti, matematikos \u0161riftus \u012Fdiegus vietiniame sistemos \u0161rift\u0173 aplanke.",
imageFonts: "\u201EMathJax\u201C vartoja paveikslinius, o ne vietinius arba tinkle saugomus \u0161riftus. Matematikos \u017Eenklai vaizduojami l\u0117\u010Diau, o spausdinant netenkama rai\u0161kos.",
noFonts: "Matematikos \u017Eenklams rodyti \u201EMathJax\u201C nepavyksta rasti \u0161rifto arba paveikslini\u0173 \u0161rift\u0173, tod\u0117l vartojami bendrieji unikodo ra\u0161menys, tikintis, kad nar\u0161ykl\u0117 juos rodys taisyklingai. Kai kurie \u017Eenklai gali b\u016Bti rodomi i\u0161darkyti arba visai nerodomi.",
webFonts: "Dauguma dabartini\u0173 nar\u0161ykli\u0173 leid\u017Eia gauti \u0161riftus i\u0161 tinklo. Tik\u0117tina, kad atnaujinus nar\u0161ykl\u0117s laid\u0105 arba esam\u0105 nar\u0161ykl\u0119 pakeitus kita, tinklalapyje ger\u0117t\u0173 matematikos \u017Eenkl\u0173 vaizdavimas.",
fonts: "\u201EMathJax\u201C gali vartoti [STIX fonts](%1) arba [MathJax TeX fonts](%2). \u012Ediegus vien\u0105 i\u0161 min\u0117t\u0173 alternatyv\u0173, ger\u0117s \u201EMathJax\u201C veikimas.",
STIXPage: "Tinklalapyje numatyti [STIX fonts](%1). \u012Ediegus min\u0117tus \u0161riftus, ger\u0117s \u201EMathJax\u201C veikimas.",
TeXPage: "Tinklalapyje numatyti [MathJax TeX fonts](%1). \u012Ediegus min\u0117tus \u0161riftus, ger\u0117s \u201EMathJax\u201C veikimas."
}
});
MathJax.Ajax.loadComplete("[MathJax]/localization/lt/FontWarnings.js");
|
/**
* FILE: StableL1Shape.js
* PERCORSO /Codice/sgad/clienttier/view/graphicobjects/components/worldcomponentshape/StableL1Shape.js
* DATA CREAZIONE: 19 Febbraio 2014
* AUTORE: ProTech
* EMAIL: protech.unipd@gmail.com
*
* Questo file è proprietà del gruppo ProTech, viene rilasciato sotto licenza Apache v2.
*
* DIARIO DELLE MODIFICHE:
* 2014-02-19 - Creazione della classe - Battistella Stefano
*/
//Eredita da WorldComponentShapeImg.
StableL1Shape.prototype = new WorldComponentShapeImg();
//Costruttore della classe.
StableL1Shape.prototype.constructor = StableL1Shape;
/**
* Classe per la memorizzazione dell'immagine e del poligono per la rappresentazione di una stalla di livello 1.
* @extends WorldComponentShapeImg
* @constructor
*/
function StableL1Shape() {
var shape = this.shape;
shape.addPoint(new Point2D(0, 72));
shape.addPoint(new Point2D(45, 42));
shape.addPoint(new Point2D(45, 28));
shape.addPoint(new Point2D(41, 24));
shape.addPoint(new Point2D(67, 0));
shape.addPoint(new Point2D(122, 36));
shape.addPoint(new Point2D(120, 38));
shape.addPoint(new Point2D(120, 59));
shape.addPoint(new Point2D(139, 72));
shape.addPoint(new Point2D(70, 117));
this.image.src = "canvas/images/Stalla_L1.png";
}
|
'use strict';
/**
* @memberof CollaborativeMap
*
* @fileOverview Adds listeners for all leaflet specific draw events.
*
* Adds click handlers for new features (through the MapHandler).
* Edit/delete events call a Callback (further handling is done in the SynchronizeMapService)
*
* @exports CollaborativeMap.MapHandler
* @requires MapHandler
* @author Dennis Wilhelm
*/
angular.module('CollaborativeMap')
.service('MapDrawEvents', ['MapHandler',
function(MapHandler) {
var mapScope;
/**
* Creates an event object to send via Websockets
* @param {Object} event map draw event
* @param {String} type created/deleted/edited
* @return {Object} {action, feature, fid, user}
*/
function eventToMessage(event, type) {
//jshint camelcase: false
return {
'action': type,
'feature': event.layer.toGeoJSON(),
'fid': event.layer._leaflet_id,
'user': mapScope.userName
};
}
return {
/**
* Listens for leaflet draw events. Packs the events in a message and calls the callback
* @param {Object} map the map
* @param {Object} scope Angular scope
* @param {Function} callback
*/
connectMapEvents: function(map, scope, callback) {
mapScope = scope;
map.on('draw:created', function(event) {
scope.selectFeature(event.layer);
MapHandler.addClickEvent(event.layer);
callback(eventToMessage(event, event.action || 'created feature'));
});
map.on('draw:edited', function(event) {
if (event.layers && event.layers._layers) {
var layers = event.layers._layers;
for (var key in layers) {
callback(eventToMessage({
layer: layers[key]
}, 'edited geometry'));
}
}
});
//Property ofa feature edited through the toolbox
map.on('propertyEdited', function(event) {
if (event && event.layer && event.fid) {
callback({
'action': 'edited properties',
'feature': event.layer,
'fid': event.fid,
user: mapScope.userName
});
}
});
map.on('draw:deleted', function(event) {
if (event.layers && event.layers._layers) {
var layers = event.layers._layers;
for (var key in layers) {
callback(eventToMessage({
layer: layers[key]
}, 'deleted feature'));
}
}
});
}
};
}
]);
|
var dir_dc404e6d5bd6be759ffb66d8cbe1ce77 =
[
[ "ApiDocRegistrator.java", "apps_2dhcp_2app_2target_2generated-sources_2org_2onosproject_2dhcp_2rest_2ApiDocRegistrator_8java.html", [
[ "ApiDocRegistrator", "classorg_1_1onosproject_1_1dhcp_1_1rest_1_1ApiDocRegistrator.html", "classorg_1_1onosproject_1_1dhcp_1_1rest_1_1ApiDocRegistrator" ]
] ]
];
|
/// <reference path = "../../typings/index.d.ts"/>
"use strict";
var files_1 = require('../../lib/files');
describe('downloader', function () {
var fileUrlHttp = 'http://foobar.com';
var fileUrlHttps = 'https://foobar.com';
var argProxy = 'http://foobar.arg';
var envNoProxy = 'http://foobar.com';
var envHttpProxy = 'http://foobar.env';
var envHttpsProxy = 'https://foobar.env';
it('should return undefined when proxy arg is not used', function () {
var proxy = files_1.Downloader.resolveProxy_(fileUrlHttp);
expect(proxy).toBeUndefined();
});
describe('proxy arg', function () {
var opt_proxy = 'http://bar.foo';
it('should return the proxy arg', function () {
var proxy = files_1.Downloader.resolveProxy_(fileUrlHttp, opt_proxy);
expect(proxy).toBe(opt_proxy);
});
it('should always return the proxy arg with env var set', function () {
process.env.HTTP_PROXY = envHttpProxy;
process.env.HTTPS_PROXY = envHttpsProxy;
process.env.NO_PROXY = envNoProxy;
var proxy = files_1.Downloader.resolveProxy_(fileUrlHttp, opt_proxy);
expect(proxy).toBe(opt_proxy);
});
});
describe('environment varialbes', function () {
beforeEach(function () {
delete process.env.HTTP_PROXY;
delete process.env.http_proxy;
delete process.env.HTTPS_PROXY;
delete process.env.https_proxy;
delete process.env.NO_PROXY;
delete process.env.no_proxy;
});
it('should return the HTTP env variable', function () {
process.env.HTTP_PROXY = envHttpProxy;
var proxy = files_1.Downloader.resolveProxy_(fileUrlHttp);
expect(proxy).toBe(envHttpProxy);
});
it('should return the http env variable', function () {
process.env.http_proxy = envHttpProxy;
var proxy = files_1.Downloader.resolveProxy_(fileUrlHttp);
expect(proxy).toBe(envHttpProxy);
});
it('should return the HTTPS env variable for https protocol', function () {
process.env.HTTPS_PROXY = envHttpsProxy;
var proxy = files_1.Downloader.resolveProxy_(fileUrlHttps);
expect(proxy).toBe(envHttpsProxy);
});
it('should return the https env variable for https protocol', function () {
process.env.https_proxy = envHttpsProxy;
var proxy = files_1.Downloader.resolveProxy_(fileUrlHttps);
expect(proxy).toBe(envHttpsProxy);
});
it('should return the HTTP env variable for https protocol', function () {
process.env.HTTP_PROXY = envHttpProxy;
var proxy = files_1.Downloader.resolveProxy_(fileUrlHttps);
expect(proxy).toBe(envHttpProxy);
});
it('should return the https env variable for https protocol', function () {
process.env.http_proxy = envHttpProxy;
var proxy = files_1.Downloader.resolveProxy_(fileUrlHttps);
expect(proxy).toBe(envHttpProxy);
});
describe('NO_PROXY environment variable', function () {
beforeEach(function () {
delete process.env.NO_PROXY;
delete process.env.no_proxy;
});
it('should return null when the NO_PROXY matches the fileUrl', function () {
process.env.NO_PROXY = envNoProxy;
var proxy = files_1.Downloader.resolveProxy_(fileUrlHttp);
expect(proxy).toBeUndefined();
});
it('should return null when the no_proxy matches the fileUrl', function () {
process.env.no_proxy = envNoProxy;
var proxy = files_1.Downloader.resolveProxy_(fileUrlHttp);
expect(proxy).toBeUndefined();
});
});
});
});
|
import * as React from 'react';
/**
* Represents an application.
*/
export default class App extends React.Component {
/**
* Renders the component.
*
* @method render
* @returns {JSX} Component markup.
*/
render () {
return <div><img src="img/react.png" width="64" />Hello React!</div>;
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var app = {
// Application Constructor
initialize: function() {
this.bindEvents();
},
// Bind Event Listeners
//
// Bind any events that are required on startup. Common events are:
// 'load', 'deviceready', 'offline', and 'online'.
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
// deviceready Event Handler
//
// The scope of 'this' is the event. In order to call the 'receivedEvent'
// function, we must explicitly call 'app.receivedEvent(...);'
onDeviceReady: function() {
app.receivedEvent('deviceready');
},
checkConnection: function() {
var networkState = navigator.connection.type;
var states = {};
states[Connection.UNKNOWN] = 'Unknown connection';
states[Connection.ETHERNET] = 'Ethernet connection';
states[Connection.WIFI] = 'WiFi connection';
states[Connection.CELL_2G] = 'Cell 2G connection';
states[Connection.CELL_3G] = 'Cell 3G connection';
states[Connection.CELL_4G] = 'Cell 4G connection';
states[Connection.CELL] = 'Cell generic connection';
states[Connection.NONE] = 'No network connection';
alert("Connection type: " + states[networkState]);
// Test Statusbar
StatusBar.overlaysWebView(true);
StatusBar.styleDefault();
alert("StatusBar visible? " + StatusBar.isVisible);
StatusBar.hide();
alert("StatusBar now visible? " + StatusBar.isVisible);
navigator.camera.getPicture(onSuccess, onFail, { quality: 50,
destinationType: Camera.DestinationType.DATA_URL
});
function onSuccess(imageData) {
var image = document.getElementById('myImage');
image.src = "data:image/jpeg;base64," + imageData;
}
function onFail(message) {
alert('Picture Failed because: ' + message);
}
// Test File
alert("File Object " + cordova.file);
// Test File Transfer
alert("File transfer obj " + FileTransfer);
alert("Capture object " + navigator.device.capture)
// capture callback
var captureSuccess = function(mediaFiles) {
var i, path, len;
for (i = 0, len = mediaFiles.length; i < len; i += 1) {
path = mediaFiles[i].fullPath;
// do something interesting with the file
}
};
// capture error callback
var captureError = function(error) {
navigator.notification.alert('Error code: ' + error.code, null, 'Capture Error');
};
// start audio capture
navigator.device.capture.captureAudio(captureSuccess, captureError, {limit:2});
var push = PushNotification.init({ "android": {"senderID": "12345679"},
"ios": {"alert": "true", "badge": "true", "sound": "true"}, "windows": {} } );
},
// Update DOM on a Received Event
receivedEvent: function(id) {
var parentElement = document.getElementById(id);
var listeningElement = parentElement.querySelector('.listening');
var receivedElement = parentElement.querySelector('.received');
listeningElement.setAttribute('style', 'display:none;');
receivedElement.setAttribute('style', 'display:block;');
console.log('Received Event: ' + id);
alert("Device platform " + device.platform);
app.checkConnection();
}
};
app.initialize();
|
(function () {
'use strict';
angular.module('programs').run(['MenuService', function (MenuService) {
MenuService.addMenuItem ('topbar', {
title: 'Opportunities',
state: 'opportunities.list',
roles: ['*'],
icon: 'none',
position: 5
});
}]);
}());
|
export * as ready from './ready'
|
import PdvController from './pdv-controller';
import bodyParser from 'body-parser';
import logger from '../../utils/logger';
export default class PdvRoutes {
constructor (express, controller) {
this.express = express;
/* istanbul ignore next */
this._controller = !controller ? new PdvController() : controller;
}
getApp () {
var app = this.express();
app.use(bodyParser.json())
.use(bodyParser.urlencoded({ extended: true }));
app.get('/:id', (req, res) => {
logger.info('==> Routes: PDV - ID: ' + req.params.id);
this._controller.getById(req.params.id, function (result) {
try {
var status = result.pdvs.length > 0 ? 200 : (result.error ? 400 : 404);
res.status(status).json(result);
} catch (error) {
res.status(500).json(error);
}
});
});
app.post('/', (req, res) => {
logger.info('==> Routes: PDV - POST');
this._controller.createPdv(req.body, function (result) {
try {
var status = result.pdvs.length > 0 ? 201 : 400;
res.status(status).json(result);
} catch (error) {
res.status(500).json(error);
}
});
});
app.use('/', (req, res) => {
logger.info('==> Routes: PDV - LNG: ' + req.query.lng + ' LAT: ' + req.query.lat);
this._controller.getClosestPdv(req.query.lng, req.query.lat, function (result) {
try {
var status = result.pdvs.length > 0 ? 200 : (result.error ? 400 : 404);
res.status(status).json(result);
} catch (error) {
res.status(500).json(error);
}
});
});
return app;
}
}
|
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
'use strict';
function main() {
// [START bigquery_query_params_structs]
// Run a query using struct query parameters
// Import the Google Cloud client library
const {BigQuery} = require('@google-cloud/bigquery');
const bigquery = new BigQuery();
async function queryParamsStructs() {
// The SQL query to run
const sqlQuery = 'SELECT @struct_value AS struct_obj;';
const options = {
query: sqlQuery,
// Location must match that of the dataset(s) referenced in the query.
location: 'US',
params: {struct_value: {x: 1, y: 'foo'}},
};
// Run the query
const [rows] = await bigquery.query(options);
console.log('Rows:');
rows.forEach(row => console.log(row.struct_obj.y));
}
// [END bigquery_query_params_structs]
queryParamsStructs();
}
main(...process.argv.slice(2));
|
/**
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
// MODULES //
var dispatch = require( '@stdlib/strided/base/unary-addon-dispatch' );
var addon = require( './../src/addon.node' );
var js = require( './sqrt.js' );
// MAIN //
/**
* Computes the principal square root for each element in a strided array `x` and assigns the results to elements in a strided array `y`.
*
* @name sqrt
* @type {Function}
* @param {integer} N - number of indexed elements
* @param {*} dtypeX - `x` data type
* @param {Collection} x - input array
* @param {integer} strideX - `x` stride length
* @param {*} dtypeY - `y` data type
* @param {Collection} y - destination array
* @param {integer} strideY - `y` stride length
* @throws {TypeError} first argument must be an integer
* @throws {TypeError} third argument must be an array-like object
* @throws {TypeError} fourth argument must be an integer
* @throws {TypeError} sixth argument must be an array-like object
* @throws {TypeError} seventh argument must be an integer
* @throws {Error} insufficient arguments
* @throws {Error} too many arguments
* @throws {RangeError} third argument has insufficient elements based on the associated stride and the number of indexed elements
* @throws {RangeError} sixth argument has insufficient elements based on the associated stride and the number of indexed elements
* @throws {TypeError} unable to resolve a strided array function supporting the provided array argument data types
* @returns {Collection} `y`
*
* @example
* var Float64Array = require( '@stdlib/array/float64' );
*
* var x = new Float64Array( [ 0.0, 4.0, 9.0, 12.0, 24.0 ] );
* var y = new Float64Array( [ 0.0, 0.0, 0.0, 0.0, 0.0 ] );
*
* sqrt( x.length, 'float64', x, 1, 'float64', y, 1 );
* // y => <Float64Array>[ 0.0, 2.0, 3.0, ~3.464, ~4.899 ]
*/
var sqrt = dispatch( addon, js );
// EXPORTS //
module.exports = sqrt;
|
(function() {
// enyo can use information from the script tag that loads this bootstrap file
var thisScript = "enyo.js";
enyo = window.enyo || {};
enyo.locateScript = function(inName) {
var scripts = document.getElementsByTagName("script");
for (var i=scripts.length-1, s, src, l=inName.length; (i>=0) && (s=scripts[i]); i--) {
if (!s.located) {
src = s.getAttribute("src") || "";
if (src.slice(-l) == inName) {
s.located = true;
return {path: src.slice(0, Math.max(0, src.lastIndexOf("/"))), node: s};
}
}
}
};
enyo.args = enyo.args || {};
var tag = enyo.locateScript(thisScript);
if (tag) {
// infer the framework path from the document, unless the user has specified one explicitly
enyo.args.root = (enyo.args.root || tag.path).replace("/source", "");
// all attributes of the bootstrap script tag become enyo.args
for (var i=0, it; (it = tag.node.attributes.item(i)); i++) {
enyo.args[it.nodeName] = it.value;
}
}
})();
|
export const FETCH_INVALID = 'FETCH_INVALID';
export const FETCH_ONGOING = 'FETCH_ONGOING';
export const FETCH_SUCCEEDED = 'FETCH_SUCCEEDED';
export const FETCH_FAILED = 'FETCH_FAILED';
function combineArrayOfFetchStatuses(fetchStatusesArray) {
const allInvalid = fetchStatusesArray.reduce((total, status) => total && (status === FETCH_INVALID), true);
const anyOngoing = fetchStatusesArray.reduce((total, status) => total || (status === FETCH_ONGOING), false);
const anyFailed = fetchStatusesArray.reduce((total, status) => total || (status === FETCH_FAILED), false);
const allSucceeded = fetchStatusesArray.reduce((total, status) => total && (status === FETCH_SUCCEEDED), true);
if (allInvalid) {
return FETCH_INVALID;
}
if (anyOngoing) {
return FETCH_ONGOING;
}
if (anyFailed) {
return FETCH_FAILED;
}
if (allSucceeded) {
return FETCH_SUCCEEDED;
}
return FETCH_ONGOING;
}
function combineIndexedFetchStatuses(indexedFetchStatuses) {
const fetchStatusesArray = Object.keys(indexedFetchStatuses).map(k => indexedFetchStatuses[k]);
return combineArrayOfFetchStatuses(fetchStatusesArray);
}
// accept a string, an array, or an object
export function combineFetchStatuses(input) {
let fetchStatusToUse;
if (input === undefined) {
const missingFetchStatusError = {
msg: 'fetchStatuses is undefined!',
};
throw missingFetchStatusError;
// support a basic string
} else if (typeof input === 'string') {
fetchStatusToUse = input;
// or an array of strings
} else if (Array.isArray(input)) {
fetchStatusToUse = combineArrayOfFetchStatuses(input);
// or an object keyed to strings
} else if (typeof input === 'object' && input !== null) {
fetchStatusToUse = combineIndexedFetchStatuses(input);
} else {
const badFetchStatusTypeError = {
msg: `fetchStatus received is not a valid type - it is ${typeof input}`,
};
throw badFetchStatusTypeError;
}
return fetchStatusToUse;
}
|
import { describe, beforeEach, it } from '@bigtest/mocha';
import { expect } from 'chai';
import React, { Component } from 'react';
import setupApplication from '../helpers/setup-core-application';
import AboutInteractor from '../interactors/about';
describe('About', () => {
const about = new AboutInteractor();
class DummyApp extends Component {
render() {
return (<h1>Hello Stripes!</h1>);
}
}
setupApplication({
modules: [{
type: 'app',
name: '@folio/ui-dummy',
displayName: 'dummy.title',
route: '/dummy',
hasSettings: true,
module: DummyApp
}],
translations: {
'dummy.title': 'Dummy'
}
});
describe('viewing the about page', () => {
beforeEach(function () {
this.visit('/settings/about');
});
it('has one installed app', function () {
expect(about.installedApps()).to.have.lengthOf(1);
});
});
});
|
/**
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const urify = require('urify');
const dataurl = urify(__dirname + '/image.png');
console.log(dataurl);
|
'use strict';
angular.module('sbAdminApp')
.provider("ngModalDefaults", function() {
return {
options: {
closeButtonHtml: "<i class='fa fa-times'></i>"
},
$get: function() {
return this.options;
},
set: function(keyOrHash, value) {
var k, v, _results;
if (typeof keyOrHash === 'object') {
_results = [];
for (k in keyOrHash) {
v = keyOrHash[k];
_results.push(this.options[k] = v);
}
return _results;
} else {
return this.options[keyOrHash] = value;
}
}
};
});
angular.module('sbAdminApp')
.directive('modalDialog', [
'ngModalDefaults', '$sce', function(ngModalDefaults, $sce) {
return {
restrict: 'E',
scope: {
show: '=',
dialogTitle: '@',
onClose: '&?'
},
replace: true,
transclude: true,
link: function(scope, element, attrs) {
var setupCloseButton, setupStyle;
setupCloseButton = function() {
return scope.closeButtonHtml = $sce.trustAsHtml(ngModalDefaults.closeButtonHtml);
};
setupStyle = function() {
scope.dialogStyle = {};
if (attrs.width) {
scope.dialogStyle['width'] = attrs.width;
}
if (attrs.height) {
return scope.dialogStyle['height'] = attrs.height;
}
};
scope.hideModal = function() {
return scope.show = false;
};
scope.$watch('show', function(newVal, oldVal) {
/*
if (newVal && !oldVal) {
document.getElementsByTagName("body")[0].style.overflow = "hidden";
} else {
document.getElementsByTagName("body")[0].style.overflow = "";
}
*/
if ((!newVal && oldVal) && (scope.onClose != null)) {
return scope.onClose();
}
});
setupStyle();
return setupCloseButton();
},
templateUrl: '../../static/ng-admin/scripts/directives/modal-dialog/modal-dialog.html',
};
}
]);
|
module.exports = function(grunt) {
grunt.registerTask('css', ['sass','postcss']);
}
|
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
// MODULES //
var tape = require( 'tape' );
var isnan = require( '@stdlib/math/base/assert/is-nan' );
var randu = require( '@stdlib/random/base/randu' );
var PINF = require( '@stdlib/constants/float64/pinf' );
var NINF = require( '@stdlib/constants/float64/ninf' );
var skewness = require( './../lib' );
// TESTS //
tape( 'main export is a function', function test( t ) {
t.ok( true, __filename );
t.equal( typeof skewness, 'function', 'main export is a function' );
t.end();
});
tape( 'if provided `NaN` for any parameter, the function returns `NaN`', function test( t ) {
var y = skewness( NaN, 1.0 );
t.equal( isnan( y ), true, 'returns NaN' );
y = skewness( 1.0, NaN );
t.equal( isnan( y ), true, 'returns NaN' );
t.end();
});
tape( 'if provided a nonpositive `beta`, the function returns `NaN`', function test( t ) {
var y;
y = skewness( 2.0, 0.0 );
t.equal( isnan( y ), true, 'returns NaN' );
y = skewness( 2.0, -1.0 );
t.equal( isnan( y ), true, 'returns NaN' );
y = skewness( 2.0, -1.0 );
t.equal( isnan( y ), true, 'returns NaN' );
y = skewness( 1.0, NINF );
t.equal( isnan( y ), true, 'returns NaN' );
y = skewness( PINF, NINF );
t.equal( isnan( y ), true, 'returns NaN' );
y = skewness( NINF, NINF );
t.equal( isnan( y ), true, 'returns NaN' );
y = skewness( NaN, NINF );
t.equal( isnan( y ), true, 'returns NaN' );
t.end();
});
tape( 'the function returns `~1.14` as the skewness of a Gumbel distribution ', function test( t ) {
var a;
var b;
var i;
var v;
for ( i = 0; i < 10; i++ ) {
a = ( randu()*10.0 );
b = ( randu()*10.0 ) + a;
v = skewness( a, b );
t.equal( v, 1.1395470994046488, 'returns ~1.14' );
}
t.end();
});
|
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
// MAIN //
/**
* Polyfill for returning the current working directory in environments which do not have support for returning the current working directory.
*
* @private
* @returns {string} current working directory
*
* @example
* var dir = cwd();
* // returns '/'
*/
function cwd() {
return '/';
}
// EXPORTS //
module.exports = cwd;
|
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
// MODULES //
var isnan = require( '@stdlib/math/base/assert/is-nan' );
var PI = require( '@stdlib/constants/float64/pi' );
// MAIN //
/**
* Returns the variance of a Rayleigh distribution.
*
* @param {NonNegativeNumber} sigma - scale parameter
* @returns {NonNegativeNumber} variance
*
* @example
* var v = variance( 9.0 );
* // returns ~34.765
*
* @example
* var v = variance( 2.0 );
* // returns ~1.717
*
* @example
* var v = variance( -0.2 );
* // returns NaN
*
* @example
* var v = variance( NaN );
* // returns NaN
*/
function variance( sigma ) {
if ( isnan( sigma ) || sigma < 0 ) {
return NaN;
}
return ( 4.0-PI ) * sigma*sigma / 2.0;
}
// EXPORTS //
module.exports = variance;
|
exports.stringify = JSON.stringify
exports.newEvent = function(str) {
return new Event(str)
}
|
'use strict';
var
Promise = require('bluebird');
var
bunyan = require('bunyan'),
log = bunyan.createLogger({name: 'enyo-dev'});
module.exports = log;
Promise.onPossiblyUnhandledRejection(function (e) {
throw e;
});
process.on('uncaughtException', function (err) {
log.fatal(err);
process.exit(1);
});
|
const {app, BrowserWindow} = require('electron');
const dialog = require('electron').dialog;
var childProcess = require('child_process');
let win;
var openFile = function() {
var files = dialog.showOpenDialog(win, {
properties: ['openFile'],
filters: [
{ name: 'MRIQA XML-Files', extensions: ['xml'] },
{ name: 'All Files', extensions: ['*']}
]
});
if(!files) {
return;
}
var file = files[0];
return file;
};
function delay(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
function createWindow (process) {
// Create the browser window.
win = new BrowserWindow({width: 1024, height: 768, title: 'MRIQA-GUI', icon:'public/img/icon.png'});
win.maximize();
// Disable menu bar
win.setMenu(null);
delay(1000).then(() => { // nasty workaround -> promise request throws timeout
win.loadURL('http://localhost:3000/');
});
// Emitted when the window is closed.
win.on('closed', () => {
process.kill();
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
win = null;
});
}
function fGenerateApp() {
// invoke child process (remote application)
var invoked = false;
var options = { stdio: [null, null, null, 'ipc'] };
var args = process.argv.slice(2);
var nodeJsProcess = childProcess.fork('./index.js', args, options);
// listen for errors as they may prevent the exit event from firing
nodeJsProcess.on('error', (err) => {
if(invoked){
return;
}
invoked = true;
if(err){
throw err;
}
});
nodeJsProcess.on('message', (data) => {
if(data === 'openDialog'){
var file = openFile();
if(file){
nodeJsProcess.send(file);
}
else{
nodeJsProcess.send(null);
}
}
});
nodeJsProcess.stdout.on('data', (data) => {
console.log(data.toString());
});
createWindow(nodeJsProcess);
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', fGenerateApp);
// Quit when all windows are closed.
app.on('window-all-closed', () => {
// On macOS it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', () => {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (win === null) {
createWindow();
}
});
|
'use strict';
angular.module('openshiftConsole')
.filter('dateRelative', function() {
// dropSuffix will tell moment whether to include the "ago" text
return function(timestamp, dropSuffix) {
if (!timestamp) {
return timestamp;
}
return moment(timestamp).fromNow(dropSuffix);
};
})
.filter('duration', function() {
return function(timestampLhs, timestampRhs, omitSingle, precision) {
if (!timestampLhs) {
return timestampLhs;
}
precision = precision || 2;
timestampRhs = timestampRhs || new Date(); // moment expects either an ISO format string or a Date object
var ms = moment(timestampRhs).diff(timestampLhs);
var duration = moment.duration(ms);
// the out of the box humanize in moment.js rounds to the nearest time unit
// but we need more details
var humanizedDuration = [];
var years = duration.years();
var months = duration.months();
var days = duration.days();
var hours = duration.hours();
var minutes = duration.minutes();
var seconds = duration.seconds();
function add(count, singularText, pluralText) {
if (count === 0) {
return;
}
if (count === 1) {
if (omitSingle) {
humanizedDuration.push(singularText);
} else {
humanizedDuration.push("one " + singularText);
}
return;
}
humanizedDuration.push(count + ' ' + pluralText);
}
add(years, "year", "years");
add(months, "month", "months");
add(days, "day", "days");
add(hours, "hour", "hours");
add(minutes, "minute", "minutes");
add(seconds, "second", "seconds");
// If precision is 1, we're showing rough values. Don't show values less
// than a minute.
// TODO: Is there ever a time we want precision = 1 and to show seconds?
if (humanizedDuration.length === 1 && seconds && precision === 1) {
if (omitSingle) {
return "minute";
}
return "one minute";
}
if (humanizedDuration.length === 0) {
humanizedDuration.push("0 seconds");
}
if (humanizedDuration.length > precision) {
humanizedDuration.length = precision;
}
return humanizedDuration.join(", ");
};
})
.filter('ageLessThan', function() {
// ex: amt = 5 and unit = 'minutes'
return function(timestamp, amt, unit) {
return moment().subtract(amt, unit).diff(moment(timestamp)) < 0;
};
})
.filter('orderObjectsByDate', function(toArrayFilter) {
return function(items, reverse) {
items = toArrayFilter(items);
/*
* Note: This is a hotspot in our code. We sort frequently by date on
* the overview and browse pages.
*/
items.sort(function (a, b) {
if (!a.metadata || !a.metadata.creationTimestamp || !b.metadata || !b.metadata.creationTimestamp) {
throw "orderObjectsByDate expects all objects to have the field metadata.creationTimestamp";
}
// The date format can be sorted using straight string comparison.
// Compare as strings for performance.
// Example Date: 2016-02-02T21:53:07Z
if (a.metadata.creationTimestamp < b.metadata.creationTimestamp) {
return reverse ? 1 : -1;
}
if (a.metadata.creationTimestamp > b.metadata.creationTimestamp) {
return reverse ? -1 : 1;
}
return 0;
});
return items;
};
});
|
/**
* First we will load all of this project's JavaScript dependencies which
* includes Vue and other libraries. It is a great starting point when
* building robust, powerful web applications using Vue and Laravel.
*/
require('./bootstrap');
window.Vue = require('vue');
Vue.component(
'passport-clients',
require('./components/passport/Clients.vue')
);
Vue.component(
'passport-authorized-clients',
require('./components/passport/AuthorizedClients.vue')
);
Vue.component(
'passport-personal-access-tokens',
require('./components/passport/PersonalAccessTokens.vue')
);
Vue.component(
'example',
require('./components/Example.vue')
);
const app = new Vue({
el: '#app'
});
|
enyo.kind({
name: "moon.sample.CalendarSample",
classes: "moon enyo-unselectable enyo-fit",
kind: "FittableColumns",
components: [
{components: [
{kind: "moon.Calendar", name: "calendar", onChange: "changed"}
]},
{kind: "FittableRows", fit: true, components: [
{kind: "moon.Scroller", fit:true, components: [
{kind:"moon.Divider", content:"Set value:"},
{classes:"moon-hspacing", components: [
{kind: "moon.InputDecorator", classes: "moon-2h", components: [
{kind: "moon.Input", name:"yearInput", classes: "moon-calendar-sample-input", placeholder: "Year"}
]},
{kind: "moon.InputDecorator", classes: "moon-2h", components: [
{kind: "moon.Input", name:"monthInput", classes: "moon-calendar-sample-input", placeholder: "Month"}
]},
{kind: "moon.InputDecorator", classes: "moon-2h", components: [
{kind: "moon.Input", name:"dayInput", classes: "moon-calendar-sample-input", placeholder: "Day"}
]}
]},
{classes:"moon-hspacing", components: [
{kind: "moon.Button", small:true, content:"Set Date", ontap:"setDate"},
{kind: "moon.Button", small:true, content:"Reset to Current", ontap:"resetDate"}
]},
{classes:"moon-1v"},
{classes:"moon-7h", components: [
{kind: "moon.DatePicker", name: "picker", noneText: "Pick a Date", content: "Pick a Date"},
{kind: "moon.ExpandablePicker", name:"localePicker", noneText: "No Language Selected", content: "Choose Locale", onChange: "setLocale", components: [
{content: "Use Default Locale", active: true},
{content: "ko-KO"}, //Korea, firstDayOfWeek: 1
{content: "zh-TW"},
{content: "fa-IR"}, // Iran, persian calendar
{content: "th-TH"}, //Thailand
{content: "en-US"}, //United States, firstDayOfWeek: 0
{content: "und-AE"}, //United Arab Emirates, firstDayOfWeek: 6
{content: "und-AG"}, //Antigua and Barbuda, firstDayOfWeek: 0
{content: "und-CA"}, //Canada, firstDayOfWeek: 0
{content: "it-CH"}, //Italian
{content: "en-MX"},
{content: "de-DE"}, // Germany, firstDayOfWeek: 1
{content: "fr-FR"}, // France, firstDayOfWeek: 1
{content: "fr-CA"},
{content: "it-IT"}, // Italy, firstDayOfWeek: 1
{content: "es-ES"}, // Spain, firstDayOfWeek: 1
{content: "es-MX"}
]},
{name: 'dowLengthPicker', kind: "moon.ExpandablePicker", content: "Choose DOW Label Length", onChange: "setLabelLength", components: [
{content: "short", active: true},
{content: "medium"},
{content: "long"},
{content: "full"}
]},
{name: 'dowLabelClass', kind: "moon.ExpandablePicker", content: "Choose DOW Label Class", onChange: "setLabelStyle", components: [
{content: "Default", active: true, className:""},
{content: "Divider", className:"moon-divider moon-divider-text"},
{content: "Smaller font", className: "moon-calendar-picker-day small"}
]}
]}
]},
{kind: "moon.Divider", content: "Result"},
{kind: "moon.BodyText", name: "result", content: "No change yet"}
]}
],
bindings: [
{from: ".$.calendar.value", to:".$.picker.value", oneWay:false}
],
create: function(){
this.inherited(arguments);
if (!window.ilib) {
this.$.localePicker.hide();
this.$.dowLengthPicker.hide();
this.log("iLib not present -- hiding locale & dow length picker");
} else {
this.df = new ilib.DateFmt({
type: "datetime",
time: "hmsa",
date: "dmy",
useNative: false,
length: "short"
});
}
if (this.$.localePicker.selected) {
this.setLocale(null, {selected: this.$.localePicker.selected});
}
},
updateCurrentString: function (date) {
var formatted = window.ilib ? this.df.format(date) : date.toDateString();
this.$.result.setContent("Current Date" + " changed to " + formatted);
},
setLocale: function(inSender, inEvent){
if (ilib) {
var locale = inEvent.selected.content,
val = (locale == "Use Default Locale") ? null : locale;
enyo.updateLocale(locale);
this.$.calendar.setLocale(val);
this.$.picker.setLocale(val);
this.df = new ilib.DateFmt({
type: "datetime",
time: "hmsa",
date: "dmy",
useNative: false,
length: this.$.dowLengthPicker.selected.content
});
this.updateCurrentString(this.$.calendar.getValue());
}
return true;
},
setLabelLength: function(inSender, inEvent){
if (inEvent.content){
this.$.calendar.setDayOfWeekLength(inEvent.content);
if (ilib) {
this.df = new ilib.DateFmt({
type: "datetime",
time: "hmsa",
date: "dmy",
useNative: false,
length: inEvent.content
});
}
this.updateCurrentString(this.$.calendar.getValue());
this.removeLabelItem(this.$.dowLabelClass, inEvent, 'Divider', 'full');
}
return true;
},
setLabelStyle: function(inSender, inEvent){
if (inEvent.content){
this.$.calendar.setDayOfWeekClasses(inEvent.selected.className);
this.removeLabelItem(this.$.dowLengthPicker, inEvent, 'full', 'Divider');
}
return true;
},
removeLabelItem: function (inControl, inEvent, inLabelName1, inLabelName2) {
var i,
c = inControl.getClientControls();
for (i = 0; i < c.length; i++) {
if (c[i].content == inLabelName1) {
c[i].addRemoveClass("moon-calendar-dow-lable-nodisplay", Boolean(inEvent.content == inLabelName2));
}
}
},
changed: function(inSender, inEvent) {
if (this.$.result && inEvent.value) {
this.updateCurrentString(inEvent.value);
}
},
setDate: function(inSender, inEvent){
var year = isNaN(parseInt(this.$.yearInput.getValue(), 0)) ? this.$.picker.value.getFullYear() : parseInt(this.$.yearInput.getValue(), 0);
var month = isNaN(parseInt(this.$.monthInput.getValue(), 0)) ? this.$.picker.value.getMonth() : parseInt(this.$.monthInput.getValue(), 0) - 1;
var day = isNaN(parseInt(this.$.dayInput.getValue(), 0)) ? this.$.picker.value.getDate() : parseInt(this.$.dayInput.getValue(), 0);
this.$.calendar.setValue(new Date(year, month, day));
},
resetDate: function() {
this.$.calendar.setValue(null);
}
});
|
ManageIQ.angular.app.directive('autoFocus', ['$timeout', function($timeout) {
return {
require: 'ngModel',
link: function(scope, elem, attr, ctrl) {
scope['form_focus_' + ctrl.$name] = elem[0];
scope.$watch(function() {
return elem.is(':visible');
}, function() {
if (attr.autoFocus === '' || attr.autoFocus === 'proactiveFocus') {
angular.element(scope['form_focus_' + ctrl.$name]).focus();
if (!angular.element(scope['form_focus_' + ctrl.$name]).is(':focus')) {
ManageIQ.qe.autofocus += 1;
$timeout(function() {
angular.element(scope['form_focus_' + ctrl.$name]).focus();
ManageIQ.qe.autofocus -= 1;
}, 1000);
}
}
});
scope.$on('reactiveFocus', function(_e) {
if (!angular.element(scope['form_focus_' + ctrl.$name]).is(':focus')) {
ManageIQ.qe.autofocus += 1;
$timeout(function() {
angular.element(scope['form_focus_' + ctrl.$name]).focus();
ManageIQ.qe.autofocus -= 1;
}, 0);
}
});
},
};
}]);
|
(function() {
'use strict';
angular
.module('mvnblogApp')
.controller('SettingsController', SettingsController);
SettingsController.$inject = ['Principal', 'Auth'];
function SettingsController (Principal, Auth) {
var vm = this;
vm.error = null;
vm.save = save;
vm.settingsAccount = null;
vm.success = null;
/**
* Store the "settings account" in a separate variable, and not in the shared "account" variable.
*/
var copyAccount = function (account) {
return {
activated: account.activated,
email: account.email,
firstName: account.firstName,
langKey: account.langKey,
lastName: account.lastName,
login: account.login
};
};
Principal.identity().then(function(account) {
vm.settingsAccount = copyAccount(account);
});
function save () {
Auth.updateAccount(vm.settingsAccount).then(function() {
vm.error = null;
vm.success = 'OK';
Principal.identity(true).then(function(account) {
vm.settingsAccount = copyAccount(account);
});
}).catch(function() {
vm.success = null;
vm.error = 'ERROR';
});
}
}
})();
|
require('http').createServer(function (req, res) {
res.setHeader('X-Has-Header', res.hasHeader(req.headers['x-header']) + '');
res.end();
}).listen(7080);
|
var io = require('socket.io')(22122);
var replSocketio = io.of('/admin/repl');
var logger = global.thisapp.logger;
var EventEmitter = require('events');
var replEmitter = new EventEmitter();
module.exports = replEmitter;
replSocketio.on('connection', function(socket) {
replEmitter.on('output', (data) => {
socket.emit('output', data);
});
socket.on('input', function(inputValue) {
logger.info(inputValue);
replEmitter.emit('input', inputValue);
});
socket.on('error', function(err) {
console.log('socket id is ' + socket.id + ' has error');
console.log(err);
});
socket.on('disconnect', function() {
console.log('a client disconnect, socket id is ' + socket.id);
});
});
|
const filterFromInImports = require('./filterFromInImports')();
const words = ['import', ' { ', 'from', ' } ', 'from', ' \'', 'rxjs', '\';'];
const words2 = [' } ', 'from', '(', 'of'];
describe('filterFromInImports(words, index)', () => {
it('should not filter the word, if the word is not "from"', () => {
expect(filterFromInImports(words, 0)).toEqual(false);
});
it('should not filter the word, if the word "from" is not positioned between } and \' signs', () => {
expect(filterFromInImports(words, 2)).toEqual(false);
});
it('should filter "from" when "from" is positioned between } and \' signs', () => {
expect(filterFromInImports(words, 4)).toEqual(true);
});
it('should not filter "from" when "from" is after } but not before \'', () => {
expect(filterFromInImports(words2, 1)).toEqual(false);
});
});
|
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
/**
* @license
* Copyright (c) 2015 The Polymer Project Authors. All rights reserved.
* This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
* The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
* The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
* Code distributed by Google as part of the polymer project is also
* subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/
const launchpad = require("launchpad");
const promisify = require("promisify-node");
const LAUNCHPAD_TO_SELENIUM = {
chrome: chrome,
canary: chrome,
firefox: firefox,
aurora: firefox,
ie: internetExplorer,
safari: safari,
};
function normalize(browsers) {
return (browsers || []).map(function (browser) {
if (typeof browser === 'string') {
return browser;
}
return browser.browserName;
});
}
exports.normalize = normalize;
/**
* Expands an array of browser identifiers for locally installed browsers into
* their webdriver capabilities objects.
*
* If `names` is empty, or contains `all`, all installed browsers will be used.
*/
function expand(names) {
return __awaiter(this, void 0, void 0, function* () {
if (names.indexOf('all') !== -1) {
names = [];
}
const unsupported = difference(names, exports.supported());
if (unsupported.length > 0) {
throw new Error(`The following browsers are unsupported: ${unsupported.join(', ')}. ` +
`(All supported browsers: ${exports.supported().join(', ')})`);
}
const installedByName = yield exports.detect();
const installed = Object.keys(installedByName);
// Opting to use everything?
if (names.length === 0) {
names = installed;
}
const missing = difference(names, installed);
if (missing.length > 0) {
throw new Error(`The following browsers were not found: ${missing.join(', ')}. ` +
`(All installed browsers found: ${installed.join(', ')})`);
}
return names.map(function (n) { return installedByName[n]; });
});
}
exports.expand = expand;
/**
* Detects any locally installed browsers that we support.
*
* Exported and declared as `let` variables for testabilty in wct.
*/
exports.detect = function detect() {
return __awaiter(this, void 0, void 0, function* () {
const launcher = yield promisify(launchpad.local)();
const browsers = yield promisify(launcher.browsers)();
const results = {};
for (const browser of browsers) {
if (!LAUNCHPAD_TO_SELENIUM[browser.name])
continue;
const converter = LAUNCHPAD_TO_SELENIUM[browser.name];
const convertedBrowser = converter(browser);
if (convertedBrowser) {
results[browser.name] = convertedBrowser;
}
}
return results;
});
};
/**
* Exported and declared as `let` variables for testabilty in wct.
*
* @return A list of local browser names that are supported by
* the current environment.
*/
exports.supported = function supported() {
return Object.keys(launchpad.local.platform).filter((key) => key in LAUNCHPAD_TO_SELENIUM);
};
// Launchpad -> Selenium
/**
* @param browser A launchpad browser definition.
* @return A selenium capabilities object.
*/
function chrome(browser) {
return {
'browserName': 'chrome',
'version': browser.version.match(/\d+/)[0],
'chromeOptions': {
'binary': browser.binPath,
'args': ['start-maximized']
},
};
}
/**
* @param browser A launchpad browser definition.
* @return A selenium capabilities object.
*/
function firefox(browser) {
const version = parseInt(browser.version.match(/\d+/)[0], 10);
const marionette = version >= 47;
return {
'browserName': 'firefox',
'version': `${version}`,
'firefox_binary': browser.binPath,
marionette
};
}
/**
* @param browser A launchpad browser definition.
* @return A selenium capabilities object.
*/
function safari(browser) {
// SafariDriver doesn't appear to support custom binary paths. Does Safari?
return {
'browserName': 'safari',
'version': browser.version,
// TODO(nevir): TEMPORARY. https://github.com/Polymer/web-component-tester/issues/51
'safari.options': {
'skipExtensionInstallation': true,
},
};
}
/**
* @param browser A launchpad browser definition.
* @return A selenium capabilities object.
*/
function phantom(browser) {
return {
'browserName': 'phantomjs',
'version': browser.version,
'phantomjs.binary.path': browser.binPath,
};
}
/**
* @param browser A launchpad browser definition.
* @return A selenium capabilities object.
*/
function internetExplorer(browser) {
return {
'browserName': 'internet explorer',
'version': browser.version,
};
}
/** Filter out all elements from toRemove from source. */
function difference(source, toRemove) {
return source.filter((value) => toRemove.indexOf(value) < 0);
}
|
const getOwnPropSymbols = Object.getOwnPropertySymbols
const propIsEnumerable = Object.prototype.propertyIsEnumerable
const toObject = (val) => {
if (val === null || val === undefined) {
throw new TypeError('Object.assign cannot be called with null or undefined')
}
return Object(val)
}
const objectAssign = (...args) => {
const to = toObject(args[0])
args.slice(1).forEach((arg) => {
const from = Object(arg)
Object.keys(from).forEach((key) => {
to[key] = from[key]
})
if (getOwnPropSymbols) {
const symbols = getOwnPropSymbols(from)
symbols.forEach((symbol) => {
if (propIsEnumerable.call(from, symbol)) {
to[symbol] = from[symbol]
}
})
}
})
return to
}
export default objectAssign
|
// //////////////////////////////////////////////////////////////////////////////////////////////////
// Edit View Form Container
// //////////////////////////////////////////////////////////////////////////////////////////////////
import { useDeps, composeAll, compose } from 'mantra-core';
import EditRootViewForm from '../components/edit_view/edit_root_view_form';
const onPropsChange = ({ context }, onData) => {
const { TAPi18n } = context();
const text = {
title: TAPi18n.__('edit_view.root_form.title'),
description: TAPi18n.__('edit_view.root_form.description'),
};
onData(null, { text });
};
export const depsMapper = (context, actions) => ({
setTitle: actions.editView.setTitle,
setDescription: actions.editView.setRootDescription,
context: () => context,
});
export default composeAll(
compose(onPropsChange),
useDeps(depsMapper),
)(EditRootViewForm);
|
angular.module('assignmentApp', ['ionic', 'ngCordova', 'assignmentApp.services', 'assignmentApp.cloudServices', 'assignmentApp.controllers', 'assignmentApp.cloudController'])
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
if(window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
}
if(window.StatusBar) {
StatusBar.styleDefault();
}
});
})
.config(function ($stateProvider, $urlRouterProvider, CloudPhotoLibraryServiceProvider) {
$urlRouterProvider.otherwise('/tab');
$stateProvider
.state('tab', {
url: '/tab',
templateUrl: 'templates/tabs.html'
})
.state('tab.photos', {
url: '/photos',
views: {
'photos': {
templateUrl: 'templates/photos.html',
controller: 'PhotosCtrl'
}
}
})
.state('tab.photo', {
url: '/photos/:photoid',
views: {
'photos': {
templateUrl: 'templates/photo.html',
controller: 'PhotoCtrl'
}
}
})
.state('tab.clouds', {
url: '/cloud',
views: {
'cloud': {
templateUrl: 'templates/cloudPhotos.html',
controller: 'CloudPhotosCtrl'
}
}
})
.state('tab.cloud', {
url: '/cloud/:photoid',
views: {
'cloud': {
templateUrl: 'templates/photo.html',
controller: 'CloudPhotoCtrl'
}
}
});
CloudPhotoLibraryServiceProvider.setConfig({
bucket: 'cpmd-photo-library',
website_url: 'http://cpmd-photo-library.s3-website.eu-central-1.amazonaws.com/',
awsconfig: {
accessKeyId: 'AKIAJSJHNFR5QOGSGVVA',
secretAccessKey: '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',
region: 'eu-central-1',
apiVersions: {
s3: '2006-03-01',
dynamodb: '2012-08-10'
}
}
});
});
|
define("dojox/mvc/computed", [
"dojo/_base/array",
"dojo/_base/lang",
"dojo/has"
], function(array, lang, has){
"use strict";
has.add("object-is-api", lang.isFunction(Object.is));
var arrayProto = Array.prototype,
areSameValues = has("object-is-api") ? Object.is : function(lhs, rhs){
return lhs === rhs && (lhs !== 0 || 1 / lhs === 1 / rhs) || lhs !== lhs && rhs !== rhs;
};
function watch(o, prop, callback){
var hWatch;
if(o && lang.isFunction(o.watch)){
hWatch = o.watch(prop, function(name, old, current){
if(!areSameValues(old, current)){
callback(current, old);
}
});
}else{
0 && console.log("Attempt to observe non-stateful " + o + " with " + prop + ". Observation not happening.");
}
return {
remove: function(){
if(hWatch){
hWatch.remove();
}
}
};
}
function getProps(list){
return array.map(list, function(p){
return p.each ?
array.map(p.target, function(entry){
return entry.get ? entry.get(p.targetProp) : entry[p.targetProp];
}) :
p.target.get ? p.target.get(p.targetProp) : p.target[p.targetProp];
});
}
function removeHandles(handles) {
for(var h = null; (h = handles.shift());){
h.remove();
}
}
return function(target, targetProp, compute /*===== , deps =====*/){
// summary:
// Returns a pointer to a dojo/Stateful property that are computed with other dojo/Stateful properties.
// target: dojo/Stateful
// dojo/Stateful where the property is in.
// targetProp: String
// The property name.
// compute: Function
// The function, which takes dependent dojo/Stateful property values as the arguments, and returns the computed value.
// deps: dojox/mvc/at...
// The dojo/Stateful properties this computed property depends on.
// returns:
// The handle to clean this up.
// example:
// If stateful.first is "John" and stateful.last is "Doe", stateful.name becomes "John Doe".
// | computed(stateful, "name", function(first, last){
// | return first + " " + last;
// | }, at(stateful, "first"), at(stateful, "last"));
// example:
// If names is an array of objects with name property, stateful.totalNameLength becomes the sum of length of name property of each array item.
// | computed(stateful, "totalNameLength", function(names){
// | var total = 0;
// | array.forEach(names, function(name){
// | total += name.length;
// | });
// | return total;
// | }, lang.mixin(at(names, "name"), {each: true}));
function applyComputed(data){
var result, hasResult;
try{
result = compute.apply(target, data);
hasResult = true;
}catch(e){
console.error("Error during computed property callback: " + (e && e.stack || e));
}
if(hasResult){
if(lang.isFunction(target.set)){
target.set(targetProp, result);
}else{
target[targetProp] = result;
}
}
}
if(target == null){
throw new Error("Computed property cannot be applied to null.");
}
if(targetProp === "*"){
throw new Error("Wildcard property cannot be used for computed properties.");
}
var deps = arrayProto.slice.call(arguments, 3),
hDep = array.map(deps, function(dep, index){
function observeEntry(entry){
return watch(entry, dep.targetProp, function(){
applyComputed(getProps(deps));
});
}
if(dep.targetProp === "*"){
throw new Error("Wildcard property cannot be used for computed properties.");
}else if(dep.each){
var hArray,
hEntry = array.map(dep.target, observeEntry);
if(dep.target && lang.isFunction(dep.target.watchElements)){
hArray = dep.target.watchElements(function(idx, removals, adds){
removeHandles(arrayProto.splice.apply(hEntry, [idx, removals.length].concat(array.map(adds, observeEntry))));
applyComputed(getProps(deps));
});
}else{
0 && console.log("Attempt to observe non-stateful-array " + dep.target + ". Observation not happening.");
}
return {
remove: function(){
if(hArray){
hArray.remove();
}
removeHandles(hEntry);
}
};
}else{
return watch(dep.target, dep.targetProp, function(current){
var list = [];
arrayProto.push.apply(list, getProps(deps.slice(0, index)));
list.push(current);
arrayProto.push.apply(list, getProps(deps.slice(index + 1)));
applyComputed(list);
});
}
});
applyComputed(getProps(deps));
return {
remove: function(){
removeHandles(hDep);
}
};
};
});
|
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
function getDecimals(n) {
n = n + '';
var i = n.indexOf('.');
return (i == -1) ? 0 : n.length - i - 1;
}
function getVF(n, opt_precision) {
var v = opt_precision;
if (undefined === v) {
v = Math.min(getDecimals(n), 3);
}
var base = Math.pow(10, v);
var f = ((n * base) | 0) % base;
return {v: v, f: f};
}
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"\u0190nkak\u025bny\u00e1",
"\u0190nd\u00e1m\u00e2"
],
"DAY": [
"Jumap\u00edl\u00ed",
"Jumat\u00e1tu",
"Jumane",
"Jumat\u00e1n\u0254",
"Ala\u00e1misi",
"Jum\u00e1a",
"Jumam\u00f3si"
],
"ERANAMES": [
"Me\u00edn\u014d Y\u025b\u0301s\u0289",
"E\u00edn\u014d Y\u025b\u0301s\u0289"
],
"ERAS": [
"MY",
"EY"
],
"FIRSTDAYOFWEEK": 0,
"MONTH": [
"Oladal\u0289\u0301",
"Ar\u00e1t",
"\u0186\u025bn\u0268\u0301\u0254\u0268\u014b\u0254k",
"Olodoy\u00ed\u00f3r\u00ed\u00ea ink\u00f3k\u00fa\u00e2",
"Oloil\u00e9p\u016bny\u012b\u0113 ink\u00f3k\u00fa\u00e2",
"K\u00faj\u00fa\u0254r\u0254k",
"M\u00f3rus\u00e1sin",
"\u0186l\u0254\u0301\u0268\u0301b\u0254\u0301r\u00e1r\u025b",
"K\u00fash\u00een",
"Olg\u00edsan",
"P\u0289sh\u0289\u0301ka",
"Nt\u0289\u0301\u014b\u0289\u0301s"
],
"SHORTDAY": [
"Jpi",
"Jtt",
"Jnn",
"Jtn",
"Alh",
"Iju",
"Jmo"
],
"SHORTMONTH": [
"Dal",
"Ar\u00e1",
"\u0186\u025bn",
"Doy",
"L\u00e9p",
"Rok",
"S\u00e1s",
"B\u0254\u0301r",
"K\u00fas",
"G\u00eds",
"Sh\u0289\u0301",
"Nt\u0289\u0301"
],
"WEEKENDRANGE": [
5,
6
],
"fullDate": "EEEE, d MMMM y",
"longDate": "d MMMM y",
"medium": "d MMM y h:mm:ss a",
"mediumDate": "d MMM y",
"mediumTime": "h:mm:ss a",
"short": "dd/MM/y h:mm a",
"shortDate": "dd/MM/y",
"shortTime": "h:mm a"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "Ksh",
"DECIMAL_SEP": ".",
"GROUP_SEP": ",",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "-\u00a4",
"negSuf": "",
"posPre": "\u00a4",
"posSuf": ""
}
]
},
"id": "mas",
"pluralCat": function(n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]);
|
'use strict';
var clone = require('clone');
var addPipelineExtras = require('../../lib/addPipelineExtras');
var readGltf = require('../../lib/readGltf');
var generateNormals = require('../../lib/generateNormals');
var gltfNoNormalsPath = './specs/data/generateNormals/box_no_normals.gltf';
var gltfNormalsPath = './specs/data/generateNormals/box_normals.gltf';
var boxahedronNoNormalsGltfPath = './specs/data/generateNormals/boxahedron_no_normals.gltf';
describe('generateNormals', function(){
var gltfNoNormals;
var gltfNormals;
beforeAll(function(done) {
readGltf(gltfNoNormalsPath)
.then(function(gltf) {
gltfNoNormals = gltf;
addPipelineExtras(gltfNoNormals);
return readGltf(gltfNormalsPath);
})
.then(function(gltf) {
gltfNormals = gltf;
addPipelineExtras(gltfNormals);
done();
});
});
it('generates smooth normals if they do not exist', function() {
var gltf = gltfNoNormals;
var byteLengthBefore = 168;
generateNormals(gltf);
var attributes = gltf.meshes.mesh_box.primitives[0].attributes;
var byteLengthAfter = gltf.buffers[Object.keys(gltf.buffers)[0]].byteLength;
expect(attributes.NORMAL).toBeDefined();
expect(gltf.accessors[attributes.NORMAL]).toBeDefined();
expect(byteLengthAfter).toBe(byteLengthBefore + 8 * 3 * 4); // 8 normals are generated
});
it('does not generate normals if they already exist', function() {
var gltf = gltfNormals;
var gltfCopy = clone(gltf);
generateNormals(gltf);
expect(gltf.meshes).toEqual(gltfCopy.meshes);
});
it('generates face normals if they do not exist', function() {
var gltf = gltfNoNormals;
var byteLengthBefore = 168;
generateNormals(gltf, {
faceNormals : true
});
var attributes = gltf.meshes.mesh_box.primitives[0].attributes;
var byteLengthAfter = gltf.buffers[Object.keys(gltf.buffers)[0]].byteLength;
expect(attributes.NORMAL).toBeDefined();
expect(gltf.accessors[attributes.NORMAL]).toBeDefined();
expect(byteLengthAfter).toBe(byteLengthBefore + 8 * 3 * 4); // 8 normals are generated
});
it('generating smooth normals for mesh with more than 1 primitive produces unique normals accessors', function() {
readGltf(boxahedronNoNormalsGltfPath)
.then(function(gltf) {
gltfNoNormals = gltf;
addPipelineExtras(gltfNoNormals);
})
.then(function() {
var gltf = gltfNoNormals;
var byteLengthBefore = 432;
generateNormals(gltf);
var attributes0 = gltf.meshes['Geometry-mesh002'].primitives[0].attributes;
var attributes1 = gltf.meshes['Geometry-mesh002'].primitives[1].attributes;
var byteLengthAfter = gltf.buffers[Object.keys(gltf.buffers)[0]].byteLength;
expect(attributes0.NORMAL).toBeDefined();
expect(attributes1.NORMAL).toBeDefined();
expect(gltf.accessors[attributes0.NORMAL]).toBeDefined();
expect(gltf.accessors[attributes1.NORMAL]).toBeDefined();
expect(gltf.accessors[attributes0.NORMAL]).not.toEqual(gltf.accessors[attributes1.NORMAL]);
expect(byteLengthAfter).toBe(byteLengthBefore + 28 * 3 * 4); // 28 normals are generated
});
});
});
|
import can from 'can/';
import BaseRouter from 'kvsh/can/control/router/';
import HeaderCtrl from 'app/control/header/';
import HomeCtrl from 'app/control/home/';
/**
* @class Router
*/
var Router = BaseRouter.extend(
/** @Static */
{
defaults : {}
},
/** @Prototype */
{
setupCommons: function(screen, page, data) {
this._super.apply(this, arguments);
this.setSingleController(can.$("#header"), HeaderCtrl, {page: page, screen: screen});
// if ga (google analytics) object is attached to window tracking is enabled
window.ga && window.ga('send', 'pageview');
},
"/ route": function(data) {
this.setSingleController(can.$("#main"), HomeCtrl, {});
}
});
export default Router;
|
/**
* @class dr.dimmer {UI Components}
* A dimmer that can be placed on another dr.view to obscure the subviews of
* that view.
*/
/**
* @attribute {Boolean} restorefocus
* Determines if focus will be sent back to the view that had focus before
* the dimmer was shown when the dimmer is hidden.
*/
/**
* @attribute {dr.View} restorefocus
* @readonly
* The thing to set focus on when the dimmer is hidden if restorefocus
* is true.
*/
/**
* @method show
* Shows the dimmer and remembers the focus location.
* @returns {void}
*/
/**
* @method show
* Hides the dimmer and restores focus if necessary.
* @returns {void}
*/
|
/**
* TextLink -> tests
*/
import React from 'react';
import { describe, beforeEach, it } from 'mocha';
import { HashRouter } from 'react-router-dom';
import { expect } from 'chai';
import { mount } from '../../../tests/helpers';
import TextLinkInteractor from './interactor';
import TextLink from '../TextLink';
describe('TextLink', () => {
const textLink = new TextLinkInteractor();
beforeEach(async () => {
await mount(
<TextLink
id="some-id"
href="/hello-world"
>
TextLink
</TextLink>
);
});
it('Should have an ID', () => {
expect(textLink.id).to.equal('some-id');
});
describe('If rendered with a "href"-prop', () => {
beforeEach(async () => {
await mount(
<TextLink href="/hello-world">TextLink</TextLink>
);
});
it('Should render a native anchor tag', () => {
expect(textLink.tagName).to.equal('a');
});
});
describe('If rendered with a "to"-prop', () => {
beforeEach(async () => {
await mount(
<HashRouter>
<TextLink to="/hello-world">TextLink</TextLink>
</HashRouter>
);
});
it('Should render a native anchor tag', () => {
expect(textLink.tagName).to.equal('a');
});
});
});
|
import path from 'path';
import { Server } from 'http';
import Express from 'express';
import React from 'react';
import { renderToString } from 'react-dom/server';
import { match, RouterContext } from 'react-router';
import routes from './routes';
import NotFoundPage from './components/not_found_page';
// initialize the server and configure support for ejs templates
const app = new Express();
const server = new Server(app);
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
// define the folder that will be used for static assets
app.use(Express.static(path.join(__dirname, 'static')));
// universal routing and rendering
app.get('*', (req, res) => {
match(
{ routes, location: req.url },
(err, redirectLocation, renderProps) => {
// in case of error display the error message
if (err) {
return res.status(500).send(err.message);
}
// in case of redirect propagate the redirect to the browser
if (redirectLocation) {
return res.redirect(302, redirectLocation.pathname + redirectLocation.search);
}
// generate the React markup for the current route
let markup;
if (renderProps) {
// if the current route matched we have renderProps
markup = renderToString(<RouterContext {...renderProps}/>);
} else {
// otherwise we can render a 404 page
markup = renderToString(<NotFoundPage/>);
res.status(404);
}
// render the index template with the embedded React markup
return res.render('index', { markup });
}
);
});
// start the server
const port = process.env.PORT || 3000;
const env = process.env.NODE_ENV || 'production';
server.listen(port, err => {
if (err) {
return console.error(err);
}
console.info(`Server running on http://localhost:${port} [${env}]`);
});
|
var Segmenter = require('./lib/Segmenter');
var opts = {
MainDictPath: 'lib/dict/main.dic',
SurnameDictPath: 'lib/dict/surname.dic',
QuantifierDictPath: 'lib/dict/quantifier.dic',
SuffixDictPath: 'lib/dict/suffix.dic',
PrepDictPath: 'lib/dict/preposition.dic',
StopWordDictPath: 'lib/dict/stopword.dic',
};
var segmenter = new Segmenter(opts);
var txt = '1995年10月,他与中方探讨了在海运、造船方面合作的可能与途径。';
console.log('txt: ', txt);
var result = segmenter.analyze(txt);
console.log('result: ', result);
txt = '无耻啊无耻,西工大图书馆 标题要长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长';
console.log('txt: ', txt);
result = segmenter.analyze(txt);
console.log('result: ', result);
|
/*
* #%L
* %%
* Copyright (C) 2011 - 2017 BMW Car IT GmbH
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
define("joynr/messaging/browser/BrowserMessagingStub", [ "joynr/util/Typing"
], function(Typing) {
/**
* @name BrowserMessagingStub
* @constructor
*
* @param {Object} settings
* @param {String} [settings.windowId] the destination windowId to send the messages to, defaults to defaultWindowId of master tab
* @param {WebMessagingStub} settings.webMessagingStub an initialized sender that has the default window already set
*/
function BrowserMessagingStub(settings) {
/**
* @name BrowserMessagingStub#transmit
* @function
*
* @param {JoynrMessage} joynrMessage the joynr message to transmit
*/
this.transmit = function transmit(joynrMessage) {
return settings.webMessagingStub.transmit({
windowId : settings.windowId,
message : joynrMessage
});
};
}
return BrowserMessagingStub;
});
|
const DataStore = require('./DataStore');
const Channel = require('../structures/Channel');
const { Events } = require('../util/Constants');
const kLru = Symbol('LRU');
const lruable = ['group', 'dm'];
/**
* Stores channels.
* @private
* @extends {DataStore}
*/
class ChannelStore extends DataStore {
constructor(client, iterableOrOptions = {}, options) {
if (!options && typeof iterableOrOptions[Symbol.iterator] !== 'function') {
options = iterableOrOptions;
iterableOrOptions = undefined;
}
super(client, iterableOrOptions, Channel);
if (options.lru) {
const lru = this[kLru] = [];
lru.add = item => {
lru.remove(item);
lru.unshift(item);
while (lru.length > options.lru) this.remove(lru[lru.length - 1]);
};
lru.remove = item => {
const index = lru.indexOf(item);
if (index > -1) lru.splice(index, 1);
};
}
}
get(key, peek = false) {
const item = super.get(key);
if (!item || !lruable.includes(item.type)) return item;
if (!peek && this[kLru]) this[kLru].add(key);
return item;
}
set(key, val) {
if (this[kLru] && lruable.includes(val.type)) this[kLru].add(key);
return super.set(key, val);
}
delete(key) {
const item = this.get(key, true);
if (!item) return false;
if (this[kLru] && lruable.includes(item.type)) this[kLru].remove(key);
return super.delete(key);
}
create(data, guild, cache = true) {
const existing = this.get(data.id);
if (existing) return existing;
const channel = Channel.create(this.client, data, guild);
if (!channel) {
this.client.emit(Events.DEBUG, `Failed to find guild for channel ${data.id} ${data.type}`);
return null;
}
if (cache) this.set(channel.id, channel);
return channel;
}
remove(id) {
const channel = this.get(id);
if (channel.guild) channel.guild.channels.remove(id);
super.remove(id);
}
/**
* Data that can be resolved to give a Channel object. This can be:
* * A Channel object
* * A Snowflake
* @typedef {Channel|Snowflake} ChannelResolvable
*/
/**
* Resolves a ChannelResolvable to a Channel object.
* @method resolve
* @memberof ChannelStore
* @instance
* @param {ChannelResolvable} channel The channel resolvable to resolve
* @returns {?Channel}
*/
/**
* Resolves a ChannelResolvable to a channel ID string.
* @method resolveID
* @memberof ChannelStore
* @instance
* @param {ChannelResolvable} channel The channel resolvable to resolve
* @returns {?Snowflake}
*/
}
module.exports = ChannelStore;
|
import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';
moduleForComponent('custom-property/boolean', 'Integration | Component | custom property/boolean', {
integration: true
});
test('it renders', function(assert) {
// Set any properties with this.set('myProperty', 'value');
// Handle any actions with this.on('myAction', function(val) { ... });
this.render(hbs`{{custom-property/boolean}}`);
assert.equal(this.$().text().trim(), '');
// Template block usage:
this.render(hbs`
{{#custom-property/boolean}}
template block text
{{/custom-property/boolean}}
`);
assert.equal(this.$().text().trim(), 'template block text');
});
|
/**
* (description)
*
* @author yourname
*/
export default class ClaimListController {
constructor($q, storeSvc, $scope, $http, NgTableParams, $state, storeManageSvc) {
"ngInject";
this.$state = $state
this.storeSvc = storeSvc;
this.q = $q;
this.NgTableParams = NgTableParams;
this.storeManageSvc = storeManageSvc;
this.init();
this.getProvince();
this.submitting = false;
}
init() {
var self = this;
var _this = this;
this.tableParams = new this.NgTableParams({
page: 1,
count: 10
}, {
getData: function (params) {
self.loading = true;
let formData = self.getSearchFormData(params.url());
self.loadPromise = self.storeManageSvc.getClaimList(formData);
return self.loadPromise
.then(result => {
self.loading = false;
if (result.datas) {
_this.storeInfo = {
totalCount: result.totalCount
};
params.total(result.totalCount);
self.submitting = false;
return result.datas
}
});
}
})
}
getSearchFormData(paramsUrl) {
let params = this.formatSearchObj();
params.offset = (paramsUrl.page-1) * paramsUrl.count;
params.limit = paramsUrl.count;
return params;
}
// 选择所在区域
getProvince() {
this.storeManageSvc.getProvinceList()
.then(res=>{
this.provinceList = res;
})
}
getCity(provinceId) {
this.storeManageSvc.getCityList(provinceId)
.then(res=>{
this.cityList = res;
})
}
getRegion(cityId) {
this.storeManageSvc.getRegionList(cityId)
.then(res=>{
this.regionList = res;
})
}
// 查询
search() {
this.submitting = true;
this.tableParams.parameters({
page: 1
}).reload();
}
// 格式化检索数据
formatSearchObj() {
let params = {};
let status = parseInt(this.searchOptions.status);
if (status > -1) {
params.status = status;
}
if (status == -1) {
params.status = "0,1,2,3,4,6,8";
}
if (this.searchOptions.storeName) {
params.storeName = this.searchOptions.storeName;
}
if (this.searchOptions.brandName) {
params.brandName = this.searchOptions.brandName;
}
if (this.searchOptions.provinceId) {
params.provinceId = this.searchOptions.provinceId.provinceId;
}
if (this.searchOptions.cityId) {
params.cityId = this.searchOptions.cityId.cityId;
}
if (this.searchOptions.regionId) {
params.regionId = this.searchOptions.regionId.regionId;
}
return params;
}
reset() {
this.searchOptions = {
publisherSubject:'-1',
status:'-1'
}
}
goList() {
this.$state.go('storeMlist');
}
goAdd() {
this.$state.go('storeMadd');
}
goClaimDetail(id) {
this.$state.go('storeMclaimdetail', {id: id});
}
goView(id) {
this.$state.go('storeMview', {id: id});
}
getstaffpageadd() {
this.staffnewSvc.getstaffpage()
}
goStaff(storeid) {
this.$state.go('stafflist', {storeid: storeid});
}
// 导出Excel
exportExcel() {
var params = this.formatSearchObj();
var limit = $("#page .active span").html(),
page = $("#page ul li.active a span").html();
if (page == undefined) {
page = 1;
}
page = parseInt(page);
params.limit = parseInt(limit);
params.offset = (page-1)*limit;
var temp = "";
for(var i in params){
temp += i+"="+params[i]+"&";
}
temp = temp.substr(temp, temp.length-1)
this.exportExcelUrl = "/storemanage/claim/excel?" + temp;
}
}
|
U.Style.RegularShape = U.Style.Image.extend({
init:function (options) {
var opts = options || {};
this.points = opts.points !== undefined ? opts.points : [];
this.innerRadius = options.innerRadius;
this.radius = options.radius !== undefined ? options.radius : options.innerRadius;
this.outerRadius = options.outerRadius !== undefined ? options.outerRadius : this.radius;
}
})
|
'use strict';
angular.module('yawl.controllers.header', []).
controller('headerCtrl', ['$rootScope', function ($rootScope) {
this.logout = function () {
$rootScope.$broadcast("user:logout");
};
}]);
|
/**!
*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/*global _*/
(function () {
'use strict';
/**
* @name CgroupCPUHeadroomMetricDataModel
* @desc
*/
function CgroupCPUHeadroomMetricDataModel(ContainerMetadataService, WidgetDataModel, MetricListService, DashboardService) {
var DataModel = function () {
return this;
};
DataModel.prototype = Object.create(WidgetDataModel.prototype);
DataModel.prototype.init = function () {
WidgetDataModel.prototype.init.call(this);
this.name = this.dataModelOptions ? this.dataModelOptions.name : 'metric_' + DashboardService.getGuid();
// create create base metrics
var cpuUsageMetric = MetricListService.getOrCreateCumulativeMetric('cgroup.cpuacct.usage'),
cpuSharesMetric = MetricListService.getOrCreateMetric('cgroup.cpusched.shares'),
cpuPeriodsMetric = MetricListService.getOrCreateMetric('cgroup.cpusched.periods'),
ncpuMetric = MetricListService.getOrCreateMetric('hinv.ncpu'),
derivedFunction;
derivedFunction = function () {
var returnValues = [];
if ( cpuUsageMetric.data.length > 0){
angular.forEach(cpuUsageMetric.data, function (instance) {
if (instance.values.length > 0 && ContainerMetadataService.containerIdExist(instance.key)) {
var lastValue = instance.values[instance.values.length - 1];
var name = ContainerMetadataService.idDictionary(instance.key) || instance.key;
if (ContainerMetadataService.checkContainerName(name) && ContainerMetadataService.checkContainerFilter(name)) {
returnValues.push({
timestamp: lastValue.x,
key: name,
value: lastValue.y / 1000 / 1000 / 1000
});
}
}
});
}
if ( cpuPeriodsMetric.data.length > 0) {
angular.forEach(cpuPeriodsMetric.data, function (instance) {
if (instance.values.length > 0 && ContainerMetadataService.containerIdExist(instance.key)) {
var lastValue = instance.values[instance.values.length - 1];
var name = ContainerMetadataService.idDictionary(instance.key) || instance.key;
if (ContainerMetadataService.checkContainerName(name) && ContainerMetadataService.checkContainerFilter(name)) {
if (lastValue.y > 0) {
var cpuSharesInstance = _.find(cpuSharesMetric.data, function(el) {
return el.key === instance.key;
});
if (angular.isDefined(cpuSharesInstance)) {
var cpuSharesValue = cpuSharesInstance.values[cpuSharesInstance.values.length - 1];
returnValues.push({
timestamp: lastValue.x,
key: name + ' (limit)',
value: cpuSharesValue.y / lastValue.y
});
}
} else {
if (ncpuMetric.data.length > 0) {
var ncpuInstance = ncpuMetric.data[ncpuMetric.data.length - 1];
if (ncpuInstance.values.length > 0) {
var ncpuValue = ncpuInstance.values[ncpuInstance.values.length - 1];
returnValues.push({
timestamp: ncpuValue.x,
key: name + ' (physical)',
value: ncpuValue.y
});
}
}
}
}
}
});
}
return returnValues;
};
// create derived metric
this.metric = MetricListService.getOrCreateDerivedMetric(this.name, derivedFunction);
this.updateScope(this.metric.data);
};
DataModel.prototype.destroy = function () {
// remove subscribers and delete derived metric
MetricListService.destroyDerivedMetric(this.name);
// remove subscribers and delete base metrics
MetricListService.destroyMetric('cgroup.cpuacct.usage');
WidgetDataModel.prototype.destroy.call(this);
};
return DataModel;
}
angular
.module('datamodel')
.factory('CgroupCPUHeadroomMetricDataModel', CgroupCPUHeadroomMetricDataModel);
})();
|
/**
* Copyright 2014 IBM
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var Provider = require('../models/providermodel');
exports.findAllView = function(req, res) {
Provider.find({},function(err, docs) {
if (!docs) {
console.log('no provider found');
docs = [];
}
res.render('topology/providers/providerindex', {
title: 'Available Providers',
docs: docs
});
});
};
exports.addViewSetup = function(req, res) {
res.render('topology/providers/newprovider.jade', {
title: 'Create new provider'
});
};
var validator = require('validator');
var validateProvider = function(doc, next) {
console.log("validating Provider document");
console.log(doc);
console.log('validated json');
next(null);
};
exports.addViewExecute = function(req, res) {
validateProvider(req.body.provider, function(err) {
if (! err) {
var provider = new Provider(req.body.provider);
provider.save(function(err) {
if (! err) {
res.redirect('/providers/');
}else {
console.log('error saving provider');
console.log(err);
res.redirect('/providers/new');
}
});
}else {
console.log('error in addViewExecute validating provider');
console.log(err);
res.redirect('/providers');
}
});
};
exports.findAll = function(req, res) {
Provider.find({},function(err, docs) {
if (!docs) {
console.log('findAll could not find any documents');
console.log('printing our err');
console.log(err);
res.send(404);
}else {
res.send(docs);
}
});
};
exports.editViewSetup = function(req, res) {
Provider.findById(req.params.id, function(err, doc) {
res.render('topology/providers/editprovider', {
title: 'Edit Provider',
provider: doc
});
});
};
exports.editViewExecute = function(req, res) {
Provider.findById(req.params.id, function(err, doc) {
doc.name = req.body.provider.name;
doc.description = req.body.provider.description;
doc.UCD_webURL= req.body.provider.UCD_webURL;
doc.UCD_authtoken= req.body.provider.UCD_authtoken;
doc.UCD_version= req.body.provider.UCD_version;
doc.IWD_host= req.body.provider.IWD_host;
doc.IWD_version= req.body.provider.IWD_version;
//doc.IWD_username= req.body.provider.IWD_username;
//doc.IWD_password= req.body.provider.IWD_password;
console.log('attempting to update document');
console.log(doc);
validateProvider(doc, function(err) {
if (!err) {
doc.save(function(err) {
if (!err) {
res.redirect('/providers');
}
else {
console.log('error saving to database');
res.redirect('/providers');
}
});
}else {
console.log('invalid data:' + err);
res.redirect('/providers');
}
});
});
};
exports.deleteView = function(req, res) {
Provider.findById(req.params.id, function(err, doc) {
if (!doc) {
console.log('could not remove document using ID ' + req.params.id);
res.redirect('/providers');
}else {
doc.remove(function() {
res.redirect('/providers');
});
}
});
};
exports.find = function(req, res) {
console.log('provider find: finding ' + req.params.id);
Provider.find({provider:req.params.id}, function(err, docs) {
console.log('printing docs');
console.log(docs);
if (docs.length==0) {
res.send(404);
}else {
console.log('print build stream object found:');
console.log(docs[0]);
res.send(docs[0]);
}
});
};
exports.delete = function(req, res) {
Provider.find({buildStream:req.params.id}, function(err, docs) {
if (docs.length==0) {
res.send(404);
}else {
docs[0].remove(function() {
res.send(200);
});
}
});
};
exports.update = function(req, res) {
console.log('Updating document ' + req.params.id);
Provider.find({_id:req.params.id}, function(err, docs) {
updateDoc = req.body;
console.log(updateDoc);
if (err) {
console.log('error finding provider');
res.send(err, 400);
}else if ( docs.length==0) {
console.log('could not find document');
res.send(400);
}else {
try {
console.log('found document, attempting to update');
doc=docs[0];
for (var param in updateDoc) {
console.log('updating ' + param + ' with ' + updateDoc[param]);
doc[param] = updateDoc[param];
}
validateProvider(doc, function(err) {
if (!err) {
doc.save();
res.json(doc);
console.log('saved doc');
console.log(doc);
}else {
console.log('error caught validating provider ' + err);
res.send(err, 400);
}
});
}catch (myerror) {
console.log('error caught ' + myerror);
res.send(myerror, 400);
}
}
});
};
exports.create = function(req, res) {
validateProvider(req.body, function(err) {
if (! err) {
try {
var newProvider = new Provider(req.body);
newProvider.save(function(err) {
if (!err) {
res.send(newProvider);
}else {
res.send(err, 400);
}
});
}catch (myerror) {
console.log('could not save provider, most likely due to invalid data');
console.log(myerror);
res.send(myerror, 400);
}
}else {
console.log('invalid input: ' + err);
console.log(req.body);
res.send(err, 400);
}
});
};
|
CKEDITOR.plugins.setLang( 'mindtouch', 'fr-ca',
{
mindtouch :
{
code : 'Code',
comment : 'Comment',
css : 'CSS',
dekiscript : 'DekiScript',
format :
{
tag_h1 : 'Title',
tag_hx : 'Hx'
},
jem : 'JavaScript (JEM)',
hideBlocks : 'Hide Blocks',
wysiwyg : 'WYSIWYG'
}
});
|
Ti.API.info("!!getLooksData.js LOADED");
var jsonURL = "http://be.vlothie.com/json/getLooks.php";
Alloy.Globals.looksArray = {};
Ti.API.info("!!---- getLooksData.js get json data from: " + jsonURL);
var xhr = Titanium.Network.createHTTPClient();
xhr.onload = function() {
Ti.API.info("got data from the network: " + this.responseText);
var jsonData = JSON.parse(this.responseText);
var count = 0;
for (var index in jsonData) {
Alloy.Globals.looksArray[index] = [];
for (var field in jsonData[index]) Alloy.Globals.looksArray[index][field] = jsonData[index][field];
count++;
}
Alloy.Globals.looksArray["size"] = count;
};
xhr.open("GET", jsonURL);
xhr.send();
|
'use strict';
exports.__esModule = true;
exports.AsyncBase = undefined;
var _objectWithoutProperties2 = require('babel-runtime/helpers/objectWithoutProperties');
var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2);
var _regenerator = require('babel-runtime/regenerator');
var _regenerator2 = _interopRequireDefault(_regenerator);
var _asyncToGenerator2 = require('babel-runtime/helpers/asyncToGenerator');
var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _inherits2 = require('babel-runtime/helpers/inherits');
var _inherits3 = _interopRequireDefault(_inherits2);
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _propTypes = require('prop-types');
var _propTypes2 = _interopRequireDefault(_propTypes);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var AsyncBase = function (_Component) {
(0, _inherits3.default)(AsyncBase, _Component);
function AsyncBase() {
(0, _classCallCheck3.default)(this, AsyncBase);
return (0, _possibleConstructorReturn3.default)(this, _Component.apply(this, arguments));
}
return AsyncBase;
}(_react.Component);
exports.AsyncBase = AsyncBase;
exports.default = function (options) {
var _class, _temp;
var resolve = options.resolve,
preload = options.preload,
Loading = options.loading;
var module = null;
var Async = (_temp = _class = function (_AsyncBase) {
(0, _inherits3.default)(Async, _AsyncBase);
function Async() {
(0, _classCallCheck3.default)(this, Async);
return (0, _possibleConstructorReturn3.default)(this, _AsyncBase.apply(this, arguments));
}
Async.resolveModule = function () {
var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee() {
var resolvedModule;
return _regenerator2.default.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
if (!module) {
_context.next = 2;
break;
}
return _context.abrupt('return', module);
case 2:
resolvedModule = resolve();
if (!(resolvedModule && typeof resolvedModule.then === 'function')) {
_context.next = 9;
break;
}
_context.next = 6;
return resolvedModule;
case 6:
module = _context.sent;
_context.next = 10;
break;
case 9:
module = resolvedModule;
case 10:
if (module.default) {
module = module.default;
}
return _context.abrupt('return', module);
case 12:
case 'end':
return _context.stop();
}
}
}, _callee, this);
}));
function resolveModule() {
return _ref.apply(this, arguments);
}
return resolveModule;
}();
Async.prototype.componentWillMount = function componentWillMount() {
if (typeof this.context.registerChunk === 'function') {
this.context.registerChunk(options);
}
this.load();
};
Async.prototype.componentDidMount = function componentDidMount() {
if (preload) {
resolve();
}
};
Async.prototype.load = function () {
var _ref2 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee2() {
return _regenerator2.default.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
_context2.t0 = this;
_context2.next = 3;
return Async.resolveModule();
case 3:
_context2.t1 = _context2.sent;
_context2.t2 = {
module: _context2.t1
};
_context2.t0.setState.call(_context2.t0, _context2.t2);
case 6:
case 'end':
return _context2.stop();
}
}
}, _callee2, this);
}));
function load() {
return _ref2.apply(this, arguments);
}
return load;
}();
Async.prototype.render = function render() {
var _props = this.props,
children = _props.children,
rest = (0, _objectWithoutProperties3.default)(_props, ['children']);
var ModuleComponent = module;
if (typeof children === 'function') {
return children(ModuleComponent, rest);
}
if (!ModuleComponent) {
return Loading ? _react2.default.createElement(Loading, null) : null;
}
return _react2.default.createElement(ModuleComponent, rest);
};
return Async;
}(AsyncBase), _class.propTypes = {
children: _propTypes2.default.func
}, _class.defaultProps = {
children: undefined
}, _class.contextTypes = {
registerChunk: _propTypes2.default.func
}, _temp);
return Async;
};
|
{
angular.module("placenames.search", ['placenames.search.service', 'placenames.templates'])
.directive('placenamesOnEnter', function () {
return function (scope, element, attrs) {
element.bind("keydown keypress", function (event) {
if (event.which === 13) {
scope.$apply(function () {
scope.$eval(attrs.placenamesOnEnter);
});
event.preventDefault();
}
});
};
})
.directive('placenamesOptions', ['searchService', function (searchService) {
return {
link: function (scope) {
scope.leave = function () {
searchService.hide();
};
scope.enter = function () {
searchService.show(scope.match.model);
};
scope.$destroy = function () {
searchService.hide();
};
}
};
}])
.directive("placenamesQuickSearch", ['$document', '$rootScope', '$timeout', 'searchService',
function ($document, $rootScope, $timeout, searchService) {
return {
templateUrl: 'placenames/search/quicksearch.html',
restrict: 'AE',
link: function (scope) {
scope.state = searchService.data;
$document.on('keyup', function keyupHandler(keyEvent) {
if (keyEvent.which === 27) {
keyEvent.stopPropagation();
keyEvent.preventDefault();
scope.$apply(function () {
scope.showFilters = false;
});
}
});
scope.loadDocs = function () {
return searchService.filtered().then(fetched => {
return fetched.response.docs;
});
};
scope.search = function search(item) {
scope.showFilters = false;
searchService.goto(item).then(() => {
scope.state.filter = "";
$rootScope.$broadcast("search.button.fired", item);
});
};
}
};
}
])
.filter('placenamesTooltip', [function () {
return function (model) {
let buffer = "<div style='text-align:left'>";
if (model.variant) {
let variants = model.variant.split("|");
variants.forEach((name, index) => {
buffer += index ? "" : "Also known as";
buffer += (index && index < variants.length - 1 ? "," : "") + " ";
if (index && index === variants.length - 1) {
buffer += "or ";
}
buffer += name;
});
buffer += "<br/>";
}
buffer += "Lat " + model.location.split(" ").reverse().join("° Lng ") + "°<br/>Feature type: " +
model.feature + "</div>";
return buffer;
};
}]);;
}
|
/// <reference types="cypress" />
// ***********************************************************
// This example plugins/index.js can be used to load plugins
//
// You can change the location of this file or turn off loading
// the plugins file with the 'pluginsFile' configuration option.
//
// You can read more here:
// https://on.cypress.io/plugins-guide
// ***********************************************************
// This function is called when a project is opened or re-opened (e.g. due to
// the project's config changing)
/**
* @type {Cypress.PluginConfig}
*/
const browserify = require("@cypress/browserify-preprocessor")
module.exports = (on, config) => {
if (process.env.CYPRESS_SNAPSHOT_UPDATE === 'true') {
config.env['cypress-plugin-snapshots'].updateSnapshots = true;
}
require("cypress-plugin-snapshots/plugin").initPlugin(on, config)
require("@cypress/code-coverage/task")(on, config)
const options = browserify.defaultOptions
// transform[1][1] is "babelify"
// so we just add our code instrumentation plugin to the list
options.browserifyOptions.transform[1][1].plugins.push("babel-plugin-istanbul")
on(
"file:preprocessor",
browserify({...options, typescript: require.resolve("typescript")}),
)
return config
}
|
/*
jQuery.extend extracted from the jQuery source & optimised for NodeJS
Twitter: @FGRibreau / fgribreau.com
Usage:
var Extend = require('./Extend');
// Extend
var obj = Extend({opt1:true, opt2:true}, {opt1:false});
// Deep Copy
var clonedObject = Extend(true, {}, myObject);
var clonedArray = Extend(true, [], ['a',['b','c',['d']]]);
*/
var toString = Object.prototype.toString,
hasOwn = Object.prototype.hasOwnProperty,
push = Array.prototype.push,
slice = Array.prototype.slice,
trim = String.prototype.trim,
indexOf = Array.prototype.indexOf,
// [[Class]] -> type pairs
class2type = {};
// Populate the class2type map
"Boolean Number String Function Array Date RegExp Object".split(" ").forEach(function(name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
function type(obj){
return obj == null ?
String( obj ) :
class2type[ toString.call(obj) ] || "object";
}
function isPlainObject( obj ) {
if ( !obj || type(obj) !== "object") {
return false;
}
// Not own constructor property must be Object
if ( obj.constructor &&
!hasOwn.call(obj, "constructor") &&
!hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
return false;
}
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
var key;
for ( key in obj ) {}
return key === undefined || hasOwn.call( obj, key );
}
module.exports = function extend(){
var options, name, src, copy, copyIsArray, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && type(target) !== "function") {
target = {};
}
// extend jQuery itself if only one argument is passed
if ( length === i ) {
target = this;
--i;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( (options = arguments[ i ]) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( isPlainObject(copy) || (copyIsArray = type(copy) === "array") ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && type(src) === "array" ? src : [];
} else {
clone = src && isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[ name ] = extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
|
'use strict';
angular.module('datafestApp')
.factory('polygons', function () {
var paintPolyLine = function(p_path) {
var flightPlanCoordinates = [];
for (i = 0; i < p_path.length; i++) {
flightPlanCoordinates.push(new google.maps.LatLng(p_path[i][1], p_path[i][0]));
}
if (polyline) {
polyline.setMap(null);
}
polyline = new google.maps.Polyline({
path: flightPlanCoordinates,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
polyline.setMap($rootScope.map);
zoomToObject(polyline);
function zoomToObject(obj) {
debugger;
var bounds = new google.maps.LatLngBounds();
var points = obj.getPath().getArray();
for (var n = 0; n < points.length; n++) {
bounds.extend(points[n]);
}
$rootScope.map.fitBounds(bounds);
}
}
var _paintPolygons = function(p_polygons) {
angular.forEach(p_polygons.features, function(value, key) {
var triangleCoords = [];
for (var j = 0; j < value.geometry.rings[0].length; j++) {
triangleCoords.push(new google.maps.LatLng(value.geometry.rings[0][j][1], value.geometry.rings[0][j][0]));
}
// Construct the polygon.
var bermudaTriangle = new google.maps.Polygon({
paths: triangleCoords,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35
});
bermudaTriangle.setMap($rootScope.map);
});
// Define the LatLng coordinates for the polygon's path.
}
});
|
// Licensed under the Apache License. See footer for details.
"use strict"
const http = require("http")
const path = require("path")
const cfenv = require("cfenv")
const concat = require("concat-stream")
const utils = require("./lib/utils")
const altStackTrace = require("./lib/altStackTrace")
const messages = require("./lib/messages")
const slack = require("./lib/send-slack-webhook")
const pkg = require("./package.json")
let appEnvOpts = {}
try {
// allow overrides when running locally
appEnvOpts.vcap = require("./tmp/vcap.json")
}
catch(e) {}
exports.version = pkg.version
exports.main = main
//------------------------------------------------------------------------------
const appEnv = cfenv.getAppEnv(appEnvOpts)
utils.appName = appEnv.name
const DEBUGinit = utils.createDebug("init")
const DEBUGserver= utils.createDebug("server")
const DEBUGexit = utils.createDebug("exit")
const DEBUGerror = utils.createDebug("error")
const DEBUGdrain = utils.createDebug("drain")
if (require.main == module) main()
//------------------------------------------------------------------------------
function main() {
DEBUGinit("starting")
DEBUGinit("enabling alternate stack trace")
altStackTrace.enable()
DEBUGinit("adding exit handler")
process.on("exit", function(code) {
DEBUGexit("code: " + code)
})
DEBUGinit("adding uncaught exception handler")
process.on("uncaughtException", function(err) {
DEBUGerror("exception: " + err.stack)
process.exit(1)
})
//----------------------------------------------------------------------------
let server = http.createServer(requestHandler)
console.log("server starting on " + appEnv.url)
server.listen(appEnv.port, appEnv.bind, function() {
console.log("server started on " + appEnv.url)
})
}
//------------------------------------------------------------------------------
function requestHandler(request, response) {
if (request.headers["content-type"] != "text/plain") {
return sendLogResponse(response)
}
const channel = path.basename(request.url)
const webHookInfo = appEnv.getServiceCreds(channel)
if (null == webHookInfo) {
DEBUGdrain(`request for unbound service: ${channel}`)
return sendLogResponse(response)
}
if (null == webHookInfo.url) {
DEBUGdrain(`request for service: ${channel}, but service has no "url" property`)
return sendLogResponse(response)
}
let contentStream = concat(function(content) {
processLogMessages(webHookInfo, content)
})
request.pipe(contentStream)
sendLogResponse(response)
}
//------------------------------------------------------------------------------
function processLogMessages(webHookInfo, content) {
// DEBUGdrain(`content: ${content}`)
let msgs = messages.splitMessages(content)
for (let i=0; i<msgs.length; i++) {
let msg = messages.splitMessage(msgs[i])
// DEBUGdrain(`msg: ${msg}`)
processLogMessage(webHookInfo, msg)
}
}
//------------------------------------------------------------------------------
function processLogMessage(webHookInfo, msg) {
// msg = {
// date: string
// component: string
// message: string
// }
if (msg.component == "RTR") return
let payload = {
text: `${msg.component}: ${msg.message}`,
icon_emoji: ":computer:"
}
copyOverride(webHookInfo, payload, "username")
copyOverride(webHookInfo, payload, "icon_url")
copyOverride(webHookInfo, payload, "icon_emoji")
copyOverride(webHookInfo, payload, "channel")
copyOverride(webHookInfo, payload, "username")
slack.send(webHookInfo.url, payload)
}
//------------------------------------------------------------------------------
function copyOverride(webHookInfo, payload, property) {
if (webHookInfo[property]) payload[property] = webHookInfo[property]
}
//------------------------------------------------------------------------------
function sendLogResponse(response) {
response.writeHead(200, {"Content-Type": "text/plain"})
response.end("Hello, world!")
}
//------------------------------------------------------------------------------
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//------------------------------------------------------------------------------
|
switch (3) {
case 1: 4
}
|
/**
* Copyright 2014 SoftWaring Solutions Pty Ltd.
*/
var updatePeriod = 20;
function restartWave(e) {
$.wave.evalJS('restartWave(' + updatePeriod + ')');
}
function toggleWave(e) {
var playing = (e.source.image === '/images/pause.png');
if (playing) {
e.source.image = '/images/play.png';
$.wave.evalJS('suspendWave()');
} else {
e.source.image = '/images/pause.png';
$.wave.evalJS('resumeWave(' + updatePeriod + ')');
}
}
function fasterWave(e) {
updatePeriod = Math.min(Math.max(1, updatePeriod-5), 5000);
$.wave.evalJS('changeWaveRefresh(' + updatePeriod + ')');
}
function slowerWave(e) {
updatePeriod = Math.min(Math.max(1, updatePeriod+5), 5000);
$.wave.evalJS('changeWaveRefresh(' + updatePeriod + ')');
}
Titanium.Gesture.addEventListener('orientationchange', function(e) {
var width = Ti.Platform.displayCaps.platformWidth - 20;
var height = Math.min(200, Ti.Platform.displayCaps.platformHeight);
$.wave.evalJS('setCanvasSize(' + width + ',' + height + ')');
});
$.index.open();
|
// Copyright (c) 2012 Ecma International. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
esid: sec-array.prototype.foreach
es5id: 15.4.4.18-8-1
description: >
Array.prototype.forEach doesn't call callbackfn if 'length' is 0
(empty array)
---*/
var callCnt = 0;
function cb() {
callCnt++
}
var i = [].forEach(cb);
assert.sameValue(callCnt, 0, 'callCnt');
|
// Identifying required modules
var express = require('express');
var router = express.Router();
var monk = require('monk');
var db = monk('localhost:27017/Learn2Gather');
var jwt = require('jsonwebtoken'); // used to create, sign, and verify tokens
var cookie = require('cookies');
// when anyone requests to see existing study groups
router.get('/', function(req, res) {
var cookies = new cookie(req, res);
var token = cookies.get("x-access-token"); // retrieve token, if possible
var db = req.db;
var collection = db.get('StudyGroups'); // retrieve study groups collection
collection.find({ Available: true},{},function(e,docs){
if (token){
res.render('viewgroupslogged', { // display available study groups
"StudyGroups" : docs
});
}
else if (!token) {
res.render('viewgroups', { // display available study groups
"StudyGroups" : docs
});
}
});
});
module.exports = router;
|
var fileslist = [
'.htaccess',
'index.php',
'map.php',
'project.php',
'backend/config.php',
'backend/required.php',
'backend/websun',
'backend/websun/websun.php',
'storage/gallery.template',
'templates/maps_list.html',
'templates/map_view.html',
'templates/css/common.css',
'templates/css/leaflet.css',
'templates/js/html5shiv.js',
'templates/js/jquery.min.js',
'templates/js/leaflet',
'templates/js/leaflet.js',
'templates/js/leaflet/L.Control.MousePosition.css',
'templates/js/leaflet/L.Control.MousePosition.js',
'templates/js/leaflet/singleclick.js'
];
module.exports = function(grunt) {
var pkgVersion = grunt.file.readJSON('package.json').version;
grunt.loadNpmTasks('grunt-contrib-compress');
grunt.initConfig({
compress: {
main: {
options: {
archive: function() {
return 'zip/lfme_release_' + pkgVersion + '.zip'
},
pretty: true
},
expand: true,
cwd: '../',
src: [].concat(fileslist),
dest: '/'
}
}
});
grunt.registerTask('default', ['compress']);
};
|
(function() {
var c2 = window.construct2api;
var gameOver = false;
window.muniverse = {
init: function() {
return c2.waitStart('Game').then(function() {
window.faketime.pause();
var startActions = [
"1851297203172589",
"228753660943099",
"241368541906159",
"416864558353451",
"119145229365271",
"1691735298658291",
"792436249758539",
"107285523526847",
"3203617066596731",
"9056865316152838",
"3706833106313872",
"1645714951464963",
"1150764003682042",
"1001837467091637",
"9715992606739724",
"571273300247036",
"6029466295208036",
"8257914319645084",
"4126609865989209",
"9543488061610864",
"3807538682966564",
"7181995871152998",
"7886214170127376",
"4286959004968254",
"7856101021955011",
"6144983032974021",
"1638319297216416",
"8195898227406143",
"4668042337873552",
"8327480100266767",
"7209414677342595",
"4855499214044951",
"2219507844815649",
"4505311455885122",
"2475988096186141",
"8915095982635582",
"7366494798172276",
"4434964486482928",
"4356806626340371",
"3018427438165503",
"656043499539164",
"7006551689525176",
"2179054818841534"
];
c2.runActions(startActions);
c2.hijackAction('7618523762154123', () => gameOver = true);
window.faketime.advance(100);
});
},
step: function(millis) {
window.faketime.advance(millis);
return Promise.resolve(gameOver);
},
score: function() {
return Promise.resolve(c2.globalVar('Score').getValue());
}
};
})();
|
// This file was procedurally generated from the following sources:
// - src/class-fields/init-err-contains-arguments.case
// - src/class-fields/initializer-error/cls-expr-fields-ternary.template
/*---
description: Syntax error if `arguments` used in class field (ternary expression)
esid: sec-class-definitions-static-semantics-early-errors
features: [class, class-fields-public]
flags: [generated]
negative:
phase: parse
type: SyntaxError
info: |
Static Semantics: Early Errors
FieldDefinition:
PropertyNameInitializeropt
- It is a Syntax Error if ContainsArguments of Initializer is true.
Static Semantics: ContainsArguments
IdentifierReference : Identifier
1. If the StringValue of Identifier is "arguments", return true.
...
For all other grammatical productions, recurse on all nonterminals. If any piece returns true, then return true. Otherwise return false.
---*/
throw "Test262: This statement should not be evaluated.";
var C = class {
x = true ? {} : arguments;
}
|
/* requires $plugins.js */
/* requires TMPL.js */
/* requires CTRL.js */
|
import IsomorphicRelay from 'isomorphic-relay';
import IsomorphicQueryAggregator from './IsomorphicQueryAggregator';
import render from './render';
export default function prepareInitialRender(environment, renderProps) {
const queryAggregator = new IsomorphicQueryAggregator(renderProps);
return IsomorphicRelay.prepareInitialRender({
environment,
Container: queryAggregator.Container,
queryConfig: queryAggregator.queryConfig,
}).then(({ initialReadyState }) => ({
...renderProps,
environment,
initialReadyState,
queryAggregator,
render,
}));
}
|
/**
* First we will load all of this project's JavaScript dependencies which
* includes Vue and other libraries. It is a great starting point when
* building robust, powerful web applications using Vue and Laravel.
*/
require('./bootstrap');
/**
* Next, we will create a fresh Vue application instance and attach it to
* the page. Then, you may begin adding components to this application
* or customize the JavaScript scaffolding to fit your unique needs.
*/
Vue.component('example', require('./components/Example.vue'));
Vue.use(window.VeeValidate);
const app = new Vue({
el: '#app',
});
let swap = function() {
let $this = $(this);
let newSource = $this.data('alt-src');
$this.data('alt-src', $this.attr('src'));
$this.attr('src', newSource);
};
/**
* Initializations
*/
$(function() {
$('.button-collapse').sideNav();
$('.parallax').parallax();
$('select').material_select();
$('.modal').modal();
$('#start_timepicker').pickatime({
darktheme: true,
vibrate: true,
autoclose: false,
twelvehour: false,
default: 'now',
});
$('#end_timepicker').pickatime({
darktheme: true,
vibrate: true,
autoclose: false,
twelvehour: false,
default: '08:00',
});
$('img[data-alt-src]').each(function() {
new Image().src = $(this).data('alt-src');
}).hover(swap, swap);
const shrinkHeader = 322;
$(window).scroll(() => {
let scroll = window.pageYOffset || document.documentElement.scrollTop;
if (scroll >= shrinkHeader) {
$('nav').addClass('ex');
} else {
$('nav').removeClass('ex');
}
$('nav').hover(() => {
if ($('nav').hasClass('ex') && scroll >= shrinkHeader) {
$('nav').removeClass('ex');
}
});
});
});
|
module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
browserify : {
test : {
src : ["src/browserify.js"],
dest : 'build/ssr.js',
options: {
standalone : "SSR"
}
}
}
});
grunt.loadNpmTasks('grunt-browserify');
grunt.registerTask('default', ['browserify']);
};
|
// Copyright (c) 2012 Ecma International. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
esid: sec-array.prototype.reduce
es5id: 15.4.4.21-9-c-i-3
description: >
Array.prototype.reduce - element to be retrieved is own data
property that overrides an inherited data property on an
Array-like object
---*/
var testResult = false;
var initialValue = 0;
function callbackfn(prevVal, curVal, idx, obj) {
if (idx === 1) {
testResult = (curVal === "11");
}
}
var proto = {
0: 0,
1: 1,
2: 2,
length: 2
};
var Con = function() {};
Con.prototype = proto;
var child = new Con();
child[1] = "11";
child[2] = "22";
child.length = 3;
Array.prototype.reduce.call(child, callbackfn, initialValue);
assert(testResult, 'testResult !== true');
|
/*
== BSD2 LICENSE ==
Copyright (c) 2014, Tidepool Project
This program is free software; you can redistribute it and/or modify it under
the terms of the associated License, which is identical to the BSD 2-Clause
License as published by the Open Source Initiative at opensource.org.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the License for more details.
You should have received a copy of the License along with this program; if
not, you can obtain one from Tidepool Project at tidepool.org.
== BSD2 LICENSE ==
Gruntfile for dummy-api
*/
module.exports = function(grunt) {
'use strict';
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
uglify: {
options: {
banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */\n'
},
build: {
src: 'src/<%= pkg.name %>.js',
dest: 'build/<%= pkg.name %>.min.js'
}
},
jshint: {
options: {
jshintrc: '.jshintrc'
},
all: ['Gruntfile.js', 'lib/**/*.js', 'test/**/*.js']
},
docco: {
docs: {
src: ['lib/**/*.js', './*.md'],
dest: ['docs'],
options: {
layout: 'linear',
output: 'docs'
}
}
},
shell: {
addlicense: {
// this may not be the best way to do this dependency, but this isn't
// a task we're going to run that often.
command: 'python ../central/tools/addLicense.py "*/*.js"',
options: {
async: false,
execOptions: {
cwd: './lib/'
}
}
}
},
mochaTest: {
test: {
options: {
reporter: 'spec'
},
src: ['test/**/*.js']
}
}
});
// Load the plugins
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-docco2');
grunt.loadNpmTasks('grunt-shell-spawn');
grunt.loadNpmTasks('grunt-mocha-test');
// Default task(s).
grunt.registerTask('default', ['jshint', 'docco', 'mochaTest']);
grunt.registerTask('test', ['mochaTest']);
};
|
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
info: The Date.prototype property "valueOf" has { DontEnum } attributes
esid: sec-date.prototype.valueof
es5id: 15.9.5.8_A1_T1
description: Checking absence of ReadOnly attribute
---*/
var x = Date.prototype.valueOf;
if (x === 1)
Date.prototype.valueOf = 2;
else
Date.prototype.valueOf = 1;
if (Date.prototype.valueOf === x) {
$ERROR('#1: The Date.prototype.valueOf has not the attribute ReadOnly');
}
|
(typeof define === "undefined" ? function ($) { $(require, exports, module); } : define)(
function (require, exports, module, undefined) {
'use strict';
function hasNative() {
// TODO: write test to avoid faulty implementation in IE8
return typeof Object.defineProperty === 'function';
}
function shouldUseNative() {
if ('useNative' in module.exports) {
return module.exports.useNative;
}
return hasNative();
}
var compose = require('compose'),
Cell,
extend,
hasOwn = Object.prototype.hasOwnProperty,
useNative;
module.exports = Cell = compose(function (mixin) {
var cell = this._cell || (this._cell = {}),
descriptors = cell.descriptors || {},
p, val;
if (useNative && descriptors) {
Object.defineProperties(this, descriptors);
}
for (p in mixin) {
val = mixin[p];
if (typeof val !== 'function') this.set(p, val);
else this[p] = val;
}
},
{
get: function (key) {
var cell = this._cell || {},
descriptors = cell.descriptors || {},
descriptor = descriptors[key] || {},
get = descriptor.get;
if (useNative || !(key in descriptors)) {
return this[key];
}
if (!get) {
if (descriptor._accessor) {
return;
}
return this[key];
}
return get.call(this);
},
set: function (key, value) {
var cell = this._cell || {},
descriptors = cell.descriptors || {},
descriptor = descriptors[key] || {},
set = descriptor.set;
if (useNative || !(key in descriptors)) {
return (this[key] = value);
}
if (!set) {
if (descriptor._accessor) {
throw new TypeError('Cannot set property ' + key + ' of ' + this + ' which has only a getter');
}
if (!descriptor.writable) {
throw new TypeError('Cannot assign to read only property \'' + key + '\' of ' + this);
}
return (this[key] = value);
}
return set.call(this, value);
}
});
Cell.defineProperty = function (descriptor) {
if (!descriptor || typeof descriptor !== 'object') {
throw new TypeError('Property description must be an object: ' + descriptor);
}
if (typeof useNative === 'undefined') {
useNative = shouldUseNative();
}
return new compose.Decorator(function (key) {
// adapted from https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/defineProperties
var d = {},
cell = this._cell || (this._cell = {}),
descriptors = cell.descriptors || (cell.descriptors = {}),
get,
set;
if (hasOwn.call(descriptor, 'enumerable')) d.enumerable = !!descriptor.enumerable;
if (hasOwn.call(descriptor, 'configurable')) d.configurable = !!descriptor.configurable;
if (hasOwn.call(descriptor, 'value')) d.value = descriptor.value;
if (hasOwn.call(descriptor, 'writable')) d.writable = !!descriptor.writable;
if (hasOwn.call(descriptor, 'get')) {
get = descriptor.get;
if (typeof get !== 'function') throw new TypeError('Getter must be a function: ' + get);
d.get = get;
}
if (hasOwn.call(descriptor, 'set')) {
set = descriptor.set;
if (typeof set !== 'function') throw new TypeError('Setter must be a function: ' + get);
d.set = set;
}
if (('get' in d || 'set' in d) && ('value' in d || 'writable' in d)) {
throw new TypeError('Invalid property. A property cannot both have accessors and be writable or have a value, ' + descriptor);
}
if (!useNative) {
// XXX: configurable and enumerable are unsupported in this branch
d._accessor = ('get' in d || 'set' in d);
if ('value' in d) {
this[key] = d.value;
}
}
descriptors[key] = d;
});
};
extend = Cell.extend;
Cell.extend = function () {
var p,
extended = extend.apply(this, arguments);
for (p in Cell) {
if (Cell.hasOwnProperty(p)) extended[p] = Cell[p];
}
return extended;
};
});
|
import React from 'react';
import formatDate from '../../util/formatDate';
import addSizeSuffix from '../../util/addSizeSuffix';
const getDuration = minutes => {
const h = Math.floor(minutes / 60);
const m = minutes % 60;
return `PT${h > 0 ? h + 'H' : ''}${m > 0 ? m + 'M' : ''}`;
};
export default ({
type,
collection,
slug,
description,
picture,
headline,
date,
datemodified,
author,
verdict,
item,
itemname,
director,
releasedate,
wikipediaurl,
rating,
review,
preptime,
cooktime,
totaltime,
recipeyield,
servingsize,
colories,
fatcontent,
ingredients,
instructions,
config: {
protocol,
media,
images,
domain,
collections,
authors,
organization,
mediasuffix,
},
}) => {
let schema = {
'@context': 'http://schema.org/',
mainEntityOfPage: `${protocol}://${domain}/${collections[collection]
.slug}/${slug}/`,
description: description,
datePublished: formatDate(date, 'YYYY-MM-DD', 'de'),
author: {
'@type': 'Person',
name: authors[author].name,
sameAs: `${protocol}://${domain}`,
},
publisher: {
'@type': 'Organization',
name: `${organization.name}`,
logo: {
'@type': 'ImageObject',
url: `${media}${organization.banner.path}${mediasuffix}`,
width: organization.banner.width,
height: organization.banner.height,
},
},
image: {
'@type': 'ImageObject',
url: `${media}${addSizeSuffix(
picture,
images.large.suffix
)}${mediasuffix}`,
height: 2000,
width: 800,
},
};
if (datemodified) {
schema.dateModified = formatDate(datemodified, 'YYYY-MM-DD', 'de');
}
switch (type) {
case 'article':
schema = {
...schema,
'@type': 'NewsArticle',
headline: headline,
};
break;
case 'review':
schema = {
...schema,
'@type': 'Review',
name: verdict,
itemReviewed: {
'@type': item,
name: itemname,
director: director,
dateCreated: releasedate,
sameAs: wikipediaurl,
},
reviewRating: {
'@type': 'Rating',
ratingValue: rating,
},
reviewBody: review,
};
break;
case 'recipe':
schema = {
...schema,
'@type': 'Recipe',
name: headline,
prepTime: getDuration(preptime),
cookTime: getDuration(cooktime),
totalTime: getDuration(totaltime),
recipeYield: recipeyield,
nutrition: {
'@type': 'NutritionInformation',
servingSize: servingsize,
calories: colories,
fatContent: fatcontent,
},
recipeIngredient: ingredients,
recipeInstructions: instructions,
};
break;
default:
return null;
}
const breadcrumbs = {
'@context': 'http://schema.org/',
'@type': 'BreadcrumbList',
itemListElement: [
{
'@type': 'ListItem',
position: 1,
item: {
'@id': `${protocol}://${domain}/${collections[collection].slug}/`,
name: collections[collection].name,
},
},
],
};
return [
<script
type="application/ld+json"
dangerouslySetInnerHTML={{
__html: JSON.stringify(schema),
}}
/>,
<script
type="application/ld+json"
dangerouslySetInnerHTML={{
__html: JSON.stringify(breadcrumbs),
}}
/>,
];
};
|
var gulp = require("gulp");
var include = require('gulp-html-tag-include');
var runSequence = require('run-sequence');
var rename = require("gulp-rename");
/*
gulp.task('lib', function () {
return gulp.src('lib/**')
.pipe(gulp.dest('./dist/lib'))
});
gulp.task('src', function () {
return gulp.src(['navbar-top-fixed.css', 'basic.ico', 'logo-ortolang-white.png'])
.pipe(gulp.dest('./dist'))
});
*/
gulp.task('basic', function () {
// construct index.html
return gulp.src(['./basic-fr.html', './basic-en.html', './body-french.html', './body-english.html'])
.pipe(include())
.pipe(gulp.dest('./temp'));
});
gulp.task('index-en', function () {
return gulp.src('./temp/basic-en.html')
.pipe(rename('./index-en.html'))
.pipe(gulp.dest('.'));
});
gulp.task('index-fr', function () {
return gulp.src('./temp/basic-fr.html')
.pipe(rename('./index-fr.html'))
.pipe(gulp.dest('.'));
});
gulp.task('all', gulp.series('basic', 'index-fr', 'index-en'));
|
$(function () {
$(".menublock").each(function () {
var wall = new Freewall(this);
wall.reset({
animate: true,
delay: 100,
selector: '.menubutton',
cellW: 320,
cellH: 100,
gutterY: 10,
gutterX: 20,
onComplete: function () {
$(".menubutton").css("display", "block");
$(".menubutton").attr("data-state", "");
},
})
wall.fitWidth();
});
});
/* Главное меню системы */
$("#mb_fregat").click(function () {
window.location.href = baseUrl + "Fregat/fregat/mainmenu";
});
$("#mb_glauk").click(function () {
window.location.href = baseUrl + "Base/patient/glaukindex";
});
$("#mb_config").click(function () {
window.location.href = baseUrl + "Config/config/index";
});
$("#mb_changepassword").click(function () {
window.location.href = baseUrl + "Config/authuser/change-self-password";
});
/* Настройки портала */
$("#mb_usermanager").click(function () {
window.location.href = baseUrl + "Config/authuser/index";
});
$("#mb_rolemanager").click(function () {
window.location.href = baseUrl + "Config/authitem/index";
});
$("#mb_configuration").click(function () {
window.location.href = baseUrl + "Config/config/configuration";
});
/* Система "Фрегат" */
$("#mb_prihod_j").click(function () {
window.location.href = baseUrl + "Fregat/material/index";
});
$("#mb_install_j").click(function () {
window.location.href = baseUrl + "Fregat/installakt/index";
});
$("#mb_remove_j").click(function () {
window.location.href = baseUrl + "Fregat/removeakt/index";
});
$("#mb_osmotr_j").click(function () {
window.location.href = baseUrl + "Fregat/osmotrakt/index";
});
$("#mb_osmotrmat_j").click(function () {
window.location.href = baseUrl + "Fregat/osmotraktmat/index";
});
$("#mb_recovery_j").click(function () {
window.location.href = baseUrl + "Fregat/recoverysendakt/index";
});
$("#mb_spisosnov_j").click(function () {
window.location.href = baseUrl + "Fregat/spisosnovakt/index";
});
$("#mb_naklad_j").click(function () {
window.location.href = baseUrl + "Fregat/naklad/index";
});
$("#mb_spismat_j").click(function () {
window.location.href = baseUrl + "Fregat/spismat/index";
});
$("#mb_prihod_new").click(function () {
window.location.href = baseUrl + "Fregat/material/create";
});
$("#mb_install_new").click(function () {
window.location.href = baseUrl + "Fregat/installakt/create";
});
$("#mb_osmotr_new").click(function () {
window.location.href = baseUrl + "Fregat/osmotrakt/create";
});
$("#mb_recovery_new").click(function () {
window.location.href = baseUrl + "Fregat/recoverysendakt/create";
});
$("#mb_importdata").click(function () {
window.location.href = baseUrl + "Fregat/fregat/import";
});
$("#mb_sprav").click(function () {
window.location.href = baseUrl + "Fregat/fregat/sprav";
});
$("#mb_fregatoptions").click(function () {
window.location.href = baseUrl + "Fregat/fregat/options";
});
/* Регистр глаукомных пациентов \ Настройки регистра глаукомных пациентов */
$("#mb_glauksprav").click(function () {
window.location.href = baseUrl + "Fregat/fregat/sprav";
});
/* Справочники */
$("#mb_sp_matvid").click(function () {
window.location.href = baseUrl + "Fregat/matvid/index";
});
$("#mb_sp_grupa").click(function () {
window.location.href = baseUrl + "Fregat/grupa/index";
});
$("#mb_sp_organ").click(function () {
window.location.href = baseUrl + "Fregat/organ/index";
});
$("#mb_sp_reason").click(function () {
window.location.href = baseUrl + "Fregat/reason/index";
});
$("#mb_sp_schetuchet").click(function () {
window.location.href = baseUrl + "Fregat/schetuchet/index";
});
$("#mb_sp_docfiles").click(function () {
window.location.href = baseUrl + "Fregat/docfiles/index";
});
$("#mb_sp_employee").click(function () {
window.location.href = baseUrl + "Config/authuser/index?emp=1";
});
$("#mb_sp_dolzh").click(function () {
window.location.href = baseUrl + "Fregat/dolzh/index";
});
$("#mb_sp_podraz").click(function () {
window.location.href = baseUrl + "Fregat/podraz/index";
});
$("#mb_sp_build").click(function () {
window.location.href = baseUrl + "Fregat/build/index";
});
$("#mb_sp_preparat").click(function () {
window.location.href = baseUrl + "Base/preparat/index";
});
$("#mb_sp_classmkb").click(function () {
window.location.href = baseUrl + "Base/classmkb/index";
});
/* Система "Фрегат" \ Настройки системы "Фрегат" */
$("#mb_fregatimport").click(function () {
window.location.href = baseUrl + "Fregat/fregat/import";
});
$("#mb_fregatsprav").click(function () {
window.location.href = baseUrl + "Fregat/fregat/sprav";
});
$("#mb_fregatconfig").click(function () {
window.location.href = baseUrl + "Fregat/fregat/settings";
});
/* Система "Фрегат" \ Настройки системы "Фрегат" \ Импорт данных */
$("#mb_fregatimp_conf_employee").click(function () {
window.location.href = baseUrl + "Fregat/importemployee/index";
});
$("#mb_fregatimp_conf_material").click(function () {
window.location.href = baseUrl + "Fregat/importmaterial/index";
});
$("#mb_fregatimp_reports").click(function () {
window.location.href = baseUrl + "Fregat/logreport/index";
});
$("#mb_fregatimp_conf").click(function () {
window.location.href = baseUrl + "Fregat/importconfig/update";
});
|
/**
* Copyright (c) 2015, 2016 Alex Grant (@localnerve), LocalNerve LLC
* Copyrights licensed under the BSD License. See the accompanying LICENSE file for terms.
*/
'use strict';
module.exports = require('./Settings.jsx');
|
$(document).ready(function() {
$("#form-user-registration > .form-group > #input-email-address").change(function() {
var email_address = $(this).val();
});
$("#submit-form-user-registration").click(function( event ) {
event.preventDefault();
var email_address = $("#form-user-registration > .form-group > #input-email-address").val();
var username = $("#form-user-registration > .form-group > #input-username").val();
var password = $("#form-user-registration > .form-group > #input-password").val();
var confirmPassword = $("#form-user-registration > .form-group > #input-confirm-password").val();
var acceptPolicies = $("#checkbox-accept-policies").is(":checked");
if (password == confirmPassword && acceptPolicies) {
$.ajax({
url: "?action=create_user",
type: "POST",
data: JSON.stringify({
"email_address": email_address,
"username": username,
"password": password,
"acceptPolicies": acceptPolicies
}),
contentType: 'application/json; charaset=utf-8',
success: function(data) {
}
});
}
});
});
|
import expect from 'expect';
import Page from '../src/page';
describe('Page', () => {
describe('#constructor()', () => {
it('Should exist', () => {
expect(Page).toExist();
});
it('Should create an instance of Page', () => {
expect(new Page()).toBeA(Page);
});
it('Should have an empty selected array in state', () => {
expect(new Page().state.selected).toEqual([]);
});
});
});
|
goog.provide('acgraph.vector.TextSegment');
goog.require('acgraph.utils.IdGenerator');
goog.require('goog.Disposable');
/**
* Text Segment. The part of the text that have own style and params of position relative other text segments.
* TextSegment used for parsing text. Text {@link acgraph.vector.Text} is parsed on text segments.
* Cause creation of text segments maybe various - text don't fit in the defined size of text block or part of the text
* have some another style different from the rest.
* @name acgraph.vector.TextSegment
* @param {string} text Text.
* @param {acgraph.vector.TextSegmentStyle} style Style.
* @constructor
* @extends {goog.Disposable}
*
*/
acgraph.vector.TextSegment = function(text, style) {
goog.base(this);
/**
* Segment style.
* @type {acgraph.vector.TextSegmentStyle}
* @private
*/
this.style_ = style || {};
/**
* Segment text.
* @type {string}
*/
this.text = text;
/**
* Is first text segment in line.
* @type {boolean}
*/
this.firstInLine = false;
/**
* Distance between the top of the segment and its baseline.
* @type {number}
*/
this.baseLine = 0;
/**
* Segment width.
* @type {number}
*/
this.width = 0;
/**
* Segment height.
* @type {number}
*/
this.height = 0;
/**
* Segment X offset.
* @type {number}
*/
this.dx = 0;
/**
* Segment Y offset.
* @type {number}
*/
this.dy = 0;
/**
* Coordinate X in parent coordinate system.
* @type {number}
*/
this.x = 0;
/**
* Coordinate Y in parent coordinate system.
* @type {number}
*/
this.y = 0;
};
goog.inherits(acgraph.vector.TextSegment, goog.Disposable);
/**
* DOM element.
* @private
* @type {Element}
*/
acgraph.vector.TextSegment.prototype.domElement_ = null;
/**
* Parent container. For the text segment of parent is text element.
* @type {acgraph.vector.Text}
* @private
*/
acgraph.vector.TextSegment.prototype.parent_ = null;
/**
* If opt_value is passed and is not null, adds the TextSegment to a passed Text as a child and returns itself.
* If null passed - removes the TextSegment from current Text and returns itself.
* If nothing passed - returns current parent Text.
* @param {acgraph.vector.Text=} opt_value Parent - text element.
* @return {(acgraph.vector.TextSegment|acgraph.vector.Text)} Returns parent text or itself depending on
* opt_value presence.
*/
acgraph.vector.TextSegment.prototype.parent = function(opt_value) {
if (goog.isDef(opt_value)) {
this.parent_ = opt_value;
return this;
} else
return this.parent_;
};
/**
* Returns DOM element.
* @return {Element} DOM Element.
*/
acgraph.vector.TextSegment.prototype.domElement = function() {
return this.domElement_;
};
/**
* Returns type prefix.
* @return {acgraph.utils.IdGenerator.ElementTypePrefix} Type prfix.
*/
acgraph.vector.TextSegment.prototype.getElementTypePrefix = function() {
return acgraph.utils.IdGenerator.ElementTypePrefix.TEXT_SEGMENT;
};
/**
* Returns segment style.
* @return {acgraph.vector.TextSegmentStyle} Style.
*/
acgraph.vector.TextSegment.prototype.getStyle = function() {
return this.style_;
};
/**
* Sets segment style.
* @param {acgraph.vector.TextSegmentStyle} value Style.
*/
acgraph.vector.TextSegment.prototype.setStyle = function(value) {
this.style_ = value;
};
//----------------------------------------------------------------------------------------------------------------------
//
// Rendering
//
//----------------------------------------------------------------------------------------------------------------------
/**
* Set position for text segment.
*/
acgraph.vector.TextSegment.prototype.setTextSegmentPosition = function() {
if (this.domElement_) acgraph.getRenderer().setTextSegmentPosition(this);
};
/**
* Set style, events and others properties for text segment.
*/
acgraph.vector.TextSegment.prototype.setTextSegmentProperties = function() {
if (this.domElement_) acgraph.getRenderer().setTextSegmentProperties(this);
};
/**
* Set text for text segment.
*/
acgraph.vector.TextSegment.prototype.renderData = function() {
if (this.text == '') return;
this.domElement_ = acgraph.getRenderer().createTextSegmentElement();
this.setTextSegmentProperties();
};
//----------------------------------------------------------------------------------------------------------------------
//
// Disposing
//
//----------------------------------------------------------------------------------------------------------------------
/** @inheritDoc */
acgraph.vector.TextSegment.prototype.disposeInternal = function() {
goog.dom.removeNode(this.domElement_);
this.domElement_ = null;
goog.base(this, 'disposeInternal');
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.