text
stringlengths 2
6.14k
|
|---|
// Localization
module.exports = function localizationInitializer() {
var i18n = require('../extensions/i18n-namespace')
, i18nConfiguration = {
defaultLocale : 'en',
locales:['en', 'fr'],
directory: __dirname + '/../../app/locales/',
updateFiles: false,
cookie: 'lang'
};
// lambda for hogan-express
this.set('lambdas', {
"localizeLambda": function(text, hogan, context){
return text;
}
});
switch (this.env) {
case 'production':
break;
case 'staging' :
break;
case 'development' :
i18nConfiguration.updateFiles = true;
break;
}
i18n.configure(i18nConfiguration);
};
|
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
"use strict";
// Tests changing viewport DPR
const TEST_URL = "data:text/html;charset=utf-8,DPR list test";
const DEFAULT_DPPX = window.devicePixelRatio;
const VIEWPORT_DPPX = DEFAULT_DPPX + 2;
const Types = require("devtools/client/responsive.html/types");
const testDevice = {
"name": "Fake Phone RDM Test",
"width": 320,
"height": 470,
"pixelRatio": 5.5,
"userAgent": "Mozilla/5.0 (Mobile; rv:39.0) Gecko/39.0 Firefox/39.0",
"touch": true,
"firefoxOS": true,
"os": "custom",
"featured": true,
};
// Add the new device to the list
addDeviceForTest(testDevice);
addRDMTask(TEST_URL, function* ({ ui, manager }) {
yield waitStartup(ui);
yield testDefaults(ui);
yield testChangingDevice(ui);
yield testResetWhenResizingViewport(ui);
yield testChangingDPR(ui);
});
function* waitStartup(ui) {
let { store } = ui.toolWindow;
// Wait until the viewport has been added and the device list has been loaded
yield waitUntilState(store, state => state.viewports.length == 1
&& state.devices.listState == Types.deviceListState.LOADED);
}
function* testDefaults(ui) {
info("Test Defaults");
yield testDevicePixelRatio(ui, window.devicePixelRatio);
testViewportDPRSelect(ui, {value: window.devicePixelRatio, disabled: false});
testViewportDeviceSelectLabel(ui, "no device selected");
}
function* testChangingDevice(ui) {
info("Test Changing Device");
let waitPixelRatioChange = onceDevicePixelRatioChange(ui);
yield selectDevice(ui, testDevice.name);
yield waitForViewportResizeTo(ui, testDevice.width, testDevice.height);
yield waitPixelRatioChange;
yield testDevicePixelRatio(ui, testDevice.pixelRatio);
testViewportDPRSelect(ui, {value: testDevice.pixelRatio, disabled: true});
testViewportDeviceSelectLabel(ui, testDevice.name);
}
function* testResetWhenResizingViewport(ui) {
info("Test reset when resizing the viewport");
let waitPixelRatioChange = onceDevicePixelRatioChange(ui);
let deviceRemoved = once(ui, "device-removed");
yield testViewportResize(ui, ".viewport-vertical-resize-handle",
[-10, -10], [testDevice.width, testDevice.height - 10], [0, -10], ui);
yield deviceRemoved;
yield waitPixelRatioChange;
yield testDevicePixelRatio(ui, window.devicePixelRatio);
testViewportDPRSelect(ui, {value: window.devicePixelRatio, disabled: false});
testViewportDeviceSelectLabel(ui, "no device selected");
}
function* testChangingDPR(ui) {
info("Test changing device pixel ratio");
let waitPixelRatioChange = onceDevicePixelRatioChange(ui);
yield selectDPR(ui, VIEWPORT_DPPX);
yield waitPixelRatioChange;
yield testDevicePixelRatio(ui, VIEWPORT_DPPX);
testViewportDPRSelect(ui, {value: VIEWPORT_DPPX, disabled: false});
testViewportDeviceSelectLabel(ui, "no device selected");
}
function testViewportDPRSelect(ui, expected) {
info("Test viewport's DPR Select");
let select = ui.toolWindow.document.querySelector("#global-dpr-selector > select");
is(select.value, expected.value,
`DPR Select value should be: ${expected.value}`);
is(select.disabled, expected.disabled,
`DPR Select should be ${expected.disabled ? "disabled" : "enabled"}.`);
}
function* testDevicePixelRatio(ui, expected) {
info("Test device pixel ratio");
let dppx = yield getViewportDevicePixelRatio(ui);
is(dppx, expected, `devicePixelRatio should be: ${expected}`);
}
function* getViewportDevicePixelRatio(ui) {
return yield ContentTask.spawn(ui.getViewportBrowser(), {}, function* () {
return content.devicePixelRatio;
});
}
function onceDevicePixelRatioChange(ui) {
return ContentTask.spawn(ui.getViewportBrowser(), {}, function* () {
info(`Listening for a pixel ratio change (current: ${content.devicePixelRatio}dppx)`);
let pixelRatio = content.devicePixelRatio;
let mql = content.matchMedia(`(resolution: ${pixelRatio}dppx)`);
return new Promise(resolve => {
const onWindowCreated = () => {
if (pixelRatio !== content.devicePixelRatio) {
resolve();
}
};
addEventListener("DOMWindowCreated", onWindowCreated, {once: true});
mql.addListener(function listener() {
mql.removeListener(listener);
removeEventListener("DOMWindowCreated", onWindowCreated, {once: true});
resolve();
});
});
});
}
|
import React from 'react';
import PropTypes from 'prop-types';
import logo from '../img/ff-logo.png';
const DevHomework = props => (
<div className="homework">
<div className="container">
<img className="homework__logo" alt="Firefox Logo" src={logo} />
<h2 className="homework__title">{props.title}</h2>
<div className="row">
<div className="homework__content">{props.children}</div>
</div>
</div>
</div>
);
DevHomework.PropTypes = {
title: PropTypes.string.isRequired,
};
export default DevHomework;
|
angular.module('moviematch.movieinput', [])
.controller('MovieInputController', function($scope, $http, $location, Session, RequestFactory, $uibModalInstance) {
$scope.movieTitle = "";
$scope.searchResults;
$scope.movieChoices = [];
$scope.error;
// Get movies and assigns them to $scope.searchResults
$scope.fetchSearchResults = function() {
RequestFactory.omdbSearch($scope.movieTitle)
.then(function(res){
var data = JSON.parse(res.data);
$scope.searchResults = data.Search;
});
};
// Adds and removes movies from $scope.movieChoices
// Assigns error messages if > 5 movies chosen
$scope.updateMovies = function(add, movie) {
if (add && $scope.movieChoices.length < 5 ) {
$scope.movieChoices.push(movie);
} else if (!add) {
$scope.movieChoices.splice(movie, 1);
$scope.error = null;
} else {
$scope.error = "Already 5 movies!!";
}
};
// Fired when user completes movie picks
$scope.readyToVote = function($http) {
// Make array of imdb_IDs from movie picks
var movies = _.map($scope.movieChoices, function(movie) {
return movie.imdbID;
})
Session.getSession()
.then(function(session) {
var options = {
session_id: session.id,
movies: movies
};
// send IMDB_ID of movies picks to server
RequestFactory.addMovies(options)
.then(function() {
// send data back to '/loading'
$uibModalInstance.close($scope.movieChoices);
});
});
};
/** POP-UP SPECIFIC FUNCTIONS **/
$scope.ready = function() {
$location.path('/loading')
}
$scope.cancel = function () {
$uibModalInstance.dismiss('cancel');
};
/******************************/
// Watch for changes in searchbar for live search
$scope.$watch('movieTitle', $scope.fetchSearchResults);
})
.factory('RequestFactory', function($http) {
// Makes request to omdb API and returns results in a promise
var omdbSearch = function(movieTitle) {
return $http({
method: 'GET',
url: '/api/omdb/search/' + movieTitle
});
};
// Makes request to movieDB API and returns results in a promise
var movieDB = function() {
return $http({
method: 'GET',
url: '/api/movieDB/'
});
};
// Makes request to add movies to database and returns nothing
var addMovies = function(data) {
return $http({
method: 'POST',
url: '/api/moviesTODO',
data: data
});
};
return {
omdbSearch: omdbSearch,
movieDB: movieDB,
addMovies: addMovies
};
});
|
/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
/* vim: set ft=javascript ts=2 et sw=2 tw=80: */
/* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/publicdomain/zero/1.0/ */
// Test that makes sure web console eval happens in the user-selected stackframe
// from the js debugger.
"use strict";
const TEST_URI = "http://example.com/browser/devtools/client/webconsole/" +
"test/test-eval-in-stackframe.html";
var gWebConsole, gJSTerm, gDebuggerWin, gThread, gDebuggerController;
var gStackframes;
// Force the old debugger UI since it's directly used (see Bug 1301705)
Services.prefs.setBoolPref("devtools.debugger.new-debugger-frontend", false);
registerCleanupFunction(function* () {
Services.prefs.clearUserPref("devtools.debugger.new-debugger-frontend");
});
function test() {
loadTab(TEST_URI).then(() => {
openConsole().then(consoleOpened);
});
}
function consoleOpened(hud) {
gWebConsole = hud;
gJSTerm = hud.jsterm;
gJSTerm.execute("foo").then(onExecuteFoo);
}
function onExecuteFoo() {
isnot(gWebConsole.outputNode.textContent.indexOf("globalFooBug783499"), -1,
"|foo| value is correct");
gJSTerm.clearOutput();
// Test for Bug 690529 - Web Console and Scratchpad should evaluate
// expressions in the scope of the content window, not in a sandbox.
executeSoon(() => {
gJSTerm.execute("foo2 = 'newFoo'; window.foo2").then(onNewFoo2);
});
}
function onNewFoo2(msg) {
is(gWebConsole.outputNode.textContent.indexOf("undefined"), -1,
"|undefined| is not displayed after adding |foo2|");
ok(msg, "output result found");
isnot(msg.textContent.indexOf("newFoo"), -1,
"'newFoo' is displayed after adding |foo2|");
gJSTerm.clearOutput();
info("openDebugger");
executeSoon(() => openDebugger().then(debuggerOpened));
}
function debuggerOpened(aResult) {
gDebuggerWin = aResult.panelWin;
gDebuggerController = gDebuggerWin.DebuggerController;
gThread = gDebuggerController.activeThread;
gStackframes = gDebuggerController.StackFrames;
info("openConsole");
executeSoon(() =>
openConsole().then(() =>
gJSTerm.execute("foo + foo2").then(onExecuteFooAndFoo2)
)
);
}
function onExecuteFooAndFoo2() {
let expected = "globalFooBug783499newFoo";
isnot(gWebConsole.outputNode.textContent.indexOf(expected), -1,
"|foo + foo2| is displayed after starting the debugger");
executeSoon(() => {
gJSTerm.clearOutput();
info("openDebugger");
openDebugger().then(() => {
gThread.addOneTimeListener("framesadded", onFramesAdded);
info("firstCall()");
ContentTask.spawn(gBrowser.selectedBrowser, {}, function* () {
content.wrappedJSObject.firstCall();
});
});
});
}
function onFramesAdded() {
info("onFramesAdded, openConsole() now");
executeSoon(() =>
openConsole().then(() =>
gJSTerm.execute("foo + foo2").then(onExecuteFooAndFoo2InSecondCall)
)
);
}
function onExecuteFooAndFoo2InSecondCall() {
let expected = "globalFooBug783499foo2SecondCall";
isnot(gWebConsole.outputNode.textContent.indexOf(expected), -1,
"|foo + foo2| from |secondCall()|");
function runOpenConsole() {
openConsole().then(() => {
gJSTerm.execute("foo + foo2 + foo3").then(onExecuteFoo23InFirstCall);
});
}
executeSoon(() => {
gJSTerm.clearOutput();
info("openDebugger and selectFrame(1)");
openDebugger().then(() => {
gStackframes.selectFrame(1);
info("openConsole");
executeSoon(() => runOpenConsole());
});
});
}
function onExecuteFoo23InFirstCall() {
let expected = "fooFirstCallnewFoofoo3FirstCall";
isnot(gWebConsole.outputNode.textContent.indexOf(expected), -1,
"|foo + foo2 + foo3| from |firstCall()|");
executeSoon(() =>
gJSTerm.execute("foo = 'abba'; foo3 = 'bug783499'; foo + foo3").then(
onExecuteFooAndFoo3ChangesInFirstCall));
}
var onExecuteFooAndFoo3ChangesInFirstCall = Task.async(function*() {
let expected = "abbabug783499";
isnot(gWebConsole.outputNode.textContent.indexOf(expected), -1,
"|foo + foo3| updated in |firstCall()|");
yield ContentTask.spawn(gBrowser.selectedBrowser, null, function*() {
is(content.wrappedJSObject.foo, "globalFooBug783499",
"|foo| in content window");
is(content.wrappedJSObject.foo2, "newFoo", "|foo2| in content window");
ok(!content.wrappedJSObject.foo3,
"|foo3| was not added to the content window");
});
gWebConsole = gJSTerm = gDebuggerWin = gThread = gDebuggerController =
gStackframes = null;
executeSoon(finishTest);
});
|
/*global describe, it, assert, clone */
/*jshint browser: true */
describe('clone', function () {
'use strict';
it('should clone an object', function () {
var obj = {
cats: true,
dogs: 2,
fish: [ 0, 1, 2 ]
};
var c = clone(obj);
obj.cats = false;
obj.dogs = 1;
obj.fish[0] = 'stuff';
assert.strictEqual(c.cats, true);
assert.strictEqual(c.dogs, 2);
assert.deepEqual(c.fish, [0, 1, 2]);
});
it('should clone nested objects', function () {
var obj = {
cats: {
fred: 1,
billy: 2,
meow: true
},
dogs: {
spot: 1,
max: 2,
woof: [ 0, 1, 2 ]
},
fish: [ 0, 1, 2 ]
};
var c = clone(obj);
obj.cats.fred = 47;
obj.dogs = 47;
obj.fish[0] = 'stuff';
assert.deepEqual(c.cats, {
fred: 1,
billy: 2,
meow: true
});
assert.deepEqual(c.dogs, {
spot: 1,
max: 2,
woof: [ 0, 1, 2 ]
});
assert.deepEqual(c.fish, [ 0, 1, 2]);
});
it('should clone objects with methods', function () {
var obj = {
cats: function () { return 'meow'; },
dogs: function () { return 'woof'; }
};
var c = clone(obj);
assert.strictEqual(obj.cats, c.cats);
assert.strictEqual(obj.dogs, c.dogs);
obj.cats = function () {};
obj.dogs = function () {};
assert.notStrictEqual(obj.cats, c.cats);
assert.notStrictEqual(obj.dogs, c.dogs);
});
it('should clone prototypes', function () {
function Cat(name) {
this.name = name;
}
Cat.prototype.meow = function () {
return 'meow';
};
Cat.prototype.bark = function () {
return 'cats dont bark';
};
var cat = new Cat('Fred'),
c = clone(cat);
assert.deepEqual(cat.name, c.name);
assert.deepEqual(Cat.prototype.bark, c.bark);
assert.deepEqual(Cat.prototype.meow, c.meow);
});
});
|
/*global define*/
define('app/panels-time-active', ['moment', 'lodash', 'TelemetryPromises', 'DevToolsMetrics', 'DEVTOOLS_PANELS', 'LatestVersions', 'FIREFOX_RELEASES'],
function(moment, _, T, DevToolsMetrics, DEVTOOLS_PANELS, LatestVersions, FIREFOX_RELEASES) {
var metrics = DEVTOOLS_PANELS.map((m) => {
return { label: m.label, metric: m.metric.time_active, color: m.color };
});
var CHART_DEFAULTS = {
title: 'All DevTools Panels Time Actively Spent',
description: 'Time per panel grouped and plotted together with all other panels (log scale)',
color_accessor: 'panel',
color_domain: metrics.map((m) => m.label),
color_range: metrics.map((m) => m.color),
y_scale_type: 'log',
width: 515,
height: 320,
left: 60
};
var DEFAULT_OPTIONS = {
sanitized: true
};
var ALL_DATA = {};
var ID = 'devtools-toolbox-panels-time-active-chart';
function evolutionMap(panel, evolutions) {
// map the data into the values we need
// histogram, index, date
return evolutions.map((h, i, date) => {
return {
panel: panel,
value: (moment.duration(h.mean(), 'seconds').minutes()),
submissions: h.submissions,
date: date
};
});
}
return {
graph: function(channel = 'beta', chart = {}, options = {}) {
chart = _.defaults(chart, CHART_DEFAULTS);
chart.markers = FIREFOX_RELEASES[channel];
options = _.defaults(options, DEFAULT_OPTIONS);
// draw initial empty chart
DevToolsMetrics.line(ID, chart);
return LatestVersions.getLatestVersion().then((versions) => {
var fxChannel = _.find(versions, { channel: channel });
var total = fxChannel.versions.length;
var current = total;
return Promise.all(metrics.map((m) => {
return T.getEvolutions(fxChannel.channel, fxChannel.versions, m.metric, options).then(function (evo) {
// update progress meter when we have data
DevToolsMetrics.progress(ID, total, current -= 1);
return evo;
}).catch(function () {
// update progress meter when telemetry returned nothing
DevToolsMetrics.progress(ID, total, current -= 1);
return null;
}).
then((evolutions) => T.reduceEvolutions(evolutions)).
then((evolutions) => evolutionMap(m.label, evolutions)).
then(_.flatten);
})).then(_.flatten). // flatten again because we want one big cluster of data
then((data) => {
// cache data for lata
ALL_DATA[channel] = data;
chart.data = data;
DevToolsMetrics.point(ID, chart);
return data;
});
});
}
};
}); // end define
|
var __windowDictionary = {
selectedGrammar: [],
selectedLanguage: "",
initialize: {
C: false,
Python: false
}
}
$(function() {
function updateTips( t ) {
tips
.text( t )
.addClass( "ui-state-highlight" );
setTimeout(function() {
tips.removeClass( "ui-state-highlight", 1500 );
setTimeout(function(){
tips.html("All form fields are required.");
}, 1500)
}, 500 );
}
function checkLength( o, n, min, max ) {
if ( o.val().length > max || o.val().length < min ) {
o.addClass( "ui-state-error" );
updateTips( "Length of " + n + " must be between " +
min + " and " + max + "." );
return false;
} else {
return true;
}
}
function checkRegexp( o, regexp, n ) {
if ( !( regexp.test( o.val() ) ) ) {
o.addClass( "ui-state-error" );
updateTips( n );
return false;
} else {
return true;
}
}
function checkLengthNum( o, n, min, max ) {
if ( o.val().length > max || o.val().length < min ) {
o.addClass( "ui-state-error" );
updateTips( "Length of " + n + " must be between " +
min + " and " + max + "." );
return false;
} else {
try {
if (parseInt(o.val() == NaN)) {
throw "Not a number exception";
}
return true;
}
catch (exception) {
o.addClass( "ui-state-error" );
updateTips("Value must be number");
return false;
}
}
}
$( "#dictionaryWindow" ).dialog({
autoOpen: false,
resizable: true,
height: 500,
width: 800,
modal: true,
buttons: {
},
open: function() {
},
close: function() {
}
});
$("#supportedLanguageList").fancytree({
activate: function(event, data) {
__windowDictionary.selectedLanguage = data.node.title;
if (__windowDictionary.selectedLanguage == "Python") {
if (__windowDictionary.initialize.Python == false) {
dictionary.python.initialize();
__windowDictionary.initialize.Python = true;
}
}
else if (__windowDictionary.selectedLanguage == "C") {
if (__windowDictionary.initialize.C == false) {
dictionary.c.initialize();
__windowDictionary.initialize.C = true;
}
}
var functionTree = [];
var funcList = dictionary.pages.findWordsByKeywords([__windowDictionary.selectedLanguage + "-language"]);
for (var i = 0; i < funcList.length; i++) {
var cFunc = dictionary.pages.word[funcList[i].index];
var rType = cFunc.returnType == 0 ? "void" : cFunc.returnType;
var func = {title: cFunc.name + " : " + rType, folder: false, key: funcList[i].index, children: []};
functionTree.push(func);
}
$("#dictionaryFunctionList").fancytree("getTree").reload(functionTree);
},
deactivate: function(event, data) {
$("#echoSelected").text("-");
},
focus: function(event, data) {
$("#echoFocused").text(data.node.title);
},
blur: function(event, data) {
$("#echoFocused").text("-");
},
lazyLoad: function(event, data){
// Simulate a slow ajax request
var dfd = new $.Deferred()
data.result = dfd;
window.setTimeout(function(){
dfd.resolve([
{ title: 'Lazy node 1', lazy: true },
{ title: 'Simple node 2', select: true }
]);
}, 1500);
},
source: [
{title: "C", data: "C", key: 1, folder: true},
{title: "Python", data: "Python", key: 2, folder: true}
]
});
$("#dictionaryFunctionList").fancytree({
activate: function(event, data) {
var functionText = dictionary.pages.word[data.node.key].function.toString();
$("#functionCode").val(functionText);
//editAreaLoader.setValue("functionCode", functionText);
},
select: function(event, data) {
var selNodes = data.tree.getSelectedNodes(true);
__windowDictionary.selectedGrammar = selNodes;
},
lazyLoad: function(event, data){
// Simulate a slow ajax request
var dfd = new $.Deferred()
data.result = dfd;
window.setTimeout(function(){
dfd.resolve([
{ title: 'Lazy node 1', lazy: true },
{ title: 'Simple node 2', select: true }
]);
}, 1500);
},
source: [
]
});
$("#addFunction").on("click", function(){
if (__windowDictionary.selectedLanguage != "") {
}
else {
$( "#addNewGrammar_error_noLanguage" ).dialog("open");
}
});
$("#deleteFunction").on("click", function(){
var funcSelList = __windowDictionary.selectedGrammar;
var funcList = dictionary.pages.findWordsByKeywords([__windowDictionary.selectedLanguage + "-language"]);
for (var i = 0; i < funcList.length; i++) {
var found = false;
var selectionIndex = -1;
for (var j = 0; j < funcSelList.length; j++) {
if (funcList[i].name == dictionary.pages.word[funcSelList[j].key].name) {
found = true;
selectionIndex = j;
dictionary.pages.word.splice(funcSelList[j].key, 1);
break;
}
}
if (found) {
i--;
funcList.splice(i, 1);
funcSelList.splice(j, 1);
}
}
var functionTree = [];
var funcList = dictionary.pages.findWordsByKeywords([__windowDictionary.selectedLanguage + "-language"]);
for (var i = 0; i < funcList.length; i++) {
var cFunc = dictionary.pages.word[funcList[i].index];
var rType = cFunc.returnType == 0 ? "void" : cFunc.returnType;
var func = {title: cFunc.name + " : " + rType, folder: false, key: funcList[i].index, children: []};
functionTree.push(func);
}
$("#dictionaryFunctionList").fancytree("getTree").reload(functionTree);
});
$("#functionCode").val("");
/*editAreaLoader.init({
id: "functionCode"
,start_highlight: true
,word_wrap: true
,language: "en"
,syntax: "python"
});
editAreaLoader.setValue("functionCode", "");*/
});
|
'use strict';
/**
* @module emitters/AdvancedEmitter
*/
var events = require('events');
var util = require('util');
var AdvancedEvent = process.requireApi('lib/emitters/AdvancedEvent.js');
/**
* Defines an AdvancedEmitter which wraps an EventEmitter.
*
* An AdvancedEmitter works pretty much the same as the default Node.js EventEmitter
* excepts that it adds a new method to emit an AdvancedEvent to have the event's name
* as the first argument of the handler function.
*
* It helps emit an event with the name of the event as the first argument.
*
* @example
* var AdvancedEmitter = require('@openveo/api').emitters.AdvancedEmitter;
* var AdvancedEvent = require('@openveo/api').emitters.AdvancedEvent;
*
* var emitter = new AdvancedEmitter();
* emitter.emitEvent(new AdvancedEvent('eventName', param1, param2, ...));
*
* emitter.on('eventName', function(eventName, param1, param2, ...) {
* console.log(eventName); // Output "eventName"
* });
*
* @class AdvancedEmitter
* @extends EventEmitter
* @see {@link https://nodejs.org/dist/latest-v16.x/docs/api/events.html#events_class_eventemitter}
* @constructor
*/
function AdvancedEmitter() {
AdvancedEmitter.super_.call(this);
}
module.exports = AdvancedEmitter;
util.inherits(AdvancedEmitter, events.EventEmitter);
/**
* Emits an AdvancedEvent by emitting its constructor's arguments.
*
* @param {module:emitters/AdvancedEvent~AdvancedEvent} event The advanced event to emit
*/
AdvancedEmitter.prototype.emitEvent = function(event) {
if (event instanceof AdvancedEvent)
this.emit.apply(this, event.arguments);
};
|
define(function(require) {
'use strict';
var PIXI = require('pixi');
var EnergyConverterView = require('views/energy-converter');
var Assets = require('assets');
var Constants = require('constants');
var ElectricalGenerator = Constants.ElectricalGenerator;
var ElectricalGeneratorView = EnergyConverterView.extend({
/**
*
*/
initialize: function(options) {
EnergyConverterView.prototype.initialize.apply(this, [options]);
this.listenTo(this.model, 'change:wheelRotationalAngle', this.updateWheelRotation);
this.listenTo(this.model, 'change:directCouplingMode', this.directCouplingModeChanged);
},
initGraphics: function() {
EnergyConverterView.prototype.initGraphics.apply(this);
this.backLayer = new PIXI.Container();
this.frontLayer = new PIXI.Container();
this.createEnergyChunkCollectionView('electricalEnergyChunkLayer', this.model.electricalEnergyChunks);
this.createEnergyChunkCollectionView('hiddenEnergyChunkLayer', this.model.hiddenEnergyChunks);
var curvedWire = this.createSpriteWithOffset(Assets.Images.WIRE_BLACK_LEFT, ElectricalGenerator.WIRE_OFFSET);
var housing = this.createSpriteWithOffset(Assets.Images.GENERATOR);
var connector = this.createSpriteWithOffset(Assets.Images.CONNECTOR, ElectricalGenerator.CONNECTOR_OFFSET);
var spokes = this.createSpriteWithOffset(Assets.Images.GENERATOR_WHEEL_SPOKES, ElectricalGenerator.WHEEL_CENTER_OFFSET, 0.5);
var paddles = this.createSpriteWithOffset(Assets.Images.GENERATOR_WHEEL_PADDLES, ElectricalGenerator.WHEEL_CENTER_OFFSET, 0.5);
var hub = this.createSpriteWithOffset(Assets.Images.GENERATOR_WHEEL_HUB_2, ElectricalGenerator.WHEEL_CENTER_OFFSET, 0.5);
// Need to fudge the position a little...
curvedWire.x += 2;
this.backLayer.addChild(curvedWire);
this.frontLayer.addChild(housing);
this.frontLayer.addChild(connector);
this.frontLayer.addChild(spokes);
this.frontLayer.addChild(paddles);
this.frontLayer.addChild(hub);
this.spokes = spokes;
this.paddles = paddles;
//this.drawDebugOrigin(this.frontLayer);
},
updatePosition: function(model, position) {
var viewPoint = this.mvt.modelToView(position);
this.backLayer.x = this.frontLayer.x = viewPoint.x;
this.backLayer.y = this.frontLayer.y = viewPoint.y;
},
updateWheelRotation: function(model, rotation) {
this.spokes.rotation = -rotation;
this.paddles.rotation = -rotation;
},
directCouplingModeChanged: function(model, directCouplingMode) {
this.paddles.visible = !directCouplingMode;
this.spokes.visible = directCouplingMode;
}
});
return ElectricalGeneratorView;
});
|
define([
'backbone.associations',
'../qt_basemodel'
],
function (Backbone,BaseModel) {
'use strict';
return BaseModel.extend({
defaults: {
url : '',
uuid : '',
title : '',
preset : '', //url du preset
sub_processor : '', //url du subprocessor
parameters_schema : '' //schema des paramètres
},
relations: [],
//////////////////////////////////////////
});
});
|
import React from 'react';
import InputSelectImage from '../../../src/js/components/RegisterFields/InputSelectImage/InputSelectImage.js';
import { shallow, configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
configure({ adapter: new Adapter() });
describe('Test InputSelectImage component', () => {
const mockFn = jest.fn();
const options = [
{
id: "lorem",
text: "Lorem",
image: "http://via.placeholder.com/300x300"
},
{
id: "ipsum",
text: "Ipsum",
image: "http://via.placeholder.com/300x300"
},
{
id: "lorem-ipsum",
text: "Lorem ipsum",
image: "http://via.placeholder.com/300x300"
},
{
id: "sed-ut-perspiciatis",
text: "Sed ut perspiciatis",
image: "http://via.placeholder.com/300x300"
},
{
id: "perspiciatis",
text: "perspiciatis",
image: "http://via.placeholder.com/300x300"
},
];
const inputSelectImage = shallow(<InputSelectImage options={options} placeholder={"Foo"} onClickHandler={mockFn}/>);
it('should be defined', () => {
expect(inputSelectImage).toBeDefined();
});
it('should render correctly', () => {
expect(inputSelectImage).toMatchSnapshot();
});
});
|
#!/usr/bin/env node
var fs = require('fs');
var path = require('path');
var sys = require('sys');
var exec = require('child_process').exec;
var rootdir = process.argv[2];
if (rootdir) {
exec("gulp", function puts(error, stdout, stderr) {
sys.puts(error);
sys.puts(stderr);
sys.puts(stdout);
if (error) {
process.exit(1);
}
});
}
|
'use strict';
var util = require('util');
var Promise = require('bluebird');
var uuid = require('../../utils/uuid');
var errors = require('../../errors');
var EmbeddedModel = require('../../EmbeddedModel');
// Schema Validator
// ----------------
var validator = require('jjv')();
validator.addSchema(require('../../schemas/cycle'));
// EmbeddedModel Constructor
// -------------------------
function Status (conn, data, parent) {
return EmbeddedModel.call(this, conn, data, parent)
.then(function(self) {
// check authorizations
if(!self.parent.authorizations['cycle/statuses:read'])
return Promise.reject(new errors.ForbiddenError());
// cycle_id
self.cycle_id = self.parent.id;
return self;
});
}
// EmbeddedModel Configuration
// ---------------------------
Status.key = 'statuses';
Status.collections = {};
Status.validate = function(data) {
return validator.validate('http://www.gandhi.io/schema/cycle#/definitions/status', data, {useDefault: true, removeAdditional: true});
};
Status.create = function(conn, data, parent) {
if(!parent.authorizations['cycle/statuses:write'])
return Promise.reject(new errors.ForbiddenError());
// generate a new uuid
data.id = uuid();
var err = Status.validate(data);
if(err) return Promise.reject(new errors.ValidationError('The input is invalid.', err));
return new Status(conn, data, parent)
.then(function(status) {
return status.save(conn);
});
};
// Public Methods
// --------------
util.inherits(Status, EmbeddedModel);
// check authorizations for update
Status.prototype.update = function(conn, delta) {
var self = this;
if(!self.parent.authorizations['cycle/statuses:write'])
return Promise.reject(new errors.ForbiddenError());
return EmbeddedModel.prototype.update.call(self, conn, delta);
};
// check authorizations for delete
Status.prototype.delete = function(conn) {
var self = this;
if(!self.parent.authorizations['cycle/statuses:write'])
return Promise.reject(new errors.ForbiddenError());
return EmbeddedModel.prototype.delete.call(self, conn);
};
module.exports = Status;
|
function humanize(string) {
string = string.replace(/-/g, ' ');
string = string.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
return string;
}
function randomString() {
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
var string_length = 32;
var randomstring = '';
for (var i=0; i<string_length; i++) {
var rnum = Math.floor(Math.random() * chars.length);
randomstring += chars.substring(rnum,rnum+1);
}
return randomstring;
}
function ISODateString(d){
function pad(n){return n<10 ? '0'+n : n}
return d.getUTCFullYear()+'-'
+ pad(d.getUTCMonth()+1)+'-'
+ pad(d.getUTCDate())+'T'
+ pad(d.getUTCHours())+':'
+ pad(d.getUTCMinutes())+':'
+ pad(d.getUTCSeconds())+'Z'
}
var generateUserToken = function( m_conn ) {
var S4 = function() {
return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
};
token = S4()+S4()+S4()+S4()+S4()+S4();
m_conn.set( memcachePrefix + token, '1', memcache_memorize_time, function( err ) {
if (err) {
if (debug) console.log("MEMCACHE ERROR DURING SET");
}
});
return token;
}
|
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import $ from 'jquery'
import _ from 'lodash'
import 'bootstrap/dist/css/bootstrap.css'
import 'bootstrap/dist/js/bootstrap.min.js'
require('jquery-ui-bundle');
/* eslint-disable no-new */
new Vue({
el: '#app',
template: '<App/>',
components: { App }
});
|
/*=========================================================================================
File Name: stacked-clustered-column.js
Description: echarts stacked clustered column chart
----------------------------------------------------------------------------------------
Item Name: Stack - Responsive Admin Theme
Version: 2.0
Author: PIXINVENT
Author URL: http://www.themeforest.net/user/pixinvent
==========================================================================================*/
// Stacked clustered column chart
// ------------------------------
$(window).on("load", function(){
// Set paths
// ------------------------------
require.config({
paths: {
echarts: '../../../app-assets/vendors/js/charts/echarts'
}
});
// Configuration
// ------------------------------
require(
[
'echarts',
'echarts/chart/bar',
'echarts/chart/line'
],
// Charts setup
function (ec) {
// Initialize chart
// ------------------------------
var myChart = ec.init(document.getElementById('stacked-clustered-column'));
// Chart Options
// ------------------------------
chartOptions = {
// Setup grid
grid: {
x: 40,
x2: 20,
y: 70,
y2: 30
},
// Add tooltip
tooltip: {
trigger: 'axis'
},
// Add legend
legend: {
data: [
'ECharts1 - 2k Data','ECharts1 - 2w Data','ECharts1 - 20w Data','',
'ECharts2 - 2k Data','ECharts2 - 2w Data','ECharts2 - 20w Data'
]
},
// Enable drag recalculate
calculable: true,
// Horizontal axis
xAxis: [{
type : 'category',
data : ['Line','Bar','Scatter','K','Map']
},
{
type : 'category',
axisLine: {show:false},
axisTick: {show:false},
axisLabel: {show:false},
splitArea: {show:false},
splitLine: {show:false},
data : ['Line','Bar','Scatter','K','Map']
}
],
// Vertical axis
yAxis: [{
type : 'value',
axisLabel:{formatter:'{value} ms'}
}],
// Add series
series : [
{
name:'ECharts2 - 2k Data',
type:'bar',
itemStyle: {normal: {color:'rgba(22,211,154,1)', label:{show:true}}},
data:[40,155,95,75, 0]
},
{
name:'ECharts2 - 2w Data',
type:'bar',
itemStyle: {normal: {color:'rgba(45,206,227,1)', label:{show:true,textStyle:{color:'#27727B'}}}},
data:[100,200,105,100,156]
},
{
name:'ECharts2 - 20w Data',
type:'bar',
itemStyle: {normal: {color:'rgba(249,142,118,1)', label:{show:true,textStyle:{color:'#E87C25'}}}},
data:[906,911,908,778,0]
},
{
name:'ECharts1 - 2k Data',
type:'bar',
xAxisIndex:1,
itemStyle: {normal: {color:'rgba(22,211,154,0.7)', label:{show:true,formatter:function(p){return p.value > 0 ? (p.value +'\n'):'';}}}},
data:[96,224,164,124,0]
},
{
name:'ECharts1 - 2w Data',
type:'bar',
xAxisIndex:1,
itemStyle: {normal: {color:'rgba(45,206,227,0.7)', label:{show:true}}},
data:[491,2035,389,955,347]
},
{
name:'ECharts1 - 20w Data',
type:'bar',
xAxisIndex:1,
itemStyle: {normal: {color:'rgba(249,142,118,0.7)', label:{show:true,formatter:function(p){return p.value > 0 ? (p.value +'+'):'';}}}},
data:[3000,3000,2817,3000,0]
}
]
};
// Apply options
// ------------------------------
myChart.setOption(chartOptions);
// Resize chart
// ------------------------------
$(function () {
// Resize chart on menu width change and window resize
$(window).on('resize', resize);
$(".menu-toggle").on('click', resize);
// Resize function
function resize() {
setTimeout(function() {
// Resize chart
myChart.resize();
}, 200);
}
});
}
);
});
|
// @flow
import { createSelector, type OutputSelector } from 'reselect'
import { sortOrderSort } from 'utils'
import type { EntityState, WrappedEntityState } from 'ducks/entities'
import type { Player, Character, fullQc, Battlegroup } from 'utils/flow-types'
export type entitySelector<T> = OutputSelector<WrappedEntityState, any, T>
type CharacterListSelector = entitySelector<Array<Character>>
type QcListSelector = entitySelector<Array<fullQc>>
type BgListSelector = entitySelector<Array<Battlegroup>>
export const entities = (state: WrappedEntityState): EntityState =>
state.entities.current
export const getSpecificPlayer = (
state: WrappedEntityState,
id: number
): Player => ({
characters: [],
qcs: [],
battlegroups: [],
chronicles: [],
own_chronicles: [],
...entities(state).players[id],
})
export const getCurrentPlayer = (state: WrappedEntityState): Player =>
getSpecificPlayer(state, state.session.id)
const getCharacters = state => entities(state).characters
export const getMyCharacters: CharacterListSelector = createSelector(
[getCurrentPlayer, getCharacters],
(currentPlayer, characters) =>
currentPlayer.characters.map(c => characters[c]).sort(sortOrderSort)
)
export const getMyCharactersWithoutChronicles: CharacterListSelector = createSelector(
[getMyCharacters],
characters => characters.filter(c => c.chronicle_id == null)
)
const getQCs = state => entities(state).qcs
export const getMyQCs: QcListSelector = createSelector(
[getCurrentPlayer, getQCs],
(currentPlayer, qcs) => currentPlayer.qcs.map(c => qcs[c]).sort(sortOrderSort)
)
export const getMyQcsWithoutChronicles: QcListSelector = createSelector(
[getMyQCs],
qcs => qcs.filter(c => c.chronicle_id == null)
)
const getBattlegroups = state => entities(state).battlegroups
export const getMyBattlegroups: BgListSelector = createSelector(
[getCurrentPlayer, getBattlegroups],
(currentPlayer, battlegroups) =>
currentPlayer.battlegroups.map(c => battlegroups[c]).sort(sortOrderSort)
)
export const getMyBattlegroupsWithoutChronicles: BgListSelector = createSelector(
[getMyBattlegroups],
battlegroups => battlegroups.filter(c => c.chronicle_id == null)
)
|
const HTTP_TIMEOUT = 30000;
export function httpAsync(theUrl, callback, type, payload, errorCB) {
const xmlHttp = new XMLHttpRequest();
const timeout = setTimeout(() => {
xmlHttp.abort();
if (typeof errorCB === 'function') errorCB();
}, HTTP_TIMEOUT);
xmlHttp.timeout = HTTP_TIMEOUT; // Set timeout to 30s 'cause ESPs are slow
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
clearTimeout(timeout);
if (typeof callback === 'function') callback(xmlHttp.responseText);
else if (typeof errorCB === 'function') errorCB();
}
};
xmlHttp.onerror = () => {
clearTimeout(timeout);
if (typeof errorCB === 'function') errorCB();
};
xmlHttp.open(type ? type : "GET", theUrl, true); // true for asynchronous
xmlHttp.send(payload);
}
export function reboot() {
if (!PRODUCTION)
setTimeout(() => {
window.location.href = window.location.href;
}, 3000);
if (PRODUCTION)
httpAsync('/reboot', function (res) {
window.location.href = window.location.href;
});
}
|
/*
*
* (c) Copyright Ascensio System SIA 2010-2019
*
* This program is a free software product. You can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License (AGPL)
* version 3 as published by the Free Software Foundation. In accordance with
* Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
* that Ascensio System SIA expressly excludes the warranty of non-infringement
* of any third-party rights.
*
* This program is distributed WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For
* details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
*
* You can contact Ascensio System SIA at 20A-12 Ernesta Birznieka-Upisha
* street, Riga, Latvia, EU, LV-1050.
*
* The interactive user interfaces in modified source and object code versions
* of the Program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU AGPL version 3.
*
* Pursuant to Section 7(b) of the License you must retain the original Product
* logo when distributing the program. Pursuant to Section 7(e) we decline to
* grant you any rights under trademark law for use of our trademarks.
*
* All the Product's GUI elements, including illustrations and icon sets, as
* well as technical writing content are licensed under the terms of the
* Creative Commons Attribution-ShareAlike 4.0 International. See the License
* terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
*
*/
/**
* EquationGroups.js
*
* Created by Alexey Musinov on 29/10/14
* Copyright (c) 2018 Ascensio System SIA. All rights reserved.
*
*/
define([
'backbone',
'documenteditor/main/app/model/EquationGroup'
], function(Backbone){ 'use strict';
DE.Collections = DE.Collections || {};
DE.Collections.EquationGroups = Backbone.Collection.extend({
model: DE.Models.EquationGroup
});
});
|
/* Copyright (c) 2015 - 2016 CoNWeT Lab., Universidad Politécnica de Madrid
*
* This file belongs to the business-ecosystem-logic-proxy of the
* Business API Ecosystem
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @author Francisco de la Vega <fdelavega@conwet.com>
* Jaime Pajuelo <jpajuelo@conwet.com>
* Aitor Magán <amagan@conwet.com>
*/
(function() {
'use strict';
angular.module('app').factory('CustomerAccount', ['$q', '$resource', 'URLS', 'Customer', CustomerAccountService]);
function CustomerAccountService($q, $resource, URLS, Customer) {
var CustomerAccount = $resource(
URLS.CUSTOMER_MANAGEMENT + '/customerAccount/:id',
{},
{
update: { method: 'PUT' },
updatePartial: { method: 'PATCH' }
}
);
CustomerAccount.prototype.serialize = function serialize() {
return {
id: this.id,
href: this.href,
name: this.name
};
};
var EVENTS = {};
var TYPES = {};
var TEMPLATES = {
CUSTOMER_ACCOUNT: {
name: '',
accountType: 'shipping address',
customer: {}
}
};
return {
EVENTS: EVENTS,
TEMPLATES: TEMPLATES,
TYPES: TYPES,
create: create,
detail: detail,
launch: launch
};
function create(data) {
var deferred = $q.defer();
var resource = angular.extend({}, data, {
name: data.customer.name,
customer: data.customer.serialize()
});
CustomerAccount.save(
resource,
function(customerAccount) {
customerAccount.customer = data.customer;
deferred.resolve(customerAccount);
},
function(response) {
deferred.reject(response);
}
);
return deferred.promise;
}
function detail(id) {
var deferred = $q.defer();
var params = {
id: id
};
CustomerAccount.get(
params,
function(customerAccount) {
Customer.detail(customerAccount.customer.id).then(
function(customer) {
customerAccount.customer = customer;
deferred.resolve(customerAccount);
},
function(response) {
deferred.reject(response);
}
);
},
function(response) {
deferred.reject(response);
}
);
return deferred.promise;
}
function launch() {
var customerAccount = new CustomerAccount(angular.copy(TEMPLATES.CUSTOMER_ACCOUNT));
customerAccount.customer = Customer.launch();
return customerAccount;
}
}
})();
|
/*
Clashing Coders RPG Platform - The platform used for Creamfinance's first coding contest.
Copyright (C) 2016 Florian Proksch
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
var Player = require('./player');
var World = module.exports = function World(level, players) {
//Mixin level definitions
for (var key in level) {
this[key] = level[key];
}
this.width = this.map_definition.width;
this.height = this.map_definition.height;
this.map = new Array(this.height);
this.tileset = {};
this.log = [];
this.messages = [];
this.players = new Array(this.player_definition.length);
for (var i = 0, imax = this.player_definition.length; i < imax; i += 1) {
this.players[i] = new Player(this.player_definition[i]);
}
for (var i = 0, imax = this.map_definition.height; i < imax; i += 1) {
this.map[i] = new Array(this.map_definition.width);
for (var j = 0, jmax = this.map_definition.width; j < jmax; j += 1) {
this.map[i][j] = new this.map_definition.tileDefinition[i][j]();
this.tileset[this.map[i][j].display] = {
type: this.map[i][j].type,
traversable: this.map_definition.tileDefinition[i][j].prototype.traversable,
weight: this.map_definition.tileDefinition[i][j].prototype.weight,
};
}
}
for (var i = 0, imax = this.map_definition.objectDefinition.length; i < imax; i += 1) {
var object_definition = this.map_definition.objectDefinition[i];
this.map[object_definition.x][object_definition.y].object = new object_definition.object();
}
this.init();
}
World.prototype.action = function (player, action, data) {
var ret = this.processAction(player, action, data);
var inv = {};
for (var k in player.inventory) {
inv[k] = player.inventory[k];
}
return ret;
};
|
/*
Agora Forum Software
Copyright (C) 2016 Gregory Sartucci
License: AGPL-3.0, Check file LICENSE
*/
Package.describe({
name: 'agoraforum:core',
version: '0.1.3',
summary: 'Graph-based forum',
git: 'https://github.com/Agora-Project/agora-meteor',
documentation: 'README.md'
});
Npm.depends({
step: '1.0.0',
xml2js: '0.4.19',
request: '2.87.0',
'node-rsa': '1.0.0'
});
Package.onUse(function(api) {
both = ['client', 'server'];
api.use([
'mongo',
'accounts-password',
'useraccounts:core',
'agoraforum:activitypub',
'ecmascript',
'iron:router',
'useraccounts:iron-routing',
'matb33:collection-hooks',
'accounts-base',
'alanning:roles',
'utilities:avatar',
'spacebars',
'email',
'http'
], both);
api.use([
'mrest:restivus',
'percolate:migrations'
], 'server');
api.addFiles([
'lib/identity_collections/identity_collections.js',
'lib/grapher/layered_grapher.js',
'lib/collections/actors.js',
'lib/collections/posts.js',
'lib/collections/reports.js',
'lib/collections/users.js',
'lib/collections/orderedCollections.js',
'lib/collections/activities.js',
'routes.js'
], both);
api.addFiles([
'lib/webfinger/lib/webfinger.js',
'server/methods.js',
'server/publish.js',
'server/clientActivity.js',
'server/federation.js',
'lib/collections/keys.js',
'server/migrations.js',
'server/initial-data.js'
], 'server');
api.addFiles([
'client/lib/notifier.js',
'client/lib/requestAnimationFrame.js',
'client/lib/templateParents.js',
'client/lib/seenPosts.js',
'client/subscriptionManager.js'
], 'client');
api.addFiles([
'client/main.html',
'client/main.css',
'client/init.js'
], 'client');
api.addFiles([
'client/userList/userList.html',
'client/userList/userList.js'
], 'client');
api.addFiles([
'client/federation/federation.html',
'client/federation/federation.js',
'client/federation/federation.css'
], 'client');
api.addFiles([
'client/errorPage/errorPage.html'
], 'client');
api.addFiles([
'client/mainView/detailed/detailed.html',
'client/mainView/detailed/detailed.css',
'client/mainView/detailed/detailed.js',
'client/mainView/reply/reply.html',
'client/mainView/reply/reply.css',
'client/mainView/reply/reply.js',
'client/mainView/main.html',
'client/mainView/main.css',
'client/mainView/layout.js',
'client/mainView/partitioner.js',
'client/mainView/camera.js',
'client/mainView/renderer.js',
'client/mainView/main.js'
], 'client');
api.addFiles([
'client/userProfile/userProfile.html',
'client/userProfile/userProfile.css',
'client/userProfile/userProfile.js'
], 'client');
api.addFiles([
'client/adminScreen/adminScreen.html',
'client/adminScreen/adminScreen.css',
'client/adminScreen/adminScreen.js'
], 'client');
api.use([
'ui',
'session',
'templating',
'reactive-var',
'verron:autosize',
'momentjs:moment',
'gwendall:body-events',
'meteorhacks:subs-manager'
], 'client');
});
Package.onTest(function(api) {
api.use('tinytest');
api.use('agoraforum:core', ['client', 'server']);
});
|
const registry = (() => {
if (!process.env.EXTENSION_DATA) {
// console.log("no EXTENSION_DATA found");
return {};
}
const extensions = typeof process.env.EXTENSION_DATA === "string" ?
JSON.parse(process.env.EXTENSION_DATA) : process.env.EXTENSION_DATA;
Object.keys(extensions).forEach((key) => {
if (key.endsWith("Component")) {
// console.log("loading component", key);
/* "@extensions" is a webpack alias */
extensions[key] = require(`@extensions/${extensions[key]}`).default; // eslint-disable-line
}
});
// console.log("extensions", extensions);
return extensions;
})();
export const getExtension = (what) => {
if (registry[what]) {
return registry[what];
}
console.error("Requested non-existing extension", what);
return false;
};
export const hasExtension = (what) => {
return Object.keys(registry).includes(what);
};
|
/*
* get_iframes_content.js
*
* -> returns as a string all innerHTML from current document
* as well as from all iframes present in the document
*/
var phantom_iframes = document.getElementsByTagName('frame'),
iframes_content = '',
iframe_content,
ph_i, ph_j;
if (!phantom_iframes.length) {
phantom_iframes = [];
}
phantom_iframes.push(document);
for (ph_i=0; ph_i<phantom_iframes.length; ph_i++) {
if ("contentDocument" in phantom_iframes[ph_i]) {
iframe_content = phantom_iframes[ph_i].contentDocument.childNodes;
} else {
iframe_content = phantom_iframes[ph_i].childNodes;
}
if (iframe_content) {
for (ph_j=0; ph_j<iframe_content.length; ph_j++) {
if (iframe_content[ph_j] && "innerHTML" in iframe_content[ph_j]) {
iframes_content += iframe_content[ph_j].innerHTML;
}
}
}
}
return iframes_content;
|
chrome.app.runtime.onLaunched.addListener(function() {
chrome.app.window.create('index.html', {
'bounds': {
'width': 400,
'height': 425
}
});
});
|
import Controller from '@ember/controller';
import modal from '../utils/modal';
import i18n from '../utils/i18n';
import session from '../utils/session';
import persistence from '../utils/persistence';
import CoughDrop from '../app';
import { later as runLater } from '@ember/runloop';
export default Controller.extend({
actions: {
update_org: function() {
var org = this.get('model');
org.save().then(null, function(err) {
console.log(err);
modal.error(i18n.t('org_update_failed', 'Organization update failed unexpectedly'));
});
},
jobs: function() {
persistence.ajax('/api/v1/auth/admin', {type: 'POST', data: {}}).then(function(res) {
location.href = '/jobby';
}, function(err) {
alert('Not authorized');
})
},
masquerade: function() {
if(this.get('model.admin') && this.get('model.permissions.manage')) {
var user_name = this.get('masquerade_user_name');
var _this = this;
this.store.findRecord('user', user_name).then(function(u) {
var data = session.restore();
data.original_user_name = data.user_name;
data.as_user_id = user_name;
data.user_name = user_name;
session.persist(data).then(function() {
_this.transitionToRoute('index');
runLater(function() {
location.reload();
});
});
}, function() {
modal.error(i18n.t('couldnt_find_user', "Couldn't retrieve user \"%{user_name}\" for masquerading", {user_name: user_name}));
});
}
},
find_board: function() {
var key = this.get('search_board');
var _this = this;
if(key) {
CoughDrop.store.findRecord('board', key).then(function(res) {
_this.transitionToRoute('board', res.get('key'));
}, function(err) {
if(err.deleted && err.key) {
_this.transitionToRoute('board', err.key);
} else {
modal.error(i18n.t('no_boards_found', "No boards found matching that lookup"));
}
});
}
},
find_user: function() {
var q = this.get('search_user');
var _this = this;
if(q) {
var opts = {q: q};
if(!this.get('model.admin')) {
opts.org_id = this.get('model.id');
}
CoughDrop.store.query('user', opts).then(function(res) {
if(res.content.length === 0) {
modal.warning(i18n.t('no_user_result', "No results found for \"%{q}\"", {q: q}));
} else if(res.content.length == 1) {
_this.transitionToRoute('user.index', res.map(function(i) { return i; })[0].get('user_name'));
} else {
modal.open('user-results', {list: res, q: q});
}
}, function() {
modal.error(i18n.t('error_searching', "There was an unexpected error while search for the user"));
});
}
}
}
});
|
/**
* Created by
* Pratish Shrestha <pratishshrestha@lftechnology.com>
* on 2/15/16.
*/
;(function () {
'use strict';
//React and Redux dependencies
var React = require('react');
var Link = require('react-router').Link;
var connect = require('react-redux').connect;
var bindActionCreators = require('redux').bindActionCreators;
//constants
var resourceConstants = require('../../constants/resourceConstants');
var urlConstants = require('../../constants/urlConstants');
var messageConstants = require('../../constants/messageConstants');
//components
var BudgetTypeRow = require('./BudgetTypeRow');
var EntityHeader = require('../common/header/EntityHeader');
var Pagination = require('../common/pagination/Pagination');
//utils
var alertBox = require('../../utils/alertBox');
//services
var listService = require('../../services/listService');
//actions
var apiActions = require('../../actions/apiActions');
var crudActions = require('../../actions/crudActions');
//libraries
var _ = require('lodash');
var sortBy = '';
var BudgetTypeList = React.createClass({
getDefaultProps: function () {
return {
offset: parseInt(resourceConstants.OFFSET)
}
},
componentWillMount: function () {
this.fetchData(this.props.pagination.startPage);
},
componentWillUnmount: function () {
this.props.actions.clearPagination();
this.props.actions.clearList(resourceConstants.BUDGET_TYPES);
this.props.actions.apiClearState();
},
fetchData: function (start) {
this.props.actions.fetch(resourceConstants.BUDGET_TYPES, resourceConstants.BUDGET_TYPES, {
sort: sortBy,
start: start || 1,
offset: this.props.offset
});
},
refreshList: function (index) {
var start = 1 + (index - 1) * this.props.offset;
this.fetchData(start);
},
deleteBudgetType: function (id) {
var that = this;
alertBox.confirm(messageConstants.DELETE_MESSAGE, function () {
that.props.actions.deleteItem(resourceConstants.BUDGET_TYPES, resourceConstants.BUDGET_TYPES, id, {
sort: sortBy,
start: that.props.pagination.startPage || 1,
offset: that.props.offset
}, that.props.pagination.count);
});
},
//sorts data in ascending or descending order according to clicked field
sort: function (field) {
var isAscending = listService.changeSortDisplay(field);
sortBy = (isAscending) ? field : '-' + field;
this.fetchData(this.props.pagination.startPage);
},
renderBudgetType: function (key) {
var startIndex = this.props.pagination.startPage + parseInt(key);
return (
<BudgetTypeRow key={key} index={startIndex || 1 + parseInt(key)}
budgetType={this.props.budgetTypes[key]}
deleteBudgetType={this.deleteBudgetType}/>
)
},
render: function () {
return (
<div>
<EntityHeader header="Budget Types" routes={this.props.routes} title="Budget Types"
apiState={this.props.apiState}/>
<div className="block full">
<div className="block-title">
<h2>Budget Type Details</h2>
<div className="block-options pull-right">
<Link to={urlConstants.BUDGET_TYPES.NEW} title="Add Budget Type"
className="btn btn-sm btn-success btn-ghost text-uppercase"><i
className="fa fa-plus"></i> Add Budget Type</Link>
</div>
</div>
<div className="table-responsive">
<table className="table table-vcenter table-bordered table-hover table-striped">
<thead>
<tr>
<th>S.No.</th>
<th className="cursor-pointer sort noselect col-400" data-sort="none" id="title"
onClick={this.sort.bind(null, 'title')}>
Budget Type
<i className="fa fa-sort pull-right"></i>
</th>
<th className="text-center">Actions</th>
</tr>
</thead>
<tbody>
{this.props.budgetTypes.length ? Object.keys(this.props.budgetTypes).map(this.renderBudgetType) : listService.displayNoRecordFound()}
</tbody>
</table>
</div>
<Pagination maxPages={Math.ceil(this.props.pagination.count / this.props.offset)}
selectedPage={parseInt(this.props.pagination.startPage / 10) + 1}
refreshList={this.refreshList}/>
</div>
</div>
)
}
});
var mapStateToProps = function (state) {
return {
budgetTypes: state.crudReducer.budgetTypes,
pagination: state.crudReducer.pagination,
apiState: state.apiReducer
}
};
var mapDispatchToProps = function (dispatch) {
return {
actions: bindActionCreators(_.assign({}, crudActions, apiActions), dispatch)
}
};
module.exports = connect(mapStateToProps, mapDispatchToProps)(BudgetTypeList);
})();
|
define({
input: {
eingabe: {
gegenstandswert: 0
},
gebuehr: 0,
hebesatz: {
mittelwert: "",
nenner: undefined,
zaehler: undefined,
zaehler_max: undefined,
zaehler_min: undefined
},
paragraph: "8",
paragraph16: {
checked: false
},
tabelle: "Pauschal",
taetigkeit: "Vorschuss (netto)"
},
expectedOutput: {
eingabe: {
gegenstandswert: 0
},
gebuehr: 0,
hebesatz: {
mittelwert: "",
nenner: undefined,
zaehler: undefined,
zaehler_max: undefined,
zaehler_min: undefined
},
paragraph: "8",
paragraph16: {
checked: false,
value: 0
},
tabelle: "Pauschal",
taetigkeit: "Vorschuss (netto)"
}
});
|
/******************************************************************************
Copyright Härnösands kommun(C) 2014
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Affero General Public License
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/agpl-3.0.html
******************************************************************************/
/**
* Full extent configuration details
*/
Ext.define('AdmClient.view.mapconfiguration.tools.details.FullExtent', {
extend : 'Ext.panel.Panel',
alias : 'widget.fullextent',
initComponent : function() {
this.items = [ {
xtype : 'button',
text : 'FullExtent'
} ];
this.callParent(arguments);
}
});
|
/**
* Babel JavaScript Support
*
* Copyright (C) 2008-2011 Edgewall Software
* All rights reserved.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at http://babel.edgewall.org/wiki/License.
*
* This software consists of voluntary contributions made by many
* individuals. For the exact contribution history, see the revision
* history and logs, available at http://babel.edgewall.org/log/.
*/
/**
* A simple module that provides a gettext like translation interface.
* The catalog passed to load() must be a object conforming to this
* interface::
*
* {
* messages: an object of {msgid: translations} items where
* translations is an array of messages or a single
* string if the message is not pluralizable.
* plural_expr: the plural expression for the language.
* locale: the identifier for this locale.
* domain: the name of the domain.
* }
*
* Missing elements in the object are ignored.
*
* Typical usage::
*
* var translations = babel.Translations.load(...).install();
*/
var babel = new function() {
var defaultPluralExpr = function(n) { return n == 1 ? 0 : 1; };
var formatRegex = /%?%(?:\(([^\)]+)\))?([disr])/g;
/**
* A translations object implementing the gettext interface
*/
var Translations = this.Translations = function(locale, domain) {
this.messages = {};
this.locale = locale || 'unknown';
this.domain = domain || 'messages';
this.pluralexpr = defaultPluralExpr;
};
/**
* Create a new translations object from the catalog and return it.
* See the babel-module comment for more details.
*/
Translations.load = function(catalog) {
var rv = new Translations();
rv.load(catalog);
return rv;
};
Translations.prototype = {
/**
* translate a single string.
*/
gettext: function(string) {
var translated = this.messages[string];
if (typeof translated == 'undefined')
return string;
return (typeof translated == 'string') ? translated : translated[0];
},
/**
* translate a pluralizable string
*/
ngettext: function(singular, plural, n) {
var translated = this.messages[singular];
if (typeof translated == 'undefined')
return (n == 1) ? singular : plural;
return translated[this.pluralexpr(n)];
},
/**
* Install this translation document wide. After this call, there are
* three new methods on the window object: _, gettext and ngettext
*/
install: function() {
var self = this;
window.gettext = function(string) {
return self.gettext(string);
};
window.ngettext = function(singular, plural, n) {
return self.ngettext(singular, plural, n);
};
return this;
},
/**
* Works like Translations.load but updates the instance rather
* then creating a new one.
*/
load: function(catalog) {
if (catalog.messages)
this.update(catalog.messages);
if (catalog.plural_expr)
this.setPluralExpr(catalog.plural_expr);
if (catalog.locale)
this.locale = catalog.locale;
if (catalog.domain)
this.domain = catalog.domain;
return this;
},
/**
* Updates the translations with the object of messages.
*/
update: function(mapping) {
for (var key in mapping)
if (mapping.hasOwnProperty(key))
this.messages[key] = mapping[key];
return this;
},
/**
* Sets the plural expression
*/
setPluralExpr: function(expr) {
this.pluralexpr = new Function('n', 'return +(' + expr + ')');
return this;
}
};
/**
* A python inspired string formatting function. Supports named and
* positional placeholders and "s", "d" and "i" as type characters
* without any formatting specifications.
*
* Examples::
*
* babel.format(_('Hello %s'), name)
* babel.format(_('Progress: %(percent)s%%'), {percent: 100})
*/
this.format = function() {
var arg, string = arguments[0], idx = 0;
if (arguments.length == 1)
return string;
else if (arguments.length == 2 && typeof arguments[1] == 'object')
arg = arguments[1];
else {
arg = [];
for (var i = 1, n = arguments.length; i != n; ++i)
arg[i - 1] = arguments[i];
}
return string.replace(formatRegex, function(all, name, type) {
if (all[0] == all[1]) return all.substring(1);
var value = arg[name || idx++];
return (type == 'i' || type == 'd') ? +value : value;
});
}
};
|
/**
* Created by
* Pratish Shrestha <pratishshrestha@lftechnology.com>
* on 4/19/16.
*/
var jsdom = require('jsdom').jsdom;
var exposedProperties = ['window', 'navigator', 'document', 'localStorage'];
global.document = jsdom('');
global.window = document.defaultView;
global.localStorage = {getItem: ()=>{}, setItem: ()=>{}};
Object.keys(document.defaultView).forEach((property) => {
if (typeof global[property] === 'undefined') {
exposedProperties.push(property);
global[property] = document.defaultView[property];
}
});
global.navigator = {
userAgent: 'node.js'
};
//for jQuery
global.jQuery = require('jquery');
global.$ = global.jQuery;
global.window.jQuery = global.jQuery;
global.window.$ = global.jQuery;
//for jQuery plugins
require('jquery-confirm');
require('../src/custom-ui/bootstrap-colorselector');
|
var mongoose = require('mongoose');
var es = require('event-stream');
var config = require('../lib/config/config');
var _ = require('lodash');
require('../lib/config/mongoose')(mongoose, config);
var Situation = mongoose.model('Situation');
Situation.find({ status: 'test' }).stream()
.pipe(es.map(function (situation, done) {
var isSituationUpdated = false;
hasConjoint = _.find(situation.individus, { role: 'conjoint' });
hasEnfant = _.find(situation.individus, { role: 'enfant' });
if (hasEnfant && ! hasConjoint) {
situation.individus[0].isolementRecent = true;
isSituationUpdated = true;
}
situation.save(function (err) {
if (err) {
console.log('Cannot save migrated situation %s', situation.id);
console.trace(err);
}
else if (isSituationUpdated)
console.log('Situation migrée');
done();
});
}))
.on('end', function() {
console.log('Terminé');
process.exit();
})
.on('error', function(err) {
console.trace(err);
process.exit();
})
.resume();
|
import React from 'react'
import PropTypes from 'prop-types'
import { ToastContainer } from 'react-toastify'
import { createBrowserHistory } from 'history'
import { Router, Redirect, Switch, Route, useLocation } from 'react-router'
import { BondeSessionProvider, BondeSessionUI } from 'bonde-core-tools'
import { Loading } from 'bonde-components'
import { ProviderRedux } from 'services/redux'
// Routes
// import Dashboard from './scenes/Dashboard'
// import { Root as AuthRoot } from './scenes/Auth'
import HomePage from 'scenes/HomePage'
import ChatbotPage from 'scenes/ChatbotPage/page'
import CommunityPage from 'scenes/CommunityPage'
// import SettingsPage from './scenes/Dashboard/scenes/Settings'
// import TagsPage from './scenes/Dashboard/scenes/Tags'
// import InvitationsPage from './scenes/Dashboard/scenes/Invitations'
import { NotFound } from 'components'
// Styles
import 'react-toastify/dist/ReactToastify.css'
const PagesRoute = () => {
const location = useLocation()
return (
<BondeSessionUI
indexRoute='/'
disableNavigation={location.pathname === '/'}
>
<ToastContainer
className='BondeToastify'
hideProgressBar={true}
/>
<Switch>
<Route exact path='/' component={HomePage} />
<Route path='/chatbot' component={ChatbotPage} />
<Route path='/community' component={CommunityPage} />
<Redirect from='/admin' to='/' />
<Route component={NotFound} />
</Switch>
</BondeSessionUI>
)
}
const TextLoading = ({ fetching }) => {
const messages = {
session: 'Carregando sessão...',
user: 'Carregando usuário...',
communities: 'Carregando communities...',
redirect: 'Redirecionando para autenticação...',
module: 'Redirecionando para módulo...'
}
return <Loading fullsize message={messages[fetching]} />
}
TextLoading.propTypes = {
fetching: PropTypes.string.isRequired
}
BondeSessionProvider.displayName = 'BondeSessionProvider'
const history = createBrowserHistory()
const Root = () => (
<BondeSessionProvider
fetchData
environment={process.env.REACT_APP_ENVIRONMENT || 'development'}
loading={TextLoading}
>
<ProviderRedux>
<Router history={history}>
<PagesRoute />
</Router>
</ProviderRedux>
</BondeSessionProvider>
)
export default Root
|
/**
* Created with IntelliJ IDEA.
* User: issa
* Date: 3/16/14
* Time: 9:08 PM
* To change this template use File | Settings | File Templates.
*/
function DistrictStockedOutController($scope,$location,$routeParams,dashboardMenuService,messageService,StockedOutFacilitiesByDistrict) {
$scope.filterObject = {};
$scope.formFilter = {};
$scope.formPanel = {openPanel:true};
$scope.startYears = [];
$scope.showProductsFilter = true;
$scope.$parent.currentTab = 'DISTRICT-STOCK-OUT';
$scope.productSelectOption = {maximumSelectionSize : 1};
$scope.stockedOutPieChartOption = {
series: {
pie: {
show: true,
radius: 1,
label: {
show: true,
radius: 2 / 3,
formatter: function (label, series) {
return '<div style="font-size:8pt;text-align:center;padding:2px;color:black;">' + Math.round(series.percent) + '%</div>';
},
threshold: 0.1
}
}
},
legend: {
container:$("#stockedOutReportLegend"),
noColumns: 0,
labelBoxBorderColor: "none"
},
grid:{
hoverable: true,
clickable: true,
borderWidth: 1,
borderColor: "#d6d6d6",
backgroundColor: {
colors: ["#FFF", "#CCC"]
}
},
tooltip: true,
tooltipOpts: {
content: "%p.0%, %s",
shifts: {
x: 20,
y: 0
},
defaultTheme: false
}
};
$scope.$on('$viewContentLoaded', function () {
$scope.filterObject = $routeParams;
if(!isUndefined($routeParams.programId) &&
!isUndefined($routeParams.periodId) &&
!isUndefined($routeParams.productId) &&
!isUndefined($routeParams.zoneId)){
StockedOutFacilitiesByDistrict.get({
periodId: $routeParams.periodId,
programId: $routeParams.programId,
productId: $routeParams.productId,
zoneId: $routeParams.zoneId
},function(stockData){
$scope.totalStockOuts = 0;
if(!isUndefined(stockData.stockOut)){
$scope.totalStockOuts = stockData.stockOut.length;
var suppliedInPast = _.filter(stockData.stockOut, function(stock){ if(stock.suppliedInPast === true){return stock;}});
$scope.product = _.pluck(stockData.stockOut,'product')[0];
$scope.location = _.pluck(stockData.stockOut,'location')[0];
$scope.datarows = [{label:messageService.get('label.facility.supplied.in.past'),
total: suppliedInPast.length,
color: "#F47900"
},
{label:messageService.get('label.facility.not.supplied.in.past'),
total: $scope.totalStockOuts - suppliedInPast.length,
color:"#CC0505"
}];
$scope.stockedOutPieChartData = [];
for (var i = 0; i < $scope.datarows.length; i++) {
$scope.stockedOutPieChartData[i] = {
label: $scope.datarows[i].label,
data: $scope.datarows[i].total,
color: $scope.datarows[i].color
};
}
bindChartEvent("#stocked-out-reporting","plotclick",$scope.stockedOutChartClickHandler);
bindChartEvent("#stocked-out-reporting","plothover",flotChartHoverCursorHandler);
}else{
$scope.resetStockedOutData();
}
});
} else{
$scope.resetStockedOutData();
}
// };
});
$scope.stockedOutChartClickHandler = function (event, pos, item){
if(item){
var districtStockOutPath = '/stock-out-detail/'+$scope.filterObject.programId+'/'+$scope.filterObject.periodId+'/'+$scope.filterObject.zoneId+'/'+$scope.filterObject.productId;
dashboardMenuService.addTab('menu.header.dashboard.stocked.out.district.detail','/public/pages/dashboard/index.html#'+districtStockOutPath,'DISTRICT-STOCK-OUT-DETAIL',true, 5);
$location.path(districtStockOutPath);
$scope.$apply();
}
};
$scope.resetStockedOutData = function(){
$scope.stockedOutPieChartData = null;
$scope.datarows = null;
$scope.stockedOutDetails = null;
};
function flotChartHoverCursorHandler(event,pos,item){
if (item && !isUndefined(item.dataIndex)) {
$(event.target).css('cursor','pointer');
} else {
$(event.target).css('cursor','auto');
}
}
function bindChartEvent(elementSelector, eventType, callback){
$(elementSelector).bind(eventType, callback);
}
$scope.getFacilityStockOutPercent = function(value){
return Math.round((value/$scope.totalStockOuts)*100) +'%';
};
}
|
import ChatAppDispatcher from '../dispatcher/ChatAppDispatcher';
import ChatConstants from '../constants/ChatConstants';
import * as ChatMessageUtils from '../utils/ChatMessageUtils';
import { EventEmitter } from 'events';
import ThreadStore from './ThreadStore';
let ActionTypes = ChatConstants.ActionTypes;
let CHANGE_EVENT = 'change';
let _messages = {};
let _feedback = {};
let _showLoading = false;
let TTSVoices = [];
let _initialisedVoices = false;
function _markAllInThreadRead(threadID) {
for (let id in _messages) {
if (_messages[id].threadID === threadID) {
_messages[id].isRead = true;
}
}
}
function _addDates(allMsgs){
let msgsWithDates = [];
let currDate = null;
allMsgs.forEach((message)=>{
if(currDate === null){
let dateMsg = {
id: 'd_'+Date.parse(message.date),
threadID: 't_1',
date: message.date,
type: 'date',
};
msgsWithDates.push(dateMsg);
}
else if(currDate.getDate() !== message.date.getDate()){
let dateMsg = {
id: 'd_'+Date.parse(message.date),
threadID: 't_1',
date: message.date,
type: 'date',
};
msgsWithDates.push(dateMsg);
}
currDate = message.date;
msgsWithDates.push(message);
});
return msgsWithDates;
}
let MessageStore = {
...EventEmitter.prototype,
emitChange() {
this.emit(CHANGE_EVENT);
},
/**
* @param {function} callback
*/
addChangeListener(callback) {
this.on(CHANGE_EVENT, callback);
},
removeChangeListener(callback) {
this.removeListener(CHANGE_EVENT, callback);
},
get(id) {
return _messages[id];
},
getAll() {
return _messages;
},
getTTSVoiceList() {
return TTSVoices;
},
getTTSInitStatus(){
return _initialisedVoices;
},
getLoadStatus(){
return _showLoading;
},
getFeedback(){
return _feedback;
},
/**
* @param {string} threadID
*/
getAllForThread(threadID) {
let threadMessages = [];
for (let id in _messages) {
if (_messages[id].threadID === threadID) {
threadMessages.push(_messages[id]);
}
}
threadMessages.sort((a, b) => {
if (a.date < b.date) {
return -1;
}
else if (a.date > b.date) {
return 1;
}
return 0;
});
return threadMessages;
},
getAllForCurrentThread() {
return _addDates(this.getAllForThread(ThreadStore.getCurrentID()));
},
resetVoiceForThread(threadID) {
for (let id in _messages) {
if ((_messages[id].threadID === threadID) &&
(_messages[id].authorName === 'SUSI')) {
_messages[id].voice = false;
_messages[id].feedback.isRated = true;
}
}
},
resetVoiceForCurrentThread(){
this.resetVoiceForThread(ThreadStore.getCurrentID());
}
};
MessageStore.dispatchToken = ChatAppDispatcher.register(action => {
switch(action.type) {
case ActionTypes.CLICK_THREAD:
ChatAppDispatcher.waitFor([ThreadStore.dispatchToken]);
_markAllInThreadRead(ThreadStore.getCurrentID());
MessageStore.emitChange();
break;
case ActionTypes.CREATE_MESSAGE: {
let message = action.message;
_messages[message.id] = message;
_showLoading = true;
MessageStore.emitChange();
break;
}
case ActionTypes.RECEIVE_RAW_CREATED_MESSAGE: {
let { rawMessage, tempMessageID } = action;
delete _messages[tempMessageID];
let message = ChatMessageUtils.convertRawMessage(rawMessage);
_messages[message.id] = message;
MessageStore.emitChange();
break;
}
case ActionTypes.CREATE_SUSI_MESSAGE: {
let message = action.message;
MessageStore.resetVoiceForThread(message.threadID);
_messages[message.id] = message;
_showLoading = false;
_feedback = {};
MessageStore.emitChange();
break;
}
case ActionTypes.STORE_HISTORY_MESSAGE: {
let message = action.message;
_messages[message.id] = message;
MessageStore.emitChange();
break;
}
case ActionTypes.RESET_MESSAGE_VOICE: {
MessageStore.resetVoiceForCurrentThread();
MessageStore.emitChange();
break;
}
case ActionTypes.FEEDBACK_RECEIVED: {
_feedback = action.feedback;
MessageStore.emitChange();
break;
}
case ActionTypes.INIT_TTS_VOICES: {
TTSVoices = action.voiceList;
_initialisedVoices = true;
MessageStore.emitChange();
break;
}
default:
// do nothing
}
});
export default MessageStore;
|
(function($,v){
v=xe.getApp('validator')[0];if(!v)return;
v.cast('ADD_RULE', ['signed_number', /-?[0-9]+/]);
v.cast('ADD_FILTER',['insertModuleSetup', {'module_srls':{required:true},'module_category_srl':{rule:'number'},'layout_srl':{rule:'signed_number'}}]);
v.cast('ADD_MESSAGE',['isnull','%s 값은 필수입니다.']);
v.cast('ADD_MESSAGE',['outofrange','%s의 글자 수를 맞추어 주세요.']);
v.cast('ADD_MESSAGE',['equalto','%s이(가) 잘못되었습니다.']);
v.cast('ADD_MESSAGE',['invalid','%s의 값이 올바르지 않습니다.']);
v.cast('ADD_MESSAGE',['invalid_email','%s의 값은 올바른 메일 주소가 아닙니다.']);
v.cast('ADD_MESSAGE',['invalid_userid','%s의 값은 영문, 숫자, _만 가능하며 첫 글자는 영문이어야 합니다.']);
v.cast('ADD_MESSAGE',['invalid_user_id','%s의 값은 영문, 숫자, _만 가능하며 첫 글자는 영문이어야 합니다.']);
v.cast('ADD_MESSAGE',['invalid_homepage','%s의 형식이 잘못되었습니다.(예: http://www.xpressengine.com)']);
v.cast('ADD_MESSAGE',['invalid_url','%s의 형식이 잘못되었습니다.(예: http://www.xpressengine.com)']);
v.cast('ADD_MESSAGE',['invalid_korean','%s의 형식이 잘못되었습니다. 한글로만 입력해야 합니다.']);
v.cast('ADD_MESSAGE',['invalid_korean_number','%s의 형식이 잘못되었습니다. 한글과 숫자로만 입력해야 합니다.']);
v.cast('ADD_MESSAGE',['invalid_alpha','%s의 형식이 잘못되었습니다. 영문으로만 입력해야 합니다.']);
v.cast('ADD_MESSAGE',['invalid_alpha_number','%s의 형식이 잘못되었습니다. 영문과 숫자로만 입력해야 합니다.']);
v.cast('ADD_MESSAGE',['invalid_mid','%s의 형식이 잘못되었습니다. 첫 글자는 영문으로 시작해야 하며 \'영문+숫자+_\'로만 입력해야 합니다.']);
v.cast('ADD_MESSAGE',['invalid_number','%s의 형식이 잘못되었습니다. 숫자로만 입력해야 합니다.']);
})(jQuery);
|
/**
* Site Members Groups component GET method
*/
function main()
{
var siteId, theUrl, json, membership, data;
siteId = page.url.templateArgs.site;
// get the membership info for the current user in the current site
theUrl = "/api/sites/" + siteId + "/memberships/" + encodeURIComponent(user.name);
json = remote.call(theUrl);
membership = JSON.parse(json);
// add the role to the model
model.currentUserRole = membership.role ? membership.role : "";
// get the roles available in the current site
theUrl = "/api/sites/" + siteId + "/roles";
json = remote.call(theUrl);
data = JSON.parse(json);
// add all roles except "None"
model.siteRoles = [];
if (json.status == 200 && data.siteRoles)
{
for (var i = 0, j = data.siteRoles.length; i < j; i++)
{
if (data.siteRoles[i] != "None")
{
model.siteRoles.push(data.siteRoles[i]);
}
}
}
else
{
model.error = membership.message;
}
// Widget instantiation metadata...
var searchConfig = config.scoped['Search']['search'],
defaultMinSearchTermLength = searchConfig.getChildValue('min-search-term-length'),
defaultMaxSearchResults = searchConfig.getChildValue('max-search-results');
var siteGroups = {
id : "SiteGroups",
name : "Alfresco.SiteGroups",
options : {
siteId : (page.url.templateArgs.site != null) ? page.url.templateArgs.site : "",
currentUser : user.name,
currentUserRole : model.currentUserRole,
roles : model.siteRoles,
minSearchTermLength : parseInt((args.minSearchTermLength != null) ? args.minSearchTermLength : defaultMinSearchTermLength),
maxSearchResults : parseInt((args.maxSearchResults != null) ? args.maxSearchResults : defaultMaxSearchResults),
setFocus : (args.setFocus == "true")
}
};
if (model.error)
{
siteGroups.options.error = model.error;
}
model.widgets = [siteGroups];
}
main();
|
import {Inject, Injectable} from 'app/app';
import {RestClient} from 'services/rest-client';
import {PromiseAdapter} from 'adapters/angular/promise-adapter';
import data from 'sandbox/services/rest/object-browser-service.data.json!';
@Injectable()
@Inject(RestClient, PromiseAdapter)
export class ObjectBrowserRestService {
constructor(restClient, promiseAdapter) {
this.restClient = restClient;
this.promiseAdapter = promiseAdapter;
}
getChildNodes(id, params) {
var result = data[id];
if (!result) {
result = data[params.rootId];
}
if (!result) {
result = []
}
return this.promiseAdapter.resolve(result);
}
}
|
define(
[],
function newItemController() {
return function newItemController($log, $scope, $state) {
$log.debug('newItemController');
$scope.title = 'Nowa pozycja';
$scope.itemTypes = [
{
view : 'sg.new.newPlace',
label: 'Nowe miejsce'
}
];
$scope.selectedItem = undefined;
$scope.$watch('selectedItem', function (newVal, oldVal) {
if (newVal === oldVal) {
return;
}
$state.go(newVal);
})
}
}
);
|
function MbaSelfAccessor(){
}
MbaSelfAccessor.prototype = new MbaAccessor();
MbaSelfAccessor.prototype.constructor = MbaSelfAccessor;
MbaSelfAccessor.prototype.getModelValue = function(model){
return model;
};
MbaSelfAccessor.prototype.setModelValue = function(model, value){
throw new Error('setModelValue not allowed on MbaSelfAccessor');//TODO faire deux classes MbaReadAccessor et MbaReadWriteAccessor
};
MbaSelfAccessor.prototype.toString = function(){
return 'model';
};
|
isc.DataSource.create({
ID:"employees",
dataURL:"[ISOMORPHIC]/system/reference/inlineExamples/trees/dataBinding/employeesDataChildrenArrays.xml",
recordXPath:"/Employees/employee",
fields:[
{name:"Name"},
{name:"Job"},
{name:"directReports", childrenProperty:true}
]
});
isc.TreeGrid.create({
ID: "employeeTree",
dataSource: "employees",
autoFetchData: true,
// customized appearance
width: 500,
height: 400,
nodeIcon:"icons/16/person.png",
folderIcon:"icons/16/person.png",
showOpenIcons:false,
showDropIcons:false,
closedIconSuffix:""
});
|
const kevoree = require('kevoree-library');
const modelValidator = require('kevoree-validator');
const monkeyPatch = require('./util/monkey-patch');
// statements list
const statements = {
addRepo: require('./statements/addRepo'),
add: require('./statements/add'),
move: require('./statements/move'),
attach: require('./statements/attach'),
addBinding: require('./statements/addBinding'),
delBinding: require('./statements/delBinding'),
include: require('./statements/include'),
set: require('./statements/set'),
network: require('./statements/network'),
remove: require('./statements/remove'),
detach: require('./statements/detach'),
namespace: require('./statements/namespace'),
start: require('./statements/start'),
stop: require('./statements/stop'),
pause: require('./statements/pause'),
};
// expressions list
const expressions = {
typeDef: require('./expressions/typeDef'),
typeFQN: require('./expressions/typeFQN'),
nameList: require('./expressions/nameList'),
instancePath: require('./expressions/instancePath'),
wildcard: require('./expressions/wildcard'),
string: require('./expressions/string'),
string2: require('./expressions/string2'),
string3: require('./expressions/string3'),
repoString: require('./expressions/repoString'),
version: require('./expressions/version'),
anything: require('./expressions/anything'),
realString: require('./expressions/realString'),
realStringNoNewLine: require('./expressions/realStringNoNewLine'),
newLine: require('./expressions/newLine'),
singleQuoteLine: require('./expressions/singleQuoteLine'),
doubleQuoteLine: require('./expressions/doubleQuoteLine'),
escaped: require('./expressions/escaped'),
ctxVar: require('./expressions/ctxVar'),
genCtxVar: require('./expressions/genCtxVar'),
tdefVersion: require('./expressions/tdefVersion'),
duVersion: require('./expressions/duVersion'),
integer: require('./expressions/integer'),
latest: require('./expressions/latest'),
release: require('./expressions/release'),
versionDecl: require('./expressions/versionDecl'),
versionLine: require('./expressions/versionLine'),
versionLines: require('./expressions/versionLines'),
};
const factory = new kevoree.factory.DefaultKevoreeFactory();
const cloner = factory.createModelCloner();
/**
*
* @param ast
* @param ctxModel
* @param opts
* @param callback
* @constructor
*/
function interpreter(ast, ctxModel, opts) {
// output model
let model = null;
if (ctxModel) {
// if we have a context model, clone it and use it has a base
model = cloner.clone(ctxModel, false);
} else {
// otherwise start from a brand new model
model = factory.createContainerRoot();
}
// this ContainerRoot is the root of the model
factory.root(model);
opts.warnings = [];
opts.identifiers = [];
return Promise.resolve()
.then(() => {
// create commands based on interpreted statements & expressions
const commands = [];
ast.children.forEach((child0) => {
child0.children.forEach((stmt) => {
if (typeof (statements[stmt.type]) === 'function') {
commands.push(() => {
return statements[stmt.type](model, expressions, stmt, opts);
});
} else {
throw new Error('Unknown statement "' + stmt.type + '"');
}
});
});
return commands;
})
.then((commands) => {
// execute commands sequentially
return commands.reduce((prev, next) => {
return prev.then(next);
}, Promise.resolve());
})
.then(() => {
// commands executed successfully => validate output model
return new Promise((resolve) => {
modelValidator(model);
resolve();
})
.then(() => {
// model is valid => return
return {
error: null,
model: model,
warnings: opts.warnings,
};
})
.catch((err) => {
// model is not valid
// try to find instance position for ModelValidationError
ast.children
.map((stmt) => {
return stmt.children[0];
})
.filter((stmt) => {
return stmt.type === 'add';
})
.some((addStmt) => {
const instancePos = addStmt.instances[err.path];
if (instancePos) {
err.pos = instancePos;
return true;
}
return false;
});
return {
error: err,
model: null,
warnings: opts.warnings,
};
})
.then((result) => {
// whether it is valid or not => monkey patch model
monkeyPatch(model);
return result;
});
}, (err) => {
return {
error: err,
model: null,
warnings: opts.warnings,
};
});
}
module.exports = interpreter;
|
var assert = require('assert');
var path = false;
var path2 = false;
// Normal switch
var test = "B";
switch (test) {
case "A":
assert(false);
break;
case "B":
path = true;
break;
default:
assert(false);
}
assert(path)
// Strict equality in switch test
path = false;
var test2 = 0;
switch (test2) {
case "0":
assert(false);
break;
default:
path = true;
}
assert(path);
// Empty switch
switch (test) {}
// Switch without default
var test3 = "A"
path = false;
switch (test3) {
case "A":
path = true;
break;
case "B":
assert(false);
break;
}
assert(path);
// value not handled
var test4 = "Z";
switch (test4) {
case "A":
assert(false);
break;
}
// Switch with default only
path = false;
switch (test) {
default: path = true;
}
assert(path)
// Break in default
path = false;
switch (test) {
default: path = true;
break;
}
assert(path)
// Case whihout break;
var test5 = "A";
path = false;
switch (test5) {
case "A":
case "B":
path = true;
break;
}
assert(path)
// Default placed first
var test6 = "B";
path = false;
switch (test6) {
default: assert(false);
case "A":
assert(false);
break;
case "B":
path = true;
break;
}
assert(path);
// More complex expression as test
var test7 = 21
path = false;
switch (test7) {
case (function () {
return 42;
})():
assert(false);
break;
case (function () {
return 21;
})():
path = true;
break
default:
assert(false);
}
assert(path);
// Bonus
var test8 = "C"
path = false;
path2 = false;
switch (test8) {
case "A":
assert(false);
default:
path = true;
case "B":
path2 = true;
}
assert(path && path2);
var test9 = "B";
path = false;
path2 = false;
switch (test9) {
case "A":
assert(false);
case "B":
path = true;
default:
path2 = true;
}
assert(path && path2);
var test10 = "B";
path = false;
switch (test10) {
default: assert(false);
case "A":
assert(false);
case "B":
path = true;
}
assert(path);
var test11 = "B";
path = false;
switch (test11) {
default: assert(false);
case "A":
assert(false);
case "B":
path = true;
break;
}
assert(path);
var i = 3;
var a = [];
while(i){
switch(i--){
case 3:
a.push(3);
break;
case 2:
a.push(2);
break;
case 1:
a.push(1);
break;
}
}
assert(a.length === 3);
assert(a[0] === 3);
assert(a[1] === 2);
assert(a[2] === 1);
|
/// <reference path="../references.d.ts" />
/// <reference path="./gameManager.service.ts" />
/// <reference path="../kdarts.ts" />
var kdarts;
(function (kdarts) {
var game;
(function (game) {
var X01SidenavController = (function () {
function X01SidenavController($state, $mdSidenav, $mdDialog) {
this.$state = $state;
this.$mdSidenav = $mdSidenav;
this.$mdDialog = $mdDialog;
}
X01SidenavController.prototype.closeMenu = function () {
this.$mdSidenav('left').close()
.then(function () {
});
};
X01SidenavController.prototype.cancelGame = function () {
var _this = this;
var confirm = this.$mdDialog.confirm()
.title('Cancel Game')
.content('Are you sure you want to cancel the game?')
.ok('Yes')
.cancel('Cancel');
this.$mdDialog.show(confirm).then(function () {
_this.closeMenu();
_this.$state.go('home');
}, function () {
_this.closeMenu();
});
};
X01SidenavController.$inject = ['$state', '$mdSidenav', '$mdDialog'];
return X01SidenavController;
})();
angular.module('kdarts.game').controller('X01SidenavController', X01SidenavController);
})(game = kdarts.game || (kdarts.game = {}));
})(kdarts || (kdarts = {}));
//# sourceMappingURL=x01sidenav.controller.js.map
|
var gui={};
(function() {
try {
var open = require("open");
var fs = require("fs");
} catch(e) {
var open = function(path) {
window.open("file://"+path);
}
}
var state = document.getElementById("state"),
statemsg = document.getElementById("statemsg"),
progress = document.getElementById("progress"),
pickdir = document.getElementById("pickdir"),
table = document.getElementById("collisions_table").tBodies[0];
pickdir.addEventListener("click", function(){
var fc = document.createElement("input");
fc.type = "file";
fc.value = "";
fc.nwdirectory = true;
fc.multiple = true;
state.classList.remove("hidden");
fc.onchange = function() {
analyze_dir(fc.value);
}
fc.click();
}, true);
gui.update_progress = function(rate) {
progress.value = rate;
};
gui.set_statemsg = function (msg) {
statemsg.innerHTML = msg;
};
gui.analyze_authorized = function (auth) {
pickdir.disabled = auth;
};
function readableSize (size) {
if (size > 1e9) return ((size/1e8|0)/10) + " Gb";
else if (size > 1e6) return ((size/1e5|0)/10) + " Mb";
else if (size > 1e3) return ((size/1e2|0)/10) + " Kb";
else return size+" bytes";
}
function insert_collision (idx, files, dist) {
var row = table.insertRow(idx);
row.dataset["dist"] = dist;
for (var i=0; i<2; i++) {
var cell = row.insertCell(i);
var pathElem = document.createTextNode(files[i].dirname+"/");
var fileNameElem = document.createElement("b");
var sizeElem = document.createElement("i");
var deleteBtn = document.createElement("button");
cell.dataset["filepath"] = files[i].filepath;
fileNameElem.addEventListener("click",function(e) {
var path = e.target.parentElement.dataset["filepath"];
open(path);
}, true);
fileNameElem.textContent = files[i].stats.name;
deleteBtn.textContent = "delete";
deleteBtn.addEventListener("click",function(e) {
var path = e.target.parentElement.dataset["filepath"];
if (confirm("Delete "+path+"?")) {
fs.unlink(path, function (err) {
if (err) {
alert("Unable to delete "+path);
} else {
var row = e.target.parentElement.parentElement;
row.parentElement.removeChild(row);
}
});
}
}, true);
sizeElem.textContent = readableSize(files[i].stats.size);
cell.appendChild(pathElem);
cell.appendChild(fileNameElem);
cell.appendChild(sizeElem);
cell.appendChild(deleteBtn);
}
cell = row.insertCell(2);
cell.textContent = dist;
};
gui.display_collision = function (files, dist) {
for (var idx=0; idx < table.rows.length; idx++) { //May not be necessary to do a dichotomy
if (table.rows[idx].dataset["dist"] >= dist) break;
}
insert_collision(idx, files, dist);
};
gui.init_display_collisions = function() {
table.parentElement.classList.remove("hidden");
table.innerHTML = "";
};
gui.all_collisions_displayed = function (ndoublets) {
gui.set_statemsg(ndoublets + " collisions found");
gui.update_progress(1);
};
})();
|
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const react_1 = __importDefault(require("react"));
const R = react_1.default.createElement;
const ui = __importStar(require("react-library/lib/bootstrap"));
// Number input component that handles parsing and maintains state when number is invalid
class NumberAnswerComponent extends react_1.default.Component {
focus() {
var _a;
return (_a = this.input) === null || _a === void 0 ? void 0 : _a.focus();
}
validate() {
if (!this.input.isValid()) {
return "Invalid number";
}
return null;
}
render() {
return R(ui.NumberInput, {
ref: (c) => {
return (this.input = c);
},
decimal: this.props.decimal,
value: this.props.value,
onChange: this.props.onChange,
size: this.props.small ? "sm" : undefined,
onTab: this.props.onNextOrComments,
onEnter: this.props.onNextOrComments
});
}
}
exports.default = NumberAnswerComponent;
|
/*
* Copyright 2013, Nexedi SA
*
* This program is free software: you can Use, Study, Modify and Redistribute
* it under the terms of the GNU General Public License version 3, or (at your
* option) any later version, as published by the Free Software Foundation.
*
* You can also Link and Combine this program with other software covered by
* the terms of any of the Free Software licenses or any of the Open Source
* Initiative approved licenses and Convey the resulting work. Corresponding
* source of such a combination shall include the source code for all other
* software used.
*
* This program is distributed WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* See COPYING file for full licensing terms.
* See https://www.nexedi.com/licensing for rationale and options.
*/
return parser.parse(string);
} // parseStringToObject
|
/*
* SonarQube
* Copyright (C) 2009-2017 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
import Backbone from 'backbone';
import Rule from './rule';
export default Backbone.Collection.extend({
model: Rule,
parseRules(r) {
let rules = r.rules;
const profiles = r.qProfiles || [];
if (r.actives != null) {
rules = rules.map(rule => {
const activations = (r.actives[rule.key] || []).map(activation => {
const profile = profiles[activation.qProfile];
if (profile != null) {
Object.assign(activation, { profile });
if (profile.parent != null) {
Object.assign(activation, { parentProfile: profiles[profile.parent] });
}
}
return activation;
});
return { ...rule, activation: activations.length > 0 ? activations[0] : null };
});
}
return rules;
},
setIndex() {
this.forEach((rule, index) => {
rule.set({ index });
});
},
addExtraAttributes(repositories) {
this.models.forEach(model => {
model.addExtraAttributes(repositories);
});
}
});
|
var searchData=
[
['hisconst',['HISConst',['../namespaceglados_1_1loaders.html#ac429e94c883bc55092765c8bf14dbe29',1,'glados::loaders']]]
];
|
import compose from 'koa-compose';
import webpack from 'webpack';
import { devMiddleware, hotMiddleware } from 'koa-webpack-middleware';
// Need to mock these files for development, because our Pug template
// will be looking for them, but they're actually all bundled up into one
// file during development with webpack and hot reloading
export function mockProductionStaticFiles() {
return async(ctx, next) => {
if (ctx.path === '/dist/vendor.bundle.js' || ctx.path === '/dist/styles.css') {
ctx.body =
"/*Mocked files for development " +
"(not using separate bundle files for vendor" +
" and app code in development mode or separate" +
" files for styles either)*/";
} else {
await next();
}
};
}
export function webpackMiddleware() {
console.log("Development environment, starting HMR");
const devConfig = require('../../../webpack.config.client');
const compile = webpack(devConfig);
return compose([
devMiddleware(compile, {
noInfo: true,
publicPath: devConfig.output.publicPath,
}),
hotMiddleware(compile),
]);
}
|
var esprima = require('esprima');
return esprima.parse(
"function foo(x, y) {\n" +
" var z = x + y;\n" +
" z++;\n" +
" return z;\n" +
"}\n"
);
|
'use strict';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '';
let currentLine = 0;
process.stdin.on('data', inputStdin => {
inputString += inputStdin;
});
process.stdin.on('end', _ => {
inputString = inputString.trim().split('\n').map(string => {
return string.trim();
});
main();
});
function readLine() {
return inputString[currentLine++];
}
/*
* Complete the reverseString function
* Use console.log() to print to stdout.
*/
function reverseString(s) {
try {
var splitString = s.split("");
var reverseArray = splitString.reverse();
var joinArray = reverseArray.join("");
console.log(joinArray);
}
catch (error)
{
console.log(error.message);
console.log(s);
}
}
function main() {
const s = eval(readLine());
reverseString(s);
}
|
/* @flow */
import React, { PureComponent } from 'react';
import { checkCompatibility } from '../api';
import CompatibilityScreen from '../start/CompatibilityScreen';
export default class CompatibilityChecker extends PureComponent {
state = {
compatibilityCheckFail: false,
};
componentDidMount() {
checkCompatibility().then(res => {
if (res.status === 400) {
this.setState({
compatibilityCheckFail: true,
});
}
});
}
render() {
const { compatibilityCheckFail } = this.state;
return compatibilityCheckFail ? <CompatibilityScreen /> : this.props.children;
}
}
|
var nock = require('nock')
//, sinon = require('sinon')
, chai = require('chai')
, fixtures = require('./portal-fixtures')
, EsriPortal = require('../index');
var expect = chai.expect;
var scope;
var prodUrl = 'https://www.arcgis.com';
describe('search ', function () {
beforeEach(function() {
ago = new EsriPortal();
});
afterEach(function() {
nock.cleanAll()
});
it("encodes the query string", function(done) {
var options = {query:'title:"San Francisco" AND type:"layer package"'};
scope = nock(prodUrl)
//.log(console.log)
.get('/sharing/rest/search?q=title%3A%22San%20Francisco%22%20AND%20type%3A%22layer%20package%22&f=json')
.reply(200, {});
ago.search(options)
.then(function(selfJson){
scope.done();
done();
})
.done();
});
it("accepts a simple query string", function(done) {
var options = {query:'colorado'};
scope = nock(prodUrl)
.get('/sharing/rest/search?q=colorado&f=json')
.reply(200, {});
ago.search(options)
.then(function(selfJson){
scope.done();
done();
})
.done();
});
it("accepts start", function(done) {
var options = {
query:'colorado',
start:12
};
scope = nock(prodUrl)
.get('/sharing/rest/search?q=colorado&start=12&f=json')
.reply(200, {});
ago.search(options)
.then(function(selfJson){
scope.done();
done();
})
.done();
});
it("accepts num", function(done) {
var options = {
query:'colorado',
num:45
};
scope = nock(prodUrl)
.get('/sharing/rest/search?q=colorado&num=45&f=json')
.reply(200, {});
ago.search(options)
.then(function(selfJson){
scope.done();
done();
})
.done();
});
it("accepts sortOrder", function(done) {
var options = {
query:'colorado',
sortOrder:'asc'
};
scope = nock(prodUrl)
.get('/sharing/rest/search?q=colorado&sortOrder=asc&f=json')
.reply(200, {});
ago.search(options)
.then(function(selfJson){
scope.done();
done();
})
.done();
});
it("accepts sortField", function(done) {
var options = {
query:'colorado',
sortField:'title'
};
scope = nock(prodUrl)
.get('/sharing/rest/search?q=colorado&sortField=title&f=json')
.reply(200, {});
ago.search(options)
.then(function(selfJson){
scope.done();
done();
})
.done();
});
it("accepts a token", function(done) {
var options = {
query:'colorado',
token:'sometoken'
};
scope = nock(prodUrl)
.get('/sharing/rest/search?q=colorado&token=sometoken&f=json')
.reply(200, {});
ago.search(options)
.then(function(selfJson){
scope.done();
done();
})
.done();
});
it("accepts everything", function(done) {
var options = {
query:'colorado',
sortOrder:'asc',
sortField:'title',
num:10,
start:100,
token:'sometoken'
};
scope = nock(prodUrl)
.get('/sharing/rest/search?q=colorado&start=100&num=10&sortField=title&sortOrder=asc&token=sometoken&f=json')
.reply(200, {});
ago.search(options)
.then(function(selfJson){
scope.done();
done();
})
.done();
});
});
|
/**
* @license
* Copyright 2019 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
/**
* @fileoverview The class representing a cursor.
* Used primarily for keyboard navigation.
* @author aschmiedt@google.com (Abby Schmiedt)
*/
'use strict';
goog.provide('Blockly.Cursor');
goog.require('Blockly.ASTNode');
goog.require('Blockly.Marker');
goog.require('Blockly.registry');
goog.require('Blockly.utils.object');
/**
* Class for a cursor.
* A cursor controls how a user navigates the Blockly AST.
* @constructor
* @extends {Blockly.Marker}
*/
Blockly.Cursor = function() {
Blockly.Cursor.superClass_.constructor.call(this);
/**
* @override
*/
this.type = 'cursor';
};
Blockly.utils.object.inherits(Blockly.Cursor, Blockly.Marker);
/**
* Find the next connection, field, or block.
* @return {Blockly.ASTNode} The next element, or null if the current node is
* not set or there is no next value.
* @public
*/
Blockly.Cursor.prototype.next = function() {
var curNode = this.getCurNode();
if (!curNode) {
return null;
}
var newNode = curNode.next();
while (newNode && newNode.next() &&
(newNode.getType() == Blockly.ASTNode.types.NEXT ||
newNode.getType() == Blockly.ASTNode.types.BLOCK)) {
newNode = newNode.next();
}
if (newNode) {
this.setCurNode(newNode);
}
return newNode;
};
/**
* Find the in connection or field.
* @return {Blockly.ASTNode} The in element, or null if the current node is
* not set or there is no in value.
* @public
*/
Blockly.Cursor.prototype.in = function() {
var curNode = this.getCurNode();
if (!curNode) {
return null;
}
// If we are on a previous or output connection, go to the block level before
// performing next operation.
if (curNode.getType() == Blockly.ASTNode.types.PREVIOUS ||
curNode.getType() == Blockly.ASTNode.types.OUTPUT) {
curNode = curNode.next();
}
var newNode = curNode.in();
if (newNode) {
this.setCurNode(newNode);
}
return newNode;
};
/**
* Find the previous connection, field, or block.
* @return {Blockly.ASTNode} The previous element, or null if the current node
* is not set or there is no previous value.
* @public
*/
Blockly.Cursor.prototype.prev = function() {
var curNode = this.getCurNode();
if (!curNode) {
return null;
}
var newNode = curNode.prev();
while (newNode && newNode.prev() &&
(newNode.getType() == Blockly.ASTNode.types.NEXT ||
newNode.getType() == Blockly.ASTNode.types.BLOCK)) {
newNode = newNode.prev();
}
if (newNode) {
this.setCurNode(newNode);
}
return newNode;
};
/**
* Find the out connection, field, or block.
* @return {Blockly.ASTNode} The out element, or null if the current node is
* not set or there is no out value.
* @public
*/
Blockly.Cursor.prototype.out = function() {
var curNode = this.getCurNode();
if (!curNode) {
return null;
}
var newNode = curNode.out();
if (newNode && newNode.getType() == Blockly.ASTNode.types.BLOCK) {
newNode = newNode.prev() || newNode;
}
if (newNode) {
this.setCurNode(newNode);
}
return newNode;
};
Blockly.registry.register(
Blockly.registry.Type.CURSOR, Blockly.registry.DEFAULT, Blockly.Cursor);
|
// @link http://schemas.wbeme.com/json-schema/eme/solicits/event/solicit-updated/1-0-0.json#
import EmeAccountsAccountRefV1Mixin from '@wbeme/schemas/eme/accounts/mixin/account-ref/AccountRefV1Mixin';
import GdbotsNcrNodeUpdatedV1Mixin from '@gdbots/schemas/gdbots/ncr/mixin/node-updated/NodeUpdatedV1Mixin';
import GdbotsPbjxEventV1Mixin from '@gdbots/schemas/gdbots/pbjx/mixin/event/EventV1Mixin';
import GdbotsPbjxEventV1Trait from '@gdbots/schemas/gdbots/pbjx/mixin/event/EventV1Trait';
import Message from '@gdbots/pbj/Message';
import MessageResolver from '@gdbots/pbj/MessageResolver';
import Schema from '@gdbots/pbj/Schema';
export default class SolicitUpdatedV1 extends Message {
/**
* @private
*
* @returns {Schema}
*/
static defineSchema() {
return new Schema('pbj:eme:solicits:event:solicit-updated:1-0-0', SolicitUpdatedV1,
[],
[
EmeAccountsAccountRefV1Mixin.create(),
GdbotsPbjxEventV1Mixin.create(),
GdbotsNcrNodeUpdatedV1Mixin.create(),
],
);
}
}
GdbotsPbjxEventV1Trait(SolicitUpdatedV1);
MessageResolver.register('eme:solicits:event:solicit-updated', SolicitUpdatedV1);
Object.freeze(SolicitUpdatedV1);
Object.freeze(SolicitUpdatedV1.prototype);
|
/**
* Copyright 2017 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
const glob = require('glob');
const fs = require('fs');
const path = require('path');
const mkdirp = require('mkdirp');
const ampOptimizer = require('amp-toolbox-optimizer');
const runtimeVersion = require('amp-toolbox-runtime-version');
// Transformers are easy to implement and integrate
class CustomTransformer {
transform(tree /* optional: ', params' */) {
const html = tree.root.firstChildByTag('html');
if (!html) return;
const head = html.firstChildByTag('head');
if (!head) return;
const desc = tree.createElement('meta', {
name: 'description',
content: 'this is just a demo'
});
head.appendChild(desc);
}
}
// Configure the transformers to be used.
// otherwise a default configuration is used.
ampOptimizer.setConfig({
transformers: [
new CustomTransformer(),
'AddAmpLink',
'ServerSideRendering',
'RemoveAmpAttribute',
// needs to run after ServerSideRendering
'AmpBoilerplateTransformer',
// needs to run after ServerSideRendering
'ReorderHeadTransformer',
// needs to run after ReorderHeadTransformer
'RewriteAmpUrls'
]
});
const SRC_DIR = 'src';
const DIST_DIR = 'dist';
runAmpOptimizerTransformations();
async function runAmpOptimizerTransformations() {
// This is optional in case AMP runtime URLs should be versioned
const ampRuntimeVersion = await runtimeVersion.currentVersion();
console.log('amp version: ', ampRuntimeVersion);
// Collect input files and invoke the transformers
const files = await collectInputFiles('/**/*.html');
files.forEach(file => copyAndTransform(file, ampRuntimeVersion));
}
// Collect all files in the src dir.
function collectInputFiles(pattern) {
return new Promise((resolve, reject) => {
glob(pattern, {root: SRC_DIR, nomount: true}, (err, files) => {
if (err) {
return reject(err);
}
resolve(files);
});
});
}
// Copy original and transformed AMP file into the dist dir.
async function copyAndTransform(file, ampRuntimeVersion) {
const originalHtml = await readFile(file);
const ampFile = file.substring(1, file.length)
.replace('.html', '.amp.html');
// The transformer needs the path to the original AMP document
// to correctly setup AMP to canonical linking
const optimizedHtml = await ampOptimizer.transformHtml(originalHtml, {
ampUrl: ampFile,
ampRuntimeVersion: ampRuntimeVersion
});
// We change the path of the original AMP file to match the new
// amphtml link and make the canonical link point to the transformed version.
writeFile(ampFile, originalHtml);
writeFile(file, optimizedHtml);
}
function readFile(fileName) {
return new Promise((resolve, reject) => {
fs.readFile(path.join(SRC_DIR, fileName), 'utf8', (err, contents) => {
if (err) {
return reject(err);
}
resolve(contents);
});
});
}
function writeFile(filePath, content) {
filePath = path.join(DIST_DIR, filePath);
mkdirp(path.dirname(filePath), err => {
if (err) {
throw err;
}
fs.writeFile(filePath, content, err => {
if (err) {
throw err;
}
});
});
}
|
import * as utils from 'src/utils';
import * as url from 'src/url';
import {registerBidder} from 'src/adapters/bidderFactory';
import {NATIVE, VIDEO} from 'src/mediaTypes';
/**
* Adapter for requesting bids from adxcg.net
* updated to latest prebid repo on 2017.10.20
*/
const BIDDER_CODE = 'adxcg';
const SUPPORTED_AD_TYPES = [VIDEO, NATIVE];
const SOURCE = 'pbjs10';
export const spec = {
code: BIDDER_CODE,
supportedMediaTypes: SUPPORTED_AD_TYPES,
/**
* Determines whether or not the given bid request is valid.
*
* @param {object} bid The bid params to validate.
* @return boolean True if this is a valid bid, and false otherwise.
*/
isBidRequestValid: function (bid) {
return !!(bid.params.adzoneid);
},
/**
* Make a server request from the list of BidRequests.
*
* an array of validBidRequests
* Info describing the request to the server.
*/
buildRequests: function (validBidRequests, bidderRequest) {
utils.logMessage(`buildRequests: ${JSON.stringify(validBidRequests)}`);
let adZoneIds = [];
let prebidBidIds = [];
let sizes = [];
validBidRequests.forEach(bid => {
adZoneIds.push(utils.getBidIdParameter('adzoneid', bid.params));
prebidBidIds.push(bid.bidId);
sizes.push(utils.parseSizesInput(bid.sizes).join('|'));
});
let location = utils.getTopWindowLocation();
let secure = location.protocol === 'https:';
let requestUrl = url.parse(location.href);
requestUrl.search = null;
requestUrl.hash = null;
let adxcgRequestUrl = url.format({
protocol: secure ? 'https' : 'http',
hostname: secure ? 'hbps.adxcg.net' : 'hbp.adxcg.net',
pathname: '/get/adi',
search: {
renderformat: 'javascript',
ver: 'r20171102PB10',
adzoneid: adZoneIds.join(','),
format: sizes.join(','),
prebidBidIds: prebidBidIds.join(','),
url: encodeURIComponent(url.format(requestUrl)),
secure: secure ? '1' : '0',
source: SOURCE,
pbjs: '$prebid.version$'
}
});
return {
method: 'GET',
url: adxcgRequestUrl,
};
},
/**
* Unpack the response from the server into a list of bids.
*
* @param {*} serverResponse A successful response from the server.
* @return {bidRequests[]} An array of bids which were nested inside the server.
*/
interpretResponse: function (serverResponse, bidRequests) {
let bids = [];
serverResponse = serverResponse.body;
if (serverResponse) {
serverResponse.forEach(serverResponseOneItem => {
let bid = {};
bid.requestId = serverResponseOneItem.bidId;
bid.cpm = serverResponseOneItem.cpm;
bid.creativeId = parseInt(serverResponseOneItem.creativeId);
bid.currency = serverResponseOneItem.currency ? serverResponseOneItem.currency : 'USD';
bid.netRevenue = serverResponseOneItem.netRevenue ? serverResponseOneItem.netRevenue : true;
bid.ttl = serverResponseOneItem.ttl ? serverResponseOneItem.ttl : 300;
if (serverResponseOneItem.deal_id != null && serverResponseOneItem.deal_id.trim().length > 0) {
bid.dealId = serverResponseOneItem.deal_id;
}
if (serverResponseOneItem.ad) {
bid.ad = serverResponseOneItem.ad;
} else if (serverResponseOneItem.vastUrl) {
bid.vastUrl = serverResponseOneItem.vastUrl;
bid.mediaType = 'video';
} else if (serverResponseOneItem.nativeResponse) {
bid.mediaType = 'native';
let nativeResponse = serverResponseOneItem.nativeResponse;
bid['native'] = {
clickUrl: encodeURIComponent(nativeResponse.link.url),
impressionTrackers: nativeResponse.imptrackers
};
nativeResponse.assets.forEach(asset => {
if (asset.title && asset.title.text) {
bid['native'].title = asset.title.text;
}
if (asset.img && asset.img.url) {
bid['native'].image = asset.img.url;
}
if (asset.data && asset.data.label === 'DESC' && asset.data.value) {
bid['native'].body = asset.data.value;
}
if (asset.data && asset.data.label === 'SPONSORED' && asset.data.value) {
bid['native'].sponsoredBy = asset.data.value;
}
});
}
bid.width = serverResponseOneItem.width;
bid.height = serverResponseOneItem.height;
utils.logMessage(`submitting bid[${serverResponseOneItem.bidId}]: ${JSON.stringify(bid)}`);
bids.push(bid);
});
} else {
utils.logMessage(`empty bid response`);
}
return bids;
},
getUserSyncs: function (syncOptions) {
if (syncOptions.iframeEnabled) {
return [{
type: 'iframe',
url: '//cdn.adxcg.net/pb-sync.html'
}];
}
}
};
registerBidder(spec);
|
var nearby = function(){
navigator.geolocation.getCurrentPosition(
// success
highlight
// error
,function(position){
console.log('Error occurred. Error code: ' + error.code);
}
);
}
var highlight = function(currentPosition, types){
if (!types)
types = ['car_dealer', 'car_rental', 'car_repair', 'car_wash', 'gas_station'];
var request = {
location: new google.maps.LatLng(currentPosition.coords.latitude, currentPosition.coords.longitude)
,rankBy: google.maps.places.RankBy.DISTANCE
,types: types
}
placesService.nearbySearch(request, onNearbyFound);
}
var onNearbyFound = function(results, status){
setAllMap(null);
if (status == google.maps.places.PlacesServiceStatus.OK){
for (var i=0; i<results.length; i++){
var place = results[i];
createMarker(results[i]);
}
}
}
var createMarker = function(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function(){
new google.maps.InfoWindow({
content: place.name
}).open(map, marker);
});
markers.push(marker);
};
var getDetails = function(result){
placesService.getDetails({reference: result.reference});
}
|
/*jslint node:true, browser:true */
'use strict';
/*
Copyright 2015 Enigma Marketing Services Limited
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
module.exports = require('lackey-make-title');
|
/* global error:false */
/* global done:false */
/* global PaymentRequest:false */
/**
* Updates details based on shipping address.
* @param {object} details - The details to update.
* @param {ShippingAddress} addr - The shipping address.
* @return {object} The updated details.
*/
function updateDetails(details, addr) {
if (addr.regionCode === 'US') {
var shippingOption = {
id: '',
label: '',
amount: {
currency: 'USD',
value: '0.00'
}
};
if (addr.administrativeArea === 'CA') {
shippingOption.id = 'ca';
shippingOption.label = 'Free shipping in California';
details.items[details.items.length - 1].amount.value = '55.00';
} else {
shippingOption.id = 'us';
shippingOption.label = 'Standard shipping in US';
shippingOption.amount.value = '5.00';
details.items[details.items.length - 1].amount.value = '60.00';
}
if (details.items.length === 3) {
details.items.splice(-1, 0, shippingOption);
} else {
details.items.splice(-2, 1, shippingOption);
}
details.shippingOptions = [shippingOption];
} else {
delete details.shippingOptions;
}
return details;
}
/**
* Starts PaymentRequest with shipping options that depend on the shipping
* address.
*/
function onBuyClicked() { // eslint-disable-line no-unused-vars
var supportedInstruments = [
'https://android.com/pay', 'visa', 'mastercard', 'amex', 'discover',
'maestro', 'diners', 'jcb', 'unionpay'
];
var details = {
items: [{
id: 'original',
label: 'Original donation amount',
amount: {
currency: 'USD',
value: '65.00'
}
},
{
id: 'discount',
label: 'Friends and family discount',
amount: {
currency: 'USD',
value: '-10.00'
}
},
{
id: 'total',
label: 'Donation',
amount: {
currency: 'USD',
value: '55.00'
}
}
]
};
var options = {
requestShipping: true
};
var schemeData = {
'https://android.com/pay': {
'gateway': 'stripe',
'stripe:publishableKey': 'pk_test_VKUbaXb3LHE7GdxyOBMNwXqa',
'stripe:version': '2015-10-16 (latest)'
}
};
if (!window.PaymentRequest) {
error('PaymentRequest API is not supported.');
return;
}
try {
var request =
new PaymentRequest(supportedInstruments, details, options, schemeData);
request.addEventListener('shippingaddresschange', e => {
e.updateWith(new Promise(resolve => {
resolve(updateDetails(details, request.shippingAddress));
}));
});
request.show()
.then(instrumentResponse => {
instrumentResponse.complete(true)
.then(() => {
done(
'This is a demo website. No payment will be processed.', request.shippingAddress,
request.shippingOption, instrumentResponse.methodName,
instrumentResponse.details);
})
.catch(err => {
error(err.message);
});
})
.catch(err => {
error(err.message);
});
} catch (e) {
error('Developer mistake: \'' + e.message + '\'');
}
}
|
// Copyright 2016, Google, Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
'use strict';
var gcloud = require('gcloud');
// Create a datastore client.
var datastore = gcloud.datastore();
/**
* Gets a Datastore key from the kind/key pair in the request.
*
* @param {Object} requestData Cloud Function request data.
* @param {string} requestData.key Datastore key string.
* @param {string} requestData.kind Datastore kind.
* @returns {Object} Datastore key object.
*/
function getKeyFromRequestData (requestData) {
if (!requestData.key) {
throw new Error('Key not provided. Make sure you have a "key" property ' +
'in your request');
}
if (!requestData.kind) {
throw new Error('Kind not provided. Make sure you have a "kind" property ' +
'in your request');
}
return datastore.key([requestData.kind, requestData.key]);
}
/**
* Creates and/or updates a record.
*
* @example
* gcloud alpha functions call ds-set --data '{"kind":"gcf-test","key":"foobar","value":{"message": "Hello World!"}}'
*
* @param {Object} context Cloud Function context.
* @param {Function} context.success Success callback.
* @param {Function} context.failure Failure callback.
* @param {Object} data Request data, in this case an object provided by the user.
* @param {string} data.kind The Datastore kind of the data to save, e.g. "user".
* @param {string} data.key Key at which to save the data, e.g. 5075192766267392.
* @param {Object} data.value Value to save to Cloud Datastore, e.g. {"name":"John"}
*/
function set (context, data) {
try {
// The value contains a JSON document representing the entity we want to save
if (!data.value) {
throw new Error('Value not provided. Make sure you have a "value" ' +
'property in your request');
}
var key = getKeyFromRequestData(data);
return datastore.save({
key: key,
data: data.value
}, function (err) {
if (err) {
console.error(err);
return context.failure(err);
}
return context.success('Entity saved');
});
} catch (err) {
console.error(err);
return context.failure(err.message);
}
}
/**
* Retrieves a record.
*
* @example
* gcloud alpha functions call ds-get --data '{"kind":"gcf-test","key":"foobar"}'
*
* @param {Object} context Cloud Function context.
* @param {Function} context.success Success callback.
* @param {Function} context.failure Failure callback.
* @param {Object} data Request data, in this case an object provided by the user.
* @param {string} data.kind The Datastore kind of the data to retrieve, e.g. "user".
* @param {string} data.key Key at which to retrieve the data, e.g. 5075192766267392.
*/
function get (context, data) {
try {
var key = getKeyFromRequestData(data);
return datastore.get(key, function (err, entity) {
if (err) {
console.error(err);
return context.failure(err);
}
// The get operation will not fail for a non-existent entity, it just
// returns null.
if (!entity) {
return context.failure('No entity found for key ' + key.path);
}
return context.success(entity);
});
} catch (err) {
console.error(err);
return context.failure(err.message);
}
}
/**
* Deletes a record.
*
* @example
* gcloud alpha functions call ds-del --data '{"kind":"gcf-test","key":"foobar"}'
*
* @param {Object} context Cloud Function context.
* @param {Function} context.success Success callback.
* @param {Function} context.failure Failure callback.
* @param {Object} data Request data, in this case an object provided by the user.
* @param {string} data.kind The Datastore kind of the data to delete, e.g. "user".
* @param {string} data.key Key at which to delete data, e.g. 5075192766267392.
*/
function del (context, data) {
try {
var key = getKeyFromRequestData(data);
return datastore.delete(key, function (err) {
if (err) {
console.error(err);
return context.failure(err);
}
return context.success('Entity deleted');
});
} catch (err) {
console.error(err);
return context.failure(err.message);
}
}
exports.set = set;
exports.get = get;
exports.del = del;
|
/**
* @license
* Copyright 2014 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.
*/
goog.provide('lf.query.InsertBuilder');
goog.require('lf.Binder');
goog.require('lf.Exception');
goog.require('lf.query.BaseBuilder');
goog.require('lf.query.Insert');
goog.require('lf.query.InsertContext');
/**
* @extends {lf.query.BaseBuilder.<!lf.query.InsertContext>}
* @implements {lf.query.Insert}
* @struct
* @constructor
*
* @param {!lf.Global} global
* @param {boolean=} opt_allowReplace Whether the generated query should allow
* replacing an existing record.
*/
lf.query.InsertBuilder = function(global, opt_allowReplace) {
lf.query.InsertBuilder.base(
this, 'constructor', global, new lf.query.InsertContext());
this.query.allowReplace = opt_allowReplace || false;
};
goog.inherits(lf.query.InsertBuilder, lf.query.BaseBuilder);
/** @override */
lf.query.InsertBuilder.prototype.assertExecPreconditions = function() {
lf.query.InsertBuilder.base(this, 'assertExecPreconditions');
var context = this.query;
if (!goog.isDefAndNotNull(context.into) ||
!goog.isDefAndNotNull(context.values)) {
throw new lf.Exception(
lf.Exception.Type.SYNTAX,
'Invalid usage of insert()');
}
// "Insert or replace" makes no sense for tables that do not have a primary
// key.
if (context.allowReplace &&
goog.isNull(context.into.getConstraint().getPrimaryKey())) {
throw new lf.Exception(
lf.Exception.Type.SYNTAX,
'Attemted to insert or replace in a table with no primary key.');
}
};
/** @override */
lf.query.InsertBuilder.prototype.into = function(table) {
this.assertIntoPreconditions_();
this.query.into = table;
return this;
};
/** @override */
lf.query.InsertBuilder.prototype.values = function(rows) {
this.assertValuesPreconditions_();
if (rows instanceof lf.Binder ||
rows.some(function(r) { return r instanceof lf.Binder; })) {
this.query.binder = rows;
} else {
this.query.values = rows;
}
return this;
};
/**
* Asserts whether the preconditions for calling the into() method are met.
* @private
*/
lf.query.InsertBuilder.prototype.assertIntoPreconditions_ = function() {
if (goog.isDefAndNotNull(this.query.into)) {
throw new lf.Exception(
lf.Exception.Type.SYNTAX,
'into() has already been called.');
}
};
/**
* Asserts whether the preconditions for calling the values() method are met.
* @private
*/
lf.query.InsertBuilder.prototype.assertValuesPreconditions_ = function() {
if (goog.isDefAndNotNull(this.query.values)) {
throw new lf.Exception(
lf.Exception.Type.SYNTAX,
'values() has already been called.');
}
};
|
// This snippet file was generated by processing the source file:
// ./storage-next/list-files.js
//
// To update the snippets in this file, edit the source and then run
// 'npm run snippets'.
// [START storage_list_paginate_modular]
import { getStorage, ref, list } from "firebase/storage";
async function pageTokenExample(){
// Create a reference under which you want to list
const storage = getStorage();
const listRef = ref(storage, 'files/uid');
// Fetch the first page of 100.
const firstPage = await list(listRef, { maxResults: 100 });
// Use the result.
// processItems(firstPage.items)
// processPrefixes(firstPage.prefixes)
// Fetch the second page if there are more elements.
if (firstPage.nextPageToken) {
const secondPage = await list(listRef, {
maxResults: 100,
pageToken: firstPage.nextPageToken,
});
// processItems(secondPage.items)
// processPrefixes(secondPage.prefixes)
}
}
// [END storage_list_paginate_modular]
|
function toggleMenuItem(item, selector) {
if ($(item).parent().next(selector).hasClass('in')) { { $(selector).collapse('hide'); } } else { { $(selector).collapse('show'); } };
}
function refreshView() {
RaiseXafCallback(globalCallbackControl, "", "XafParentWindowRefresh", "", false);
}
|
process.stdin.pipe(process.stdout);
|
var class_tri_1_1_graphic_1_1_model =
[
[ "Model", "class_tri_1_1_graphic_1_1_model.html#a57f8abc051d104b925e6a2cbb253b56c", null ],
[ "GetNormal", "class_tri_1_1_graphic_1_1_model.html#a086a31e07b32371a5d7d6c4629853cb9", null ],
[ "GetUV", "class_tri_1_1_graphic_1_1_model.html#a64da67596d9650b41ce0dd60f90eb7bb", null ],
[ "GetVertex", "class_tri_1_1_graphic_1_1_model.html#af64f04fc0559ceb51061f8dfed0eb4e6", null ],
[ "Render", "class_tri_1_1_graphic_1_1_model.html#aa190ca9e2258a28ea12a36d7fb25b0de", null ]
];
|
// Copyright 2013 Traceur 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.
System.set('@traceur/module', (function() {
'use strict';
var {resolveUrl, isStandardModuleUrl} = System.get('@traceur/url');
var modules = Object.create(null);
var refererUrl = './';
function setRefererUrl(url) {
refererUrl = url || './';
}
function getRefererUrl() {
return refererUrl;
}
class PendingModule {
constructor(name, func, self) {
this.name = name;
this.func = func;
this.self = self;
}
toModule() {
var oldName = refererUrl;
refererUrl = this.name;
try {
return this.func.call(this.self);
} finally {
refererUrl = oldName
}
}
}
function registerModule(name, func, self) {
var url = resolveUrl(refererUrl, name);
modules[url] = new PendingModule(name, func, self);
}
// Now it is safe to override System.{get,set} to use resolveUrl.
var $get = System.get;
var $set = System.set;
System.get = function(name) {
if (isStandardModuleUrl(name))
return $get(name);
var url = resolveUrl(refererUrl, name);
var module = modules[url];
if (module instanceof PendingModule)
return modules[url] = module.toModule();
return module;
};
System.set = function(name, object) {
if (isStandardModuleUrl(name))
$set(name, object);
else
modules[resolveUrl(refererUrl, name)] = object;
};
return {
getRefererUrl,
registerModule,
setRefererUrl,
};
})());
|
goog.module('grrUi.forms.outputPluginDescriptorFormDirective');
goog.module.declareLegacyNamespace();
const apiService = goog.requireType('grrUi.core.apiService');
const reflectionService = goog.requireType('grrUi.core.reflectionService');
/**
* Controller for OutputPluginDescriptorFormDirective.
* @unrestricted
*/
const OutputPluginDescriptorFormController = class {
/**
* @param {!angular.Scope} $scope
* @param {!apiService.ApiService} grrApiService
* @param {!reflectionService.ReflectionService}
* grrReflectionService
* @ngInject
*/
constructor($scope, grrApiService, grrReflectionService) {
/** @private {!angular.Scope} */
this.scope_ = $scope;
/** @private {!apiService.ApiService} */
this.grrApiService_ = grrApiService;
/** @private {!reflectionService.ReflectionService} */
this.grrReflectionService_ = grrReflectionService;
/** @type {Object} */
this.outputPluginsDescriptors;
/** @type {Array<string>} */
this.allowedPluginsNames;
this.grrApiService_.get('/output-plugins/all').then(function(response) {
this.outputPluginsDescriptors = {};
angular.forEach(response['data']['items'], function(item) {
if (item['plugin_type'] === 'LEGACY') {
this.outputPluginsDescriptors[item['name']] = item;
}
}.bind(this));
this.allowedPluginsNames =
Object
.keys(
/** @type {!Object} */ (this.outputPluginsDescriptors))
.sort();
if (angular.isUndefined(
this.scope_.$eval('value.value.plugin_name.value'))) {
this.scope_['value']['value']['plugin_name'] = {
type: 'RDFString',
value: this.allowedPluginsNames[0]
};
}
this.scope_.$watch('value.value.plugin_name.value', function(newValue) {
if (angular.isDefined(newValue)) {
var argsType = this.outputPluginsDescriptors[newValue]['args_type'];
var pluginArgs = this.scope_['value']['value']['plugin_args'];
// We want to replace the plugin args only if they're undefined or
// their type differs from the selected ones. This check helps
// prefilled forms to keep prefilled data.
if (angular.isUndefined(pluginArgs) ||
pluginArgs['type'] != argsType) {
this.grrReflectionService_.getRDFValueDescriptor(argsType).then(
function(descriptor) {
this.scope_['value']['value']['plugin_args'] =
angular.copy(descriptor['default']);
}.bind(this));
}
}
}.bind(this));
}.bind(this));
}
};
/**
* OutputPluginDescriptorFormDirective definition.
*
* @return {angular.Directive} Directive definition object.
*/
exports.OutputPluginDescriptorFormDirective = function() {
return {
restrict: 'E',
scope: {value: '='},
templateUrl: '/static/angular-components/forms/' +
'output-plugin-descriptor-form.html',
controller: OutputPluginDescriptorFormController,
controllerAs: 'controller'
};
};
/**
* Directive's name in Angular.
*
* @const
* @export
*/
exports.OutputPluginDescriptorFormDirective.directive_name =
'grrOutputPluginDescriptorForm';
/**
* Semantic type corresponding to this directive.
*
* @const
* @export
*/
exports.OutputPluginDescriptorFormDirective.semantic_type =
'OutputPluginDescriptor';
|
//Info-Content
function getBivesData(v1, v2, command, place){
$(".bivesNavi").hide();
$(".bivesResult").hide();
$('#loading').show();
d3.selectAll(place + ' > *').remove();
$("#bivesInfo").show ();
var dataCatch;
if(sessionStorage.getItem(v1.model+"_"+v1.versionid+"_"+v2.versionid) != null){
dataCatch = sessionStorage.getItem(v1.model+"_"+v1.versionid+"_"+v2.versionid);
fillGraphTabs(dataCatch);
return;
}
var bivesJob = {
files:
[
v1.url,
v2.url
],
commands:
command
};
// call the bives wrapper script
$.post (
"bives/bives.php",
"bivesJob=" + JSON.stringify (bivesJob),
function (data)
{
dataCatch = data;
}
).done(function(){
console.log(dataCatch);
fillGraphTabs(dataCatch);
//save diff in local storage
sessionStorage.setItem(v1.model+"_"+v1.versionid+"_"+v2.versionid, dataCatch);
console.log("saved in sessionStorage");
});
}
function fillGraphTabs(data){
//fill bives tabs
$("#bivesReport").html ($.parseJSON (data).reportHtml);
var annotations = $.parseJSON (data).separateAnnotations;
fillcomodiFig(annotations);
var sbgnJson = $.parseJSON (data).reactionsSbgnJson;
showSbgn(sbgnJson);
//highlight XmlDiff
$("#highlightXmlDiff").text($.parseJSON (data).xmlDiff);
$('#highlightXmlDiff').each(function(i, block) {
hljs.highlightBlock(block);
});
//hide loading gif, show bives tabs
$("#loading").hide();
$(".bivesNavi").show();
$('#bivesResult').show();
//set Hash to report tab
setHash('b', 'r');
}
|
import { Template } from 'meteor/templating';
import { ReactiveDict } from 'meteor/reactive-dict';
import { _ } from 'meteor/underscore';
import { Beaches, BeachesSchema } from '/imports/api/items/beach/beach-item.js';
import { FlowRouter } from 'meteor/kadira:flow-router';
import { Profiles } from '/imports/api/profiles/ProfileCollection.js';
import { Meteor } from 'meteor/meteor';
/* eslint-disable no-param-reassign */
const displayErrorMessages = 'displayErrorMessages';
const displaySuccessMessage = 'displaySuccessMessage';
export const locationList = ['Aiea', 'Haleiwa', 'Hawaii Kai', 'Kahala', 'Kailua', 'Kaimuki', 'Kakaako', 'Kalihi', 'Kaneohe', 'Laie', 'Liliha', 'Manoa', 'Makiki', 'Mililani', 'Moanalua', 'Moilili', 'Pearl City', 'Waikiki'];
export const beachTagList = ['Busy', 'Dog-friendly', 'Good waves', 'Kid-friendly', 'No Lifeguard', 'No waves' , 'Private Access', 'Secluded'];
Template.Create_Beach_Form.onCreated(function onCreated() {
this.subscribe('Profiles');
this.subscribe('Beaches');
this.messageFlags = new ReactiveDict();
this.messageFlags.set(displaySuccessMessage, false);
this.messageFlags.set(displayErrorMessages, false);
this.context = BeachesSchema.namedContext('Create_Beach_Form');
});
Template.Create_Beach_Form.helpers({
errorClass() {
return Template.instance().messageFlags.get(displayErrorMessages) ? 'error' : '';
},
successClass() {
return Template.instance().messageFlags.get(displaySuccessMessage) ? 'success' : '';
},
displaySuccessMessage() {
return Template.instance().messageFlags.get(displaySuccessMessage);
},
fieldError(fieldName) {
const invalidKeys = Template.instance().context.invalidKeys();
const errorObject = _.find(invalidKeys, (keyObj) => keyObj.name === fieldName);
return errorObject && Template.instance().context.keyErrorMessage(errorObject.name);
},
locationChoice() {
return _.map(locationList, function makeLocationObject(location) {
return { label: location };
});
},
beachTagChoice() {
return _.map(beachTagList, function maketagObject(tag) {
return { label: tag };
});
},
});
Template.Create_Beach_Form.events({
'submit .create-beach-data'(event, instance) {
event.preventDefault();
// Get name (text field)
const title = event.target.Title.value;
const location = event.target.Location.value;
const about = event.target.About.value;
const selectedTags = _.filter(event.target.Tags.selectedOptions, (option) => option.selected);
const tags = _.map(selectedTags, (option) => option.value);
tags.push(location);
const createdAt = Date.now();
const picture = event.target.Picture.value;
const status = 'Pending';
const newItemData = { title, location, about, tags, status, picture, createdAt };
const currentTitle = title;
// Clear out any old validation errors.
instance.context.resetValidation();
// Invoke clean so that newStudentData reflects what will be inserted.
BeachesSchema.clean(newItemData);
// Determine validity.
instance.context.validate(newItemData);
if (instance.context.isValid()) {
Beaches.insert(newItemData);
instance.messageFlags.set(displayErrorMessages, false);
const usernameCurrent = Meteor.user().profile.name;
const profileId = Profiles.findOne({ username: usernameCurrent })._id;
const currentBeach = Beaches.findOne({ title: currentTitle })._id;
Profiles.update(profileId, { $push: { youritems: currentBeach } });
instance.messageFlags.set(displaySuccessMessage, true);
instance.messageFlags.set(displayErrorMessages, false);
FlowRouter.go('Item_Feed_Page');
} else {
instance.messageFlags.set(displaySuccessMessage, false);
instance.messageFlags.set(displayErrorMessages, true);
}
},
});
|
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("distfs/codemirror/lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["distfs/codemirror/lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
CodeMirror.defineMode("apl", function() {
var builtInOps = {
".": "innerProduct",
"\\": "scan",
"/": "reduce",
"⌿": "reduce1Axis",
"⍀": "scan1Axis",
"¨": "each",
"⍣": "power"
};
var builtInFuncs = {
"+": ["conjugate", "add"],
"−": ["negate", "subtract"],
"×": ["signOf", "multiply"],
"÷": ["reciprocal", "divide"],
"⌈": ["ceiling", "greaterOf"],
"⌊": ["floor", "lesserOf"],
"∣": ["absolute", "residue"],
"⍳": ["indexGenerate", "indexOf"],
"?": ["roll", "deal"],
"⋆": ["exponentiate", "toThePowerOf"],
"⍟": ["naturalLog", "logToTheBase"],
"○": ["piTimes", "circularFuncs"],
"!": ["factorial", "binomial"],
"⌹": ["matrixInverse", "matrixDivide"],
"<": [null, "lessThan"],
"≤": [null, "lessThanOrEqual"],
"=": [null, "equals"],
">": [null, "greaterThan"],
"≥": [null, "greaterThanOrEqual"],
"≠": [null, "notEqual"],
"≡": ["depth", "match"],
"≢": [null, "notMatch"],
"∈": ["enlist", "membership"],
"⍷": [null, "find"],
"∪": ["unique", "union"],
"∩": [null, "intersection"],
"∼": ["not", "without"],
"∨": [null, "or"],
"∧": [null, "and"],
"⍱": [null, "nor"],
"⍲": [null, "nand"],
"⍴": ["shapeOf", "reshape"],
",": ["ravel", "catenate"],
"⍪": [null, "firstAxisCatenate"],
"⌽": ["reverse", "rotate"],
"⊖": ["axis1Reverse", "axis1Rotate"],
"⍉": ["transpose", null],
"↑": ["first", "take"],
"↓": [null, "drop"],
"⊂": ["enclose", "partitionWithAxis"],
"⊃": ["diclose", "pick"],
"⌷": [null, "index"],
"⍋": ["gradeUp", null],
"⍒": ["gradeDown", null],
"⊤": ["encode", null],
"⊥": ["decode", null],
"⍕": ["format", "formatByExample"],
"⍎": ["execute", null],
"⊣": ["stop", "left"],
"⊢": ["pass", "right"]
};
var isOperator = /[\.\/⌿⍀¨⍣]/;
var isNiladic = /⍬/;
var isFunction = /[\+−×÷⌈⌊∣⍳\?⋆⍟○!⌹<≤=>≥≠≡≢∈⍷∪∩∼∨∧⍱⍲⍴,⍪⌽⊖⍉↑↓⊂⊃⌷⍋⍒⊤⊥⍕⍎⊣⊢]/;
var isArrow = /←/;
var isComment = /[⍝#].*$/;
var stringEater = function(type) {
var prev;
prev = false;
return function(c) {
prev = c;
if (c === type) {
return prev === "\\";
}
return true;
};
};
return {
startState: function() {
return {
prev: false,
func: false,
op: false,
string: false,
escape: false
};
},
token: function(stream, state) {
var ch, funcName, word;
if (stream.eatSpace()) {
return null;
}
ch = stream.next();
if (ch === '"' || ch === "'") {
stream.eatWhile(stringEater(ch));
stream.next();
state.prev = true;
return "string";
}
if (/[\[{\(]/.test(ch)) {
state.prev = false;
return null;
}
if (/[\]}\)]/.test(ch)) {
state.prev = true;
return null;
}
if (isNiladic.test(ch)) {
state.prev = false;
return "niladic";
}
if (/[¯\d]/.test(ch)) {
if (state.func) {
state.func = false;
state.prev = false;
} else {
state.prev = true;
}
stream.eatWhile(/[\w\.]/);
return "number";
}
if (isOperator.test(ch)) {
return "operator apl-" + builtInOps[ch];
}
if (isArrow.test(ch)) {
return "apl-arrow";
}
if (isFunction.test(ch)) {
funcName = "apl-";
if (builtInFuncs[ch] != null) {
if (state.prev) {
funcName += builtInFuncs[ch][1];
} else {
funcName += builtInFuncs[ch][0];
}
}
state.func = true;
state.prev = false;
return "function " + funcName;
}
if (isComment.test(ch)) {
stream.skipToEnd();
return "comment";
}
if (ch === "∘" && stream.peek() === ".") {
stream.next();
return "function jot-dot";
}
stream.eatWhile(/[\w\$_]/);
word = stream.current();
state.prev = true;
return "keyword";
}
};
});
CodeMirror.defineMIME("text/apl", "apl");
});
|
var Portfolio = function () {
this.performance = [];
this.dateToIndexMap = [];
var index = 0;
for (var i = 0; i <= 30; i++) {
var date = moment().subtract(30 - i, 'days');
if (date.day() != 0 && date.day() != 6) {
var formattedDate = date.format("YYYY-MM-DD");
this.performance[index] = {date: formattedDate, portfolio: new PortfolioFIFO()};
this.dateToIndexMap[formattedDate] = index;
index++;
}
}
}
Portfolio.prototype = {
buyStock: function (symbol, amount, price, date) {
var dateObject = moment(date, "YYYY-MM-DD");
if (dateObject.isBefore(this.performance[0].date)) {
for (var i = 0; i < this.performance.length; i++) {
this.performance[i].portfolio.push(symbol, amount, price);
}
} else {
for (var i = 0; i < 30; i++) {
var formattedDate = dateObject.format("YYYY-MM-DD");
if (formattedDate in this.dateToIndexMap) {
this.performance[this.dateToIndexMap[formattedDate]].portfolio.push(symbol, amount, price);
}
dateObject.add(1, 'days');
}
}
},
sellStock: function (symbol, amount, date) {
// Adjust date to a weekday
var dateObject = moment(date, "YYYY-MM-DD");
if (dateObject.isBefore(this.performance[0].date)) {
for (var i = 0; i < this.performance.length; i++) {
this.performance[i].portfolio.pop(symbol, amount);
}
} else {
for (var i = 0; i < this.performance.length; i++) {
var formattedDate = dateObject.format("YYYY-MM-DD");
if (formattedDate in this.dateToIndexMap) {
this.performance[this.dateToIndexMap[formattedDate]].portfolio.pop(symbol, amount);
}
dateObject.add(1, 'days');
}
}
},
cost: function (date) {
if (date in this.dateToIndexMap) {
var dayData = this.performance[this.dateToIndexMap[date]];
return dayData.portfolio.cost();
} else {
console.log("cost(): Oops. Didn't find day in history data [" + date + "]");
return 0;
}
},
value: function (date) {
if (date in this.dateToIndexMap) {
var dayData = this.performance[this.dateToIndexMap[date]];
return dayData.portfolio.value();
} else {
console.log("value(): Oops. Didn't find day in history data [" + date + "]");
return 0;
}
},
setClosePrice: function (symbol, closePrice, date) {
if (date in this.dateToIndexMap) {
var dayData = this.performance[this.dateToIndexMap[date]];
dayData.portfolio.setClosePrice(symbol, closePrice);
} else {
console.log("setClosePrice(): Oops. Didn't find day in history data [" + date + "]");
}
},
getHistoryPerformance: function () {
this._padMissingDays();
var history = [];
for (var i = 0; i < this.performance.length; i++) {
var value = this.performance[i].portfolio.value();
var cost = this.performance[i].portfolio.cost();
if(value > 0 && cost > 0) {
var relative = (100 * value / cost);
history.push(relative);
}
}
return history;
},
getPortfolio: function () {
return this.performance[this.performance.length - 1].portfolio;
},
/**
* Use previous day's close price if close price is missing (e.g. public holiday)
* @private
*/
_padMissingDays: function () {
var previousDay = this.performance[0].portfolio.getStockAndClose();
for (var i = 1; i < this.performance.length; i++) {
var portfolio = this.performance[i].portfolio;
var stockClosePrices = portfolio.getStockAndClose();
for (var symbol in stockClosePrices) {
if (stockClosePrices[symbol] == undefined && symbol in previousDay) {
stockClosePrices[symbol] = previousDay[symbol];
portfolio.setClosePrice(symbol, previousDay[symbol]);
}
}
previousDay = stockClosePrices;
}
},
_adjustToWeekday: function (moment) {
if (moment.day() == 0) {
moment.add(1, 'days');
} else if (date.day() == 6) {
moment.add(2, 'days');
}
return moment;
}
};
|
export default {
name: "Zena",
x: 0,
y: 0,
control: "us",
zone: "green",
star: {
spectrum: "K",
temperature: "0",
size: "V"
},
planets: [
{
name: "Marider",
shape: "terrestrial",
size: "medium",
atmosphere: "trace",
hydrosphere: "dry",
biosphere: "remnants",
population: "6",
government: "corporation",
laws: "heavy",
tech: "advanced",
temperature: "cold",
resources: "abundant",
infrastructure: "high",
spaceport: "10",
satellites: "3",
description: "Marider is controlled by various Thurid companies and boasts some of the best shipyards in US space.",
tags: ["Multi-Corporate Control"]
},
{
name: "Thurid",
shape: "terrestrial",
size: "medium",
atmosphere: "standard",
hydrosphere: "moderate",
biosphere: "compatible",
population: "8",
government: "representative",
laws: "heavy",
tech: "interstellar",
temperature: "cold",
resources: "high",
infrastructure: "substantial",
spaceport: "9",
satellites: "1",
description: "Thurid is known for it’s industrial output and lenient trading laws. The US council chambers are located here.",
tags: []
},
{
name: "Pikos",
shape: "jovian",
size: "colossal",
atmosphere: "exotic",
hydrosphere: "none",
biosphere: "none",
population: "0",
government: "none",
laws: "none",
tech: "none",
temperature: "varied",
resources: "none",
infrastructure: "none",
spaceport: "0",
satellites: "0",
description: "Only gas giant in the system and a source of starship fuel.",
tags: []
},
{
name: "Central Command",
shape: "station",
size: "micro",
atmosphere: "standard",
hydrosphere: "none",
biosphere: "engineered",
population: "5",
government: "participatory",
laws: "extreme",
tech: "foundational",
temperature: "temperate",
resources: "none",
infrastructure: "covered",
spaceport: "4",
satellites: "0",
description: "Central Command is the political capitol of the United Systems. It is a space station located at the edge of the \
Zena system, and is governed solely by the United Systems council.",
tags: ["US Capital"]
}
],
description: "While Al-Taleqani and Careeno are the superpowers of \
interstellar politics, Zena is the close third. It’s position in the middle of the \
United Systems’ territory has meant that it has become the de-facto capital."
}
|
import React from "react"
import PropTypes from "prop-types"
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"
import Link from "./Link"
const BoxNav = ({ navItems }) => (
<div className="card-footer">
{navItems.map((navItem, navIndex) => (
<Link href={navItem.link} className="card-footer-item" key={navIndex}>
{navItem.fa &&
<span className="icon">
<FontAwesomeIcon icon={["fab", navItem.fa]} />
</span>
}
{navItem.name}
</Link>
))}
</div>
)
BoxNav.propTypes = {
navItems: PropTypes.arrayOf(
PropTypes.shape({
link: PropTypes.string.isRequired,
name: PropTypes.string,
fa: PropTypes.string,
})
)
}
export default BoxNav
|
module.exports = checkQuote
function checkQuote(context) {
var marker = context.options.quote || '"'
if (marker !== '"' && marker !== "'") {
throw new Error(
'Cannot serialize title with `' +
marker +
'` for `options.quote`, expected `"`, or `\'`'
)
}
return marker
}
|
"use strict";
/** @test {index} */
describe("index", () => {
});
|
cordova.define("org.jshybugger.cordova.jsHybuggerLoader", function(require, exports, module) { var newLocation = typeof(JsHybuggerNI) !== 'undefined' ? JsHybuggerNI.getDebugUrl(window.location.toString()) : window.location.toString();
if (newLocation != window.location.toString()) {
console.log('jsHybugger redirected to: ' + newLocation);
window.location = newLocation;
}
});
|
describe("", function() {
var rootEl;
beforeEach(function() {
rootEl = browser.rootEl;
browser.get("build/docs/examples/example-example25/index-jquery.html");
});
it('should allow user expression testing', function() {
element(by.css('.expressions button')).click();
var lis = element(by.css('.expressions ul')).all(by.repeater('expr in exprs'));
expect(lis.count()).toBe(1);
expect(lis.get(0).getText()).toEqual('[ X ] 3*10|currency => $30.00');
});
});
|
var app = angular.module('mobile');
app.controller('CouponSelect', function ($scope, ShareSvc, UserCouponSvc) {
document.title = '我的优惠券';
ShareSvc.user().then(function (user) {
UserCouponSvc.listPaged(user._id, CouponStatus.Usable, 1).then(function (userCoupons) {
$scope.userCoupons = userCoupons.data;
});
});
});
|
console.warn( "THREE.LineGeometry: As part of the transition to ES6 Modules, the files in 'examples/js' were deprecated in May 2020 (r117) and will be deleted in December 2020 (r124). You can find more information about developing using ES6 Modules in https://threejs.org/docs/index.html#manual/en/introduction/Import-via-modules." );
/**
* @author WestLangley / http://github.com/WestLangley
*
*/
THREE.LineGeometry = function () {
THREE.LineSegmentsGeometry.call( this );
this.type = 'LineGeometry';
};
THREE.LineGeometry.prototype = Object.assign( Object.create( THREE.LineSegmentsGeometry.prototype ), {
constructor: THREE.LineGeometry,
isLineGeometry: true,
setPositions: function ( array ) {
// converts [ x1, y1, z1, x2, y2, z2, ... ] to pairs format
var length = array.length - 3;
var points = new Float32Array( 2 * length );
for ( var i = 0; i < length; i += 3 ) {
points[ 2 * i ] = array[ i ];
points[ 2 * i + 1 ] = array[ i + 1 ];
points[ 2 * i + 2 ] = array[ i + 2 ];
points[ 2 * i + 3 ] = array[ i + 3 ];
points[ 2 * i + 4 ] = array[ i + 4 ];
points[ 2 * i + 5 ] = array[ i + 5 ];
}
THREE.LineSegmentsGeometry.prototype.setPositions.call( this, points );
return this;
},
setColors: function ( array ) {
// converts [ r1, g1, b1, r2, g2, b2, ... ] to pairs format
var length = array.length - 3;
var colors = new Float32Array( 2 * length );
for ( var i = 0; i < length; i += 3 ) {
colors[ 2 * i ] = array[ i ];
colors[ 2 * i + 1 ] = array[ i + 1 ];
colors[ 2 * i + 2 ] = array[ i + 2 ];
colors[ 2 * i + 3 ] = array[ i + 3 ];
colors[ 2 * i + 4 ] = array[ i + 4 ];
colors[ 2 * i + 5 ] = array[ i + 5 ];
}
THREE.LineSegmentsGeometry.prototype.setColors.call( this, colors );
return this;
},
fromLine: function ( line ) {
var geometry = line.geometry;
if ( geometry.isGeometry ) {
this.setPositions( geometry.vertices );
} else if ( geometry.isBufferGeometry ) {
this.setPositions( geometry.attributes.position.array ); // assumes non-indexed
}
// set colors, maybe
return this;
},
copy: function ( /* source */ ) {
// todo
return this;
}
} );
|
'use strict';
describe('Service: solvice', function () {
// load the service's module
beforeEach(module('vcPlannerApp'));
// instantiate service
var solvice;
beforeEach(inject(function (_solvice_) {
solvice = _solvice_;
}));
it('should do something', function () {
expect(!!solvice).toBe(true);
});
});
|
import {action} from "mobx";
import MainStore from "../common/MainStore";
import ToastStore from "../toast/ToastStore";
import commonActions from "../common/commonActions";
import "whatwg-fetch";
// TODO: ES2015
module.exports = {
saveDownloadList: action(saveDownloadList),
hideDownloadCard: action(hideDownloadCard)
};
function saveDownloadList(title, id) {
if (commonActions.isInvalidTitle(title) ||
commonActions.isDuplicateTitle(title) ||
commonActions.isInvalidId(id)) {
return;
}
fetch("https://spoilerblocker.herokuapp.com/downloadList?id=" + id, {
method: "get",
credentials: "include"
}).then(function(response) {
return response.json();
}).then(function(data) {
if (data.Status !== "Success") {
ToastStore.isMissingList = true;
return;
}
const tagArr = commonActions.tagStringToArray(data.list.tags);
if (commonActions.isInvalidTags(tagArr)) {
// Ideally should never happen, as tags on website should be valid
return;
}
commonActions.addNewList(title, tagArr);
hideDownloadCard();
});
}
function hideDownloadCard() {
MainStore.isDownloadCardVisible = false;
}
|
import React, { Component } from "react";
import { ReactiveBase, MultiList, ReactiveElement } from "../../app.js";
import { combineStreamData } from "../../middleware/helper.js";
import ResponsiveStory from "./ResponsiveStory";
import { GetTopTopics } from "./helper";
import { Img } from "../Img.js";
require("../list.css");
export default class WithTheme extends Component {
constructor(props) {
super(props);
this.cityQuery = this.cityQuery.bind(this);
this.onAllData = this.onAllData.bind(this);
this.DEFAULT_IMAGE = "http://www.avidog.com/wp-content/uploads/2015/01/BellaHead082712_11-50x65.jpg";
}
cityQuery(value) {
if (value) {
const field = "group.group_city.group_city_simple";
const query = JSON.parse(`{"${field}":${JSON.stringify(value)}}`);
return { terms: query };
} return null;
}
componentDidMount() {
ResponsiveStory();
}
onAllData(res, err) {
let result = null;
if (res && res.appliedQuery) {
let combineData = res.currentData;
if (res.mode === "historic") {
combineData = res.currentData.concat(res.newData);
} else if (res.mode === "streaming") {
combineData = combineStreamData(res.currentData, res.newData);
}
if (combineData) {
combineData = GetTopTopics(combineData);
const resultMarkup = combineData.map((data, index) => {
if (index < 5) {
return this.itemMarkup(data, index);
}
});
result = (
<div className="trendingTopics col s12 col-xs-12" style={{ padding: "10px", paddingBottom: "60px", color: "#eee" }}>
<table className="table">
<tbody>
{resultMarkup}
</tbody>
</table>
</div>
);
}
}
return result;
}
itemMarkup(data, index) {
return (
<tr key={index}>
<th>{data.name}</th>
<td>{data.value}</td>
</tr>
);
}
render() {
return (
<ReactiveBase
app="meetup2"
credentials="qz4ZD8xq1:a0edfc7f-5611-46f6-8fe1-d4db234631f3"
type="meetup"
theme="rbc-dark"
>
<div className="row reverse-labels">
<div className="col s6 col-xs-6">
<ReactiveElement
componentId="SearchResult"
from={0}
size={1000}
onAllData={this.onAllData}
placeholder="Select a city from the input filter..."
title="Reactive Element: Dark Theme"
{...this.props}
react={{
and: "CitySensor"
}}
/>
</div>
<div className="col s6 col-xs-6">
<MultiList
componentId="CitySensor"
dataField="group.group_city.group_city_simple"
showCount={true}
size={10}
title="Input Filter"
initialLoader="Loading city list.."
selectAllLabel="All cities"
customQuery={this.cityQuery}
searchPlaceholder="Search City"
includeSelectAll={true}
/>
</div>
</div>
</ReactiveBase>
);
}
}
|
'use strict';
const React = require('react');
const rB = require('react-bootstrap');
const AppActions = require('../actions/AppActions');
const ListNotif = require('./ListNotif');
const AppStatus = require('./AppStatus');
const Counter = require('./Counter');
const Follow = require('./Follow');
const DisplayError = require('./DisplayError');
const cE = React.createElement;
class MyApp extends React.Component {
constructor(props) {
super(props);
this.state = this.props.ctx.store.getState();
}
componentDidMount() {
if (!this.unsubscribe) {
this.unsubscribe = this.props.ctx.store
.subscribe(this._onChange.bind(this));
this._onChange();
}
}
componentWillUnmount() {
if (this.unsubscribe) {
this.unsubscribe();
this.unsubscribe = null;
}
}
_onChange() {
if (this.unsubscribe) {
this.setState(this.props.ctx.store.getState());
}
}
render() {
const following = this.state.linkedTo ?
this.state.linkedTo.slice(0, -8) :
'NOBODY';
return cE('div', {className: 'container-fluid'},
cE(DisplayError, {
ctx: this.props.ctx,
error: this.state.error
}),
cE(rB.Panel, null,
cE(rB.Panel.Heading, null,
cE(rB.Panel.Title, null,
cE(rB.Grid, {fluid: true},
cE(rB.Row, null,
cE(rB.Col, {sm:1, xs:1},
cE(AppStatus, {
isClosed: this.state.isClosed
})
),
cE(rB.Col, {
sm: 5,
xs:10,
className: 'text-right'
}, 'Counter Example'),
cE(rB.Col, {
sm: 5,
xs:11,
className: 'text-right'
}, this.state.fullName)
)
)
)
),
cE(rB.Panel.Body, null,
cE(rB.Panel, null,
cE(rB.Panel.Heading, null,
cE(rB.Panel.Title, null, 'Counter')
),
cE(rB.Panel.Body, null,
cE(Counter, {
ctx: this.props.ctx,
counter: this.state.counter,
increment: this.state.increment
})
)
),
cE(rB.Panel, null,
cE(rB.Panel.Heading, null,
cE(rB.Panel.Title, null, 'Last Notifications')
),
cE(rB.Panel.Body, null,
cE(ListNotif, {
notif: this.state.notif
})
)
),
cE(rB.Panel, null,
cE(rB.Panel.Heading, null,
cE(rB.Panel.Title, null, `Following ${following}`)
),
cE(rB.Panel.Body, null,
cE(Follow, {
ctx: this.props.ctx
})
)
)
)
)
);
}
};
module.exports = MyApp;
|
'use strict';
/**
* @ngdoc overview
* @name tryingAngularJsApp
* @description
* # tryingAngularJsApp
*
* Main module of the application.
*/
angular
.module('tryingAngularJsApp', [
'ngAnimate',
'ngAria',
'ngCookies',
'ngMessages',
'ngResource',
'ngRoute',
'ngSanitize',
'ngTouch'
])
.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl',
controllerAs: 'main'
})
.when('/about', {
templateUrl: 'views/about.html',
controller: 'AboutCtrl',
controllerAs: 'about'
})
.otherwise({
redirectTo: '/'
});
});
|
function Controller() {
require("alloy/controllers/BaseController").apply(this, Array.prototype.slice.call(arguments));
$model = arguments[0] ? arguments[0].$model : null;
var $ = this, exports = {};
Alloy.Models.instance("user");
_.extend($, $.__views);
var user = Alloy.Models.user;
user.set("id", "instance");
user.fetch();
Alloy.createController(user.authenticatedStatus() ? "home" : "login").getView().open();
_.extend($, exports);
}
var Alloy = require("alloy"), Backbone = Alloy.Backbone, _ = Alloy._, A$ = Alloy.A, $model;
module.exports = Controller;
|
/**
* @license Copyright 2019 The Lighthouse Authors. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
'use strict';
/** @typedef {import('./common.js').Result} Result */
/** @typedef {import('./common.js').Summary} Summary */
/** @typedef {import('../run-on-all-assets.js').Golden} Golden */
import fs from 'fs';
import * as common from './common.js';
/**
* @template T
* @param {number} percentile 0 - 1
* @param {T[]} values
* @param {(sortValue: T) => number} mapper
*/
function getPercentileBy(percentile, values, mapper) {
const resultsWithValue = values.map(value => {
return {sortValue: mapper(value), value};
});
resultsWithValue.sort((a, b) => a.sortValue - b.sortValue);
const pos = Math.floor((values.length - 1) * percentile);
return resultsWithValue[pos].value;
}
/**
* Returns run w/ the %ile based on FCP.
* @param {number} percentile
* @param {Result[]} results
*/
function getPercentileResult(percentile, results) {
const resultsWithMetrics = results.map(result => {
const metrics = common.getMetrics(loadLhr(result.lhr));
if (!metrics) throw new Error('could not find metrics'); // This shouldn't happen.
return {result, metrics};
});
return getPercentileBy(
percentile, resultsWithMetrics, ({metrics}) => Number(metrics.firstContentfulPaint)).result;
}
/**
* @param {string} filename
* @return {LH.Result}
*/
function loadLhr(filename) {
return JSON.parse(fs.readFileSync(`${common.collectFolder}/${filename}`, 'utf-8'));
}
/**
* @param {string} filename
*/
function copyToGolden(filename) {
fs.copyFileSync(`${common.collectFolder}/${filename}`, `${common.goldenFolder}/${filename}`);
}
/**
* @param {string} filename
* @param {string} data
*/
function saveGoldenData(filename, data) {
fs.writeFileSync(`${common.goldenFolder}/${filename}`, data);
}
/** @type {typeof common.ProgressLogger['prototype']} */
let log;
async function main() {
log = new common.ProgressLogger();
/** @type {Summary} */
const summary = common.loadSummary();
const goldenSites = [];
for (const [index, {url, wpt, unthrottled}] of Object.entries(summary.results)) {
log.progress(`finding median ${Number(index) + 1} / ${summary.results.length}`);
// Use the nearly-best-case run from WPT, to match the optimistic viewpoint of lantern, and
// avoid variability that is not addressable by Lighthouse. Don't use the best case because
// that increases liklihood of using a run that failed to load an important subresource.
const medianWpt = getPercentileResult(0.25, wpt);
// Use the median run for unthrottled.
const medianUnthrottled = getPercentileResult(0.5, unthrottled);
if (!medianWpt || !medianUnthrottled) continue;
if (!medianUnthrottled.devtoolsLog) throw new Error(`missing devtoolsLog for ${url}`);
const wptMetrics = common.getMetrics(loadLhr(medianWpt.lhr));
if (!wptMetrics) {
throw new Error('expected wptMetrics');
}
goldenSites.push({
url,
wpt3g: {
firstContentfulPaint: wptMetrics.firstContentfulPaint,
firstMeaningfulPaint: wptMetrics.firstMeaningfulPaint,
timeToConsistentlyInteractive: wptMetrics.interactive,
speedIndex: wptMetrics.speedIndex,
largestContentfulPaint: wptMetrics.largestContentfulPaint,
},
unthrottled: {
tracePath: medianUnthrottled.trace,
devtoolsLogPath: medianUnthrottled.devtoolsLog,
},
});
}
/** @type {Golden} */
const golden = {sites: goldenSites};
fs.rmSync(common.goldenFolder, {recursive: true, force: true});
fs.mkdirSync(common.goldenFolder);
saveGoldenData('site-index-plus-golden-expectations.json', JSON.stringify(golden, null, 2));
for (const result of goldenSites) {
log.progress('making site-index-plus-golden-expectations.json');
copyToGolden(result.unthrottled.devtoolsLogPath);
copyToGolden(result.unthrottled.tracePath);
}
log.progress('archiving ...');
await common.archive(common.goldenFolder);
log.closeProgress();
}
main();
|
$(function(){
// 设置jQuery Ajax全局的参数
$.ajaxSetup({
type: "POST",
error: function(jqXHR, textStatus, errorThrown){
switch (jqXHR.status){
case(500):
alert("服务器系统内部错误");
break;
case(401):
alert("未登录");
window.location.href = webRoot;
break;
case(403):
alert("无权限执行此操作");
case(404):
alert("找不到处理的方法");
break;
case(408):
alert("请求超时");
break;
case(518):
alert("登录超时");
window.location.href = webRoot;
break;
default:
alert("未知错误");
}
}
});
// 点击表头排序
$('th[class^=sorting]').click(function(){
var className = $(this).attr('class');
var sort = $(this).attr('title');
if(sort != ''){
$(this).parent().find('th').removeClass();
if(className == 'sorting'){
$(this).addClass('sorting_asc');
sort += ' asc';
}
else if(className == 'sorting_asc'){
$(this).addClass('sorting_desc');
sort += ' desc';
}
else if(className == 'sorting_desc'){
$(this).addClass('sorting_asc');
sort += ' asc';
}
var url = $('.panel-search form').attr('action');
if(url.indexOf('?') > -1){
url += '&sort=' + sort;
}
else{
url += '?sort=' + sort;
}
$.ajax({
type: 'post',
url: webRoot+url,
data: $('.panel-search form').serialize(),
dataType: 'html',
success: function(data){
$(".panel-content").html(data);
}
});
}
});
});
/**
* 菜单跳转
* @param obj 菜单本身(A标签)
* @param url 菜单访问地址
*/
function menu(obj,url){
$('.page-sidebar-menu li').removeClass('active');
rootliActive(obj);
$(obj).parent().addClass('active');
var header = '<li><i class="fa fa-home"> </i></li>' + getHeader(obj,'','');
$.ajax({
type: 'post',
url: webRoot+url,
dataType: 'html',
success: function(data){
$('.page-title').html($(obj).find('.title').text());
$('.content-header').html(header);
$('.content-panel').html(data);
}
});
}
/**
* 当前菜单的根目录选中
* @param obj
*/
function rootliActive(obj){
if($(obj).parent().parent().attr('class') == 'sub-menu'){
rootliActive($(obj).parent().parent().prev());
}
else{
$(obj).parent().addClass('active');
$(obj).parent().find('.title').after('<span class="selected"></span>');
}
}
/**
* 初始化页面的头
* @param obj
* @param header
* @param fa
* @returns {String}
*/
function getHeader(obj,header,fa){
var title = '<li><span>' + $(obj).find('.title').text() + '</span>' + fa + '</li>' + header;
if($(obj).parent().parent().attr('class') == 'sub-menu'){
return getHeader($(obj).parent().parent().prev(), title, '<i class="fa fa-angle-right"></i>');
}
else{
return title;
}
}
/**
* 分页查询
* @param pageNo 页码
*/
function page(pageNo){
var url = $('.panel-search form').attr('action');
if(url.indexOf('?') > -1){
url += '&pageNo=' + pageNo;
}
else{
url += '?pageNo=' + pageNo;
}
$.ajax({
type: 'post',
url: webRoot+url,
data: $('.panel-search form').serialize(),
dataType: 'html',
success: function(data){
$(".panel-content").html(data);
}
});
}
/**
* 查询
*/
function search(){
$.ajax({
type: 'post',
url: webRoot+$('.panel-search form').attr('action'),
data: $('.panel-search form').serialize(),
dataType: 'html',
success: function(data){
$(".panel-content").html(data);
}
});
}
/**
* 重置
*/
function reset(){
$('.panel-search form')[0].reset();
search();
}
/**
* 新增
* @param url 新增请求路径
*/
function add(url){
$.ajax({
type: 'post',
url: webRoot+url,
dataType: 'html',
success: function(data){
$(".panel-search").hide();
$(".panel-content").html(data);
}
});
}
/**
* 修改
* @param url 修改请求路径
*/
function update(url){
$.ajax({
type: 'post',
url: webRoot+url,
dataType: 'html',
success: function(data){
$(".panel-search").hide();
$(".panel-content").html(data);
}
});
}
/**
* 保存
* @param obj 保存按钮(按钮需要在form表单中)
*/
function save(obj){
if($(obj).closest('form').valid()){
$.ajax({
type: 'post',
url: webRoot+$(obj).closest('form').attr('action'),
data: $(obj).closest('form').serialize(),
dataType: 'json',
success: function(data){
alert(messages[data.result]);
search();
$(".panel-search").show();
}
});
}
}
/**
* 取消返回
*/
function cancel(){
search();
$(".panel-search").show();
}
/**
* 删除
* @param url 删除请求路径
* @param message 删除前提示信息
* @returns
*/
function del(url){
if(confirm(messages.delete_confirm)){
$.ajax({
type: 'post',
url: webRoot+url,
dataType: 'json',
success: function(data){
alert(messages[data.result]);
search();
}
});
}
}
/**
* ajax 提交
* @param url 请求路径
* @param isRefreshList 是否刷新列表
*/
function ajaxSubmit(url,isRefreshList){
$.ajax({
type: 'post',
url: webRoot+url,
dataType: 'json',
success: function(data){
alert(messages[data.result]);
if(isRefreshList){
search();
}
}
});
}
|
import merge from 'deepmerge';
import { grey4, lightBlack, blue1 } from '../../../../../styles/modules/variables';
import commonCss, { avatar } from '../../../common.styles';
export default merge(
commonCss,
{
row: {
paddingBottom: 20,
maxHeight: 177,
borderTop: `1px solid ${grey4}`,
},
avatar: {
...avatar(),
},
engineSelect: {
position: 'absolute',
top: 0,
left: 0,
},
primary: {
borderRight: `2px solid ${grey4}`,
},
icon: {
height: '100%',
},
title: {
'&:hover': {
cursor: 'pointer',
color: blue1,
},
},
secondary: {
flexWrap: 'wrap',
flexDirection: 'row',
justifyContent: 'space-between',
minWidth: '37%',
maxWidth: '37%',
padding: '0 20px',
paddingRight: 0,
},
description: {
fontSize: 13,
lineHeight: '20px',
color: lightBlack,
marginTop: 2,
},
logos: {
flexWrap: 'wrap',
alignContent: 'flex-start',
justifyContent: 'space-between',
width: 122,
marginRight: 15,
},
logo: {
'&:first-child': {
marginBottom: 20,
}
},
main: {
display: 'flex',
justifyContent: 'space-between',
},
}
)
|
/******************************************************************************
Redis dispatch client
*******************************************************************************/
'use strict';
var _ = require('underscore'),
Base = require('./base'),
logger = require('../../logger'),
redis = require('redis');
module.exports = function(options) {
_.extend(this, new Base(options));
//abort if we do not have an api key
if (!options.redis.host) return;
var sub = redis.createClient({
host: options.redis.host,
port: options.redis.port,
password: options.redis.password
});
var pub = redis.createClient({
host: options.redis.host,
port: options.redis.port,
password: options.redis.password
});
var ready = false, that = this;
sub.on('subscribe', function(channel) {
if (channel === 'fruum') {
ready = true;
logger.system('Redis dispatch connected');
}
});
sub.on('message', function(channel, message) {
if (channel !== 'fruum') return;
try {
message = JSON.parse(message);
_.each(that.getCallbacks(), function(cb) {
cb(message);
});
}
catch(err) {}
});
sub.subscribe('fruum');
//override emit function
this.emit = function(payload) {
if (!ready) return;
pub.publish('fruum', JSON.stringify(payload));
}
}
|
/**
* @require common:widget/jquery/jqueryEx.js
* @require common:widget/utils/underscore.js
* @require common:widget/dhtmlxSuite/dhtmlxEx.js
*/
$(window).resize(function() {
GPW.layout.mainLayout.setSizes();
});
var GPC = {
url:{
refreshGridUrl:GLOBAL.S.URL+GLOBAL.P.MODULES+"/a/resLoadRole?_value="+GLOBAL.P.value,
queryUrl:GLOBAL.S.URL+GLOBAL.P.MODULES+"/a/resQueryRole?_value="+GLOBAL.P.value,
updateUrl:GLOBAL.S.URL+GLOBAL.P.MODULES+"/a/updateResourceRole/Roles?format=xml&_value="+GLOBAL.P.value
},
constant:{add:"add",edit:"edit",delect:"delect",query:"query",
update:"update",detailQuery:"detailQuery",between:"between"}
}
var GPW = {
layout : {},
toolbar : {},
grid : {}
};
GPW.layout = {
mainLayout : {},
mainGridLayout:{},
init : function() {
this.mainLayout = new dhtmlXLayoutObject("layoutObj", "1C");
this.mainGridLayout=this.mainLayout.cells("a");
this.mainGridLayout.hideHeader();
}
}
GPW.grid = {
mainGrid : {},
gridDataProcessor : {},
init : function() {
this.mainGrid = GPW.layout.mainGridLayout.attachGrid();
this.mainGrid.setImagePath(GLOBAL.IconsPath);
this.mainGrid.setHeader("角色编码,角色名称,授权名称");
this.mainGrid.setColumnIds("name,alias,permissionStr");
this.mainGrid.setInitWidths("120,120,*");
this.mainGrid.setColAlign("left,left,left");
this.mainGrid.setColTypes("ro,ro,clist");
this.mainGrid.setColSorting("str,str,str");
this.mainGrid.registerCList(2,GLOBAL.P.P_PERMISSION);
var pagingContainer="<div id='recinfoArea' /><div id='pagingArea' style='border:none;'/>";
var statusBar=GPW.layout.mainGridLayout.attachStatusBar({height: 28});
statusBar.setText(pagingContainer);
this.mainGrid.enablePaging(true,20,5,"pagingArea",true,"recInfoArea");
this.mainGrid.setPagingSkin("toolbar", "dhx_skyblue");
//this.mainGrid.enableAutoWidth(true)
this.mainGrid.i18n.paging=GLOBAL.paging;
this.mainGrid.init();
this.mainGrid.attachEvent("onValidationError", function(id,index,value,rule){
parent.dhtmlx.message({
type:"error",
expire: -1,
text:"校验错误:"+GPW.grid.mainGrid.getColLabel(index)+","+GLOBAL.validText(rule)+",字段值不能为["+value+"]!"});
});
this.gridDataProcessor = new dataProcessor(GPC.url.updateUrl); //lock feed url
//this.gridDataProcessor.setTransactionMode("POST",false); //set mode as send-all-by-post
this.gridDataProcessor.setTransactionMode("REST");
this.gridDataProcessor.setUpdateMode("off"); //disable auto-update
this.gridDataProcessor.enableDataNames(true);
//只发送更改的项目
this.gridDataProcessor.enablePartialDataSend(true);
this.gridDataProcessor.init(this.mainGrid); //link dataprocessor to the grid
this.gridDataProcessor.attachEvent("onBeforeDataSending", function(id, state, data){
//去除Data数据的发送
_.each(data,function (v, k, value) {
if(!!v.data){
v.data=null;
delete v.data;
}
});
return true;
});
this.gridDataProcessor.attachEvent("onAfterUpdate", function(id, action, tid, element){
if(element instanceof Element){
if(element.getElementsByTagName("code").item(0)!=null){
var code=element.getElementsByTagName("code").item(0).childNodes[0].nodeValue;
var message=element.getElementsByTagName("message").item(0).childNodes[0].nodeValue;
if(code==-1){
parent.dhtmlx.message({
type:"error",
expire: -1,
text:message});
}
}
}
});
this.refreshMainGrid();
},
sendGridData : function(){
this.gridDataProcessor.sendData();
},
refreshMainGrid : function(url) {
if(!url){
url=GPC.url.refreshGridUrl;
}
this.mainGrid.clearAll();
this.mainGrid.load(url,"js");
}
}
GPW.toolbar = {
mainToolbar : {},
init : function() {
this.mainToolbar=GPW.layout.mainGridLayout.attachToolbar();
var toolbar = this.mainToolbar;
toolbar.setIconsPath(GLOBAL.IconsPath);
toolbar.addText("text_select", 0, "选");
this.mainToolbar.addSelectEx("queryName", 1, [{"text":"编码","value":"name"},{"text":"名称","value":"alias"}], 100);
toolbar.addInput("queryValue", 3, "", 200);
toolbar.addButton("query", 9, "查询", "new.gif", "new_dis.gif");
toolbar.addSeparator("sep1", 10);
toolbar.addButton("update", 16, "更新", "new.gif", "new_dis.gif");
this.mainToolbarClick();
},
mainToolbarClick:function(){
this.mainToolbar.attachEvent("onClick", function(id) {
switch(id)
{
case GPC.constant.query:
var toolbar = GPW.toolbar.mainToolbar;
var where = toolbar.getInput("queryName").value;
var queryValue = toolbar.getInput("queryValue").value;
var url=GPC.url.queryUrl+"&where="+encodeURI(where)+"&whereValue="+encodeURI(queryValue);
GPW.grid.refreshMainGrid(url);
break;
case GPC.constant.update:
GPW.grid.sendGridData();
break;
default:
}
});
}
}//end GPW.toolbar
$(function() {
GPW.layout.init();
GPW.grid.init();
GPW.toolbar.init();
});
|
'use strict'
var crypto = require('crypto');
var Authenticator = require('./authenticator.js');
/**
* A class implementing http digest authentication.
*
* @constructs Digest
* @param {ReplayDetector} detector - A replay detector registering hashes.
* @param {Function} identify - A function performing the password lookup.
*/
var Digest = function (detector, identify) {
Authenticator.call(this, identify);
this.detector = detector;
};
Digest.prototype = Object.create(Authenticator.prototype);
var hash = function (array) {
return crypto.createHash('md5').update(array.join(':')).digest('hex');
};
Digest.prototype.parse = function (authorization) {
var strings = /([a-z]*)=("[^"]*")(,|$)/g;
var unquoted = /([a-z]*)=([0-9A-Za-z]*)(,|$)/g;
var fields = {}, match;
// Parse all quoted values in the authorization header.
while (match = strings.exec(authorization)) {
fields[match[1]] = JSON.parse(match[2]);
}
// Parse the unquoted qop and nc values.
while (match = unquoted.exec(authorization)) {
fields[match[1]] = match[2];
}
return fields;
};
Digest.prototype.check = function (fields, realm, password, method) {
var identity;
var resource;
if (this.detector.check(fields.nonce, parseInt(fields.nc, 16)) !== true) {
return false;
} else if (password !== undefined && password !== null) {
identity = hash([fields.username, realm, password]);
resource = hash([method, fields.uri]);
return fields.response === hash([
identity,
fields.nonce,
fields.nc,
fields.cnonce,
fields.qop,
resource
]);
} else {
return false;
}
};
Digest.prototype.nonce = function () {
var nonce = Math.random();
this.detector.register(nonce);
return nonce;
};
Digest.prototype.header = function (realm) {
var result = '';
result += 'Digest realm="' + realm + '"';
result += 'qop="auth",nonce="' + this.nonce() + '"';
result += 'opaque="' + hash([realm]) + '"';
return result;
};
/**
* Request an authentication strategy for the passport module.
*
* @returns {passport.Strategy} A passport strategy for digest authentication.
*/
Digest.prototype.passport = function () {
this.name = 'digest';
return this;
};
module.exports = Digest;
|
var Utils = {
_parseUrl: function (url) {
var query_string = {};
var url = url.substring(url.lastIndexOf("?") + 1).split("&")[0];
var vars = url.split("&");
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split("=");
// If first entry with this name
if (typeof query_string[pair[0]] === "undefined") {
query_string[pair[0]] = decodeURIComponent(pair[1]);
// If second entry with this name
} else if (typeof query_string[pair[0]] === "string") {
var arr = [query_string[pair[0]], decodeURIComponent(pair[1])];
query_string[pair[0]] = arr;
// If third or later entry with this name
} else {
query_string[pair[0]].push(decodeURIComponent(pair[1]));
}
}
return query_string;
},
getParameterFromUrl: function (url, parameter) {
//TODO: Check if the parameter exists
return this._parseUrl(url)[parameter];
}
}
export {Utils as default}
|
var chai = require('chai');
var expect = chai.expect;
var sinonChai = require('sinon-chai');
var _ = require("underscore");
var syncClient = require("../../src/feedhenry").sync;
chai.use(sinonChai);
//work around phantomjs's issue: https://github.com/ariya/phantomjs/issues/10647
var fakeNavigator = {};
for (var i in navigator) {
fakeNavigator[i] = navigator[i];
}
fakeNavigator.onLine = true;
navigator = fakeNavigator;
var dataSetId = "myShoppingList";
var onSync = function(cb){
syncClient.forceSync(dataSetId, function(){
setTimeout(function(){
cb();
}, 600);
});
}
describe("test sync framework cloud handler", function(){
this.timeout(10000);
var header = { "Content-Type": "application/json" };
var xhr;
var requests;
before(function(done){
syncClient.init({
do_console_log: true,
sync_frequency: 1,
sync_active: false,
storage_strategy: ['memory'],
crashed_count_wait: 0
});
syncClient.manage(dataSetId, {"sync_active": false, "has_custom_sync": false}, {}, {}, done);
});
beforeEach(function(done){
xhr = sinon.useFakeXMLHttpRequest();
requests = [];
xhr.onCreate = function(req){
console.log("Got sync request", req);
requests.push(req);
}
syncClient.manage(dataSetId, {}, {}, {}, function(){
syncClient.clearPending(dataSetId, function(){
done();
});
});
});
afterEach(function(done){
xhr.restore();
syncClient.notify(undefined);
syncClient.stopSync(dataSetId, done, done);
});
it("load initial dataset from remote", function(done){
//since we want to check what requests have been sent and their data,
//we turn off sync and use forceSync to control sync loop
onSync(function(){
//verify there is one request is in the queue
expect(requests.length).to.equal(1);
var reqObj = requests[0];
expect(reqObj.url).to.have.string("/mbaas/sync/" + dataSetId);
expect(reqObj.method.toLowerCase()).to.equal("post");
var reqBody = JSON.parse(reqObj.requestBody);
expect(reqBody.fn).to.equal("sync");
expect(reqBody.pending).is.empty;
//return hash
var mockHash = "97d170e1550eee4afc0af065b78cda302a97674c";
reqObj.respond(200, header, JSON.stringify({
"hash": mockHash,
"updates": {}
}));
var syncRecorsReq = requests[1];
reqBody = JSON.parse(syncRecorsReq.requestBody);
expect(reqBody.fn).to.equal("syncRecords");
syncRecorsReq.respond(200, header, JSON.stringify({
"hash": mockHash
}));
//server turned empty dataset, then the client dataset should be empty as well
syncClient.getDataset(dataSetId, function(dataset){
expect(dataset.data).is.empty;
done();
});
});
});
});
|
LineAnnotate = Rickshaw.Class.create({
initialize: function(args) {
var graph = this.graph = args.graph;
var element = this.element = document.createElement('div');
element.className = 'line_annotation_parent';
this.visible = true;
graph.element.appendChild(element);
this.lastEvent = null;
this._addListeners();
this.onShow = args.onShow;
this.onHide = args.onHide;
this.onRender = args.onRender;
this.shortFormatter = args.shortFormatter;
this.detailedFormatter = args.detailedFormatter;
},
update: function() {
var graph = this.graph;
var j = 0;
var points = [];
this.graph.series.active().forEach(function(series) {
var data = graph.stackedData[j++];
if (data.length < 2)
return;
var prev = data[0];
data.forEach(function(value, index){
if (index == 0)
return;
var point = {
prev: prev,
series: series,
value: value
};
points.push(point);
prev = value;
}, this);
}, this);
this.element.innerHTML = '';
this.element.style.left = '0px';
this.visible && this.render(points);
},
hide: function() {
this.visible = false;
this.element.classList.add('inactive');
if (typeof this.onHide == 'function') {
this.onHide();
}
},
show: function() {
this.visible = true;
this.element.classList.remove('inactive');
if (typeof this.onShow == 'function') {
this.onShow();
}
},
render: function(points) {
var graph = this.graph;
var alignables = [];
this.element.innerHTML = '';
points.forEach(function(point){
if (point.value.y === null || point.prev.y === null) return;
var series = point.series;
var shortFormatted = this.shortFormatter(series, point.value);
if (shortFormatted === null) return;
var detailedFormatted = this.detailedFormatter(series, point.value);
var outer = document.createElement('div');
outer.className = 'line_annotation_outer';
var x = graph.x(point.value.x);
outer.style.left = x + 'px';
outer.style.top = graph.y(point.value.y0 + (point.value.y + point.prev.y) / 2) + 'px';
var item = document.createElement('div');
item.className = 'line_annotation';
function displayShort() {
item.innerHTML = shortFormatted;
outer.classList.remove('detailed');
}
function displayDetailed() {
item.innerHTML = detailedFormatted;
outer.classList.add('detailed');
}
displayShort();
item.addEventListener('mouseenter', displayDetailed);
item.addEventListener('mouseleave', displayShort);
outer.appendChild(item);
this.element.appendChild(outer);
item.classList.add('active');
// Assume left alignment until the element has been displayed and
// bounding box calculations are possible.
alignables.push({
orignalX: x,
outer: outer,
inner: item
});
}, this);
alignables.forEach(function(el) {
el.outer.classList.add('fromleft');
}, false);
this.show();
// If left-alignment results in any error, try right-alignment.
alignables.forEach(function(el) {
var leftAlignError = this._calcLayoutError(el.inner);
if (leftAlignError > 0) {
el.outer.style.left = (el.orignalX - 500) + "px";
el.outer.classList.remove('fromleft');
el.outer.classList.add('fromright');
// If right-alignment is worse than left alignment, switch back.
var rightAlignError = this._calcLayoutError(el.inner);
if (rightAlignError > leftAlignError) {
el.outer.style.left = el.orignalX + "px";
el.outer.classList.remove('fromright');
el.outer.classList.add('fromleft');
}
}
}, this);
if (typeof this.onRender == 'function') {
this.onRender(points);
}
},
_calcLayoutError: function(el) {
// Layout error is calculated as the number of linear pixels by which
// an alignable extends past the left or right edge of the parent.
var parentRect = this.element.parentNode.getBoundingClientRect();
var error = 0;
var rect = el.getBoundingClientRect();
if (!rect.width) {
return;
}
if (rect.right > parentRect.right) {
error += rect.right - parentRect.right;
}
if (rect.left < parentRect.left) {
error += parentRect.left - rect.left;
}
return error;
},
_addListeners: function() {
this.graph.onUpdate( function() { this.update() }.bind(this) );
}
});
|
/*
Template Name: Color Admin - Responsive Admin Dashboard Template build with Twitter Bootstrap 3.3.4
Version: 1.7.0
Author: Sean Ngu
Website: http://www.seantheme.com/color-admin-v1.7/admin/
*/var handleDataTableTools=function(){"use strict";if($("#data-table").length!==0){$("#data-table").DataTable({dom:'T<"clear">lfrtip',tableTools:{sSwfPath:"assets/plugins/DataTables/swf/copy_csv_xls_pdf.swf"}})}};var TableManageTableTools=function(){"use strict";return{init:function(){handleDataTableTools()}}}()
|
/**
* Created by Administrator on 14/12/2016.
*/
$(document).ready(function () {
function showDateNgaySinh(target) {
//datetimepicker nam sinh.
var date_input = $('input[name="' + target + '"]');
var container = $('.bootstrap-iso form').length > 0 ? $('.bootstrap-iso form').parent() : "body";
date_input.datepicker({
format: 'dd/mm/yyyy',
container: container,
todayHighlight: true,
autoclose: true,
});
}
function showDateWithFocus(target) {
var date_input = $('input[name="' + target + '"]');
var container = $('.bootstrap-iso form').length > 0 ? $('.bootstrap-iso form').parent() : "body";
date_input.datepicker({
format: 'dd/mm/yyyy',
container: container,
todayHighlight: true,
autoclose: true,
}).focus();
}
// Ngay sinh
showDateNgaySinh('inputNgaysinh');
// when click icon calender
$('#btn_inputNgaySinh').click(function () {
showDateWithFocus('inputNgaysinh');
});
//End ngay sinh
// Nam nhap hoc
showDateNgaySinh('inputNamNhapHoc[]');
// when click icon calender
$('#btn_nam_nhap_hoc').click(function () {
showDateWithFocus('inputNamNhapHoc[]');
});
// End nam nhap hoc
// Nam tot nghiep
showDateNgaySinh('inputNamTotNghiep[]');
// when click icon calender
$('#btn_nam_tot_nghiep').click(function () {
showDateWithFocus('inputNamTotNghiep[]');
});
// End nam tot nghiep
// Bat dau du an
showDateNgaySinh('inputThoiGianBatDau[]');
// when click icon calender
$('#btn_inputThoiGianBatDau').click(function () {
showDateWithFocus('inputThoiGianBatDau[]');
});
// End bat dau du an
// Ket thuc du an
showDateNgaySinh('inputThoiGianKetThuc[]');
// when click icon calender
$('#btn_inputThoiGianKetThuc').click(function () {
showDateWithFocus('inputThoiGianKetThuc[]');
});
// Ket thuc du an
// Bat dau kinh nghiem
showDateNgaySinh('ngaybatdau[]');
// when click icon calender
$('#btn_inputTime_begin_du_an').click(function () {
showDateWithFocus('ngaybatdau[]');
});
// Ket thuc du an
// Ket thuc du an
showDateNgaySinh('ngayketthuc[]');
// when click icon calender
$('#btn_inputTime_end_du_an').click(function () {
showDateWithFocus('ngayketthuc[]');
});
// Ket thuc du an
});
|
module.exports = [
require('./abs'),
require('./add'),
require('./ceil'),
require('./cube'),
require('./divide'),
require('./dotDivide'),
require('./dotMultiply'),
require('./dotPow'),
require('./exp'),
require('./fix'),
require('./floor'),
require('./gcd'),
require('./lcm'),
require('./log'),
require('./log10'),
require('./mod'),
require('./multiply'),
require('./norm'),
require('./nthRoot'),
require('./pow'),
require('./round'),
require('./sign'),
require('./sqrt'),
require('./square'),
require('./subtract'),
require('./unaryMinus'),
require('./unaryPlus'),
require('./xgcd')
];
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.