text
stringlengths 2
6.14k
|
|---|
/**
* Whether a reference is defined or not.
* @method isDefined
* @param {*} value Reference to check
* @return {boolean} Whether a reference is defined or not.
*/
export const isDefined = (value) => {
if (typeof value === 'undefined') {
return false
}
return true
}
/**
* Whether a reference is undefined or not.
* @method isUndefined
* @param {*} value Reference to check
* @return {boolean} Whether a reference is undefined or not.
*/
export const isUndefined = (value) => !isDefined(value)
/**
* Whether a reference is string or not.
* @method isString
* @param {*} value Reference to check
* @return {Boolean} Whether a reference is string or not.
*/
export const isString = (value) => {
if (typeof value === 'string') {
return true
}
return false
}
/**
* Whether a reference is integer type or not.
* @method isIntegerType
* @param {*} value Reference to check
* @return {Boolean} Whether a reference is integer type or not.
*/
export const isIntegerType = (value) => {
if (value === parseInt(value, 10)) {
return true
}
return false
}
/**
* Whether a reference is finite number or not.
* @method isFiniteNumber
* @param {*} value Reference to check
* @return {Boolean} Whether a reference is finite number or not.
*/
export const isFiniteNumber = (value) => {
if (typeof (value) !== 'number' && typeof (value) !== 'string') {
return false
} else {
return (value === parseFloat(value) && isFinite(value))
}
}
/**
* Whether a reference is numeric or not.
* @method isNumeric
* @param {*} value Reference to check
* @return {Boolean} Whether a reference is numeric or not. <br/>
*
* (e.g. 0, 0.0, -1, '-1.5', '30.0', '20.80', -20.85, .42, 0x89f, '0x89f', 8e5)
*/
export const isNumeric = (value) => !isNaN(parseFloat(value)) && isFinite(value)
export default {
isDefined,
isUndefined,
isString,
isIntegerType,
isFiniteNumber,
isNumeric
}
|
(function () {
"use strict";
require('../bufferjs/indexOf');
var assert = require('assert');
// Test the static version, Buffer needle
function test1() {
var haystack = new Buffer(10)
, needle = new Buffer(1);
needle[0] = haystack[0] = 255;
assert.equal(Buffer.indexOf(haystack, needle), 0);
assert.equal(Buffer.indexOf(haystack, new Buffer(haystack.length)), -1);
}
// Test the OO version, String needle
function test2() {
var haystack = new Buffer(20)
, needle = '\r\n'
, index = 5;
haystack.write(needle, index);
assert.equal(haystack.indexOf(needle), index);
assert.equal(haystack.indexOf('should not be found'), -1);
}
// Test starting from a specified index
function testFromSpecifiedIndex() {
var haystack = new Buffer('abracadabra')
, needle = new Buffer('a');
assert.equal(haystack.indexOf(needle), 0);
assert.equal(Buffer.indexOf(haystack, needle, 1), 3);
assert.equal(haystack.indexOf(needle, 4), 5);
assert.equal(Buffer.indexOf(haystack, needle, 6), 7);
assert.equal(haystack.indexOf(needle, 8), 10);
}
test1();
test2();
testFromSpecifiedIndex();
console.log("Done. `indexOf` tests passed!");
}());
|
define([
'pex/materials/Material',
'pex/gl/Context',
'pex/gl/Program',
'pex/color/Color',
'pex/utils/ObjectUtils',
'lib/text!pex/materials/SolidColor.glsl'
], function (Material, Context, Program, Color, ObjectUtils, SolidColorGLSL) {
function SolidColor(uniforms) {
this.gl = Context.currentContext.gl;
var program = new Program(SolidColorGLSL);
var defaults = {
color: Color.create(1, 1, 1, 1),
pointSize: 1,
premultiplied: 0
};
uniforms = ObjectUtils.mergeObjects(defaults, uniforms);
Material.call(this, program, uniforms);
}
SolidColor.prototype = Object.create(Material.prototype);
return SolidColor;
});
|
var db = require('./db')
// create a comments sublevel
var comments = db.sublevel('comments')
var Comment = module.exports = function(key, attrs) {
this.key = key
if (attrs) {
this.author = attrs.author
this.date = attrs.date
this.body = attrs.body
}
}
Comment.prototype.save = function(callback) {
var key = this.key || this.author.replace(/\s/g, '_').replace(/[\W\D\-]/g, '')
comments.put(key, {
author: this.author,
date: this.date,
body: this.body
}, callback)
}
Comment.get = function(key, callback) {
comments.get(key, function(err, value) {
if (err && err.notFound) return callback()
if (err) return callback(err)
callback(null, new Comment(key, value))
})
}
Comment.list = function(postKey, callback) {
var results = []
var options = {
start: postKey + '!',
end: postKey + '!\xff'
}
comments.createReadStream(options)
.on('data', function(data) {
results.push(new Comment(data.key, data.value))
})
.on('error', function(err) {
if (callback)
callback(err)
callback = null
})
.on('end', function() {
if (callback)
callback(null, results)
callback = null
})
}
|
var $routeProviderReference;
var app = angular.module('cdg', [require('angular-route'),'angularUtils.directives.dirPagination', 'ngCookies']);
var basel = require('basel-cli');
var routes = basel.routes();
app.config(['$routeProvider', function($routeProvider) {
$routeProviderReference = $routeProvider;
}]);
app.run(['$rootScope', '$http', '$route', '$location', '$cookieStore', function($rootScope, $http, $route, $location, $cookieStore) {
$rootScope.globals = $cookieStore.get('globals') || {};
if ($rootScope.globals.currentUser) {
$http.defaults.headers.common['Authorization'] = 'Basic ' + $rootScope.globals.currentUser.authdata;
}
$rootScope.$on('$locationChangeStart', function (event, next, current) {
// redirect to login page if not logged in
if (!$rootScope.globals.currentUser) {
$('#menubar').hide();
$location.path('/login');
}else{
$('#menubar').show();
}
});
//getting routes
angular.forEach(routes, function (route) {
$routeProviderReference.when( route.when, route.data );
});
/**
* For new routes:
* $routeProviderReference.when('/when',{
* controller: 'yourController',
* templateUrl: 'your-view.html'
* })
*
*/
$routeProviderReference.when('/equilibrio',{
controller: 'equilibrioController',
templateUrl: 'views/equilibrio.html'
});
$routeProviderReference.when('/vpl',{
controller: 'vplController',
templateUrl: 'views/vpl.html'
});
$routeProviderReference.when('/fluxoCaixa',{
controller: 'fluxoCaixaController',
templateUrl: 'views/fluxoCaixa.html'
});
$routeProviderReference.when('/analise',{
controller: 'analiseController',
templateUrl: 'views/analise.html'
});
$routeProviderReference.when('/balanco',{
controller: 'balancoController',
templateUrl: 'views/balanco.html'
});
$routeProviderReference.when('/receita',{
controller: 'receitaController',
templateUrl: 'views/receita.html'
});
$routeProviderReference.when('/custoTotal',{
controller: 'custoTotalController',
templateUrl: 'views/custoTotal.html'
});
$routeProviderReference.when('/custoOportunidade',{
controller: 'custoOportunidadeController',
templateUrl: 'views/custoOportunidade.html'
});
$routeProviderReference.when('/custoOperacional',{
controller: 'custoOperacionalController',
templateUrl: 'views/custoOperacional.html'
});
$routeProviderReference.when('/investimento',{
controller: 'investimentoController',
templateUrl: 'views/investimento.html'
});
$routeProviderReference.when('/custoAdm',{
controller: 'custoAdmController',
templateUrl: 'views/custoAdm.html'
});
$routeProviderReference.when('/custoVariavel',{
controller: 'custoVariavelController',
templateUrl: 'views/custoVariavel.html'
});
$routeProviderReference.when('/custoFixo',{
controller: 'custoFixoController',
templateUrl: 'views/custoFixo.html'
});
$routeProviderReference.when('/variacaoRebanho',{
controller: 'variacaoRebanhoController',
templateUrl: 'views/variacaoRebanho.html'
});
$routeProviderReference.when('/depreciacoes',{
controller: 'depreciacoesController',
templateUrl: 'views/depreciacoes.html'
});
$routeProviderReference.when('/inventario',{
controller: 'inventarioController',
templateUrl: 'views/inventario.html'
});
$routeProviderReference.when('/cria',{
controller: 'criaController',
templateUrl: 'views/cria.html'
});
$routeProviderReference.when('/',{
controller: 'inicioController',
templateUrl: 'views/inicio.html'
});
$routeProviderReference.when('/rebanho',{
controller: 'rebanhoController',
templateUrl: 'views/rebanho.html'
});
$routeProviderReference.when('/null',{
controller: 'usuariosController',
templateUrl: 'views/usuarios.html'
});
$routeProviderReference.when('/manutencao',{
controller: 'manutencaoController',
templateUrl: 'views/manutencao.html'
});
$routeProviderReference.when('/benfeitorias',{
controller: 'benfeitoriasController',
templateUrl: 'views/benfeitorias.html'
});
$routeProviderReference.when('/maquinas',{
controller: 'maquinasController',
templateUrl: 'views/maquinas.html'
});
$routeProviderReference.when('/evolucao',{
controller: 'evolucaoController',
templateUrl: 'views/evolucao.html'
});
$routeProviderReference.when('/login',{
controller: 'loginController',
templateUrl: 'views/login.html'
});
$routeProviderReference.otherwise({ redirectTo: '/' });
$route.reload();
}]);
|
import SettingsListView from '../components/settingslist.js'
import { connect } from 'react-redux'
import {
showToggleAcceptingModal,
hideToggleAcceptingModal,
updateSettings,
pushSettings
} from '../actions/actions.js'
import { bindActionCreators } from 'redux'
import { Map } from 'immutable'
const mapDispatchToProps = dispatch => ({
actions: bindActionCreators(
{
showToggleAcceptingModal,
hideToggleAcceptingModal,
updateSettings,
pushSettings
},
dispatch
)
})
const mapStateToProps = state => ({
usersettings: Map({
maxduration: Map({
name: 'Max Duration (Weeks)',
value: state.settingsReducer.get('maxduration'),
min: 12
}),
collateral: Map({
name: 'Collateral per TB per Month (SC)',
value: state.settingsReducer.get('collateral')
}),
storageprice: Map({
name: 'Price per TB per Month (SC)',
value: state.settingsReducer.get('storageprice')
}),
downloadbandwidthprice: Map({
name: 'Bandwidth Price (SC/TB)',
value: state.settingsReducer.get('downloadbandwidthprice')
})
}),
conversionRate: state.settingsReducer.get('conversionRate'),
acceptingContracts: state.settingsReducer.get('acceptingContracts'),
settingsChanged: state.settingsReducer.get('settingsChanged'),
defaultsettings: state.settingsReducer.get('defaultsettings'),
shouldShowToggleAcceptingModal: state.modalReducer.get(
'shouldShowToggleAcceptingModal'
)
})
const SettingsList = connect(mapStateToProps, mapDispatchToProps)(
SettingsListView
)
export default SettingsList
|
(function($) {
$.fn.extend({
dustParticles: function(particlesNumber, opacity) {
return this.each(function() {
//Generate a 'canvas' with size of element selected from the DOM .
var width = $(this).width();
var height = $(this).height();
var canvas = document.createElement('canvas');
canvas.id = 'canvas';
document.body.appendChild(canvas);
//Generate the context of canvas
var ctx = canvas.getContext('2d');
canvas.width = width;
canvas.height = height;
var particles = [];
var particleLimit = particlesNumber;
//We create our funny particles !
for (var i = 0; i < particleLimit; i++) {
particles.push(new particle());
}
//Function generating the object particles , having size , radio, opacity, initial position and color.
function particle() {
this.speed = {
x: Math.random() * 3 - 0.5,
y: Math.random() * 3 - 0.5
};
this.radius = Math.random() * (10 - 1) + 1;
console.log(this.radius)
this.opacity = opacity / this.radius;
this.r = 255;
this.g = 255;
this.b = 255;
this.x = Math.random() * (canvas.width - 0) + 0;
this.y = Math.random() * (canvas.height - 0) + 0;
this.color = this.color = 'rgba(' + this.r + ', ' + this.g + ', ' + this.b + ', ' + this.opacity + ')';
}
function live() {
//We repainted the canvas to create the sensation of movement.
ctx.clearRect(0, 0, canvas.width, canvas.height);
particles.forEach(function(element, index) {
ctx.beginPath();
var gradient = ctx.createRadialGradient(element.x, element.y, 0, element.x, element.y, element.radius);
gradient.addColorStop(1, 'rgba(' + element.r + ', ' + element.g + ', ' + element.b + ', 0)');
gradient.addColorStop(0.5, 'rgba(' + element.r + ', ' + element.g + ', ' + element.b + ', ' + (element.opacity / 2) + ')');
gradient.addColorStop(0, 'rgba(' + element.r + ', ' + element.g + ', ' + element.b + ', ' + element.opacity + ')');
ctx.fillStyle = gradient;
ctx.arc(element.x, element.y, element.radius, 0, Math.PI * 2, true);
ctx.fill();
//New position of particles
element.x += element.speed.x;
element.y += element.speed.y;
//We avoid the particles are beyond our territory!
if (element.x < -50) element.x = canvas.width + 50;
if (element.y < -50) element.y = canvas.height + 50;
if (element.x > canvas.width + 50) element.x = -50;
if (element.y > canvas.height + 50) element.y = -50;
});
}
setInterval(live, 33);
});
}
});
})(jQuery)
|
import getBrowserDimensions from './utils/getBrowserDimensions.js';
import Logger from './Logger';
export default class Screen {
constructor(parent, width = 600, height = 600) {
this.parent = parent;
this.log = new Logger();
// const { browserWidth, browserHeight } = getBrowserDimensions(window, document);
this.height = height; // === 0 ? browserHeight : height;
this.width = width; // === 0 ? browserWidth : width;
this.screen = this.createCanvasElement(`screen-${0}`, height, width);
this.surface = this.screen.getContext('2d');
this.surface.scale(1, 1);
this.createCanvasElement = this.createCanvasElement.bind(this);
this.resize = this.resize.bind(this);
// window.addEventListener('resize', this.resize, false);
this.destroy = this.destroy.bind(this);
this.clear = this.clear.bind(this);
this.getSurface = this.getSurface.bind(this);
// make 0,0 center screen.
this.surface.translate(this.width / 2, this.height / 2);
}
destroy() {
window.removeEventListener('resize');
}
clear() {
this.surface.clearRect(- this.width / 2,
- this.height / 2,
this.width, this.height);
}
resize() {
const { browserWidth, browserHeight } = getBrowserDimensions(window, document);
this.height = Math.min(browserHeight, this.height);
this.width = Math.min(browserWidth, this.width);
this.screen.setAttribute('width', `${this.width}px`);
this.screen.setAttribute('height', `${this.height}px`);
}
getSurface() {
return this.surface;
}
createCanvasElement(id) {
const divElement = document.createElement('div');
divElement.setAttribute('style', `
margin: auto;
position: absolute;
top: 50%;
left: 50%;
transform: translate( -50%, -50%);
`);
const canvasElement = document.createElement('canvas');
canvasElement.id = id;
canvasElement.style.background = '#000000';
canvasElement.width = `${this.width}px`;
canvasElement.height = `${this.height}px`;
canvasElement.setAttribute('width', `${this.width}px`);
canvasElement.setAttribute('height', `${this.height}px`);
divElement.appendChild(canvasElement);
this.parent.appendChild(divElement);
return canvasElement;
}
}
|
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M4 9h16v2H4V9zm0 4h10v2H4v-2z"
}), 'ShortText');
exports.default = _default;
|
import createSvgIcon from './utils/createSvgIcon';
import { jsx as _jsx } from "react/jsx-runtime";
export default createSvgIcon( /*#__PURE__*/_jsx("path", {
d: "M20 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm0 4-8 5-8-5V6l8 5 8-5v2z"
}), 'Markunread');
|
nucleomediaApi.controller('moedaCtrl', ['$scope', 'nucleomediaRequest', function ($scope, nucleomediaRequest) {
var rootScope = $scope.$root;
rootScope.moedas = [];
rootScope.carregarMoeda = function (idMoeda) {
url = "http://localhost:8080/getMoeda?" + idMoeda + "&cachebuster=" + RandomNumber();
if (moedaConfig.isDeveloper) {
url = "content/moeda_" + idMoeda + "_offline.xml?cachebuster=" + RandomNumber();
}
nucleomediaRequest.get(url, carregarComplete);
};
rootScope.carregarMoeda(1);
rootScope.carregarMoeda(2);
function carregarComplete(result) {
NormalizaJson(result.moedas.moeda);
rootScope.moedas.push(ConverteTipos(result.moedas.moeda));
console.log(rootScope.moedas)
}
function ConverteTipos(moeda) {
moeda.dataAtualizacao = new Date(moeda.dataAtualizacao);
moeda.variacao = parseFloat(moeda.variacao.replace(",", ".")).toPrecision(2);
return moeda;
}
}]);
|
"use strict";
(function (cornerstoneWADOImageLoader) {
function decodeJPEGLossless(dataSet, frame) {
var pixelDataElement = dataSet.elements.x7fe00010;
var bitsAllocated = dataSet.uint16('x00280100');
var pixelRepresentation = dataSet.uint16('x00280103');
var frameData = dicomParser.readEncapsulatedPixelData(dataSet, pixelDataElement, frame);
var byteOutput = bitsAllocated <= 8 ? 1 : 2;
//console.time('jpeglossless');
var decoder = new jpeg.lossless.Decoder();
var decompressedData = decoder.decode(frameData.buffer, frameData.byteOffset, frameData.length, byteOutput);
//console.timeEnd('jpeglossless');
if (pixelRepresentation === 0) {
if (byteOutput === 2) {
return new Uint16Array(decompressedData.buffer);
} else {
// untested!
return new Uint8Array(decompressedData.buffer);
}
} else {
return new Int16Array(decompressedData.buffer);
}
}
// module exports
cornerstoneWADOImageLoader.decodeJPEGLossless = decodeJPEGLossless;
}(cornerstoneWADOImageLoader));
|
'use strict';
/**
* remove-hidden-paths module
* @module remove-hidden-paths
* @see module:index
*/
const lang = require('zero-lang');
const isHidden = require('./is-hidden');
module.exports = paths => lang.filter(paths, pathname => !isHidden(pathname));
|
var modal = (<Modal type="popup" title="爱过什么女爵的滋味">
<p>为你封了国境<br/>为你赦了罪<br/>为你撤了历史记载<br/>为你涂了装扮<br/>为你喝了醉<br/>为你建了城池围墙<br/>一颗热的心穿着冰冷外衣<br/>一张白的脸漆上多少褪色的情节<br/>在我的空虚身体里面<br/>爱上哪个肤浅的王位<br/>在你的空虚宝座里面<br/>爱过什麽女爵的滋味<br/>为你封了国境</p><p>为你赦了罪<br/>为你撤了历史记载<br/>一颗热的心<br/>穿着冰冷外衣<br/>一张白的脸<br/>漆上多少褪色的情节<br/>在我的空虚身体里面<br/>爱上哪个肤浅的王位<br/>在你的空虚宝座里面<br/>爱过什麽女爵的滋味<br/>在我的空虚身体里面<br/>爱上哪个肤浅的王位<br/>在你的空虚宝座里面<br/>爱过什麽女爵的滋味</p>
</Modal>);
var modalInstance = (
<ModalTrigger
modal={modal}>
<Button amStyle="primary">Popup 窗口</Button>
</ModalTrigger>
);
ReactDOM.render(modalInstance, mountNode);
|
import jQuery from 'jquery';
export const DelayedStart = (function($) {
return function() {
var waitDeferred = new $.Deferred();
var promises = [];
var performed = false;
return {
promise: function() {
return waitDeferred.promise();
},
wait: function(callback) {
var cancelled = false;
waitDeferred.then(function() {
if (!cancelled) {
callback();
}
});
return {
cancel: function() {
cancelled = true;
}
};
},
waitFor: function(callbackOrPromise) {
if (!performed) {
if (typeof callbackOrPromise === 'function') {
callbackOrPromise = new $.Deferred(function(deferred) {
callbackOrPromise(deferred.resolve);
}).promise();
}
promises.push(callbackOrPromise);
}
},
perform: function() {
if (!performed) {
performed = true;
$.when.apply(null, promises).then(waitDeferred.resolve);
}
}
};
};
}(jQuery));
export const delayedStart = new DelayedStart();
|
"use strict";
module.exports = require('./lib/modclean');
|
var common = require("./common")
, ibmdb = require("../")
, db = new ibmdb.Database()
, assert = require("assert");
db.query("select * from " + common.tableName).then(null, function (err) {
assert.deepEqual(err, { message: 'Connection not open.' });
assert.equal(db.connected, false);
});
db.open(common.connectionString).then(function(res) {
console.log("db = ", db);
assert.equal(db.connected, true);
db.query("select * from " + common.tableName).then(null, function (err) {
var errorFound = false;
if(err) console.log(err);
if (err.message) {
var errorFound = err.message.includes("SQL0204N");
}
assert.equal(errorFound, true);
assert.equal(db.connected, true);
db.close().then(function () {
assert.equal(db.connected, false);
db.query("select * from " + common.tableName).then(null, function (err) {
if(err) console.log(err);
assert.deepEqual(err, { message: 'Connection not open.' });
assert.equal(db.connected, false);
});
});
});
})
.catch(function(err){console.log(err);})
.done();
|
// Globals
var $window = $(window);
var $document = $(document);
var location = window.location;
var navigator = window.navigator;
var ArrayBuffer = window.ArrayBuffer;
var Uint8Array = window.Uint8Array;
var DataView = window.DataView;
var btoa = window.btoa;
// Constants
var NAMESPACE = 'cropper';
var DPI = 233;
var BORDER = 0.15748031480000002;
var MARGIN = 0.039370078700000005;
// Classes
var CLASS_MODAL = 'cropper-modal';
var CLASS_HIDE = 'cropper-hide';
var CLASS_HIDDEN = 'cropper-hidden';
var CLASS_INVISIBLE = 'cropper-invisible';
var CLASS_MOVE = 'cropper-move';
var CLASS_CROP = 'cropper-crop';
var CLASS_DISABLED = 'cropper-disabled';
var CLASS_BG = 'cropper-bg';
// Events
var EVENT_MOUSE_DOWN = 'mousedown touchstart pointerdown MSPointerDown';
var EVENT_MOUSE_MOVE = 'mousemove touchmove pointermove MSPointerMove';
var EVENT_MOUSE_UP = 'mouseup touchend touchcancel pointerup pointercancel MSPointerUp MSPointerCancel';
var EVENT_WHEEL = 'wheel mousewheel DOMMouseScroll';
var EVENT_DBLCLICK = 'dblclick';
var EVENT_LOAD = 'load.' + NAMESPACE;
var EVENT_ERROR = 'error.' + NAMESPACE;
var EVENT_RESIZE = 'resize.' + NAMESPACE; // Bind to window with namespace
var EVENT_BUILD = 'build.' + NAMESPACE;
var EVENT_BUILT = 'built.' + NAMESPACE;
var EVENT_CROP_START = 'cropstart.' + NAMESPACE;
var EVENT_CROP_MOVE = 'cropmove.' + NAMESPACE;
var EVENT_CROP_END = 'cropend.' + NAMESPACE;
var EVENT_CROP = 'crop.' + NAMESPACE;
var EVENT_ZOOM = 'zoom.' + NAMESPACE;
// RegExps
var REGEXP_ACTIONS = /^e|w|s|n|se|sw|ne|nw|all|crop|move|zoom$/;
var REGEXP_DATA_URL = /^data:/;
var REGEXP_DATA_URL_HEAD = /^data:([^;]+);base64,/;
var REGEXP_DATA_URL_JPEG = /^data:image\/jpeg.*;base64,/;
// Data keys
var DATA_PREVIEW = 'preview';
var DATA_ACTION = 'action';
// Actions
var ACTION_EAST = 'e';
var ACTION_WEST = 'w';
var ACTION_SOUTH = 's';
var ACTION_NORTH = 'n';
var ACTION_SOUTH_EAST = 'se';
var ACTION_SOUTH_WEST = 'sw';
var ACTION_NORTH_EAST = 'ne';
var ACTION_NORTH_WEST = 'nw';
var ACTION_ALL = 'all';
var ACTION_CROP = 'crop';
var ACTION_MOVE = 'move';
var ACTION_ZOOM = 'zoom';
var ACTION_NONE = 'none';
// Supports
var SUPPORT_CANVAS = $.isFunction($('<canvas>')[0].getContext);
var IS_SAFARI_OR_UIWEBVIEW = navigator && /(Macintosh|iPhone|iPod|iPad).*AppleWebKit/i.test(navigator.userAgent);
// Maths
var num = Number;
var min = Math.min;
var max = Math.max;
var abs = Math.abs;
var sin = Math.sin;
var cos = Math.cos;
var sqrt = Math.sqrt;
var round = Math.round;
var floor = Math.floor;
var pow = Math.pow;
// Utilities
var fromCharCode = String.fromCharCode;
|
module.exports = {
"git": require('./git'),
};
|
(function () {
'use strict';
PN.namespace('PN.AngularDashboard.List');
PN.AngularDashboard.List.PagedListControllerScope = PN.AngularDashboard.List.ListControllerScope.extend({
_$timeout: null,
pageSize: 30,
pageNumber: 1,
pageCount: 1,
maxPageLength: 11,
showPaginationUtilities: false,
performSearchTimeoutPromise: null,
init: function ($scope, factory, $filter, $timeout) {
this._$timeout = $timeout;
this._super($scope, factory, $filter);
$scope.$watch('pageNumber', function (newValue, oldValue) {
if (newValue !== oldValue) {
$scope.showLoading = true;
$scope._loadModels();
window.scrollTo(0, 0);
}
});
$scope.$watch('pageSize', function (newValue, oldValue) {
if (newValue !== oldValue) {
$scope.showLoading = true;
$scope._loadModels();
window.scrollTo(0, 0);
}
});
},
__sort: function (expression, reverse) {
this.sortExpression = expression;
this.sortReverse = reverse;
this.pageNumber = 1;
this.showLoading = true;
this._loadModels();
},
_loadModels: function () {
this.focusAddFormInput = false;
var that = this,
token = new Date().valueOf().toString();
this._factory.latestToken = token;
this._factory.query(this._createQueryData(), function (models, responseHeaders) {
var returnedToken = responseHeaders('token');
if (returnedToken !== that._factory.latestToken) {
return;
}
that.showLoading = false;
that.models = models;
that.totalCount = Number(responseHeaders('total-count'));
that.filteredCount = Number(responseHeaders('filtered-count'));
that.pageCount = Math.max(Math.ceil(that.filteredCount / that.pageSize), 1);
if (that.totalCount === 0) {
that.showAddForm = true;
that.focusAddFormInput = true;
}
});
},
_createQueryData: function () {
var token = new Date().valueOf().toString();
this._factory.latestToken = token;
return {
token: token,
search: this.search,
pageNumber: this.pageNumber,
pageSize: this.pageSize,
sort: this.sortExpression,
reverse: this.sortReverse,
};
},
_performSearch: function (search) {
if (this.performSearchTimeoutPromise !== null) {
this._$timeout.cancel(this.performSearchTimeoutPromise);
}
var that = this;
this.performSearchTimeoutPromise = this._$timeout(function () {
that.performSearchTimeoutPromise = null;
that.pageNumber = 1;
that.showLoading = true;
that._loadModels();
}, 500);
}
});
})();
|
'use strict';
const NODE_ENV = process.env.NODE_ENV || 'development';
const webpack = require('webpack');
var path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var CopyWebpackPlugin = require('copy-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
entry: {
index: './index'
// gallery: './gallery'
},
output: {
path: __dirname + '/dist',
filename: NODE_ENV == 'development' ? 'resources/js/[name].[hash].js': 'resources/js/[name].[hash].js'
},
//watch: NODE_ENV == 'development', // recompile with changes
watchOptions: {
aggregateTimeout: 100
},
devtool: NODE_ENV == 'development' ? "cheap-inline-module-source-map" : null, //+ Debugging
plugins: [
new ExtractTextPlugin('./resources/style/[name].[hash].css'),
new webpack.NoErrorsPlugin(),
//new webpack.optimize.CommonsChunkPlugin({ //the allocation of the total
// // The order of this array matters
// names: ['common'],
// minChunks: 2
//}),
new webpack.DefinePlugin({
NODE_ENV: JSON.stringify(NODE_ENV)
}),
new HtmlWebpackPlugin({
template: 'index.html',
inject: 'body',
hash: true,
filename: 'index.html',
chunks: ['index']
})
// new HtmlWebpackPlugin({
// template: 'gallery.html',
// inject: 'body',
// hash: true,
// filename: 'gallery.html',
// chunks: ['gallery']
// })
//new webpack.ProvidePlugin({
// $: 'jquery',
// jQuery: 'jquery',
// 'window.jQuery': 'jquery'
//})
],
resolve: {
modulesDirectories: [path.join(__dirname, 'bower_components'), path.join(__dirname, 'node_modules')],
extensions: ['', '.js']
},
//
//resolveLoaders: {
// modulesDirectories:['node_modules'],
// moduleTemplates: ['*-loader.js', '*'],
// extensions: ['', '.js']
//},
module: {
loaders: [{
test: /\.js$/,
exclude: /\/node_modules\/|\/bower_components\//,
loader: 'babel'
},{
test: /\.css$/,
//loader: 'style!css'
loader: ExtractTextPlugin.extract('css')
},{
test: /\.(png|jpg|svg|ttf|eof|eot|woff|woff2|gif)$/,
loader: 'file?name=/img/[name].[hash].[ext]'
},{
test: /\.json$/,
loader: 'json'
}]
},
devServer: {
host: 'localhost',
port: 7017
}
};
if(NODE_ENV == 'development'){
module.exports.plugins.push(
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false,
drop_console: true,
unsafe: true
},
output: {comments: false}
})
);
module.exports.plugins.push(
new CopyWebpackPlugin([
{ from: 'resources/**/*.png'},
{ from: 'resources/**/*.jpg'},
{ from: 'resources/**/*.JPG'}
])
);
}
|
/**
* Main JS file for Scriptor behaviours
*/
/*globals jQuery, document */
(function ($) {
"use strict";
$(document).ready(function(){
// Scroll to content
$('.cover .scroll-down').on('click', function(e) {
$('html, body').animate({'scrollTop': $('.cover').height()}, 1800);
e.preventDefault();
});
// Scroll to top
$('.site-footer .top-link').on('click', function(e) {
$('html, body').animate({'scrollTop': 0});
e.preventDefault();
});
// Header adjustments
adjustCover();
$(window).bind('resize orientationchange', function() {
adjustCover();
});
// Sidebar
$('.sidebar-toggle, .overlay').on('click', function(e){
$('body').toggleClass('sidebar-opened');
e.preventDefault();
});
// Post reading time
$('.post-template .post').readingTime();
// Show comments
if ( typeof disqus_shortname !== 'undefined' ) {
$('.comments-title').on('click', function() {
$.ajax({
type: "GET",
url: "//" + disqus_shortname + ".disqus.com/embed.js",
dataType: "script",
cache: true
});
$(this).off('click').addClass('comments-loaded');
});
}
// Display recent posts and tagcloud
if ( $('.recent-posts').length || $('.tagcloud').length ) {
parseRss();
}
});
function adjustCover() {
if ( $('.cover .scroll-down').is(':hidden') )
$('.post-header .cover-bg').css({ 'top' : 0 });
else
$('.post-header .cover-bg').css({ 'top' : $('.site-header').outerHeight() });
}
function getPosts(feeds) {
var posts = [],
items = [];
feeds.forEach(function(feed) {
items = $.merge(items, $(feed).find('item'));
});
for (var i = 0; i < items.length; i++) {
var item = $(items[i]);
posts.push({
title: item.find('title').text(),
url: item.find('link').text(),
date: item.find('pubDate').text(),
tags: $.map(item.find('category'), function(elem) {
return $(elem).text();
})
});
}
return posts;
}
function formatDate(postDate) {
var months = Array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'),
date = new Date(postDate),
dateString = months[date.getMonth()] + ' ' + date.getDate() + ', ' + date.getFullYear();
return dateString;
}
function displayTagCloud(posts) {
var tagList = [],
tagCloud = '';
posts.forEach(function(post) {
var tags = post.tags;
tags.forEach(function(tag) {
if ( $.inArray(tag, tagList) == -1 ) {
tagList.push(tag);
}
});
});
for ( var i=0; i<tagList.length; i++ ) {
var tag = tagList[i],
tagLink = tag.replace(/\s+/g, '-').toLowerCase();
tagCloud += ('<a href="/tag/' + tagLink + '" class="button dark">' + tag + '</a>');
}
$('.tagcloud').append(tagCloud);
}
}(jQuery));
|
import Comp from './index.vue'
import { mount } from 'vue-test-utils'
import { expect } from 'chai'
describe('Datetime', () => {
it('basic', () => {
const wrapper = mount(Comp)
expect(wrapper.name()).to.equal('datetime')
})
})
|
/**
* Copyright (C) 2015 tieba.baidu.com
* target.js
*
* changelog
* 2015-11-06[16:45:43]:revised
*
* @author yinyong02@baidu.com
* @version 0.1.0
* @since 0.1.0
*/
module.exports = 'module.yml';
|
/**
* Removes all key-value entries from the list cache.
*
* @private
* @name clear
* @memberOf ListCache
*/
function listCacheClear() {
this.__data__ = [];
}
module.exports = listCacheClear;
|
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2019 Photon Storm Ltd.
* @license {@link https://opensource.org/licenses/MIT|MIT License}
*/
/**
* Create an array of points for each corner of a Rectangle
* If an array is specified, each point object will be added to the end of the array, otherwise a new array will be created.
*
* @function Phaser.Geom.Rectangle.Decompose
* @since 3.0.0
*
* @param {Phaser.Geom.Rectangle} rect - The Rectangle object to be decomposed.
* @param {array} [out] - If provided, each point will be added to this array.
*
* @return {array} Will return the array you specified or a new array containing the points of the Rectangle.
*/
var Decompose = function (rect, out)
{
if (out === undefined) { out = []; }
out.push({ x: rect.x, y: rect.y });
out.push({ x: rect.right, y: rect.y });
out.push({ x: rect.right, y: rect.bottom });
out.push({ x: rect.x, y: rect.bottom });
return out;
};
module.exports = Decompose;
|
'use strict';
module.exports = (sequelize, DataTypes) => {
const revision = sequelize.define('revision', {
// Schema
id: {
type: DataTypes.UUID,
primaryKey: true,
defaultValue: DataTypes.UUIDV4
},
postId: {
type: DataTypes.UUID,
allowNull: false,
references: {
model: sequelize.models.post,
key: 'id'
}
},
userId: {
type: DataTypes.UUID,
allowNull: false,
references: {
model: sequelize.models.user,
key: 'id'
}
},
title: DataTypes.TEXT,
content: DataTypes.TEXT
}, {
// Class methods
classMethods: { },
// Instance methods
instanceMethods: { }
});
return revision;
};
|
(function($) {
jQuery.fn.intoViewport = function(options) {
options = $.extend({
// Configuration
// Add whatever options animate schould get by default
duration: 200,
easing: "swing"
}, options || {});
return this.each(function(){
// scroll to certain destination:
function scrollX(left) {
$("html,body").stop().animate({ scrollLeft: left}, options );
}
function scrollY(top) {
$("html,body").stop().animate({ scrollTop: top}, options );
}
var
margin = 200,
screen_y = $(document).scrollTop() || $(window).scrollTop(),
window_height = $(window).height(),
element_top = $(this).offset().top,
element_height = $(this).outerHeight(),
screen_x = $(document).scrollLeft() || $(window).scrollLeft(),
window_width = $(window).width(),
element_left = $(this).offset().left,
element_width = $(this).outerWidth();
// scroll up
if (screen_y > element_top) {
scrollY(element_top - margin);
}
// scroll down
else if (screen_y != element_top && element_top+element_height > screen_y+window_height) {
scrollY(element_top + margin + Math.min(element_height - window_height, 0));
}
// scroll left
if (screen_x > element_left) {
scrollX(element_left - margin);
}
// scroll right
else if (screen_x != element_left && element_left+element_width > screen_x+window_width) {
scrollX(element_left + margin + Math.min(element_width-window_width, 0));
}
});
};
})(jQuery); //compatibility
|
// Karma configuration
// Generated on Fri Feb 26 2016 16:59:16 GMT+0900 (JST)
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['mocha'],
// list of files / patterns to load in the browser
files: [
'dist/ajv-i18n.test.min.js',
'.browser/*.spec.js'
],
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['dots'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: false,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['Chrome'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: true,
browserNoActivityTimeout: 90000
})
}
|
{
if ("development" !== "production" && dir.modifiers) {
warn("v-on without argument does not support modifiers.");
}
el.wrapListeners = function(code) {
return "_g(" + code + "," + dir.value + ")";
};
}
|
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule RelayIRTransforms
* @flow
* @format
*/
'use strict';
const RelayApplyFragmentArgumentTransform = require('../transforms/RelayApplyFragmentArgumentTransform');
const RelayConnectionTransform = require('../handlers/connection//RelayConnectionTransform');
const RelayDeferrableFragmentTransform = require('../transforms/RelayDeferrableFragmentTransform');
const RelayFieldHandleTransform = require('../transforms/RelayFieldHandleTransform');
const RelayGenerateIDFieldTransform = require('../transforms/RelayGenerateIDFieldTransform');
const RelayGenerateTypeNameTransform = require('../transforms/RelayGenerateTypeNameTransform');
const RelayMaskTransform = require('../transforms/RelayMaskTransform');
const RelayRelayDirectiveTransform = require('../transforms/RelayRelayDirectiveTransform');
const RelaySkipHandleFieldTransform = require('../transforms/RelaySkipHandleFieldTransform');
const RelayViewerHandleTransform = require('../handlers/viewer/RelayViewerHandleTransform');
const {
FilterDirectivesTransform,
FlattenTransform,
InlineFragmentsTransform,
SkipClientFieldTransform,
SkipRedundantNodesTransform,
SkipUnreachableNodeTransform,
} = require('graphql-compiler');
import type {IRTransform} from 'graphql-compiler';
// Transforms applied to the code used to process a query response.
const relaySchemaExtensions: Array<string> = [
RelayConnectionTransform.SCHEMA_EXTENSION,
RelayRelayDirectiveTransform.SCHEMA_EXTENSION,
];
// Transforms applied to both operations and fragments for both reading and
// writing from the store.
const relayCommonTransforms: Array<IRTransform> = [
RelayConnectionTransform.transform,
RelayViewerHandleTransform.transform,
RelayRelayDirectiveTransform.transform,
RelayMaskTransform.transform,
RelayDeferrableFragmentTransform.transformOperations,
];
// Transforms applied to fragments used for reading data from a store
const relayFragmentTransforms: Array<IRTransform> = [
RelayFieldHandleTransform.transform,
FlattenTransform.transformWithOptions({flattenAbstractTypes: true}),
SkipRedundantNodesTransform.transform,
];
// Transforms applied to queries/mutations/subscriptions that are used for
// fetching data from the server and parsing those responses.
const relayQueryTransforms: Array<IRTransform> = [
RelayDeferrableFragmentTransform.transformSpreads,
RelayApplyFragmentArgumentTransform.transform,
SkipClientFieldTransform.transform,
SkipUnreachableNodeTransform.transform,
RelayGenerateIDFieldTransform.transform,
];
// Transforms applied to the code used to process a query response.
const relayCodegenTransforms: Array<IRTransform> = [
InlineFragmentsTransform.transform,
FlattenTransform.transformWithOptions({flattenAbstractTypes: true}),
SkipRedundantNodesTransform.transform,
RelayGenerateTypeNameTransform.transform,
FilterDirectivesTransform.transform,
];
// Transforms applied before printing the query sent to the server.
const relayPrintTransforms: Array<IRTransform> = [
FlattenTransform.transformWithOptions({}),
RelayGenerateTypeNameTransform.transform,
RelaySkipHandleFieldTransform.transform,
FilterDirectivesTransform.transform,
];
module.exports = {
commonTransforms: relayCommonTransforms,
codegenTransforms: relayCodegenTransforms,
fragmentTransforms: relayFragmentTransforms,
printTransforms: relayPrintTransforms,
queryTransforms: relayQueryTransforms,
schemaExtensions: relaySchemaExtensions,
};
|
var gulp = require('gulp');
var config = require('../config');
gulp.task('watch', function() {
// watch for changes to html
gulp.watch([
config.baseDir() + '/**/*.html'
], ['html']);
// watch for changes to sass
gulp.watch([
'common/assets/css/*',
config.baseDir() + '/css/*'
], ['sass']);
});
|
TeamPoker.CurrentVoterName = '';
TeamPoker.CurrentVoterId = 0;
TeamPoker.CurrentVotingStory = 0;
TeamPoker.MessageType = {
LoginCallback: 'LoginCallback',
NewParticipant: 'NewParticipant',
LeaveParticipant: 'LeaveParticipant',
SetCurrentStory: "SetCurrentStory",
UpdateStoryInfo: "UpdateStoryInfo",
ViewVoteResult: 'ViewVoteResult',
Revote: 'Revote',
SavePoint: "SavePoint",
GameStatus: 'GameStatus'
};
TeamPoker.login = function (loginName) {
TeamPoker.SocketClient.sendMsg("login_event", loginName);
};
TeamPoker.loginCallback = function(data) {
if(data.Success === 'true') {
TeamPoker.CurrentVoterId = data.ParticipantInfo.Id;
TeamPoker.CurrentVoterName = data.ParticipantInfo.Name;
TeamPoker.UIManager.loadRoomInfo(data.RoomInfo);
sessionStorage.setObject("RoomInfo", data.RoomInfo);
}
else
alert("Login failed! Please try again:)");
};
TeamPoker.logout = function () {
$.removeCookie("LoginName");
TeamPoker.SocketClient.sendMsg("logout_event", TeamPoker.CurrentVoterId);
};
TeamPoker.logoutCallback = function (data) {
TeamPoker.UIManager.removeFromParticipantsList(data.Id);
};
TeamPoker.newParticipantCallback = function(data) {
TeamPoker.UIManager.refreshParticipantsList(data.ParticipantCollection);
};
TeamPoker.leaveParticipantCallback = function(data) {
TeamPoker.UIManager.refreshParticipantsList(data.ParticipantCollection);
};
TeamPoker.setCurrentStory = function(storyId) {
TeamPoker.CurrentVotingStory = storyId;
TeamPoker.SocketClient.sendMsg("set_current_story_event", storyId);
};
TeamPoker.setCurrentStoryCallback = function(data) {
TeamPoker.UIManager.setStoryPointer(data.StoryId);
}
TeamPoker.updateStoryInfo = function(storyId, val) {
TeamPoker.SocketClient.sendMsg("update_story_event", { Id: storyId, Val: val });
};
TeamPoker.updateStoryInfoCallback = function(data) {
TeamPoker.UIManager.updateStoryInfo(data.StoryInfo);
};
TeamPoker.vote = function (value) {
TeamPoker.SocketClient.sendMsg("vote_event", { StoryId: TeamPoker.CurrentVotingStory, VoterName: TeamPoker.CurrentVoterName, VoteVal: value });
};
TeamPoker.viewVoteResult = function (data) {
TeamPoker.SocketClient.sendMsg("view_vote_result_event", TeamPoker.CurrentVotingStory);
};
TeamPoker.viewVoteResultCallback = function (data) {
// Marking special/high/low scores
_(data.VoteStatus).each(function (voteInfo) {
if(voteInfo.VoteVal === "?" || voteInfo.VoteVal === "0")
voteInfo.SpecialScore = true;
else
voteInfo.VoteVal = parseFloat(voteInfo.VoteVal);
});
var allVotes = _.chain(data.VoteStatus).pluck("VoteVal").without("?", "0").sort(function (a,b) {return a-b}).uniq();
if(allVotes.value().length > 2) {
_(data.VoteStatus).each(function (voteInfo) {
if(voteInfo.VoteVal === allVotes.first().value())
voteInfo.LowScore = true;
if(voteInfo.VoteVal === allVotes.last().value())
voteInfo.HighScore = true;
});
}
TeamPoker.UIManager.displayVoteResult(data.VoteStatus);
};
TeamPoker.reVote = function() {
TeamPoker.SocketClient.sendMsg("revote_event", TeamPoker.CurrentVotingStory);
};
TeamPoker.reVoteCallback = function(data) {
TeamPoker.UIManager.revoteForStory(data.Id);
};
TeamPoker.savePoint = function(point) {
TeamPoker.SocketClient.sendMsg("save_point_event", { Id: TeamPoker.CurrentVotingStory, Point: point });
};
TeamPoker.savePointCallback = function(data) {
TeamPoker.UIManager.savePointForStory(data.Id, data.Point);
};
TeamPoker.SocketClient.addListener(TeamPoker.MessageType.LoginCallback, TeamPoker.loginCallback);
TeamPoker.SocketClient.addListener(TeamPoker.MessageType.GameStatus, TeamPoker.onLoadGameStatus);
TeamPoker.SocketClient.addListener(TeamPoker.MessageType.NewParticipant, TeamPoker.newParticipantCallback);
TeamPoker.SocketClient.addListener(TeamPoker.MessageType.LeaveParticipant, TeamPoker.logoutCallback);
TeamPoker.SocketClient.addListener(TeamPoker.MessageType.SetCurrentStory, TeamPoker.setCurrentStoryCallback);
TeamPoker.SocketClient.addListener(TeamPoker.MessageType.UpdateStoryInfo, TeamPoker.updateStoryInfoCallback);
TeamPoker.SocketClient.addListener(TeamPoker.MessageType.ViewVoteResult, TeamPoker.viewVoteResultCallback);
TeamPoker.SocketClient.addListener(TeamPoker.MessageType.Revote, TeamPoker.reVoteCallback);
TeamPoker.SocketClient.addListener(TeamPoker.MessageType.SavePoint, TeamPoker.savePointCallback);
|
describe('Logger', ()=> {
let loggerInstance, toaster, toasterMock;
beforeEach(()=> {
angular.mock.module(function ($provide) {
$provide.service('toaster', function () {
this.pop = jasmine.createSpy('pop');
});
});
angular.mock.module('espackApp');
});
describe('#ctor', ()=> {
beforeEach(()=> {
_inject();
});
it('should exist', ()=> {
expect(!!loggerInstance).toBe(true);
});
});
describe('#info', ()=> {
beforeEach(()=> {
_inject();
});
it('should be defined', ()=> {
expect(loggerInstance.info).toBeDefined();
});
it('should be defined', ()=> {
let expectedMessage = 'TEST';
spyOn(toasterMock, 'pop').and.callThrough();
loggerInstance.info(expectedMessage);
expect(toasterMock.pop).toHaveBeenCalledWith({type: 'info', body: expectedMessage});
});
});
function _inject() {
inject((logger, toaster) => {
loggerInstance = logger;
toasterMock = toaster;
});
}
});
|
'use strict';
jest.mock('@strapi/strapi/lib/utils/ee', () => {
const eeModule = () => false;
Object.assign(eeModule, {
features: {
isEnabled() {
return false;
},
getEnabled() {
return [];
},
},
});
return eeModule;
});
const adminController = require('../admin');
describe('Admin Controller', () => {
describe('init', () => {
beforeAll(() => {
global.strapi = {
config: {
get: jest.fn(() => 'foo'),
},
admin: {
services: {
user: {
exists: jest.fn(() => true),
},
},
},
};
});
test('Returns the uuid and if the app has admins', async () => {
const result = await adminController.init();
expect(global.strapi.config.get).toHaveBeenCalledWith('uuid', false);
expect(global.strapi.admin.services.user.exists).toHaveBeenCalled();
expect(result.data).toBeDefined();
expect(result.data).toStrictEqual({
uuid: 'foo',
hasAdmin: true,
});
});
});
describe('information', () => {
beforeAll(() => {
global.strapi = {
config: {
get: jest.fn(
(key, value) =>
({
autoReload: undefined,
'info.strapi': '1.0.0',
environment: 'development',
}[key] || value)
),
},
EE: true,
};
});
test('Returns application information', async () => {
const result = await adminController.information();
expect(global.strapi.config.get.mock.calls).toEqual([
['environment'],
['autoReload', false],
['info.strapi', null],
]);
expect(result.data).toBeDefined();
expect(result.data).toStrictEqual({
currentEnvironment: 'development',
autoReload: false,
strapiVersion: '1.0.0',
nodeVersion: process.version,
communityEdition: false,
});
});
});
});
|
export { default } from 'ember-pikaday/components/pikaday-input';
|
import React from 'react';
import { shallow } from 'enzyme';
import assert from 'assert';
import WeUI from '../src/index';
const {Label} = WeUI;
describe('<Label></Label>', ()=> {
[undefined, null, 'custom_class'].map(clazz => {
describe(`<Label className=${clazz}></Label>`, ()=> {
const wrapper = shallow(
<Label className={clazz}/>
);
it(`should render Label label component with weui_label class`, ()=> {
assert(wrapper.find('label').hasClass('weui-label'));
});
it(`should have custom class name ${clazz} when className is not null or empty`, ()=>{
if (clazz) {
assert(wrapper.find('label').hasClass(clazz));
}
});
});
});
});
|
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path d="M12 6v3l4-4-4-4v3c-4.42 0-8 3.58-8 8 0 1.57.46 3.03 1.24 4.26L6.7 14.8c-.45-.83-.7-1.79-.7-2.8 0-3.31 2.69-6 6-6zm6.76 1.74L17.3 9.2c.44.84.7 1.79.7 2.8 0 3.31-2.69 6-6 6v-3l-4 4 4 4v-3c4.42 0 8-3.58 8-8 0-1.57-.46-3.03-1.24-4.26z" /><path fill="none" d="M0 0h24v24H0z" /></React.Fragment>
, 'Autorenew');
|
/* eslint-disable flowtype/require-valid-file-annotation */
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Button from 'material-ui/Button';
import Dialog, {
DialogTitle,
DialogContent,
DialogContentText,
DialogActions,
} from 'material-ui/Dialog';
import Typography from 'material-ui/Typography';
import withStyles from 'material-ui/styles/withStyles';
import withRoot from '../components/withRoot';
const styles = {
root: {
textAlign: 'center',
paddingTop: 200,
},
};
class Index extends Component {
state = {
open: false,
};
handleRequestClose = () => {
this.setState({
open: false,
});
};
handleClick = () => {
this.setState({
open: true,
});
};
render() {
return (
<div className={this.props.classes.root}>
<Dialog open={this.state.open} onRequestClose={this.handleRequestClose}>
<DialogTitle>Super Secret Password</DialogTitle>
<DialogContent>
<DialogContentText>1-2-3-4-5</DialogContentText>
</DialogContent>
<DialogActions>
<Button color="primary" onClick={this.handleRequestClose}>
OK
</Button>
</DialogActions>
</Dialog>
<Typography type="display1" gutterBottom>
Material-UI
</Typography>
<Typography type="subheading" gutterBottom>
example project
</Typography>
<Button raised color="accent" onClick={this.handleClick}>
Super Secret Password
</Button>
</div>
);
}
}
Index.propTypes = {
classes: PropTypes.object.isRequired,
};
export default withRoot(withStyles(styles)(Index));
|
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2019 Photon Storm Ltd.
* @license {@link https://opensource.org/licenses/MIT|MIT License}
*/
var GetValue = require('../object/GetValue');
var Shuffle = require('./Shuffle');
var BuildChunk = function (a, b, qty)
{
var out = [];
for (var aIndex = 0; aIndex < a.length; aIndex++)
{
for (var bIndex = 0; bIndex < b.length; bIndex++)
{
for (var i = 0; i < qty; i++)
{
out.push({ a: a[aIndex], b: b[bIndex] });
}
}
}
return out;
};
/**
* Creates an array populated with a range of values, based on the given arguments and configuration object.
*
* Range ([a,b,c], [1,2,3]) =
* a1, a2, a3, b1, b2, b3, c1, c2, c3
*
* Range ([a,b], [1,2,3], qty = 3) =
* a1, a1, a1, a2, a2, a2, a3, a3, a3, b1, b1, b1, b2, b2, b2, b3, b3, b3
*
* Range ([a,b,c], [1,2,3], repeat x1) =
* a1, a2, a3, b1, b2, b3, c1, c2, c3, a1, a2, a3, b1, b2, b3, c1, c2, c3
*
* Range ([a,b], [1,2], repeat -1 = endless, max = 14) =
* Maybe if max is set then repeat goes to -1 automatically?
* a1, a2, b1, b2, a1, a2, b1, b2, a1, a2, b1, b2, a1, a2 (capped at 14 elements)
*
* Range ([a], [1,2,3,4,5], random = true) =
* a4, a1, a5, a2, a3
*
* Range ([a, b], [1,2,3], random = true) =
* b3, a2, a1, b1, a3, b2
*
* Range ([a, b, c], [1,2,3], randomB = true) =
* a3, a1, a2, b2, b3, b1, c1, c3, c2
*
* Range ([a], [1,2,3,4,5], yoyo = true) =
* a1, a2, a3, a4, a5, a5, a4, a3, a2, a1
*
* Range ([a, b], [1,2,3], yoyo = true) =
* a1, a2, a3, b1, b2, b3, b3, b2, b1, a3, a2, a1
*
* @function Phaser.Utils.Array.Range
* @since 3.0.0
*
* @param {array} a - The first array of range elements.
* @param {array} b - The second array of range elements.
* @param {object} [options] - A range configuration object. Can contain: repeat, random, randomB, yoyo, max, qty.
*
* @return {array} An array of arranged elements.
*/
var Range = function (a, b, options)
{
var max = GetValue(options, 'max', 0);
var qty = GetValue(options, 'qty', 1);
var random = GetValue(options, 'random', false);
var randomB = GetValue(options, 'randomB', false);
var repeat = GetValue(options, 'repeat', 0);
var yoyo = GetValue(options, 'yoyo', false);
var out = [];
if (randomB)
{
Shuffle(b);
}
// Endless repeat, so limit by max
if (repeat === -1)
{
if (max === 0)
{
repeat = 0;
}
else
{
// Work out how many repeats we need
var total = (a.length * b.length) * qty;
if (yoyo)
{
total *= 2;
}
repeat = Math.ceil(max / total);
}
}
for (var i = 0; i <= repeat; i++)
{
var chunk = BuildChunk(a, b, qty);
if (random)
{
Shuffle(chunk);
}
out = out.concat(chunk);
if (yoyo)
{
chunk.reverse();
out = out.concat(chunk);
}
}
if (max)
{
out.splice(max);
}
return out;
};
module.exports = Range;
|
"use strict";
// START A WEB SERVER INSTANCE FOR EACH CPU CORE. START WITH COMMAND: forever startWebServers.js
var cluster = require('cluster');
var os = require('os');
var redisService = require('./server/service/redisService');
var log = require('./server/service/logFunction.js');
var service = 'WEB SERVERS STARTUP SCRIPT';
// Spawn web servers for each core to ports starting at 3010
var webServerPort = 3010;
var startNewWorker = function() {
var workerEnv = {
WEB_SERVER_PORT: webServerPort
};
var worker = cluster.fork(workerEnv);
if (++webServerPort === 3020) webServerPort = 3010;
return worker;
}
if (cluster.isMaster) {
console.log("\n*** STARTING WEB SERVERS ***");
log(service, 'info', '*** STARTING WEB SERVERS ***');
log(service, 'info', 'Blog App web servers master cluster pid ' + process.pid);
var cpus = os.cpus().length;
for (var i = 0; i < cpus; i++) {
startNewWorker();
}
// Replace crashed worker
cluster.on('exit', function(worker, code) {
if (code != 0 && !worker.suicide) {
log(service, 'error', 'Web server worker crashed! Starting a new worker');
startNewWorker();
}
});
log(service, 'info' + '*** STARTING ' + cpus + ' WEB SERVER CLONES ***');
// Zero downtime reload:
// Using the SIGUSR2 signal to listen for reload requests
// you could, instead, use file watcher logic, or anything else
process.on("SIGUSR2", function() {
var workers = Object.keys(cluster.workers);
log(service, 'info', '*** SIGUSR2 received, reloading ' + (workers.length) + ' Web server workers ***');
// delete the cached module, so we can reload the app
delete require.cache[require.resolve("./server/httpServer")];
// only reload one worker at a time
// otherwise, we'll have a time when no request handlers are running
var i = 0;
var f = function() {
if (i == workers.length) return;
log(service, 'info', 'Killing HTML server worker ' + (i + 1));
cluster.workers[workers[i]].disconnect();
cluster.workers[workers[i]].on("disconnect", function() {
cluster.workers[workers[i]].kill();
log(service, 'info', 'Worker shutdown complete');
});
var newWorker = startNewWorker();
newWorker.on("listening", function() {
log(service, 'info', 'Replacement worker online.');
i++;
f();
});
}
f();
});
console.log("\nWEB SERVERS STARTED!");
log(service, 'info', 'WEB SERVERS STARTED!');
}
// Else start web server instance on defined port
else {
require('./server/httpServer').startServer();
}
|
/*
* Copyright 2016-2017 Hewlett Packard Enterprise Development Company, L.P.
* Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
*/
define([
'backbone',
'find/app/util/merge-collection'
], function(Backbone, MergeCollection) {
'use strict';
const Animal = {CAT: 'CAT', DOG: 'DOG'};
describe('Merge collection', function() {
beforeEach(function() {
this.catCollection = new Backbone.Collection([
{id: 0, name: 'Oscar', animal: Animal.CAT},
{id: 1, name: 'Katy', animal: Animal.CAT}
]);
this.dogCollection = new Backbone.Collection([
{id: 0, name: 'Rover', animal: Animal.DOG}
]);
this.mergeCollection = new MergeCollection([], {
collections: [this.catCollection, this.dogCollection],
comparator: 'name',
typeAttribute: 'animal'
});
});
it('adds all existing models on construction', function() {
expect(this.mergeCollection.length).toBe(3);
expect(this.mergeCollection.at(0)).toBe(this.catCollection.at(1));
expect(this.mergeCollection.at(1)).toBe(this.catCollection.at(0));
expect(this.mergeCollection.at(2)).toBe(this.dogCollection.at(0));
});
it('adds models added to the tracked collection from itself', function() {
const model = this.dogCollection.add({id: 1, name: 'Barky', animal: Animal.DOG});
expect(this.mergeCollection.length).toBe(4);
expect(this.mergeCollection.findWhere({name: 'Barky'})).toBe(model);
});
it('removes models removed from the tracked collections from itself', function() {
this.catCollection.remove(0);
expect(this.mergeCollection.length).toBe(2);
expect(this.mergeCollection.findWhere({name: 'Oscar'})).toBeUndefined();
});
it('resets itself when one of the tracked collections is reset', function() {
this.catCollection.reset([
{id: 3, name: 'Tom', animal: Animal.CAT}
]);
expect(this.mergeCollection.length).toBe(2);
expect(this.mergeCollection.at(0)).toBe(this.dogCollection.at(0));
expect(this.mergeCollection.at(1)).toBe(this.catCollection.at(0));
});
it('preserves the collection reference on the models', function() {
expect(this.mergeCollection.findWhere({animal: Animal.CAT}).collection).toBe(this.catCollection);
});
it('handles adding two new models to the tracked collection', function() {
// New models have no id
this.catCollection.add({name: 'Willow', animal: Animal.CAT});
this.catCollection.add({name: 'George', animal: Animal.CAT});
expect(this.mergeCollection.length).toBe(5);
});
});
});
|
import React from 'react'
export default () => (
<div>
<h1>Features</h1>
</div>
)
|
var searchData=
[
['handler',['Handler',['../classHandler.html',1,'']]],
['host',['Host',['../classHost.html',1,'']]]
];
|
'use strict';
angular.module('rastros')
.directive('loader', function (loader) {
return {
restrict : 'E',
templateUrl: 'app/templates/directives/loader-directive-template.html',
scope : {},
link : function (scope) {
scope.activities = loader.activities;
scope.errors = loader.errors;
scope.clearError = function (error) {
loader.clearError(error);
};
},
};
});
|
import _ from 'lodash';
import 'ui/paginated_table';
import popularityHtml from 'plugins/kibana/management/sections/indices/_field_popularity.html';
import controlsHtml from 'plugins/kibana/management/sections/indices/_field_controls.html';
import dateScripts from 'plugins/kibana/management/sections/indices/_date_scripts';
import uiModules from 'ui/modules';
import scriptedFieldsTemplate from 'plugins/kibana/management/sections/indices/_scripted_fields.html';
import { getSupportedScriptingLangs } from 'ui/scripting_langs';
import { scriptedFields as docLinks } from 'ui/documentation_links/documentation_links';
uiModules.get('apps/management')
.directive('scriptedFields', function (kbnUrl, Notifier, $filter) {
const rowScopes = []; // track row scopes, so they can be destroyed as needed
const filter = $filter('filter');
const notify = new Notifier();
return {
restrict: 'E',
template: scriptedFieldsTemplate,
scope: true,
link: function ($scope) {
const fieldCreatorPath = '/management/kibana/indices/{{ indexPattern }}/scriptedField';
const fieldEditorPath = fieldCreatorPath + '/{{ fieldName }}';
$scope.docLinks = docLinks;
$scope.perPage = 25;
$scope.columns = [
{ title: 'name' },
{ title: 'lang' },
{ title: 'script' },
{ title: 'format' },
{ title: 'controls', sortable: false }
];
$scope.$watchMulti(['[]indexPattern.fields', 'fieldFilter'], refreshRows);
function refreshRows() {
_.invoke(rowScopes, '$destroy');
rowScopes.length = 0;
const fields = filter($scope.indexPattern.getScriptedFields(), $scope.fieldFilter);
_.find($scope.editSections, {index: 'scriptedFields'}).count = fields.length; // Update the tab count
$scope.rows = fields.map(function (field) {
const rowScope = $scope.$new();
rowScope.field = field;
rowScopes.push(rowScope);
return [
_.escape(field.name),
_.escape(field.lang),
_.escape(field.script),
_.get($scope.indexPattern, ['fieldFormatMap', field.name, 'type', 'title']),
{
markup: controlsHtml,
scope: rowScope
}
];
});
}
$scope.addDateScripts = function () {
const conflictFields = [];
let fieldsAdded = 0;
_.each(dateScripts($scope.indexPattern), function (script, field) {
try {
$scope.indexPattern.addScriptedField(field, script, 'number');
fieldsAdded++;
} catch (e) {
conflictFields.push(field);
}
});
if (fieldsAdded > 0) {
notify.info(fieldsAdded + ' script fields created');
}
if (conflictFields.length > 0) {
notify.info('Not adding ' + conflictFields.length + ' duplicate fields: ' + conflictFields.join(', '));
}
};
$scope.create = function () {
const params = {
indexPattern: $scope.indexPattern.id
};
kbnUrl.change(fieldCreatorPath, params);
};
$scope.edit = function (field) {
const params = {
indexPattern: $scope.indexPattern.id,
fieldName: field.name
};
kbnUrl.change(fieldEditorPath, params);
};
$scope.remove = function (field) {
$scope.indexPattern.removeScriptedField(field.name);
};
$scope.getDeprecatedLanguagesInUse = function () {
const fields = $scope.indexPattern.getScriptedFields();
const langsInUse = _.uniq(_.map(fields, 'lang'));
return _.difference(langsInUse, getSupportedScriptingLangs());
};
}
};
});
|
'use strict';
module.exports = require('tough-cookie');
|
/**
* Autocomplete User @ Mentions in Chat
*/
/* global Dubtrack */
var settings = require("../lib/settings.js");
var modal = require('../utils/modal.js');
var options = require('../utils/options.js');
var myModule = {};
myModule.id = "custom_mentions";
myModule.moduleName = "Custom Mentions";
myModule.description = "Toggle using custom mentions to trigger sounds in chat";
myModule.category = "General";
myModule.extraIcon = 'pencil';
var saveCustomMentions = function() {
var mentionsVal = $('.dp-modal textarea').val();
if (mentionsVal !== '') {
options.saveOption('custom', 'custom_mentions', mentionsVal);
}
};
myModule.customMentionCheck = function(e) {
var content = e.message;
if (settings.custom.custom_mentions) {
var customMentions = settings.custom.custom_mentions.split(',');
var inUsers = customMentions.some(function(v) {
var reg = new RegExp('\\b' + v.trim() + '\\b', 'i');
return reg.test(content);
});
if(QueUp.session.id !== e.user.userInfo.userid && inUsers){
QueUp.room.chat.mentionChatSound.play();
}
}
};
myModule.turnOn = function() {
QueUp.Events.bind("realtime:chat-message", this.customMentionCheck);
};
myModule.extra = function() {
modal.create({
title: 'Custom Mentions',
content: 'Add your custom mention triggers here (separate by comma)',
value : settings.custom.custom_mentions || '',
placeholder: 'separate, custom triggers, by, comma, :heart:',
maxlength: '255',
confirmCallback: saveCustomMentions
});
};
myModule.turnOff = function() {
QueUp.Events.unbind("realtime:chat-message", this.customMentionCheck);
};
module.exports = myModule;
|
module.exports = [
'socketFactory',
function (socketFactory) {
var socket = socketFactory({
url: '/socket'
});
socket._handlers = {};
socket.addHandler = function (name, handler) {
socket._handlers[name] = handler;
};
socket.doDeploy = function (project, environment) {
socket.send(angular.toJson({
event: 'deploy',
request: {
project: project.Name,
environment: environment.Name
}
}))
};
socket.getContainers = function (project) {
socket.send(angular.toJson({
event: 'containers',
request: {project: project.Name}
}))
};
socket.getStatus = function (project) {
socket.send(angular.toJson({
event: 'status',
request: {}
}))
};
socket.setHandler('message', function (e) {
data = angular.fromJson(e.data);
socket._handlers[data.event](data.result);
});
return socket;
}
];
|
'use strict';
var Grid = require('nd-grid');
var datetime = require('nd-datetime');
var RbacRoleModel = require('../../../mod/model/rbac/role');
module.exports = function(util) {
if (!util.auth.hasAuth('=8')) {
return util.redirect('error/403');
}
var instance = new Grid({
parentNode: '#main',
proxy: new RbacRoleModel(),
mode: util.RBAC_ENABLED ? 2 : 0,
autoload: util.RBAC_ENABLED,
uniqueId: 'role_id',
entryKey: null,
labelMap: {
'role_id': 'ID',
'role_name': '名称',
'remarks': '备注',
'is_default': '默认角色',
// 0-NONE,1-READ,2-ADD,3-WRITE,4-DELETE
'auth_extra': '权限扩展',
'updated_at': '更新时间'
},
adapters: function(key, value) {
switch (key) {
case 'is_default':
return value ? '是' : '否';
case 'auth_extra':
return ['NONE', 'READ', 'ADD', 'WRITE', 'DELETE'][value];
case 'updated_at':
return datetime(value).format();
default:
return value;
}
},
plugins: [{
name: 'roleUser',
starter: require('./user/starter')
}, {
name: 'roleAuth',
starter: require('./auth/starter')
}],
pluginCfg: {
addItem: {
disabled: false,
listeners: {
start: require('./add/start')
}
},
editItem: {
disabled: false,
listeners: {
start: require('./edit/start')
}
},
delItem: {
disabled: false
},
search: {
disabled: util.RBAC_ENABLED,
listeners: {
start: require('./search/start')
}
}
}
}).render();
if (!util.RBAC_ENABLED) {
// 新增
// RISK: 如果多次调用,会多次绑定
instance.get('proxy').on('POST', function(options) {
options.data.realm = instance.get('params').realm;
});
}
// 面包屑导航
util.bread.set(
[{
title: '权限管理'
}, {
title: '角色列表'
}]
);
// 返回垃圾回收
// 否则内存泄漏
return function() {
instance.destroy();
};
};
|
'use strict';
var _ = require('lodash');
var Inherits = require('util').inherits;
var URI = require('urijs');
var sway = require('sway');
var Promise = require('bluebird');
var swagger2openapi = require('swagger2openapi');
var BaseFormat = require('../base_format.js');
var Util = require('../util.js');
var Swagger2 = module.exports = function() {
Swagger2.super_.apply(this, arguments);
this.format = 'swagger_2';
this.converters.openapi_3 = Promise.method(swagger => swagger2openapi.convert(swagger.spec,{direct:true,patch:true}));
}
Inherits(Swagger2, BaseFormat);
Swagger2.prototype.formatName = 'swagger';
Swagger2.prototype.supportedVersions = ['2.0'];
Swagger2.prototype.getFormatVersion = function () {
return this.spec.swagger;
}
Swagger2.prototype.fixSpec = function () {
var swagger = this.spec;
//Typical mistake is to make version number insted of string
var version = _.get(swagger, 'info.version');
if (_.isNumber(version))
swagger.info.version = version % 1 ? version.toString() : version.toFixed(1);
if (this.sourceType == 'url') {
var url = URI(this.source);
swagger.host = swagger.host || url.host();
swagger.schemes = swagger.schemes || [url.scheme()];
//TODO: decide what to do with base path
}
Util.removeNonValues(swagger);
var basePath = swagger.basePath
if (_.isString(basePath))
swagger.basePath = URI().path(basePath).normalize().path();
_.each(swagger.definitions, function (schema) {
if (!_.isUndefined(schema.id))
delete schema.id;
});
};
Swagger2.prototype.fillMissing = function (dummyData) {
dummyData = dummyData || {
info: {
title: '< An API title here >',
version: '< An API version here >'
}
};
this.spec = _.merge(dummyData, this.spec);
}
Swagger2.prototype.parsers = {
'JSON': Util.parseJSON,
'YAML': Util.parseYAML
};
Swagger2.prototype.checkFormat = function (spec) {
return !_.isUndefined(spec.swagger);
}
Swagger2.prototype.validate = function (callback) {
var promise = sway.create({definition: this.spec, jsonRefs: this.jsonRefs})
.then(function (swaggerObj) {
var result = swaggerObj.validate();
result.remotesResolved = swaggerObj.definitionRemotesResolved;
if (_.isEmpty(result.errors))
result.errors = null;
if (_.isEmpty(result.warnings))
result.warnings = null;
return result;
});
return Promise.resolve(promise).asCallback(callback);
};
|
"use strict";
/**
* Copyright 2013 Facebook, 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.
*
* @providesModule emptyFunction
*/
var copyProperties = require("./copyProperties")["default"];
function makeEmptyFunction (arg) {
return function () {
return arg;
};
}
/**
* This function accepts and discards inputs; it has no side effects. This is
* primarily useful idiomatically for overridable function endpoints which
* always need to be callable, since JS lacks a null-call idiom ala Cocoa.
*/
function emptyFunction () {}
copyProperties(emptyFunction, {
thatReturns: makeEmptyFunction,
thatReturnsFalse: makeEmptyFunction(false),
thatReturnsTrue: makeEmptyFunction(true),
thatReturnsNull: makeEmptyFunction(null),
thatReturnsThis: function() { return this; },
thatReturnsArgument: function(arg) { return arg; }
});
exports["default"] = emptyFunction;
|
//
// Grunttask runners
//
module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
jshint: {
files: ['Gruntfile.js', 'src/**/*.js', 'tests/**/*.js'],
options: {
ignores: ['tests/specs/libs/*.js'],
// options here to override JSHint defaults
globals: {
console: true,
module: true,
document: true
},
// dont check dot notation
sub :true
}
},
watch: {
files: ['<%= jshint.files %>'],
tasks: ['jshint']
},
karma : {
unit: {
configFile: 'tests/karma.conf.js'
// autoWatch: true
}
},
mocha_phantomjs: {
options: {
//'reporter': 'xunit',
//'output': 'test/results/mocha.xml'
},
all: ['tests/specs/index.html'],
},
// Shunt files around
shunt : {
// Shunt the documents of our project
docs : {
'README.md' : './index.html'
},
// Combine the src files, create minified versions
build : {
'dist/hello.js' : ['src/hello.js', 'src/hello.amd.js'],
'dist/hello.all.js' : ['src/hello.js', 'src/modules/', 'src/hello.amd.js']
},
minify : {
'dist/hello.min.js' : 'dist/hello.js',
'dist/hello.all.min.js' : 'dist/hello.all.js'
}
}
});
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-mocha-phantomjs');
grunt.loadNpmTasks('grunt-karma');
grunt.loadNpmTasks('shunt');
grunt.registerTask('test', ['jshint', 'mocha_phantomjs']);
grunt.registerTask('default', ['test', 'shunt:build', 'shunt:minify']);
};
|
/*
Copyright (c) 2017 Jirtdan Team and other collaborators
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import * as $ from 'jquery';
import { Board } from './app/Board.js';
import { AndGate } from './app/controls/gates/AndGate.js';
import { OrGate } from './app/controls/gates/OrGate.js';
import { HighConstant } from './app/controls/terminals/HighConstant.js';
import { LowConstant } from './app/controls/terminals/LowConstant.js';
import { Bulb } from './app/controls/terminals/Bulb.js';
import { NotGate } from './app/controls/gates/NotGate.js';
import { BufferGate } from './app/controls/gates/BufferGate.js';
import { XorGate } from './app/controls/gates/XorGate.js';
import { SwitchButton } from './app/controls/terminals/SwitchButton.js';
import { PushButton } from './app/controls/terminals/PushButton.js';
import { NandGate } from './app/controls/gates/NandGate.js';
import { NorGate } from './app/controls/gates/NorGate.js';
import { XnorGate } from './app/controls/gates/XnorGate.js';
let board = new Board(Raphael('board', 1280, 800));
$(document).ready(function() {
$('#board')
.mousedown(function(event) {
'use strict';
board.onMouseDown(event);
})
.mousemove(function(event) {
'use strict';
board.onMouseMove(event);
})
.mouseup(function(event) {
'use strict';
board.onMouseUp(event);
});
$('#btn-add-and').click(function(event) {
board.addControl(new AndGate(board));
});
$('#btn-add-one').click(function(event) {
board.addControl(new HighConstant(board));
});
$('#btn-add-zero').click(function(event) {
board.addControl(new LowConstant(board));
});
$('#btn-add-bulb').click(function(event) {
board.addControl(new Bulb(board));
});
$('#btn-add-or').click(function(event) {
board.addControl(new OrGate(board));
});
$('#btn-add-not').click(function(event) {
board.addControl(new NotGate(board));
});
$('#btn-add-xor').click(function(event) {
board.addControl(new XorGate(board));
});
$('#btn-add-switch').click(function(event) {
board.addControl(new SwitchButton(board));
});
$('#btn-add-push').click(function(event) {
board.addControl(new PushButton(board));
});
$('#btn-add-buffer').click(function(event) {
board.addControl(new BufferGate(board));
});
$('#btn-add-nand').click(function(event) {
board.addControl(new NandGate(board));
});
$('#btn-add-nor').click(function(event) {
board.addControl(new NorGate(board));
});
$('#btn-add-xnor').click(function(event) {
board.addControl(new XnorGate(board));
});
$('#btn-delete').click(function(event) {
board.deleteSelected();
});
$('body').on('keyup', function(event) {
// delete selected item
// when user clicks 'del' button on keyboard
if (event.keyCode === 46) {
board.deleteSelected();
}
});
$('#btn-unselect').click(function(event) {
board.unselect();
});
});
|
const Product = require('../models/product');
exports.getAddProduct = (req, res, next) => {
res.render('admin/edit-product', {
pageTitle: 'Add Product',
path: '/admin/add-product',
editing: false
});
};
exports.postAddProduct = (req, res, next) => {
const title = req.body.title;
const imageUrl = req.body.imageUrl;
const price = req.body.price;
const description = req.body.description;
const product = new Product(title, price, description, imageUrl);
product
.save()
.then(result => {
// console.log(result);
console.log('Created Product');
res.redirect('/admin/products');
})
.catch(err => {
console.log(err);
});
};
// exports.getEditProduct = (req, res, next) => {
// const editMode = req.query.edit;
// if (!editMode) {
// return res.redirect('/');
// }
// const prodId = req.params.productId;
// req.user
// .getProducts({ where: { id: prodId } })
// // Product.findById(prodId)
// .then(products => {
// const product = products[0];
// if (!product) {
// return res.redirect('/');
// }
// res.render('admin/edit-product', {
// pageTitle: 'Edit Product',
// path: '/admin/edit-product',
// editing: editMode,
// product: product
// });
// })
// .catch(err => console.log(err));
// };
// exports.postEditProduct = (req, res, next) => {
// const prodId = req.body.productId;
// const updatedTitle = req.body.title;
// const updatedPrice = req.body.price;
// const updatedImageUrl = req.body.imageUrl;
// const updatedDesc = req.body.description;
// Product.findById(prodId)
// .then(product => {
// product.title = updatedTitle;
// product.price = updatedPrice;
// product.description = updatedDesc;
// product.imageUrl = updatedImageUrl;
// return product.save();
// })
// .then(result => {
// console.log('UPDATED PRODUCT!');
// res.redirect('/admin/products');
// })
// .catch(err => console.log(err));
// };
// exports.getProducts = (req, res, next) => {
// req.user
// .getProducts()
// .then(products => {
// res.render('admin/products', {
// prods: products,
// pageTitle: 'Admin Products',
// path: '/admin/products'
// });
// })
// .catch(err => console.log(err));
// };
// exports.postDeleteProduct = (req, res, next) => {
// const prodId = req.body.productId;
// Product.findById(prodId)
// .then(product => {
// return product.destroy();
// })
// .then(result => {
// console.log('DESTROYED PRODUCT');
// res.redirect('/admin/products');
// })
// .catch(err => console.log(err));
// };
|
var INSTALLED={
"keys":["G/Town Roads","Caribbean","Guyana","World","Iceland","Greenland"],
"Caribbean":{
"path":"./static/ggmc/data/caribbean/",
"bbox":[-90.,-2.,-53.,30.],
"center":[-71.5,14.5],
"color":"rgba(255,255,0,0)",
"fill":"rgba(0,100,40,0)",
"width":2,
"polygon_sources":[
{"filename":"caribbean.geojson","color":"rgba(0,255,0,1)","fill":'rgba(0,255,0,0.15)','width':1,"category":"Caribbean","layer_name":'Nations'},
],
"point_sources":[],
"line_sources":[],
"gpx_sources":[]
},
"Guyana":{
"path":"./static/ggmc/data/guyana/",
"bbox":[-61.5,1.1,-56.3,8.7],
"center":[-58.9,4.9],
"color":"rgba(255,255,0,1)",
"fill":"rgba(0,100,40,.1)",
"width":2,
"polygon_sources":[
{"filename":"pacs.geojson","color":"rgba(0,255,0,1)","fill":'rgba(0,255,0,0.25)','width':1,"category":"PAC","layer_name":'Protected Areas'},
{"filename":"gy_rivers.geojson","color":"rgba(0,100,255,1)","fill":'rgba(0,0,255,1)','width':1,"category":"PAC", "layer_name":'Rivers'},
// {"filename":"gy_creeks.geojson","color":"rgba(100,200,155,1)","fill":'rgba(0,0,255,1)','width':1,"category":"PAC", "layer_name":'Creeks'},
],
"point_sources":[
{"filename":"gy_towns.geojson","color":"rgba(255,0,0,1)","fill":'rgba(255,255,255,1)','width':5,'radius':10,"category":"Places", "layer_name":'Towns'},
],
"line_sources":[
// {"filename":"test_segment.geojson","color":"rgba(155,255,0,1)",'width':5},
],
"gpx_sources":[]
},
"Iceland":{
"path":"./static/ggmc/data/iceland/",
"bbox":[-24.542, 63.39,-13.499,66.536],
"center":[(-24.542+-13.499)/2.,65.],
"color":"#ff0",
"fill":"rgba(0,100,0,0.5)",
"width":2,
"polygon_sources":[],
"point_sources":[],
"line_sources":[],
"gpx_sources":[]
},
"Greenland":{
"path":"./static/ggmc/data/greenland/",
"bbox":[-73.054, 59.79,-12.155,83.624],
"center":[(-73.054-12.155)/2.,76.],
"color":"#ff0",
"fill":"rgba(100,100,0,0.5)",
"width":2,
"polygon_sources":[],
"point_sources":[],
"line_sources":[],
"gpx_sources":[]
},
"World":{
"path":"./static/ggmc/data/world/",
"bbox":[-160,-60,100,60],
"center":[0,20],
"color":"rgba(255,0,0,0)",
"fill":"rgba(0,100,0,0.1)",
"width":0,
"polygon_sources":[
{"filename":"world_borders.geojson","color":"rgba(0,255,0,1)","fill":'rgba(0,255,0,0.25)','width':1,"category":"World","layer_name":'Countries'},
],
"point_sources":[],
"line_sources":[],
"gpx_sources":[]
},
"G/Town Roads":{
"path":"./static/ggmc/data/georgetown/",
"bbox":[-58.104,6.762, -58.169,6.832],
"center":[-58.13836,6.79834],
"color":"rgba(255,0,0,0)",
"fill":"rgba(0,100,0,0.1)",
"width":0,
"polygon_sources":[
{"filename":"gt_roads.geojson","color":"rgba(0,255,234,1)","fill":'rgba(0,255,0,0.25)','width':3,"category":"Roads","layer_name":'Georgetown Roads'}
],
"point_sources":[],
"line_sources":[],
"gpx_sources":[
{"filename":"gtown-44.gpx","color":"rgba(255,0,0,1)","fill":'rgba(0,255,0,0.25)','width':3,"category":"Bus Routes","layer_name":"Bus 44"},
{"filename":"gtown-45.gpx","color":"rgba(155,110,0,1)","fill":'rgba(0,255,0,0.25)','width':3,"category":"Bus Routes","layer_name":"Bus 45"},
]
}
}
|
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2007 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Create the FCKeditorAPI object that is available as a global object in
* the page where the editor is placed in.
*/
var FCKeditorAPI ;
function InitializeAPI()
{
var oParentWindow = window.parent ;
if ( !( FCKeditorAPI = oParentWindow.FCKeditorAPI ) )
{
// Make the FCKeditorAPI object available in the parent window. Use
// eval so this core runs in the parent's scope and so it will still be
// available if the editor instance is removed ("Can't execute code
// from a freed script" error).
// Note: we check the existence of oEditor.GetParentForm because some external
// code (like JSON) can extend the Object prototype and we get then extra oEditor
// objects that aren't really FCKeditor instances.
var sScript =
'var FCKeditorAPI = {' +
'Version : "2.5.1",' +
'VersionBuild : "17566",' +
'__Instances : new Object(),' +
'GetInstance : function( name )' +
'{' +
'return this.__Instances[ name ];' +
'},' +
'_FormSubmit : function()' +
'{' +
'for ( var name in FCKeditorAPI.__Instances )' +
'{' +
'var oEditor = FCKeditorAPI.__Instances[ name ] ;' +
'if ( oEditor.GetParentForm && oEditor.GetParentForm() == this )' +
'oEditor.UpdateLinkedField() ;' +
'}' +
'this._FCKOriginalSubmit() ;' +
'},' +
'_FunctionQueue : {' +
'Functions : new Array(),' +
'IsRunning : false,' +
'Add : function( f )' +
'{' +
'this.Functions.push( f );' +
'if ( !this.IsRunning )' +
'this.StartNext();' +
'},' +
'StartNext : function()' +
'{' +
'var aQueue = this.Functions ;' +
'if ( aQueue.length > 0 )' +
'{' +
'this.IsRunning = true;' +
'aQueue[0].call();' +
'}' +
'else ' +
'this.IsRunning = false;' +
'},' +
'Remove : function( f )' +
'{' +
'var aQueue = this.Functions;' +
'var i = 0, fFunc;' +
'while( (fFunc = aQueue[ i ]) )' +
'{' +
'if ( fFunc == f )' +
'aQueue.splice( i,1 );' +
'i++ ;' +
'}' +
'this.StartNext();' +
'}' +
'}' +
'}' ;
// In IE, the "eval" function is not always available (it works with
// the JavaScript samples, but not with the ASP ones, for example).
// So, let's use the execScript instead.
if ( oParentWindow.execScript )
oParentWindow.execScript( sScript, 'JavaScript' ) ;
else
{
if ( FCKBrowserInfo.IsGecko10 )
{
// FF 1.0.4 gives an error with the request bellow. The
// following seams to work well.
eval.call( oParentWindow, sScript ) ;
}
else if ( FCKBrowserInfo.IsSafari || FCKBrowserInfo.IsGecko19 )
{
// oParentWindow.eval in Safari and Gran Paradiso executes in the calling window
// environment, instead of the parent one. The following should make it work.
var oParentDocument = oParentWindow.document ;
var eScript = oParentDocument.createElement('script') ;
eScript.appendChild( oParentDocument.createTextNode( sScript ) ) ;
oParentDocument.documentElement.appendChild( eScript ) ;
}
else
oParentWindow.eval( sScript ) ;
}
FCKeditorAPI = oParentWindow.FCKeditorAPI ;
}
// Add the current instance to the FCKeditorAPI's instances collection.
FCKeditorAPI.__Instances[ FCK.Name ] = FCK ;
}
// Attach to the form onsubmit event and to the form.submit().
function _AttachFormSubmitToAPI()
{
// Get the linked field form.
var oForm = FCK.GetParentForm() ;
if ( oForm )
{
// Attach to the onsubmit event.
FCKTools.AddEventListener( oForm, 'submit', FCK.UpdateLinkedField ) ;
// IE sees oForm.submit function as an 'object'.
if ( !oForm._FCKOriginalSubmit && ( typeof( oForm.submit ) == 'function' || ( !oForm.submit.tagName && !oForm.submit.length ) ) )
{
// Save the original submit.
oForm._FCKOriginalSubmit = oForm.submit ;
// Create our replacement for the submit.
oForm.submit = FCKeditorAPI._FormSubmit ;
}
}
}
function FCKeditorAPI_Cleanup()
{
if ( ! window.FCKUnloadFlag )
return ;
delete FCKeditorAPI.__Instances[ FCK.Name ] ;
}
function FCKeditorAPI_ConfirmCleanup()
{
window.FCKUnloadFlag = true ;
}
FCKTools.AddEventListener( window, 'unload', FCKeditorAPI_Cleanup ) ;
FCKTools.AddEventListener( window, 'beforeunload', FCKeditorAPI_ConfirmCleanup) ;
|
define("dijit/form/HorizontalRule", [
"dojo/_base/declare", // declare
"../_Widget",
"../_TemplatedMixin"
], function(declare, _Widget, _TemplatedMixin){
// module:
// dijit/form/HorizontalRule
return declare("dijit.form.HorizontalRule", [_Widget, _TemplatedMixin], {
// summary:
// Hash marks for `dijit/form/HorizontalSlider`
templateString: '<div class="dijitRuleContainer dijitRuleContainerH"></div>',
// count: Integer
// Number of hash marks to generate
count: 3,
// container: String
// For HorizontalSlider, this is either "topDecoration" or "bottomDecoration",
// and indicates whether this rule goes above or below the slider.
container: "containerNode",
// ruleStyle: String
// CSS style to apply to individual hash marks
ruleStyle: "",
_positionPrefix: '<div class="dijitRuleMark dijitRuleMarkH" style="left:',
_positionSuffix: '%;',
_suffix: '"></div>',
_genHTML: function(pos){
return this._positionPrefix + pos + this._positionSuffix + this.ruleStyle + this._suffix;
},
// _isHorizontal: [protected extension] Boolean
// VerticalRule will override this...
_isHorizontal: true,
buildRendering: function(){
this.inherited(arguments);
var innerHTML;
if(this.count == 1){
innerHTML = this._genHTML(50, 0);
}else{
var i;
var interval = 100 / (this.count-1);
if(!this._isHorizontal || this.isLeftToRight()){
innerHTML = this._genHTML(0, 0);
for(i=1; i < this.count-1; i++){
innerHTML += this._genHTML(interval*i, i);
}
innerHTML += this._genHTML(100, this.count-1);
}else{
innerHTML = this._genHTML(100, 0);
for(i=1; i < this.count-1; i++){
innerHTML += this._genHTML(100-interval*i, i);
}
innerHTML += this._genHTML(0, this.count-1);
}
}
this.domNode.innerHTML = innerHTML;
}
});
});
|
var searchData=
[
['data_5fthr',['data_thr',['../classdataManager.html#a509a1915ab57d91969f4d7075a138c2e',1,'dataManager']]],
['datamanager',['dataManager',['../classdataManager.html#a53882fb8b2d08f1b73f6c8e9202c5ae4',1,'dataManager']]]
];
|
/* Marker cluster styles */
var styles = [[{
url: '/js/js-marker-cluster/images/union2bluemarker.png',
height: 56,
width: 40,
anchor: [16, 0],
textColor: '#000000',
textSize: 10
}, {
url: '/js/js-marker-cluster/images/union10bluemarker.png',
height: 66,
width: 50,
anchor: [24, 0],
textColor: '#000000',
textSize: 11
}, {
url: '/js/js-marker-cluster/images/union100bluemarker.png',
height: 106,
width: 90,
anchor: [32, 0],
textColor: '#000000',
textSize: 12
}], [{
url: '/js/js-marker-cluster/images/union2redmarker.png',
height: 40,
width: 40,
anchor: [16, 0],
textColor: '#000000',
textSize: 10
}, {
url: '/js/js-marker-cluster/images/union10redmarker.png',
height: 50,
width: 50,
anchor: [24, 0],
textColor: '#000000',
textSize: 11
}, {
url: '/js/js-marker-cluster/images/union100redmarker.png',
height: 90,
width: 90,
anchor: [32, 0],
textColor: '#000000',
textSize: 12
}],
];
/* Google map */
function googleMap(mapid)
{
// show map props
this.mapid = mapid;
this.lat = null;
this.lng = null;
this.zoom = null;
this.map = null;
this.center = null;
this.mapProp = null;
// marker cluster props
this.maxZoom = null;
this.gridSize = null;
this.style = null;
this.markers = [];
this.markerClusterer = null;
// moveable marker
this.mMarker = null;
this.mLat = null;
this.mLng = null;
this.mIcon = null;
}
googleMap.prototype.showMap = function(lat, lng, zoom)
{
this.lat = lat || 63.31268278;
this.lng = lng || 103.42773438;
this.zoom = zoom || 3;
this.center = new google.maps.LatLng(this.lat, this.lng);
this.mapProp = {
center: this.center,
zoom: this.zoom,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
this.map = new google.maps.Map(document.getElementById(this.mapid), this.mapProp);
};
googleMap.prototype.showMarker = function(lat, lng, icon, moveable)
{
lat = lat || 63.31268278;
lng = lng || 103.42773438;
icon = icon || "/images/pointer-blue.png";
var location = new google.maps.LatLng(lat, lng);
var infoWindowTitle = "Местоположение";
var infoWinfowContent = "Широта: " + lat + "<br>Долгота: " + lng;
var marker = new google.maps.Marker({
position: location,
map: this.map,
title: infoWindowTitle,
clickable: true
});
var infoWindow = new google.maps.InfoWindow({
content: infoWinfowContent,
position: location
});
google.maps.event.addListener(marker, "click", function () {
infoWindow.open(this.map);
});
marker.setIcon(icon);
if (moveable) {
this.mMarker = marker;
this.mLat = lat;
this.mLng = lng;
this.mIcon = icon;
} else {
this.markers.push(marker);
}
};
googleMap.prototype.hideMarker = function()
{
if (this.mMarker) {
this.mMarker.setMap(null);
this.mMarker = null;
}
};
googleMap.prototype.showMoveableMarker = function(lat, lng, icon)
{
var m = this;
m.showMarker(lat, lng, icon, true);
google.maps.event.addListener(m.map, 'click', function(event) {
m.moveMarker(event.latLng);
m.saveCoords("/private-room/save-coords/");
});
};
googleMap.prototype.moveMarker = function(latLng)
{
this.hideMarker();
this.mLat = latLng.lat();
this.mLng = latLng.lng();
this.showMarker(this.mLat, this.mLng, this.mIcon, true);
};
googleMap.prototype.saveCoords = function(url)
{
$.ajax({
url: url,
method: "POST",
data: { latitude: this.mLat, longitude: this.mLng },
dataType: "json"
});
};
googleMap.prototype.markerClusterInit = function(maxZoom, gridSize, style)
{
this.maxZoom = maxZoom || null;
this.gridSize = gridSize || null;
this.style = style || 0;
this.markerClusterer = new MarkerClusterer(this.map, this.markers, {
maxZoom: this.maxZoom,
gridSize: this.gridSize,
styles: styles[this.style]
});
}
googleMap.prototype.placeMarkers = function(coords, icon)
{
icon = icon || "/images/pointer-blue.png";
for (var i = 0; i < coords.length; i++) {
var lat = coords[i].latitude;
var lng = coords[i].longitude;
this.showMarker(lat, lng, icon);
}
}
googleMap.prototype.clearMarkers = function()
{
for (var i = 0; i < this.markers.length; i++) {
this.markers[i].setMap(null);
this.markers[i] = null;
}
this.markers.length = 0;
if (this.markerClusterer) {
this.markerClusterer.clearMarkers();
this.markerClusterer = null;
}
}
|
var smart_energy_lenslider_fn = function(inparr) {
jQuery(".ls_sm_en_ib_manage li").hover(
function() {
jQuery(this).addClass("hvr");
},
function() {
jQuery(this).removeClass("hvr");
}
);
jQuery(".ls_sm_en_ib_manage").prepend("<div class=\"labs\"></div>");
jQuery(".ls_sm_en_ibanner").tabs(
{
fx:{opacity:"toggle"},
select: function(event, ui) {
jQuery(".labs").animate({'margin-left':ui.index*240}, 200);
},
show: function(event, ui) {
jQuery(".ls_sm_en_ibanner_overlay").hide();
jQuery("#ibo_"+ui.index).fadeIn(300);
}
}
).tabs("rotate", inparr.slideshow.ls_autoplay_delay);
}
|
'use strict';
/*
* The goal of this test is to cover the Workers' implementation of
* Worker.prototype.destroy. Worker.prototype.destroy is called within
* the worker's context: once when the worker is still connected to the
* master, and another time when it's not connected to it, so that we cover
* both code paths.
*/
const common = require('../common');
var cluster = require('cluster');
var worker1, worker2;
if (cluster.isMaster) {
worker1 = cluster.fork();
worker2 = cluster.fork();
[worker1, worker2].forEach(function(worker) {
worker.on('disconnect', common.mustCall(function() {}));
worker.on('exit', common.mustCall(function() {}));
});
} else {
if (cluster.worker.id === 1) {
// Call destroy when worker is disconnected
cluster.worker.process.on('disconnect', function() {
cluster.worker.destroy();
});
cluster.worker.disconnect();
} else {
// Call destroy when worker is not disconnected yet
cluster.worker.destroy();
}
}
|
/**
* @package ZT Headline module for Joomla! 1.7
* @author http://www.zootemplate.com
* @copyright (C) 2011- ZooTemplate.Com
* @license PHP files are GNU/GPL
**/
var ZTVerHeadLine = new Class({
options:{
duration: 2000,
transition: Fx.Transitions.Quart.easeInOut
},
initialize:function(){
$each(arguments, function(argument, i){
switch($type(argument)){
case 'object': options = argument; break;
}
});
this.fx = [];
this.setOptions(options);
this.counter = -1;
this.activeSlide = 0;
this.nextSlide = 0;
this.slideOuter = $$(this.options.slideOuter);
this.slideBarItem = $$(this.options.slideBarItem);
this.slideOuter.each(function(item,i){
item.setStyle('opacity',0);
});
this.slideBarItem.each(function(item,i){
item.addEvent('mouseenter',function(e){
item.addClass('slideactive1');
});
item.addEvent('mouseleave',function(e){
item.removeClass('slideactive1');
});
item.addEvent('click',function(e){
this.changeSlideByClick(i);
}.bind(this));
}.bind(this)) ;
this.changeSlide();
this.slideTime = this.changeSlide.periodical(this.options.slideDelay,this);
},
changeSlide:function(){
var obj= {};
if(this.counter !=-1){
if(this.counter != this.slideOuter.length - 1) {
this.activeSlide = this.counter;
this.nextSlide = this.counter + 1;
} else {
this.activeSlide = this.counter;
this.nextSlide = 0;
}
this.slideOuter.each(function(item,i){
if(this.slideOuter[i].fx){this.slideOuter[i].fx.stop();}
}.bind(this));
(this.slideOuter)[this.activeSlide].fx = (this.slideOuter)[this.activeSlide].effect('opacity', {duration: this.options.duration,wait:false}).start(0);
(this.slideOuter)[this.nextSlide].fx = (this.slideOuter)[this.nextSlide].effect('opacity', {duration: this.options.duration,wait:false}).start(1);
(this.slideBarItem)[this.activeSlide].removeClass('slideactive');
(this.slideBarItem)[this.nextSlide].addClass('slideactive');
if(this.counter == this.slideOuter.length - 1) {this.counter=0;} else { this.counter++;}
}else {
this.slideBarItem[0].addClass('slideactive');
this.slideOuter[0].setStyle('opacity',1);
this.counter = 0;
}
},
changeSlideByClick:function(i){
if(this.counter !=i){
this.counter = i;
this.slideOuter.each(function(item,i){
if(this.slideOuter[i].fx){this.slideOuter[i].fx.stop();}
}.bind(this));
(this.slideOuter)[this.nextSlide].fx = (this.slideOuter)[this.nextSlide].effect('opacity', {duration: this.options.duration,wait:false}).start(0);
(this.slideOuter)[i].fx = (this.slideOuter)[i].effect('opacity', {duration: this.options.duration,wait:false}).start(1);
(this.slideBarItem)[this.nextSlide].removeClass('slideactive');
(this.slideBarItem)[i].addClass('slideactive');
this.nextSlide = i;
$clear(this.slideTime);
this.slideTime = this.changeSlide.periodical(this.options.slideDelay,this);
}
}
});
ZTVerHeadLine.implement(new Options);
ZTVerHeadLine.implement(new Events);
|
jQuery( window ).load( function() {
if ( 'true' == woo_localized_data.slideshow ) { woo_localized_data.slideshow = true; } else { woo_localized_data.slideshow = false; }
if ( 'true' == woo_localized_data.directionNav ) { woo_localized_data.directionNav = true; } else { woo_localized_data.directionNav = false; }
if ( 'true' == woo_localized_data.controlNav ) { woo_localized_data.controlNav = true; } else { woo_localized_data.controlNav = false; }
if ( 'true' == woo_localized_data.pauseOnHover ) { woo_localized_data.pauseOnHover = true; } else { woo_localized_data.pauseOnHover = false; }
if ( 'true' == woo_localized_data.pauseOnAction ) { woo_localized_data.pauseOnAction = true; } else { woo_localized_data.pauseOnAction = false; }
if ( 'true' == woo_localized_data.touch ) { woo_localized_data.touch = true; } else { woo_localized_data.touch = false; }
if ( 'true' == woo_localized_data.smoothHeight ) { woo_localized_data.smoothHeight = true; } else { woo_localized_data.smoothHeight = false; }
// Cast the speed variables as floats.
woo_localized_data.slideshowSpeed = parseFloat( woo_localized_data.slideshowSpeed );
woo_localized_data.animationSpeed = parseFloat( woo_localized_data.animationSpeed );
jQuery( '#featured-slider' ).flexslider({
animation: woo_localized_data.animation,
controlsContainer: woo_localized_data.controlsContainer,
smoothHeight: woo_localized_data.smoothHeight,
directionNav: woo_localized_data.directionNav,
controlNav: woo_localized_data.controlNav,
manualControls: woo_localized_data.manualControls,
slideshow: woo_localized_data.slideshow,
pauseOnHover: woo_localized_data.pauseOnHover,
slideshowSpeed: woo_localized_data.slideshowSpeed,
animationSpeed: woo_localized_data.animationSpeed,
touch: woo_localized_data.touch,
pauseOnHover: woo_localized_data.pauseOnHover,
pauseOnAction: woo_localized_data.pauseOnAction
});
});
|
/*
* Title : Pinpoint Booking System WordPress Plugin (PRO)
* Version : 2.1.2
* File : assets/js/templates/backend-templates.js
* File Version : 1.0.2
* Created / Last Modified : 11 October 2015
* Author : Dot on Paper
* Copyright : © 2012 Dot on Paper
* Website : http://www.dotonpaper.net
* Description : Back end templates JavaScript class.
*/
var DOPBSPBackEndTemplates = new function(){
'use strict';
/*
* Private variables.
*/
var $ = jQuery.noConflict();
/*
* Constructor
*/
this.__construct = function(){
};
/*
* Display templates.
*/
this.display = function(){
// $('.DOPBSP-admin .dopbsp-main').css('display', 'block');
};
return this.__construct();
};
|
/*
Copyright (c) 2004-2008, The Dojo Foundation All Rights Reserved.
Available via Academic Free License >= 2.1 OR the modified BSD license.
see: http://dojotoolkit.org/license for details
*/
dojo._xdResourceLoaded(function(dojo, dijit, dojox){
return {depends: [["provide", "dojox.gfx.move"],
["require", "dojox.gfx.Mover"],
["require", "dojox.gfx.Moveable"]],
defineResource: function(dojo, dijit, dojox){if(!dojo._hasResource["dojox.gfx.move"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
dojo._hasResource["dojox.gfx.move"] = true;
dojo.provide("dojox.gfx.move");
dojo.require("dojox.gfx.Mover");
dojo.require("dojox.gfx.Moveable");
}
}};});
|
/*
* Copyright (C) 2016 Max Prettyjohns
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
import {camelToSnake, snakeToCamel} from '../util';
export default function titleUnlock(bookshelf) {
const TitleUnlock = bookshelf.Model.extend({
editor() {
return this.belongsTo('Editor', 'editor_id');
},
format: camelToSnake,
idAttribute: 'id',
parse: snakeToCamel,
tableName: 'bookbrainz.title_unlock',
title() {
return this.belongsTo('TitleType', 'title_id');
}
});
return bookshelf.model('TitleUnlock', TitleUnlock);
}
|
function clientEditRow(baseURL, elementID, dbID) {
console.log("inside clientEditRow function, variables:", elementID, ",",dbID);
var hostPort = "http://";
if (baseURL.port) { hostPort = baseURL.hostname.concat(':', baseURL.port); }
else { hostPort = baseURL.hostname; }
var URL = hostPort.concat(baseURL.pathname);
console.log(URL);
var cmdResponseText = sendCommand(URL+ "edit",{id:dbID});
}
function clientModifyRow(command,baseURL, elementID, dbID) {
if ( ! (command == "edit" || command == "delete" )) {
console.log ("Bad command:", command);
return;
}
var protocol = "http://";
if (baseURL.port) { hostPort = protocol.concat(baseURL.hostname,':', baseURL.port); }
else { hostPort = protocol.concat(baseURL.hostname); }
var URL = hostPort.concat(baseURL.pathname);
console.log(URL);
var cmdResponseText = sendCommand(URL + command,{id:dbID});
console.log("Reponse Text is:", cmdResponseText);
}
function clientDeleteRow(baseURL, elementID, dbID) {
console.log("inside clientDeleteRow function, variables:", baseURL, elementID,",", dbID);
var protocol = "http://";
if (baseURL.port) { hostPort = protocol.concat(baseURL.hostname,':', baseURL.port); }
else { hostPort = protocol.concat(baseURL.hostname); }
var URL = hostPort.concat(baseURL.pathname);
console.log(URL);
sendCommand(URL+ "delete",{id:dbID});
}
function sendCommand (path, params) {
var connection = new XMLHttpRequest();
var sendString = path;
sendString += "?";
var firstArg = true;
for (key in params) {
if (params.hasOwnProperty(key)) {
if ( ! firstArg ) {
sendString += "&";
}
else {
firstArg = false;
}
sendString += "" + key + "=" + params[key];
}
}
console.log("Opening get request with:", sendString);
connection.open("GET", sendString,true);
connection.send(null);
connection.addEventListener('load', function () {
console.log("Request status:", connection.status);
if ( connection.status < 400 )
return connection.responseText;
else
return undefined;
});
}
|
function stream_context_get_params (stream_or_context) {
// http://kevin.vanzonneveld.net
// + original by: Brett Zamir (http://brett-zamir.me)
// * example 1: var params = {notification:function (notification_code, severity, message, message_code, bytes_transferred, bytes_max) {}};
// * example 1: var context = stream_context_create({}, params);
// * example 1: stream_context_get_params(context);
// * returns 1: {notification:function (notification_code, severity, message, message_code, bytes_transferred, bytes_max) {}, options:{}}
return stream_or_context.stream_params;
}
|
function selectDate(str, obj) {
var now = new Date(); //获取当前时间
var year = now.getFullYear(); //获取当前日期的年份部分
// if ($.browser.mozilla) { year = year + 1900; } //如果是火狐浏览器,则需要加上1900年
// if ($.browser.opera) { year = year + 1900; } //如果是opera浏览器,则需要加上1900年
// if ($.browser.safari) { year = year + 1900; } //如果是safari浏览器,则需要加上1900年
//if (!$.browser.msie) { year = year + 1900;} //如果不是IE浏览器,则需要加上1900年
var month = now.getMonth() + 1 +""; //获取当前日期的月份部分
var day = now.getDate() +""; //获取当前日期的天数部分
if(day.length==1){
day="0"+day;
}
//alert(year); //opera safari msie
//获取当前月份包含的天数
var nowdays = new Date(year, month, 0).getDate();
var lastMonth = month - 1+"";
var lastMonthdays = new Date(year, lastMonth, 0).getDate() +"";
if(month.length==1){
month="0"+month;
}
if(lastMonth.length==1){
lastMonth="0"+lastMonth;
}
if(lastMonthdays.length==1){
lastMonthdays="0"+lastMonthdays;
}
var startTime = "";
var endTime = "";
switch (str) {
case "toDay":
startTime = year + "-" + month + "-" + day;
endTime = year + "-" + month + "-" + day;
break;
case "lastMonth":
if (lastMonth == 0) { lastMonth = 12; year = year - 1; }
startTime = year + "-" + lastMonth + "-01";
endTime = year + "-" + lastMonth + "-" + lastMonthdays;
break;
case "currentMonth":
startTime = year + "-" + month + "-01";
//endTime = year + "-" + month + "-" + day;
endTime = year + "-" + month + "-" + nowdays;
break;
case "lastYear":
startTime = (year - 1) + "-01-01";
endTime = (year - 1) + "-12-31";
break;
case "currentYear":
startTime = year + "-01-01";
endTime = year + "-12-31";
break;
}
//alert(endTime);
// if (str != "all") {
$("#beginDate").val(startTime);
$("#endDate").val(endTime);
//}
//$("#td_Date a").removeClass(); //清空所有a标签的css
//$(obj).addClass("Fcurrent"); //为当前选中的a标签增加css
}
// 清空表单
function clearForm(myForm){
$(':input','#'+myForm)
.not(':button, :submit, :reset, :hidden')
.val('')
.removeAttr('checked')
.removeAttr('selected');
}
|
/*
* This file is part of the Doodle3D project (http://doodle3d.com).
*
* Copyright (c) 2013, Doodle3D
* This software is licensed under the terms of the GNU GPL v2 or later.
* See file LICENSE.txt or visit http://www.gnu.org/licenses/gpl.html for full license details.
*/
// http://stackoverflow.com/questions/1403888/get-url-parameter-with-jquery
function getURLParameter(name) {
return decodeURI(
(new RegExp('[&?]'+name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
);
}
// returns true for all smartphones and tablets
function isMobileDevice() {
return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini|Windows Mobile/i.test(navigator.userAgent);
}
// returns true for smartphones (Android will be a bit dodgy (tablet or phone, all depends on pixels vs devicePixelRatio...)
function isSmartphone() {
var returnBool = false;
if( /Android/i.test(navigator.userAgent) && window.devicePixelRatio > 1) {
var w = $(window).width() / window.devicePixelRatio;
console.log("Android device >> ratio'd width: " + w);
if (w < 480) {
returnBool = true;
}
} else {
returnBool = /Android|webOS|iPhone|iPod|BlackBerry|IEMobile|Opera Mini|Windows Mobile/i.test(navigator.userAgent)
}
return returnBool;
}
function distance(x1, y1, x2, y2) {
return Math.sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1));
}
|
var config = require('../config'),
db_name = config.couchdb.db_name,
nano = require('nano')(config.couchdb.server_url),
Utils = require('../utils/Utils.js');
/* If database already exists, an error will be returned by CouchDB
but we can still use that database. */
nano.db.create(db_name);
var keg_db = nano.db.use(db_name);
/* Keep track of a counter of all the shortened urls in order to know
how to generate the next short url. Does not get overwritten. */
keg_db.insert({
doc_type: 'keg_meta',
count: 0,
alphabet: 'Q5lP9DO2yAIW1TFbu6gHNVahdREU0Sm7M8cJBpeCZioGLwYnvzf3krK4tsXqxj'
}, 'keg:meta');
var CouchInterface = {
insertDocument: function (id, doc, callback) {
keg_db.insert(doc, id, function (err, body) {
callback(err, body)
});
},
updateDocument: function (doc, callback) {
keg_db.insert(doc, function (err, body) {
callback(err, body)
});
},
retrieveDocument: function (id, callback) {
keg_db.get(id, {}, function (err, body) {
callback(err, body)
});
},
generateShortId: function (callback) {
keg_db.get('keg:meta', {}, function (err, doc) {
if (err) {
return null;
}
var count = doc.count;
var alphabet = doc.alphabet;
var shortId = Utils.encodeToAlphabet(alphabet, count);
/* Update counter in CouchDB */
doc.count = count + 1;
keg_db.insert(doc, function (err, body) {
if (err) {
//TODO: Log and handle.
}
callback(shortId);
});
});
},
generateMetricsId: function (str) {
if (!str || str.length == 0) {
return null;
}
return str + ':metrics'
}
};
module.exports = CouchInterface;
|
// Facebook Friend
angular.module('FriendFB', [])
.config(function($interpolateProvider) {
$interpolateProvider.startSymbol('//');
$interpolateProvider.endSymbol('//');
})
.controller('Controller', function($scope, $http){
// TODO: needs to be a domain for Facebook app. ex: sitio.com
$http.get('http://matrix.com:8000/api/friends/').success(function(data){
$scope.friends = data;
});
});
|
Ext.define('Bloodbank.bloodbank.shared.com.model.healthcontext.StockUpdateModel.StockUpdateModel', {
"extend": "Ext.data.Model",
"fields": [{
"name": "numberofUnits",
"type": "int",
"defaultValue": ""
}, {
"name": "bloodGroup",
"type": "string",
"defaultValue": ""
}, {
"name": "donorId",
"type": "string",
"defaultValue": ""
}]
});
|
(function(App) {
'use strict';
var Config = {
title: 'Guimovie',
platform: process.platform,
genres: [
'All',
'Action',
'Adventure',
'Animation',
'Biography',
'Comedy',
'Crime',
'Documentary',
'Drama',
'Family',
'Fantasy',
'Film-Noir',
'History',
'Horror',
'Music',
'Musical',
'Mystery',
'Romance',
'Sci-Fi',
'Short',
'Sport',
'Thriller',
'War',
'Western'
],
sorters: [
'popularity',
'date',
'year',
'rating',
'alphabet'
],
sorters_tv: [
'popularity',
'updated',
'year',
'name'
],
types_anime: [
'All',
'Movies',
'TV',
'OVA',
'ONA'
],
genres_anime: [
'All',
'Action',
'Adventure',
'Cars',
'Comedy',
'Dementia',
'Demons',
'Drama',
'Ecchi',
'Fantasy',
'Game',
'Harem',
'Historical',
'Horror',
'Josei',
'Kids',
'Magic',
'Martial Arts',
'Mecha',
'Military',
'Music',
'Mystery',
'Parody',
'Police',
'Psychological',
'Romance',
'Samurai',
'School',
'Sci-Fi',
'Seinen',
'Shoujo',
'Shoujo Ai',
'Shounen',
'Shounen Ai',
'Slice of Life',
'Space',
'Sports',
'Super Power',
'Supernatural',
'Thriller',
'Vampire'
],
genres_tv: [
'All',
'Action',
'Adventure',
'Animation',
'Children',
'Comedy',
'Crime',
'Documentary',
'Drama',
'Family',
'Fantasy',
'Game Show',
'Home and Garden',
'Horror',
'Mini Series',
'Mystery',
'News',
'Reality',
'Romance',
'Science Fiction',
'Soap',
'Special Interest',
'Sport',
'Suspense',
'Talk Show',
'Thriller',
'Western'
],
cache: {
name: 'cachedb',
version: '1.7',
tables: ['subtitle'],
desc: 'Cache database',
size: 10 * 1024 * 1024
},
cachev2: {
name: 'cache',
version: 5,
tables: ['metadata']
},
providers: {
movie: ['Yts'],
tvshow: ['Eztv'],
anime: ['Haruhichan'],
subtitle: 'YSubs',
metadata: 'Trakttv',
tvshowsubtitle: 'OpenSubtitles',
torrentCache: 'TorrentCache'
},
getProvider: function(type) {
var provider = App.Config.providers[type];
if (provider instanceof Array) {
return _.map(provider, function(t) {
return App.Providers.get(t);
});
}
return App.Providers.get(provider);
}
};
App.Config = Config;
})(window.App);
|
import React from "react";
import PropTypes from "prop-types";
/**
* Represents the textarea HTML element.
*
* @param {Object} props The properties to use.
* @returns {JSX} A representation of the textarea HTML element based on the passed props.
* @constructor
*/
class Textarea extends React.Component {
/**
* Renders the textarea.
*
* @returns {ReactElement} The rendered element.
*/
render() {
return (
<textarea
ref={ this.setReference.bind( this ) }
name={ this.props.name }
value={ this.props.value }
onChange={ this.props.onChange }
{ ...this.props.optionalAttributes }
/>
);
}
/**
* Sets a reference to the current component.
*
* @param {Object} ref The reference to set.
* @returns {void}
*/
setReference( ref ) {
this.ref = ref;
}
/**
* Determines whether or not the component updated and sets its focus accordingly.
*
* @returns {void}
*/
componentDidUpdate() {
if ( this.props.hasFocus ) {
this.ref.focus();
}
}
}
/**
* Adds validation for the properties.
*
* @type {{name: string, value: string, onChange:function, optionalAttributes: object}}
*/
Textarea.propTypes = {
name: PropTypes.string.isRequired,
value: PropTypes.string,
onChange: PropTypes.func,
optionalAttributes: PropTypes.object,
hasFocus: PropTypes.bool,
};
/**
* Defines the default values for the properties.
*
* @type {{name: string, value: string, optionalAttributes: object}}
*/
Textarea.defaultProps = {
name: "textarea",
value: "",
hasFocus: false,
};
export default Textarea;
|
// Placeholder file for cordova.js
|
define(
"jbundle/back", ["dojo/hash", "dojo/topic"],
function(hash, topic) {
return {
// module:
// jbundle/back
// summary:
// The code skeleton was copied from the deprecated module dojo/back. Thanks!
forwardStack: [],
historyStack: [],
initialized: false,
CRAWLABLE: false, // Change this to true and URLs will be #! crawlable
init: function() {
if (this.initialized == true)
return;
topic.subscribe("/dojo/hashchange", this.hashChange);
this.initialized = true;
},
setHash: function(h){
// Change the browser URL hash
if (dojoConfig.isDebug == true)
console.log("setHash:" + h);
if(!h){ h = ""; }
if (this.CRAWLABLE)
if (h.charAt(0) !== "!")
h = "!" + h; // Makes it crawlable
window.location.hash = encodeURIComponent(h);
},
setInitialState: function(/*Object*/args){
//summary:
// Sets the state object and back callback for the very first page
// that is loaded.
//description:
// It is recommended that you call this method as part of an event
// listener that is registered via dojo.addOnLoad().
//args: Object
// See the addToHistory() function for the list of valid args properties.
if (dojoConfig.isDebug == true)
console.log("setInitialState:" + args);
initialHref = (typeof(window) !== "undefined") ? window.location.href : "";
initialHash = (typeof(window) !== "undefined") ? hash() : "";
initialState = this.createState(initialHref, args, initialHash);
this.forwardStack = [];
this.historyStack = [];
this.historyStack.push(initialState);
},
createState: function(url, args, hash){
//summary: private method. Do not call this directly.
if (!this.initialized)
this.init();
return {"url": url, "args": args, "urlHash": hash}; //Object
},
addToHistory: function(/*dojo.__backArgs*/ args){
// summary:
// adds a state object (args) to the history list.
// args: dojo.__backArgs
// The state object that will be added to the history list.
// description:
// To support getting back button notifications, the object
// argument should implement a function called "back".
//If addToHistory is called, then that means we prune the
//forward stack -- the user went back, then wanted to
//start a new forward path.
if (dojoConfig.isDebug == true)
console.log("addToHistory:" + args);
this.forwardStack = [];
var hashValue = null;
var url = null;
if(args["changeUrl"]){
hashValue = ""+ ((args["changeUrl"]!==true) ? args["changeUrl"] : (new Date()).getTime());
//If the current hash matches the new one, just replace the history object with
//this new one. It doesn't make sense to track different state objects for the same
//logical URL. This matches the browser behavior of only putting in one history
//item no matter how many times you click on the same #hash link, at least in Firefox
//and Safari, and there is no reliable way in those browsers to know if a #hash link
//has been clicked on multiple times. So making this the standard behavior in all browsers
//so that dojo.back's behavior is the same in all browsers.
if(this.historyStack.length == 1 && this.historyStack[0].urlHash == hashValue){
this.historyStack[0] = this.createState(url, args, hashValue);
return;
} else if(this.historyStack.length > 0 && this.historyStack[this.historyStack.length - 1].urlHash == hashValue) {
this.historyStack[this.historyStack.length - 1] = this.createState(url, args, hashValue);
return;
}
}
this.historyStack.push(this.createState(url, args, hashValue));
setTimeout(function() {
require (["jbundle/back"],
function(back) {
back.setHash(hashValue);
});
}, 1);
},
handleBackButton: function(){
//summary: private method. Do not call this directly.
if (dojoConfig.isDebug == true)
console.log("handleBackButton");
//The "current" page is always at the top of the history stack.
if (this.historyStack.length > 0)
{
var current = this.historyStack.pop();
if(!current){ return; }
}
var last = this.historyStack[this.historyStack.length-1];
if (last)
if (last.args)
if (last.args.back) {
last.args.back();
}
this.forwardStack.push(current);
},
handleForwardButton: function(){
//summary: private method. Do not call this directly.
if (dojoConfig.isDebug == true)
console.log("handleForwardButton");
var last = this.forwardStack.pop();
if(!last){ return; }
last.args.forward();
this.historyStack.push(last);
},
hashChange: function(hashValue)
{
// Respond to a browser hash change event.
require (["jbundle/back"],
function(back) {
if (this.CRAWLABLE)
if (hashValue.charAt(0) === "!")
hashValue = hashValue.substring(1); // Make it crawlable
back.checkLocation(hashValue);
});
},
checkLocation: function(hashValue) {
// Respond to a browser hash change event.
if (dojoConfig.isDebug == true)
console.log("checkLocation:" + hashValue);
var hsl = this.historyStack.length;
if(this.historyStack.length > 0 && encodeURIComponent(this.historyStack[this.historyStack.length - 1].urlHash) == hashValue) {
if (dojoConfig.isDebug == true)
console.log("checkLocation:ignore");
return; // Ignore - already the starting hash value
}
if(this.historyStack.length > 1 && encodeURIComponent(this.historyStack[this.historyStack.length - 2].urlHash) == hashValue) {
if (dojoConfig.isDebug == true)
console.log("checkLocation:back");
this.handleBackButton();
return;
}
// first check to see if we could have gone forward. We always halt on
// a no-hash item.
if(this.forwardStack.length > 0){
if(encodeURIComponent(this.forwardStack[this.forwardStack.length-1].urlHash) === hashValue){
this.handleForwardButton();
return;
}
}
// ok, that didn't work, try someplace back in the history stack
if((hsl >= 2)&&(this.historyStack[hsl-2])){
if(encodeURIComponent(this.historyStack[hsl-2].urlHash) === hashValue){
this.handleBackButton();
}
}
// If I'm getting a new hash value, I better push it on my history stack
// ??
}
}});
|
// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// License: GNU General Public License v3. See license.txt
frappe.provide("erpnext.stock");
frappe.ui.form.on("Stock Reconciliation", {
onload: function(frm) {
frm.add_fetch("item_code", "item_name", "item_name");
// end of life
frm.set_query("item_code", "items", function(doc, cdt, cdn) {
return {
query: "erpnext.controllers.queries.item_query",
filters:{
"is_stock_item": 1,
"has_serial_no": 0
}
}
});
if (frm.doc.company) {
erpnext.queries.setup_queries(frm, "Warehouse", function() {
return erpnext.queries.warehouse(frm.doc);
});
}
if (!frm.doc.expense_account) {
frm.trigger("set_expense_account");
}
},
refresh: function(frm) {
if(frm.doc.docstatus < 1) {
frm.add_custom_button(__("Items"), function() {
frm.events.get_items(frm);
});
}
if(frm.doc.company) {
frm.trigger("toggle_display_account_head");
}
},
get_items: function(frm) {
frappe.prompt({label:"Warehouse", fieldtype:"Link", options:"Warehouse", reqd: 1,
"get_query": function() {
return {
"filters": {
"company": frm.doc.company,
}
}
}},
function(data) {
frappe.call({
method:"erpnext.stock.doctype.stock_reconciliation.stock_reconciliation.get_items",
args: {
warehouse: data.warehouse,
posting_date: frm.doc.posting_date,
posting_time: frm.doc.posting_time,
company:frm.doc.company
},
callback: function(r) {
var items = [];
frm.clear_table("items");
for(var i=0; i< r.message.length; i++) {
var d = frm.add_child("items");
$.extend(d, r.message[i]);
if(!d.qty) d.qty = null;
if(!d.valuation_rate) d.valuation_rate = null;
}
frm.refresh_field("items");
}
});
}
, __("Get Items"), __("Update"));
},
set_valuation_rate_and_qty: function(frm, cdt, cdn) {
var d = frappe.model.get_doc(cdt, cdn);
if(d.item_code && d.warehouse) {
frappe.call({
method: "erpnext.stock.doctype.stock_reconciliation.stock_reconciliation.get_stock_balance_for",
args: {
item_code: d.item_code,
warehouse: d.warehouse,
posting_date: frm.doc.posting_date,
posting_time: frm.doc.posting_time
},
callback: function(r) {
frappe.model.set_value(cdt, cdn, "qty", r.message.qty);
frappe.model.set_value(cdt, cdn, "valuation_rate", r.message.rate);
frappe.model.set_value(cdt, cdn, "current_qty", r.message.qty);
frappe.model.set_value(cdt, cdn, "current_valuation_rate", r.message.rate);
frappe.model.set_value(cdt, cdn, "current_amount", r.message.rate * r.message.qty);
frappe.model.set_value(cdt, cdn, "amount", r.message.rate * r.message.qty);
}
});
}
},
set_item_code: function(doc, cdt, cdn) {
var d = frappe.model.get_doc(cdt, cdn);
if (d.barcode) {
frappe.call({
method: "erpnext.stock.get_item_details.get_item_code",
args: {"barcode": d.barcode },
callback: function(r) {
if (!r.exe){
frappe.model.set_value(cdt, cdn, "item_code", r.message);
}
}
});
}
},
set_amount_quantity: function(doc, cdt, cdn) {
var d = frappe.model.get_doc(cdt, cdn);
if (d.qty & d.valuation_rate) {
frappe.model.set_value(cdt, cdn, "amount", flt(d.qty) * flt(d.valuation_rate));
frappe.model.set_value(cdt, cdn, "quantity_difference", flt(d.qty) - flt(d.current_qty));
frappe.model.set_value(cdt, cdn, "amount_difference", flt(d.amount) - flt(d.current_amount));
}
},
company: function(frm) {
frm.trigger("toggle_display_account_head");
},
toggle_display_account_head: function(frm) {
frm.toggle_display(['expense_account', 'cost_center'],
erpnext.is_perpetual_inventory_enabled(frm.doc.company));
},
purpose: function(frm) {
frm.trigger("set_expense_account");
},
set_expense_account: function(frm) {
if (frm.doc.company && erpnext.is_perpetual_inventory_enabled(frm.doc.company)) {
return frm.call({
method: "erpnext.stock.doctype.stock_reconciliation.stock_reconciliation.get_difference_account",
args: {
"purpose": frm.doc.purpose,
"company": frm.doc.company
},
callback: function(r) {
if (!r.exc) {
frm.set_value("expense_account", r.message);
}
}
});
}
}
});
frappe.ui.form.on("Stock Reconciliation Item", {
barcode: function(frm, cdt, cdn) {
frm.events.set_item_code(frm, cdt, cdn);
},
warehouse: function(frm, cdt, cdn) {
frm.events.set_valuation_rate_and_qty(frm, cdt, cdn);
},
item_code: function(frm, cdt, cdn) {
frm.events.set_valuation_rate_and_qty(frm, cdt, cdn);
},
qty: function(frm, cdt, cdn) {
frm.events.set_amount_quantity(frm, cdt, cdn);
},
valuation_rate: function(frm, cdt, cdn) {
frm.events.set_amount_quantity(frm, cdt, cdn);
}
});
erpnext.stock.StockReconciliation = erpnext.stock.StockController.extend({
setup: function() {
var me = this;
this.setup_posting_date_time_check();
if (me.frm.doc.company && erpnext.is_perpetual_inventory_enabled(me.frm.doc.company)) {
this.frm.add_fetch("company", "cost_center", "cost_center");
}
this.frm.fields_dict["expense_account"].get_query = function() {
if(erpnext.is_perpetual_inventory_enabled(me.frm.doc.company)) {
return {
"filters": {
'company': me.frm.doc.company,
"is_group": 0
}
}
}
}
this.frm.fields_dict["cost_center"].get_query = function() {
if(erpnext.is_perpetual_inventory_enabled(me.frm.doc.company)) {
return {
"filters": {
'company': me.frm.doc.company,
"is_group": 0
}
}
}
}
},
refresh: function() {
if(this.frm.doc.docstatus==1) {
this.show_stock_ledger();
if (erpnext.is_perpetual_inventory_enabled(this.frm.doc.company)) {
this.show_general_ledger();
}
}
},
});
cur_frm.cscript = new erpnext.stock.StockReconciliation({frm: cur_frm});
|
/*
Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'forms', 'bs', {
button: {
title: 'Button Properties',
text: 'Text (Value)',
type: 'Type',
typeBtn: 'Button',
typeSbm: 'Submit',
typeRst: 'Reset'
},
checkboxAndRadio: {
checkboxTitle: 'Checkbox Properties',
radioTitle: 'Radio Button Properties',
value: 'Value',
selected: 'Selected'
},
form: {
title: 'Form Properties',
menu: 'Form Properties',
action: 'Action',
method: 'Method',
encoding: 'Encoding'
},
hidden: {
title: 'Hidden Field Properties',
name: 'Name',
value: 'Value'
},
select: {
title: 'Selection Field Properties',
selectInfo: 'Select Info',
opAvail: 'Available Options',
value: 'Value',
size: 'Size',
lines: 'lines',
chkMulti: 'Allow multiple selections',
opText: 'Text',
opValue: 'Value',
btnAdd: 'Add',
btnModify: 'Modify',
btnUp: 'Up',
btnDown: 'Down',
btnSetValue: 'Set as selected value',
btnDelete: 'Delete'
},
textarea: {
title: 'Textarea Properties',
cols: 'Columns',
rows: 'Rows'
},
textfield: {
title: 'Text Field Properties',
name: 'Name',
value: 'Value',
charWidth: 'Character Width',
maxChars: 'Maximum Characters',
type: 'Type',
typeText: 'Text',
typePass: 'Password',
typeEmail: 'Email', // MISSING
typeSearch: 'Search', // MISSING
typeTel: 'Telephone Number', // MISSING
typeUrl: 'URL'
}
} );
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const Controller_1 = require("./lib/Controller");
exports.Controller = Controller_1.default;
const Route_1 = require("./lib/Route");
exports.Route = Route_1.default;
const Router_1 = require("./lib/Router");
exports.Router = Router_1.default;
const Decorators = require("./lib/Decorators");
exports.Decorators = Decorators;
function default_1(fileName, baseDir) {
let r = new Router_1.default(fileName, baseDir);
return (ctx, next) => {
return r.handler(ctx, next);
};
}
exports.default = default_1;
|
var adminStore = Ext.create('Ext.data.TreeStore', {
root: {
expanded: true,
children: [
{ text: "Variables", leaf: true },
{ text: "Machines", leaf: true },
{ text: "Users", leaf: true },
{ text: "Projects", leaf: true }
]
}
});
Ext.define('Redwood.view.Administration', {
extend: 'Ext.panel.Panel',
alias: 'widget.administration',
title:"Administration",
layout: 'fit',
items:[
{
region: 'west',
split:true,
xtype: 'treepanel',
collapseDirection: "left",
collapsible: true,
multiSelect: false,
rootVisible: false,
store: adminStore,
width: 150,
focused: true
}
//Ext.create('Redwood.view.Variables',{region:"center"})
]
});
|
import Ember from 'ember';
import layout from '../templates/components/tooltip-on-parent';
const { computed, on, warn } = Ember;
export default Ember.Component.extend({
attributeBindings: ['style'],
layout,
style: computed(function() {
return Ember.String.htmlSafe('display:none;');
}),
registerOnParent: on('didInsertElement', function() {
const parentView = this.get('parentView');
if (parentView.renderTooltip) {
parentView.renderTooltip(this);
} else {
warn('No renderTooltip method found on the parent view of the {{tooltip-on-parent}} component');
}
this.remove();
}),
});
|
import React from 'react'
import {TouchableOpacity, Image} from 'react-native'
import {ResponsiveStyleSheet} from 'react-native-responsive-stylesheet'
import {resource} from '../utils/image'
export const ControlButton = ({onPress, type, backgroundColor}) => {
const s = makeStyles()
return (
<TouchableOpacity
onPress={onPress}
style={[s.button, {backgroundColor}]}
activeOpacity={0.8}>
<Image source={resource(`icons/${type}.png`)} style={s.image} />
</TouchableOpacity>
)
}
const makeStyles = ResponsiveStyleSheet.create(({controlButtonSize}) => {
const padding = 20
return {
button: {
padding: padding,
width: controlButtonSize,
height: controlButtonSize,
borderRadius: controlButtonSize / 2,
},
image: {
width: controlButtonSize - 2 * padding,
height: controlButtonSize - 2 * padding,
},
}
})
|
import React from 'react'
import { Map } from 'immutable'
import Path from 'path'
const ResizeDialogModal = ({ resizePath, resizeSize, initialSize, actions }) => {
const handleSettingInput = (e) => actions.updateModal('resizeSize', e.target.value)
const hideResizeDialog = (newSize) => actions.hideResizeDialog(Map({ path: resizePath, size: newSize }))
const closeResizeDialog = () => hideResizeDialog(0)
const handleSubmit = () => {
if (resizeSize >= 35 && resizeSize !== initialSize.toString()) {
hideResizeDialog(resizeSize)
}
}
const handleSettingKeyDown = (e) => {
if (e.keyCode === 13) {
handleSubmit()
e.preventDefault()
}
}
return (
<div className={'hosting-options-modal modal' + (resizePath ? '': ' hidden')}>
<form className="hosting-options modal-message" onSubmit="">
<div className="close-button" onClick={closeResizeDialog}>
X
</div>
<h3>Resize "{Path.basename(resizePath)}"</h3>
<p>
<label>Size in GB (Min is 35 GB)</label>
<input type="number" onChange={handleSettingInput} onKeyDown={handleSettingKeyDown} value={resizeSize} min="35" />
</p>
<span className={'error' + ( resizeSize < 35 ? '' : ' hidden' )}>Storage folder must be at least 35 GB.</span>
<p>
<input className={'button accept' + ( resizeSize !== initialSize.toString() && resizeSize >= 35 ? '' : ' disabled' )} type="button" value="Save" onClick={handleSubmit} />
</p>
</form>
</div>
)
}
export default ResizeDialogModal
|
/*
Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'print', 'ja', {
toolbar: '印刷'
} );
|
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Contain the events the course component can trigger.
*
* @module core_course/events
* @copyright 2018 Simey Lameze <simey@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
define([], function() {
return {
favourited: 'core_course:favourited',
unfavorited: 'core_course:unfavorited',
};
});
|
import React, {Component, PropTypes} from 'react'
import {Card, CardTitle, CardText, CardActions} from 'react-mdl'
import {autobind} from 'core-decorators'
import {t} from 'utils/i18n'
import _styles from './index.scss'
export default class CustomImage extends Component {
static propTypes = {
url: PropTypes.string.isRequired,
image: PropTypes.oneOfType([
PropTypes.instanceOf(Node),
PropTypes.instanceOf(Error)
]),
onLoad: PropTypes.func,
onError: PropTypes.func
}
@autobind
handleLoad (evt) {
const {onLoad} = this.props
onLoad && onLoad(evt.target)
}
@autobind
handleError (evt) {
const {onError} = this.props
onError && onError(evt.target)
}
render () {
const {url, image} = this.props
const state = (image ? 'finished' : 'loading')
return (
<Card className='app-image hidden' shadow={2}
style={{backgroundImage: 'url(' + url + ')'}}
>
<CardTitle expand>
<span className='visuallyhidden'>
{t('msg_image_title')}
</span>
</CardTitle>
<CardText>
<img src={url}
onLoad={this.handleLoad}
onError={this.handleError}
/>
</CardText>
<CardActions>
<span className='app-image__message'>
{t(`msg_image_state_${state}`)}
</span>
</CardActions>
</Card>
)
}
}
|
var status = -1;
function action(mode, type, selection) {
var em = cm.getEventManager("Juliet");
if (em == null) {
cm.dispose();
return;
}
if (!cm.canHold(4001131,1)) {
cm.sendOk("I will need 1 ETC space.");
cm.dispose();
return;
}
if (cm.getPlayer().getMapId() == 926110000) { //just first stage
if (java.lang.Math.random() < 0.1) {
if (em.getProperty("stage1").equals("0")) {
em.setProperty("stage1", "1");
cm.getMap().setReactorState();
}
} else if (java.lang.Math.random() < 0.05) {
if (em.getProperty("stage").equals("0")) {
cm.gainItem(4001131,1);
}
}
}
cm.dispose();
}
|
/**
* Represents a filter that can be applied to a {@link Ext.util.MixedCollection MixedCollection}. Can either simply
* filter on a property/value pair or pass in a filter function with custom logic. Filters are always used in the
* context of MixedCollections, though {@link Ext.data.Store Store}s frequently create them when filtering and searching
* on their records. Example usage:
*
* //set up a fictional MixedCollection containing a few people to filter on
* var allNames = new Ext.util.MixedCollection();
* allNames.addAll([
* {id: 1, name: 'Ed', age: 25},
* {id: 2, name: 'Jamie', age: 37},
* {id: 3, name: 'Abe', age: 32},
* {id: 4, name: 'Aaron', age: 26},
* {id: 5, name: 'David', age: 32}
* ]);
*
* var ageFilter = new Ext.util.Filter({
* property: 'age',
* value : 32
* });
*
* var longNameFilter = new Ext.util.Filter({
* filterFn: function(item) {
* return item.name.length > 4;
* }
* });
*
* //a new MixedCollection with the 3 names longer than 4 characters
* var longNames = allNames.filter(longNameFilter);
*
* //a new MixedCollection with the 2 people of age 24:
* var youngFolk = allNames.filter(ageFilter);
*
*/
Ext.define('Ext.util.Filter', {
/* Begin Definitions */
/* End Definitions */
/**
* @cfg {String} property
* The property to filter on. Required unless a {@link #filterFn} is passed
*/
/**
* @cfg {Function} filterFn
* A custom filter function which is passed each item in the {@link Ext.util.MixedCollection} in turn. Should return
* true to accept each item or false to reject it
*/
/**
* @cfg {Boolean} anyMatch
* True to allow any match - no regex start/end line anchors will be added.
*/
anyMatch: false,
/**
* @cfg {Boolean} exactMatch
* True to force exact match (^ and $ characters added to the regex). Ignored if anyMatch is true.
*/
exactMatch: false,
/**
* @cfg {Boolean} caseSensitive
* True to make the regex case sensitive (adds 'i' switch to regex).
*/
caseSensitive: false,
/**
* @cfg {String} root
* Optional root property. This is mostly useful when filtering a Store, in which case we set the root to 'data' to
* make the filter pull the {@link #property} out of the data object of each item
*/
/**
* Creates new Filter.
* @param {Object} [config] Config object
*/
constructor: function(config) {
var me = this;
Ext.apply(me, config);
//we're aliasing filter to filterFn mostly for API cleanliness reasons, despite the fact it dirties the code here.
//Ext.util.Sorter takes a sorterFn property but allows .sort to be called - we do the same here
me.filter = me.filter || me.filterFn;
if (me.filter === undefined) {
if (me.property === undefined || me.value === undefined) {
// Commented this out temporarily because it stops us using string ids in models. TODO: Remove this once
// Model has been updated to allow string ids
// Ext.Error.raise("A Filter requires either a property or a filterFn to be set");
} else {
me.filter = me.createFilterFn();
}
me.filterFn = me.filter;
}
},
/**
* @private
* Creates a filter function for the configured property/value/anyMatch/caseSensitive options for this Filter
*/
createFilterFn: function() {
var me = this,
matcher = me.createValueMatcher(),
property = me.property;
return function(item) {
var value = me.getRoot.call(me, item)[property];
return matcher === null ? value === null : matcher.test(value);
};
},
/**
* @private
* Returns the root property of the given item, based on the configured {@link #root} property
* @param {Object} item The item
* @return {Object} The root property of the object
*/
getRoot: function(item) {
var root = this.root;
return root === undefined ? item : item[root];
},
/**
* @private
* Returns a regular expression based on the given value and matching options
*/
createValueMatcher : function() {
var me = this,
value = me.value,
anyMatch = me.anyMatch,
exactMatch = me.exactMatch,
caseSensitive = me.caseSensitive,
escapeRe = Ext.String.escapeRegex;
if (value === null) {
return value;
}
if (!value.exec) { // not a regex
value = String(value);
if (anyMatch === true) {
value = escapeRe(value);
} else {
value = '^' + escapeRe(value);
if (exactMatch === true) {
value += '$';
}
}
value = new RegExp(value, caseSensitive ? '' : 'i');
}
return value;
}
});
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at <http://mozilla.org/MPL/2.0/>. */
import { clearDocuments } from "../utils/editor";
import { getSources } from "../reducers/sources";
import { waitForMs } from "../utils/utils";
import { newSources } from "./sources";
import {
clearASTs,
clearSymbols,
clearScopes,
clearSources
} from "../workers/parser";
import { clearWasmStates } from "../utils/wasm";
/**
* Redux actions for the navigation state
* @module actions/navigation
*/
/**
* @memberof actions/navigation
* @static
*/
export function willNavigate(_, event) {
return async function({ dispatch, getState, client, sourceMaps }: ThunkArgs) {
await sourceMaps.clearSourceMaps();
clearWasmStates();
clearDocuments();
clearSymbols();
clearASTs();
clearScopes();
clearSources();
dispatch(navigate(event.url));
};
}
export function navigate(url) {
return {
type: "NAVIGATE",
url
};
}
export function connect(url) {
return {
type: "CONNECT",
url
};
}
/**
* @memberof actions/navigation
* @static
*/
export function navigated() {
return async function({ dispatch, getState, client }: ThunkArgs) {
await waitForMs(100);
if (getSources(getState()).size == 0) {
const sources = await client.fetchSources();
dispatch(newSources(sources));
}
};
}
|
var fs = require("fs");
var moment = require("moment");
/*
* Serve JSON to our AngularJS client
*/
// For a real app, you'd make database requests here.
// For this example, "data" acts like an in-memory "database"
// GET
exports.posts = function (req, res) {
fs.readFile("data/data.txt", 'utf-8', function (error, data) {
if (error) throw error;
data = JSON.parse(data);
var posts = [];
var sum = data.posts.length;
console.log("评论数量:"+data.posts.length);
for (var i=sum-1; i>=0; i--) {
var post = data.posts[i];
var mytext, name, mytitle;
mytext = post.text;
if (mytext == undefined)
mytext = "什么都没留下...";
else
if (mytext.length > 50)
mytext = post.text.substr(0, 50) + '...';
if (post.title == undefined)
mytitle = "无题";
else
mytitle = post.title;
posts.push({
id: i,
title: mytitle,
text: mytext,
author: post.author
});
}
res.json({
posts: posts
});
});
};
exports.post = function (req, res) {
var id = req.params.id;
fs.readFile("data/data.txt", 'utf-8', function (error, data) {
if (error) throw error;
data = JSON.parse(data);
if (id >= 0 && id < data.posts.length) {
res.json({
post: data.posts[id]
});
} else {
res.json(false);
}
});
};
// POST
exports.addPost = function (req, res) {
fs.readFile("data/data.txt", 'utf-8', function (error, data) {
if (error) throw error;
data = JSON.parse(data);
var name, title, text;
if (req.session.user == undefined) {
name = "匿名网友";
if (req.body.title == undefined) {
title = "无题";
req.body.title = title;
}
if (req.body.text == undefined) {
text = "什么都没留下...";
req.body.text = text ;
}
} else
name = req.session.user.username;
var time = moment().format("YYYY-MM-DD HH:mm:ss");
req.body.author = name+" \t "+time;
data.posts.push(req.body);
fs.writeFile("data/data.txt", JSON.stringify(data), function (error) {
if (error) throw error;
res.json(req.body);
})
});
};
// PUT
exports.editPost = function (req, res) {
var id = req.params.id;
fs.readFile("data/data.txt", 'utf-8', function (error, data) {
if (error) throw error;
data = JSON.parse(data);
if (id >= 0 && id < data.posts.length) {
data.posts[id] = req.body;
fs.writeFile("data/data.txt", JSON.stringify(data), function (error) {
if (error) throw error;
res.json(true);
})
} else {
fs.writeFile("data/data.txt", JSON.stringify(data), function (error) {
if (error) throw error;
res.json(false);
})
}
});
};
// DELETE
exports.deletePost = function (req, res) {
var id = req.params.id;
fs.readFile("data/data.txt", 'utf-8', function (error, data) {
if (error) throw error;
data = JSON.parse(data);
if (id >= 0 && id < data.posts.length) {
data.posts.splice(id, 1);
fs.writeFile("data/data.txt", JSON.stringify(data), function (error) {
if (error) throw error;
res.json(true);
})
} else {
fs.writeFile("data/data.txt", JSON.stringify(data), function (error) {
if (error) throw error;
res.json(false);
})
}
});
};
|
/* Copyright (C) 2017 Canonical Ltd. */
'use strict';
const classNames = require('classnames');
const PropTypes = require('prop-types');
const React = require('react');
class ExpandingRow extends React.Component {
constructor() {
super();
this.state = {
expanded: false,
styles: {
height: '0px',
opacity: 0
}
};
}
/**
Called once the component has initially mounted.
@method componentDidMount
*/
componentDidMount() {
// If the component should initially be shown as expanded then animate it
// open.
if (this.props.expanded) {
this._toggle();
}
// Observe the DOM for any changes to the content of the expanded row. If
// the content changes then animate to the new size required.
this.observer = new MutationObserver(mutations => {
this._resize();
});
this.observer.observe(this.refs.inner, {childList: true, subtree: true});
}
componentWillReceiveProps(nextProps, nextState) {
if (this.props.expanded !== nextProps.expanded) {
this._toggle();
}
}
componentWillUnmount() {
// Stop observing the child DOM.
this.observer.disconnect();
}
/**
Generate the base class names for the component.
@method _generateClasses
@returns {Object} The collection of class names.
*/
_generateClasses() {
var classes = this.props.classes || {};
classes['expanding-row--expanded'] = this.state.expanded;
classes['expanding-row--clickable'] = this.props.clickable;
return classNames(
'expanding-row',
'twelve-col',
classes);
}
/**
Toggle between the expanded and closed states.
@method _toggle
*/
_toggle() {
this.setState({expanded: !this.state.expanded}, () => {
this._resize();
});
}
/**
Resize the
@method _resize
*/
_resize() {
const expanded = this.state.expanded;
this.setState({styles: {
height: expanded ? this.refs.inner.offsetHeight + 'px' : '0px',
opacity: expanded ? 1 : 0
}});
}
render() {
return (
<li className={this._generateClasses()}
onClick={this.props.clickable ? this._toggle.bind(this) : undefined}
style={this.props.style}>
<div className="expanding-row__initial twelve-col no-margin-bottom">
{this.props.children[0]}
</div>
<div className="expanding-row__expanded twelve-col"
style={this.state.styles}>
<div className="twelve-col no-margin-bottom"
ref="inner">
{this.props.children[1]}
</div>
</div>
</li>);
}
};
ExpandingRow.propTypes = {
children: PropTypes.oneOfType([
PropTypes.object,
PropTypes.array
]),
classes: PropTypes.object,
clickable: PropTypes.bool,
expanded: PropTypes.bool,
style: PropTypes.object
};
ExpandingRow.defaultProps = {
clickable: true
};
module.exports = ExpandingRow;
|
angular.module('sislegisapp').factory('ReuniaoProposicaoResource', function($resource) {
var resource = $resource('http://localhost:8080/sislegis/rest/reuniaoProposicao/:ReuniaoId/:ProposicaoId/', {
ReuniaoId : '@idReuniao',
ProposicaoId : '@idProposicao'
}, {
'queryAll' : {
method : 'GET',
isArray : true
},
'query' : {
method : 'GET',
isArray : false
},
'update' : {
method : 'PUT'
}
});
return resource;
});
|
function pybossaNotify(msg, showNotification, type){
$("#pybossa-notification").remove();
var div = $("<div/>");
div.attr("id", "pybossa-notification");
var icon = $("<li/>");
var close = $("<li/>");
close.addClass("fa fa-2x fa-close pull-right");
close.on('click', function(){
$("#pybossa-notification").addClass("hide-notification");
});
if (type === undefined) {
type = 'info';
}
if ((type === 'danger') || (type === 'error') || (type === 'warning') || (type == 'message')) {
icon.addClass("fa fa-2x fa-exclamation-triangle pull-left hidden-xs");
}
if (type === 'message') {
type = 'warning';
}
if (type === 'info') {
icon.addClass("fa fa-2x fa-bullhorn pull-left hidden-xs");
}
if (type === 'success') {
icon.addClass("fa fa-2x fa-check pull-left hidden-xs");
}
if (type === 'loading') {
icon.addClass("fa fa-2x fa-circle-o-notch fa-spin pull-left hidden-xs");
type = 'info';
}
var text = $("<span/>");
text.html(msg);
if (type === 'error') {
type = 'danger';
}
div.addClass("alert-" + type);
div.prepend(icon);
div.append(text);
div.append(close);
if (showNotification === true) {
div.addClass("show-notification");
$("body").prepend(div);
}
else {
$("#pybossa-notification").addClass("hide-notification");
}
}
|
// Modified from Original Code by Blazyb and his Innervate module.
import React from 'react';
import SPELLS from 'common/SPELLS';
import SpellLink from 'common/SpellLink';
import TalentStatisticBox from 'interface/others/TalentStatisticBox';
import AbilityTracker from 'parser/shared/modules/AbilityTracker';
import Analyzer from 'parser/core/Analyzer';
import { STATISTIC_ORDER } from 'interface/others/StatisticBox';
import Vivify from '../spells/Vivify';
import ManaTea from './ManaTea';
class RenewingMistDuringManaTea extends Analyzer {
static dependencies = {
abilityTracker: AbilityTracker,
vivify: Vivify,
manaTea: ManaTea,
};
constructor(...args) {
super(...args);
this.active = this.selectedCombatant.hasTalent(SPELLS.MANA_TEA_TALENT.id);
}
get avgRemDuringMT() {
return this.vivify.remDuringManaTea / this.manaTea.vivCasts || 0;
}
get suggestionThresholds() {
return {
actual: this.avgRemDuringMT,
isLessThan: {
minor: 2,
average: 1.5,
major: 1,
},
style: 'number',
};
}
suggestions(when) {
when(this.suggestionThresholds).addSuggestion((suggest, actual, recommended) => {
return suggest(
<>
During <SpellLink id={SPELLS.MANA_TEA_TALENT.id} /> you should have a minimum of two <SpellLink id={SPELLS.RENEWING_MIST.id} /> out to maximize your healing during the buff.
</>
)
.icon(SPELLS.MANA_TEA_TALENT.icon)
.actual(`${this.avgRemDuringMT.toFixed(2)} average Renewing Mists during Mana Tea`)
.recommended(`${recommended} average Renewing Mists recommended`);
});
}
statistic() {
return (
<TalentStatisticBox
talent={SPELLS.MANA_TEA_TALENT.id}
position={STATISTIC_ORDER.CORE(30)}
value={`${this.avgRemDuringMT.toFixed(2)}`}
label="Average Renewing Mists"
tooltip={`This is the average number of Renewing Mists active during Mana Tea`}
/>
);
}
}
export default RenewingMistDuringManaTea;
|
/**
* @module timed
* @submodule timed-components
* @public
*/
import Component from "@ember/component";
/**
* Target component for the sy modal
*
* @class SyModalTargetComponent
* @extends Ember.Component
* @public
*/
export default Component.extend({
/**
* The id of the container. This is the wormhole target.
*
* @property {String} elementId
* @public
*/
elementId: "sy-modals"
});
|
/*
* Spreed WebRTC.
* Copyright (C) 2013-2014 struktur AG
*
* This file is part of Spreed WebRTC.
*
* 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/>.
*
*/
"use strict";
define(['text!partials/socialshare.html'], function(template) {
var urls = {
email: "mailto:?subject=_TEXT_%20_URL_",
facebook: "https://www.facebook.com/sharer.php?u=_URL_&t=_TEXT_",
twitter: "https://twitter.com/share?url=_URL_&text=_TEXT_&via=_SITE_",
google: "https://plus.google.com/share?url=_URL_",
xing: "https://www.xing.com/app/user?op=share;url=_URL_"
};
// socialShare
return ["$window", "translation", "rooms", "alertify", function($window, translation, rooms, alertify) {
var title = $window.encodeURIComponent($window.document.title);
var makeUrl = function(nw, target) {
var url = urls[nw];
if (url) {
url = url.replace(/_URL_/, $window.encodeURIComponent(target)).replace(/_TEXT_/, $window.encodeURIComponent(translation._("Meet with me here:"))).replace(/_SITE_/, title);
}
return url;
};
return {
scope: true,
restrict: "E",
template: template,
replace: true,
link: function($scope, $element, $attr) {
$scope.$on("room.updated", function(ev, room) {
$scope.roomlink = rooms.link(room);
});
$scope.$on("room.left", function(ev) {
$scope.roomlink = null;
});
$element.find("a").on("click", function(event) {
event.preventDefault();
var nw = event.currentTarget.getAttribute("data-nw");
var url = makeUrl(nw, $scope.roomlink);
if (url) {
if (nw === "email") {
// Hack our way to disable unload popup for mail links.
$scope.manualReloadApp(url);
} else {
$window.open(url, "social_" + nw, "menubar=no,toolbar=no,resizable=yes,width=600,height=600,scrollbars=yes");
}
} else {
if (nw === "link") {
//$window.alert("Room link: " + $scope.roomlink);
alertify.dialog.notify(translation._("Room link"), '<a href="'+$scope.roomlink+'" rel="external" target="_blank">'+$scope.roomlink+'</a>');
}
}
});
}
}
}];
});
|
module.exports = {
extends: ["@adfinis-sygroup/eslint-config/ember-app"],
rules: {}
};
|
import React from 'react';
import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer';
import Events from 'parser/core/Events';
import calculateEffectiveDamage from 'parser/core/calculateEffectiveDamage';
import SPELLS from 'common/SPELLS';
import { formatThousands, formatNumber, formatPercentage } from 'common/format';
import Tooltip from 'common/Tooltip';
import Statistic from 'interface/statistics/Statistic';
import BoringSpellValueText from 'interface/statistics/components/BoringSpellValueText';
import STATISTIC_ORDER from 'interface/others/STATISTIC_ORDER';
const DAMAGE_BONUS = 0.25;
const MAX_STACKS = 4;
const STACKS_PER_CAST = 2;
const debug = false;
class Flashover extends Analyzer {
_currentStacks = 0;
bonusStacks = 0;
wastedStacks = 0;
damage = 0;
constructor(...args) {
super(...args);
this.active = this.selectedCombatant.hasTalent(SPELLS.FLASHOVER_TALENT.id);
this.addEventListener(Events.damage.by(SELECTED_PLAYER).spell(SPELLS.CONFLAGRATE), this.onConflagrateDamage);
this.addEventListener(Events.cast.by(SELECTED_PLAYER).spell(SPELLS.CONFLAGRATE), this.onConflagrateCast);
this.addEventListener(Events.removebuffstack.to(SELECTED_PLAYER).spell(SPELLS.BACKDRAFT), this.onBackdraftRemoveBuffStack);
this.addEventListener(Events.removebuff.to(SELECTED_PLAYER).spell(SPELLS.BACKDRAFT), this.onBackdraftRemoveBuff);
}
onConflagrateDamage(event) {
this.damage += calculateEffectiveDamage(event, DAMAGE_BONUS);
}
onConflagrateCast() {
if (this._currentStacks <= MAX_STACKS - STACKS_PER_CAST) {
// We don't waste the base Backdraft stack, nor the bonus one
this._currentStacks += STACKS_PER_CAST;
this.bonusStacks += 1;
}
else {
// Conflagrate grants 2 stacks with Flashover, we can attribute 1 to the base Conflagrate and 1 to the Flashover, in this case the Flashover one would get wasted
debug && this.log('WASTE');
this._currentStacks = MAX_STACKS;
this.wastedStacks += 1;
}
debug && this.log(`Stacks after conflag cast: ${this._currentStacks}`);
}
onBackdraftRemoveBuffStack() {
this._currentStacks -= 1;
debug && this.log(`Remove buff stack, current: ${this._currentStacks}`);
}
onBackdraftRemoveBuff() {
this._currentStacks = 0;
debug && this.log(`Remove buff, current: ${this._currentStacks}`);
}
get dps() {
return this.damage / this.owner.fightDuration * 1000;
}
statistic() {
return (
<Statistic
position={STATISTIC_ORDER.OPTIONAL(1)}
size="flexible"
tooltip={`${formatThousands(this.damage)} bonus damage`}
>
<BoringSpellValueText spell={SPELLS.FLASHOVER_TALENT}>
{formatNumber(this.dps)} DPS <small>{formatPercentage(this.owner.getPercentageOfTotalDamageDone(this.damage))} % of total</small> <br />
{this.bonusStacks} <small>bonus Backdraft stacks</small> <br />
{this.wastedStacks}
<Tooltip content="Conflagrate on 3 or 4 stacks of Backdraft">
<small style={{ marginLeft: 7 }}>wasted Backdraft stacks <sup>*</sup></small>
</Tooltip>
</BoringSpellValueText>
</Statistic>
);
}
}
export default Flashover;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.