text
stringlengths 2
6.14k
|
|---|
module.exports = function(app) {
app.get("/api1", function(req, res) {
console.log('api1');
});
};
|
/* */
var core = require("../../modules/es6.date.to-string"),
$toString = Date.prototype.toString;
module.exports = function toString(it) {
return $toString.call(it);
};
|
/* global require */
var LoggingEnhancer = require('better-logging-base').LoggingEnhancer;
var sprintf = require('sprintf-js');
var moment = require('moment');
// depending on sprintf availability *and* version if available
sprintf = (sprintf && sprintf.sprintf) || (window.sprintf && window.sprintf.sprintf) || window.sprintf;
moment = moment || window.moment;
var angular = window.angular;
(function (logEnhancer, angular, sprintf, moment) {
'use strict';
angular.module('angular-logger', []).
provider('logEnhancer', function() {
var provider = this;
this.datetimePattern = 'LLL'; // default datetime stamp pattern, overwrite in config phase
this.datetimeLocale = window.navigator.userLanguage || window.navigator.language || 'en';
this.prefixPattern = '%s::[%s]> '; // default prefix pattern, overwrite in config phase
this.LEVEL = logEnhancer.LEVEL; // with these configure loglevels in config fase
this.logLevels = {'*': this.LEVEL.TRACE}; // everything by everyone should be visible by default
// instanceFactoryFactory moved here for modding purposes; now you can repurpose all the logging functions after they are enhanced
this.instanceFactoryFactory = function($log) {
return function(context) {
return {
trace : logEnhancer.enhanceLogging($log.$$orig$log.debug, $log.LEVEL.TRACE, context, $log, provider.datetimePattern, provider.datetimeLocale, provider.prefixPattern),
debug : logEnhancer.enhanceLogging($log.$$orig$log.debug, $log.LEVEL.DEBUG, context, $log, provider.datetimePattern, provider.datetimeLocale, provider.prefixPattern),
log : logEnhancer.enhanceLogging($log.$$orig$log.log, $log.LEVEL.INFO, context, $log, provider.datetimePattern, provider.datetimeLocale, provider.prefixPattern),
info : logEnhancer.enhanceLogging($log.$$orig$log.info, $log.LEVEL.INFO, context, $log, provider.datetimePattern, provider.datetimeLocale, provider.prefixPattern),
warn : logEnhancer.enhanceLogging($log.$$orig$log.warn, $log.LEVEL.WARN, context, $log, provider.datetimePattern, provider.datetimeLocale, provider.prefixPattern),
error : logEnhancer.enhanceLogging($log.$$orig$log.error, $log.LEVEL.ERROR, context, $log, provider.datetimePattern, provider.datetimeLocale, provider.prefixPattern)
};
};
};
this.$get = function() {
return {
// Actually modifies $log. Without calling this in the run phase, $log remains untouched
enhanceAngularLog : function($log) {
$log.LEVEL = provider.LEVEL; // assign to $log, so the user can change them after config phase
$log.logLevels = provider.logLevels; // assign to $log, so the user can change them after config phase
$log.getInstance = provider.instanceFactoryFactory($log);
}
};
};
}).
/*
Default config and example config as well.
Overrides default logging pattern and global logLevel
*/
config(['logEnhancerProvider', function (logEnhancerProvider) {
logEnhancerProvider.datetimePattern = 'LLL';
logEnhancerProvider.datetimeLocale = window.navigator.userLanguage || window.navigator.language || 'en';
logEnhancerProvider.prefixPattern = '%s::[%s]> ';
logEnhancerProvider.logLevels = {'*': logEnhancerProvider.LEVEL.TRACE};
/*
// example structure:
logEnhancerProvider.logLevels = {
'a.b.c': logEnhancerProvider.LEVEL.TRACE, // trace + debug + info + warn + error
'a.b.d': logEnhancerProvider.LEVEL.ERROR, // error
'a.b': logEnhancerProvider.LEVEL.DEBUG, // debug + info + warn + error
'a': logEnhancerProvider.LEVEL.WARN, // warn + error
'*': logEnhancerProvider.LEVEL.INFO // info + warn + error
};
*/
}]).
config(['$provide', 'logEnhancerProvider', function ($provide, p) {
$provide.decorator('$log', ['$delegate', function ($delegate) {
$delegate.logLevels = p.logLevels; // copy the initial loglevel config
return {
// keep original methods, otherwise the enhanced functions on .getInstance() will have a double (global context) prefix
$$orig$log: angular.extend({}, $delegate),
trace : logEnhancer.enhanceLogging($delegate.debug, p.LEVEL.TRACE, 'global', $delegate, p.datetimePattern, p.datetimeLocale, p.prefixPattern),
debug : logEnhancer.enhanceLogging($delegate.debug, p.LEVEL.DEBUG, 'global', $delegate, p.datetimePattern, p.datetimeLocale, p.prefixPattern),
log : logEnhancer.enhanceLogging($delegate.log, p.LEVEL.INFO, 'global', $delegate, p.datetimePattern, p.datetimeLocale, p.prefixPattern),
info : logEnhancer.enhanceLogging($delegate.info, p.LEVEL.INFO, 'global', $delegate, p.datetimePattern, p.datetimeLocale, p.prefixPattern),
warn : logEnhancer.enhanceLogging($delegate.warn, p.LEVEL.WARN, 'global', $delegate, p.datetimePattern, p.datetimeLocale, p.prefixPattern),
error : logEnhancer.enhanceLogging($delegate.error, p.LEVEL.ERROR, 'global', $delegate, p.datetimePattern, p.datetimeLocale, p.prefixPattern)
};
}]);
}]).
run(['$log', 'logEnhancer', function ($log, logEnhancer) {
logEnhancer.enhanceAngularLog($log);
if (!sprintf) {
$log.warn('sprintf.js not found: https://github.com/alexei/sprintf.js, using fixed layout pattern "%s::[%s]> "');
}
if (!moment) {
$log.warn('moment.js not found: http://momentjs.com, using non-localized simple Date format');
}
}]);
}(new LoggingEnhancer(sprintf, moment), angular, sprintf, moment));
|
'use strict';
const chai = require('chai');
const expect = chai.expect;
const Support = require('../support');
const current = Support.sequelize;
const sinon = require('sinon');
const DataTypes = require('../../../lib/data-types');
const { Logger } = require('../../../lib/utils/logger');
const sequelizeErrors = require('../../../lib/errors');
describe(Support.getTestDialectTeaser('Model'), () => {
describe('warnOnInvalidOptions', () => {
beforeEach(function() {
this.loggerSpy = sinon.spy(Logger.prototype, 'warn');
});
afterEach(function() {
this.loggerSpy.restore();
});
it('Warns the user if they use a model attribute without a where clause', function() {
const User = current.define('User', { firstName: 'string' });
User.warnOnInvalidOptions({ firstName: 12, order: [] }, ['firstName']);
const expectedError = 'Model attributes (firstName) passed into finder method options of model User, but the options.where object is empty. Did you forget to use options.where?';
expect(this.loggerSpy.calledWith(expectedError)).to.equal(true);
});
it('Does not warn the user if they use a model attribute without a where clause that shares its name with a query option', function() {
const User = current.define('User', { order: 'string' });
User.warnOnInvalidOptions({ order: [] }, ['order']);
expect(this.loggerSpy.called).to.equal(false);
});
it('Does not warn the user if they use valid query options', function() {
const User = current.define('User', { order: 'string' });
User.warnOnInvalidOptions({ where: { order: 1 }, order: [] });
expect(this.loggerSpy.called).to.equal(false);
});
});
describe('method findAll', () => {
const Model = current.define('model', {
name: DataTypes.STRING
}, { timestamps: false });
before(function() {
this.stub = sinon.stub(current.getQueryInterface(), 'select').callsFake(() => Model.build({}));
this.warnOnInvalidOptionsStub = sinon.stub(Model, 'warnOnInvalidOptions');
});
beforeEach(function() {
this.stub.resetHistory();
this.warnOnInvalidOptionsStub.resetHistory();
});
after(function() {
this.stub.restore();
this.warnOnInvalidOptionsStub.restore();
});
describe('handles input validation', () => {
it('calls warnOnInvalidOptions', function() {
Model.findAll();
expect(this.warnOnInvalidOptionsStub.calledOnce).to.equal(true);
});
it('Throws an error when the attributes option is formatted incorrectly', () => {
const errorFunction = Model.findAll.bind(Model, { attributes: 'name' });
expect(errorFunction).to.throw(sequelizeErrors.QueryError);
});
});
describe('attributes include / exclude', () => {
it('allows me to include additional attributes', function() {
return Model.findAll({
attributes: {
include: ['foobar']
}
}).then(() => {
expect(this.stub.getCall(0).args[2].attributes).to.deep.equal([
'id',
'name',
'foobar'
]);
});
});
it('allows me to exclude attributes', function() {
return Model.findAll({
attributes: {
exclude: ['name']
}
}).then(() => {
expect(this.stub.getCall(0).args[2].attributes).to.deep.equal([
'id'
]);
});
});
it('include takes precendence over exclude', function() {
return Model.findAll({
attributes: {
exclude: ['name'],
include: ['name']
}
}).then(() => {
expect(this.stub.getCall(0).args[2].attributes).to.deep.equal([
'id',
'name'
]);
});
});
it('works for models without PK #4607', function() {
const Model = current.define('model', {}, { timestamps: false });
const Foo = current.define('foo');
Model.hasOne(Foo);
Model.removeAttribute('id');
return Model.findAll({
attributes: {
include: ['name']
},
include: [Foo]
}).then(() => {
expect(this.stub.getCall(0).args[2].attributes).to.deep.equal([
'name'
]);
});
});
});
});
});
|
/**
* Game
*
* @param {Room} room
*/
function Game(room)
{
BaseGame.call(this, room);
this.render = document.getElementById('render');
this.canvas = new Canvas(0, 0, document.getElementById('game'));
this.background = new Canvas(0, 0, document.getElementById('background'));
this.onResize = this.onResize.bind(this);
window.addEventListener('error', this.stop);
window.addEventListener('resize', this.onResize);
this.onResize();
}
Game.prototype = Object.create(BaseGame.prototype);
Game.prototype.constructor = Game;
/**
* Background color
*
* @type {String}
*/
Game.prototype.backgroundColor = '#222222';
/**
* Get new frame
*/
Game.prototype.newFrame = function()
{
this.frame = window.requestAnimationFrame(this.loop);
};
/**
* Clear frame
*/
Game.prototype.clearFrame = function()
{
window.cancelAnimationFrame(this.frame);
this.frame = null;
};
/**
* On frame
*
* @param {Number} step
*/
Game.prototype.onFrame = function(step)
{
this.draw();
BaseGame.prototype.onFrame.call(this, step);
};
/**
* On round new
*/
Game.prototype.onRoundNew = function()
{
BaseGame.prototype.onRoundNew.call(this);
this.clearBackground();
this.draw();
};
/**
* On stop
*/
Game.prototype.onStop = function()
{
BaseGame.prototype.onStop.call(this);
this.clearBackground();
this.draw();
};
/**
* Is tie break
*
* @return {Boolean}
*/
Game.prototype.isTieBreak = function()
{
var maxScore = this.maxScore;
return this.avatars.match(function () { return this.score >= maxScore; }) !== null;
};
/**
* Is borderless?
*
* @return {Boolean}
*/
Game.prototype.isBorderless = function()
{
return this.avatars.match(function () {
return this.alive && this.borderless;
}) !== null;
};
/**
* Are all avatars ready?
*
* @return {Boolean}
*/
Game.prototype.isReady = function()
{
return this.started ? true : BaseGame.prototype.isReady.call(this);
};
/**
* Clear trails
*/
Game.prototype.clearTrails = function()
{
this.clearBackground();
};
/**
* End
*/
Game.prototype.end = function()
{
if (this.started) {
this.started = false;
window.removeEventListener('error', this.stop);
window.removeEventListener('resize', this.onResize);
this.stop();
this.fps.stop();
this.canvas.clear();
}
};
/**
* Update size
*/
Game.prototype.setSize = function(size)
{
BaseGame.prototype.setSize.call(this, size);
this.onResize();
};
/**
* Draw
*
* @param {Number} step
*/
Game.prototype.draw = function()
{
var i, avatar;
for (i = this.avatars.items.length - 1; i >= 0; i--) {
avatar = this.avatars.items[i];
if (avatar.present) {
this.drawTail(avatar);
}
}
this.canvas.clear();
for (i = this.avatars.items.length - 1; i >= 0; i--) {
avatar = this.avatars.items[i];
if (avatar.present) {
this.drawAvatar(avatar);
if (avatar.alive && avatar.hasBonus()) {
this.drawBonusStack(avatar);
}
if (!this.frame && avatar.local) {
this.drawArrow(avatar);
}
if (avatar.animation) {
avatar.animation.draw(this.canvas);
}
}
}
this.drawBonuses();
};
/**
* Draw tail
*
* @param {Avatar} avatar
*/
Game.prototype.drawTail = function(avatar)
{
var points = avatar.trail.getLastSegment();
if (points) {
this.background.drawLineScaled(points, avatar.width, avatar.color);
}
};
/**
* Draw avatar
*
* @param {Avatar} avatar
*/
Game.prototype.drawAvatar = function(avatar)
{
avatar.updateStart();
this.canvas.drawImage(avatar.canvas.element, avatar.start, avatar.angle);
};
/**
* Draw bonus stack
*
* @param {Avatar} avatar
*/
Game.prototype.drawBonusStack = function(avatar)
{
this.canvas.drawImage(avatar.bonusStack.canvas.element, [avatar.start[0] + 15, avatar.start[1] + 15]);
};
/**
* Draw arrow
*
* @param {Avatar} avatar
*/
Game.prototype.drawArrow = function(avatar)
{
this.canvas.drawImageScaled(
avatar.arrow.element,
[
avatar.head[0] - 5,
avatar.head[1] - 5
],
10,
10,
avatar.angle
);
};
/**
* Draw bonuses
*/
Game.prototype.drawBonuses = function()
{
this.bonusManager.draw(this.canvas);
};
/**
* Clear background with color
*/
Game.prototype.clearBackground = function()
{
this.background.color(this.backgroundColor);
};
/**
* On resize
*/
Game.prototype.onResize = function()
{
var x = window.innerWidth,
y = window.innerHeight;
var width = Math.min(x - document.getElementById('game-infos').clientWidth - 8, y - 8),
scale = width / this.size,
avatar;
for (i = this.avatars.items.length - 1; i >= 0; i--) {
avatar = this.avatars.items[i];
avatar.setScale(scale);
if (typeof(avatar.input) !== 'undefined') {
avatar.input.setWidth(x);
}
}
this.render.style.width = (width + 8) + 'px';
this.render.style.height = (width + 8) + 'px';
this.canvas.setDimension(width, width, scale);
this.background.setDimension(width, width, scale, true);
this.draw();
};
|
var storage = require('@google-cloud/storage')({
projectId: 'artbot-26016',
keyFilename: './service.json'
})
const Promise = require('bluebird')
const bucket = storage.bucket('artbot-26016.appspot.com')
function downloadFromBucket (dir, name) {
const newPath = `/tmp/${dir}/${name}`
return new Promise((resolve, reject) => {
bucket.file(name).download({destination: newPath})
.then(() => resolve(newPath))
.catch((e) => {
console.warn(e)
return reject(e)
})
})
}
function uploadToBucket (img) {
return new Promise((resolve, reject) => {
if (!img) return reject(new Error('no image'))
bucket.upload(img, {resumable: false}, (err, file) => {
if (err) {
if (err.code === 'ECONNRESET') {
return uploadToBucket(img)
}
return reject(err)
}
file.getSignedUrl({
action: 'read',
expires: '03-17-2025'
}, function (err, signedUrl) {
if (err) {
return reject(err)
}
return resolve(signedUrl)
})
})
})
}
exports.download = downloadFromBucket
exports.upload = uploadToBucket
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _reactIconBase = require('react-icon-base');
var _reactIconBase2 = _interopRequireDefault(_reactIconBase);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var MdCrop54 = function MdCrop54(props) {
return _react2.default.createElement(
_reactIconBase2.default,
_extends({ viewBox: '0 0 40 40' }, props),
_react2.default.createElement(
'g',
null,
_react2.default.createElement('path', { d: 'm31.6 28.4v-16.8h-23.2v16.8h23.2z m0-20q1.4 0 2.4 0.9t1 2.3v16.8q0 1.3-1 2.3t-2.4 0.9h-23.2q-1.4 0-2.4-0.9t-1-2.3v-16.8q0-1.3 1-2.3t2.4-0.9h23.2z' })
)
);
};
exports.default = MdCrop54;
module.exports = exports['default'];
|
$(function () {
var optsDate = {
format: 'Y-m-d', // รูปแบบวันที่
formatDate: 'Y-m-d',
timepicker: false,
closeOnDateSelect: true,
}
var setDateFunc = function (ct, obj) {
var minDateSet = $("#startDate_Booking").val();
var maxDateSet = $("#endDate_Booking").val();
if ($(obj).attr("id") == "startDate_Booking") {
this.setOptions({
minDate: false,
maxDate: maxDateSet ? maxDateSet : false
})
}
if ($(obj).attr("id") == "endDate_Booking") {
this.setOptions({
maxDate: false,
minDate: minDateSet ? minDateSet : false
})
}
}
$("#startDate_Booking,#endDate_Booking").datetimepicker($.extend(optsDate, {
onShow: setDateFunc,
onSelectDate: setDateFunc,
}));
});
|
/*jslint browser: true, undef: true, white: false, laxbreak: true *//*global Ext*/
/**
* A simple h1 component for titling a {@link Jarvus.widget.chart.Container chart container}.
*/
Ext.define('Jarvus.widget.chart.Title', {
extend: 'Ext.Component'
,xtype: 'charttitle'
,autoEl: 'h1'
,componentCls: 'chart-title'
/**
* @cfg {Function}
* A function to be called within the scope of the chart title when the associated chart is updated
*/
,onChartRefresh: Ext.emptyFn
});
|
import { themr } from "react-css-themr";
import { PAGE_ARTIFACTS } from "ui-components/identifiers";
import ArtifactsPage from "./Page";
import theme from "./theme.scss";
const ThemedArtifactsPage = themr(PAGE_ARTIFACTS, theme)(ArtifactsPage);
export default ThemedArtifactsPage;
export { ThemedArtifactsPage as ArtifactsPage };
|
/**
* Model for payment objects
*/
define([
'jquery', 'backbone',
'objects/models/recordId'
],
function ($, Backbone, RecordId) {
return Backbone.Model.extend({
idAttribute: "id",
defaults: {
id: "",
recordId: new RecordId(),
amount: 0.0,
amountNotAllocated: 0.0,
cashierId: "",
paymentDate: null,
paymentMethod: "",
paymentStatus: "",
receiptId: 0,
transactionId: 0,
transactionCode: ""
},
toJSON: function () {
var json = Backbone.Model.prototype.toJSON.call(this);
// TODO: add any special field processing here
return json;
},
url: function () {
//TODO: add url logic
}
});
});
|
// warning: This file is auto generated by `npm run build:tests`
// Do not edit by hand!
process.env.TZ = 'UTC'
var expect = require('chai').expect
var ini_set = require('../../../../src/php/info/ini_set') // eslint-disable-line no-unused-vars,camelcase
var ini_get = require('../../../../src/php/info/ini_get') // eslint-disable-line no-unused-vars,camelcase
var strip_tags = require('../../../../src/php/strings/strip_tags.js') // eslint-disable-line no-unused-vars,camelcase
describe('src/php/strings/strip_tags.js (tested in test/languages/php/strings/test-strip_tags.js)', function () {
it('should pass example 1', function (done) {
var expected = 'Kevin <b>van</b> <i>Zonneveld</i>'
var result = strip_tags('<p>Kevin</p> <br /><b>van</b> <i>Zonneveld</i>', '<i><b>')
expect(result).to.deep.equal(expected)
done()
})
it('should pass example 2', function (done) {
var expected = '<p>Kevin van Zonneveld</p>'
var result = strip_tags('<p>Kevin <img src="someimage.png" onmouseover="someFunction()">van <i>Zonneveld</i></p>', '<p>')
expect(result).to.deep.equal(expected)
done()
})
it('should pass example 3', function (done) {
var expected = "<a href='https://kvz.io'>Kevin van Zonneveld</a>"
var result = strip_tags("<a href='https://kvz.io'>Kevin van Zonneveld</a>", "<a>")
expect(result).to.deep.equal(expected)
done()
})
it('should pass example 4', function (done) {
var expected = '1 < 5 5 > 1'
var result = strip_tags('1 < 5 5 > 1')
expect(result).to.deep.equal(expected)
done()
})
it('should pass example 5', function (done) {
var expected = '1 1'
var result = strip_tags('1 <br/> 1')
expect(result).to.deep.equal(expected)
done()
})
it('should pass example 6', function (done) {
var expected = '1 <br/> 1'
var result = strip_tags('1 <br/> 1', '<br>')
expect(result).to.deep.equal(expected)
done()
})
it('should pass example 7', function (done) {
var expected = '1 <br/> 1'
var result = strip_tags('1 <br/> 1', '<br><br/>')
expect(result).to.deep.equal(expected)
done()
})
it('should pass example 8', function (done) {
var expected = 'hello world'
var result = strip_tags('<i>hello</i> <<foo>script>world<</foo>/script>')
expect(result).to.deep.equal(expected)
done()
})
it('should pass example 9', function (done) {
var expected = '4'
var result = strip_tags(4)
expect(result).to.deep.equal(expected)
done()
})
})
|
const jwt = require('jsonwebtoken');
const { SecretKey } = require('../config/config.secret.json');
const db = require('../models');
const auth = {
loginRequired: function loginRequired(req, res, next) {
const authorizationHeader = req.headers.authorization;
let token;
if (authorizationHeader) {
token = authorizationHeader.split(' ')[1];
}
if (token) {
jwt.verify(token, SecretKey.jwt, (err, decoded) => {
if (err) {
res.status(401).json({ error: 'Failed to authenticate' });
} else {
db.User.findOne({
where: { id: decoded.id },
attributes: ['id', 'email', 'role'],
}).then((user) => {
req.user = user;
next();
return null;
}).catch(() => {
res.status(404).json({ error: 'No such user' });
});
}
});
} else {
res.status(403).json({
error: 'No token provided',
});
}
},
// isBusinessAccount: function isBusinessAccount(req, res, next) {
//
// },
// isCustomerAccount: function isCustomerAccount(req, res, next) {
//
// },
// isBusinessOwner: function isBusinessOwner(req, res, next) {
//
// },
};
module.exports = auth;
|
'use strict';
var lint = require('lint-templates');
/**
* Lint `file.content` for missing helpers
* or data properties.
*/
module.exports = function (app) {
return function(file, next) {
lint(app, file);
next();
};
};
|
const specs = require('../support/controllers/resources');
describe('Controller Resources', () => {
const names = ['getResources', 'getResourceThings', 'createResource', 'deleteResourceById', 'updateResourceById',
'getResourceById'];
_.each(names, (name) => {
describe(`#${name}`, () => {
const spec = specs[name];
beforeEach('nock requests', spec.nockRequest);
it('resolve promise', spec.promiseResolved);
it('resolve correct response', spec.correctInstance);
it('resolve correct content', spec.correctContent);
});
});
});
|
function RunestoneBase () { // Basic parent stuff
}
RunestoneBase.prototype.logBookEvent = function (eventInfo) {
eventInfo.course = eBookConfig.course;
if (eBookConfig.useRunestoneServices && eBookConfig.logLevel > 0) {
jQuery.get(eBookConfig.ajaxURL + 'hsblog', eventInfo); // Log the run event
}
console.log("logging event " + JSON.stringify(eventInfo));
};
RunestoneBase.prototype.logRunEvent = function (eventInfo) {
eventInfo.course = eBookConfig.course;
if (! 'to_save' in eventInfo) {
eventInfo.save_code = "True"
}
if (eBookConfig.useRunestoneServices && eBookConfig.logLevel > 0) {
jQuery.post(eBookConfig.ajaxURL + 'runlog', eventInfo); // Log the run event
}
console.log("running " + JSON.stringify(eventInfo));
};
/* Checking/loading from storage */
RunestoneBase.prototype.checkServer = function (eventInfo) {
// Check if the server has stored answer
if (this.useRunestoneServices) {
var data = {};
data.div_id = this.divid;
data.course = eBookConfig.course;
data.event = eventInfo;
jQuery.getJSON(eBookConfig.ajaxURL + "getAssessResults", data, this.repopulateFromStorage.bind(this)).error(this.checkLocalStorage.bind(this));
} else {
this.checkLocalStorage(); // just go right to local storage
}
};
RunestoneBase.prototype.repopulateFromStorage = function (data, status, whatever) {
// decide whether to use the server's answer (if there is one) or to load from storage
if (data !== null && this.shouldUseServer(data)) {
this.restoreAnswers(data);
this.setLocalStorage(data);
} else {
this.checkLocalStorage();
}
};
RunestoneBase.prototype.shouldUseServer = function (data) {
// returns true if server data is more recent than local storage or if server storage is correct
if (data.correct == "T" || localStorage.length === 0)
return true;
var ex = localStorage.getItem(eBookConfig.email + ":" + this.divid + "-given");
if (ex === null)
return true;
var storedData = JSON.parse(ex);
if (data.answer == storedData.answer)
return true;
var storageDate = new Date(storedData.timestamp);
var serverDate = new Date(data.timestamp);
if (serverDate < storageDate)
return false;
return true;
};
|
module.exports = {
env: {
node: true,
es6: true,
'jest/globals': true,
},
parserOptions: {
ecmaVersion: 2018,
},
plugins: ['import', 'jest'],
extends: ['eslint:recommended', 'prettier'],
rules: {
'no-unused-vars': 'off',
eqeqeq: 'error',
'prefer-const': 'error',
'no-var': 'error',
'prefer-template': 'error',
'object-shorthand': 'error',
'no-console': 'off',
'no-debugger': 'off',
},
};
|
function accumulate(arr) {
return arr.reduce(function(r, a) {
r.push((r.length && r[r.length - 1] || 0) + a);
return r;
}, []);
}
// // Grab metadata on the latest json
// getRetry('https://www.googleapis.com/storage/v1/b/sgdq-backend.appspot.com/o/killVsSave.json', function(res) {
// // Get media link and pipe data to setupAll
// getRetry(res.mediaLink, setupBidSeries)
// });
getRetry('/data/2016/killVsSave.json', setupBidSeries);
function setupBidSeries(data) {
// data = JSON.parse(data)
var accumulatedYs = data.ys.map(function(d) { return accumulate(d.slice(1)) })
accumulatedYs.forEach(function(d, idx) { d.unshift(data.ys[idx][0]) })
var chart = graphSeries('#metroid_chat', data.x, accumulatedYs);
chart.data.colors({
'Save': d3.rgb('#00AEEF'),
'Kill': d3.rgb('#F21847')
});
}
function graphSeries(element, xSeries, yArrs){
var cols = [xSeries].concat(yArrs);
return chart = c3.generate({
bindto: element,
data: {
x: 'x',
columns: cols
},
axis: {
x: {
type: 'timeseries',
tick: {
format: '%Y-%m-%d %I:%M%p',
fit: false,
count: 9
}
},
y: {
// min: 0,
// padding: {
// bottom: 0
// },
tick: {
format: d3.format("$,")
}
}
},
point: {
r: 1
},
tooltip: {
format: {
value: function (value, ratio, id) {
var format = d3.format('$,.2f');
return format(value);
}
}
},
zoom: {
enabled: true,
rescale: true
}
});
}
function getRetry(url, cb) {
$.ajax({
url: url,
async: true,
// retryCount and retryLimit will let you retry a determined number of times
retryCount: 0,
retryLimit: 5,
// retryTimeout limits the total time retrying (in milliseconds)
retryTimeout: 15000,
// timeout for each request
timeout: 2000,
// created tells when this request was created
created : Date.now(),
error : function(xhr, textStatus, errorThrown ) {
this.retryCount++;
if (this.retryCount <= this.retryLimit && Date.now() - this.created < this.retryTimeout) {
console.log("Retrying");
$.ajax(this);
return;
}
},
success: cb
});
}
|
var renderPage = function(total, page, numofpage, callback) {
var max_page = Math.ceil(total / numofpage), page_pre = page * 1 - 1 > 0 ? page * 1 - 1
: 1, page_next = page * 1 + 1 > max_page ? max_page : page * 1 + 1;
if (max_page > 1) {
var html = '<a href="javascript:void(0);" title="上一页" class="page_pre" page="'
+ page_pre + '"><i class="ico page_arrow_l"></i></a>';
var start = 1, end = max_page, aso = '';
if (max_page > 10) {
start = page - 2;
start = start > 1 ? start : 1;
end = page - 0 + 2;
end = end > max_page ? max_page : end;
}
for ( var i = 1; i <= max_page; i++) {
if (i == page) {
html += '<a href="javascript:void(0);" class="current"><span>'
+ i + '</span></a>';
} else {
if (i == 1 || i == max_page || (i >= start && i <= end)) {
html += '<a href="javascript:void(0);" page="' + i
+ '"><span>' + i + '</span></a>';
aso = '...'
} else {
html += aso;
aso = '';
}
}
}
html += '<a href="javascript:void(0);" title="下一页" class="page_next" page="'
+ page_next + '"><i class="ico page_arrow_r"></i></a>';
$('.mod_page_nav').html(html).show();
if (callback) {
$('.mod_page_nav a').unbind().click(function() {
var cur_page = $(this).attr('page');
if (cur_page) {
callback(cur_page);
}
});
}
} else {
$('.mod_page_nav').hide();
}
};
|
/* eslint-disable */
export default {
"message" : "Server returned HTTP response code: 401, message: 'Unauthorized' for URL: https://api.github.com/user",
"code" : 500,
"errors" : [ ]
}
|
import { connect } from 'react-redux';
import { selectReferralReward } from 'redux/selectors/rewards';
import { selectUserInvitees, selectUserInviteStatusIsPending } from 'redux/selectors/user';
import InviteList from './view';
const select = state => ({
invitees: selectUserInvitees(state),
isPending: selectUserInviteStatusIsPending(state),
referralReward: selectReferralReward(state),
});
const perform = () => ({});
export default connect(select, perform)(InviteList);
|
export default class Filters {
/**
*
* @param propertyMetadata
* @param model
* @param keyPrefix
* @param metadataEvaluator
* @param reduxProps
* @param onChange
* @returns {*}
*/
static arrayFilter(propertyMetadata, model, keyPrefix, metadataEvaluator, reduxProps, onChange, globalScope) {
if(!propertyMetadata) throw Error('Argument \'propertyMetadata\' should be truthy');
if(!model) throw Error('Argument \'model\' should be truthy');
if( !globalScope ) globalScope = model
if (propertyMetadata.type == 'array' && propertyMetadata.arrayType == 'entity') {
if (!propertyMetadata.fields) {
throw Error('when metadata is of type \'array\' and arrayType is \'entity\', it must have a fields property');
}
if (!model.hasOwnProperty(propertyMetadata.name) || model[propertyMetadata.name] === null || model[propertyMetadata.name] === undefined) {
// if the property does not exist, create it
model[propertyMetadata.name] = [];
} else {
// if the property exists, it must be an object
if (!(model[propertyMetadata.name] instanceof Array)) {
throw Error('when metadata is of type array, the model value should be an array');
}
}
// returns the reduxProps for a particular array item
let getReduxPropsForItem = (index) => {
if(!reduxProps) return undefined;
if(reduxProps && !reduxProps.hasOwnProperty(propertyMetadata.name)) throw Error('reduxProps is defined but it does not have the required property metadata');
return reduxProps[propertyMetadata.name][index];
};
propertyMetadata.fields = model[propertyMetadata.name].map((item, index) => metadataEvaluator.evaluate(propertyMetadata.fields, item, `${keyPrefix}.${index}`, getReduxPropsForItem(index), onChange, globalScope));
}
return propertyMetadata;
}
/**
*
* @param propertyMetadata
* @param model
* @param keyPrefix
* @param metadataEvaluator
* @param reduxProps
* @param onChange
* @returns {*}
*/
static defaultFilter(propertyMetadata, model, keyPrefix, metadataEvaluator, reduxProps, onChange, globalScope) {
if(!propertyMetadata) throw Error('Argument \'propertyMetadata\' should be truthy');
if(!model) throw Error('Argument \'model\' should be truthy');
propertyMetadata.key = keyPrefix;
// set redux properties
if(reduxProps && reduxProps.hasOwnProperty(propertyMetadata.name)) {
propertyMetadata.reduxFormProps = reduxProps[propertyMetadata.name];
}
return propertyMetadata;
}
/**
*
* @param propertyMetadata
* @param model
* @param keyPrefix
* @param metadataEvaluator
* @param reduxProps
* @param onChange
* @returns {*}
*/
static entityFilter(propertyMetadata, model, keyPrefix, metadataEvaluator, reduxProps, onChange, globalScope) {
if (!propertyMetadata) throw new Error('metadata is required');
if (!model) throw new Error('model is required');
if( !globalScope ) globalScope = model
if (propertyMetadata.type == 'entity') {
if (! propertyMetadata.fields) {
throw Error('when metadata is of type entity, it must have a fields property');
}
if (model && !model.hasOwnProperty(propertyMetadata.name) || model[propertyMetadata.name] === null || model[propertyMetadata.name] === undefined) {
// if the property does not exist, create it
model[propertyMetadata.name] = {};
} else {
// if the property exists, it must be an object
if (typeof model[propertyMetadata.name] !== 'object') {
throw Error('when metadata is of type entity, the model value should be an object');
}
}
let itemReduxProps = reduxProps ? reduxProps[propertyMetadata.name] : undefined;
propertyMetadata.fields = metadataEvaluator.evaluate(propertyMetadata.fields, model[propertyMetadata.name], keyPrefix, itemReduxProps, onChange, globalScope);
}
return propertyMetadata;
}
}
|
var LinkedList = require("../node_modules/basic-ds/lib/LinkedList");
var Scheduler = (function () {
function Scheduler() {
this.queue = new LinkedList();
}
Scheduler.prototype.addTask = function (task) {
var _this = this;
var done = task.doneCallback;
task.doneCallback = function () {
_this.removeTask(task);
done();
};
this.queue.push_front(task);
this.tick();
};
Scheduler.prototype.tick = function () {
var _this = this;
setTimeout(function () {
var currentTask = _this.currentTask();
if (currentTask !== null && !currentTask.started) {
currentTask.start();
_this.tick();
}
}, 0);
};
Scheduler.prototype.removeTask = function (task) {
if (task === this.currentTask()) {
this.queue.pop_back();
this.tick();
}
else {
throw "not the current task";
}
};
Scheduler.prototype.currentTask = function () {
return this.queue.last ? this.queue.last.value : null;
};
Scheduler.prototype.clear = function () {
this.queue.clear();
};
Scheduler.prototype.createRepeater = function (createFunc, delay) {
var _repeat = true;
var _scheduler = this;
var _delay = delay;
function repeatFunc() {
if (!_repeat) {
return;
}
var task = createFunc();
var done = task.doneCallback;
task.doneCallback = function () {
if (_repeat) {
setTimeout(repeatFunc, _delay);
}
done();
};
_scheduler.addTask(task);
}
var repeater = {
stop: function () {
_repeat = false;
},
start: function () {
repeatFunc();
}
};
Object.defineProperty(repeater, "delay", {
get: function () {
return _delay;
},
set: function (delay) {
_delay = delay;
}
});
return repeater;
};
return Scheduler;
})();
module.exports = Scheduler;
|
///* jshint -W117, -W030 */
//describe('UserCreateController', function () {
// var scope;
// var controller;
//
// bard.verifyNoOutstandingHttpRequests();
//
// beforeEach(function () {
// bard.inject('$controller', '$rootScope', 'EventService');
// scope = window.$rootScope.$new();
// bard.mockService(EventService, appMockServices.eventResult);
// controller = newAppController();
// $rootScope.$apply();
// });
//
// describe('Controller Initialization', function () {
// //var activateSpy;
// //var getEventsSpy;
//
// beforeEach(function () {
// controller = newAppController();
// //var activateSpy = sinon.spy(controller.activate);
// //var getEventsSpy = sinon.spy(EventService.getEvents);
// });
//
// it('creates controller', function () {
// expect(controller, 'controller obj').to.exist;
// });
// });
//
// function newAppController(bsMock) {
// //if (bsMock != null) {
// // EventService.getEvents.returns(bsMock.getEvents);
// //}
// var newController = $controller('UserCreateController', {$scope: scope});
// $rootScope.$apply();
// return newController;
// }
//});
|
(function() {
'use strict';
module.exports = {
isUnique: {
email: function(users) {
var email = [];
// loop through the array and get all the emails
for (var key in users) {
email.push(users[key].email);
}
// check if they are unique
if (email.length === 1) {
return true;
}
var unique = false;
// if the email array is more than one
for (var i = 0; i < email.length - 1; i++) {
if (email[i] !== email[i + 1]) {
unique = true;
} else {
unique = false;
}
}
return unique;
},
// check if the usernames are unique
username: function(users) {
var username = [];
// loop through the array and get all the usernames
for (var key in users) {
username.push(users[key].username);
}
// check if they are unique
if (username.length === 1) {
return true;
}
// if the username array is more than one
var unique = false;
for (var i = 0; i < username.length - 1; i++) {
if (username[i] !== username[i + 1]) {
unique = true;
} else {
unique = false;
}
}
return unique;
},
// chekc if the roles created have a unique title.
roleTitle: function(roles) {
var titles = [];
for (var key in roles) {
titles.push(roles[key].title);
}
if (titles.length == 1) {
return true;
} else {
var unique = false;
for (var i = 0; i < titles.length - 1; i++) {
if (titles[i] !== titles[i + 1]) {
unique = true;
} else {
unique = false;
}
}
return unique;
}
},
// is unique document title
docTitle: function(docs) {
var titles = [];
for (var key in docs) {
titles.push(docs[key].title);
}
if (titles.length == 1) {
return true;
} else {
var unique = false;
for (var i = 0; i < titles.length - 1; i++) {
if (titles[i] !== titles[i + 1]) {
unique = true;
} else {
unique = false;
}
}
return unique;
}
}
},
// chekc if the user role are defined
isDefined: function(users) {
var unique = false;
for (var key in users) {
if (users[key].role) {
unique = true;
} else {
unique = false;
}
}
return unique;
},
hasFirstName: function(users) {
var unique;
for (var key in users) {
if (users[key].name.first) {
unique = true;
} else {
unique = false;
}
}
return unique;
},
hasLastName: function(users) {
var unique;
for (var key in users) {
if (users[key].name.last) {
unique = true;
} else {
unique = false;
}
}
return unique;
},
hasOwner: function(docs) {
var unique = false;
for (var key in docs) {
if (docs[key].ownerId) {
unique = true;
} else {
unique = false;
}
}
return unique;
},
// Check if the documents have date created
hasDateCreated: function(docs) {
var unique = false;
for (var key in docs) {
if (docs[key].dateCreated) {
unique = true;
} else {
unique = false;
}
}
return unique;
},
// checks if the the documents retrived are ordered.
ordered: function(docs) {
var dates = [];
for (var key in docs) {
dates.push(docs[key].dateCreated);
}
var ordered = false;
for (var i = 0; i < dates.length - 1; i++) {
if (+dates[i] > +dates[i + 1] || +dates[i] === +dates[i + 1]) {
ordered = true;
} else {
ordered = false;
}
}
return ordered;
},
// check if the documenst fetched are of the same Date
isByDate: function(docs) {
var dates = [];
for (var key in docs) {
dates.push(docs[key].dateCreated);
}
var isDate = false;
if (dates.length === 1) {
return true;
} else {
for (var i = 0; i < dates.length - 1; i++) {
if (+dates[i] === +dates[i + 1]) {
isDate = true;
} else {
isDate = false;
}
}
return isDate;
}
},
// chekc if the documenst fetched are of the same
isOfSameRole: function(docs) {
var role = [];
for (var key in docs) {
role.push(docs[key].access);
}
var isRole = false;
for (var i = 0; i < role.length - 1; i++) {
if (role[i] == role[i + 1]) {
isRole = true;
} else {
isRole = false;
}
}
return isRole;
}
};
})();
|
import { WebVTTParser } from 'webvtt-parser';
const cleanText = (s) => {
const BREAK_RE = /(<br>)/ig; // sub files shouldn't have these, but some do
const NL_RE = /(\\n|\\N)/ig;
const TAG_RE = /(<([^>]+)>)/ig;
const ASS_STYLE_RE = /(\{\\[^}]*\})/ig;
return s.trim().replace(BREAK_RE, '\n').replace(NL_RE, '\n').replace(TAG_RE, '').replace(ASS_STYLE_RE, '');
};
const parseSRTTime = (s) => {
const re = /(\d{2}):(\d{2}):(\d{2}),(\d{3})/;
const [, hours, mins, seconds, ms] = re.exec(s);
return 3600*(+hours) + 60*(+mins) + (+seconds) + 0.001*(+ms);
};
export const parseSRT = (text) => {
const normText = text.replace(/\r\n/g, '\n'); // normalize newlines
const re = /(\d+)\n(\d{2}:\d{2}:\d{2},\d{3}) --> (\d{2}:\d{2}:\d{2},\d{3})\s*\n((?:.+\n)+)/g;
const subs = [];
let found;
while (true) {
found = re.exec(normText);
if (!found) {
break;
}
const [full, , beginStr, endStr, lines] = found;
const begin = parseSRTTime(beginStr);
const end = parseSRTTime(endStr);
// TODO: Should verify that end time is >= begin time
// NOTE: We could check that indexes and/or time are in order, but don't really care
subs.push({
begin,
end,
lines: cleanText(lines),
});
re.lastIndex = found.index + full.length;
}
return subs;
};
export const parseVTT = (text) => {
const parser = new WebVTTParser();
const tree = parser.parse(text, 'metadata');
return tree.cues.map(cue => ({
begin: cue.startTime,
end: cue.endTime,
lines: cleanText(cue.text),
}));
};
const parseASSTime = (s) => {
const re = /(\d):(\d{2}):(\d{2})\.(\d{2})/;
const [, hours, mins, seconds, cs] = re.exec(s);
return 3600*(+hours) + 60*(+mins) + (+seconds) + 0.01*(+cs);
};
export const parseASS = (text) => {
const EVENTS_SECTION_RE = /^\[Events\]\s+Format:(.*)\s*([^]*)/mg;
const EVENT_LINE_RE = /([^:]+):\s*(.*)/;
const result = [];
const eventsSectionMatch = EVENTS_SECTION_RE.exec(text);
if (eventsSectionMatch) {
const fieldNames = eventsSectionMatch[1].split(',').map(s => s.trim());
if (fieldNames[fieldNames.length-1] !== 'Text') {
throw new Error('Last field of ASS events must be Text');
}
const startFieldIdx = fieldNames.indexOf('Start');
if (startFieldIdx < 0) {
throw new Error('Start field not found in ASS events format');
}
const endFieldIdx = fieldNames.indexOf('End');
if (endFieldIdx < 0) {
throw new Error('End field not found in ASS events format');
}
const eventLines = eventsSectionMatch[2].trim().split('\n').map(s => s.trim());
for (const eventLine of eventLines) {
const lineMatch = EVENT_LINE_RE.exec(eventLine);
if (lineMatch) {
const eventType = lineMatch[1];
if (eventType === 'Dialogue') {
const fields = lineMatch[2].split(',');
const text = fields.slice(fieldNames.length-1).join(',').trim();
const start = parseASSTime(fields[startFieldIdx]);
const end = parseASSTime(fields[endFieldIdx]);
if (text) {
result.push({
begin: start,
end,
lines: cleanText(text),
});
}
}
}
}
}
return result;
};
|
import LookupDialogController from 'ember-flexberry/controllers/lookup-dialog';
export default LookupDialogController;
|
//$("#registrar").css("display","none"); botonRegistrarse
//Aparicion -desaparciion
$("#registrar").click(function() {
$("#log").hide("slow");
$("#register").show("slow");
});
$("#volverToIniciarSesion").click(function() {
$("#register").hide("slow");
$("#log").show("slow");
});
//Antes de enviar el registro comprobamos que el correo y los passwords coincidan.
/*$('#form-register').submit(function(){
var pass1=$('#password1').val();
var pass2=$('#password2').val();
var correo=$('#correo').val();
var correo2=$('#correo2').val();
var seguir=false;
var mensaje="";
if (pass1!=pass2){
mensaje="Las contraseñas no coinciden";
$('#error_registro').text(mensaje);
$('#error_registro').show("slow");
return false;
}else {
seguir=true;
}
if(correo!=correo2){
mensaje="El correo no coincide";
$('#error_registro').text(mensaje);
$('#error_registro').show("slow");
return false
}else{
seguir=true;
}
return seguir;
});
//En el login se encripta la contrasena antes de enviarla
$('#form_login').submit(function(){
var pass=$('#password_login').val();
var md5=$.md5(pass);
//alert(pass+" "+md5);
return true;
})*/
|
var endpoints = {};
if (process.env.HOST_ENV === 'frontend') {
endpoints = {
// WEB_SERVER_URL: '', // do not call URL directly, use relative urls
WEB_SERVER_PORT: 3000,
ETH_SERVER_URL: 'http://54.190.58.228',
ETH_SERVER_PORT: 3002,
AUTH_SERVER_URL: 'http://52.33.65.180',
AUTH_SERVER_PORT: 3003,
DB_SERVER_URL: 'http://52.33.65.180',
DB_SERVER_PORT: 3004,
ES_SERVER_URL: 'http://52.33.65.180',
ES_SERVER_PORT: 3005,
POSTGRES_CONNECTION_STRING: 'postgres://docker:docker@postgres:5432',
};
} else if (process.env.NODE_ENV === 'development') {
endpoints = {
WEB_SERVER_URL: 'http://localhost',
WEB_SERVER_PORT: 3000,
WEBPACK_DEV_SERVER_URL: 'http://localhost',
WEBPACK_DEV_SERVER_PORT: 3001,
ETH_SERVER_URL: 'http://localhost',
ETH_SERVER_PORT: 3002,
AUTH_SERVER_URL: 'http://localhost',
AUTH_SERVER_PORT: 3003,
DB_SERVER_URL: 'http://localhost',
DB_SERVER_PORT: 3004,
ES_SERVER_URL: 'http://localhost',
ES_SERVER_PORT: 3005,
// change your environment variables based on your local postgres database settings
// POSTGRES_CONNECTION_STRING: `postgres://${process.env.DATABASEUSER || 'postgres'}:${process.env.DATABASEPASSWORD || 'password'}@${process.env.DATABASEADDRESS || 'localhost'}:${process.env.DATABASEPORT || '5432'}/tickether`,
ETHEREUM_CONNECTION_STRING: 'http://localhost:8545',
BLOCKCHAIN_PORT: 8545,
ELASTICSEARCH_URL: 'http://localhost',
ELASTICSEARCH_PORT: 9200,
};
} else if (process.env.NODE_ENV === 'production' && process.env.HOST_ENV === 'ecs') {
endpoints = {
ETH_SERVER_URL: 'http://54.190.58.228',
ETH_SERVER_PORT: 3002,
AUTH_SERVER_URL: 'http://auth',
AUTH_SERVER_PORT: 3003,
DB_SERVER_URL: 'http://db',
DB_SERVER_PORT: 3004,
ES_SERVER_URL: 'http://es',
ES_SERVER_PORT: 3005,
POSTGRES_CONNECTION_STRING: 'postgres://docker:docker@postgres:5432/tickether',
ELASTICSEARCH_URL: 'http://elasticsearch',
ELASTICSEARCH_PORT: 9200,
};
} else if (process.env.NODE_ENV === 'production' && process.env.HOST_ENV === 'eth') {
endpoints = {
DB_SERVER_URL: 'http://52.33.65.180',
DB_SERVER_PORT: 3004,
ETH_SERVER_PORT: 3002,
ETHEREUM_CONNECTION_STRING: 'http://localhost:8545',
BLOCKCHAIN_PORT: 8545,
};
} else if (process.env.NODE_ENV === 'production' && process.env.HOST_ENV === 'web') {
endpoints = {
// WEB_SERVER_URL: '', // do not call URL directly, use relative urls
WEB_SERVER_PORT: 3000,
ETH_SERVER_URL: 'http://54.190.58.228',
ETH_SERVER_PORT: 3002,
AUTH_SERVER_URL: 'http://52.33.65.180',
AUTH_SERVER_PORT: 3003,
DB_SERVER_URL: 'http://52.33.65.180',
DB_SERVER_PORT: 3004,
ES_SERVER_URL: 'http://52.33.65.180',
ES_SERVER_PORT: 3005,
POSTGRES_CONNECTION_STRING: 'postgres://docker:docker@postgres:5432',
};
} else {
throw new Error('NODE_ENV environment variable not valid');
}
module.exports = endpoints;
|
'use strict';
var React = require('react');
var SvgIcon = require('../../svg-icon');
var NotificationSync = React.createClass({
displayName: 'NotificationSync',
render: function render() {
return React.createElement(
SvgIcon,
this.props,
React.createElement('path', { d: 'M12 4V1L8 5l4 4V6c3.31 0 6 2.69 6 6 0 1.01-.25 1.97-.7 2.8l1.46 1.46C19.54 15.03 20 13.57 20 12c0-4.42-3.58-8-8-8zm0 14c-3.31 0-6-2.69-6-6 0-1.01.25-1.97.7-2.8L5.24 7.74C4.46 8.97 4 10.43 4 12c0 4.42 3.58 8 8 8v3l4-4-4-4v3z' })
);
}
});
module.exports = NotificationSync;
|
import createSvgIcon from './utils/createSvgIcon';
import { jsx as _jsx } from "react/jsx-runtime";
export default createSvgIcon( /*#__PURE__*/_jsx("path", {
d: "M4 6H2v14c0 1.1.9 2 2 2h14v-2H4V6zm16-4H8c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-1 9h-4v4h-2v-4H9V9h4V5h2v4h4v2z"
}), 'LibraryAdd');
|
import React from 'react';
import Header from './views/layouts/Header';
const Root = ({children}) => (
<div>
<Header />
{children}
</div>
);
export default Root;
|
var Falcor = require('falcor'),
FalcorDataSource = require('falcor-http-datasource'),
model = new Falcor.Model({
source: new FalcorDataSource('/model.json')
})
module.exports = model
|
exports.uriToZipEntryName = uriToZipEntryName;
exports.replaceFragment = replaceFragment;
function uriToZipEntryName(base, uri) {
if (uri.charAt(0) === "/") {
return uri.substr(1);
} else {
// In general, we should check first and second for trailing and leading slashes,
// but in our specific case this seems to be sufficient
return base + "/" + uri;
}
}
function replaceFragment(uri, fragment) {
var hashIndex = uri.indexOf("#");
if (hashIndex !== -1) {
uri = uri.substring(0, hashIndex);
}
return uri + "#" + fragment;
}
|
'use strict'
const mongoose = require('mongoose')
const config = require('./config')
const Tweet = require('./models/tweet')
describe('Index Method', function () {
before(function (done) {
mongoose.connect(config.mongoUrl, function () {
config.deleteIndexIfExists(['tweets', 'public_tweets'], function () {
Tweet.remove(function () {
config.createModelAndEnsureIndex(Tweet, {
user: 'jamescarr',
message: 'I know kung-fu!',
post_date: new Date()
}, done)
})
})
})
})
after(function (done) {
Tweet.remove(function () {
mongoose.disconnect()
done()
})
})
it('should be able to index it directly without saving', function (done) {
Tweet.findOne({
message: 'I know kung-fu!'
}, function (err, doc) {
doc.message = 'I know nodejitsu!'
doc.index(function () {
setTimeout(function () {
Tweet.search({
query_string: {
query: 'know'
}
}, function (err1, res) {
res.hits.hits[0]._source.message.should.eql('I know nodejitsu!')
done()
})
}, config.INDEXING_TIMEOUT)
})
})
})
it('should be able to index to alternative index', function (done) {
Tweet.findOne({
message: 'I know kung-fu!'
}, function (err, doc) {
doc.message = 'I know taebo!'
doc.index({
index: 'public_tweets'
}, function () {
setTimeout(function () {
Tweet.search({
query_string: {
query: 'know'
}
}, {
index: 'public_tweets'
}, function (err1, res) {
res.hits.hits[0]._source.message.should.eql('I know taebo!')
done()
})
}, config.INDEXING_TIMEOUT)
})
})
})
it('should be able to index to alternative index and type', function (done) {
Tweet.findOne({
message: 'I know kung-fu!'
}, function (err, doc) {
doc.message = 'I know taebo!'
doc.index({
index: 'public_tweets',
type: 'utterings'
}, function () {
setTimeout(function () {
Tweet.search({
query_string: {
query: 'know'
}
}, {
index: 'public_tweets',
type: 'utterings'
}, function (err1, res) {
res.hits.hits[0]._source.message.should.eql('I know taebo!')
done()
})
}, config.INDEXING_TIMEOUT)
})
})
})
})
|
import createSvgIcon from './utils/createSvgIcon';
import { jsx as _jsx } from "react/jsx-runtime";
export default createSvgIcon( /*#__PURE__*/_jsx("path", {
d: "M9.12 5 1 12.68V23h18v-2.5h-7v-1h9V17h-9v-1h10v-2.5H12v-1h8V10H8.86l1.88-3.3L9.12 5zm4.38 4c.83 0 1.5-.67 1.5-1.5 0-.84-1.5-2.5-1.5-2.5S12 6.66 12 7.5c0 .83.67 1.5 1.5 1.5zm5-8S16 3.83 16 5.5C16 6.88 17.12 8 18.5 8S21 6.88 21 5.5C21 3.83 18.5 1 18.5 1z"
}), 'WashSharp');
|
import { REFINEMENT } from '../../../../config/types';
import { expectedExpression } from './errors';
import { name as namePattern } from './patterns';
import readExpression from '../../readExpression';
export default function readRefinement ( parser ) {
// some things call for strict refinement (partial names), meaning no space between reference and refinement
if ( !parser.strictRefinement ) {
parser.allowWhitespace();
}
// "." name
if ( parser.matchString( '.' ) ) {
parser.allowWhitespace();
const name = parser.matchPattern( namePattern );
if ( name ) {
return {
t: REFINEMENT,
n: name
};
}
parser.error( 'Expected a property name' );
}
// "[" expression "]"
if ( parser.matchString( '[' ) ) {
parser.allowWhitespace();
const expr = readExpression( parser );
if ( !expr ) parser.error( expectedExpression );
parser.allowWhitespace();
if ( !parser.matchString( ']' ) ) parser.error( `Expected ']'` );
return {
t: REFINEMENT,
x: expr
};
}
return null;
}
|
/**
* Rotating image demo.
*
*/
(function() {
'use strict';
Wings.run(function() {
var view = new Wings.View(document.getElementById('rotating-image'));
view.backgroundColor('magenta');
view.borderColor('transparent');
/**
* RotatingImage
*
* Reusable component that loads an image and rotates it at a specified
* speed.
*
* @param url
* the url of the image
* @param speed
* the rotational speed in deg/ms (degrees x milliseconds)
*
*/
var RotatingImage = Wings.Panel.extend({
init: function RotatingImage(url, speed) {
this._super();
var self = this;
self._img = new Image();
self._img.src = url;
self._img.onload = function() {
self._img.loaded = true;
};
self._angle = 0;
setInterval(function() {
self._angle++;
if (self._angle > 360)
self._angle = 0;
view.refresh();
}, 1 / speed);
},
draw: function(ctx) {
if (this._img && this._img.loaded) {
ctx.save();
ctx.rotate(num.radians(this._angle));
ctx.drawImage(this._img, -this._img.width / 2, -this._img.height / 2);
ctx.restore();
}
}
});
var img = new RotatingImage('images/wheel.png', 1 / 10);
img.location(view.width() / 2, view.height() / 2);
view.add(img);
});
})();
|
/*{
"name": "Given PUT /components/file is a pass-through",
"components": [],
"mockData": []
}*/
module.exports = function () {
this.Given(/^PUT \/components\/file is a pass\-through$/, function (done) {
httpBackend.whenPUT(/\/components\/file/).passThrough();
done();
});
};
|
/**
* Class Grid
* @param rowsNum
* @param colsNum
* @constructor
*/
function Grid(rowsNum, colsNum) {
this.rowsNum = rowsNum;
this.colsNum = colsNum;
}
Grid.prototype.draw = function() {
var gridHTML = '';
for(var i=0; i<this.rowsNum; i++) {
gridHTML += '<div class="row clearfix">';
for(var j=0; j<this.colsNum; j++) {
gridHTML += '<div class="col">';
gridHTML += '</div>';
}
gridHTML += '</div>';
}
jQuery('#tank-grid').html(gridHTML);
}
Grid.prototype.init = function() {
this.draw();
}
|
version https://git-lfs.github.com/spec/v1
oid sha256:37347a0c35457bb941a4bcad81c57fdd13c5fb2b751f6797b67aa2d51688c16c
size 5897
|
// warning: This file is auto generated by `npm run build:tests`
// Do not edit by hand!
process.env.TZ = 'UTC'
var expect = require('chai').expect
var ini_set = require('../../../../src/php/info/ini_set') // eslint-disable-line no-unused-vars,camelcase
var ini_get = require('../../../../src/php/info/ini_get') // eslint-disable-line no-unused-vars,camelcase
var chr = require('../../../../src/php/strings/chr.js') // eslint-disable-line no-unused-vars,camelcase
describe('src/php/strings/chr.js (tested in test/languages/php/strings/test-chr.js)', function () {
it('should pass example 1', function (done) {
var expected = true
true
chr(75) === 'K'
var result = chr(65536) === '\uD800\uDC00'
expect(result).to.deep.equal(expected)
done()
})
})
|
version https://git-lfs.github.com/spec/v1
oid sha256:742432e54423e20485f3da89c10fcfc1c6c08f35bf57b6bed298c8978f29c111
size 674
|
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'codemirror', 'pt-br', {
copyright: "Copyright CodeMirror © Marijn Haverbeke. All rights reserved.",
dlgTitle: 'About CodeMirror Source Plugin',
moreInfoShortcuts: "Available Shortcuts",
moreInfoShortcuts1: "<strong>CTRL + K</strong> to comment the currently selected text",
moreInfoShortcuts2: "<strong>CTRL + SHIFT + K</strong> to uncomment currently selected text",
moreInfoShortcuts3: "<strong>CTRL + ALT + K</strong> to auto format currently selected text",
moreInfoShortcuts4: "<strong>CTRL + Q</strong> Expand / Collapse Code Block",
moreInfoShortcuts5: "<strong>CTRL + F</strong> to perform a search",
moreInfoShortcuts6: "<strong>CTRL + G</strong> to find next",
moreInfoShortcuts7: "<strong>CTRL + SHIFT + G</strong> to find previous",
moreInfoShortcuts8: "<strong>CTRL + SHIFT</strong> to find and replace",
moreInfoShortcuts9: "<strong>CTRL + SHIFT + R</strong> to find and replace all",
toolbar: 'Código-Fonte',
searchCode: 'Search Source (CTRL + F)',
replaceCode: 'Replace Code (CTRL + SHIFT + F)',
autoFormat: 'Format Selection (CTRL + ALT + K)',
commentSelectedRange: 'Comment Selection (CTRL + K)',
uncommentSelectedRange: 'Uncomment Selection (CTRL + SHIFT + K)',
autoCompleteToggle: 'Enable/Disable HTML Tag Autocomplete'
});
|
'use strict';var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") return Reflect.decorate(decorators, target, key, desc);
switch (arguments.length) {
case 2: return decorators.reduceRight(function(o, d) { return (d && d(o)) || o; }, target);
case 3: return decorators.reduceRight(function(o, d) { return (d && d(target, key)), void 0; }, void 0);
case 4: return decorators.reduceRight(function(o, d) { return (d && d(target, key, o)) || o; }, desc);
}
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var source_module_1 = require('./source_module');
var view_1 = require('angular2/src/core/metadata/view');
var xhr_1 = require('angular2/src/compiler/xhr');
var lang_1 = require('angular2/src/facade/lang');
var async_1 = require('angular2/src/facade/async');
var shadow_css_1 = require('angular2/src/compiler/shadow_css');
var url_resolver_1 = require('angular2/src/compiler/url_resolver');
var style_url_resolver_1 = require('./style_url_resolver');
var util_1 = require('./util');
var di_1 = require('angular2/src/core/di');
var view_factory_1 = require('angular2/src/core/render/view_factory');
var StyleCompiler = (function () {
function StyleCompiler(_xhr, _urlResolver) {
this._xhr = _xhr;
this._urlResolver = _urlResolver;
this._styleCache = new Map();
this._shadowCss = new shadow_css_1.ShadowCss();
}
StyleCompiler.prototype.compileComponentRuntime = function (template) {
var styles = template.styles;
var styleAbsUrls = template.styleUrls;
return this._loadStyles(styles, styleAbsUrls, template.encapsulation === view_1.ViewEncapsulation.Emulated);
};
StyleCompiler.prototype.compileComponentCodeGen = function (template) {
var shim = template.encapsulation === view_1.ViewEncapsulation.Emulated;
return this._styleCodeGen(template.styles, template.styleUrls, shim);
};
StyleCompiler.prototype.compileStylesheetCodeGen = function (stylesheetUrl, cssText) {
var styleWithImports = style_url_resolver_1.extractStyleUrls(this._urlResolver, stylesheetUrl, cssText);
return [
this._styleModule(stylesheetUrl, false, this._styleCodeGen([styleWithImports.style], styleWithImports.styleUrls, false)),
this._styleModule(stylesheetUrl, true, this._styleCodeGen([styleWithImports.style], styleWithImports.styleUrls, true))
];
};
StyleCompiler.prototype.clearCache = function () { this._styleCache.clear(); };
StyleCompiler.prototype._loadStyles = function (plainStyles, absUrls, encapsulate) {
var _this = this;
var promises = absUrls.map(function (absUrl) {
var cacheKey = "" + absUrl + (encapsulate ? '.shim' : '');
var result = _this._styleCache.get(cacheKey);
if (lang_1.isBlank(result)) {
result = _this._xhr.get(absUrl).then(function (style) {
var styleWithImports = style_url_resolver_1.extractStyleUrls(_this._urlResolver, absUrl, style);
return _this._loadStyles([styleWithImports.style], styleWithImports.styleUrls, encapsulate);
});
_this._styleCache.set(cacheKey, result);
}
return result;
});
return async_1.PromiseWrapper.all(promises).then(function (nestedStyles) {
var result = plainStyles.map(function (plainStyle) { return _this._shimIfNeeded(plainStyle, encapsulate); });
nestedStyles.forEach(function (styles) { return result.push(styles); });
return result;
});
};
StyleCompiler.prototype._styleCodeGen = function (plainStyles, absUrls, shim) {
var _this = this;
var arrayPrefix = lang_1.IS_DART ? "const" : '';
var styleExpressions = plainStyles.map(function (plainStyle) { return util_1.escapeSingleQuoteString(_this._shimIfNeeded(plainStyle, shim)); });
for (var i = 0; i < absUrls.length; i++) {
var moduleUrl = this._createModuleUrl(absUrls[i], shim);
styleExpressions.push(source_module_1.moduleRef(moduleUrl) + "STYLES");
}
var expressionSource = arrayPrefix + " [" + styleExpressions.join(',') + "]";
return new source_module_1.SourceExpression([], expressionSource);
};
StyleCompiler.prototype._styleModule = function (stylesheetUrl, shim, expression) {
var moduleSource = "\n " + expression.declarations.join('\n') + "\n " + util_1.codeGenExportVariable('STYLES') + expression.expression + ";\n ";
return new source_module_1.SourceModule(this._createModuleUrl(stylesheetUrl, shim), moduleSource);
};
StyleCompiler.prototype._shimIfNeeded = function (style, shim) {
return shim ? this._shadowCss.shimCssText(style, view_factory_1.CONTENT_ATTR, view_factory_1.HOST_ATTR) : style;
};
StyleCompiler.prototype._createModuleUrl = function (stylesheetUrl, shim) {
return shim ? stylesheetUrl + ".shim" + util_1.MODULE_SUFFIX : "" + stylesheetUrl + util_1.MODULE_SUFFIX;
};
StyleCompiler = __decorate([
di_1.Injectable(),
__metadata('design:paramtypes', [xhr_1.XHR, url_resolver_1.UrlResolver])
], StyleCompiler);
return StyleCompiler;
})();
exports.StyleCompiler = StyleCompiler;
//# sourceMappingURL=style_compiler.js.map
|
import * as PIXI from 'pixi.js';
export default class ScreenManager extends PIXI.Container{
currentScreen = null;
screenList = [];
constructor(){
super();
}
addScreen(screen){
this.screenList.push(screen);
this.currentScreen = screen;
screen.screenManager = this;
}
change(screenLabel){
let tempScreen;
for(let i = 0; i < this.screenList.length; i++){
if(this.screenList[i].label == screenLabel){
tempScreen = this.screenList[i];
}
}
if(this.currentScreen){
this.currentScreen.transitionOut(tempScreen);
}
}
//change between screens
forceChange(screenLabel){
if(this.currentScreen && this.currentScreen.parent){
this.removeChild(this.currentScreen);
}
let tempScreen;
for(let i = 0; i < this.screenList.length; i++){
if(this.screenList[i].label == screenLabel){
tempScreen = this.screenList[i];
}
}
this.currentScreen = tempScreen;
this.currentScreen.build();
this.currentScreen.transitionIn();
this.addChild(this.currentScreen);
}
//update manager
update(delta){
if(this.screenList != null){
this.currentScreen.update(delta);
}
}
}
|
(function($) {
"use strict";
//windows load event
$(window).load(function() {
/* ---------------------------------------------------------------------- */
/* -------------------------- 01 - Preloader ---------------------------- */
/* ---------------------------------------------------------------------- */
$('#preloader').delay(20).fadeOut('slow');
/* ---------------------------------------------------------------------- */
/* ---------------------------- 02 - OwlCarousel ----------------------- */
/* ---------------------------------------------------------------------- */
/* latest */
$(".epi-carousel4").owlCarousel({
autoPlay: true,
items : 4,
pagination : false,
responsive : true,
itemsDesktop : [1199, 4],
itemsDesktopSmall : [979, 4],
itemsTablet : [768, 3],
itemsTabletSmall : [600, 3],
itemsMobile : [479, 3]
});
/* portfolio Logos */
$(".epi-carousel").owlCarousel({
autoPlay: true,
items : 1,
pagination : false,
navigation:true,
navigationText: [
"<span class='leftarrow'></span>",
"<span class='rightarrow'></span>"
],
responsive : false
});
});
/* -------------------------- 04 - Sticky ---------------------------- */
$(".sticky").sticky({topSpacing:0});
/* -------------------------- 06 - scrollToTop ------------------------- */
$(window).scroll(function(){
if ($(this).scrollTop() > 600) {
$('.scrollToTop').fadeIn();
} else {
$('.scrollToTop').fadeOut();
}
});
$('.scrollToTop').click(function(){
$('html, body').animate({scrollTop : 0},800);
return false;
});
/* ---------------------------------------------------------------------- */
/* -------------------------- search_btn ------------------------ */
/* ---------------------------------------------------------------------- */
$(".search_btn").click(function(){
if($(this).parent().hasClass('closed')){
$(this).parent().removeClass('closed');
$(this).parent().find('.btmsearch').slideDown(200);
} else {
$(this).parent().addClass('closed');
$(this).parent().find('.btmsearch').slideUp(200);
}
});
/* ---------------------------------------------------------------------- */
/* -------------------------- 10 - Fit Vids ----------------------------- */
/* ---------------------------------------------------------------------- */
$('#wrapper').fitVids();
/*----------------------------- selectpicker------------------*/
$('.selectpicker').selectpicker({
style: 'btn-info',
size: 4
});
/* ---------------------------------------------------------------------- */
/* -------------------------- 12 - Contact Form ------------------------- */
/* ---------------------------------------------------------------------- */
// Needed variables
var $contactform = $('#contact-form'),
$response = '';
// After contact form submit
$contactform.submit(function() {
// Hide any previous response text
$contactform.children(".alert").remove();
// Are all the fields filled in?
if (!$('#contact_name').val()) {
$response = '<div class="alert alert-danger">Please enter your name.</div>';
$('#contact_name').focus();
$contactform.prepend($response);
} else if (!$('#contact_message').val()) {
$response = '<div class="alert alert-danger">Please enter your message.</div>';
$('#contact_message').focus();
$contactform.prepend($response);
} else if (!$('#contact_email').val()) {
$response = '<div class="alert alert-danger">Please enter valid e-mail.</div>';
$('#contact_email').focus();
$contactform.prepend($response);
} else {
// Yes, submit the form to the PHP script via Ajax
$contactform.children('button[type="submit"]').button('loading');
$.ajax({
type: "POST",
url: "php/contact-form.php",
data: $(this).serialize(),
success: function(msg) {
if (msg == 'sent') {
$response = '<div class="alert alert-success">Your message has been sent. Thank you!</div>';
$contactform[0].reset();
} else {
$response = '<div class="alert alert-danger">' + msg + '</div>';
}
// Show response message
$contactform.prepend($response);
$contactform.children('button[type="submit"]').button('reset');
}
});
}
return false;
});
$("#menu-toggle").click(function(e) {
e.preventDefault();
$("body").toggleClass("toggled");
});
/* ---------------------------------------------------------------------- */
/* -------------------------- bootstrap dropdown menu ----------------------------- */
/* ---------------------------------------------------------------------- */
$('.navbar .dropdown').hover(function() {
$(this).find('.dropdown-menu').first().stop(true, true).delay(250).slideDown();
}, function() {
$(this).find('.dropdown-menu').first().stop(true, true).delay(100).slideUp();
});
$('.navbar a').click(function(){
location.href = this.href;
});
$('nav#menu').mmenu();
$("[name='my-checkbox']").bootstrapSwitch();
})(jQuery);
|
/**
* Управление галереей каталога
* @trait
* @author: keltanas
* @link http://siteforever.ru
*/
define("system/admin/catalog/gallery",[
"jquery",
"i18n",
"system/module/alert",
"jquery-ui",
"jquery-form"
], function( $, i18n, $alert ){
return {
"behavior" : {
'input.a-gallery-file' : {
"change" : function( event, node ) {
$alert('Загрузка',0,'div.a-gallery');
this.sortable("destroy");
$(node).parents('form').ajaxSubmit({
"url" : '/cataloggallery/upload',
"iframe" : true,
"success" :$.proxy(function( response ) {
$('div.a-gallery').replaceWith(response);
this.sortable();
$alert.close();
},this)
});
}
},
// удалить изображение
'a.del_gallery_image' : {
"click" : function( event, node ){
if ( ! confirm('Действительно хотите удалить изображение?') ) {
return false;
}
try {
$alert('Удаление',0,'div.a-gallery');
$.get( $(node).attr('href'), function ( response ) {
if ( response.error ) {
$alert(response.msg,0,'div.a-gallery');
return;
}
$('div.a-gallery').replaceWith(response.msg);
$alert.close();
},'json');
} catch (e) {
console.error(e.message );
}
return false;
}
},
// сделать изображение главным
'a.main_gallery_image' : {
"click" : function( event, node ){
$alert('Сохранение',0,'div.a-gallery');
$.get($(node).attr('href'), function(response){
$('div.a-gallery:first').replaceWith(response);
$alert.close();
});
return false;
}
}
},
'sortable' : function(cmd){
var $items = $('div.a-gallery>ul');
// $items.sortable({'connectWith':'div.a-gallery>ul'});
if (!cmd) {
$items.sortable({
'update' : function( event, ui ) {
var positions = [];
$(this).find('li').each(function(){
positions.push($(this).data('id'));
});
// console.log('update', positions);
$.post($('div.a-gallery').data('url'), {'positions':positions});
}
});
} else {
$items.sortable(cmd);
}
$items.disableSelection();
}
}
});
|
version https://git-lfs.github.com/spec/v1
oid sha256:dde25977f11ebaad1b89b087a2c316efb310f3d9a55dc474a560832e5ca04b65
size 2852
|
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2022 Photon Storm Ltd.
* @license {@link https://opensource.org/licenses/MIT|MIT License}
*/
/**
* Snap a value to nearest grid slice, using floor.
*
* Example: if you have an interval gap of `5` and a position of `12`... you will snap to `10`.
* As will `14` snap to `10`... but `16` will snap to `15`.
*
* @function Phaser.Math.Snap.Floor
* @since 3.0.0
*
* @param {number} value - The value to snap.
* @param {number} gap - The interval gap of the grid.
* @param {number} [start=0] - Optional starting offset for gap.
* @param {boolean} [divide=false] - If `true` it will divide the snapped value by the gap before returning.
*
* @return {number} The snapped value.
*/
var SnapFloor = function (value, gap, start, divide)
{
if (start === undefined) { start = 0; }
if (gap === 0)
{
return value;
}
value -= start;
value = gap * Math.floor(value / gap);
return (divide) ? (start + value) / gap : start + value;
};
module.exports = SnapFloor;
|
/* */
"format global";
describe('Binding: Visible', function() {
beforeEach(jasmine.prepareTestNode);
it('Should display the node only when the value is true', function () {
var observable = new ko.observable(false);
testNode.innerHTML = "<input data-bind='visible:myModelProperty()' />";
ko.applyBindings({ myModelProperty: observable }, testNode);
expect(testNode.childNodes[0].style.display).toEqual("none");
observable(true);
expect(testNode.childNodes[0].style.display).toEqual("");
});
it('Should unwrap observables implicitly', function () {
var observable = new ko.observable(false);
testNode.innerHTML = "<input data-bind='visible:myModelProperty' />";
ko.applyBindings({ myModelProperty: observable }, testNode);
expect(testNode.childNodes[0].style.display).toEqual("none");
});
});
|
var gulp = require('gulp'),
livereload = require('gulp-livereload'),
jshint = require('gulp-jshint'),
concat = require('gulp-concat'),
uglify = require('gulp-uglify'),
rename = require('gulp-rename'),
gutil = require('gulp-util'),
ngAnnotate = require('gulp-ng-annotate'),
beep = require('beepbeep'),
header = require('gulp-header'),
wrap = require("gulp-wrap"),
sass = require('gulp-sass'),
jade = require('gulp-jade'),
minifycss = require('gulp-minify-css'),
autoprefixer = require('gulp-autoprefixer'),
plumber = require('gulp-plumber');
karma = require('karma').server,
package = require('./package.json');
var dirs = {
js: {
src: './source/js',
dest: './build/js'
},
demo: {
src: './source/demo',
dest: './demo'
},
test: {
src: './source/js',
dest: './karma'
}
};
var jsHeader = [
'// Nicholas Johnson (www.nicholasjohnson.com)',
'// Forward Advance Training (www.forwardadvance.com)',
'// MIT licence'
].join('\n');
gulp.task('js', function () {
return gulp.src([dirs.js.src, '*.js'].join('/'))
.pipe(wrap('(function() {\n<%= contents %>\n})();'))
.pipe(jshint())
.pipe(jshint.reporter('default'))
.on('error', beep)
.pipe(concat(package.name + '.js'))
.pipe(ngAnnotate())
.on('error', gutil.noop)
.pipe(header(jsHeader + '\n\n'))
.pipe(gulp.dest(dirs.js.dest))
.pipe(rename(package.name + '.min.js'))
.pipe(uglify())
.on('error', gutil.noop)
.pipe(header(jsHeader + '\n\n'))
.pipe(gulp.dest(dirs.js.dest))
.pipe(livereload());
});
gulp.task('testJs', function () {
return gulp.src([dirs.test.src, '*.js'].join('/'))
.pipe(wrap(
[
'(function() {',
'<%= contents %>',
'// Smuggle locals out of closure for testing',
'window.placeholder = placeholder;',
'window.hitZones = hitZones;',
'window.widget = widget;',
'})();'
].join('\n')
))
.pipe(concat(package.name + '.testable.js'))
.pipe(ngAnnotate())
.on('error', gutil.noop)
.pipe(header(jsHeader + '\n\n'))
.pipe(gulp.dest(dirs.test.dest));
});
gulp.task('test', function (done) {
karma.start({
configFile: __dirname + '/karma.conf.js',
singleRun: true
}, done);
});
gulp.task('tdd', function (done) {
karma.start({
configFile: __dirname + '/karma.conf.js'
}, done);
});
gulp.task('demo:jade', function() {
return gulp.src([dirs.demo.src, '**', '*.jade'].join('/'))
.pipe(jade({basedir: __dirname, pretty:true}))
.on('error', gutil.log)
.pipe(gulp.dest(dirs.demo.dest));
})
gulp.task('demo:js', function() {
return gulp.src([dirs.demo.src, '**', '*.js'].join('/'))
.pipe(gulp.dest(dirs.demo.dest));
})
gulp.task('demo:sass', function() {
return gulp.src([dirs.demo.src, '**', '*.scss'].join('/'))
.pipe(sass({ style: 'expanded' }))
.pipe(autoprefixer('last 2 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1'))
.on('error', gutil.log)
.pipe(gulp.dest(dirs.demo.dest));
})
gulp.task('demo', ['demo:jade', 'demo:js', 'demo:sass']);
gulp.task('watch', function() {
gulp.watch([dirs.js.src, '**', '*.js'].join('/'), ['js', 'testJs']);
gulp.watch([dirs.demo.src, '**', '*'].join('/'), ['demo']);
});
gulp.task('default', [
'js',
'tdd',
'watch'
]);
|
import { isKeyCode } from './key-composition.js'
const handlers = []
let escDown = false
export default {
__install () {
this.__installed = true
window.addEventListener('keydown', evt => {
escDown = evt.keyCode === 27
})
window.addEventListener('blur', () => {
escDown === true && (escDown = false)
})
window.addEventListener('keyup', evt => {
if (escDown === true) {
escDown = false
if (handlers.length !== 0 && isKeyCode(evt, 27) === true) {
handlers[handlers.length - 1].fn(evt)
}
}
})
},
register (comp, fn) {
if (comp.$q.platform.is.desktop === true) {
this.__installed !== true && this.__install()
handlers.push({ comp, fn })
}
},
pop (comp) {
if (comp.$q.platform.is.desktop === true) {
const index = handlers.findIndex(h => h.comp === comp)
if (index > -1) {
handlers.splice(index, 1)
}
}
}
}
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var chai_1 = require("chai");
var InputHandler_1 = require("./InputHandler");
var TestUtils_test_1 = require("./utils/TestUtils.test");
describe('InputHandler', function () {
describe('save and restore cursor', function () {
var terminal = new TestUtils_test_1.MockInputHandlingTerminal();
terminal.buffer.x = 1;
terminal.buffer.y = 2;
var inputHandler = new InputHandler_1.InputHandler(terminal);
inputHandler.saveCursor([]);
chai_1.assert.equal(terminal.buffer.x, 1);
chai_1.assert.equal(terminal.buffer.y, 2);
terminal.buffer.x = 10;
terminal.buffer.y = 20;
inputHandler.restoreCursor([]);
chai_1.assert.equal(terminal.buffer.x, 1);
chai_1.assert.equal(terminal.buffer.y, 2);
});
describe('setCursorStyle', function () {
it('should call Terminal.setOption with correct params', function () {
var terminal = new TestUtils_test_1.MockInputHandlingTerminal();
var inputHandler = new InputHandler_1.InputHandler(terminal);
inputHandler.setCursorStyle([0]);
chai_1.assert.equal(terminal.options['cursorStyle'], 'block');
chai_1.assert.equal(terminal.options['cursorBlink'], true);
terminal.options = {};
inputHandler.setCursorStyle([1]);
chai_1.assert.equal(terminal.options['cursorStyle'], 'block');
chai_1.assert.equal(terminal.options['cursorBlink'], true);
terminal.options = {};
inputHandler.setCursorStyle([2]);
chai_1.assert.equal(terminal.options['cursorStyle'], 'block');
chai_1.assert.equal(terminal.options['cursorBlink'], false);
terminal.options = {};
inputHandler.setCursorStyle([3]);
chai_1.assert.equal(terminal.options['cursorStyle'], 'underline');
chai_1.assert.equal(terminal.options['cursorBlink'], true);
terminal.options = {};
inputHandler.setCursorStyle([4]);
chai_1.assert.equal(terminal.options['cursorStyle'], 'underline');
chai_1.assert.equal(terminal.options['cursorBlink'], false);
terminal.options = {};
inputHandler.setCursorStyle([5]);
chai_1.assert.equal(terminal.options['cursorStyle'], 'bar');
chai_1.assert.equal(terminal.options['cursorBlink'], true);
terminal.options = {};
inputHandler.setCursorStyle([6]);
chai_1.assert.equal(terminal.options['cursorStyle'], 'bar');
chai_1.assert.equal(terminal.options['cursorBlink'], false);
});
});
describe('setMode', function () {
it('should toggle Terminal.bracketedPasteMode', function () {
var terminal = new TestUtils_test_1.MockInputHandlingTerminal();
terminal.prefix = '?';
terminal.bracketedPasteMode = false;
var inputHandler = new InputHandler_1.InputHandler(terminal);
inputHandler.setMode([2004]);
chai_1.assert.equal(terminal.bracketedPasteMode, true);
inputHandler.resetMode([2004]);
chai_1.assert.equal(terminal.bracketedPasteMode, false);
});
});
});
//# sourceMappingURL=InputHandler.test.js.map
|
// Karma configuration
// Generated on Mon Nov 10 2014 19:13:16 GMT-0500 (EST)
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: ['jasmine', 'mocha'],
// list of files / patterns to load in the browser
files: [
'bower_components/angular/angular.js',
'bower_components/angular-mocks/angular-mocks.js',
'app/**/*.js',
'app/**/*-spec.js'
],
// list of files to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'app/common/directives/modform.directive.html': ['ng-html2js']
},
ngHtml2JsPreprocessor: {
stripPrefix: 'app/'
//moduleName: 'templates'
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['mocha'],
// 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_ERROR,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['PhantomJS'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false
});
};
|
if(error==1)
{
window.prompt("Dit emailadres is ongeldig.)
}
else if(error==2)
{
window.prompt("gebruikersnaam lengte is niet tussen de 3 en 12 tekens.")
}
else if(error==3)
{
window.prompt("opgegeven wachtwoord is niet tussen de 7 en 20 tekens.")
}
else if(error==4)
{
window.prompt("opgegeven voornaam is niet tussen de 2 en 22 tekens.")
}
else if(error==5)
{
window.prompt("opgegeven achternaam is niet tussen de 2 en 22 tekens.")
}
|
System.register("../../lib/ActorListener", [], function() {
"use strict";
var __moduleName = "../../lib/ActorListener";
var co = require("co");
var ActorListener = function ActorListener(actorRepos) {
this.repos = {};
this.actorRepos = actorRepos;
};
($traceurRuntime.createClass)(ActorListener, {
listen: function(actor, eventName, handleMethodName, cxt, onlyContext) {
var actorId = actor.id,
actorType = actor.typeName,
repo,
listener = {
actorId: actorId,
actorType: actorType,
handleMethodName: handleMethodName,
cxt: cxt,
onlyContext: onlyContext
};
repo = (repo = this.repos[$traceurRuntime.toProperty(eventName)]) ? this.repos[$traceurRuntime.toProperty(eventName)] : (this.repos[$traceurRuntime.toProperty(eventName)] = []);
repo.push(listener);
},
findListener: function(eventName) {
return this.repos[$traceurRuntime.toProperty(eventName)] || [];
},
emit: function(event) {
var self = this;
co($traceurRuntime.initGeneratorFunction(function $__1() {
var list,
i,
len,
listener,
actorRepo,
actor;
return $traceurRuntime.createGeneratorInstance(function($ctx) {
while (true)
switch ($ctx.state) {
case 0:
list = self.findListener(event.name);
$ctx.state = 13;
break;
case 13:
i = 0, len = list.length;
$ctx.state = 11;
break;
case 11:
$ctx.state = (i < len) ? 5 : -2;
break;
case 8:
i++;
$ctx.state = 11;
break;
case 5:
listener = list[$traceurRuntime.toProperty(i)];
actorRepo = self.actorRepos[$traceurRuntime.toProperty(listener.actorType)];
$ctx.state = 6;
break;
case 6:
$ctx.state = 2;
return actorRepo.get(listener.actorId);
case 2:
actor = $ctx.sent;
$ctx.state = 4;
break;
case 4:
if (actor) {
actor.call(listener.handleMethodName, event, null, listener.contextId);
}
$ctx.state = 8;
break;
default:
return $ctx.end();
}
}, $__1, this);
}))();
}
}, {});
module.exports = ActorListener;
return {};
});
System.get("../../lib/ActorListener" + '');
|
// @flow
import type {A} from './a';
declare var a: A;
(a: { f: string, t: number });
|
'use strict';
angular.module('lakhaanaApp.admin', [
'lakhaanaApp.auth',
'ui.router'
]);
|
'use strict';
var nconf = require('sowa-shared').nconf,
express = require('express'),
app = express();
require('./config/config')(app, express, __dirname);
app.listen(nconf.get('node_port'));
|
/** Renders form of a FormSectionGroup object
* @param document {object} - document object, usually DOM
* @param options {object} -
* {
* append {object} - domjs object to append after fieldset
* customize {function} - customization callback
* isChildEntity {boolean} - used to handle addition of child objects
* master {object} - by default section's master object
* prepend {object} - domjs object to prepend before fieldset
* url {string} - url used by the form (note: url is used to build action attribute for the form)
* }
* @returns {array} - array of constructed domjs elements
*/
'use strict';
var _ = require('mano').i18n.bind('View: Binding: Sections')
, _d = _
, d = require('d')
, db = require('mano').db
, ns = require('mano').domjs.ns
, headersMap = require('../utils/headers-map');
require('./form-section-group-to-dom-fieldset');
require('./form-section-base');
module.exports = Object.defineProperty(db.FormSectionGroup.prototype, 'toDOMForm',
d(function (document/*, options */) {
var options = Object(arguments[1])
, url = options.url || ns.url
, actionUrl = url(this.actionUrl)
, master = options.master || this.master
, customizeData = { subSections: {}, master: master }
, headerRank = options.headerRank || 2
, contentContainer
, fieldsetResult
, sectionFieldsetOptions = {
fieldsetOptions: options.fieldsetOptions,
prepend: options.prepend,
append: options.append,
master: master,
formId: this.domId,
actionUrl: null,
subSectionHeaderRank: headerRank + 1
};
if (options.isChildEntity) {
actionUrl = master.constructor.prototype === master ?
url(this.actionUrl + '-add') :
url(this.actionUrl, master.__id__);
}
sectionFieldsetOptions.actionUrl = actionUrl;
fieldsetResult = this.toDOMFieldset(document, sectionFieldsetOptions);
contentContainer = [
ns._if(this._label, [
headersMap[headerRank](this._label),
ns._if(this._legend, ns.div({ class: 'section-primary-legend' },
ns.md(this._legend.map(function (legend) {
if (!legend) return;
return _d(legend, this.getTranslations());
}.bind(this)))))]),
fieldsetResult,
this.hasOnlyTabularChildren ? null :
ns.p({ class: 'submit-placeholder input' },
ns.input({ type: 'submit', value: _("Submit") })),
ns.p({ class: 'section-primary-scroll-top' },
ns.a({ onclick: 'window.scroll(0, 0)' },
ns.span({ class: 'fa fa-arrow-up' }, "Back to top")))
];
customizeData.arrayResult = [customizeData.container = ns.section(
{ class: options.cssSectionClass === false ?
null : options.cssSectionClass || 'section-primary' },
_if(this._isDisabled, div({ class: 'entities-overview-info' }, this._disabledMessage)),
div({ class: ['disabler-range',
_if(this._isDisabled, 'disabler-active')] },
div({ class: 'disabler' }),
this.hasOnlyTabularChildren ?
contentContainer : customizeData.form = ns.form(
{
id: this.domId,
method: 'post',
action: actionUrl,
class: ns._if(ns.eq(
this._status,
1
), 'completed form-elements', 'form-elements')
},
contentContainer
))
)];
if (typeof options.customize === 'function') {
customizeData.subSections = fieldsetResult.subSections;
options.customize.call(this, customizeData);
}
return customizeData.arrayResult;
}));
|
import m from 'mithril';
import h from '../h';
import { catarse } from '../api';
import models from '../models';
/**
* @typedef {Object} Report
* @property {number} project_id
* @property {string} report_type
* @property {string} report_type_ext
* @property {string} state
* @property {string} created_at
*/
export const createProjectReportExports = async (projectId, report_type, report_type_ext) => {
return m.request({
method: 'POST',
url: `/projects/${projectId}/project_report_exports/`,
config: h.setCsrfToken,
data: {
report_type,
report_type_ext,
}
});
}
export const listProjectReportExports = (projectId) => {
models.projectReportExports.pageSize(9);
const projectReportExportsVM = catarse.paginationVM(models.projectReportExports, null, { Prefer: 'count=exact' });
const vm = h.createBasicPaginationVMWithAutoRedraw(projectReportExportsVM);
const filter = catarse.filtersVM({
project_id: 'eq'
});
filter.order({
created_at: 'desc'
});
filter.project_id(projectId);
vm.firstPage(filter.parameters());
return vm;
}
|
'use strict';
module.exports = function (app) {
/** Set all express routes here **/
//app.use('/example', require('./example.server.route'));
app.use('/', require('./index.server.route'));
};
|
/**
* Main OpenNotion JS entry point.
*/
|
// Fetch a sports salary with USA Today API
var request = require("request");
var moment = require("moment");
var url = "http://api.usatoday.com/open/salaries/mlb"
var api_key = "XXXXXX"
var params = {"players":"derek-jeter", "encoding":"json", "api_key":api_key };
request({
url: url,
json: true,
qs: params
}, function (error, response, body) {
if (!error && response.statusCode === 200) {
var data = body["salaries"];
console.log("Average Salary: " +data["average"]);
}
});
|
import { expect } from 'chai';
import nock from 'nock';
import fetch from 'node-fetch';
import FormData from 'form-data';
import API from 'lib/api';
const HOST = 'http://test';
const PATH = '/api/component';
const GATE = HOST + PATH;
describe('API', () => {
beforeEach(() => {
global.FormData = FormData;
global.fetch = fetch;
});
afterEach(() => {
delete global.FormData;
delete global.fetch;
nock.cleanAll();
});
describe('.getQueryString(path, query)', () => {
it('should return a correct path if query params are undefined', () => {
expect(API.getQueryString(GATE)).to.be.equal(GATE);
});
it('should return a path with query params', () => {
expect(API.getQueryString(GATE, {
id: [1, 2],
text: 'test'
})).to.be.equal(`${GATE}?id=1&id=2&text=test`);
});
});
describe('.get(path, query)', () => {
it('should send a GET request with a correct url', () => {
nock(HOST)
.get(PATH)
.reply(200, {});
return API.get(GATE);
});
it('should send a GET request with correct query params', () => {
let query = { id: [1, 2] };
nock(HOST)
.get(PATH)
.query(query)
.reply(200, {});
return API.get(GATE, query);
});
it('should return correct received data', () => {
let reply = { text: 'test' };
nock(HOST)
.get(PATH)
.reply(200, reply);
return API.get(GATE)
.then(data => expect(data).to.be.deep.equal(reply));
});
});
describe('.create(path, data)', () => {
it('should send a POST request with a correct url', () => {
nock(HOST)
.post(PATH)
.reply(200, {});
return API.create(GATE);
});
it('should send FormData', () => {
let formData = new FormData();
formData.append('text', 'test');
nock(HOST)
.post(PATH, body => body.includes('form-data; name="text"') && body.includes('test'))
.reply(200, {});
return API.create(GATE, formData);
});
it('should send JSON', () => {
let data = { text: 'test' };
nock(HOST)
.post(PATH, data)
.reply(200, {});
return API.create(GATE, data);
});
it('should return correct received data', () => {
let reply = { text: 'test' };
nock(HOST)
.post(PATH)
.reply(200, reply);
return API.create(GATE)
.then(data => expect(data).to.be.deep.equal(reply));
});
});
describe('.update(path, update, query)', () => {
it('should send a PUT request with a correct url', () => {
nock(HOST)
.put(PATH)
.reply(200, {});
return API.update(GATE);
});
it('should send a PUT request with correct query params', () => {
let query = { id: [1, 2] };
nock(HOST)
.put(PATH)
.query(query)
.reply(200, {});
return API.update(GATE, null, query);
});
it('should send FormData', () => {
let formData = new FormData();
formData.append('text', 'test');
nock(HOST)
.put(PATH, body => body.includes('form-data; name="text"') && body.includes('test'))
.reply(200, {});
return API.update(GATE, formData);
});
it('should send JSON', () => {
let update = { text: 'test' };
nock(HOST)
.put(PATH, update)
.reply(200, {});
return API.update(GATE, update);
});
it('should return correct received data', () => {
let reply = { text: 'test' };
nock(HOST)
.put(PATH)
.reply(200, reply);
return API.update(GATE)
.then(data => expect(data).to.be.deep.equal(reply));
});
});
describe('.remove(path, query)', () => {
it('should send a DELETE request with a correct url', () => {
nock(HOST)
.delete(PATH)
.reply(200, {});
return API.remove(GATE);
});
it('should send a DELETE request with correct query params', () => {
let query = { id: [1, 2] };
nock(HOST)
.delete(PATH)
.query(query)
.reply(200, {});
return API.remove(GATE, query);
});
it('should return correct received data', () => {
let reply = { text: 'test' };
nock(HOST)
.delete(PATH)
.reply(200, reply);
return API.remove(GATE)
.then(data => expect(data).to.be.deep.equal(reply));
});
});
});
|
export const ChatRoomType = 'CHAT';
export const SharingRoomType = 'SHARING';
export const MediaRoomType = 'MEDIA';
export const WhiteboardRoomType = 'WHITEBOARD';
|
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails react-core
*/
'use strict';
let React;
let ReactDOM;
describe('ReactError', () => {
let globalErrorMock;
beforeEach(() => {
if (!__DEV__) {
// In production, our Jest environment overrides the global Error
// class in order to decode error messages automatically. However
// this is a single test where we actually *don't* want to decode
// them. So we assert that the OriginalError exists, and temporarily
// set the global Error object back to it.
globalErrorMock = global.Error;
global.Error = globalErrorMock.OriginalError;
expect(typeof global.Error).toBe('function');
}
jest.resetModules();
React = require('react');
ReactDOM = require('react-dom');
});
afterEach(() => {
if (!__DEV__) {
global.Error = globalErrorMock;
}
});
// @gate build === "production"
// @gate !source
it('should error with minified error code', () => {
expect(() => ReactDOM.render('Hi', null)).toThrowError(
'Minified React error #200; visit ' +
'https://reactjs.org/docs/error-decoder.html?invariant=200' +
' for the full message or use the non-minified dev environment' +
' for full errors and additional helpful warnings.',
);
});
it('should serialize arguments', () => {
function Oops() {
return;
}
Oops.displayName = '#wtf';
const container = document.createElement('div');
expect(() => ReactDOM.render(<Oops />, container)).not.toThrowError();
});
});
|
import Popup from '../popup/_popup.js'
const TIMEOUT = 100
const AuTooltip = Vue.extend({
template: require('./_tooltip.jade'),
components: {
Popup
},
props: {
message: String,
position: {
type: String,
default: 'top'
},
trigger: {
type: String,
default: 'hover'
}
},
data () {
return {
timer: null
}
},
mounted () {
this.$refs.popup.setRelateElem(this.$el)
document.body.appendChild(this.$refs.popup.$el)
switch (this.trigger) {
case 'click':
this.$el.addEventListener('click', this.showPopup)
break
case 'hover':
this.$el.addEventListener('mouseover', this.delayShowPopup)
this.$el.addEventListener('mouseout', this.delayHidePopup)
break
case 'focus':
this.$el.addEventListener('focus', this.showPopup, true)
this.$el.addEventListener('blur', this.hidePopup, true)
break
}
},
methods: {
delayShowPopup () {
if (this.timer) {
clearTimeout(this.timer)
}
this.timer = setTimeout(this.showPopup, TIMEOUT)
},
delayHidePopup () {
if (this.timer) {
clearTimeout(this.timer)
}
this.timer = setTimeout(this.hidePopup, TIMEOUT)
},
showPopup () {
this.$refs.popup.show()
},
hidePopup () {
this.$refs.popup.hide()
}
}
})
Vue.component('au-tooltip', AuTooltip)
export default AuTooltip
|
export const messages = {
age: {
placeholder: {
id: 'profile.form.age.placeholder',
defaultMessage: 'age',
},
},
email: {
label: {
id: 'profile.form.email.label',
defaultMessage: 'Email',
},
placeholder: {
id: 'profile.form.email.placeholder',
defaultMessage: 'email',
},
},
emailVerified: {
label: {
id: 'profile.form.emailVerified.label',
defaultMessage: 'Status',
},
placeholder: {
id: 'profile.form.emailVerified.placeholder',
defaultMessage: 'verified',
},
},
familyName: {
placeholder: {
id: 'profile.form.familyName.placeholder',
defaultMessage: 'family name',
},
},
gender: {
label: {
id: 'profile.form.gender.label',
defaultMessage: 'Gender',
},
male: {
label: {
id: 'profile.form.gender.male.label',
defaultMessage: 'male',
},
},
female: {
label: {
id: 'profile.form.gender.female.label',
defaultMessage: 'female',
},
},
},
givenName: {
placeholder: {
id: 'profile.form.givenName.placeholder',
defaultMessage: 'given name',
},
},
locale: {
label: {
id: 'profile.form.locale.label',
defaultMessage: 'locale',
},
},
nickname: {
placeholder: {
id: 'profile.form.nickname.placeholder',
defaultMessage: 'nickname',
},
},
notes: {
label: {
id: 'profile.form.notes.label',
defaultMessage: 'notes',
},
},
reset: {
label: {
id: 'profile.form.reset.label',
defaultMessage: 'reset',
},
},
save: {
label: {
id: 'profile.form.save.label',
defaultMessage: 'save',
},
},
};
|
(function () {
tinymce.create('tinymce.plugins.UmbracoLinkPlugin', {
init: function (ed, url) {
this.editor = ed;
// Register commands
ed.addCommand('mceUmbracoLink', function () {
var se = ed.selection;
// No selection and not in link
if (se.isCollapsed() && !ed.dom.getParent(se.getNode(), 'A'))
return;
ed.windowManager.open({
file: tinyMCE.activeEditor.getParam('umbraco_mce_controller_paths')['InsertLink'],
width: 480 + parseInt(ed.getLang('advlink.delta_width', 0)),
height: 510 + parseInt(ed.getLang('advlink.delta_height', 0)),
inline: 1
}, {
plugin_url: url
});
});
// Register buttons
ed.addButton('umbracolink', {
title: 'advlink.link_desc',
cmd: 'mceUmbracoLink'
});
ed.addShortcut('ctrl+k', 'advlink.advlink_desc', 'mceUmbracoLink');
ed.onNodeChange.add(function (ed, cm, n, co) {
cm.setDisabled('umbracolink', co && n.nodeName != 'A');
cm.setActive('umbracolink', n.nodeName == 'A' && !n.name);
});
},
getInfo: function () {
return {
longname: 'Umbraco Link Plugin',
author: 'Umbraco HQ',
authorurl: 'http://umbraco.com',
infourl: 'http://umbraco.com',
version: '1.0'
};
}
});
// Register plugin
tinymce.PluginManager.add('umbracolink', tinymce.plugins.UmbracoLinkPlugin);
})();
|
(function() {
angular
.module('app')
.controller('IntroController', IntroController);
IntroController.$inject = ['nzTour', '$timeout'];
function IntroController(nzTour, $timeout){
var vm = this;
var tour = window.tour = {
config: {
mask:{
clickExit: true
}
},
steps:[{
content: "<h1>Welcome!</h1> <br>Let's get familiar with the application before we start the tutorial. <br><br> Use the <b>left/right</b> keys to go to the next/previous step. <br><br>"
},{
target: "#html",
content: "This is the HTML editor where you will be coding the V in the MVC model."
},{
target: "#app",
content: "This is the app.js where you'll build the foundation of your application."
},{
target: "#controller",
content: "This is the controller.js where you'll be creating your controller, the C in the MVC model."
},{
target: "#factory",
content: "This is the factory.js where you'll be storing data."
},{
target: '#outputBox',
content: "This is where you'll be witnessing Angular 'magic'."
},{
target: '#toggleLine',
content: "This is where you can toggle the lines on or off."
},{
target: '#test',
content: 'Click here to see the history of the prompts as you go through the tutorial.'
},{
target: '#test1',
content: 'Click here to get started! <br><br> Tip: press the <code>esc</code> key as a shortcut to display your current tutorial prompt.<br><br>'
}]
};
vm.start =function(){
nzTour.start(tour);
};
$timeout(function(){
vm.start();
}, 2000);
}
})();
// angular
// .module('app')
// .controller('IntroController', IntroController);
//
// function IntroController() {
// var vm = this;
//
//
// vm.CompletedEvent = function (scope) {
// console.log("Completed Event called");
// };
//
// vm.ExitEvent = function (scope) {
// console.log("Exit Event called");
// };
//
// vm.ChangeEvent = function (targetElement, scope) {
// console.log("Change Event called");
// console.log(targetElement); //The target element
// console.log(this); //The IntroJS object
// };
//
// vm.BeforeChangeEvent = function (targetElement, scope) {
// console.log("Before Change Event called");
// console.log(targetElement);
// };
//
// vm.AfterChangeEvent = function (targetElement, scope) {
// console.log("After Change Event called");
// console.log(targetElement);
// };
//
// vm.IntroOptions = {
// steps:[
// {
// element: document.querySelector('#step1'),
// intro: "This is the first tooltip.",
// position: 'top'
// },
//
// ],
// showStepNumbers: false,
// exitOnOverlayClick: true,
// exitOnEsc:true,
// nextLabel: '<strong>NEXT!</strong>',
// prevLabel: '<span style="color:green">Previous</span>',
// skipLabel: 'Exit',
// doneLabel: 'Thanks'
// };
//
// vm.ShouldAutoStart = false;
//
// }
|
///import core
///import plugins\paragraph.js
///commands 段间距
///commandsName RowSpacingBottom,RowSpacingTop
///commandsTitle 段间距
/**
* @description 设置段前距,段后距
* @name baidu.editor.execCommand
* @param {String} cmdName rowspacing设置段间距
* @param {String} value 值,以px为单位
* @param {String} dir top或bottom段前后段后
* @author zhanyi
*/
UE.plugins['rowspacing'] = function(){
var me = this;
me.setOpt({
'rowspacingtop':['5', '10', '15', '20', '25'],
'rowspacingbottom':['5', '10', '15', '20', '25']
});
me.commands['rowspacing'] = {
execCommand : function( cmdName,value,dir ) {
this.execCommand('paragraph','p',{style:'margin-'+dir+':'+value + 'px'});
return true;
},
queryCommandValue : function(cmdName,dir) {
var pN = domUtils.filterNodeList(this.selection.getStartElementPath(),function(node){return domUtils.isBlockElm(node) }),
value;
//trace:1026
if(pN){
value = domUtils.getComputedStyle(pN,'margin-'+dir).replace(/[^\d]/g,'');
return !value ? 0 : value;
}
return 0;
}
};
};
|
var app = angular.module('app', []);
|
import { Meteor } from 'meteor/meteor';
import s from 'underscore.string';
import { Users } from '../../../models/server';
import { Users as UsersRaw } from '../../../models/server/raw';
import { hasPermission } from '../../../authorization/server';
import { RateLimiter } from '../lib';
import { api } from '../../../../server/sdk/api';
export const _setStatusTextPromise = async function(userId, statusText) {
if (!userId) { return false; }
statusText = s.trim(statusText).substr(0, 120);
const user = await UsersRaw.findOneById(userId);
if (!user) { return false; }
if (user.statusText === statusText) { return true; }
await UsersRaw.updateStatusText(user._id, statusText);
const { _id, username, status } = user;
api.broadcast('presence.status', {
user: { _id, username, status, statusText },
});
return true;
};
export const _setStatusText = function(userId, statusText) {
statusText = s.trim(statusText);
if (statusText.length > 120) {
statusText = statusText.substr(0, 120);
}
if (!userId) {
return false;
}
const user = Users.findOneById(userId);
// User already has desired statusText, return
if (user.statusText === statusText) {
return user;
}
// Set new statusText
Users.updateStatusText(user._id, statusText);
user.statusText = statusText;
const { _id, username, status } = user;
api.broadcast('presence.status', {
user: { _id, username, status, statusText },
});
return true;
};
export const setStatusText = RateLimiter.limitFunction(_setStatusText, 5, 60000, {
0() {
// Administrators have permission to change others status, so don't limit those
return !Meteor.userId() || !hasPermission(Meteor.userId(), 'edit-other-user-info');
},
});
|
'use strict';
var request = require('request');
module.exports = function (title, cb){
if (typeof title != 'string') {
throw TypeError('Expected a string as first argument');
}
var url = 'http://www.omdbapi.com';
var qs = {t: title, plot: 'short', r: 'json'};
request({url:url, qs:qs, json:true}, function (error, response, body) {
cb(error, body);
});
};
module.exports.getByID = function (id, cb){
if (typeof id != 'string') {
throw TypeError('Expected a string as first argument');
}
var url = 'http://www.omdbapi.com';
var qs = {i: id, plot: 'short', r: 'json'};
request({url:url, qs:qs, json:true}, function (error, response, body) {
cb(error, body)
});
};
|
'use strict';
/* globals angular */
// filter that transforms image urls by adding various parameters (width height mode and/or quality).
app.filter('mediaFilter', function () {
return function (coverURL, width, height, mode, quality) {
width = angular.isNumber(width) && width > 0 ? 'img:w='+width+';' : '';
height = angular.isNumber(height) && height > 0 ? 'img:h='+height+';' : '';
quality = angular.isNumber(quality) && quality > 0 && quality <= 100 ? 'img:q='+quality+';' : '';
mode = mode ==='scale' || mode === 'crop' || mode === 'stretch' ? 'img:m='+mode+';' : '';
if (coverURL) {
var temp = document.createElement('a');
temp.href = coverURL;
var imgPath = temp.pathname.indexOf('/') === 0 ? temp.pathname : '/'+temp.pathname; // add leading slash if not present in pathname (IE bug)
coverURL = '//'+temp.hostname+'/params;'+width+height+mode+quality+'v=0'+imgPath+'.jpg'; // insert matrix params with width placeholder and append jpg extension
}
return coverURL;
};
});
|
var svgDataUrls = require("../lib");
module.exports = function (grunt) {
grunt.registerMultiTask('svgDataUrls', 'Turns SVGs into data urls', function() {
svgDataUrls(grunt, this.data)
})
}
|
describe("Ember.Test.JasmineAdapter", function() {
var adapter = Ember.Test.adapter;
it("uses the jasmine adapter", function() {
expect(adapter).toBeTypeof(Ember.Test.JasmineAdapter);
});
describe("asyncStart", function() {
beforeEach(function() {
spyOn(jasmine.Spec.prototype, "waitsFor");
adapter.asyncStart();
});
it("sets asyncRunning to true", function() {
expect(adapter.asyncRunning).toBeTrue();
});
it("calls jasmine 'waitsFor' method", function() {
expect(jasmine.Spec.prototype.waitsFor).toHaveBeenCalledWith(adapter.asyncComplete);
});
});
describe("asyncComplete", function() {
beforeEach(function() {
adapter.asyncRunning = true;
});
it("returns the boolean opposite of asyncRunning", function() {
expect(adapter.asyncComplete()).toBeFalse();
adapter.asyncRunning = false;
expect(adapter.asyncComplete()).toBeTrue();
});
});
describe("asyncEnd", function() {
beforeEach(function() {
adapter.asyncEnd();
});
it("sets asyncRunning to false", function() {
expect(adapter.asyncRunning).toBeFalse();
});
});
describe("exception", function() {
it("calls Ember.inspect with the error", function() {
adapter.exception("");
});
});
});
|
define(['./_shuffleSelf', './values'], function(shuffleSelf, values) {
/**
* The base implementation of `_.shuffle`.
*
* @private
* @param {Array|Object} collection The collection to shuffle.
* @returns {Array} Returns the new shuffled array.
*/
function baseShuffle(collection) {
return shuffleSelf(values(collection));
}
return baseShuffle;
});
|
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path d="M20 6.83V20H6.83L20 6.83M22 2L2 22h20V2z" /><path fill="none" d="M0 0h24v24H0z" /></React.Fragment>
, 'SignalCellularNull');
|
define("dojorama/ui/_global/widget/nls/FooterWidget", {
root: {}
});
|
import createSvgIcon from './utils/createSvgIcon';
import { jsx as _jsx } from "react/jsx-runtime";
export default createSvgIcon( /*#__PURE__*/_jsx("path", {
d: "M4 6H2v14c0 1.1.9 2 2 2h14v-2H4V6zm16-4H8c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-1 9H9V9h10v2zm-4 4H9v-2h6v2zm4-8H9V5h10v2z"
}), 'LibraryBooks');
|
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var React = _interopRequireWildcard(require("react"));
var _createSvgIcon = _interopRequireDefault(require("../../utils/createSvgIcon"));
/**
* @ignore - internal component.
*/
var _default = (0, _createSvgIcon.default)( /*#__PURE__*/React.createElement("path", {
d: "M8.59 16.34l4.58-4.59-4.58-4.59L10 5.75l6 6-6 6z"
}), 'KeyboardArrowRight');
exports.default = _default;
|
//= require bootstrap-sprockets
//= require portfolio/admin/markdown_preview
//= require portfolio/ajax_checkbox
|
export { default } from 'ember-time-tools/components/tt-time-picker';
|
import './drilldown.styl';
import template from './drilldown.html';
import {DrilldownController as controller} from './drilldown.controller.js';
export const drilldownDirective = ()=> {
return {
template,
controller,
restrict: 'E',
replace: true,
scope: {}
};
};
|
angular.module('ui.grid').directive('uiGridCell', ['$compile', '$parse', 'gridUtil', 'uiGridConstants', function ($compile, $parse, gridUtil, uiGridConstants) {
var uiGridCell = {
priority: 0,
scope: false,
require: '?^uiGrid',
compile: function() {
return {
pre: function($scope, $elm, $attrs, uiGridCtrl) {
function compileTemplate() {
var compiledElementFn = $scope.col.compiledElementFn;
compiledElementFn($scope, function(clonedElement, scope) {
$elm.append(clonedElement);
});
}
// If the grid controller is present, use it to get the compiled cell template function
if (uiGridCtrl && $scope.col.compiledElementFn) {
compileTemplate();
}
// No controller, compile the element manually (for unit tests)
else {
if ( uiGridCtrl && !$scope.col.compiledElementFn ){
// gridUtil.logError('Render has been called before precompile. Please log a ui-grid issue');
$scope.col.getCompiledElementFn()
.then(function (compiledElementFn) {
compiledElementFn($scope, function(clonedElement, scope) {
$elm.append(clonedElement);
});
});
}
else {
var html = $scope.col.cellTemplate
.replace(uiGridConstants.MODEL_COL_FIELD, 'row.entity.' + gridUtil.preEval($scope.col.field))
.replace(uiGridConstants.COL_FIELD, 'grid.getCellValue(row, col)');
var cellElement = $compile(html)($scope);
$elm.append(cellElement);
}
}
},
post: function($scope, $elm, $attrs, uiGridCtrl) {
$elm.addClass($scope.col.getColClass(false));
var classAdded;
var updateClass = function( grid ){
var contents = $elm;
if ( classAdded ){
contents.removeClass( classAdded );
classAdded = null;
}
if (angular.isFunction($scope.col.cellClass)) {
classAdded = $scope.col.cellClass($scope.grid, $scope.row, $scope.col, $scope.rowRenderIndex, $scope.colRenderIndex);
}
else {
classAdded = $scope.col.cellClass;
}
contents.addClass(classAdded);
};
if ($scope.col.cellClass) {
updateClass();
}
// Register a data change watch that would get triggered whenever someone edits a cell or modifies column defs
var watchUid = $scope.grid.registerDataChangeCallback( updateClass, [uiGridConstants.dataChange.COLUMN, uiGridConstants.dataChange.EDIT]);
var deregisterFunction = function() {
$scope.grid.deregisterDataChangeCallback( watchUid );
};
$scope.$on( '$destroy', deregisterFunction );
}
};
}
};
return uiGridCell;
}]);
|
import { createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
import { hashHistory } from 'react-router';
import { routerMiddleware, push } from 'react-router-redux';
import createLogger from 'redux-logger';
import rootReducer from '../reducers';
const actionCreators = {
push,
};
const logger = createLogger({
level: 'info',
collapsed: true
});
const router = routerMiddleware(hashHistory);
// If Redux DevTools Extension is installed use it, otherwise use Redux compose
/* eslint-disable no-underscore-dangle */
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ?
window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({
// Options: http://zalmoxisus.github.io/redux-devtools-extension/API/Arguments.html
actionCreators,
}) :
compose;
/* eslint-enable no-underscore-dangle */
const enhancer = composeEnhancers(
applyMiddleware(thunk, router, logger)
);
export default function configureStore(initialState: Object) {
const store = createStore(rootReducer, initialState, enhancer);
if (module.hot) {
module.hot.accept('../reducers', () =>
store.replaceReducer(require('../reducers')) // eslint-disable-line global-require
);
}
return store;
}
|
function __export(m) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
__export(require('./service/famous'));
__export(require('./core/node'));
__export(require('./core/dom-element'));
__export(require('./webgl-renderables/mesh'));
__export(require('./components/camera'));
|
(
function(){
var moduleName='serialInput';
var module={};
function connected(path,connection){
module.container.classList.remove('disabled');
module.input.disabled=false;
module.send.disabled=false;
module.clear.disabled=false;
module.connection=connection;
}
function send(data,callback){
if(!module.connection)
app.trigger(
'serial.output',
'Not connected to any serial port',
'warn'
)
chrome.serial.send(
module.connection.connectionId,
str2serial(data+'\r\n'),
function(){
}
);
}
function keyup(e){
if(e.keyCode==13)
sendInputData();
}
function sendInputData(e){
if(!e)
e={
target:{}
}
if(e.target.disabled)
return;
send(module.input.value);
module.input.value='';
}
function render(el){
module.container=el;
module.input=el.querySelector('input');
module.send=el.querySelector('#serial-send');
module.clear=el.querySelector('#serial-clear');
module.send.addEventListener(
'click',
sendInputData
);
module.clear.addEventListener(
'click',
function(e){
if(e.target.disabled)
return;
app.trigger('serial.output.clear');
}
);
module.input.addEventListener(
'keyup',
keyup
)
}
exports(moduleName,render);
app.on("serial.connection.success",connected);
}
)();
|
/*
* @name सशर्त 1
* @description शर्तें सवालों की तरह हैं।
* वे एक कार्यक्रम को एक कार्रवाई करने का निर्णय लेने की अनुमति देते हैं यदि
* किसी प्रश्न का उत्तर सत्य है या कोई अन्य क्रिया करना
* यदि प्रश्न का उत्तर गलत है।
* एक कार्यक्रम के भीतर पूछे जाने वाले प्रश्न हमेशा तार्किक होते हैं
* या संबंधपरक बयान। उदाहरण के लिए, यदि चर 'i' is
* शून्य के बराबर फिर एक रेखा खींचे।
*/
function setup() {
createCanvas(720, 360);
background(0);
for (let i = 10; i < width; i += 10) {
// यदि 'i' को 20 से विभाजित किया जाता है और कोई शेष नहीं है तो पहली पंक्ति बनाएं
// अन्यथा दूसरी पंक्ति बनाएं
if (i % 20 === 0) {
stroke(255);
line(i, 80, i, height / 2);
} else {
stroke(153);
line(i, 20, i, 180);
}
}
}
|
/*******************************************************************************
* Copyright (c) 2014 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
define([ 'dojo/_base/declare', '../ObservableResource', 'jsExplore/utils/ID' ],
function(declare, ObservableResource, ID) {
/**
* Hosts represents a collection of Host objects. The values stored in Hosts are a high-level tally
* of the number of hosts which are considered to have all servers running (up), all servers stopped (down),
* some servers running (partial), all servers unknown (unknown) and no servers (empty). The list of
* host IDs is also stored. The direct Host objects are not stored as that would require a very large
* amount of memory in a large collective topology.
*
* The Hosts collection is created based on the REST API response. See the ResourceManager
* for details on how the REST API response is converted to the initialization object.
*
* The cumulative public attributes for Hosts are as follows:
* @class
* @typedef {Object} Hosts
* @property {string} id - The resource's unique ID within the set of same type
* @property {string} type - The resource's type
* @property {number} up - The number of hosts that are considered to have all servers running
* @property {number} down - The number of hosts that are considered to have all servers stopped
* @property {number} unknown - The number of hosts that are considered to have all servers in an unknown state
* @property {number} partial - The number of hosts that are considered to have some servers running
* @property {number} empty - The number of hosts that are considered to have no servers at all
* @property {Array.<string>} list - The list of host IDs. The list will have no duplicate values.
*/
return declare('Hosts', [ObservableResource], {
/** Hard-code the id and type to be 'hosts' **/
/** @type {string} */ id: ID.getHosts(),
/** @type {string} */ type: 'hosts',
/** Set during construction and handleChangeEvent **/
/** @type {number} */ up: 0,
/** @type {number} */ down: 0,
/** @type {number} */ unknown: 0,
/** @type {number} */ partial: 0,
/** @type {number} */ empty: 0,
/** @type {Array.<string>} */ list: [],
/**
* Construct the initial Hosts state.
*
* @param {Object} init The initialization object
*/
constructor: function(init) {
if (!init) { this._throwError('Hosts created without an initialization object'); }
(init.up >= 0) ? this.up = init.up : this._throwError('Hosts created without an initial up tally');
(init.down >= 0) ? this.down = init.down : this._throwError('Hosts created without an initial down tally');
(init.unknown >= 0) ? this.unknown = init.unknown : this._throwError('Hosts created without an initial unknown tally');
(init.partial >= 0) ? this.partial = init.partial : this._throwError('Hosts created without an initial partial tally');
(init.empty >= 0) ? this.empty = init.empty : this._throwError('Hosts created without an initial empty tally');
(Array.isArray(init.list)) ? this.list = init.list : this._throwError('Hosts created without an initial list of host names');
},
/**
* Handle a change event for this resource.
*
* The event can have the following properties:
* Hosts Event {
* type: 'hosts',
* up, down, unknown, partial, empty,
* added: [ "name" ] (optional),
* removed: [ "name" ] (optional)
* }
*
* If the inbound event has the wrong type, the event is ignored. This does not provide any sort of security,
* but does guard against programming errors and will make the code more serviceable / robust.
*
* The following observer methods may be called:
* -- onTallyChange(newTally, oldTally) - parameters are objects: {up, down, unknown, partial, empty}
* -- onListChange(newList, oldList, added, removed) - parameters are Array.<string>
*
* @param {Object} e The received Hosts Event object
*/
_handleChangeEvent: function(e) {
console.log('Hosts got an event!', e);
if (e.type !== this.type) {
console.error('Hosts got an event which did not have the correct type. The event will be ignored. Received event type: ' + e.type);
return;
}
this._updateArray('onListChange', this.list, e.added, e.removed);
this._updateTally('onTallyChange', e, this, ['up', 'down', 'unknown', 'partial', 'empty']);
}
});
});
|
/*******************************************************************************
* Copyright (c) 2014 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
/* jshint strict: false */
define([
"jsExplore/resources/stats/_jvmStats",
"jsExplore/utils/ID",
"dojo/_base/declare",
"dojo/_base/lang",
"dojo/json",
"dojo/dom-construct",
"dojo/number",
"./ExploreGraph",
"dijit/_TemplatedMixin",
"dijit/_WidgetsInTemplateMixin",
"dojo/i18n!jsExplore/nls/explorerMessages",
"dojo/text!./templates/ProcessCPUGraph.html"
], function(
jvmStats,
ID,
declare,
lang,
JSON,
domConstruct,
number,
ExploreGraph,
_TemplatedMixin,
_WidgetsInTemplateMixin,
i18n,
template
){
var ProcessCPUGraph = declare("ProcessCPUGraph", [ ExploreGraph, _TemplatedMixin, _WidgetsInTemplateMixin ], {
constructor : function(params) { // resourceName
this.chartId = this.server.name + ID.getProcessCPUStatsUpper();
this.chartNodeId = this.chartId + ID.getChartNode();
this.legendNodeId = this.chartId + ID.getLegendNode();
this.idLiveMsgDetailNode = ID.underscoreDelimit(this.id, ID.getLiveMsgDetailNode());
this.title = i18n.STATS_PROCESSCPU_TITLE;
this.yAxisTitle = i18n.STATS_PROCESSCPU_Y_PERCENT;
},
graphKey : "ProcessCPUStats",
loadValue : -1,
loadLabel : i18n.STATS_PROCESSCPU_USAGE,
templateString : template,
postCreate : function() {
this.inherited(arguments);
this.yDomain = [0,100];
this.yAxisTickSuffix = "%";
},
generateHistoricalData: function() {
this.chartData = [];
this.intervalHandle = setInterval(lang.hitch(this, function() {
if (this.chartData.length >= this.numberOfSnapshots) {
this.chartData.shift();
}
jvmStats.getCPUUsage(this.server).then(lang.hitch(this, function(response) {
var responseObj = null;
try {
responseObj = JSON.parse(response);
} catch(e) {
console.error(response);
return;
}
// Check to see if the loadNode exists or not. When the User has navigated away from the stats pane, the divs
// can get removed, and our repeating MBean call can try and write data to a non-existent div.
if (! responseObj.ProcessCpuLoad) {
// If there hasn't been any data returned yet, it should be safe to stop polling.
// Otherwise, just do nothing and let it come around again. Hopefully the next call will
// return data.
if (this.chartData.length < 2) {
this.stopPolling();
domConstruct.empty(this.laChartNode);
if (this.loadNode) {
this.loadNode.innerHTML ="";
}
var warningMsg = new GraphWarningMessage({}, this.laChartNode);
warningMsg.setTextMessage(i18n.NO_CPU_STATS_AVAILABLE);
}
} else {
this.loadValue = (responseObj.ProcessCpuLoad * 100);
if (this.loadValue < 0) {
this.loadValue = 0;
}
if (this.loadNode) {
this.loadNode.innerHTML = lang.replace(this.loadLabel, [number.format(this.loadValue, {
places: 1
})]);
};
this.addDataPointAndRender(this.loadValue);
}
}));
}), this.interval);
}
});
return ProcessCPUGraph;
});
|
(function ($) {
$.mobiscroll.themes['ios-classic'] = {
display: 'bottom',
dateOrder: 'MMdyy',
rows: 5,
height: 30,
minWidth: 60,
headerText: false,
showLabel: false,
btnWidth: false,
selectedLineHeight: true,
selectedLineBorder: 2,
useShortLabels: true
};
})(jQuery);
|
var Options = Backbone.Collection.extend({
model: Option
});
|
/*
* metismenu - v1.1.3
* Easy menu jQuery plugin for Twitter Bootstrap 3
* https://github.com/onokumus/metisMenu
*
* Made by Osman Nuri Okumus
* Under MIT License
*/
;(function($, window, document, undefined) {
var pluginName = "metisMenu",
defaults = {
toggle: true,
doubleTapToGo: false,
cookieName: "MetisMenuState",
cookieExpiration: 1 //Number of days
};
function Plugin(element, options) {
this.element = $(element);
this.settings = $.extend({}, defaults, options);
this._defaults = defaults;
this._name = pluginName;
this.init();
}
Plugin.prototype = {
init: function() {
var $this = this.element,
$toggle = this.settings.toggle,
$cookieName = this.settings.cookieName,
$cookieExpiration = this.settings.cookieExpiration;
obj = this;
//Restores the menu state from cookies
var documentCookie = document.cookie;
$this.find("li").has("ul").each(function (i) {
var pos = documentCookie.indexOf($cookieName + "_" + i + "=");
if (pos > -1) {
documentCookie.substr(pos).split("=")[1].indexOf("false") ? $(this).addClass("active") : $(this).removeClass("active");
}
});
if (this.isIE() <= 9) {
$this.find("li.active").has("ul").children("ul").collapse("show");
$this.find("li").not(".active").has("ul").children("ul").collapse("hide");
} else {
$this.find("li.active").has("ul").children("ul").addClass("collapse in");
$this.find("li").not(".active").has("ul").children("ul").addClass("collapse");
}
//add the "doubleTapToGo" class to active items if needed
if (obj.settings.doubleTapToGo) {
$this.find("li.active").has("ul").children("a").addClass("doubleTapToGo");
}
$this.find("li").has("ul").children("a").on("click" + "." + pluginName, function(e) {
e.preventDefault();
//Do we need to enable the double tap
if (obj.settings.doubleTapToGo) {
//if we hit a second time on the link and the href is valid, navigate to that url
if (obj.doubleTapToGo($(this)) && $(this).attr("href") !== "#" && $(this).attr("href") !== "") {
e.stopPropagation();
document.location = $(this).attr("href");
return;
}
}
$(this).parent("li").toggleClass("active").children("ul").collapse("toggle");
if ($toggle) {
$(this).parent("li").siblings().removeClass("active").children("ul.in").collapse("hide");
}
//Deletes all cookies
var cookies = document.cookie.split(";");
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i];
var eqPos = cookie.indexOf("=");
var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
if (name.trim().slice(0, $cookieName.length) === $cookieName) {
document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/";
}
}
//Stores the menu state in cookies
var date = new Date();
date.setTime(date.getTime() + ($cookieExpiration * 24 * 60 * 60 * 1000));
$this.find("li").has("ul").each(function (i) {
document.cookie = $cookieName + "_" + i + "=" + $(this).hasClass("active") + ";expires=" + date.toGMTString() + ";path=/";
});
});
},
isIE: function() { //https://gist.github.com/padolsey/527683
var undef,
v = 3,
div = document.createElement("div"),
all = div.getElementsByTagName("i");
while (
div.innerHTML = "<!--[if gt IE " + (++v) + "]><i></i><![endif]-->",
all[0]
) {
return v > 4 ? v : undef;
}
},
//Enable the link on the second click.
doubleTapToGo: function(elem) {
var $this = this.element;
//if the class "doubleTapToGo" exists, remove it and return
if (elem.hasClass("doubleTapToGo")) {
elem.removeClass("doubleTapToGo");
return true;
}
//does not exists, add a new class and return false
if (elem.parent().children("ul").length) {
//first remove all other class
$this.find(".doubleTapToGo").removeClass("doubleTapToGo");
//add the class on the current element
elem.addClass("doubleTapToGo");
return false;
}
},
remove: function() {
this.element.off("." + pluginName);
this.element.removeData(pluginName);
}
};
/*$.fn[pluginName] = function(options) {
this.each(function () {
var el = $(this);
if (el.data(pluginName)) {
el.data(pluginName).remove();
}
el.data(pluginName, new Plugin(this, options));
});
return this;
};*/
$.fn[ pluginName ] = function (options) {
return this.each(function () {
if (!$.data(this, "plugin_" + pluginName)) {
$.data(this, "plugin_" + pluginName, new Plugin(this, options));
}
});
};
})(jQuery, window, document);
|
/**
* Czech lang variables
* encoding: utf-8
*
* $Id: cs.js,v 1.4 2006/01/11 14:25:47 spocke Exp $
*/
tinyMCE.addToLang('advimage',{
tab_general : 'Obecné',
tab_appearance : 'Vzhled',
tab_advanced : 'Pokročilé',
general : 'Obecné',
title : 'Titulek',
preview : 'Náhled',
constrain_proportions : 'Zachovat rozměry',
langdir : 'Směr textu',
langcode : 'Kód jazyka',
long_desc : 'Dlouhý popis odkazu',
style : 'Styl',
classes : 'Třídy',
ltr : 'Z leva doprava',
rtl : 'Z prava doleva',
id : 'Id',
image_map : 'Obrázková mapa',
swap_image : 'Přepnout obrázek',
alt_image : 'Alternativní obrázek',
mouseover : 'pro přejetí myší',
mouseout : 'pro odjetí myší',
misc : 'Různé',
example_img : 'Vzhled náhled obrázek',
missing_alt : 'Jste si jistý(á), že chcete pokračovat bez vyplnění popisu obrázku? Bez popisu může být obrázek nepřístupný handicapovaným uživatelům, nebo těm kteří používají textový prohlížeč, nebo prohlíží stránky s vypnutým obrázky.'
});
|
/**
* External dependencies
*/
import { uniqueId } from 'lodash';
/**
* WordPress dependencies
*/
import { select as selectData, dispatch as dispatchData } from '@wordpress/data';
import { default as triggerApiFetch } from '@wordpress/api-fetch';
/**
* Internal dependencies
*/
import responseToError from '@ithemes/security-utils';
/**
* Trigger an API Fetch request.
*
* @param {Object} request API Fetch Request Object.
* @return {Object} control descriptor.
*/
export function apiFetch( request ) {
return {
type: 'API_FETCH',
request,
};
}
/**
* Calls a selector using the current state.
* @param {string} selectorName Selector name.
* @param {Array} args Selector arguments.
*
* @return {Object} control descriptor.
*/
export function select( selectorName, ...args ) {
return {
type: 'SELECT',
selectorName,
args,
};
}
/**
* Yields action objects used in signalling that a notice is to be created.
*
* @see @wordpress/notices#createNotice()
*
* @param {?string} status Notice status.
* Defaults to `info`.
* @param {string} content Notice message.
* @param {?Object} options Notice options.
* @param {?string} options.context Context under which to
* group notice.
* @param {?string} options.id Identifier for notice.
* Automatically assigned
* if not specified.
* @param {?boolean} options.isDismissible Whether the notice can
* be dismissed by user.
* Defaults to `true`.
* @param {?number} options.autoDismiss Whether the notice should
* by automatically dismissed
* after x milliseconds.
* Defaults to `false`.
* @param {?Array<WPNoticeAction>} options.actions User actions to be
* presented with notice.
*
* @return {Object} control descriptor.
*/
export function createNotice( status = 'info', content, options = {} ) {
return {
type: 'CREATE_NOTICE',
status,
content,
options: {
context: 'ithemes-security',
...options,
},
};
}
const controls = {
API_FETCH( { request } ) {
return triggerApiFetch( request ).catch( responseToError );
},
SELECT( { selectorName, args } ) {
return selectData( 'ithemes-security/admin-notices' )[ selectorName ]( ...args );
},
CREATE_NOTICE( { status, content, options } ) {
if ( options.autoDismiss ) {
options.id = options.id || uniqueId( 'itsec-auto-dismiss-' );
setTimeout( () => dispatchData( 'core/notices' ).removeNotice( options.id, options.context ), options.autoDismiss );
}
dispatchData( 'core/notices' ).createNotice( status, content, options );
},
};
export default controls;
|
function recursiveAnimationFrame(frames, callback) {
if (window && frames && Number.isInteger(frames) && frames > 0) {
window.requestAnimationFrame(() => {
recursiveAnimationFrame(frames - 1, callback);
});
return;
}
callback();
}
export function setCssEndEvent(
element,
type,
{ tolerance = 0, propertyName } = {}
) {
return new Promise(resolve => {
if (!element) {
resolve(false);
return;
}
let eventName = null;
const capitalized = type.charAt(0).toUpperCase() + type.slice(1);
let run = 0;
function end(event) {
const target = event.srcElement || event.target;
if (target === element) {
if (run >= tolerance) {
if (propertyName && propertyName !== event.propertyName) {
return;
}
element.removeEventListener(eventName, end);
resolve(event);
}
run += 1;
}
}
if (element.style[`Webkit${capitalized}`] !== undefined) {
eventName = `webkit${capitalized}End`;
}
if (element.style.OTransition !== undefined) {
eventName = `o${type}End`;
}
if (element.style[type] !== undefined) {
eventName = `${type}end`;
}
if (element.clearCssEndEvent) {
element.clearCssEndEvent();
}
element.clearCssEndEvent = function() {
element.removeEventListener(eventName, end);
};
element.addEventListener(eventName, end);
});
}
export function beforeCssLayout(callback) {
window && window.requestAnimationFrame(callback);
}
export function beforeNextCssLayout(callback) {
window &&
window.requestAnimationFrame(() => {
window.requestAnimationFrame(callback);
});
}
export function beforeFutureCssLayout(frames, callback) {
recursiveAnimationFrame(frames + 1, callback);
}
export function onceNextCssLayout() {
return new Promise(resolve => {
beforeNextCssLayout(resolve);
});
}
export function onceTransitionEnd(element, options = {}) {
return new Promise(resolve => {
setCssEndEvent(element, "transition", options).then(resolve);
});
}
export function onceAnimationEnd(element, options = {}) {
return new Promise(resolve => {
setCssEndEvent(element, "animation", options).then(resolve);
});
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.