text
stringlengths 2
6.14k
|
|---|
E2.p = E2.plugins["assets_started_generator"] = function(core, node)
{
this.desc = 'Emits the current number of assets that have begun loading.';
this.input_slots = [];
this.output_slots = [
{ name: 'count', dt: core.datatypes.FLOAT, desc: 'Number of assets that have begun loading.' }
];
this.core = core;
this.node = node;
this.asset_listener = function(self) { return function()
{
self.node.queued_update = 1;
}}(this);
core.asset_tracker.add_listener(this.asset_listener);
};
E2.p.prototype.reset = function()
{
};
E2.p.prototype.destroy = function()
{
this.core.asset_tracker.remove_listener(this.asset_listener);
};
E2.p.prototype.update_output = function(slot)
{
return this.core.asset_tracker.started;
};
|
import {createItemSelector} from 'collections';
import {memoizedSelector} from 'utils';
const selector = createItemSelector('widgets');
export function widgetAttributes({role}) {
return memoizedSelector(
selector({id: role}),
widget => widget
);
}
|
'use strict';
let path = require('path');
let defaultSettings = require('./defaults');
// Additional npm or bower modules to include in builds
// Add all foreign plugins you may need into this array
// @example:
// let npmBase = path.join(__dirname, '../node_modules');
// let additionalPaths = [ path.join(npmBase, 'react-bootstrap') ];
const npmBase = path.join(__dirname, '../node_modules');
const additionalPaths = [ path.join(npmBase, 'pouch-redux-middleware')];
module.exports = {
additionalPaths: additionalPaths,
port: defaultSettings.port,
debug: true,
devtool: 'eval',
output: {
path: path.join(__dirname, '/../dist/assets'),
filename: 'app.js',
publicPath: defaultSettings.publicPath
},
devServer: {
contentBase: './src/',
historyApiFallback: true,
hot: true,
port: defaultSettings.port,
publicPath: defaultSettings.publicPath,
noInfo: false
},
resolve: {
extensions: ['', '.js', '.jsx'],
alias: {
actions: `${defaultSettings.srcPath}/actions/`,
components: `${defaultSettings.srcPath}/components/`,
sources: `${defaultSettings.srcPath}/sources/`,
stores: `${defaultSettings.srcPath}/stores/`,
styles: `${defaultSettings.srcPath}/styles/`,
config: `${defaultSettings.srcPath}/config/` + process.env.REACT_WEBPACK_ENV
}
},
module: {}
};
|
{
"name": "Chillin.js",
"url": "https://github.com/frantzmiccoli/Chillin.js.git"
}
|
'use strict';
describe('portfolio.version module', function() {
beforeEach(module('portfolio.version'));
describe('app-version directive', function() {
it('should print current version', function() {
module(function($provide) {
$provide.value('version', 'TEST_VER');
});
inject(function($compile, $rootScope) {
var element = $compile('<span app-version></span>')($rootScope);
expect(element.text()).toEqual('TEST_VER');
});
});
});
});
|
/**
* Main application file
*/
'use strict';
// Set default node environment to development
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
var express = require('express');
var mongoose = require('mongoose');
var config = require('./config/environment');
// Connect to database
mongoose.connect(config.mongo.uri, config.mongo.options);
// Populate DB with sample data
if (config.seedDB) {
require('./config/seed');
}
// Setup server
var app = express();
var server = require('http').createServer(app);
var socketio = require('socket.io')(server, {
serveClient: (config.env === 'production') ? false : true,
path: '/socket.io-client'
});
require('./config/socketio')(socketio);
require('./config/express')(app);
require('./routes')(app);
// Start server
server.listen(config.port, config.ip, function () {
console.log('Express server listening on %d, in %s mode', config.port, app.get('env'));
});
// Expose app
exports = module.exports = app;
|
pageflow.AudioPlayer.getMediaElementMethod = function(player) {
player.getMediaElement = function() {
return player.audio.audio;
};
};
|
var http = require('http'),
browserify = require('browserify'),
literalify = require('literalify'),
React = require('react');
var App = require('./app');
http.createServer(function(req, res) {
if (req.url == '/') {
res.setHeader('Content-Type', 'text/html');
var props = {
items: [
'Item 0',
'Item 1'
]
};
var html = React.renderToStaticMarkup(
<body>
<div id="content" dangerouslySetInnerHTML={{__html:
React.renderToString(<App items={props.items}/>)
}} />,
<script dangerouslySetInnerHTML={{__html:
'var APP_PROPS = ' + JSON.stringify(props) + ';'
}}/>
<script src="//fb.me/react-0.13.1.min.js"/>
<script src="/bundle.js"/>
</body>
);
res.end(html);
} else if (req.url == '/bundle.js') {
res.setHeader('Content-Type', 'text/javascript');
browserify()
.add('./browser.js')
.transform(literalify.configure({react: 'window.React'}))
.bundle()
.pipe(res);
} else {
res.statusCode = 404;
res.end();
}
}).listen(3000, function(err) {
if (err) throw err;
console.log('Listening on 3000...');
})
|
import Ember from 'ember';
import layout from '../../templates/components/one-way-select/option';
const {
Component
} = Ember;
export default Component.extend({
layout,
tagName: ''
});
|
const gulp = require('gulp');
const babel = require('gulp-babel');
const gdt = require('gulp-dev-tasks');
const eslintrc = require('./.eslintrc.json');
gdt.setRules(eslintrc.rules);
gulp.task('build', () =>
gulp.src('src/**/*.js')
.pipe(babel({ presets: ['es2015', 'stage-2'] }))
.pipe(gulp.dest('build/'))
);
gulp.task('default', ['lint', 'build'], () => {
gulp.watch('src/**/*.js', ['lint', 'build']);
});
|
import peek42 from './browser/peek42';
export default peek42;
|
var favicon = require('./includes/favicon.js');
var feed = require('./includes/feed.js');
var retrofitIcon = function (f, callback) {
console.log("Checking ", f.htmlUrl);
favicon.find(f.htmlUrl, function (favicon_url) {
f.icon = favicon_url;
feed.update(f, function (err, data) {
callback(err, data);
});
});
};
// retrofit "icon" image urls to each feed
feed.readAll(function (allFeeds) {
var i = 0,
f = {};
console.log("Finding favicons for ", allFeeds.length, " feeds.");
for (i = 0; i < allFeeds.length; i++) {
f = allFeeds[i];
if (typeof f.icon === "undefined" || f.icon === null) {
retrofitIcon(f, function (err, data) {
console.log(err, data);
});
}
}
});
|
/**
* Zepernick jQuery plugins
*/
(function($) {
$.fn.dataTableSearch = function(delay) {
//console.log("data table search plugin...");
var dt = this;
this.find("thead input").on( 'keyup', function (event) {
getInput = function() {
return $(event.target);
};
$z.delay(delay, function() {
var td = getInput().closest("td");
var index = td.index();
//console.log("index is " + index);
dt.DataTable()
.columns(index)
.search(getInput().val())
.draw();
});
});
return this;
};
function delay(){
var timer = 0;
return function(ms, callback){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
};
})(jQuery);
|
const path = require('path');
const webpack = require('webpack');
module.exports = {
devtool: 'cheap-module-eval-source-map',
entry: './index.js',
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/static/'
},
module: {
loaders: [
{
test: /\.js?$/,
loaders: ['babel'],
exclude: /node_modules/,
},
{
test: /\.css$/,
loaders: 'style-loader!css-loaders',
}
]
}
}
|
const request = require('request-promise')
const config = require('../tool/config.js')
const api = require('../tool/api.js')
const error = require('../tool/error.js')
const Const = require('../tool/const.js')
const exp = {
URL : '/authenticate',
ACTION : (req, res) => {
try {
const params = req.body
if (!params || !params.login || !params.password) {
error.fn401(res, 'incorrect params')
return
}
options = {
method: 'POST',
uri: api.getUrl(exp.URL),
form: {
login: params.login,
password: params.password
},
headers: {
'User-Agent': 'Request-Promise',
},
json: true
}
request(options)
.then((data) => {
res.json({
success : true,
token : data.token,
user : data.user
})
})
.catch((err) => {
if (err.statusCode == 401)
error.fn401(res, 'Authentication failed')
else
error.fn500(res, err)
})
} catch(ex) {
error.fn500(res, ex)
}
}
}
module.exports = exp
|
define(['./_baseFindIndex', './_baseIsNaN', './_strictLastIndexOf', './toInteger'], function(baseFindIndex, baseIsNaN, strictLastIndexOf, toInteger) {
/** Used as a safe reference for `undefined` in pre-ES5 environments. */
var undefined;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max,
nativeMin = Math.min;
/**
* This method is like `_.indexOf` except that it iterates over elements of
* `array` from right to left.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @param {number} [fromIndex=array.length-1] The index to search from.
* @returns {number} Returns the index of the matched value, else `-1`.
* @example
*
* _.lastIndexOf([1, 2, 1, 2], 2);
* // => 3
*
* // Search from the `fromIndex`.
* _.lastIndexOf([1, 2, 1, 2], 2, 2);
* // => 1
*/
function lastIndexOf(array, value, fromIndex) {
var length = array ? array.length : 0;
if (!length) {
return -1;
}
var index = length;
if (fromIndex !== undefined) {
index = toInteger(fromIndex);
index = index < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1);
}
return value === value
? strictLastIndexOf(array, value, index)
: baseFindIndex(array, baseIsNaN, index, true);
}
return lastIndexOf;
});
|
version https://git-lfs.github.com/spec/v1
oid sha256:0680588e6712ebab3160ef2c9e5754716d6d2d05b09790964fe828cba5abf8e2
size 2189
|
/**
* @module Joy
*/
/**
* This class is used on SpriteSheet's `animations` attribute.
*
* @class SpriteAnimation
* @constructor
*/
var SpriteAnimation = function (options) {
/**
* @attribute parent
* @type {SpriteSheet}
*/
this.parent = options.parent;
/**
* @attribute name
* @type {String}
*/
this.name = options.name;
/**
* @attribute framesPerSecond
* @type {Number}
*/
this.framesPerSecond = options.framesPerSecond;
/**
* @attribute frames
* @type {Array}
*/
this.frames = options.frames;
/**
* @attribute firstFrame
* @type {Number}
*/
this.firstFrame = this.frames[0];
/**
* @attribute lastFrame
* @type {Number}
*/
this.lastFrame = lastFrame = this.frames[1] || this.frames[0];
/**
* @attribute currentFrame
* @type {Number}
*/
this.currentFrame = 0;
};
/**
* Start the animation
* @method start
*/
SpriteAnimation.prototype.start = function () {
this.currentFrame = this.firstFrame;
// Create the interval to change through frames
var self = this;
this._interval = setInterval(function(){ self.update(); }, 1000 / this.framesPerSecond);
};
/**
* Stops the animation
* @method stop
*/
SpriteAnimation.prototype.stop = function () {
if (this._interval) {
clearInterval(this._interval);
}
return this;
};
/**
* Update frame animation
* @method update
*/
SpriteAnimation.prototype.update = function () {
if (this.currentFrame == this.lastFrame) {
this.currentFrame = this.firstFrame;
// Reached the first frame, trigger animation start callback.
this.parent.trigger('animationStart');
} else {
this.currentFrame = this.currentFrame + 1;
// Reached the last frame, trigger animation end callback.
if (this.currentFrame == this.lastFrame) {
this.parent.trigger('animationEnd');
}
}
};
module.exports = SpriteAnimation;
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
'use strict';
module.metadata = {
'stability': 'experimental',
'engines': {
'Firefox': '> 28'
}
};
const { Class } = require('../../core/heritage');
const { merge } = require('../../util/object');
const { Disposable } = require('../../core/disposable');
const { on, off, emit, setListeners } = require('../../event/core');
const { EventTarget } = require('../../event/target');
const { getNodeView } = require('../../view/core');
const view = require('./view');
const { toggleButtonContract, toggleStateContract } = require('./contract');
const { properties, render, state, register, unregister,
setStateFor, getStateFor, getDerivedStateFor } = require('../state');
const { events: stateEvents } = require('../state/events');
const { events: viewEvents } = require('./view/events');
const events = require('../../event/utils');
const { getActiveTab } = require('../../tabs/utils');
const { id: addonID } = require('../../self');
const { identify } = require('../id');
const buttons = new Map();
const toWidgetId = id =>
('toggle-button--' + addonID.toLowerCase()+ '-' + id).
replace(/[^a-z0-9_-]/g, '');
const ToggleButton = Class({
extends: EventTarget,
implements: [
properties(toggleStateContract),
state(toggleStateContract),
Disposable
],
setup: function setup(options) {
let state = merge({
disabled: false,
checked: false
}, toggleButtonContract(options));
let id = toWidgetId(options.id);
register(this, state);
// Setup listeners.
setListeners(this, options);
buttons.set(id, this);
view.create(merge({ type: 'checkbox' }, state, { id: id }));
},
dispose: function dispose() {
let id = toWidgetId(this.id);
buttons.delete(id);
off(this);
view.dispose(id);
unregister(this);
},
get id() {
return this.state().id;
},
click: function click() {
return view.click(toWidgetId(this.id));
}
});
exports.ToggleButton = ToggleButton;
identify.define(ToggleButton, ({id}) => toWidgetId(id));
getNodeView.define(ToggleButton, button =>
view.nodeFor(toWidgetId(button.id))
);
var toggleButtonStateEvents = events.filter(stateEvents,
e => e.target instanceof ToggleButton);
var toggleButtonViewEvents = events.filter(viewEvents,
e => buttons.has(e.target));
var clickEvents = events.filter(toggleButtonViewEvents, e => e.type === 'click');
var updateEvents = events.filter(toggleButtonViewEvents, e => e.type === 'update');
on(toggleButtonStateEvents, 'data', ({target, window, state}) => {
let id = toWidgetId(target.id);
view.setIcon(id, window, state.icon);
view.setLabel(id, window, state.label);
view.setDisabled(id, window, state.disabled);
view.setChecked(id, window, state.checked);
view.setBadge(id, window, state.badge, state.badgeColor);
});
on(clickEvents, 'data', ({target: id, window, checked }) => {
let button = buttons.get(id);
let windowState = getStateFor(button, window);
let newWindowState = merge({}, windowState, { checked: checked });
setStateFor(button, window, newWindowState);
let state = getDerivedStateFor(button, getActiveTab(window));
emit(button, 'click', state);
emit(button, 'change', state);
});
on(updateEvents, 'data', ({target: id, window}) => {
render(buttons.get(id), window);
});
|
import {CssAnimator} from '../src/animator';
import {animationEvent} from 'aurelia-templating';
jasmine.getFixtures().fixturesPath = 'base/test/fixtures/';
describe('animator-css', () => {
var sut;
beforeEach(() => {
sut = new CssAnimator();
});
describe('runSequence function', () => {
var elems;
beforeEach(() => {
loadFixtures('run-sequence.html');
elems = $('.sequenced-items li');
});
it('should run multiple animations one after another', (done) => {
var testClass = 'animate-test';
sut.runSequence([
{ element: elems.eq(0)[0], className: testClass },
{ element: elems.eq(1)[0], className: testClass },
{ element: elems.eq(2)[0], className: testClass }
]).then( () => {
expect(elems.eq(0).css('opacity')).toBe('1');
expect(elems.eq(1).css('opacity')).toBe('1');
expect(elems.eq(2).css('opacity')).toBe('1');
done();
});
});
it('should fire sequence DOM events', () => {
var beginFired = false
, doneFired = false
, listenerBegin = document.addEventListener(animationEvent.sequenceBegin, () => beginFired = true)
, listenerDone = document.addEventListener(animationEvent.sequenceDone, () => doneFired = true);
var testClass = 'animate-test';
sut.runSequence([
{ element: elems.eq(0)[0], className: testClass },
{ element: elems.eq(1)[0], className: testClass },
{ element: elems.eq(2)[0], className: testClass }
]).then( () => {
document.removeEventListener(animationEvent.sequenceBegin, listenerBegin);
document.removeEventListener(animationEvent.sequenceDone, listenerDone);
expect(beginFired).toBe(true);
expect(doneFired).toBe(true);
});
});
});
});
|
declare module 'redux-starter-kit' {
declare export type PayloadAction<P: any, T: string = string> = {
type: T,
payload: P,
...
}
}
|
// Check whether a object is an instance of the given type, respecting model
// factory injections
export default function isInstanceOfType(type, obj) {
return obj instanceof type;
}
|
Xflow.registerOperator("xflow.selectBool", {
outputs: [ {type: 'bool', name : 'result', customAlloc: true} ],
params: [ {type: 'int', source : 'index'},
{type: 'bool', source: 'value'} ],
alloc: function(sizes, index, value) {
sizes['result'] = 1;
},
evaluate: function(result, index, value) {
var i = index[0];
if (i < value.length) {
result[0] = value[i];
} else {
result[0] = false;
}
}
});
|
import shell from 'shelljs';
import path from 'path';
import tmp from 'tmp';
import helpers from './helpers';
const { isWindows, isOSX } = helpers;
tmp.setGracefulCleanup();
const SCRIPT_PATHS = {
singleIco: path.join(__dirname, '../..', 'bin/singleIco'),
convertToPng: path.join(__dirname, '../..', 'bin/convertToPng'),
convertToIco: path.join(__dirname, '../..', 'bin/convertToIco'),
convertToIcns: path.join(__dirname, '../..', 'bin/convertToIcns'),
};
/**
* Executes a shell script with the form "./pathToScript param1 param2"
* @param {string} shellScriptPath
* @param {string} icoSrc input .ico
* @param {string} dest has to be a .ico path
*/
function iconShellHelper(shellScriptPath, icoSrc, dest) {
return new Promise((resolve, reject) => {
if (isWindows()) {
reject('OSX or Linux is required');
return;
}
shell.exec(`${shellScriptPath} ${icoSrc} ${dest}`, { silent: true }, (exitCode, stdOut, stdError) => {
if (exitCode) {
reject({
stdOut,
stdError,
});
return;
}
resolve(dest);
});
});
}
function getTmpDirPath() {
const tempIconDirObj = tmp.dirSync({ unsafeCleanup: true });
return tempIconDirObj.name;
}
/**
* Converts the ico to a temporary directory which will be cleaned up on process exit
* @param {string} icoSrc path to a .ico file
* @return {Promise}
*/
function singleIco(icoSrc) {
return iconShellHelper(SCRIPT_PATHS.singleIco, icoSrc, `${getTmpDirPath()}/icon.ico`);
}
function convertToPng(icoSrc) {
return iconShellHelper(SCRIPT_PATHS.convertToPng, icoSrc, `${getTmpDirPath()}/icon.png`);
}
function convertToIco(icoSrc) {
return iconShellHelper(SCRIPT_PATHS.convertToIco, icoSrc, `${getTmpDirPath()}/icon.ico`);
}
function convertToIcns(icoSrc) {
if (!isOSX()) {
return new Promise((resolve, reject) => reject('OSX is required to convert to a .icns icon'));
}
return iconShellHelper(SCRIPT_PATHS.convertToIcns, icoSrc, `${getTmpDirPath()}/icon.icns`);
}
export default {
singleIco,
convertToPng,
convertToIco,
convertToIcns,
};
|
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2020 Photon Storm Ltd.
* @license {@link https://opensource.org/licenses/MIT|MIT License}
*/
/**
* Finds the key within the top level of the {@link source} object, or returns {@link defaultValue}
*
* @function Phaser.Utils.Objects.GetFastValue
* @since 3.0.0
*
* @param {object} source - The object to search
* @param {string} key - The key for the property on source. Must exist at the top level of the source object (no periods)
* @param {*} [defaultValue] - The default value to use if the key does not exist.
*
* @return {*} The value if found; otherwise, defaultValue (null if none provided)
*/
var GetFastValue = function (source, key, defaultValue)
{
var t = typeof(source);
if (!source || t === 'number' || t === 'string')
{
return defaultValue;
}
else if (source.hasOwnProperty(key) && source[key] !== undefined)
{
return source[key];
}
else
{
return defaultValue;
}
};
module.exports = GetFastValue;
|
import createSvgIcon from './utils/createSvgIcon';
import { jsx as _jsx } from "react/jsx-runtime";
export default createSvgIcon([/*#__PURE__*/_jsx("path", {
d: "M20 4H4v13.17L5.17 16H20V4zm-6 10H6v-2h8v2zm4-3H6V9h12v2zm0-3H6V6h12v2z",
opacity: ".3"
}, "0"), /*#__PURE__*/_jsx("path", {
d: "M20 18c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2H4c-1.1 0-1.99.9-1.99 2L2 22l4-4h14zm-16-.83V4h16v12H5.17L4 17.17zM6 12h8v2H6zm0-3h12v2H6zm0-3h12v2H6z"
}, "1")], 'ChatTwoTone');
|
import Ember from 'ember';
import { moduleForComponent, test } from 'ember-qunit';
import startApp from '../../helpers/start-app';
var App;
moduleForComponent('zip-code-input', 'zip-code-input component', {
setup: function() {
App = startApp();
},
teardown: function() {
Ember.run(App, 'destroy');
},
unit: true
});
test('values are correct', function(assert) {
assert.expect(2);
var component = this.subject();
// append the component to the DOM
this.render();
// testing filled in value
fillIn('input', '12345');
triggerEvent('input', 'blur');
andThen(function() { // wait for async helpers to complete
assert.equal(find('input').val(), '12345');
assert.equal(component.get('unmaskedValue'), 12345);
});
});
test('full code works', function(assert) {
assert.expect(2);
var component = this.subject();
// append the component to the DOM
this.render();
Ember.run(function(){
component.set('fullCode', true);
});
// testing filled in value
fillIn('input', '123451234');
triggerEvent('input', 'blur');
andThen(function() { // wait for async helpers to complete
assert.equal(find('input').val(), '12345-1234');
assert.equal(component.get('unmaskedValue'), 123451234);
});
});
|
var grow = grow || {};
window.grow = grow;
(function(grow){
var toolConfig = {};
grow.ui = grow.ui || {};
grow.ui.showNotice = function(text) {
var notice = document.createElement('div');
notice.classList.add('grow_tool__notice');
if (text) {
notice.appendChild(document.createTextNode(text));
}
document.body.appendChild(notice);
return notice;
};
grow.ui.toolConfig = function(tool, options) {
toolConfig[tool] = options;
};
grow.ui.tools = grow.ui.tools || [];
grow.ui.main = function(settings) {
var el = document.createElement('div');
var buttonsEl = document.createElement('div');
buttonsEl.setAttribute('class', 'grow__buttons');
buttonsEl.appendChild(createButton_('primary', null, null, {
'click': function() {
buttonsEl.classList.toggle('grow__expand');
}
}));
buttonsEl.appendChild(createButton_('close', null, null, {
'click': function() {
el.parentNode.removeChild(el);
}
}));
if (settings.injectEditUrl) {
buttonsEl.appendChild(
createButton_('edit', 'Edit', settings.injectEditUrl));
}
if (settings.injectTranslateUrl) {
buttonsEl.appendChild(createButton_(
'translate', 'Translate', settings.injectTranslateUrl));
}
for(i in grow.ui.tools) {
tool = grow.ui.tools[i];
if (tool['init']) {
tool['init'](toolConfig[tool['kind']] || {});
}
if (tool['button']) {
buttonsEl.appendChild(createButton_(
tool['kind'], tool['name'], tool['button']['link'] || null,
tool['button']['events'] || {}));
}
}
// If there is nothing to do, do not show the menu at all.
if (buttonsEl.children.length <= 2) {
return;
}
el.setAttribute('id', 'grow-utils');
el.appendChild(buttonsEl);
document.body.appendChild(el);
};
var createButton_ = function(kind, label, url, events) {
var containerEl = document.createElement('div');
containerEl.classList.add('grow__button');
var buttonEl = document.createElement('a');
buttonEl.classList.add('grow__icon');
buttonEl.classList.add('grow__icon_' + kind);
if (url) {
buttonEl.setAttribute('href', url);
buttonEl.setAttribute('target', '_blank');
} else {
buttonEl.setAttribute('href', 'javascript:void(0)');
}
if (events) {
for (var prop in events) {
buttonEl.addEventListener(prop, events[prop]);
}
}
containerEl.appendChild(buttonEl);
if (label) {
var labelEl = document.createElement('p');
labelEl.appendChild(document.createTextNode(label));
labelEl.classList.add('grow__label');
containerEl.appendChild(labelEl);
}
return containerEl;
};
})(grow);
|
var RELANG = {};
RELANG['sq'] = {
html: 'HTML',
video: 'Video',
image: 'Fotografi',
table: 'Tabelë',
link: 'Link',
link_insert: 'Lidh linq ...',
unlink: 'Hiq linkun',
formatting: 'Stilet',
paragraph: 'Paragraf',
quote: 'Kuotë',
code: 'Kod',
header1: 'Header 1',
header2: 'Header 2',
header3: 'Header 3',
header4: 'Header 4',
bold: 'Te trasha / Bold',
italic: 'Kursive / Italic',
fontcolor: 'Ngjyra e shkronjave',
backcolor: 'Ngjyra e mbrapavisë së shkronjave',
unorderedlist: 'Liste pa renditje',
orderedlist: 'Liste me renditje',
outdent: 'Outdent',
indent: 'Indent',
redo: 'Ribëj',
undo: 'Zhbëj',
cut: 'Cut',
cancel: 'Anulo',
insert: 'Insert',
save: 'Ruaje',
_delete: 'Fshije',
insert_table: 'Shto tabelë',
insert_row_above: 'Shto rresht sipër',
insert_row_below: 'Shto rresht përfundi',
insert_column_left: 'Shto kolonë majtas',
insert_column_right: 'Shto kolonë djathtas',
delete_column: 'Fshije kolonën',
delete_row: 'Fshije rreshtin',
delete_table: 'Fshije tabelën',
rows: 'Rreshta',
columns: 'Kolona',
add_head: 'Shto titujt e tabelës',
delete_head: 'Fshije titujt e tabelës',
title: 'Titulli',
image_position: 'Pozita',
none: 'Normale',
left: 'Majtas',
right: 'Djathtas',
image_web_link: 'Linku i fotografisë në internet',
text: 'Teksti',
mailto: 'Email',
web: 'URL',
video_html_code: 'Video embed code',
file: 'Fajll',
upload: 'Ngarko',
download: 'Shkarko',
choose: 'Zgjedh',
or_choose: 'Ose zgjedh',
drop_file_here: 'Gjuaje fajllin këtu',
align_left: 'Rreshtoje majtas',
align_center: 'Rreshtoje në mes',
align_right: 'Rreshtoje djathtas',
align_justify: 'Rreshtoje të gjithin njejt',
horizontalrule: 'Vizë horizontale',
fullscreen: 'Pamje e plotë',
deleted: 'E fshirë',
anchor: 'Anchor',
link_new_tab: 'Open link in new tab'
};
|
'use strict';
const chalk = require('chalk');
const Task = require('../models/task');
const Watcher = require('../models/watcher');
const Builder = require('../models/builder');
const pDefer = require('p-defer');
class BuildWatchTask extends Task {
constructor(options) {
super(options);
this._builder = null;
this._runDeferred = null;
}
async run(options) {
let { ui } = this;
ui.startProgress(chalk.green('Building'), chalk.green('.'));
this._runDeferred = pDefer();
let builder = (this._builder =
options._builder ||
new Builder({
ui,
outputPath: options.outputPath,
environment: options.environment,
project: this.project,
}));
ui.writeLine(`Environment: ${options.environment}`);
let watcher =
options._watcher ||
new Watcher({
ui,
builder,
analytics: this.analytics,
options,
});
await watcher;
// Run until failure or signal to exit
return this._runDeferred.promise;
}
/**
* Exit silently
*
* @private
* @method onInterrupt
*/
async onInterrupt() {
await this._builder.cleanup();
this._runDeferred.resolve();
}
}
module.exports = BuildWatchTask;
|
/**
* Imports
*/
import React from 'react';
import {FormattedMessage} from 'react-intl';
// Flux
import IntlStore from '../../../stores/Application/IntlStore';
// Required components
import Button from '../buttons/Button';
import Text from '../typography/Text';
// Translation data for this component
import intlData from './AddressPreview.intl';
/**
* Component
*/
class AddressPreview extends React.Component {
static contextTypes = {
getStore: React.PropTypes.func.isRequired
};
//*** Component Lifecycle ***//
componentDidMount() {
// Component styles
require('./AddressPreview.scss');
}
//*** Template ***//
render() {
let intlStore = this.context.getStore(IntlStore);
return (
<div className="address-preview">
<div className="address-preview__name">
<Text weight="bold">{this.props.address.name}</Text>
</div>
{this.props.address.phone ?
<div className="address-preview__phone">
<Text size="small">{this.props.address.phone}</Text>
</div>
:
null
}
{this.props.address.vatin ?
<div className="address-preview__vatin">
<Text>
<FormattedMessage
message={intlStore.getMessage(intlData, 'vatLabel')}
locales={intlStore.getCurrentLocale()} />: {this.props.address.vatin}
</Text>
</div>
:
null
}
<div className="address-preview__address-line-1">
<Text>{this.props.address.addressLine1}</Text>
</div>
{this.props.address.addressLine2 ?
<div className="address-preview__address-line-2">
<Text>{this.props.address.addressLine2}</Text>
</div>
:
null
}
<div className="address-preview__postal-code">
<Text>{this.props.address.postalCode}</Text>
</div>
<div className="address-preview__city">
<Text>{this.props.address.city}</Text>
</div>
{this.props.address.state ?
<div className="address-preview__state">
<Text>{this.props.address.state}</Text>
</div>
:
null
}
<div className="address-preview__country">
<Text>{this.props.address.country}</Text>
</div>
<div className="address-preview__actions">
{this.props.onEditClick ?
<div className="address-preview__edit" onClick={this.props.onEditClick}>
<Text weight="bold">
<FormattedMessage
message={intlStore.getMessage(intlData, 'edit')}
locales={intlStore.getCurrentLocale()} />
</Text>
</div>
:
null
}
{this.props.onDeleteClick ?
<div className="address-preview__delete" onClick={this.props.onDeleteClick}>
<Text>
<FormattedMessage
message={intlStore.getMessage(intlData, 'delete')}
locales={intlStore.getCurrentLocale()} />
</Text>
</div>
:
null
}
</div>
</div>
);
}
}
/**
* Exports
*/
export default AddressPreview;
|
'use strict';
var constants = require('../../lifx').constants;
var Packet = {
size: 21
};
/**
* Converts packet specific data from a buffer to an object
* @param {Buffer} buf Buffer containing only packet specific data no header
* @return {Object} Information contained in packet
*/
Packet.toObject = function(buf) {
var obj = {};
var offset = 0;
if (buf.length !== this.size) {
throw new Error('Invalid length given for setWaveform LIFX packet');
}
obj.stream = buf.readUInt8(offset);
offset += 1;
obj.isTransient = buf.readUInt8(offset);
offset += 1;
obj.color = {};
obj.color.hue = buf.readUInt16LE(offset);
offset += 2;
obj.color.saturation = buf.readUInt16LE(offset);
offset += 2;
obj.color.brightness = buf.readUInt16LE(offset);
offset += 2;
obj.color.kelvin = buf.readUInt16LE(offset);
offset += 2;
obj.period = buf.readUInt32LE(offset);
offset += 4;
obj.cycles = buf.readFloatLE(offset);
offset += 4;
obj.skewRatio = buf.readUInt16LE(offset);
offset += 2;
obj.waveform = buf.readUInt8(offset);
offset += 1;
return obj;
};
/**
* Converts the given packet specific object into a packet
* @param {Object} obj object with configuration data
* @param {Boolean} obj.isTransient restore color used before effect
* @param {Object} obj.color an objects with colors to set
* @param {Number} obj.color.hue between 0 and 65535
* @param {Number} obj.color.saturation between 0 and 65535
* @param {Number} obj.color.brightness between 0 and 65535
* @param {Number} [obj.color.kelvin=3500] between 2500 and 9000
* @param {Number} obj.period length of one cycle in milliseconds
* @param {Number} obj.cycles how often to repeat through effect
* @param {Number} obj.skewRatio distribution between time on original and new color , positive is for more new color, negative for original color
* @param {Number} obj.waveform between 0 and 4 for form of effect
* @return {Buffer} packet
*/
Packet.toBuffer = function(obj) {
var buf = new Buffer(this.size);
buf.fill(0);
var offset = 0;
// obj.stream field has unknown function so leave it as 0
offset += 1;
if (obj.isTransient === undefined) {
throw new TypeError('obj.isTransient value must be given for setWaveform LIFX packet');
}
if (typeof obj.isTransient !== 'boolean') {
throw new TypeError('Invalid isTransient value given for setWaveform LIFX packet, must be boolean');
}
buf.writeUInt8(obj.isTransient, offset);
offset += 1;
if (typeof obj.color !== 'object') {
throw new TypeError('Invalid object for color given for setWaveform LIFX packet');
}
if (typeof obj.color.hue !== 'number' && obj.color.hue < 0 || obj.color.hue > 65535) {
throw new RangeError('Invalid color hue given for setWaveform LIFX packet, must be a number between 0 and 65535');
}
buf.writeUInt16LE(obj.color.hue, offset);
offset += 2;
if (typeof obj.color.saturation !== 'number' && obj.color.saturation < 0 || obj.color.saturation > 65535) {
throw new RangeError('Invalid color saturation given for setWaveform LIFX packet, must be a number between 0 and 65535');
}
buf.writeUInt16LE(obj.color.saturation, offset);
offset += 2;
if (typeof obj.color.brightness !== 'number' && obj.color.brightness < 0 || obj.color.brightness > 65535) {
throw new RangeError('Invalid color brightness given for setWaveform LIFX packet, must be a number between 0 and 65535');
}
buf.writeUInt16LE(obj.color.brightness, offset);
offset += 2;
if (obj.color.kelvin === undefined) {
obj.color.kelvin = constants.HSBK_DEFAULT_KELVIN;
}
if (typeof obj.color.kelvin !== 'number' && obj.color.kelvin < 2500 || obj.color.kelvin > 9000) {
throw new RangeError('Invalid color kelvin given for setWaveform LIFX packet, must be a number between 2500 and 9000');
}
buf.writeUInt16LE(obj.color.kelvin, offset);
offset += 2;
if (obj.period === undefined) {
throw new TypeError('obj.period value must be given for setWaveform LIFX packet');
}
if (typeof obj.period !== 'number') {
throw new TypeError('Invalid period type given for setWaveform LIFX packet, must be a number');
}
buf.writeUInt32LE(obj.period, offset);
offset += 4;
if (obj.cycles === undefined) {
throw new TypeError('obj.cycles value must be given for setWaveform LIFX packet');
}
if (typeof obj.cycles !== 'number') {
throw new TypeError('Invalid cycles type given for setWaveform LIFX packet, must be a number');
}
buf.writeFloatLE(obj.cycles, offset);
offset += 4;
if (obj.skewRatio === undefined) {
throw new TypeError('obj.skewRatio value must be given for setWaveform LIFX packet');
}
if (typeof obj.skewRatio !== 'number') {
throw new TypeError('Invalid skewRatio type given for setWaveform LIFX packet, must be a number');
}
buf.writeInt16LE(obj.skewRatio, offset);
offset += 2;
if (obj.waveform === undefined) {
throw new TypeError('obj.waveform value must be given for setWaveform LIFX packet');
}
if (typeof obj.waveform !== 'number' && obj.waveform < 0 || obj.waveform > (constants.LIGHT_WAVEFORMS.length - 1)) {
throw new RangeError('Invalid waveform value given for setWaveform LIFX packet, must be a number between 0 and ' + (constants.LIGHT_WAVEFORMS.length - 1));
}
buf.writeUInt8(obj.waveform, offset);
offset += 1;
return buf;
};
module.exports = Packet;
|
import { createReducer } from 'redux-act';
import { fetchSystemStatus } from 'actions';
import { loadState, loadStart, loadError, loadComplete } from 'reducers/util';
const initialState = loadState();
export default createReducer({
[fetchSystemStatus.START]: state => loadStart(state),
[fetchSystemStatus.ERROR]: (state, { error }) => loadError(state, error),
[fetchSystemStatus.COMPLETE]: (state, { status }) => loadComplete(status),
}, initialState);
|
define(['durandal/app','lib/pagelayout', 'lib/prettify'], function (app, pagelayout, prettify) {
var activePage = ko.observable(),
hash = "",
oc;
return {
compositionComplete : function() {
var that = this;
oc = Stashy.OffCanvas("#sticky", { enableTouch : true });
pagelayout.offcanvasLayout(oc);
prettyPrint();
Stashy.Utils.ScrollTo('#' + that.hash);
},
activePage : activePage,
activate: function (page) {
var that = this;
if (page != undefined) {
that.hash = page;
Stashy.Utils.ScrollTo('#sticky #' + that.hash);
}
ga('send', 'pageview');
}
};
});
|
/*
to package
"eslint": "^1.7.3",
"eslint-config-rackt": "^1.1.0",
"eslint-plugin-react": "^3.6.3",
*/
require('es6-promise').polyfill(); // old node 0.10
var path = require('path');
var webpack = require('webpack');
module.exports = {
externals: {
jquery: "jQuery",
autobahn: "autobahn"
},
plugins: [
// new webpack.optimize.UglifyJsPlugin({minimize: true}),
new webpack.optimize.CommonsChunkPlugin(
/* chunkName= */'vendor',
/* filename= */'vendor.js'
),
/* new webpack.ProvidePlugin({ // If you use "_", underscore is automatically required
"$": "jquery",
"_": "underscore",
}) */
],
resolve: {
alias: {
"lodash": path.resolve("./node_modules/lodash"),
"react": path.resolve("./node_modules/react/react.js"),
"react-dom": path.resolve("./node_modules/react/lib/ReactDOM.js"),
"react-router": path.resolve("./node_modules/react-router"),
"reflux": path.resolve("./node_modules/reflux/src/index.js"),
"object-assign":path.resolve("./node_modules/object-assign/index.js"),
}
},
entry: {
// demoshop: [
// './demoshop/app.js'
// ],
// employee: [
// 'employee/views/contact.js'
// ],
navbar: [
'./navbar/app.js'
],
vendor: [
'lodash',
'react',
'react-dom',
'reflux',
'object-assign'
]
},
output: {
path: 'www/app',
filename: '[name].js',
publicPath: '/app/'
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel',
query: {
presets: ['es2015', 'stage-0', 'react']
}
},
{ test: /\.css$/, loader: 'style!css' },
{ test: /\.jpg$/, loader: "file-loader" },
{ test: /\.png$/, loader: "url-loader?mimetype=image/png" }
]
},
// devtool: 'source-map',
devtool: 'inline-source-map',
// scripts: {
// watch: "webpack --watch -d --display-error-details"
// }
};
|
require('uppercase-core');
require('./DIST/NODE.js');
|
define("foo", [ "./bar", "./baz/baz" ], function(require, exports, module) {
require("./bar");
require("./baz/baz");
});
|
exports.config = {
specs: require('./index-webdriver.js').specs(),
framework: 'qunit',
baseUrl: './',
capabilities: [{
browserName: 'phantomjs',
exclude: require('./index-webdriver.js').exclude('phantomjs')
}],
updateJob: false,
waitforTimeout: 1000,
logLevel: 'silent',
coloredLogs: true,
screenshotPath: 'build/webdriver/failed',
onPrepare: require('./index-webdriver.js').onPrepare,
before: require('./index-webdriver.js').before,
after: require('./index-webdriver.js').after,
onComplete: require('./index-webdriver.js').onComplete
};
|
var equal = require('assert').equal,
notEqual = require('assert').notEqual,
Pool = require('../lib').Pool;
describe('Pool', function () {
it('should run multiple scripts', function (finished) {
var pool = new Pool({numberOfInstances: 5});
var scriptsExited = 0;
for (var i = 0; i < 20; ++i) {
var script = pool.createScript("\
exports.main = function() {\n\
exit(testGlobal);\n\
}\n\
"
);
script.on('exit', function (err, result) {
scriptsExited++;
if (scriptsExited == 10) {
pool.kill();
equal(10, result);
finished();
}
});
script.run({testGlobal: 10});
}
});
it('should run scripts on non blocking instances', function (finished) {
var pool = new Pool({numberOfInstances: 2});
var exited = false;
// Create blocking script.
var script = pool.createScript("\
exports.main = function() {\n\
while(true);\
}\n\
"
);
script.run();
var scriptsExited = 0;
for (var i = 0; i < 10; ++i) {
var script2 = pool.createScript("\
exports.main = function() {\n\
exit(10);\n\
}\n\
"
);
script2.on('exit', function (err, result) {
scriptsExited++;
if (scriptsExited == 10) {
pool.kill();
equal(10, result);
exited = true;
finished();
}
});
script2.run();
}
setTimeout(function () {
if (!exited) {
equal(false, true);
}
}, 3000);
});
it('should not be created if there are zero or negative amount of specified instances', function (finished) {
var pool = null;
try {
pool = new Pool({numberOfInstances: 0});
equal(false, true);
} catch (error) {
notEqual(-1, error.indexOf("Can't create a pool with zero instances"));
finished();
}
});
});
|
//////////////////////////////////////////
//
// ONLY EDIT babel-plugin.js at ./src/babel-plugin.js, not ./babel-plugin.js!
//
//////////////////////////////////////////
var plugin = function(babel) {
return {
visitor: {
ObjectExpression(path) {
path.node.properties.forEach(function(prop){
if (prop.key.type === "Identifier") {
var keyLoc = prop.key.loc
prop.key = babel.types.stringLiteral(prop.key.name)
prop.key.loc = keyLoc
}
})
var call = babel.types.callExpression(
babel.types.identifier("__ohdMakeObject"), [babel.types.arrayExpression(
path.node.properties.map(function(prop) {
var type = babel.types.stringLiteral(prop.type)
type.ignore = true
if (prop.type === "ObjectMethod") {
// getter/setter
var kind = babel.types.stringLiteral(prop.kind);
kind.ignore = true;
var propArray = babel.types.arrayExpression([
type,
prop.key,
kind,
babel.types.functionExpression(
null,
prop.params,
prop.body
)
])
return propArray
} else {
var propArray = babel.types.arrayExpression([
type,
prop.key,
prop.value
])
return propArray
}
console.log("continue with type", prop.type)
})
)]
)
path.replaceWith(call)
},
AssignmentExpression(path) {
if (path.node.ignore) {
return
}
if (["+=", "-=", "/=", "*="].indexOf(path.node.operator) !== -1){
// I don't think this replacement is always going to be 100% equivalent
// to the +=/... operation, but it's close enough for now
// e.g. maybe there'd be props if path.node.left is sth like a.sth().aa would
// call sth twice
var operator = {"+=": "+", "-=": "-", "/=": "/", "*=": "*"}[path.node.operator]
var value = babel.types.binaryExpression(operator, path.node.left, path.node.right)
var replacement = babel.types.assignmentExpression("=", path.node.left, value)
path.replaceWith(replacement)
}
if (path.node.operator === "=" && path.node.left.type === "MemberExpression") {
var property;
if (path.node.left.computed === true) {
property = path.node.left.property
} else {
property = babel.types.stringLiteral(path.node.left.property.name)
property.loc = path.node.left.property.loc
}
var assignExpression = babel.types.callExpression(
babel.types.identifier("__ohdAssign"), [
path.node.left.object,
property,
path.node.right
]
)
assignExpression.loc = path.node.loc
path.replaceWith(assignExpression)
}
},
UnaryExpression(path) {
if (path.node.operator === "delete"){
var prop = path.node.argument.property
if (prop.type === "Identifier"){
prop = babel.types.stringLiteral(prop.name)
}
var call = babel.types.callExpression(
babel.types.identifier("__ohdDeleteProperty"),
[
path.node.argument.object,
prop
]
)
path.replaceWith(call)
}
}
}
}
}
if (typeof module === "undefined"){
window.babelPlugin = plugin;
} else {
module.exports = plugin
}
|
'use strict';
module.exports = function(app) {
var users = require('../../app/controllers/users.server.controller');
var companies = require('../../app/controllers/companies.server.controller');
var fields = require('../../app/controllers/fields.server.controller');
var schedules = require('../../app/controllers/schedules.server.controller');
// Companies Routes
app.route('/companies')
.get(companies.list)
.post(users.requiresLogin, companies.create);
app.route('/companies/:companyId')
.get(companies.read)
.put(users.requiresLogin, users.requiresAdmin, companies.update)
.delete(users.requiresLogin, users.requiresAdmin, companies.delete);
app.route('/companies/:companyId/fields')
.get(fields.list)
app.route('/companies/:companyId/schedules')
.get(schedules.list)
// Finish by binding the Company middleware
app.param('companyId', companies.companyByID);
};
|
import phantom from 'phantom';
import logger from '../Logger';
export default class PhantomFetcher {
initialize() {
if (this.instance && this.page) {
return Promise.resolve(this.page);
}
logger.info('Creating new PhantomJS instance');
return phantom.create()
.then(
(instance) => {
this.instance = instance;
return instance.createPage();
}
)
.then((page) => {
this.page = page;
// page.on('onResourceRequested', (requestData) => {
// console.info('Requesting', requestData.url);
// });
})
;
}
get(url) {
return new Promise((resolve, reject) => {
this.page.property('onError', (msg) => {
reject(msg);
});
this.page.open(url)
.then(
(/* status */) => {
// console.log(status);
return this.page.property('content');
},
(err) => {
reject(err);
}
)
.then(
(content) => {
// console.log(content);
this.page.evaluate(() => {
return document.location;
}).then((location) => {
resolve({
text: content,
location
});
}).catch((err) => {
reject(err);
});
}
);
});
}
}
|
const path = require('path');
const env = require('yargs').argv.mode;
const webpack = require('webpack');
const projectRoot = path.resolve(__dirname, '/');
const UglifyJsPlugin = webpack.optimize.UglifyJsPlugin;
const libraryName = '<%= libraryName %>';
const plugins = [];
let outputFile;
if (env === 'build') {
plugins.push(new UglifyJsPlugin({ minimize: true }));
outputFile = `${libraryName}.min.js`;
} else {
outputFile = `${libraryName}.js`;
}
const config = {
entry: `${__dirname}/src/index.js`,
devtool: 'source-map',
output: {
path: `${__dirname}/dist`,
filename: outputFile,
library: libraryName,
libraryTarget: 'umd',
umdNamedDefine: true
},
module: {
preLoaders: [
{
test: /(\.jsx|\.js)$/,
loader: 'eslint',
include: projectRoot,
exclude: /(node_modules|bower_components)/
}
],
loaders: [
{
test: /(\.jsx|\.js)$/,
loader: 'babel',
include: projectRoot,
exclude: /(node_modules|bower_components)/
}
]
},
resolve: {
root: path.resolve('./src'),
extensions: ['', '.js']
},
plugins
};
module.exports = config;
|
var searchData=
[
['makeexternal',['MakeExternal',['../classv8_1_1String.html#a5efd1eba40c1fa8a6aae2c4a175a63be',1,'v8::String::MakeExternal(ExternalStringResource *resource)'],['../classv8_1_1String.html#a19db11c97e2ce01244e06f5cbcd094f2',1,'v8::String::MakeExternal(ExternalAsciiStringResource *resource)']]],
['markasundetectable',['MarkAsUndetectable',['../classv8_1_1ObjectTemplate.html#a7e40ef313b44c2ad336c73051523b4f8',1,'v8::ObjectTemplate']]],
['markindependent',['MarkIndependent',['../classv8_1_1PersistentBase.html#aed12b0a54bc5ade1fb44e3bdb3a1fe74',1,'v8::PersistentBase']]],
['markpartiallydependent',['MarkPartiallyDependent',['../classv8_1_1PersistentBase.html#a4a876d30dda0dfb812e82bb240e4686e',1,'v8::PersistentBase']]],
['maybe',['Maybe',['../structv8_1_1Maybe.html',1,'v8']]],
['message',['Message',['../classv8_1_1Message.html',1,'v8']]],
['message',['Message',['../classv8_1_1Debug_1_1Message.html',1,'v8::Debug']]],
['message',['Message',['../classv8_1_1TryCatch.html#a2811e500fbb906ee505895a3d94fc66f',1,'v8::TryCatch']]],
['messagehandler',['MessageHandler',['../classv8_1_1Debug.html#a526826b857bd3e3efa184e12bcebc694',1,'v8::Debug']]]
];
|
AUTOBAHN_DEBUG = true;
var autobahn = require('autobahn');
var program = require('commander');
program
.option('-p, --port <port>', 'Server IP port', parseInt,9000)
.option('-i, --ip <ip>', 'Server IP address','127.0.0.1')
.parse(process.argv);
var connection = new autobahn.Connection({
url: 'ws://' + program.ip + ':' + program.port,
realm: 'realm1'}
);
connection.onopen = function (session) {
// Define an event handler
function onEvent(publishArgs, kwargs) {
console.log('Event received args', publishArgs, 'kwargs ',kwargs);
}
// Subscribe to a topic
session.subscribe('com.myapp.topic1', onEvent).then(
function(subscription) {
console.log("subscription successfull", subscription);
currentSubscription = subscription;
},
function(error) {
console.log("subscription failed", error);
}
);
// Exit after 5 minutes
setTimeout(
function() {
console.log("Terminating subscriber");
session.unsubscribe(currentSubscription).then(
function(gone) {
console.log("unsubscribe successfull");
connection.close();
},
function(error) {
console.log("unsubscribe failed", error);
connection.close();
}
);
},
300000
);
};
connection.open();
|
'use strict';
((window, document) => {
})(window, document);
|
/*
Time Count
TimeCount class, useful for incremental games
By Luke Nickerson, 2015
*/
(function(){
var TimeCount = function(){
this.lastTime = null;
}
TimeCount.prototype.setLastTime = function(){
}
// Install into RocketBoots if it exists, otherwise make global
if (typeof RocketBoots == "object") {
RocketBoots.installComponent(
"time_count", // file name
"TimeCount", // class name
TimeCount // class
);
} else window["TimeCount"] = TimeCount;
})();
|
/*
Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'indent', 'eu', {
indent: 'Handitu koska',
outdent: 'Txikitu koska'
} );
|
const path = require('path');
const consoleLogger = require('./logger');
const _ = require('lodash');
module.exports = (config, logger, metrics, next) => {
if (!next) { next = metrics; metrics = { increment: _.noop }; }
if (!next) { next = logger; logger = consoleLogger; }
require('../db')(config, logger, (err, client) => {
if (err) { return next(err); }
const messaging = require('../db/messaging')(config);
const urls = require('./urls');
const visibility = require('./visibility');
const api = {
logger,
metrics,
client,
config,
messaging,
urls,
visibility,
};
const modules = ['auth', 'common', 'user', 'post', 'like', 'feed', 'friend', 'follow', 'group', 'comment', 'moderate', 'interest', '../db/migrations'];
modules.forEach((module) => {
const moduleName = path.basename(module);
api[moduleName] = require(path.resolve(__dirname, module))(api);
});
next(null, api);
});
};
|
'use strict';
describe('Service: Location', function () {
// load the service's module
beforeEach(module('treasuremapApp'));
// instantiate service
var Location;
beforeEach(inject(function (_Location_) {
Location = _Location_;
}));
it('should do something', function () {
expect(!!Location).toBe(true);
});
});
|
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0z" /><path d="M23.64 7c-.45-.34-4.93-4-11.64-4-1.5 0-2.89.19-4.15.48L18.18 13.8 23.64 7zm-6.6 8.22L3.27 1.44 2 2.72l2.05 2.06C1.91 5.76.59 6.82.36 7l11.63 14.49.01.01.01-.01 3.9-4.86 3.32 3.32 1.27-1.27-3.46-3.46z" /></React.Fragment>
, 'SignalWifiOff');
|
(function() {
var checkVersion = Dagaz.Model.checkVersion;
Dagaz.Model.checkVersion = function(design, name, value) {
if (name != "magyar-no-pass") {
checkVersion(design, name, value);
}
}
var CheckInvariants = Dagaz.Model.CheckInvariants;
Dagaz.Model.CheckInvariants = function(board) {
var design = Dagaz.Model.design;
_.each(board.moves, function(move) {
if (move.isSimpleMove() && (move.actions[0][0][0] == move.actions[0][1][0])) {
move.failed = true;
}
});
CheckInvariants(board);
}
})();
|
/*
* UserLogin Messages
*
* This contains all the text for the UserLogin component.
*/
import { defineMessages } from 'react-intl';
export default defineMessages({
header: {
id: 'app.containers.UserLogin.header',
defaultMessage: 'This is UserLogin container !',
},
usernameInput: {
id: 'app.containers.login_page.username',
defaultMessage: 'Username',
},
passwordInput: {
id: 'app.containers.login_page.password',
defaultMessage: 'Password',
},
rememberMe: {
id: 'app.containers.login_page.rememberMe',
defaultMessage: 'Remember Login',
},
isPrivateComputer: {
id: 'app.containers.login_page.computer_is_private',
defaultMessage: 'if this is a private computer',
},
logInButton: {
id: 'app.containers.login_page.log_in',
defaultMessage: 'Log In',
},
// Eventually the backend should be returning a constant
defaultLoginError: {
id: 'app.containers.login_page.log_in',
defaultMessage: 'Wrong username or password.',
},
});
|
"use babel";
// @flow
export function filterAtomEnv(env: Object) {
const filteredVars = ["ATOM_HOME", "NODE_PATH"];
return Object.entries(env).reduce((newEnv, [key, value]) => {
if (filteredVars.find(v => v === key) != null) return newEnv;
return { ...newEnv, [key]: value };
}, {});
}
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = clean;
var _path = require('path');
var _del = require('del');
var _del2 = _interopRequireDefault(_del);
var _config = require('../config');
var _config2 = _interopRequireDefault(_config);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function clean(dir) {
var dist = (0, _config2.default)(dir).distDir;
return (0, _del2.default)((0, _path.resolve)(dir, dist), { force: true });
}
|
import { expect } from 'chai';
import { Promise } from 'es6-promise';
import { Db } from 'mongodb';
import { Factory } from '../src/index';
import { hooks } from '../src/hooks';
describe('API spec', function() {
const Adapter = Factory();
it('Adapter object API', function() {
expect(Adapter).to.have.all.keys('connect', 'close', 'query');
[
Adapter.connect,
Adapter.close,
Adapter.query,
].forEach(function(func) {
expect(func).to.be.ok.and.to.be.a('function');
});
});
it('Query object API', function() {
const Query = Factory().query();
expect(Query).to.have.all.keys('insert', 'find', 'findOne', 'deleteOne', 'deleteMany', 'updateOne', 'updateMany');
[
Query.insert,
Query.find,
Query.findOne,
Query.updateOne,
Query.updateMany,
Query.deleteOne,
Query.deleteMany,
].forEach(function(func) {
expect(func).to.be.ok.and.to.be.a('function');
});
});
});
describe('Connection behavior', function() {
it('should be connected and disconnected', function(done) {
const connectedFactory = Factory({
database: 'test',
});
connectedFactory.connect().catch(done).then(function(adapter) {
expect(adapter.getDatabase()).to.be.instanceof(Db);
adapter.close().catch(done).then(done);
});
});
});
describe('Create documents', function() {
const Adapter = Factory({
database: 'test',
});
before(function(done) {
Adapter.connect().catch(done).then(function() {
done();
});
});
it('should return Promise', function() {
const Query = Adapter.query('orm_test');
expect(Query.insert({
key: 'value'
}).exec()).to.be.instanceof(Promise);
expect(Query.insert([{
key: 'value'
},
{
key: 'value'
}]).exec()).to.be.instanceof(Promise);
});
});
describe('Read documents', function() {
const Adapter = Factory({
database: 'test',
});
before(function(done) {
Adapter.connect().catch(done).then(function() {
done();
});
});
it('should return Promise and be equal inserted data', function(done) {
const Query = Adapter.query('orm_test');
Promise.resolve(null)
.then(function() {
return Query.find({
key: 'value'
}).exec().then(function(data) {
expect(data.slice).to.be.ok.and.to.be.a('function');
expect(data[0].key).to.be.ok.and.to.be.eql('value');
});
})
.then(function() {
Query.findOne({
key: 'value'
}).exec().then(function(data) {
expect(data.key).to.be.ok.and.to.be.eql('value');
Adapter.close();
done();
});
});
});
});
describe('Update documents', function(done) {
const Adapter = Factory({
database: 'test',
});
before(function(done) {
Adapter.connect().catch(done).then(function() {
done();
});
});
it('should return Promise and data must be updated', function(done) {
const Query = Adapter.query('orm_test');
Promise.resolve(null).then(function() {
return Query.updateMany({
key: 'value',
}, {
$set: {
param: 'value',
}
}).exec().then(function(data) {
expect(data.modifiedCount).to.be.ok.and.to.be.not.equal(0);
});
}).then(function() {
return Query.updateOne({
key: 'value',
}, {
$set: {
only: 'value',
}
}).exec().then(function(data) {
expect(data.modifiedCount).to.be.ok.and.to.be.not.equal(0);
Adapter.close();
done();
});
});
});
});
describe('Delete documents', function(done) {
const Adapter = Factory({
database: 'test',
});
before(function(done) {
Adapter.connect().catch(done).then(function() {
done();
});
});
it('should return Promise and data must be deleted', function(done) {
const Query = Adapter.query('orm_test');
Promise.resolve(null)
.then(function() {
const result = Query.deleteOne({
key: 'value',
}).exec().then(function(data) {
expect(data.deletedCount).to.be.ok.and.to.be.eql(1);
expect(result).to.be.instanceof(Promise);
});
}).then(function() {
const result = Query.deleteMany({
key: 'value',
}).exec().then(function(data) {
expect(data.deletedCount).to.be.ok.and.to.be.eql(2);
expect(result).to.be.instanceof(Promise);
Adapter.close();
done();
});
});
});
});
describe('Hooks test', function() {
const Adapter = Factory({
database: 'test',
});
before(function(done) {
Adapter.connect().catch(done).then(function() {
done();
});
});
it('Hooks should process passing data', function(done) {
const Query = Adapter.query('orm_test');
hooks.registerBeforeHook('insert', function(value) {
value.before = 'before';
return value;
});
hooks.registerAfterHook('insert', function(value) {
return value.insertedCount;
});
hooks.registerBeforeHook('find', function(value) {
value.key = 'value';
return value;
});
hooks.registerAfterHook('find', function(value) {
value.after = 'after';
return value;
});
Query.insert({
key: 'value',
}).exec().then(function(data) {
expect(data).to.be.ok.and.to.be.eql(1);
});
Query.findOne({}).exec().then(function(data) {
expect(data.key).to.be.ok.and.to.be.eql('value');
expect(data.before).to.be.ok.and.to.be.eql('before');
expect(data.after).to.be.ok.and.to.be.eql('after');
clearHooks('insert');
clearHooks('find')
});
Query.deleteMany({
key: 'value',
}).exec().then(function(data) {
Adapter.close();
done();
});
});
});
|
import { checkTest } from './utils';
var MethodCallTracker = function(env, methodName) {
this._env = env;
this._methodName = methodName;
this._isExpectingNoCalls = false;
this._expecteds = [];
this._actuals = [];
};
MethodCallTracker.prototype = {
stubMethod() {
if (this._originalMethod) {
// Method is already stubbed
return;
}
let env = this._env;
let methodName = this._methodName;
this._originalMethod = env.getDebugFunction(methodName);
env.setDebugFunction(methodName, (message, test) => {
let resultOfTest = checkTest(test);
this._actuals.push([message, resultOfTest]);
});
},
restoreMethod() {
if (this._originalMethod) {
this._env.setDebugFunction(this._methodName, this._originalMethod);
}
},
expectCall(message) {
this.stubMethod();
this._expecteds.push(message || /.*/);
},
expectNoCalls() {
this.stubMethod();
this._isExpectingNoCalls = true;
},
isExpectingNoCalls() {
return this._isExpectingNoCalls;
},
isExpectingCalls() {
return !this._isExpectingNoCalls && this._expecteds.length;
},
assert() {
let { assert } = QUnit.config.current;
let env = this._env;
let methodName = this._methodName;
let isExpectingNoCalls = this._isExpectingNoCalls;
let expecteds = this._expecteds;
let actuals = this._actuals;
let o, i;
if (!isExpectingNoCalls && expecteds.length === 0 && actuals.length === 0) {
return;
}
if (env.runningProdBuild) {
assert.ok(true, `calls to Ember.${methodName} disabled in production builds.`);
return;
}
if (isExpectingNoCalls) {
let actualMessages = [];
for (i = 0; i < actuals.length; i++) {
if (!actuals[i][1]) {
actualMessages.push(actuals[i][0]);
}
}
assert.ok(
actualMessages.length === 0,
`Expected no Ember.${methodName} calls, got ${actuals.length}: ${actualMessages.join(', ')}`
);
return;
}
let expected, actual, match;
for (o = 0; o < expecteds.length; o++) {
expected = expecteds[o];
for (i = 0; i < actuals.length; i++) {
actual = actuals[i];
if (!actual[1]) {
if (expected instanceof RegExp) {
if (expected.test(actual[0])) {
match = actual;
break;
}
} else {
if (expected === actual[0]) {
match = actual;
break;
}
}
}
}
if (!actual) {
assert.ok(false, `Received no Ember.${methodName} calls at all, expecting: ${expected}`);
} else if (match && !match[1]) {
assert.ok(true, `Received failing Ember.${methodName} call with message: ${match[0]}`);
} else if (match && match[1]) {
assert.ok(
false,
`Expected failing Ember.${methodName} call, got succeeding with message: ${match[0]}`
);
} else if (actual[1]) {
assert.ok(
false,
`Did not receive failing Ember.${methodName} call matching '${expected}', last was success with '${
actual[0]
}'`
);
} else if (!actual[1]) {
assert.ok(
false,
`Did not receive failing Ember.${methodName} call matching '${expected}', last was failure with '${
actual[0]
}'`
);
}
}
},
};
export default MethodCallTracker;
|
/**
* Example on how to use regular NodeJS files, the (module)exports is used
*/
var config = require('../../index')();
console.log(config.message);
// $> node example.js -> "We are in development"
// $> NODE_ENV=production node example.js -> "We are in production"
|
var env = require('./environment.js');
exports.config = {
seleniumAddress: env.seleniumAddress,
framework: 'jasmine',
specs: ['pass_spec.js'],
baseUrl: env.baseUrl,
plugins: [{
path: '../index.js',
failOnWarning: false,
failOnError: false
}]
};
|
#!/usr/bin/env node
/*
*
* Copyright 2013 Anis Kadri
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
// copyright (c) 2013 Andrew Lunny, Adobe Systems
var path = require('path')
, url = require('url')
, package = require(path.join(__dirname, 'package'))
, nopt = require('nopt')
, plugins = require('./src/util/plugins')
, Q = require('q')
, plugman = require('./plugman');
var known_opts = { 'platform' : [ 'ios', 'android', 'amazon-fireos', 'blackberry10', 'wp7', 'wp8' , 'windows8', 'firefoxos' ]
, 'project' : path
, 'plugin' : [String, path, url, Array]
, 'version' : Boolean
, 'help' : Boolean
, 'debug' : Boolean
, 'silent' : Boolean
, 'plugins': path
, 'link': Boolean
, 'variable' : Array
, 'www': path
, 'searchpath' : [path, Array]
}, shortHands = { 'var' : ['--variable'], 'v': ['--version'], 'h': ['--help'] };
var cli_opts = nopt(known_opts, shortHands);
var cmd = cli_opts.argv.remain.shift();
// Without these arguments, the commands will fail and print the usage anyway.
if (cli_opts.plugins_dir || cli_opts.project) {
cli_opts.plugins_dir = typeof cli_opts.plugins_dir == 'string' ?
cli_opts.plugins_dir :
path.join(cli_opts.project, 'cordova', 'plugins');
}
process.on('uncaughtException', function(error) {
if (cli_opts.debug) {
console.error(error.stack);
} else {
console.error(error.message);
}
process.exit(1);
});
// Set up appropriate logging based on events
if (cli_opts.debug) {
plugman.on('verbose', console.log);
}
if (!cli_opts.silent) {
plugman.on('log', console.log);
plugman.on('warn', console.warn);
plugman.on('results', console.log);
}
plugman.on('error', console.error);
if (cli_opts.version) {
console.log(package.version);
} else if (cli_opts.help) {
console.log(plugman.help());
} else if (plugman.commands[cmd]) {
var result = plugman.commands[cmd](cli_opts);
if (result && Q.isPromise(result)) {
result.done();
}
} else {
console.log(plugman.help());
}
|
import {CYCLE_STATES, PRACTICE, REFLECTION, COMPLETE} from 'src/common/models/cycle'
import {userCan} from 'src/common/util'
import getUser from 'src/server/actions/getUser'
import assertUserIsMember from 'src/server/actions/assertUserIsMember'
import createNextCycleForChapter from 'src/server/actions/createNextCycleForChapter'
import {Cycle, getCyclesInStateForChapter, getLatestCycleForChapter} from 'src/server/services/dataService'
import {
LGCLIUsageError,
LGNotAuthorizedError,
LGForbiddenError,
LGBadRequestError,
} from 'src/server/util/error'
const subcommands = {
async init(args, {user}) {
const mergedUser = await getUser(user.id)
const currentCycle = await getLatestCycleForChapter(mergedUser.chapterId)
if (currentCycle.state !== REFLECTION && currentCycle.state !== COMPLETE) {
throw new LGBadRequestError('Failed to initialize a new cycle because the current cycle is still in progress.')
}
await _createCycle(mergedUser)
return {
text: '🔃 Initializing Cycle ... stand by.'
}
},
async launch(args, {user}) {
await _changeCycleState(user, PRACTICE)
return {
text: '🚀 Initiating Launch ... stand by.',
}
},
async reflect(args, {user}) {
await _changeCycleState(user, REFLECTION)
return {
text: '🤔 Initiating Reflection... stand by.',
}
},
}
export async function invoke(args, options) {
if (args._.length >= 1) {
const subcommand = args._[0]
return await subcommands[subcommand](args.$[subcommand], options)
}
throw new LGCLIUsageError()
}
async function _createCycle(user) {
if (!userCan(user, 'createCycle')) {
throw new LGNotAuthorizedError()
}
const member = await assertUserIsMember(user.id)
return await createNextCycleForChapter(member.chapterId)
}
async function _changeCycleState(user, newState) {
const newStateIndex = CYCLE_STATES.indexOf(newState)
if (!userCan(user, 'updateCycle')) {
throw new LGNotAuthorizedError()
}
const member = await assertUserIsMember(user.id)
if (newStateIndex === -1) {
throw new LGBadRequestError(`Invalid cycle state ${newState}`)
}
if (newStateIndex === 0) {
throw new LGForbiddenError(`You cannot change the cycle state back to ${newState}`)
}
const validOriginState = CYCLE_STATES[newStateIndex - 1]
const cycles = await getCyclesInStateForChapter(member.chapterId, validOriginState)
if (cycles.length === 0) {
throw new LGForbiddenError(`No cycles for the chapter in ${validOriginState} state`)
}
return Cycle.get(cycles[0].id).updateWithTimestamp({state: newState})
}
|
/**
* Created by sunNode on 16/10/16.
*/
var should = require('should')
var app = require('../app')
var request = require('supertest')
describe('upload temporyary testing', function () {
it('uploadTemporyary should be return success', function (done) {
request(app)
.get('/admin/crawler')
.end(function (err, res) {
if (err) throw err
should.exist(res.text)
done()
})
})
})
|
module.exports = { str: "7.5.0" };
|
/** schemas.js **/
schemas = {
user: {
id: null,
name: null,
password: null
}
}
module.exports = schemas;
|
;
(function ($, scope) {
function NextendElementStyle(id, parameters) {
this.element = $('#' + id);
this.parameters = parameters;
this.defaultSetId = parameters.set;
this.element.parent()
.on('click', $.proxy(this.show, this));
this.element.siblings('.n2-form-element-clear')
.on('click', $.proxy(this.clear, this));
this.name = this.element.siblings('input');
nextend.styleManager.$.on('visualDelete', $.proxy(this.styleDeleted, this));
this.updateName(this.element.val());
NextendElement.prototype.constructor.apply(this, arguments);
};
NextendElementStyle.prototype = Object.create(NextendElement.prototype);
NextendElementStyle.prototype.constructor = NextendElementStyle;
NextendElementStyle.prototype.show = function (e) {
e.preventDefault();
if (this.parameters.font != '') {
nextend.styleManager.setConnectedFont(this.parameters.font);
}
if (this.parameters.font2 != '') {
nextend.styleManager.setConnectedFont2(this.parameters.font2);
}
if (this.parameters.style2 != '') {
nextend.styleManager.setConnectedStyle(this.parameters.style2);
}
if (this.defaultSetId) {
nextend.styleManager.changeSetById(this.defaultSetId);
}
nextend.styleManager.show(this.element.val(), $.proxy(this.save, this), {
previewMode: this.parameters.previewmode,
previewHTML: this.parameters.preview
});
};
NextendElementStyle.prototype.clear = function (e) {
e.preventDefault();
e.stopPropagation();
this.val('');
};
NextendElementStyle.prototype.save = function (e, value) {
nextend.styleManager.addVisualUsage(this.parameters.previewmode, value, window.nextend.pre);
this.val(value);
};
NextendElementStyle.prototype.val = function (value) {
this.element.val(value);
this.updateName(value);
this.triggerOutsideChange();
};
NextendElementStyle.prototype.insideChange = function (value) {
this.element.val(value);
this.updateName(value);
this.triggerInsideChange();
};
NextendElementStyle.prototype.updateName = function (value) {
$.when(nextend.styleManager.getVisual(value))
.done($.proxy(function (style) {
this.name.val(style.name);
}, this));
};
NextendElementStyle.prototype.styleDeleted = function (e, id) {
if (id == this.element.val()) {
this.insideChange('');
}
};
NextendElementStyle.prototype.renderStyle = function () {
var style = this.element.val();
nextend.styleManager.addVisualUsage(this.parameters.previewmode, style, '');
return nextend.styleManager.getClass(style, this.parameters.previewmode);
};
scope.NextendElementStyle = NextendElementStyle;
$(window).ready(function () {
new NextendElementContextMenu('.n2-form-element-style', 'style');
});
})(n2, window);
|
define(function() {
var config = {
paths: {
FAOSTAT_UI_COMMONS: 'faostat-ui-commons',
faostat_ui_commons: '../'
},
shim: {
bootstrap: {
deps: ['jquery']
}
}
};
return config;
});
|
// initializeSearchBox
// Description: used to set an initial value for the search
// box, clear it when the user clicks into it and
// reset the value if no text was entered
function initializeSearchBox() {
var inputPrompt = "Search people and the Web";
$("#q").val(inputPrompt);
$("#q").focus(function(){
if ($(this).val() == inputPrompt) {
$(this).val("");
}
});
$("#q").blur(function(){
if ($(this).val() == "") {
$(this).val(inputPrompt);
}
});
}
//searchAction
//Description: used to determine the form action, searching the web or directory
function initializeSearchAction() {
document.getElementById('search-button-people').onclick = function() {
var form = document.getElementById('searchform');
form.action = 'http://www3.unca.edu/directory/';
form.method = 'POST'
$('.cse').remove();
form.submit();
}
}
// initializeNavigationSecondary
// Description: used to create expandable subnavigation menus
function initializeNavigationSecondary () {
//close open menus and change the trigger image
if($.browser.msie && $.browser.version == "6.0") {
return;
}
$('.navigation-secondary ul.menu li ul').hide();
$('.navigation-secondary ul.menu li.active-trail ul').show();
$('.navigation-secondary ul.menu li.active-trail ul li ul').hide();
$('.navigation-secondary ul.menu li.active-trail ul li.active-trail ul').show();
$(".navigation-secondary ul.menu li.expanded ul").before("<span class='trigger trigger-closed'/>");
$('.navigation-secondary ul.menu li.active-trail span').toggleClass('trigger-closed');
$('.navigation-secondary ul.menu li.active-trail ul li span').toggleClass('trigger-closed');
$('.navigation-secondary ul.menu li.active-trail ul li.active-trail span').toggleClass('trigger-closed');
$('.trigger').click(function() {
$(this).toggleClass('trigger-closed');
$(this).siblings('ul').toggle();
return false;
});
}
function initializeSlideshow(width) {
var currentPosition = 0;
var slideWidth = width;
var slides = $('.slide');
var numberOfSlides = slides.length;
// Remove scrollbar in JS
$('#slidesContainer').css('overflow', 'hidden');
// Wrap all .slides with #slideInner div
slides
.wrapAll('<div id="slideInner"></div>')
// Float left to display horizontally, readjust .slides width
.css({
'float' : 'left',
'width' : slideWidth
});
// Set #slideInner width equal to total width of all slides
$('#slideInner').css('width', slideWidth * numberOfSlides);
// Insert left and right arrow controls in the DOM
$('#slideshow')
.append('<span class="control" id="leftControl">Move left</span>')
.append('<span class="control" id="rightControl">Move right</span>');
// Hide left arrow control on first load
manageControls(currentPosition);
// Create event listeners for .controls clicks
$('.control').bind('click', function(){
// Determine new position
currentPosition = ($(this).attr('id')=='rightControl')
? currentPosition+1 : currentPosition-1;
// Hide / show controls
manageControls(currentPosition);
// Move slideInner using margin-left
$('#slideInner').animate({
'marginLeft' : slideWidth*(-currentPosition)
});
});
// manageControls: Hides and shows controls depending on currentPosition
function manageControls(position){
// Hide left arrow if position is first slide
if(position==0){ $('#leftControl').hide() }
else{ $('#leftControl').show() }
// Hide right arrow if position is last slide
if(position==numberOfSlides-1){ $('#rightControl').hide() }
else{ $('#rightControl').show() }
}
}
|
describe('fs-xhr',function() {
function createJQPromise(success) {
return {
done: function() {
var p = Q.when(success);
return p.then.apply(p,arguments);
}
};
}
var fakeJQuery = {
get: jasmine.createSpy('jqget').andReturn(createJQPromise('get')),
post: jasmine.createSpy('jqpost').andReturn(createJQPromise('post')),
ajax: jasmine.createSpy('jqajax').andReturn(createJQPromise('ajax'))
};
var fs = factory('services/fs-xhr',{
'q':Q,
'jquery': fakeJQuery
});
describe('fs signature',function() {
it('should have a read method',function() {
expect(fs.read).not.toBeUndefined();
});
it('should have a write method',function() {
expect(fs.write).not.toBeUndefined();
});
it('should have a remove method',function() {
expect(fs.remove).not.toBeUndefined();
});
});
describe('reading',function() {
it('should read a test file',function() {
return fs.read('foo.txt').then(function(data) {
expect(data).toBe('get');
expect(fakeJQuery.get).toHaveBeenCalledWith('fs/foo.txt');
});
});
it('should fail on xhr exception',function() {
fakeJQuery.get.andReturn(createJQPromise(Q.reject(new Error('foo'))));
return fs.read('foo.txt').catch(function(err) {
expect(fakeJQuery.get).toHaveBeenCalledWith('fs/foo.txt');
expect(err.message).toBe('foo');
});
});
});
describe('writing',function() {
it('should write a test file',function() {
return fs.write('foo.txt','bar').then(function(data) {
expect(fakeJQuery.post).toHaveBeenCalledWith('fs/foo.txt','bar');
expect(data).toBe('post');
});
});
it('should fail on xhr exception',function() {
fakeJQuery.post.andReturn(createJQPromise(Q.reject(new Error('foo'))));
return fs.write('foo.txt','bar').catch(function(err) {
expect(fakeJQuery.post).toHaveBeenCalledWith('fs/foo.txt','bar');
expect(err.message).toBe('foo');
});
});
});
describe('removing',function() {
it('should remove a test file',function() {
return fs.remove('foo.txt').then(function(data) {
expect(fakeJQuery.ajax).toHaveBeenCalledWith('fs/foo.txt',{
type: 'DELETE'
});
expect(data).toBe('ajax');
});
});
it('should fail on xhr exception',function() {
fakeJQuery.ajax.andReturn(createJQPromise(Q.reject(new Error('foo'))));
return fs.remove('foo.txt','bar').catch(function(err) {
expect(fakeJQuery.ajax).toHaveBeenCalledWith('fs/foo.txt',{
type: 'DELETE'
});
expect(err.message).toBe('foo');
});
});
});
});
|
/**
* @file
* Webform module Gmap admin page script.
*/
(function ($) {
Drupal.behaviors.gmapAdmin = {
attach: function(context, settings) {
var lat = Drupal.settings.gmap.lat;
var lon = Drupal.settings.gmap.lon;
var zoom = Drupal.settings.gmap.zoom;
var icon = Drupal.settings.gmap.path;
var latlng = new google.maps.LatLng(lat, lon);
var myOptions = {
zoom: parseInt(zoom),
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("gmap"), myOptions);
var input = (document.getElementById('MapLocation'));
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
google.maps.event.addListener(autocomplete, 'place_changed', function(event) {
var place = autocomplete.getPlace();
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17);
}
var address = '';
if (place.address_components) {
address = [
(place.address_components[0] && place.address_components[0].short_name || ''),
(place.address_components[1] && place.address_components[1].short_name || ''),
(place.address_components[2] && place.address_components[2].short_name || '')
].join(' ');
}
placeMarker(place.geometry.location);
});
var marker = new google.maps.Marker({
position: latlng,
map: map,
icon: icon
});
google.maps.event.addListener(map, 'zoom_changed', function() {
document.getElementById('gmap_zoom').value = map.getZoom();
});
google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
});
function placeMarker(location) {
marker.setPosition(location);
document.getElementById('gmap_lat').value = location.lat();
document.getElementById('gmap_lon').value = location.lng();
}
}
};
})(jQuery);
|
(function( $ ) {
/**
* Activity reply object for the activity index screen
*
* @since ajency-activity-and-notifications (1.6)
*/
var activityReply = {
/**
* Attach event handler functions to the relevant elements.
*
* @since ajency-activity-and-notifications (1.6)
*/
init : function() {
$(document).on( 'click', '.row-actions a.reply', activityReply.open );
$(document).on( 'click', '#bp-activities-container a.cancel', activityReply.close );
$(document).on( 'click', '#bp-activities-container a.save', activityReply.send );
// Close textarea on escape
$(document).on( 'keyup', '#bp-activities:visible', function( e ) {
if ( 27 == e.which ) {
activityReply.close();
}
});
},
/**
* Reveals the entire row when "reply" is pressed.
*
* @since ajency-activity-and-notifications (1.6)
*/
open : function( e ) {
// Hide the container row, and move it to the new location
var box = $( '#bp-activities-container' ).hide();
$( this ).parents( 'tr' ).after( box );
// Fade the whole row in, and set focus on the text area.
box.fadeIn( '300' );
$( '#bp-activities' ).focus();
return false;
},
/**
* Hide and reset the entire row when "cancel", or escape, are pressed.
*
* @since ajency-activity-and-notifications (1.6)
*/
close : function( e ) {
// Hide the container row
$('#bp-activities-container').fadeOut( '200', function () {
// Empty and unfocus the text area
$( '#bp-activities' ).val( '' ).blur();
// Remove any error message and disable the spinner
$( '#bp-replysubmit .error' ).html( '' ).hide();
$( '#bp-replysubmit .waiting' ).hide();
});
return false;
},
/**
* Submits "form" via AJAX back to WordPress.
*
* @since ajency-activity-and-notifications (1.6)
*/
send : function( e ) {
// Hide any existing error message, and show the loading spinner
$( '#bp-replysubmit .error' ).hide();
$( '#bp-replysubmit .waiting' ).show();
// Grab the nonce
var reply = {};
reply['_ajax_nonce-bp-activity-admin-reply'] = $( '#bp-activities-container input[name="_ajax_nonce-bp-activity-admin-reply"]' ).val();
// Get the rest of the data
reply.action = 'bp-activity-admin-reply';
reply.content = $( '#bp-activities' ).val();
reply.parent_id = $( '#bp-activities-container' ).prev().data( 'parent_id' );
reply.root_id = $( '#bp-activities-container' ).prev().data( 'root_id' );
// Make the AJAX call
$.ajax({
data : reply,
type : 'POST',
url : ajaxurl,
// Callbacks
error : function( r ) { activityReply.error( r ); },
success : function( r ) { activityReply.show( r ); }
});
return false;
},
/**
* send() error message handler
*
* @since ajency-activity-and-notifications (1.6)
*/
error : function( r ) {
var er = r.statusText;
$('#bp-replysubmit .waiting').hide();
if ( r.responseText ) {
er = r.responseText.replace( /<.[^<>]*?>/g, '' );
}
if ( er ) {
$('#bp-replysubmit .error').html( er ).show();
}
},
/**
* send() success handler
*
* @since ajency-activity-and-notifications (1.6)
*/
show : function ( xml ) {
var bg, id, response;
// Handle any errors in the response
if ( typeof( xml ) == 'string' ) {
activityReply.error( { 'responseText': xml } );
return false;
}
response = wpAjax.parseAjaxResponse( xml );
if ( response.errors ) {
activityReply.error( { 'responseText': wpAjax.broken } );
return false;
}
response = response.responses[0];
// Close and reset the reply row, and add the new Activity item into the list.
$('#bp-activities-container').fadeOut( '200', function () {
// Empty and unfocus the text area
$( '#bp-activities' ).val( '' ).blur();
// Remove any error message and disable the spinner
$( '#bp-replysubmit .error' ).html( '' ).hide();
$( '#bp-replysubmit .waiting' ).hide();
// Insert new activity item
$( '#bp-activities-container' ).before( response.data );
// Get background colour and animate the flash
id = $( '#activity-' + response.id );
bg = id.closest( '.widefat' ).css( 'backgroundColor' );
id.animate( { 'backgroundColor': '#CEB' }, 300 ).animate( { 'backgroundColor': bg }, 300 );
});
}
};
$(document).ready( function () {
// Create the Activity reply object after domready event
activityReply.init();
// On the edit screen, unload the close/open toggle js for the action & content metaboxes
$( '#ajan_activity_action h3, #ajan_activity_content h3' ).unbind( 'click' );
// redo the post box toggles to reset the one made by comment.js in favor
// of activity administration page id so that metaboxes are still collapsible
// in single Activity Administration screen.
postboxes.add_postbox_toggles( ajan_activity_admin_vars.page );
});
})(jQuery);
|
script('../node_modules/domready/ready.js', function () {
domready(function() {
sink('Basic', function(test, ok, before, after) {
test('should call from chained ready calls', 4, function() {
script.ready('jquery', function() {
ok(true, 'loaded from ready callback')
})
script.ready('jquery', function() {
ok(true, 'called jquery callback again')
})
.ready('jquery', function() {
ok(true, 'called ready on a chain')
})
script('../vendor/jquery.js', 'jquery', function() {
ok(true, 'loaded from base callback')
})
})
test('multiple files can be loaded at once', 1, function() {
script(['../demos/js/foo.js', '../demos/js/bar.js'], function() {
ok(true, 'foo and bar have been loaded')
})
})
test('ready should wait for multiple files by name', 1, function() {
script(['../demos/js/baz.js', '../demos/js/thunk.js'], 'bundle').ready('bundle', function() {
ok(true, 'batch has been loaded')
})
})
test('ready should wait for several batches by name', 1, function() {
script('../vendor/yui-utilities.js', 'yui')
script('../vendor/mootools.js', 'moomoo')
script.ready(['yui', 'moomoo'], function() {
console.log('ONCE')
ok(true, 'multiple batch has been loaded')
})
})
test('ready should not call a duplicate callback', 1, function() {
script.ready(['yui', 'moomoo'], function() {
console.log('TWICE')
ok(true, 'found yui and moomoo again')
})
})
test('ready should not call a callback a third time', 1, function() {
script.ready(['yui', 'moomoo'], function() {
console.log('THREE')
ok(true, 'found yui and moomoo again')
})
})
test('should load a single file without extra arguments', 1, function () {
var err = false
try {
script('../vendor/yui-utilities.js')
} catch (ex) {
err = true
console.log('wtf ex', ex)
} finally {
ok(!err, 'no error')
}
})
test('should callback a duplicate file without loading the file', 1, function () {
script('../vendor/yui-utilities.js', function () {
ok(true, 'loaded yui twice. nice')
})
})
test('onerror', 1, function () {
script('waaaaaaaaaaaa', function () {
ok(true, 'no waaaa')
})
})
test('setting script path', 3, function () {
script.path('../vendor/')
script(['patha', 'pathb', 'http://ded.github.com/morpheus/morpheus.js'], function () {
ok(patha == true, 'loaded patha.js')
ok(pathb == true, 'loaded pathb.js')
ok(typeof morpheus !== 'undefined', 'loaded morpheus.js from http')
})
})
test('syncronous ordered loading', 2, function () {
script.order(['order-a', 'order-b', 'order-c'], 'ordered-id', function () {
ok(true, 'loaded each file in order')
console.log('loaded each file in order')
})
script.ready('ordered-id', function () {
console.log('readiness by id')
ok(ordera && orderb && orderc, 'done listen for readiness by id')
})
})
})
start()
})
})
|
var winston = require('winston');
module.exports = function(app, models, tasks, channel) {
// initialize the sync of a repo
app.post('/', function (req, res) {
winston.log("info", "POST /");
channel.sendToQueue("gms.queue", new Buffer(JSON.stringify(req.body)), {deliveryMode: true});
res.sendStatus(201);
});
};
|
define(
//begin v1.x content
{
"decimal": ".",
"group": ",",
"list": ";",
"percentSign": "%",
"plusSign": "+",
"minusSign": "-",
"exponential": "E",
"perMille": "‰",
"infinity": "∞",
"nan": "NaN",
"decimalFormat": "#,##0.###",
"decimalFormat-short": "000조",
"scientificFormat": "#E0",
"percentFormat": "#,##0%",
"currencyFormat": "¤#,##0.00"
}
//end v1.x content
);
|
jQuery.fn.resolveLetterData = function() {
var letterTypes = [];
letterTypes.push("Peraturan");
letterTypes.push("Pedoman");
letterTypes.push("Petunjuk Pelaksanaan");
letterTypes.push("Instruksi");
letterTypes.push("Prosedur Tetap (SOP)");
letterTypes.push("Surat Edaran");
letterTypes.push("Keputusan");
letterTypes.push("Surat Perintah/Surat Tugas");
letterTypes.push("Nota Dinas");
letterTypes.push("Memorandum");
letterTypes.push("Surat Dinas");
letterTypes.push("Surat Undangan");
letterTypes.push("Surat Perjanjian");
letterTypes.push("Surat Kuasa");
letterTypes.push("Berita Acara");
letterTypes.push("Surat Keterangan");
letterTypes.push("Surat Pengantar");
letterTypes.push("Pengumuman");
letterTypes.push("Laporan");
letterTypes.push("Lain-lain");
var letterPriorities = ["Biasa", "Segera", "Amat Segera"];
var letterPrioritiesClasses = ["success", "warning", "important"];
var letterClassifications = ["Biasa", "Rahasia", "Sangat Rahasia"];
var letterClassificationClasses = ["success", "warning", "important"];
var letterStatus = [
"Dalam proses penulisan",
"Dalam proses pemeriksaan keluar",
"Menunggu proses pengiriman",
"Terkirim",
"Belum dibaca",
"Belum semua penerima telah membaca",
"Penerima telah membaca",
];
var letterStatusClasses = [
"warning",
"warning",
"warning",
"important",
"warning",
"success",
];
var items = $(this);
for (var i = 0; i < items.length; i ++) {
var item = items[i];
var value = $(item).attr("data-value");
var type = $(item).attr("data-type");
var index = parseInt(value);
if (!isNaN(index)) {
if (type == "type")
$(item).text(letterTypes[value]);
else if (type == "classification") {
$(item).text(letterClassifications[value]);
$(item).addClass("label label-" + letterClassificationClasses[value]);
} else if (type == "priority") {
$(item).text(letterPriorities[value]);
$(item).addClass("label label-" + letterPrioritiesClasses[value]);
} else if (type == "status") {
$(item).text(letterStatus[value]);
$(item).addClass("label label-" + letterStatusClasses[value]);
}
} else {
$(item).text("Tidak diketahui");
}
}
}
function updateSearchDateVisibility(e) {
var searchByDate = ($(e).attr("data-type") === "date");
if (searchByDate) {
$(".search-date").removeClass("hidden");
$("#search-string").addClass("hidden");
} else {
$(".search-date").addClass("hidden");
$("#search-string").removeClass("hidden");
}
}
$(document).ready(function() {
$(".resolve-letter-data").resolveLetterData();
$("#search-type").change(function(){
$("select[id='search-type'] option:selected").each(function(){
updateSearchDateVisibility(this);
});
});
});
|
import {Actions} from 'relax-framework';
class StyleActions extends Actions {
init () {
}
getActions () {
return [
'add',
'remove',
'update'
];
}
}
export default new StyleActions();
|
$(document).ready(function () {
var dropdown_fields_item_count = 0; // Global unique counter
$('#dropdown_fields').hide();
if ($('#custom_field_type').val() == 'dropdown' || $('#custom_field_type').val() == 'checkbox') {
$('#dropdown_fields').show();
}
$('#custom_field_type').change(function() {
if ($(this).val() == 'dropdown' || $('#custom_field_type').val() == 'checkbox') {
$('#dropdown_fields').show();
}
else {
$('#dropdown_fields').hide();
}
});
//Add new dropdown item
$('body').on('click', '#add_dropdown_field', function(e){
e.preventDefault();
dropdown_fields_item_count++; // Increment counter
var clonedRow = $('.dropdown_field').clone();
$(clonedRow).addClass('new_dropdown_field').removeClass('dropdown_field');
$(clonedRow).find('input').val('').end().find('p').append(' <a href="#dropdown" id="delete_dropdown_item" class="btn btn-danger">Delete</a>').end().appendTo('.extra_dropdown_field');
});
//Delete line item
$('body').on('click', '#delete_dropdown_item', function(e){
e.preventDefault();
$(this).parent('p').remove();
});
});
|
let io = require('socket.io-client');
let server = io('http://localhost:3000/');
let dispatcher = require('../dispatcher');
server.on('dispatch', dispatcher.handleServerAction.bind(dispatcher));
dispatcher.register(function(payload) {
if (payload.sendToServer) {
server.emit('message', payload.action);
}
return true;
});
|
// **********************************************************************
//
// Copyright (c) 2003-2014 ZeroC, Inc. All rights reserved.
//
// This copy of Ice is licensed to you under the terms described in the
// ICE_LICENSE file included in this distribution.
//
// **********************************************************************
(function(global){
var Ice = global.Ice || {};
var DispatchStatus = {DispatchOK: 0, DispatchUserException: 1, DispatchAsync: 2};
Ice.DispatchStatus = DispatchStatus;
global.Ice = Ice;
}(typeof (global) === "undefined" ? window : global));
|
/**
* Head
*
* This file should only include basic environment setup logic and browser feature tests
*
* This should be included before the stylesheet so the browser doesn't need to reflow after adding the feature
* detect classes from modernizer. Since this goes before the stylesheet this file should be placed inline into the html.
*
* Where possible this file should always be minified and obfuscated via `grunt build`.
*
* BEWARE: This file and all dependencies of this file should not exceed 1.5kb or it will slow down every page
* request as it can't be cached since it's inline and all.
*
*/
module.exports = function() {
'use strict';
};
|
'use strict'
const assert = require('assert')
const test = require('../../lib/test')
const Test = test.Test()
describe('Functional Contract Usage', function () {
before(Test.before())
after(Test.after())
this.timeout(10 * 1000)
it('#Constructor usage', Test.it(function (burrow) {
const source = `
pragma solidity ^0.4.21;
contract Test {
address storedData;
constructor(address x) public {
storedData = x;
}
function getAddress() public view returns (address) {
return this;
}
function getNumber() public pure returns (uint) {
return 100;
}
function getCombination() public view returns (uint _number, address _address, string _saying, bytes32 _randomBytes, address _stored) {
_number = 100;
_address = this;
_saying = "hello moto";
_randomBytes = 0xDEADBEEFFEEDFACE;
_stored = storedData;
}
}
`
const {abi, bytecode} = test.compile(source, ':Test')
const contract = burrow.contracts.new(abi, bytecode)
let A1
let A2
assert.equal(contract.address, null)
// Use the _contructor method to creat two contracts
return Promise.all(
[contract._constructor('88977A37D05A4FE86D09E88C88A49C2FCF7D6D8F'),
contract._constructor('ABCDEFABCDEFABCDEFABCDEFABCDEFABCDEF0123')])
.then(([address1, address2]) => {
assert.equal(contract.address, null)
A1 = address1
A2 = address2
return Promise.all(
[contract.getCombination.at(A1),
contract.getCombination.at(A2)])
})
.then(([object1, object2]) => {
const expected1 = [100, A1, 'hello moto', '000000000000000000000000000000000000000000000000DEADBEEFFEEDFACE', '88977A37D05A4FE86D09E88C88A49C2FCF7D6D8F']
const expected2 = [100, A2, 'hello moto', '000000000000000000000000000000000000000000000000DEADBEEFFEEDFACE', 'ABCDEFABCDEFABCDEFABCDEFABCDEFABCDEF0123']
assert.deepEqual(object1, expected1)
assert.deepEqual(object2, expected2)
})
}))
})
|
/*!
* VisualEditor IME test for Firefox on Windows in Welsh.
*
* @copyright 2011-2016 VisualEditor Team and others; see http://ve.mit-license.org
*/
ve.ce.imetests.push( [ 'input-firefox-win7-welsh', [
{ imeIdentifier: 'Welsh', userAgent: 'Mozilla/5.0 (Windows NT 6.1; rv:19.0) Gecko/20100101 Firefox/19.0', startDom: '' },
{ seq: 0, time: 4.995, action: 'sendEvent', args: [ 'keydown', { keyCode: 68 } ] },
{ seq: 1, time: 4.998, action: 'sendEvent', args: [ 'keypress', { keyCode: 0 } ] },
{ seq: 2, time: 5.001, action: 'changeText', args: [ 'd' ] },
{ seq: 3, time: 5.001, action: 'changeSel', args: [ 1, 1 ] },
{ seq: 4, time: 5.001, action: 'sendEvent', args: [ 'input', {} ] },
{ seq: 5, time: 5.004, action: 'endLoop', args: [] },
{ seq: 6, time: 5.059, action: 'sendEvent', args: [ 'keyup', { keyCode: 68 } ] },
{ seq: 7, time: 5.061, action: 'endLoop', args: [] },
{ seq: 8, time: 6.707, action: 'sendEvent', args: [ 'keydown', { keyCode: 17 } ] },
{ seq: 9, time: 6.709, action: 'sendEvent', args: [ 'keydown', { keyCode: 18 } ] },
{ seq: 10, time: 6.711, action: 'endLoop', args: [] },
{ seq: 11, time: 6.712, action: 'endLoop', args: [] },
{ seq: 12, time: 7.179, action: 'sendEvent', args: [ 'keydown', { keyCode: 54 } ] },
{ seq: 13, time: 7.181, action: 'endLoop', args: [] },
{ seq: 14, time: 7.299, action: 'sendEvent', args: [ 'keyup', { keyCode: 54 } ] },
{ seq: 15, time: 7.301, action: 'endLoop', args: [] },
{ seq: 16, time: 7.533, action: 'sendEvent', args: [ 'keyup', { keyCode: 17 } ] },
{ seq: 17, time: 7.535, action: 'endLoop', args: [] },
{ seq: 18, time: 9.708, action: 'sendEvent', args: [ 'keydown', { keyCode: 87 } ] },
{ seq: 19, time: 9.71, action: 'sendEvent', args: [ 'keypress', { keyCode: 0 } ] },
{ seq: 20, time: 9.713, action: 'changeText', args: [ 'dŵ' ] },
{ seq: 21, time: 9.713, action: 'changeSel', args: [ 2, 2 ] },
{ seq: 22, time: 9.713, action: 'sendEvent', args: [ 'input', {} ] },
{ seq: 23, time: 9.718, action: 'endLoop', args: [] },
{ seq: 24, time: 9.817, action: 'sendEvent', args: [ 'keyup', { keyCode: 87 } ] },
{ seq: 25, time: 9.82, action: 'endLoop', args: [] },
{ seq: 26, time: 11.445, action: 'sendEvent', args: [ 'keydown', { keyCode: 82 } ] },
{ seq: 27, time: 11.45, action: 'sendEvent', args: [ 'keypress', { keyCode: 0 } ] },
{ seq: 28, time: 11.454, action: 'changeText', args: [ 'dŵr' ] },
{ seq: 29, time: 11.454, action: 'changeSel', args: [ 3, 3 ] },
{ seq: 30, time: 11.454, action: 'sendEvent', args: [ 'input', {} ] },
{ seq: 31, time: 11.461, action: 'endLoop', args: [] },
{ seq: 32, time: 11.519, action: 'sendEvent', args: [ 'keyup', { keyCode: 82 } ] },
{ seq: 33, time: 11.523, action: 'endLoop', args: [] }
] ] );
|
const preferenceManager = require('../utils/preference-manager');
const logout = () => {
preferenceManager.deleteCredentials();
};
module.exports = {
logout,
};
|
export const utils = {}
utils.getChoiceById = (choices, choiceId) => {
return choices.find(choice => choice.id === choiceId)
}
utils.isSolutionChecked = (solution, answers) => {
return answers ? answers.indexOf(solution.id) > -1 : false
}
utils.answerId = (id) => {
return `${id}-your-answer`
}
utils.expectedId = (id) => {
return `${id}-expected-answer`
}
utils.getAnswerClassForSolution = (solution, answers, hasExpectedAnswer = true) => {
const checked = utils.isSolutionChecked(solution, answers)
if (checked) {
if (hasExpectedAnswer) {
if (solution.score > 0) {
return 'correct-answer'
}
return 'incorrect-answer'
}
return 'selected-answer'
}
return ''
}
utils.setChoiceTicks = (choices, multiple = false) => {
if (multiple) {
choices.map(choice => choice.checked = choice.score > 0)
} else {
let max = 0
let maxId = null
choices.map(choice => {
if (choice.score > max) {
max = choice.score
maxId = choice.id
}
})
choices.map(choice =>
choice.checked = max > 0 && choice.id === maxId
)
}
return choices
}
|
/*
Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'selectall', 'nb', {
toolbar: 'Merk alt'
} );
|
/*
Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'image', 'fa', {
alertUrl: 'لطفا URL تصویر را بنویسید',
alt: 'متن جایگزین',
border: 'لبه',
btnUpload: 'به سرور بفرست',
button2Img: 'آیا مایلید از یک تصویر ساده روی دکمه تصویری انتخاب شده استفاده کنید؟',
hSpace: 'فاصلهٴ افقی',
img2Button: 'آیا مایلید از یک دکمه تصویری روی تصویر انتخاب شده استفاده کنید؟',
infoTab: 'اطلاعات تصویر',
linkTab: 'پیوند',
lockRatio: 'قفل کردن نسبت',
menu: 'ویژگیهای تصویر',
resetSize: 'بازنشانی اندازه',
title: 'ویژگیهای تصویر',
titleButton: 'ویژگیهای دکمهٴ تصویری',
upload: 'انتقال به سرور',
urlMissing: 'آدرس URL اصلی تصویر یافت نشد.',
vSpace: 'فاصلهٴ عمودی',
validateBorder: 'مقدار خطوط باید یک عدد باشد.',
validateHSpace: 'مقدار فاصله گذاری افقی باید یک عدد باشد.',
validateVSpace: 'مقدار فاصله گذاری عمودی باید یک عدد باشد.'
} );
|
var spawn = require('child_process').spawn
var express = require('express')
var assets = __dirname + "/../../static"
var server = express()
server.use(express.cookieParser(' default '))
server.use(express.session({secret:' default '}))
server.use(express.bodyParser())
server.use(express.static(assets))
server.get('/', function(req, res){
res.send(
'<html>'
+ '<body>'
+ '<button>Test</button>'
+ '<script src="/jq.js"></script>'
+ '<script>$("button").click(function(){'
+ 'var windowObjectReference;'
+ 'function openRequestedPopup(data) {'
+ 'windowObjectReference = window.open("/preview/pdf", "Preview", strWindowFeatures);'
+ '}'
+ 'var strWindowFeatures = "menubar=no,location=no,resizable=no,scrollbars=no,status=no";'
+ '$.post("/preview/render", { data : {"body" : "<b>This is <i>a cool</i> test</b> converting html to pdf via stdout <i>stream</i>"}}, function(data){ openRequestedPopup(data) })'
+ '})</script>'
+ '</body></html>')
})
server.get('/preview/pdf', function(req, res){
var preview = spawn('phantomjs', [__dirname + '/../../simaya/controller/scripts/pdf.js', req.session.data])
res.set('Content-type', 'application/pdf')
preview.stdout.pipe(res)
})
server.post('/preview/render', function(req, res){
req.session.data = req.body.data.body
res.send({})
})
server.listen(8000)
|
module.exports = function dendro_shade_bars(params, inst_selection, inst_rc, inst_data){
var inst_opacity = 0.2;
var bot_height;
d3.selectAll(params.root+' .dendro_shadow')
.remove();
if (inst_rc == 'row'){
// top shade
d3.select(params.root+' .clust_group')
.append('rect')
.attr('width', params.viz.clust.dim.width+'px')
.attr('height', inst_data.pos_top+'px')
.attr('fill','black')
.classed('dendro_shadow',true)
.attr('opacity', inst_opacity);
bot_height = params.viz.clust.dim.height - inst_data.pos_bot;
// bottom shade
d3.select(params.root+' .clust_group')
.append('rect')
.attr('width', params.viz.clust.dim.width+'px')
.attr('height', bot_height+'px')
.attr('transform','translate(0,'+inst_data.pos_bot+')')
.attr('fill','black')
.classed('dendro_shadow',true)
.attr('opacity', inst_opacity);
} else if (inst_rc === 'col'){
// top shade
d3.select(params.root+' .clust_group')
.append('rect')
.attr('width', inst_data.pos_top+'px')
.attr('height', params.viz.clust.dim.height+'px')
.attr('fill','black')
.classed('dendro_shadow',true)
.attr('opacity', inst_opacity);
// bottom shade
bot_height = params.viz.clust.dim.width - inst_data.pos_bot;
d3.select(params.root+' .clust_group')
.append('rect')
.attr('width', bot_height+'px')
.attr('height', params.viz.clust.dim.height+'px')
.attr('transform','translate('+inst_data.pos_bot+',0)')
.attr('fill','black')
.classed('dendro_shadow',true)
.attr('opacity',inst_opacity);
}
};
|
define([
'underscore',
'backbone',
'models/version'
], function(_, Backbone, VersionModel){
var VersionCollection = Backbone.Collection.extend({
model: VersionModel,
parse: function(response) {
return response.data.versions;
},
healthClasses: {
'OK': { badge: 'badge-success', icon: 'icon-ok' },
'WARNING': { badge: 'badge-warning', icon: 'icon-warning-sign' },
'ERROR': { badge: 'badge-important', icon: 'icon-ban-circle' }
},
comparator: function(version) {
return -version.get("version");
}
});
return VersionCollection;
});
|
/* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/publicdomain/zero/1.0/
*/
/* File locked partial MAR file staged patch apply failure test */
const STATE_AFTER_STAGE = STATE_PENDING;
function run_test() {
if (!setupTestCommon()) {
return;
}
gTestFiles = gTestFilesPartialSuccess;
gTestDirs = gTestDirsPartialSuccess;
setTestFilesAndDirsForFailure();
setupUpdaterTest(FILE_PARTIAL_MAR, false);
}
/**
* Called after the call to setupUpdaterTest finishes.
*/
function setupUpdaterTestFinished() {
runHelperLockFile(gTestFiles[2]);
}
/**
* Called after the call to waitForHelperSleep finishes.
*/
function waitForHelperSleepFinished() {
stageUpdate();
}
/**
* Called after the call to stageUpdate finishes.
*/
function stageUpdateFinished() {
checkPostUpdateRunningFile(false);
// Files aren't checked after staging since this test locks a file which
// prevents reading the file.
checkUpdateLogContains(ERR_ENSURE_COPY);
// Switch the application to the staged application that was updated.
runUpdate(STATE_FAILED_READ_ERROR, false, 1, false);
}
/**
* Called after the call to runUpdate finishes.
*/
function runUpdateFinished() {
waitForHelperExit();
}
/**
* Called after the call to waitForHelperExit finishes.
*/
function waitForHelperExitFinished() {
standardInit();
Assert.equal(readStatusFile(), STATE_NONE,
"the status file failure code" + MSG_SHOULD_EQUAL);
Assert.equal(gUpdateManager.updateCount, 2,
"the update manager updateCount attribute" + MSG_SHOULD_EQUAL);
Assert.equal(gUpdateManager.getUpdateAt(0).state, STATE_FAILED,
"the update state" + MSG_SHOULD_EQUAL);
Assert.equal(gUpdateManager.getUpdateAt(0).errorCode, READ_ERROR,
"the update errorCode" + MSG_SHOULD_EQUAL);
checkPostUpdateRunningFile(false);
checkFilesAfterUpdateFailure(getApplyDirFile);
checkUpdateLogContains(ERR_UNABLE_OPEN_DEST);
checkUpdateLogContains(STATE_FAILED_READ_ERROR + "\n" + CALL_QUIT);
checkCallbackLog();
}
|
// weather_base_url comes in via django and must be set before including this file
$(document).ready(function()
{
// Save the representative id
data_to_save['scenario_id'] = $('#scenario_id').val();
// Initializes description
$('#weather-select').change();
});
$('#weather-select').change(function()
{
var option_id = $('#weather-select').val();
var weather_data_url = weather_base_url + option_id + "/";
data_to_save['weather_id'] = option_id;
updateWeatherCharts(weather_data_url);
});
function change_climate(type)
{
// IDs of each climate type
var tropical_rainforest = 1;
var tropical_monsoonal = 2;
var wet_savannah = 3;
var dry_savannah = 9;
var arid = 8;
switch (type)
{
case 'Humid':
$('#weather-select').val(tropical_rainforest).change();
break;
case 'Moist Subhumid':
$('#weather-select').val(tropical_monsoonal).change();
break;
case 'Dry Subhumid':
$('#weather-select').val(wet_savannah).change();
break;
case 'Semi Arid':
$('#weather-select').val(dry_savannah).change();
break;
case 'Arid':
$('#weather-select').val(arid).change();
break;
default:
alert('Zone ' + type + ' is not valid.');
}
}
|
/**
* ownCloud - fuel
*
* This file is licensed under the Affero General Public License version 3 or
* later. See the COPYING file.
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @copyright Christoph Wurst 2015
*/
define(function (require) {
'use strinct';
var VehicleView = require('views/vehicle'),
Marionette = require('marionette');
return Marionette.CollectionView.extend({
tagName: 'ul',
childView: VehicleView,
initialize: function (options) {
options = options || {};
this.listenTo(this.collection, 'change', this.render);
}
});
});
|
// Stripe info
// Plan ID: BASIC_HOSTING_PLAN
// Cost: $5.00 per 30 days, no trial
// Statement: Hook.io Hosting Plan
var hook = require('../lib/resources/hook');
var user = require('../lib/resources/user');
var config = require('../config');
var bodyParser = require('body-parser');
var mergeParams = require('./mergeParams');
var request = require('request');
var billing = require('../lib/resources/billing')
var stripe = require('stripe')(config.stripe.secretKey);
var billingForm = require('./billingForm');
var addPaymentOption = require('./addPaymentOption');
module['exports'] = function view (opts, callback) {
var $ = this.$;
var req = opts.request, res = opts.response;
$('#addPaymentMethod').attr('data-key', config.stripe.publicKey);
bodyParser()(req, res, function bodyParsed(){
mergeParams(req, res, function(){});
var params = req.resource.params;
if (!req.isAuthenticated()) {
req.session.redirectTo = "/billing";
return res.redirect('/login');
}
// TODO: make it so billing information can be captured directly from the /pricing page
function showBillings (results, callback) {
var count = results.length;
function finish () {
var _billing = results[0];
// TODO: data bind $('#slider').slider("value", (_billing.amount / 100));
// console.log('databinding', _billing.amount)
$('#databind').text(' \
var resource = {}; \
resource.billing = { \
amount: ' + _billing.amount + ' \
};');
if (count === 0) {
callback(null);
}
};
results.forEach(function(item){
// item.destroy();
billingForm(item, function (err, re){
$('.billingForm').append(re);
count--;
finish();
});
});
};
$('.addPaymentOption').html(addPaymentOption());
// console.log('getting params', params);
// if new billing information was posted ( from account page ), add it
if (params.addCustomer) {
// console.log('adding new customer');
// create a new customer based on email address
stripe.customers.create(
{ email: params.stripeEmail },
function (err, customer) {
if (err) {
$('.status').html(err.message);
}
// console.log('new customer created', err, customer);
$('.status').html('New billing informationed added!');
// select plan based on user-selected value
var _plan = "BASIC_HOSTING_PLAN";
if (params.amount > 500) {
_plan = _plan + "_" + (params.amount / 100);
}
// console.log('attempting to use plan', _plan);
stripe.customers.createSubscription(customer.id, {
plan: _plan,
source: params.stripeToken // source is the token created from checkout.js
}, function(err, charge){
if (err) {
$('.status').addClass('error');
$('.status').html(err.message);
return callback(err, $.html());
}
billing.create({
owner: req.user.username,
stripeID: customer.id,
amount: params.amount,
plan: _plan
}, function (err, _billing) {
// console.log('new billing created', err, _billing);
if (err) {
$('.status').html(err.message);
return callback(null, err.message);
}
// console.log('added to plan', err, charge);
$('.status').html('Billing Information Added! Thank you!');
billing.find({ owner: req.user.username }, function (err, results) {
if (err) {
$('.status').html(err.message);
return callback(err, $.html());
}
showBillings(results, function(){
callback(err, $.html());
});
});
});
});
}
);
} else {
billing.find({ owner: req.user.username }, function (err, results) {
if (err) {
return callback(null, err.message);
}
// console.log('billing results', err, results)
if (results.length === 0) {
var checkOut = ' \
<form action="/billing" method="POST"> \
<input type="hidden" value="true" name="addCustomer"/> \
<script \
src="https://checkout.stripe.com/checkout.js" class="stripe-button" \
data-key="' + config.stripe.publicKey + '" \
data-image="/square-image.png" \
data-name="hook.io hosting" \
data-description="1 Month Basic Hosting ($5.00)" \
data-amount="500" \
data-currency="usd" \
data-bitcoin="true"> \
</script> \
</form> \
';
// $('.billingForm').html('<h3>No Billing Options Found!</h3>' + checkOut);
callback(null, $.html());
} else {
var _billing = results[0];
showBillings(results, function(){
callback(null, $.html());
});
// $('.billingForm').html(JSON.stringify(_billing, true, 2));
}
});
// callback(null, $.html());
}
});
};
|
/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'iframe', 'ka', {
border: 'ჩარჩოს გამოჩენა',
noUrl: 'აკრიფეთ iframe-ის URL',
scrolling: 'გადახვევის ზოლების დაშვება',
title: 'IFrame-ის პარამეტრები',
toolbar: 'IFrame'
});
|
"use strict";
/** @internalapi @module hooks */ /** */
Object.defineProperty(exports, "__esModule", { value: true });
/**
* A [[TransitionHookFn]] that rejects the Transition if it is invalid
*
* This hook is invoked at the end of the onBefore phase.
* If the transition is invalid (for example, param values do not validate)
* then the transition is rejected.
*/
function invalidTransitionHook(trans) {
if (!trans.valid()) {
throw new Error(trans.error().toString());
}
}
exports.registerInvalidTransitionHook = function (transitionService) {
return transitionService.onBefore({}, invalidTransitionHook, { priority: -10000 });
};
//# sourceMappingURL=invalidTransition.js.map
|
/*
Open Chord Charts -- Database of free chord charts
By: Christophe Benz <contact@openchordcharts.org>
Copyright (C) 2012, 2013, 2014, 2015 Christophe Benz
https://github.com/openchordcharts/
This file is part of Open Chord Charts.
Open Chord Charts is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
Open Chord Charts is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
@flow weak
*/
import webservices from "./webservices";
function forgetCredentials() {
delete sessionStorage.loggedInUsername;
global.authEvents.emit("loggedOut");
}
function login() {
return webservices.login().then((res) => {
if (res.login === "ok") {
sessionStorage.loggedInUsername = res.username;
global.authEvents.emit("loggedIn");
return true;
} else {
forgetCredentials();
return false;
}
});
}
function logout() {
// TODO simplify promises construct
return webservices.logout().catch(() => {
forgetCredentials();
}).then(() => {
forgetCredentials();
});
}
module.exports = {login, logout};
|
/*
* Copyright (C) 2019 - present Instructure, Inc.
*
* This file is part of Canvas.
*
* Canvas is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, version 3 of the License.
*
* Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import React from 'react'
import {bool, node, oneOf} from 'prop-types'
import {Alert} from '@instructure/ui-alerts'
import {ScreenReaderContent} from '@instructure/ui-a11y-content'
CanvasInlineAlert.propTypes = {
liveAlert: bool,
screenReaderOnly: bool,
politeness: oneOf(['assertive', 'polite']),
children: node
}
export default function CanvasInlineAlert({
children,
liveAlert,
screenReaderOnly,
politeness = 'assertive',
...alertProps
}) {
let body = children
if (liveAlert || screenReaderOnly) {
body = (
<span role="alert" aria-live={politeness} aria-atomic>
{body}
</span>
)
}
if (screenReaderOnly) {
body = <ScreenReaderContent>{body}</ScreenReaderContent>
}
return <Alert {...alertProps}>{body}</Alert>
}
|
/*! grafana - v4.2.0 - 2017-03-22
* Copyright (c) 2017 Torkel Ödegaard; Licensed Apache-2.0 */
System.register(["./plugin_edit_ctrl","./plugin_page_ctrl","./plugin_list_ctrl","./import_list/import_list","./ds_edit_ctrl","./ds_list_ctrl"],function(a,b){"use strict";b&&b.id;return{setters:[function(a){},function(a){},function(a){},function(a){},function(a){},function(a){}],execute:function(){}}});
|
// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// License: GNU General Public License v3. See license.txt
cur_frm.add_fetch("time_log", "activity_type", "activity_type");
cur_frm.add_fetch("time_log", "billing_amount", "billing_amount");
cur_frm.add_fetch("time_log", "hours", "hours");
cur_frm.set_query("time_log", "time_logs", function(doc) {
return {
query: "erpnext.projects.utils.get_time_log_list",
filters: {
"billable": 1,
"status": "Submitted"
}
}
});
$.extend(cur_frm.cscript, {
refresh: function(doc) {
cur_frm.set_intro({
"Draft": __("Select Time Logs and Submit to create a new Sales Invoice."),
"Submitted": __("Click on 'Make Sales Invoice' button to create a new Sales Invoice."),
"Billed": __("This Time Log Batch has been billed."),
"Cancelled": __("This Time Log Batch has been cancelled.")
}[doc.status]);
if(doc.status=="Submitted") {
cur_frm.add_custom_button(__("Make Sales Invoice"), function() { cur_frm.cscript.make_invoice() },
"icon-file-alt");
}
},
make_invoice: function() {
frappe.model.open_mapped_doc({
method: "erpnext.projects.doctype.time_log_batch.time_log_batch.make_sales_invoice",
frm: cur_frm
});
}
});
frappe.ui.form.on("Time Log Batch Detail", "time_log", function(frm, cdt, cdn) {
var tl = frm.doc.time_logs || [];
total_hr = 0;
total_amt = 0;
for(var i=0; i<tl.length; i++) {
total_hr += tl[i].hours;
total_amt += tl[i].billing_amount;
}
cur_frm.set_value("total_hours", total_hr);
cur_frm.set_value("total_billing_amount", total_amt);
});
|
var searchData=
[
['yellowcolor',['yellowColor',['../interface_c_p_color.html#a76410df22a14d10a7e3a70d7b959f29c',1,'CPColor']]]
];
|
import $ from 'jquery';
import _ from 'underscore';
import Marionette from 'backbone.marionette';
import CreateProfileView from './create-profile-view';
import RestoreProfileView from './restore-profile-view';
import RestoreBuiltInProfilesView from './restore-built-in-profiles-view';
import Template from './templates/quality-profiles-actions.hbs';
export default Marionette.ItemView.extend({
template: Template,
events: {
'click #quality-profiles-create': 'onCreateClick',
'click #quality-profiles-restore': 'onRestoreClick',
'click #quality-profiles-restore-built-in': 'onRestoreBuiltInClick',
'click .js-filter-by-language': 'onLanguageClick'
},
onCreateClick: function (e) {
e.preventDefault();
this.create();
},
onRestoreClick: function (e) {
e.preventDefault();
this.restore();
},
onRestoreBuiltInClick: function (e) {
e.preventDefault();
this.restoreBuiltIn();
},
onLanguageClick: function (e) {
e.preventDefault();
var language = $(e.currentTarget).data('language');
this.filterByLanguage(language);
},
create: function () {
var that = this;
this.requestImporters().done(function () {
new CreateProfileView({
collection: that.collection,
languages: that.languages,
importers: that.importers
}).render();
});
},
restore: function () {
new RestoreProfileView({
collection: this.collection
}).render();
},
restoreBuiltIn: function () {
new RestoreBuiltInProfilesView({
collection: this.collection,
languages: this.languages
}).render();
},
requestLanguages: function () {
var that = this,
url = baseUrl + '/api/languages/list';
return $.get(url).done(function (r) {
that.languages = r.languages;
});
},
requestImporters: function () {
var that = this,
url = baseUrl + '/api/qualityprofiles/importers';
return $.get(url).done(function (r) {
that.importers = r.importers;
});
},
filterByLanguage: function (language) {
this.selectedLanguage = _.findWhere(this.languages, { key: language });
this.render();
this.collection.trigger('filter', language);
},
serializeData: function () {
return _.extend(Marionette.ItemView.prototype.serializeData.apply(this, arguments), {
canWrite: this.options.canWrite,
languages: this.languages,
selectedLanguage: this.selectedLanguage
});
}
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.