code stringlengths 2 1.05M | repo_name stringlengths 5 114 | path stringlengths 4 991 | language stringclasses 1 value | license stringclasses 15 values | size int32 2 1.05M |
|---|---|---|---|---|---|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import styles from '../../build/styles';
export default class Subtitle extends Component {
static propTypes = {
children: PropTypes.any,
className: PropTypes.string,
size: PropTypes.oneOf([
'is1',
'is2',
'is3',
'is4',
'is5',
'is6',
]),
};
static defaultProps = {
className: '',
};
createClassName() {
return [
styles.subtitle,
styles[this.props.size],
this.props.className,
].join(' ').trim();
}
render() {
return (
<p {...this.props} className={this.createClassName()}>
{this.props.children}
</p>
);
}
}
| bokuweb/re-bulma | src/elements/subtitle.js | JavaScript | mit | 713 |
define(function(require, exports, module) {
var Notify = require('common/bootstrap-notify');
exports.run = function() {
var $form = $("#user-roles-form"),
isTeacher = $form.find('input[value=ROLE_TEACHER]').prop('checked'),
currentUser = $form.data('currentuser'),
editUser = $form.data('edituser');
if (currentUser == editUser) {
$form.find('input[value=ROLE_SUPER_ADMIN]').attr('disabled', 'disabled');
};
$form.find('input[value=ROLE_USER]').on('change', function(){
if ($(this).prop('checked') === false) {
$(this).prop('checked', true);
var user_name = $('#change-user-roles-btn').data('user') ;
Notify.info('用户必须拥有'+user_name+'角色');
}
});
$form.on('submit', function() {
var roles = [];
var $modal = $('#modal');
$form.find('input[name="roles[]"]:checked').each(function(){
roles.push($(this).val());
});
if ($.inArray('ROLE_USER', roles) < 0) {
var user_name = $('#change-user-roles-btn').data('user') ;
Notify.danger('用户必须拥有'+user_name+'角色');
return false;
}
if (isTeacher && $.inArray('ROLE_TEACHER', roles) < 0) {
if (!confirm('取消该用户的教师角色,同时将收回该用户所有教授的课程的教师权限。您真的要这么做吗?')) {
return false;
}
}
$form.find('input[value=ROLE_SUPER_ADMIN]').removeAttr('disabled');
$('#change-user-roles-btn').button('submiting').addClass('disabled');
$.post($form.attr('action'), $form.serialize(), function(html) {
$modal.modal('hide');
Notify.success('用户组保存成功');
var $tr = $(html);
$('#' + $tr.attr('id')).replaceWith($tr);
}).error(function(){
Notify.danger('操作失败');
});
return false;
});
};
}); | smeagonline-developers/OnlineEducationPlatform---SMEAGonline | src/Topxia/AdminBundle/Resources/public/js/controller/user/roles-modal.js | JavaScript | mit | 2,184 |
/**
* Test async injectors
*/
import { memoryHistory } from 'react-router';
import { put } from 'redux-saga/effects';
import { fromJS } from 'immutable';
import configureStore from 'store';
import {
injectAsyncReducer,
injectAsyncSagas,
getAsyncInjectors,
} from '../asyncInjectors';
// Fixtures
const initialState = fromJS({ reduced: 'soon' });
const reducer = (state = initialState, action) => {
switch (action.type) {
case 'TEST':
return state.set('reduced', action.payload);
default:
return state;
}
};
function* testSaga() {
yield put({ type: 'TEST', payload: 'yup' });
}
const sagas = [
testSaga,
];
describe('asyncInjectors', () => {
let store;
describe('getAsyncInjectors', () => {
beforeAll(() => {
store = configureStore({}, memoryHistory);
});
it('given a store, should return all async injectors', () => {
const { injectReducer, injectSagas } = getAsyncInjectors(store);
injectReducer('test', reducer);
injectSagas(sagas);
const actual = store.getState().get('test');
const expected = initialState.merge({ reduced: 'yup' });
expect(actual.toJS()).toEqual(expected.toJS());
});
it('should throw if passed invalid store shape', () => {
let result = false;
Reflect.deleteProperty(store, 'dispatch');
try {
getAsyncInjectors(store);
} catch (err) {
result = err.name === 'Invariant Violation';
}
expect(result).toEqual(true);
});
});
describe('helpers', () => {
beforeAll(() => {
store = configureStore({}, memoryHistory);
});
describe('injectAsyncReducer', () => {
it('given a store, it should provide a function to inject a reducer', () => {
const injectReducer = injectAsyncReducer(store);
injectReducer('test', reducer);
const actual = store.getState().get('test');
const expected = initialState;
expect(actual.toJS()).toEqual(expected.toJS());
});
it('should not assign reducer if already existing', () => {
const injectReducer = injectAsyncReducer(store);
injectReducer('test', reducer);
injectReducer('test', () => {});
expect(store.asyncReducers.test.toString()).toEqual(reducer.toString());
});
it('should throw if passed invalid name', () => {
let result = false;
const injectReducer = injectAsyncReducer(store);
try {
injectReducer('', reducer);
} catch (err) {
result = err.name === 'Invariant Violation';
}
try {
injectReducer(999, reducer);
} catch (err) {
result = err.name === 'Invariant Violation';
}
expect(result).toEqual(true);
});
it('should throw if passed invalid reducer', () => {
let result = false;
const injectReducer = injectAsyncReducer(store);
try {
injectReducer('bad', 'nope');
} catch (err) {
result = err.name === 'Invariant Violation';
}
try {
injectReducer('coolio', 12345);
} catch (err) {
result = err.name === 'Invariant Violation';
}
expect(result).toEqual(true);
});
});
describe('injectAsyncSagas', () => {
it('given a store, it should provide a function to inject a saga', () => {
const injectSagas = injectAsyncSagas(store);
injectSagas(sagas);
const actual = store.getState().get('test');
const expected = initialState.merge({ reduced: 'yup' });
expect(actual.toJS()).toEqual(expected.toJS());
});
it('should throw if passed invalid saga', () => {
let result = false;
const injectSagas = injectAsyncSagas(store);
try {
injectSagas({ testSaga });
} catch (err) {
result = err.name === 'Invariant Violation';
}
try {
injectSagas(testSaga);
} catch (err) {
result = err.name === 'Invariant Violation';
}
expect(result).toEqual(true);
});
});
});
});
| HachiJiang/FamilyFinanceSite | app/utils/tests/asyncInjectors.test.js | JavaScript | mit | 4,871 |
module.exports = function (grunt) {
"use strict";
grunt.initConfig({
pkg: grunt.file.readJSON("package.json"),
// grunt-contrib-clean
clean: {
instrument: "<%= instrument.options.basePath %>"
},
// grunt-contrib-jshint
jshint: {
files: [
"<%= instrument.files %>",
"<%= mochaTest.test.src %>",
"bin/**.js",
"gruntfile.js",
"node_tests/**/*.js"
],
options: grunt.file.readJSON(".jshintrc")
},
// grunt-mocha-test
mochaTest: {
test: {
options: {
reporter: "spec"
},
src: "node_tests/**/*.test.js"
}
},
// grunt-contrib-watch
watch: {
files: ["<%= jshint.files %>"],
tasks: ["beautify", "test"]
},
// grunt-istanbul
instrument: {
files: "node_libs/**/*.js",
options: {
basePath: "coverage/instrument/"
}
},
storeCoverage: {
options: {
dir: "coverage/reports/<%= pkg.version %>"
}
},
makeReport: {
src: "<%= storeCoverage.options.dir %>/*.json",
options: {
type: "lcov",
dir: "<%= storeCoverage.options.dir %>",
print: "detail"
}
},
// grunt-jsbeautifier
jsbeautifier: {
files: ["<%= jshint.files %>"],
options: {
js: grunt.file.readJSON(".jsbeautifyrc")
}
}
});
grunt.loadNpmTasks("grunt-contrib-clean");
grunt.loadNpmTasks("grunt-contrib-jshint");
grunt.loadNpmTasks("grunt-contrib-watch");
grunt.loadNpmTasks("grunt-istanbul");
grunt.loadNpmTasks("grunt-jsbeautifier");
grunt.loadNpmTasks("grunt-mocha-test");
grunt.registerTask("register_globals", function (task) {
var moduleRoot;
if ("coverage" === task) {
moduleRoot = __dirname + "/" + grunt.template.process("<%= instrument.options.basePath %>");
} else if ("test" === task) {
moduleRoot = __dirname;
}
global.MODULE_ROOT = moduleRoot;
global.MODULE_ROOT_TESTS = __dirname + "/node_tests";
});
grunt.registerTask("beautify", ["jsbeautifier"]);
grunt.registerTask("cover", ["register_globals:coverage", "clean:instrument", "instrument", "lint", "mochaTest", "storeCoverage", "makeReport"]);
grunt.registerTask("lint", ["jshint"]);
grunt.registerTask("test", ["register_globals:test", "clean:instrument", "lint", "mochaTest"]);
grunt.registerTask("default", ["jsbeautifier", "test"]);
};
| kl3ryk/pouclaige-web-crawler | gruntfile.js | JavaScript | mit | 2,846 |
const EventEmitter = require('events');
/**
* Ends the session. Uses session protocol command.
*
* @example
* this.demoTest = function (browser) {
* browser.end();
* };
*
* @method end
* @syntax .end([callback])
* @param {function} [callback] Optional callback function to be called when the command finishes.
* @see session
* @api protocol.sessions
*/
class End extends EventEmitter {
command(callback) {
const client = this.client;
if (this.api.sessionId) {
this.api.session('delete', result => {
client.session.clearSession();
client.setApiProperty('sessionId', null);
this.complete(callback, result);
});
} else {
setImmediate(() => {
this.complete(callback, null);
});
}
return this.client.api;
}
complete(callback, result) {
if (typeof callback === 'function') {
callback.call(this.api, result);
}
this.emit('complete');
}
}
module.exports = End;
| beatfactor/nightwatch | lib/api/client-commands/end.js | JavaScript | mit | 977 |
import Botkit from 'botkit';
import os from 'os';
import Wit from 'botkit-middleware-witai';
import moment from 'moment-timezone';
import models from '../../app/models';
import storageCreator from '../lib/storage';
import setupReceiveMiddleware from '../middleware/receiveMiddleware';
import notWitController from './notWit';
import miscController from './misc';
import sessionsController from './sessions';
import pingsController from './pings';
import slashController from './slash';
import dashboardController from './dashboard';
import { seedAndUpdateUsers } from '../../app/scripts';
require('dotenv').config();
var env = process.env.NODE_ENV || 'development';
if (env == 'development') {
process.env.SLACK_ID = process.env.DEV_SLACK_ID;
process.env.SLACK_SECRET = process.env.DEV_SLACK_SECRET;
}
// actions
import { firstInstallInitiateConversation, loginInitiateConversation } from '../actions';
// Wit Brain
if (process.env.WIT_TOKEN) {
var wit = Wit({
token: process.env.WIT_TOKEN,
minimum_confidence: 0.55
});
} else {
console.log('Error: Specify WIT_TOKEN in environment');
process.exit(1);
}
export { wit };
/**
* *** CONFIG ****
*/
var config = {};
const storage = storageCreator(config);
var controller = Botkit.slackbot({
interactive_replies: true,
storage
});
export { controller };
/**
* User has joined slack channel ==> make connection
* then onboard!
*/
controller.on('team_join', function (bot, message) {
console.log("\n\n\n ~~ joined the team ~~ \n\n\n");
const SlackUserId = message.user.id;
console.log(message.user.id);
bot.api.users.info({ user: SlackUserId }, (err, response) => {
if (!err) {
const { user, user: { id, team_id, name, tz } } = response;
const email = user.profile && user.profile.email ? user.profile.email : '';
models.User.find({
where: { SlackUserId },
})
.then((user) => {
if (!user) {
models.User.create({
TeamId: team_id,
email,
tz,
SlackUserId,
SlackName: name
});
} else {
user.update({
TeamId: team_id,
SlackName: name
})
}
});
}
});
});
/**
* User has updated data ==> update our DB!
*/
controller.on('user_change', function (bot, message) {
console.log("\n\n\n ~~ user updated profile ~~ \n\n\n");
if (message && message.user) {
const { user, user: { name, id, team_id, tz } } = message;
const SlackUserId = id;
const email = user.profile && user.profile.email ? user.profile.email : '';
models.User.find({
where: { SlackUserId },
})
.then((user) => {
if (!user) {
models.User.create({
TeamId: team_id,
email,
tz,
SlackUserId,
SlackName: name
});
} else {
user.update({
TeamId: team_id,
SlackName: name
})
}
});
}
});
// simple way to keep track of bots
export var bots = {};
if (!process.env.SLACK_ID || !process.env.SLACK_SECRET || !process.env.HTTP_PORT) {
console.log('Error: Specify SLACK_ID SLACK_SECRET and HTTP_PORT in environment');
process.exit(1);
}
// Custom Toki Config
export function customConfigBot(controller) {
// beef up the bot
setupReceiveMiddleware(controller);
notWitController(controller);
dashboardController(controller);
pingsController(controller);
sessionsController(controller);
slashController(controller);
miscController(controller);
}
// try to avoid repeat RTM's
export function trackBot(bot) {
bots[bot.config.token] = bot;
}
/**
* *** TURN ON THE BOT ****
* VIA SIGNUP OR LOGIN
*/
export function connectOnInstall(team_config) {
console.log(`\n\n\n\n CONNECTING ON INSTALL \n\n\n\n`);
let bot = controller.spawn(team_config);
controller.trigger('create_bot', [bot, team_config]);
}
export function connectOnLogin(identity) {
// bot already exists, get bot token for this users team
var SlackUserId = identity.user_id;
var TeamId = identity.team_id;
models.Team.find({
where: { TeamId }
})
.then((team) => {
const { token } = team;
if (token) {
var bot = controller.spawn({ token });
controller.trigger('login_bot', [bot, identity]);
}
})
}
controller.on('rtm_open',function(bot) {
console.log(`\n\n\n\n** The RTM api just connected! for bot token: ${bot.config.token}\n\n\n`);
});
// upon install
controller.on('create_bot', (bot,team) => {
const { id, url, name, bot: { token, user_id, createdBy, accessToken, scopes } } = team;
// this is what is used to save team data
const teamConfig = {
TeamId: id,
createdBy,
url,
name,
token,
scopes,
accessToken
}
if (bots[bot.config.token]) {
// already online! do nothing.
console.log("already online! restarting bot due to re-install");
// restart the bot
bots[bot.config.token].closeRTM();
}
bot.startRTM((err) => {
if (!err) {
console.log("\n\n RTM on with team install and listening \n\n");
trackBot(bot);
controller.saveTeam(teamConfig, (err, id) => {
if (err) {
console.log("Error saving team")
}
else {
console.log("Team " + team.name + " saved");
console.log(`\n\n installing users... \n\n`);
bot.api.users.list({}, (err, response) => {
if (!err) {
const { members } = response;
seedAndUpdateUsers(members);
}
firstInstallInitiateConversation(bot, team);
});
}
});
} else {
console.log("RTM failed")
}
});
});
// subsequent logins
controller.on('login_bot', (bot,identity) => {
if (bots[bot.config.token]) {
// already online! do nothing.
console.log("already online! do nothing.");
loginInitiateConversation(bot, identity);
} else {
bot.startRTM((err) => {
if (!err) {
console.log("RTM on and listening");
trackBot(bot);
loginInitiateConversation(bot, identity);
} else {
console.log("RTM failed")
console.log(err);
}
});
}
});
| kevinsuh/toki | src/bot/controllers/index.js | JavaScript | mit | 5,878 |
/**
Create by Huy: codocmm@gmail.com ~ nqhuy2k6@gmail.com
07/31/2015
*/
define(["durandal/app", "knockout", "bootstrap", "viewmodels/component-4"], function (app, ko, bootstrap, Component4) {
return function () {
var me = this;
var dashboardViewModel = this;
dashboardViewModel.compoment4 = ko.observable();
dashboardViewModel.activate = function () {
me.compoment4(new Component4(0))
}
}
});
| cmasv2/client | app/page/pages/alarm-summary.js | JavaScript | mit | 457 |
/*
************************************************************************
Copyright (c) 2013 UBINITY SAS
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*************************************************************************
*/
var ChromeapiPlugupCardTerminalFactory = Class.extend(CardTerminalFactory, {
/** @lends ChromeapiPlugupCardTerminalFactory.prototype */
/**
* @class Implementation of the {@link CardTerminalFactory} using the Chrome API for Plug-up Dongle
* @constructs
* @augments CardTerminalFactory
*/
initialize: function(pid, usagePage, ledgerTransport, vid) {
this.pid = pid;
this.vid = vid;
this.usagePage = usagePage;
this.ledgerTransport = ledgerTransport;
},
list_async: function(pid, usagePage) {
if (typeof chromeDevice == "undefined") {
throw "Content script is not available";
}
return chromeDevice.enumerateDongles_async(this.pid, this.usagePage, this.vid)
.then(function(result) {
return result.deviceList;
});
},
waitInserted: function() {
throw "Not implemented"
},
getCardTerminal: function(device) {
return new ChromeapiPlugupCardTerminal(device, undefined, this.ledgerTransport);
}
}); | LedgerHQ/ledger-wallet-chrome | app/libs/btchip/btchip-js-api/chromeApp/ChromeapiPlugupCardTerminalFactory.js | JavaScript | mit | 1,664 |
'use strict';
/**
* Created by Alex Levshin on 26/11/16.
*/
var RootFolder = process.env.ROOT_FOLDER;
if (!global.rootRequire) {
global.rootRequire = function (name) {
return require(RootFolder + '/' + name);
};
}
var restify = require('restify');
var _ = require('lodash');
var fs = require('fs');
var expect = require('chai').expect;
var ApiPrefix = '/api/v1';
var Promise = require('promise');
var config = rootRequire('config');
var util = require('util');
var WorktyRepositoryCodePath = RootFolder + '/workties-repository';
var SubVersion = config.restapi.getLatestVersion().sub; // YYYY.M.D
// Init the test client using supervisor account (all acl permissions)
var adminClient = restify.createJsonClient({
version: SubVersion,
url: config.restapi.getConnectionString(),
headers: {
'Authorization': config.supervisor.getAuthorizationBasic() // supervisor
},
rejectUnauthorized: false
});
describe('Workflow Rest API', function () {
var WorkflowsPerPage = 3;
var Workflows = [];
var WorktiesPerPage = 2;
var Workties = [];
var WorktiesInstances = [];
var WORKTIES_FILENAMES = ['unsorted/nodejs/unit-tests/without-delay.zip'];
console.log('Run Workflow API tests for version ' + ApiPrefix + '/' + SubVersion);
function _createPromises(callback, count) {
var promises = [];
for (var idx = 0; idx < count; idx++) {
promises.push(callback(idx));
}
return promises;
}
function _createWorkty(idx) {
return new Promise(function (resolve, reject) {
try {
var compressedCode = fs.readFileSync(WorktyRepositoryCodePath + '/' + WORKTIES_FILENAMES[0]);
adminClient.post(ApiPrefix + '/workties', {
name: 'myworkty' + idx,
desc: 'worktydesc' + idx,
compressedCode: compressedCode,
template: true
}, function (err, req, res, data) {
var workty = data;
adminClient.post(ApiPrefix + '/workties/' + data._id + '/properties', {
property: {
name: 'PropertyName',
value: 'PropertyValue'
}
}, function (err, req, res, data) {
workty.propertiesIds = [data];
resolve({res: res, data: workty});
});
});
} catch (ex) {
reject(ex);
}
});
}
function _createWorkflow(idx) {
return new Promise(function (resolve, reject) {
try {
adminClient.post(ApiPrefix + '/workflows', {
name: 'myworkflow' + idx,
desc: 'workflowdesc' + idx
}, function (err, req, res, data) {
resolve({res: res, data: data});
});
} catch (ex) {
reject(ex);
}
});
}
function _createWorktyInstance(idx) {
return new Promise(function (resolve, reject) {
try {
adminClient.post(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances', {
name: 'worktyinstance' + idx,
desc: 'worktyinstance' + idx,
worktyId: Workties[idx]._id,
embed: 'properties'
}, function (err, req, res, data) {
resolve({res: res, data: data});
});
} catch (ex) {
reject(ex);
}
});
}
// Delete workflows and workties
function _deleteWorkty(idx) {
return new Promise(function (resolve, reject) {
try {
adminClient.del(ApiPrefix + '/workties/' + Workties[idx]._id, function (err, req, res, data) {
resolve({res: res});
});
} catch (ex) {
reject(ex);
}
});
}
function _deleteWorkflow(idx) {
return new Promise(function (resolve, reject) {
try {
adminClient.del(ApiPrefix + '/workflows/' + Workflows[idx]._id, function (err, req, res, data) {
resolve({res: res});
});
} catch (ex) {
reject(ex);
}
});
}
// Run once before the first test case
before(function (done) {
Promise.all(_createPromises(_createWorkty, WorktiesPerPage)).then(function (results) { // Create workties
for (var idx = 0; idx < results.length; idx++) {
var res = results[idx].res;
var data = results[idx].data;
expect(res.statusCode).to.equals(201);
expect(data).to.not.be.empty;
Workties.push(data);
}
return Promise.all(_createPromises(_createWorkflow, WorkflowsPerPage));
}).then(function (results) { // Create workflows
for (var idx = 0; idx < results.length; idx++) {
var res = results[idx].res;
var data = results[idx].data;
expect(res.statusCode).to.equals(201);
expect(data).to.not.be.empty;
Workflows.push(data);
}
return Promise.all(_createPromises(_createWorktyInstance, WorktiesPerPage));
}).then(function (results) { // Create workties instances
for (var idx = 0; idx < results.length; idx++) {
var res = results[idx].res;
var data = results[idx].data;
expect(res.statusCode).to.equals(201);
expect(data).to.not.be.empty;
WorktiesInstances.push(data);
}
}).done(function (err) {
expect(err).to.be.undefined;
done();
});
});
// Run once after the last test case
after(function (done) {
Promise.all(_createPromises(_deleteWorkty, WorktiesPerPage)).then(function (results) { // Delete workties
for (var idx = 0; idx < results.length; idx++) {
var res = results[idx].res;
expect(res.statusCode).to.equals(204);
}
return Promise.all(_createPromises(_deleteWorkflow, WorkflowsPerPage));
}).then(function (results) { // Delete workflows
for (var idx = 0; idx < results.length; idx++) {
var res = results[idx].res;
expect(res.statusCode).to.equals(204);
}
}).done(function (err) {
expect(err).to.be.undefined;
done();
});
});
describe('.getAll()', function () {
it('should get a 200 response', function (done) {
adminClient.get(ApiPrefix + '/workflows', function (err, req, res, data) {
expect(err).to.be.null;
expect(res.statusCode).to.equals(200);
expect(data).to.have.length.above(1);
done();
});
});
it('should get 3', function (done) {
adminClient.get(ApiPrefix + '/workflows?page_num=1&per_page=3', function (err, req, res, data) {
expect(err).to.be.null;
expect(res.statusCode).to.equals(200);
expect(data).to.have.length(3);
done();
});
});
it('should get 2', function (done) {
adminClient.get(ApiPrefix + '/workflows?per_page=2', function (err, req, res, data) {
expect(err).to.be.null;
expect(res.statusCode).to.equals(200);
expect(data).to.have.length(2);
done();
});
});
it('should get records-count', function (done) {
adminClient.get(ApiPrefix + '/workflows?per_page=3&count=true', function (err, req, res, data) {
expect(err).to.be.null;
expect(res.statusCode).to.equals(200);
expect(data).to.have.length(3);
expect(res.headers).to.contain.keys('records-count');
expect(res.headers['records-count']).equals('3');
done();
});
});
it('should get sorted', function (done) {
adminClient.get(ApiPrefix + '/workflows?per_page=3&sort=_id', function (err, req, res, data) {
expect(err).to.be.null;
expect(res.statusCode).to.equals(200);
expect(data).to.have.length(3);
expect(data).to.satisfy(function (workflows) {
var currentValue = null;
_.each(workflows, function (workflow) {
if (!currentValue) {
currentValue = workflow._id;
} else {
if (workflow._id <= currentValue) expect(true).to.be.false();
currentValue = workflow._id;
}
});
return true;
});
done();
});
});
it('should get fields', function (done) {
adminClient.get(ApiPrefix + '/workflows?per_page=3&fields=_id,name,desc', function (err, req, res, data) {
expect(err).to.be.null;
expect(res.statusCode).to.equals(200);
expect(data).to.have.length(3);
expect(data).to.satisfy(function (workflows) {
_.each(workflows, function (workflow) {
expect(workflow).to.have.keys(['_id', 'name', 'desc']);
});
return true;
});
done();
});
});
it('should get embed fields', function (done) {
adminClient.get(ApiPrefix + '/workflows?per_page=3&embed=worktiesInstances,account', function (err, req, res, data) {
expect(err).to.be.null;
expect(res.statusCode).to.equals(200);
expect(data).to.have.length(3);
expect(data).to.satisfy(function (workflows) {
_.each(workflows, function (workflow) {
expect(workflow).to.contain.keys('accountId', 'worktiesInstancesIds');
expect(workflow.accountId).to.contain.keys('_id');
if (workflow.worktiesInstancesIds.length > 0) {
expect(workflow.worktiesInstancesIds[0]).to.contain.keys('_id');
}
});
return true;
});
done();
});
});
});
describe('.getById()', function () {
it('should get a 200 response', function (done) {
adminClient.get(ApiPrefix + '/workflows/' + Workflows[0]._id, function (err, req, res, data) {
expect(err).to.be.null;
expect(res.statusCode).to.equals(200);
expect(data).to.not.be.empty;
done();
});
});
it('should get a 500 response not found', function (done) {
adminClient.get(ApiPrefix + '/workflows/' + 'N', function (err, req, res, data) {
expect(err).to.not.be.null;
expect(res.statusCode).to.equals(500);
expect(data).to.not.be.empty;
expect(data).to.have.keys('error');
expect(data.error).to.have.keys(['code', 'error_link', 'message', 'inputParameters']);
expect(data.error.code).to.equals(1);
expect(data.error.error_link).to.not.be.empty;
expect(data.error.message).to.not.be.empty;
done();
});
});
it('should get records-count', function (done) {
adminClient.get(ApiPrefix + '/workflows/' + Workflows[0]._id + '?count=true', function (err, req, res, data) {
expect(err).to.be.null;
expect(res.statusCode).to.equals(200);
expect(data).to.not.be.empty;
expect(res.headers).to.contain.keys('records-count');
expect(res.headers['records-count']).equals('1');
done();
});
});
it('should get fields', function (done) {
adminClient.get(ApiPrefix + '/workflows/' + Workflows[0]._id + '?fields=_id,name,desc', function (err, req, res, data) {
expect(err).to.be.null;
expect(res.statusCode).to.equals(200);
expect(data).to.not.be.empty;
expect(data).to.have.keys(['_id', 'name', 'desc']);
done();
});
});
it('should get embed fields', function (done) {
adminClient.get(ApiPrefix + '/workflows/' + Workflows[0]._id + '?embed=worktiesInstances,account', function (err, req, res, data) {
expect(err).to.be.null;
expect(res.statusCode).to.equals(200);
expect(data).to.not.be.empty;
expect(data).to.contain.keys('accountId', 'worktiesInstancesIds');
expect(data.accountId).to.contain.keys('_id');
if (data.worktiesInstancesIds.length > 0) {
expect(data.worktiesInstancesIds[0]).to.contain.keys('_id');
}
done();
});
});
});
describe('.add()', function () {
it('should get a 409 response', function (done) {
adminClient.post(ApiPrefix + '/workflows', function (err, req, res, data) {
expect(err).to.not.be.null;
expect(res.statusCode).to.equals(409);
var error = JSON.parse(err.message).error;
expect(error.message).to.equals("Validation Error");
expect(error.errors).to.have.length(1);
expect(error.errors[0].message).to.equals("Path `name` is required.");
done();
});
});
it('should get a 201 response', function (done) {
// Create workflow
adminClient.post(ApiPrefix + '/workflows', {
name: 'mytestworkflow',
desc: 'testworkflow'
}, function (err, req, res, data) {
expect(err).to.be.null;
expect(res.statusCode).to.equals(201);
expect(res.headers).to.contain.keys('location');
expect(data).to.not.be.null;
var workflowId = data._id;
expect(res.headers.location).to.have.string('/' + workflowId);
expect(data.name).to.be.equal('mytestworkflow');
expect(data.desc).to.be.equal('testworkflow');
// Delete workflow
adminClient.del(res.headers.location, function (err, req, res, data) {
expect(err).to.be.null;
expect(res.statusCode).to.equals(204);
done();
});
});
});
});
describe('.update()', function () {
it('should get a 400 response', function (done) {
adminClient.put(ApiPrefix + '/workflows/' + Workflows[0]._id, function (err, req, res, data) {
expect(err).to.not.be.null;
expect(res.statusCode).to.equals(400);
var error = JSON.parse(err.message).error;
expect(error.errors).is.empty;
done();
});
});
it('should get a 409 response', function (done) {
adminClient.put(ApiPrefix + '/workflows/' + Workflows[0]._id, {name: ''}, function (err, req, res, data) {
expect(err).to.not.be.null;
expect(res.statusCode).to.equals(409);
var error = JSON.parse(err.message).error;
expect(error.errors).to.have.length(1);
expect(error.errors[0].message).to.equals("Path `name` is required.");
done();
});
});
it('should get a 200 response', function (done) {
adminClient.put(ApiPrefix + '/workflows/' + Workflows[0]._id, {
name: 'mytestworkflow',
desc: 'testworkflow'
}, function (err, req, res, data) {
expect(err).to.be.null;
expect(res.statusCode).to.equals(200);
expect(data).to.not.be.null;
var workflowId = data._id;
expect(workflowId).to.equals(Workflows[0]._id);
expect(data.name).to.be.equal('mytestworkflow');
expect(data.desc).to.be.equal('testworkflow');
done();
});
});
});
describe('.del()', function () {
it('should get a 500 response not found', function (done) {
// Delete workflow
adminClient.del(ApiPrefix + '/workflows/' + Workflows[0]._id + 'N', function (err, req, res, data) {
expect(err).to.not.be.null;
expect(res.statusCode).to.equals(500);
done();
});
});
it('should get a 204 response', function (done) {
// Create workflow
adminClient.post(ApiPrefix + '/workflows', {
name: 'mytestworkflow',
desc: 'testworkflow'
}, function (err, req, res, data) {
expect(err).to.be.null;
expect(res.statusCode).to.equals(201);
expect(res.headers).to.contain.keys('location');
expect(data).to.not.be.null;
var workflowId = data._id;
expect(res.headers.location).to.have.string('/' + workflowId);
// Delete workflow
adminClient.del(ApiPrefix + '/workflows/' + workflowId, function (err, req, res, data) {
expect(err).to.be.null;
expect(data).is.empty;
expect(res.statusCode).to.equals(204);
done();
});
});
});
});
describe('.run()', function () {
it('should get a 200 response', function (done) {
adminClient.put(ApiPrefix + '/workflows/' + Workflows[0]._id + '/running', function (err, req, res, data) {
expect(err).to.be.null;
expect(res.statusCode).to.equals(200);
expect(data).to.not.be.empty;
done();
});
});
it('should get a 500 response not found', function (done) {
adminClient.put(ApiPrefix + '/workflows/' + Workflows[0]._id + 'N' + '/running', function (err, req, res, data) {
expect(err).to.not.be.null;
expect(res.statusCode).to.equals(500);
expect(data).to.not.be.empty;
expect(data).to.have.keys('error');
expect(data.error).to.have.keys(['code', 'error_link', 'message', 'inputParameters']);
expect(data.error.code).to.be.equals(1);
expect(data.error.error_link).to.not.be.empty;
expect(data.error.message).to.not.be.empty;
done();
});
});
describe('multiple workflows', function () {
var WorkflowExtraPerPage = 2;
var WorkflowExtraIds = [];
function _deleteExtraWorkflow(idx) {
return new Promise(function (resolve, reject) {
try {
adminClient.del(ApiPrefix + '/workflows/' + WorkflowExtraIds[idx], function (err, req, res, data) {
resolve({res: res});
});
} catch (ex) {
reject(ex);
}
});
}
// Run once before the first test case
before(function (done) {
Promise.all(_createPromises(_createWorkflow, WorkflowExtraPerPage)).then(function (results) { // Create workflows
for (var idx = 0; idx < results.length; idx++) {
var res = results[idx].res;
var data = results[idx].data;
expect(res.statusCode).to.equals(201);
expect(data).to.not.be.empty;
WorkflowExtraIds.push(data._id);
}
}).done(function (err) {
expect(err).to.be.undefined;
done();
});
});
// Run once after the last test case
after(function (done) {
Promise.all(_createPromises(_deleteExtraWorkflow, WorkflowExtraPerPage)).then(function (results) { // Delete workflows
for (var idx = 0; idx < results.length; idx++) {
var res = results[idx].res;
expect(res.statusCode).to.equals(204);
}
}).done(function (err) {
expect(err).to.be.undefined;
done();
});
});
});
});
describe('.stop()', function () {
it('should get a 200 response', function (done) {
// Run workflow
adminClient.del(ApiPrefix + '/workflows/' + Workflows[0]._id + '/running', function (err, req, res, data) {
expect(err).to.be.null;
expect(res.statusCode).to.equals(200);
done();
});
});
it('should get a 500 response not found', function (done) {
adminClient.del(ApiPrefix + '/workflows/' + Workflows[0]._id + 'N' + '/running', function (err, req, res, data) {
expect(err).to.not.be.null;
expect(res.statusCode).to.equals(500);
expect(data).to.not.be.empty;
expect(data).to.have.keys('error');
expect(data.error).to.have.keys(['code', 'error_link', 'message', 'inputParameters']);
expect(data.error.code).to.be.equals(1);
expect(data.error.error_link).to.not.be.empty;
expect(data.error.message).to.not.be.empty;
done();
});
});
it('should get a 200 response after two stops', function (done) {
// Run workflow
adminClient.put(ApiPrefix + '/workflows/' + Workflows[0]._id + '/running', function (err, req, res, data) {
expect(err).to.be.null;
expect(res.statusCode).to.equals(200);
expect(data).to.not.be.empty;
// Stop workflow twice
adminClient.del(ApiPrefix + '/workflows/' + Workflows[0]._id + '/running', function (err, req, res, data) {
expect(err).to.be.null;
expect(res.statusCode).to.equals(200);
adminClient.del(ApiPrefix + '/workflows/' + Workflows[0]._id + '/running', function (err, req, res, data) {
expect(err).to.be.null;
expect(res.statusCode).to.equals(200);
done();
});
});
});
});
});
describe('.resume()', function () {
it('should get a 200 response', function (done) {
// Resume workflow
adminClient.put(ApiPrefix + '/workflows/' + Workflows[0]._id + '/running', function (err, req, res, data) {
expect(err).to.be.null;
expect(res.statusCode).to.equals(200);
expect(data).to.not.be.empty;
done();
});
});
it('should get a 500 response not found', function (done) {
adminClient.put(ApiPrefix + '/workflows/' + Workflows[0]._id + 'N' + '/running', function (err, req, res, data) {
expect(err).to.not.be.null;
expect(res.statusCode).to.equals(500);
expect(data).to.not.be.empty;
expect(data).to.have.keys('error');
expect(data.error).to.have.keys(['code', 'error_link', 'message', 'inputParameters']);
expect(data.error.code).to.be.equals(1);
expect(data.error.error_link).to.not.be.empty;
expect(data.error.message).to.not.be.empty;
done();
});
});
});
describe('Workties instances', function () {
describe('.getAllWorktiesInstances()', function () {
it('should get a 200 response', function (done) {
adminClient.get(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances', function (err, req, res, data) {
expect(err).to.be.null;
expect(res.statusCode).to.equals(200);
expect(data).to.have.length.above(0);
expect(data[0].workflowId).to.equals(Workflows[0]._id);
done();
});
});
it('should get 2', function (done) {
adminClient.get(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances?per_page=2', function (err, req, res, data) {
expect(err).to.be.null;
expect(res.statusCode).to.equals(200);
expect(data).to.have.length(2);
done();
});
});
it('should get records-count', function (done) {
adminClient.get(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances?per_page=2&count=true', function (err, req, res, data) {
expect(err).to.be.null;
expect(res.statusCode).to.equals(200);
expect(data).to.have.length(2);
expect(res.headers).to.contain.keys('records-count');
expect(res.headers['records-count']).equals('2');
done();
});
});
it('should get fields', function (done) {
adminClient.get(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances?per_page=2&fields=_id,desc,created', function (err, req, res, data) {
expect(err).to.be.null;
expect(res.statusCode).to.equals(200);
expect(data).to.have.length(2);
expect(data).to.satisfy(function (workflowInstances) {
_.each(workflowInstances, function (workflowInstance) {
expect(workflowInstance).to.have.keys(['_id', 'desc', 'created']);
});
return true;
});
done();
});
});
it('should get embed fields', function (done) {
adminClient.get(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances?per_page=2&embed=workflow,state', function (err, req, res, data) {
expect(err).to.be.null;
expect(res.statusCode).to.equals(200);
expect(data).to.have.length(2);
expect(data).to.satisfy(function (workflowInstances) {
_.each(workflowInstances, function (workflowInstance) {
expect(workflowInstance).to.contain.keys('stateId', 'workflowId');
expect(workflowInstance.workflowId).to.contain.keys('_id');
if (workflowInstance.stateId.length > 0) {
expect(workflowInstance.stateId[0]).to.contain.keys('_id');
}
});
return true;
});
done();
});
});
});
describe('.getWorktyInstanceById()', function () {
it('should get a 200 response', function (done) {
adminClient.get(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances/' + WorktiesInstances[0]._id, function (err, req, res, data) {
expect(err).to.be.null;
expect(res.statusCode).to.equals(200);
expect(data).to.not.be.empty;
done();
});
});
it('should get a 500 response not found', function (done) {
adminClient.get(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances/' + WorktiesInstances[0]._id + 'N', function (err, req, res, data) {
expect(err).to.not.be.null;
expect(res.statusCode).to.equals(500);
expect(data).to.not.be.empty;
expect(data).to.have.keys('error');
expect(data.error).to.have.keys(['code', 'error_link', 'message', 'inputParameters']);
expect(data.error.code).to.equals(1);
expect(data.error.error_link).to.not.be.empty;
expect(data.error.message).to.not.be.empty;
done();
});
});
it('should get records-count', function (done) {
adminClient.get(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances/' + WorktiesInstances[0]._id + '?count=true', function (err, req, res, data) {
expect(err).to.be.null;
expect(res.statusCode).to.equals(200);
expect(data).to.not.be.empty;
expect(res.headers).to.contain.keys('records-count');
expect(res.headers['records-count']).equals('1');
done();
});
});
it('should get fields', function (done) {
adminClient.get(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances/' + WorktiesInstances[0]._id + '?fields=_id,desc', function (err, req, res, data) {
expect(err).to.be.null;
expect(res.statusCode).to.equals(200);
expect(data).to.not.be.empty;
expect(data).to.have.keys(['_id', 'desc']);
done();
});
});
it('should get embed fields', function (done) {
adminClient.get(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances/' + WorktiesInstances[0]._id + '?embed=workflow,state', function (err, req, res, data) {
expect(err).to.be.null;
expect(res.statusCode).to.equals(200);
expect(data).to.not.be.empty;
expect(data).to.contain.keys('stateId', 'workflowId');
expect(data.stateId).to.contain.keys('_id');
expect(data.workflowId).to.contain.keys('_id');
expect(data.workflowId._id).to.equals(Workflows[0]._id);
done();
});
});
});
describe('.addWorktyInstance()', function () {
it('should get a 201 response', function (done) {
// Create workty instance
adminClient.post(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances', {
desc: 'descworktyinstance4',
worktyId: Workties[0]._id
}, function (err, req, res, data) {
expect(err).to.be.null;
expect(res.statusCode).to.equals(201);
expect(res.headers).to.contain.keys('location');
expect(data).to.not.be.null;
expect(data.worktyId).to.be.equal(Workties[0]._id);
expect(data.desc).to.be.equal('descworktyinstance4');
// Delete workty instance
adminClient.del(res.headers.location, function (err, req, res, data) {
expect(err).to.be.null;
expect(data).is.empty;
expect(res.statusCode).to.equals(204);
done();
});
});
});
it('should get a 500 response with code 12 position type is unknown', function (done) {
adminClient.post(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances?position_type=unknown', {
desc: 'testworkty',
worktyId: Workties[0]._id
}, function (err, req, res, data) {
expect(err).to.not.be.null;
expect(res.statusCode).to.equals(500);
expect(data).to.have.keys('error');
expect(data.error).to.have.keys(['code', 'error_link', 'message', 'inputParameters']);
expect(data.error.code).to.equals(12);
expect(data.error.error_link).to.not.be.empty;
expect(data.error.message).to.not.be.empty;
done();
});
});
it('should get a 201 response for position type is last', function (done) {
adminClient.post(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances?position_type=last', {
desc: 'testworkty',
worktyId: Workties[0]._id
}, function (err, req, res, data) {
expect(err).to.be.null;
expect(res.statusCode).to.equals(201);
expect(res.headers).to.contain.keys('location');
expect(data).to.not.be.null;
var worktyInstanceId = data._id;
expect(res.headers.location).to.have.string('worktiesInstances/' + worktyInstanceId);
expect(data.desc).to.be.equal('testworkty');
var headerLocation = res.headers.location;
// Get workflow to check workty instance added in last position
adminClient.get(ApiPrefix + '/workflows/' + Workflows[0]._id, function (err, req, res, data) {
expect(err).to.be.null;
expect(res.statusCode).to.equals(200);
expect(data).to.not.be.empty;
expect(data.worktiesInstancesIds).to.satisfy(function (worktiesInstancesIds) {
if (worktiesInstancesIds.length !== 3) {
return false;
}
return worktyInstanceId === worktiesInstancesIds[worktiesInstancesIds.length - 1];
});
// Delete workty instance
adminClient.del(headerLocation, function (err, req, res, data) {
expect(err).to.be.null;
expect(data).is.empty;
expect(res.statusCode).to.equals(204);
done();
});
});
});
});
it('should get a 201 response for position type is first', function (done) {
adminClient.post(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances?position_type=first', {
desc: 'testworkty',
worktyId: Workties[0]._id
}, function (err, req, res, data) {
expect(err).to.be.null;
expect(res.statusCode).to.equals(201);
expect(res.headers).to.contain.keys('location');
expect(data).to.not.be.null;
var worktyInstanceId = data._id;
expect(res.headers.location).to.have.string('worktiesInstances/' + worktyInstanceId);
expect(data.desc).to.be.equal('testworkty');
var headerLocation = res.headers.location;
// Get workflow to check workty instance added in first position
adminClient.get(ApiPrefix + '/workflows/' + Workflows[0]._id, function (err, req, res, data) {
expect(err).to.be.null;
expect(res.statusCode).to.equals(200);
expect(data).to.not.be.empty;
expect(data.worktiesInstancesIds).to.satisfy(function (worktiesInstancesIds) {
if (worktiesInstancesIds.length !== 3) {
return false;
}
return worktyInstanceId === worktiesInstancesIds[0];
});
// Delete workty instance
adminClient.del(headerLocation, function (err, req, res, data) {
expect(err).to.be.null;
expect(data).is.empty;
expect(res.statusCode).to.equals(204);
done();
});
});
});
});
it('should get a 201 response for position index is 0 among 4 values', function (done) {
adminClient.post(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances?position_index=0', {
desc: 'testworkty',
worktyId: Workties[0]._id
}, function (err, req, res, data) {
expect(err).to.be.null;
expect(res.statusCode).to.equals(201);
expect(res.headers).to.contain.keys('location');
expect(data).to.not.be.null;
var worktyInstanceId = data._id;
expect(res.headers.location).to.have.string('worktiesInstances/' + worktyInstanceId);
expect(data.desc).to.be.equal('testworkty');
var headerLocation = res.headers.location;
// Get workflow to check workty instance added by index 1
adminClient.get(ApiPrefix + '/workflows/' + Workflows[0]._id, function (err, req, res, data) {
expect(err).to.be.null;
expect(res.statusCode).to.equals(200);
expect(data).to.not.be.empty;
expect(data.worktiesInstancesIds).to.satisfy(function (worktiesInstancesIds) {
if (worktiesInstancesIds.length !== 3) {
return false;
}
return _.indexOf(worktiesInstancesIds, worktyInstanceId) === 0;
});
// Delete workty instance
adminClient.del(headerLocation, function (err, req, res, data) {
expect(err).to.be.null;
expect(data).is.empty;
expect(res.statusCode).to.equals(204);
done();
});
});
});
});
it('should get a 500 response with code 10 for position index is -1', function (done) {
adminClient.post(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances?position_index=-1', {
desc: 'testworkty',
worktyId: Workties[0]._id
}, function (err, req, res, data) {
expect(err).to.not.be.null;
expect(res.statusCode).to.equals(500);
expect(data).to.have.keys('error');
expect(data.error).to.have.keys(['code', 'error_link', 'message', 'inputParameters']);
expect(data.error.code).to.equals(10);
expect(data.error.error_link).to.not.be.empty;
expect(data.error.message).to.not.be.empty;
done();
});
});
it('should get a 500 response with code 11 for missing position id', function (done) {
adminClient.post(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances?position_id=N', {
desc: 'testworkty',
worktyId: Workties[0]._id
}, function (err, req, res, data) {
expect(err).to.not.be.null;
expect(res.statusCode).to.equals(500);
expect(data).to.have.keys('error');
expect(data.error).to.have.keys(['code', 'error_link', 'message', 'inputParameters']);
expect(data.error.code).to.equals(11);
expect(data.error.error_link).to.not.be.empty;
expect(data.error.message).to.not.be.empty;
done();
});
});
it('should get a 201 response for position id', function (done) {
// Insert workty by index 0
adminClient.post(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances?position_index=0', {
desc: 'testworkty',
worktyId: Workties[0]._id
}, function (err, req, res, data) {
expect(err).to.be.null;
expect(res.statusCode).to.equals(201);
expect(res.headers).to.contain.keys('location');
expect(data).to.not.be.null;
var worktyInstanceId = data._id;
expect(res.headers.location).to.have.string('worktiesInstances/' + worktyInstanceId);
expect(data.desc).to.be.equal('testworkty');
var headerLocationFirst = res.headers.location;
// Get workflow to check workty instance added by index 1
adminClient.get(ApiPrefix + '/workflows/' + Workflows[0]._id, function (err, req, res, data) {
expect(err).to.be.null;
expect(res.statusCode).to.equals(200);
expect(data).to.not.be.empty;
expect(data.worktiesInstancesIds).to.satisfy(function (worktiesInstancesIds) {
if (worktiesInstancesIds.length !== 3) {
return false;
}
return _.indexOf(worktiesInstancesIds, worktyInstanceId) === 0;
});
// Insert workty instance before worktyInstanceId
adminClient.post(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances?position_id=' + worktyInstanceId, {
desc: 'testworkty',
worktyId: Workties[0]._id
}, function (err, req, res, data) {
expect(err).to.be.null;
expect(res.statusCode).to.equals(201);
expect(res.headers).to.contain.keys('location');
expect(data).to.not.be.null;
worktyInstanceId = data._id;
expect(res.headers.location).to.have.string('worktiesInstances/' + worktyInstanceId);
expect(data.desc).to.be.equal('testworkty');
var headerLocation = res.headers.location;
// Get workflow to check workty instance added by index 1
adminClient.get(ApiPrefix + '/workflows/' + Workflows[0]._id, function (err, req, res, data) {
expect(err).to.be.null;
expect(res.statusCode).to.equals(200);
expect(data).to.not.be.empty;
expect(data.worktiesInstancesIds).to.satisfy(function (worktiesInstancesIds) {
if (worktiesInstancesIds.length !== 4) {
return false;
}
return _.indexOf(worktiesInstancesIds, worktyInstanceId) === 0;
});
// Delete first workty instance
adminClient.del(headerLocationFirst, function (err, req, res, data) {
expect(err).to.be.null;
expect(data).is.empty;
expect(res.statusCode).to.equals(204);
// Delete second workty instance
adminClient.del(headerLocation, function (err, req, res, data) {
expect(err).to.be.null;
expect(data).is.empty;
expect(res.statusCode).to.equals(204);
done();
});
});
});
});
});
});
});
it('should get a 500 response with code 1 for missing worktyId', function (done) {
adminClient.post(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances?position_index=-1', {desc: 'testworkty'}, function (err, req, res, data) {
expect(err).to.not.be.null;
expect(res.statusCode).to.equals(409);
expect(data).to.have.keys('error');
expect(data.error).to.have.keys(['code', 'error_link', 'message', 'errors', 'inputParameters']);
expect(data.error.code).is.empty;
expect(data.error.error_link).to.not.be.empty;
expect(data.error.message).to.not.be.empty;
done();
});
});
});
describe('.updateWorktyInstance()', function () {
it('should get a 400 response', function (done) {
adminClient.put(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances/' + WorktiesInstances[0]._id, function (err, req, res, data) {
expect(err).to.not.be.null;
expect(res.statusCode).to.equals(400);
var error = JSON.parse(err.message).error;
expect(error.errors).is.empty;
done();
});
});
it('should get a 200 response', function (done) {
adminClient.put(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances/' + WorktiesInstances[0]._id, {desc: 'updateddesc'}, function (err, req, res, data) {
expect(err).to.be.null;
expect(res.statusCode).to.equals(200);
expect(data).to.not.be.null;
expect(data.desc).to.be.equal('updateddesc');
done();
});
});
});
describe('.delWorktyInstance()', function () {
it('should get a 500 response not found', function (done) {
// Delete workty instance
adminClient.del(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances/' + WorktiesInstances[0]._id + 'N', function (err, req, res, data) {
expect(err).to.not.be.null;
expect(res.statusCode).to.equals(500);
done();
});
});
it('should get a 204 response', function (done) {
// Create workty instance
adminClient.post(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances', {
desc: 'testworkty',
worktyId: Workties[0]._id
}, function (err, req, res, data) {
expect(err).to.be.null;
expect(res.statusCode).to.equals(201);
expect(res.headers).to.contain.keys('location');
expect(data).to.not.be.null;
var workflowId = data.workflowId;
var worktyInstanceId = data._id;
expect(res.headers.location).to.have.string('/' + workflowId);
// Delete workty instance
adminClient.del(ApiPrefix + '/workflows/' + workflowId + '/worktiesInstances/' + worktyInstanceId, function (err, req, res, data) {
expect(err).to.be.null;
expect(data).is.empty;
expect(res.statusCode).to.equals(204);
done();
});
});
});
});
describe('.updateWorktyInstanceProperty()', function () {
it('should get a 400 response', function (done) {
adminClient.put(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances/' + WorktiesInstances[0]._id + '/properties/' + WorktiesInstances[0].propertiesIds[0]._id, function (err, req, res, data) {
expect(err).to.not.be.null;
expect(res.statusCode).to.equals(400);
var error = JSON.parse(err.message).error;
expect(error.errors).is.empty;
done();
});
});
it('should get a 200 response', function (done) {
adminClient.put(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances/' + WorktiesInstances[0]._id + '/properties/' + WorktiesInstances[0].propertiesIds[0]._id, {
name: 'NewPropertyName',
value: 'NewPropertyValue'
}, function (err, req, res, data) {
expect(err).to.be.null;
expect(res.statusCode).to.equals(200);
expect(data.name).to.be.equal('NewPropertyName');
expect(data.value).to.be.equal('NewPropertyValue');
done();
});
});
});
});
}); | AlexLevshin/workty | tests/functional/v1/restapi/workflow-controller.spec.js | JavaScript | mit | 50,622 |
require.register("scripts/product", function(exports, require, module) {
var req = require('scripts/req');
AddStyleTagToItemVM = function(user, styletag_repo) {
// this is very similar to AddItemToCollectionVM - yet different.
var self = this;
self.styletags = styletag_repo.create_filter();
self.styletags.load_until_entry(100);
self.target_item = ko.observable(null);
self.selected_styletag = ko.observable();
self.show_select_styletag = ko.computed(function() {
return self.target_item();
});
self.show_must_login = ko.observable(false);
var request_add_styletag_to_item = function(item, styletag, success, error) {
req.post("/api/styletag-item/create/", JSON.stringify({'item': item.id, 'styletag': styletag.name}),
success, error);
};
self.confirmed_must_login = function() {
self.show_must_login(false);
};
self.confirmed_add_styletag = function() {
if (!self.selected_styletag()) {
// user selected "Choose..." in the drop-down
return;
}
if (!_.contains(self.target_item().styletags(), self.selected_styletag())) {
var success = function() {
self.target_item().styletags.push(self.selected_styletag().name);
self.target_item(null);
};
var error = function() {
self.target_item(null);
/* TODO: display something to user. */
};
request_add_styletag_to_item(self.target_item(), self.selected_styletag(), success, error);
};
};
self.add_to_item = function(item) {
if (!user()) {
self.show_must_login(true);
return;
}
console.log("lets go add styletag");
self.target_item(item);
};
};
ProductVM = function(template_name, item_repo, add_to_collection_vm, favorites_vm, add_styletag_to_item_vm) {
var self = this;
self.template_name = template_name;
self.product = ko.observable(null);
self.add_to_collection_vm = add_to_collection_vm;
self.favorites_vm = favorites_vm;
self.add_styletag_to_item_vm = add_styletag_to_item_vm
self.load = function(params) {
item_repo.fetch(params.product_id, self.product);
}
};
exports.ProductVM = ProductVM;
exports.AddStyleTagToItemVM = AddStyleTagToItemVM;
});
| julienaubert/clothstream | frontend/app/scripts/apps/product.js | JavaScript | mit | 2,625 |
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = undefined;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = require("react");
var _react2 = _interopRequireDefault(_react);
var _propTypes = require("prop-types");
var _propTypes2 = _interopRequireDefault(_propTypes);
var _textInput = require("./text-input");
var _textInput2 = _interopRequireDefault(_textInput);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
function validateEmail(email) {
var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
var EmailInput = function (_TextInput) {
_inherits(EmailInput, _TextInput);
function EmailInput(props) {
_classCallCheck(this, EmailInput);
return _possibleConstructorReturn(this, (EmailInput.__proto__ || Object.getPrototypeOf(EmailInput)).call(this, props));
}
_createClass(EmailInput, [{
key: "onValid",
value: function onValid(e) {
if (!!this.props.onValid) {
this.props.onValid(validateEmail(e.target.value), e);
}
}
}]);
return EmailInput;
}(_textInput2.default);
exports.default = EmailInput;
EmailInput.propTypes = {
type: _propTypes2.default.string.isRequired
};
EmailInput.defaultProps = {
type: "email"
}; | njnest/rc-inputs | lib/email-input.js | JavaScript | mit | 2,843 |
import React, { Component } from 'react';
import List from 'react-toolbox/lib/list/List';
import ListSubHeader from 'react-toolbox/lib/list/ListSubHeader';
import ListCheckbox from 'react-toolbox/lib/list/ListCheckbox';
import ListItem from 'react-toolbox/lib/list/ListItem';
import Dropdown from 'react-toolbox/lib/dropdown/Dropdown';
import ConnectedStoreHOC from '../utils/connect.store.hoc';
import * as Actions from '../utils/actions';
import { NEW_PHOTO_DURATIONS } from '../configs/constants';
const NEW_PHOTO_INTERVAL_OPTIONS = [
{ value: NEW_PHOTO_DURATIONS.ALWAYS, label: 'Always' },
{ value: NEW_PHOTO_DURATIONS.HOURLY, label: 'Hourly' },
{ value: NEW_PHOTO_DURATIONS.DAILY, label: 'Daily' },
];
const handleFetchFromServerChange = (value, ev) =>
Actions.setSetting({ fetchFromServer: value });
const handleNewPhotoIntervalChange = (value, ev) =>
Actions.setSetting({ newPhotoDuration: parseInt(value, 10) });
const NewPhotoIntervalDropdown = ({ refreshInterval, className }) => (
<Dropdown
label="Duration"
className={className}
value={refreshInterval}
source={NEW_PHOTO_INTERVAL_OPTIONS}
onChange={handleNewPhotoIntervalChange} />
);
class SettingsContainer extends Component {
componentDidMount() {
// lazy initialize the state object
setTimeout(() => Actions.refresh(false), 0);
}
render() {
const { fetchFromServer, newPhotoDuration } = this.props;
return (
<List selectable ripple>
<ListSubHeader caption="Background Photos" />
<ListCheckbox
caption="Load Fresh"
legend="If disabled, it will cycle through a list of locally stored wallpapers only."
checked={fetchFromServer}
onChange={handleFetchFromServerChange} />
<ListItem
itemContent={
<div>
<p className="settings__inlineItem">Show new photo</p>
<NewPhotoIntervalDropdown
className="settings__inlineItem"
refreshInterval={newPhotoDuration} />
</div>
}
ripple={false}
selectable={false} />
</List>);
}
}
export default ConnectedStoreHOC(SettingsContainer);
| emadalam/mesmerized | src/modules/background/containers/Settings.js | JavaScript | mit | 2,449 |
import {
defaultAction,
} from '../actions';
import {
DEFAULT_ACTION,
} from '../constants';
describe('Marginals actions', () => {
describe('Default Action', () => {
it('has a type of DEFAULT_ACTION', () => {
const expected = {
type: DEFAULT_ACTION,
};
expect(defaultAction()).toEqual(expected);
});
});
});
| brainsandspace/ship | app/containers/Marginals/tests/actions.test.js | JavaScript | mit | 352 |
//A simple build file using the tests directory for requirejs
{
baseUrl: "../../../requirejs/tests/text",
paths: {
text: "../../../requirejs/../text/text"
},
dir: "builds/text",
optimize: "none",
optimizeAllPluginResources: true,
modules: [
{
name: "widget"
}
]
}
| quantumlicht/collarbone | public/js/libs/rjs/build/tests/text.build.js | JavaScript | mit | 349 |
/*
Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
CKEDITOR.plugins.setLang( 'stylescombo', 'no', {
label: 'Stil',
panelTitle: 'Stilformater',
panelTitle1: 'Blokkstiler',
panelTitle2: 'Inlinestiler',
panelTitle3: 'Objektstiler'
} );
| otto-torino/gino | ckeditor/plugins/stylescombo/lang/no.js | JavaScript | mit | 364 |
"use strict";
var sqlite3 = require('sqlite3');
var authHelper = require('./server/helpers/auth');
var db = new sqlite3.Database('./data/users.db');
db.serialize(function() {
db.run(
'CREATE TABLE "users" ('
+ '"id" INTEGER PRIMARY KEY AUTOINCREMENT,'
+ '"username" TEXT,'
+ '"password" TEXT'
+ ')'
);
db.run("INSERT INTO users('username', 'password') VALUES (?, ?)", ["admin", authHelper.hashPassword("teste")]);
});
db.close(); | fppgodinho/express-practice | install.js | JavaScript | mit | 512 |
"use strict"
var writeIEEE754 = require('../float_parser').writeIEEE754
, readIEEE754 = require('../float_parser').readIEEE754
, Long = require('../long').Long
, Double = require('../double').Double
, Timestamp = require('../timestamp').Timestamp
, ObjectID = require('../objectid').ObjectID
, Symbol = require('../symbol').Symbol
, BSONRegExp = require('../regexp').BSONRegExp
, Code = require('../code').Code
, Decimal128 = require('../decimal128')
, MinKey = require('../min_key').MinKey
, MaxKey = require('../max_key').MaxKey
, DBRef = require('../db_ref').DBRef
, Binary = require('../binary').Binary;
// To ensure that 0.4 of node works correctly
var isDate = function isDate(d) {
return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]';
}
var calculateObjectSize = function calculateObjectSize(object, serializeFunctions, ignoreUndefined) {
var totalLength = (4 + 1);
if(Array.isArray(object)) {
for(var i = 0; i < object.length; i++) {
totalLength += calculateElement(i.toString(), object[i], serializeFunctions, true, ignoreUndefined)
}
} else {
// If we have toBSON defined, override the current object
if(object.toBSON) {
object = object.toBSON();
}
// Calculate size
for(var key in object) {
totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined)
}
}
return totalLength;
}
/**
* @ignore
* @api private
*/
function calculateElement(name, value, serializeFunctions, isArray, ignoreUndefined) {
// If we have toBSON defined, override the current object
if(value && value.toBSON){
value = value.toBSON();
}
switch(typeof value) {
case 'string':
return 1 + Buffer.byteLength(name, 'utf8') + 1 + 4 + Buffer.byteLength(value, 'utf8') + 1;
case 'number':
if(Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) {
if(value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { // 32 bit
return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (4 + 1);
} else {
return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (8 + 1);
}
} else { // 64 bit
return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (8 + 1);
}
case 'undefined':
if(isArray || !ignoreUndefined) return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (1);
return 0;
case 'boolean':
return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (1 + 1);
case 'object':
if(value == null || value instanceof MinKey || value instanceof MaxKey || value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') {
return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (1);
} else if(value instanceof ObjectID || value['_bsontype'] == 'ObjectID') {
return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (12 + 1);
} else if(value instanceof Date || isDate(value)) {
return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (8 + 1);
} else if(typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) {
return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (1 + 4 + 1) + value.length;
} else if(value instanceof Long || value instanceof Double || value instanceof Timestamp
|| value['_bsontype'] == 'Long' || value['_bsontype'] == 'Double' || value['_bsontype'] == 'Timestamp') {
return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (8 + 1);
} else if(value instanceof Decimal128 || value['_bsontype'] == 'Decimal128') {
return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (16 + 1);
} else if(value instanceof Code || value['_bsontype'] == 'Code') {
// Calculate size depending on the availability of a scope
if(value.scope != null && Object.keys(value.scope).length > 0) {
return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + 4 + 4 + Buffer.byteLength(value.code.toString(), 'utf8') + 1 + calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined);
} else {
return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + 4 + Buffer.byteLength(value.code.toString(), 'utf8') + 1;
}
} else if(value instanceof Binary || value['_bsontype'] == 'Binary') {
// Check what kind of subtype we have
if(value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) {
return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (value.position + 1 + 4 + 1 + 4);
} else {
return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (value.position + 1 + 4 + 1);
}
} else if(value instanceof Symbol || value['_bsontype'] == 'Symbol') {
return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + Buffer.byteLength(value.value, 'utf8') + 4 + 1 + 1;
} else if(value instanceof DBRef || value['_bsontype'] == 'DBRef') {
// Set up correct object for serialization
var ordered_values = {
'$ref': value.namespace
, '$id' : value.oid
};
// Add db reference if it exists
if(null != value.db) {
ordered_values['$db'] = value.db;
}
return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + calculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined);
} else if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]') {
return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + Buffer.byteLength(value.source, 'utf8') + 1
+ (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1
} else if(value instanceof BSONRegExp || value['_bsontype'] == 'BSONRegExp') {
return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + Buffer.byteLength(value.pattern, 'utf8') + 1
+ Buffer.byteLength(value.options, 'utf8') + 1
} else {
return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + calculateObjectSize(value, serializeFunctions, ignoreUndefined) + 1;
}
case 'function':
// WTF for 0.4.X where typeof /someregexp/ === 'function'
if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]' || String.call(value) == '[object RegExp]') {
return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + Buffer.byteLength(value.source, 'utf8') + 1
+ (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1
} else {
if(serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) {
return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + 4 + 4 + Buffer.byteLength(value.toString(), 'utf8') + 1 + calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined);
} else if(serializeFunctions) {
return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + 4 + Buffer.byteLength(value.toString(), 'utf8') + 1;
}
}
}
return 0;
}
var BSON = {};
// BSON MAX VALUES
BSON.BSON_INT32_MAX = 0x7FFFFFFF;
BSON.BSON_INT32_MIN = -0x80000000;
// JS MAX PRECISE VALUES
BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double.
BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double.
module.exports = calculateObjectSize;
| PLfW/lab-5-BabalaV | node_modules/bson/lib/bson/parser/calculate_size.js | JavaScript | mit | 7,823 |
/**
* DocumentController
*
* @description :: Server-side logic for managing documents
* @help :: See http://links.sailsjs.org/docs/controllers
*/
var exec = require('child_process').exec;
var path = require('path');
var fs = require('fs');
var UPLOADFOLDER = __dirname+'/../../.tmp/uploads';
module.exports = {
/**
* `OdfController.create()`
*/
upload: function (req, res) {
req.file("documents").upload(function (err, files) {
if (err) {
sails.log.error(err);
return res.serverError(err);
}
for (var i = 0; i < files.length; i++) {
files[i].uploadedAs = path.basename(files[i].fd);
};
// EmailService.send(from, subject, text, html);
return res.json({
message: files.length + ' file(s) uploaded successfully!',
files: files
});
});
},
// filters source: http://listarchives.libreoffice.org/global/users/msg15151.html
// org.openoffice.da.writer2xhtml.epub
// org.openoffice.da.calc2xhtml11
// Text - txt - csv (StarCalc)
// impress_svg_Export
// math8
// EPS - Encapsulated PostScript
// StarOffice XML (Base) Report Chart
// org.openoffice.da.writer2xhtml.mathml.xsl
// impress_svm_Export
// MS Excel 95 (StarWriter)
// impress_pdf_addstream_import
// JPG - JPEG
// placeware_Export
// StarOffice XML (Math)
// T602Document
// impress_jpg_Export
// writer_globaldocument_StarOffice_XML_Writer
// draw_emf_Export
// MS Word 2003 XML
// WMF - MS Windows Metafile
// GIF - Graphics Interchange
// writer_pdf_import
// calc8
// writer_globaldocument_StarOffice_XML_Writer_GlobalDocument
// MS Word 97 Vorlage
// impress_tif_Export
// draw_xpm_Export
// Calc MS Excel 2007 XML
// Text (encoded)
// MathML XML (Math)
// MET - OS/2 Metafile
// MS PowerPoint 97 AutoPlay
// impress8
// StarOffice XML (Calc)
// calc_HTML_WebQuery
// RAS - Sun Rasterfile
// MS Excel 5.0 (StarWriter)
// impress_png_Export
// DXF - AutoCAD Interchange
// impress_pct_Export
// impress_met_Export
// SGF - StarOffice Writer SGF
// draw_eps_Export
// Calc MS Excel 2007 Binary
// calc8_template
// Calc MS Excel 2007 XML Template
// impress_pbm_Export
// draw_pdf_import
// Calc Office Open XML
// math_pdf_Export
// Rich Text Format (StarCalc)
// MS PowerPoint 97 Vorlage
// StarOffice XML (Base)
// DIF
// Impress MS PowerPoint 2007 XML Template
// MS Excel 2003 XML
// impress_ras_Export
// draw_PCD_Photo_CD_Base16
// draw_bmp_Export
// WordPerfect Graphics
// StarOffice XML (Writer)
// PGM - Portable Graymap
// Office Open XML Text Template
// MS Excel 5.0/95
// draw_svg_Export
// draw_PCD_Photo_CD_Base4
// TGA - Truevision TARGA
// Quattro Pro 6.0
// writer_globaldocument_pdf_Export
// calc_pdf_addstream_import
// writerglobal8_HTML
// draw_svm_Export
// HTML
// EMF - MS Windows Metafile
// PPM - Portable Pixelmap
// Lotus
// impress_ppm_Export
// draw_jpg_Export
// Text
// TIF - Tag Image File
// Impress Office Open XML AutoPlay
// StarOffice XML (Base) Report
// PNG - Portable Network Graphic
// draw8
// Rich Text Format
// writer_web_StarOffice_XML_Writer_Web_Template
// org.openoffice.da.writer2xhtml
// MS_Works
// Office Open XML Text
// SVG - Scalable Vector Graphics
// org.openoffice.da.writer2xhtml11
// draw_tif_Export
// impress_gif_Export
// StarOffice XML (Draw)
// StarOffice XML (Impress)
// Text (encoded) (StarWriter/Web)
// writer_web_pdf_Export
// MediaWiki_Web
// impress_pdf_Export
// draw_pdf_addstream_import
// draw_png_Export
// HTML (StarCalc)
// HTML (StarWriter)
// impress_StarOffice_XML_Impress_Template
// draw_pct_Export
// calc_StarOffice_XML_Calc_Template
// MS Excel 95 Vorlage/Template
// writerglobal8_writer
// MS Excel 95
// draw_met_Export
// dBase
// MS Excel 97
// MS Excel 4.0
// draw_pbm_Export
// impress_StarOffice_XML_Draw
// Impress Office Open XML
// writerweb8_writer
// chart8
// MediaWiki
// MS Excel 4.0 Vorlage/Template
// impress_wmf_Export
// draw_ras_Export
// writer_StarOffice_XML_Writer_Template
// BMP - MS Windows
// impress8_template
// LotusWordPro
// impress_pgm_Export
// SGV - StarDraw 2.0
// draw_PCD_Photo_CD_Base
// draw_html_Export
// writer8_template
// Calc Office Open XML Template
// writerglobal8
// draw_flash_Export
// MS Word 2007 XML Template
// impress8_draw
// CGM - Computer Graphics Metafile
// MS PowerPoint 97
// WordPerfect
// impress_emf_Export
// writer_pdf_Export
// PSD - Adobe Photoshop
// PBM - Portable Bitmap
// draw_ppm_Export
// writer_pdf_addstream_import
// PCX - Zsoft Paintbrush
// writer_web_HTML_help
// MS Excel 4.0 (StarWriter)
// Impress Office Open XML Template
// org.openoffice.da.writer2xhtml.mathml
// MathType 3.x
// impress_xpm_Export
// writer_web_StarOffice_XML_Writer
// writerweb8_writer_template
// MS Word 95
// impress_html_Export
// MS Word 97
// draw_gif_Export
// writer8
// MS Excel 5.0/95 Vorlage/Template
// draw8_template
// StarOffice XML (Chart)
// XPM
// draw_pdf_Export
// calc_pdf_Export
// impress_eps_Export
// XBM - X-Consortium
// Text (encoded) (StarWriter/GlobalDocument)
// writer_MIZI_Hwp_97
// MS WinWord 6.0
// Lotus 1-2-3 1.0 (WIN) (StarWriter)
// SYLK
// MS Word 2007 XML
// Text (StarWriter/Web)
// impress_pdf_import
// MS Excel 97 Vorlage/Template
// Impress MS PowerPoint 2007 XML AutoPlay
// Impress MS PowerPoint 2007 XML
// draw_wmf_Export
// Unifa Adressbuch
// org.openoffice.da.calc2xhtml
// impress_bmp_Export
// Lotus 1-2-3 1.0 (DOS) (StarWriter)
// MS Word 95 Vorlage
// MS WinWord 5
// PCT - Mac Pict
// SVM - StarView Metafile
// draw_StarOffice_XML_Draw_Template
// impress_flash_Export
// draw_pgm_Export
convert: function (req, res) {
var stdout = '';
var stderr = '';
sails.log.info('convert');
if(!req.param('filename')) res.badRequest('filename is required');
var source = req.param('filename');
var inputDir = UPLOADFOLDER +'/'+source;
var outputFileExtension = req.param('extension') ? req.param('extension') : 'pdf'; // example 'pdf';
var outputFilterName = req.param('filter') ? ':'+req.param('filter') : ''; //(optinal) example ':'+'MS Excel 95';
var outputDir = UPLOADFOLDER;
if(req.param('dir')) {
outputDir += '/'+req.param('dir');
}
outputDir = path.normalize(outputDir);
inputDir = path.normalize(inputDir);
var target = outputDir+"/"+path.basename(source, '.odt')+"."+outputFileExtension;
var command = 'soffice --headless --invisible --convert-to '+outputFileExtension+outputFilterName+' --outdir '+outputDir+' '+inputDir;
sails.log.info(command);
var child = exec(command, function (code, stdout, stderr) {
if(code) {
sails.log.error(code);
}
if(stderr) {
sails.log.error(stderr);
}
if(stdout) {
sails.log.info(stdout);
}
res.json({target:target, code: code, stdout: stdout, stderr: stderr});
// res.download(target); // not working over socket.io
});
}
};
| JumpLink/mwp-maps | src/api/controllers/DocumentController.js | JavaScript | mit | 7,286 |
'use strict';
var assert = require('assert'),
mongoose = require('mongoose'),
mobgoose = require('../')(mongoose);
var Foo = mongoose.model('Foo', new mongoose.Schema({}), 'foo_collection_name');
it('accepts configuration without url', function() {
return mobgoose({ host: 'localhost', database: 'test123' })
.then(function(connection) {
var model = connection.model('Foo');
assert(model.db.name === 'test123');
});
});
it('supports a simple conection string', function() {
return mobgoose('mongodb://localhost:27017/test')
.then(function(connection) {
var model = connection.model('Foo');
assert(model.db.name === 'test');
});
});
it('keeps the model collection name', function() {
return mobgoose('mongodb://localhost:27017/test')
.then(function(connection) {
var model = connection.model('Foo');
assert(model.collection.name === 'foo_collection_name');
});
});
describe('different databases on the same server', function(done) {
var connection1, connection2;
before(function() {
return mobgoose({
host: 'localhost',
database: 'test1'
})
.then(function(connection) {
connection1 = connection;
});
});
before(function() {
return mobgoose({
host: 'localhost',
database: 'test2'
})
.then(function(connection) {
connection2 = connection;
});
});
it('use one actual connection', function() {
assert(Object.keys(mobgoose.connections).length === 1);
});
it('produce connections in the connected readyState', function() {
assert(connection1.readyState === mongoose.STATES.connected);
assert(connection2.readyState === mongoose.STATES.connected);
});
it('register their own models', function() {
assert(connection1.model('Foo') !== undefined);
assert(connection1.model('Foo').modelName === Foo.modelName);
assert(connection1.model('Foo').db.name === 'test1');
assert(connection2.model('Foo') !== undefined);
assert(connection2.model('Foo').modelName === Foo.modelName);
assert(connection2.model('Foo').db.name === 'test2');
});
});
describe('multiple hosts', function() {
it('work with a bunch of databases', function() {
return Promise.all(['localhost', '127.0.0.1'].map((host) => {
return Promise.all(['foo', 'bar', 'baz'].map((database) => {
return mobgoose({
host: host,
database: database
});
}));
}))
.then(function() {
assert(Object.keys(mobgoose.connections).length == 2);
});
});
});
| dougmoscrop/mobgoose | test/spec.js | JavaScript | mit | 2,576 |
"use strict";
const setupTask = require('utils').setupTask;
const calcTasks = require("calcTasks");
module.exports = {
run : function(creep){
if(!creep.task){
var room = creep.room;
var creepsByTask = _(Game.creeps).filter( (c) => c.task && c.task.roomName == room.name).groupBy('task.type').value();
var upgradeList = calcTasks.calcUpgradeTasks(room,creepsByTask);
var myIndex = _.findIndex(upgradeList, (t) => true);
if(myIndex != -1){
var upgradeContainer = room.controller.pos.findInRange(FIND_STRUCTURES,1,{filter: (s) => s.structureType == STRUCTURE_CONTAINER})[0];
creep.task=upgradeList[myIndex];
if(upgradeContainer != undefined){
creep.task.containerId = upgradeContainer.id;
}
return OK;
}
}
}
}
| Eijolend/screeps | creep.roleUpgrader.js | JavaScript | mit | 899 |
// GET /api/v1/nowplaying/groovesalad
{
"stationId": "groovesalad",
"time": 1425871720000,
"artist": "Panorama",
"title": "Selene",
"album": "Panorama",
"trackCorrected": false,
"artistCorrected": false,
"albumCorrected": false,
"corrected": false,
"duration": 335000,
"durationEstimated": false
}
| maxkueng/somascrobbler-api | static/sample-nowplaying.js | JavaScript | mit | 320 |
/**
* Using Rails-like standard naming convention for endpoints.
* GET /api/bridges -> index
* POST /api/bridges -> create
* GET /api/bridges/:id -> show
* PUT /api/bridges/:id -> upsert
* PATCH /api/bridges/:id -> patch
* DELETE /api/bridges/:id -> destroy
*/
'use strict';
import jsonpatch from 'fast-json-patch';
import Bridge from './bridge.model';
function respondWithResult(res, statusCode) {
statusCode = statusCode || 200;
return function(entity) {
if (entity) {
return res.status(statusCode).json(entity);
}
return null;
};
}
function patchUpdates(patches) {
return function(entity) {
try {
// eslint-disable-next-line prefer-reflect
jsonpatch.apply(entity, patches, /*validate*/ true);
} catch(err) {
return Promise.reject(err);
}
return entity.save();
};
}
function removeEntity(res) {
return function(entity) {
if (entity) {
return entity.remove()
.then(() => {
res.status(204).end();
});
}
};
}
function handleEntityNotFound(res) {
return function(entity) {
if (!entity) {
res.status(404).end();
return null;
}
return entity;
};
}
function handleError(res, statusCode) {
statusCode = statusCode || 500;
return function(err) {
res.status(statusCode).send(err);
};
}
// Gets a list of Bridges
export function index(req, res) {
return Bridge.find().exec()
.then(respondWithResult(res))
.catch(handleError(res));
}
// Gets a single Bridge from the DB
export function show(req, res) {
return Bridge.findById(req.params.id).exec()
.then(handleEntityNotFound(res))
.then(respondWithResult(res))
.catch(handleError(res));
}
// Creates a new Bridge in the DB
export function create(req, res) {
return Bridge.create(req.body)
.then(respondWithResult(res, 201))
.catch(handleError(res));
}
// Upserts the given Bridge in the DB at the specified ID
export function upsert(req, res) {
if (req.body._id) {
Reflect.deleteProperty(req.body, '_id');
}
return Bridge.findOneAndUpdate({_id: req.params.id}, req.body, {new: true, upsert: true, setDefaultsOnInsert: true, runValidators: true}).exec()
.then(respondWithResult(res))
.catch(handleError(res));
}
// Updates an existing Bridge in the DB
export function patch(req, res) {
if (req.body._id) {
Reflect.deleteProperty(req.body, '_id');
}
return Bridge.findById(req.params.id).exec()
.then(handleEntityNotFound(res))
.then(patchUpdates(req.body))
.then(respondWithResult(res))
.catch(handleError(res));
}
// Deletes a Bridge from the DB
export function destroy(req, res) {
return Bridge.findById(req.params.id).exec()
.then(handleEntityNotFound(res))
.then(removeEntity(res))
.catch(handleError(res));
}
| sunshouxing/bshm | server/api/bridge/bridge.controller.js | JavaScript | mit | 2,898 |
/*
jQuery UI Sortable plugin wrapper
@param [ui-sortable] {object} Options to pass to $.fn.sortable() merged onto ui.config
*/
angular.module('ui.sortable', [])
.value('uiSortableConfig',{})
.directive('uiSortable', [ 'uiSortableConfig',
function(uiSortableConfig) {
return {
require: '?ngModel',
link: function(scope, element, attrs, ngModel) {
function combineCallbacks(first,second){
if( second && (typeof second === "function") ){
return function(e,ui){
first(e,ui);
second(e,ui);
};
}
return first;
}
var opts = {};
var callbacks = {
receive: null,
remove:null,
start:null,
stop:null,
update:null
};
var apply = function(e, ui) {
if (ui.item.sortable.resort || ui.item.sortable.relocate) {
scope.$apply();
}
};
angular.extend(opts, uiSortableConfig);
if (ngModel) {
ngModel.$render = function() {
element.sortable( "refresh" );
};
callbacks.start = function(e, ui) {
// Save position of dragged item
ui.item.sortable = { index: ui.item.index() };
};
callbacks.update = function(e, ui) {
// For some reason the reference to ngModel in stop() is wrong
ui.item.sortable.resort = ngModel;
};
callbacks.receive = function(e, ui) {
ui.item.sortable.relocate = true;
// added item to array into correct position and set up flag
ngModel.$modelValue.splice(ui.item.index(), 0, ui.item.sortable.moved);
};
callbacks.remove = function(e, ui) {
// copy data into item
if (ngModel.$modelValue.length === 1) {
ui.item.sortable.moved = ngModel.$modelValue.splice(0, 1)[0];
} else {
ui.item.sortable.moved = ngModel.$modelValue.splice(ui.item.sortable.index, 1)[0];
}
};
callbacks.stop = function(e, ui) {
// digest all prepared changes
if (ui.item.sortable.resort && !ui.item.sortable.relocate) {
// Fetch saved and current position of dropped element
var end, start;
start = ui.item.sortable.index;
end = ui.item.index();
// Reorder array and apply change to scope
ui.item.sortable.resort.$modelValue.splice(end, 0, ui.item.sortable.resort.$modelValue.splice(start, 1)[0]);
}
};
}
scope.$watch(attrs.uiSortable, function(newVal, oldVal){
angular.forEach(newVal, function(value, key){
if( callbacks[key] ){
// wrap the callback
value = combineCallbacks( callbacks[key], value );
if ( key === 'stop' ){
// call apply after stop
value = combineCallbacks( value, apply );
}
}
element.sortable('option', key, value);
});
}, true);
angular.forEach(callbacks, function(value, key ){
opts[key] = combineCallbacks(value, opts[key]);
});
// call apply after stop
opts.stop = combineCallbacks( opts.stop, apply );
// Create sortable
element.sortable(opts);
}
};
}
]);
| kdisneur/wish_list | javascripts/angular-sortable.js | JavaScript | mit | 4,272 |
load("build/jslint.js");
var src = readFile("dist/jquery.ImageColorPicker.js");
JSLINT(src, { evil: true, forin: true });
// All of the following are known issues that we think are 'ok'
// (in contradiction with JSLint) more information here:
// http://docs.jquery.com/JQuery_Core_Style_Guidelines
var ok = {
"Expected an identifier and instead saw 'undefined' (a reserved word).": true,
"Use '===' to compare with 'null'.": true,
"Use '!==' to compare with 'null'.": true,
"Expected an assignment or function call and instead saw an expression.": true,
"Expected a 'break' statement before 'case'.": true
};
var e = JSLINT.errors, found = 0, w;
for ( var i = 0; i < e.length; i++ ) {
w = e[i];
if ( !ok[ w.reason ] ) {
found++;
print( "\n" + w.evidence + "\n" );
print( " Problem at line " + w.line + " character " + w.character + ": " + w.reason );
}
}
if ( found > 0 ) {
print( "\n" + found + " Error(s) found." );
} else {
print( "JSLint check passed." );
}
| Skarabaeus/ImageColorPicker | build/jslint-check.js | JavaScript | mit | 990 |
var fs = require('fs');
var os=require('os');
var express = require('express'),
// wine = require('./routes/wines');
user = require('./services/user');
contact = require('./services/contact');
inbox = require('./services/inbox');
outbox = require('./services/outbox');
device = require('./services/device');
audio = require('./services/audio');
GLOBAL.GCMessage = require('./lib/GCMessage.js');
GLOBAL.Sound = require('./lib/Sound.js');
GLOBAL.PORT = 3000;
GLOBAL.IP = "54.214.9.117";
GLOBAL.HOSTNAME = "vivu.uni.me";
//GLOBAL.IP = "127.0.0.1";
GLOBAL.__dirname = __dirname;
var app = express();
app.configure(function () {
app.use(express.logger('dev')); /* 'default', 'short', 'tiny', 'dev' */
app.use(express.bodyParser());
app.use(express.static(__dirname + '/public/html'));
});
app.set('views', __dirname + '/views');
app.engine('html', require('ejs').renderFile);
app.get('/$',function (req, res){
res.render('homepage.html');
});
app.get('/audio/flash',function (req, res){
try{
var filePath = __dirname + "/public/flash/dewplayer.swf";
var audioFile = fs.statSync(filePath);
res.setHeader('Content-Type', 'application/x-shockwave-flash');
res.setHeader('Content-Length',audioFile.size);
var readStream = fs.createReadStream(filePath);
readStream.on('data', function(data) {
res.write(data);
});
readStream.on('end', function() {
res.end();
});
}
catch(e){
console.log("Error when process get /audio/:id, error: "+ e);
res.send("Error from server");
}
});
app.get('/cfs/audio/:id',function (req, res){
try{
var audioId = req.params.id;
var ip = GLOBAL.IP;
var host = ip+":8888";
var source = "http://"+host+"/public/audio/"+audioId+".mp3";
res.render('index1.html',
{
sourceurl:source,
sourceid: audioId
});
}
catch(e){
console.log("Error when process get cfs/audio/:id, error: "+ e);
res.send("Error from server");
}
});
/*
app.get('/cfs/audio/:id',function (req, res)
{
console.log("hostname:"+os.hostname());
try{
var audioId = req.params.id;
var ip = GLOBAL.IP;
var host = ip+":8888";
var source = "http://"+host+"/public/audio/"+audioId+".mp3";
//var source = "http://s91.stream.nixcdn.com/3ce626c71801e67a340ef3b7997001be/51828581/NhacCuaTui025/RingBackTone-SunnyHill_4g6z.mp3";
res.render(__dirname + '/public/template/index.jade', {sourceurl:source, sourceid: audioId});
}
catch(e){
console.log("Error when process get cfs/audio/:id, error: "+ e);
res.send("Error from server");
}
});
*/
/*
app.get('/audio/:id',function (req, res)
{
try{
var audioId = req.params.id;
var filePath = __dirname + "/public/audio/"+audioId+".mp3";
var audioFile = fs.statSync(filePath);
res.setHeader('Content-Type', 'audio/mpeg');
res.setHeader('Content-Length',audioFile.size);
var readStream = fs.createReadStream(filePath);
readStream.on('data', function(data) {
res.write(data);
});
readStream.on('end', function() {
res.end();
});
}
catch(e){
console.log("Error when process get /audio/:id, error: "+ e);
res.send("Error from server");
}
});
*/
/*
app.get('/wines', wine.findAll);
app.get('/wines/:id', wine.findById);
app.post('/wines', wine.addWine);
app.put('/wines', wine.updateWine);
app.delete('/wines/:id', wine.deleteWine);
*/
//gcm service
//app.get('/services/gcm', bllUsers);
// user service
app.get('/services/users', user.findAllUsers);
//app.get('/services/users/:id', user.findUserByUserId);
app.get('/services/users/:facebookid',user.findUserByFacebookID);
app.post('/services/users/searchname', user.findUserByUserName);
app.post('/services/users', user.addUser);
app.put('/services/users/:id', user.updateUser);
app.delete('/services/users/:id', user.deleteUserByUserId);
app.delete('/services/users', user.deleteAllUsers);
//contact service
app.get('/services/contacts', contact.findAllContacts);
app.get('/services/contacts/byuserid/:id', contact.getAllContactByUserId);
app.post('/services/contacts', contact.addContact);
app.delete('/services/contacts', contact.deleteAllContacts);
/*
app.post('/services/contacts', user.addUser);
app.put('/services/contacts/:id', user.updateUser);
app.delete('/services/contacts/:id', user.deleteUserByUserId);
*/
//inbox service
app.post('/services/inboxs/delete', inbox.deleteInboxs);
app.post('/services/inboxs', inbox.addInbox);
app.get('/services/inboxs', inbox.findAllInboxs);
app.get('/services/inboxs/byuserid/:id', inbox.findInboxByUserId);
app.delete('/services/inboxs', inbox.deleteAllInboxs);
app.put('/services/inboxs', inbox.updateInboxs);
//app.put('/services/inbox', inbox.updateInbox);
//outbox service
app.post('/services/outboxs/delete', outbox.deleteOutboxs);
app.post('/services/outboxs', outbox.addOutbox);
app.get('/services/outboxs', outbox.findAllInboxs);
app.get('/services/outboxs/byuserid/:id', outbox.findOutboxByUserId);
app.delete('/services/outboxs', outbox.deleteAllOutboxs);
//device service
app.post('/services/devices', device.addDevice);
app.get('/services/devices', device.getAllDevices);
app.get('/services/devices/byuserid/:id', device.getAllDevicesByUserId);
app.delete('/services/devices', device.deleteAllDevices);
//audio service
app.post('/upload', audio.uploadAudio);
app.get('/upload/view', function(req, res){
res.send(
'<form action="/upload" method="post" enctype="multipart/form-data">'+
'<input type="file" name="source">'+
'<input type="submit" value="Upload">'+
'</form>'
);
});
/************************test******************************************/
app.get('/convert', function(req, res){
function removeSubstring(str,strrm){
var newstr = str.replace(strrm,"");
return newstr;
}
GLOBAL.__staticDir = removeSubstring(GLOBAL.__dirname,"/vivuserver/trunk");
var audioDir = GLOBAL.__staticDir + "/staticserver/public/audio/";
var soundlib = new GLOBAL.Sound;
soundlib.convertWavToMp3(audioDir + "24.wav",audioDir + "testout1.mp3");
res.send("Ok");
});
/************************end test******************************************/
app.listen(GLOBAL.PORT);
console.log('Listening on port 3000...');
| tonycaovn/vivuserver | server.js | JavaScript | mit | 6,443 |
// Javascript helper functions for parsing and displaying UUIDs in the MongoDB shell.
// This is a temporary solution until SERVER-3153 is implemented.
// To create BinData values corresponding to the various driver encodings use:
// var s = "{00112233-4455-6677-8899-aabbccddeeff}";
// var uuid = UUID(s); // new Standard encoding
// var juuid = JUUID(s); // JavaLegacy encoding
// var csuuid = CSUUID(s); // CSharpLegacy encoding
// var pyuuid = PYUUID(s); // PythonLegacy encoding
// To convert the various BinData values back to human readable UUIDs use:
// uuid.toUUID() => 'UUID("00112233-4455-6677-8899-aabbccddeeff")'
// juuid.ToJUUID() => 'JUUID("00112233-4455-6677-8899-aabbccddeeff")'
// csuuid.ToCSUUID() => 'CSUUID("00112233-4455-6677-8899-aabbccddeeff")'
// pyuuid.ToPYUUID() => 'PYUUID("00112233-4455-6677-8899-aabbccddeeff")'
// With any of the UUID variants you can use toHexUUID to echo the raw BinData with subtype and hex string:
// uuid.toHexUUID() => 'HexData(4, "00112233-4455-6677-8899-aabbccddeeff")'
// juuid.toHexUUID() => 'HexData(3, "77665544-3322-1100-ffee-ddccbbaa9988")'
// csuuid.toHexUUID() => 'HexData(3, "33221100-5544-7766-8899-aabbccddeeff")'
// pyuuid.toHexUUID() => 'HexData(3, "00112233-4455-6677-8899-aabbccddeeff")'
function HexToBase64(hex) {
var base64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var base64 = "";
var group;
for (var i = 0; i < 30; i += 6) {
group = parseInt(hex.substr(i, 6), 16);
base64 += base64Digits[(group >> 18) & 0x3f];
base64 += base64Digits[(group >> 12) & 0x3f];
base64 += base64Digits[(group >> 6) & 0x3f];
base64 += base64Digits[group & 0x3f];
}
group = parseInt(hex.substr(30, 2), 16);
base64 += base64Digits[(group >> 2) & 0x3f];
base64 += base64Digits[(group << 4) & 0x3f];
base64 += "==";
return base64;
}
function Base64ToHex(base64) {
var base64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
var hexDigits = "0123456789abcdef";
var hex = "";
for (var i = 0; i < 24; ) {
var e1 = base64Digits.indexOf(base64[i++]);
var e2 = base64Digits.indexOf(base64[i++]);
var e3 = base64Digits.indexOf(base64[i++]);
var e4 = base64Digits.indexOf(base64[i++]);
var c1 = (e1 << 2) | (e2 >> 4);
var c2 = ((e2 & 15) << 4) | (e3 >> 2);
var c3 = ((e3 & 3) << 6) | e4;
hex += hexDigits[c1 >> 4];
hex += hexDigits[c1 & 15];
if (e3 != 64) {
hex += hexDigits[c2 >> 4];
hex += hexDigits[c2 & 15];
}
if (e4 != 64) {
hex += hexDigits[c3 >> 4];
hex += hexDigits[c3 & 15];
}
}
return hex;
}
function UUID(uuid) {
var hex = uuid.replace(/[{}-]/g, ""); // remove extra characters
var base64 = HexToBase64(hex);
return new BinData(4, base64); // new subtype 4
}
function JUUID(uuid) {
var hex = uuid.replace(/[{}-]/g, ""); // remove extra characters
var msb = hex.substr(0, 16);
var lsb = hex.substr(16, 16);
msb = msb.substr(14, 2) + msb.substr(12, 2) + msb.substr(10, 2) + msb.substr(8, 2) + msb.substr(6, 2) + msb.substr(4, 2) + msb.substr(2, 2) + msb.substr(0, 2);
lsb = lsb.substr(14, 2) + lsb.substr(12, 2) + lsb.substr(10, 2) + lsb.substr(8, 2) + lsb.substr(6, 2) + lsb.substr(4, 2) + lsb.substr(2, 2) + lsb.substr(0, 2);
hex = msb + lsb;
var base64 = HexToBase64(hex);
return new BinData(3, base64);
}
function CSUUID(uuid) {
var hex = uuid.replace(/[{}-]/g, ""); // remove extra characters
var a = hex.substr(6, 2) + hex.substr(4, 2) + hex.substr(2, 2) + hex.substr(0, 2);
var b = hex.substr(10, 2) + hex.substr(8, 2);
var c = hex.substr(14, 2) + hex.substr(12, 2);
var d = hex.substr(16, 16);
hex = a + b + c + d;
var base64 = HexToBase64(hex);
return new BinData(3, base64);
}
function PYUUID(uuid) {
var hex = uuid.replace(/[{}-]/g, ""); // remove extra characters
var base64 = HexToBase64(hex);
return new BinData(3, base64);
}
BinData.prototype.toUUID = function () {
var hex = Base64ToHex(this.base64()); // don't use BinData's hex function because it has bugs in older versions of the shell
var uuid = hex.substr(0, 8) + '-' + hex.substr(8, 4) + '-' + hex.substr(12, 4) + '-' + hex.substr(16, 4) + '-' + hex.substr(20, 12);
return 'UUID("' + uuid + '")';
}
BinData.prototype.toJUUID = function () {
var hex = Base64ToHex(this.base64()); // don't use BinData's hex function because it has bugs in older versions of the shell
var msb = hex.substr(0, 16);
var lsb = hex.substr(16, 16);
msb = msb.substr(14, 2) + msb.substr(12, 2) + msb.substr(10, 2) + msb.substr(8, 2) + msb.substr(6, 2) + msb.substr(4, 2) + msb.substr(2, 2) + msb.substr(0, 2);
lsb = lsb.substr(14, 2) + lsb.substr(12, 2) + lsb.substr(10, 2) + lsb.substr(8, 2) + lsb.substr(6, 2) + lsb.substr(4, 2) + lsb.substr(2, 2) + lsb.substr(0, 2);
hex = msb + lsb;
var uuid = hex.substr(0, 8) + '-' + hex.substr(8, 4) + '-' + hex.substr(12, 4) + '-' + hex.substr(16, 4) + '-' + hex.substr(20, 12);
return 'JUUID("' + uuid + '")';
}
BinData.prototype.toCSUUID = function () {
var hex = Base64ToHex(this.base64()); // don't use BinData's hex function because it has bugs in older versions of the shell
var a = hex.substr(6, 2) + hex.substr(4, 2) + hex.substr(2, 2) + hex.substr(0, 2);
var b = hex.substr(10, 2) + hex.substr(8, 2);
var c = hex.substr(14, 2) + hex.substr(12, 2);
var d = hex.substr(16, 16);
hex = a + b + c + d;
var uuid = hex.substr(0, 8) + '-' + hex.substr(8, 4) + '-' + hex.substr(12, 4) + '-' + hex.substr(16, 4) + '-' + hex.substr(20, 12);
return 'CSUUID("' + uuid + '")';
}
BinData.prototype.toPYUUID = function () {
var hex = Base64ToHex(this.base64()); // don't use BinData's hex function because it has bugs
var uuid = hex.substr(0, 8) + '-' + hex.substr(8, 4) + '-' + hex.substr(12, 4) + '-' + hex.substr(16, 4) + '-' + hex.substr(20, 12);
return 'PYUUID("' + uuid + '")';
}
BinData.prototype.toHexUUID = function () {
var hex = Base64ToHex(this.base64()); // don't use BinData's hex function because it has bugs
var uuid = hex.substr(0, 8) + '-' + hex.substr(8, 4) + '-' + hex.substr(12, 4) + '-' + hex.substr(16, 4) + '-' + hex.substr(20, 12);
return 'HexData(' + this.subtype() + ', "' + uuid + '")';
}
function TestUUIDHelperFunctions() {
var s = "{00112233-4455-6677-8899-aabbccddeeff}";
var uuid = UUID(s);
var juuid = JUUID(s);
var csuuid = CSUUID(s);
var pyuuid = PYUUID(s);
print(uuid.toUUID());
print(juuid.toJUUID());
print(csuuid.toCSUUID());
print(pyuuid.toPYUUID());
print(uuid.toHexUUID());
print(juuid.toHexUUID());
print(csuuid.toHexUUID());
print(pyuuid.toHexUUID());
}
| sragu/mongo-uuid | lib/uuidhelpers.js | JavaScript | mit | 6,977 |
var assert = require('assert');
var RequestBuilder = require('../lib/rest-builder');
describe('REST Request Builder', function () {
describe('Request templating', function () {
var server = null;
before(function (done) {
var express = require('express');
var app = express();
app.configure(function () {
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.favicon());
// app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
});
app.all('*', function (req, res, next) {
res.setHeader('Content-Type', 'application/json');
var payload = {
method: req.method,
url: req.url,
headers: req.headers,
query: req.query,
body: req.body
};
res.json(200, payload);
});
server = app.listen(app.get('port'), function (err, data) {
// console.log('Server listening on ', app.get('port'));
done(err, data);
});
});
after(function(done) {
server && server.close(done);
});
it('should substitute the variables', function (done) {
var builder = new RequestBuilder('GET', 'http://localhost:3000/{p}').query({x: '{x}', y: 2});
builder.invoke({p: 1, x: 'X'},
function (err, body, response) {
// console.log(response.headers);
assert.equal(200, response.statusCode);
if (typeof body === 'string') {
body = JSON.parse(body);
}
// console.log(body);
assert.equal(body.query.x, 'X');
assert.equal(body.query.y, 2);
done(err, body);
});
});
it('should support default variables', function (done) {
var builder = new RequestBuilder('GET', 'http://localhost:3000/{p=100}').query({x: '{x=ME}', y: 2});
builder.invoke({p: 1},
function (err, body, response) {
// console.log(response.headers);
assert.equal(200, response.statusCode);
if (typeof body === 'string') {
body = JSON.parse(body);
}
// console.log(body);
assert.equal(0, body.url.indexOf('/1'));
assert.equal('ME', body.query.x);
assert.equal(2, body.query.y);
done(err, body);
});
});
it('should support typed variables', function (done) {
var builder = new RequestBuilder('POST', 'http://localhost:3000/{p=100}').query({x: '{x=100:number}', y: 2})
.body({a: '{a=1:number}', b: '{b=true:boolean}'});
builder.invoke({p: 1, a: 100, b: false},
function (err, body, response) {
// console.log(response.headers);
assert.equal(200, response.statusCode);
if (typeof body === 'string') {
body = JSON.parse(body);
}
// console.log(body);
assert.equal(0, body.url.indexOf('/1'));
assert.equal(100, body.query.x);
assert.equal(2, body.query.y);
assert.equal(100, body.body.a);
assert.equal(false, body.body.b);
done(err, body);
});
});
it('should report missing required variables', function (done) {
var builder = new RequestBuilder('POST', 'http://localhost:3000/{!p}').query({x: '{x=100:number}', y: 2})
.body({a: '{^a:number}', b: '{!b=true:boolean}'});
try {
builder.invoke({a: 100, b: false},
function (err, body, response) {
// console.log(response.headers);
assert.equal(200, response.statusCode);
if (typeof body === 'string') {
body = JSON.parse(body);
}
// console.log(body);
done(err, body);
});
assert.fail();
} catch(err) {
// This is expected
done(null, null);
}
});
it('should support required variables', function (done) {
var builder = new RequestBuilder('POST', 'http://localhost:3000/{!p}').query({x: '{x=100:number}', y: 2})
.body({a: '{^a:number}', b: '{!b=true:boolean}'});
builder.invoke({p: 1, a: 100, b: false},
function (err, body, response) {
// console.log(response.headers);
assert.equal(200, response.statusCode);
if (typeof body === 'string') {
body = JSON.parse(body);
}
// console.log(body);
assert.equal(0, body.url.indexOf('/1'));
assert.equal(100, body.query.x);
assert.equal(2, body.query.y);
assert.equal(100, body.body.a);
assert.equal(false, body.body.b);
done(err, body);
});
});
it('should build an operation with the parameter names', function (done) {
var builder = new RequestBuilder('POST', 'http://localhost:3000/{p}').query({x: '{x}', y: 2});
var fn = builder.operation(['p', 'x']);
fn(1, 'X',
function (err, body, response) {
assert.equal(200, response.statusCode);
if (typeof body === 'string') {
body = JSON.parse(body);
}
// console.log(body);
assert.equal(0, body.url.indexOf('/1'));
assert.equal('X', body.query.x);
assert.equal(2, body.query.y);
// console.log(body);
done(err, body);
});
});
it('should build an operation with the parameter names as args', function (done) {
var builder = new RequestBuilder('POST', 'http://localhost:3000/{p}').query({x: '{x}', y: 2});
var fn = builder.operation('p', 'x');
fn(1, 'X',
function (err, body, response) {
assert.equal(200, response.statusCode);
if (typeof body === 'string') {
body = JSON.parse(body);
}
// console.log(body);
assert.equal(0, body.url.indexOf('/1'));
assert.equal('X', body.query.x);
assert.equal(2, body.query.y);
// console.log(body);
done(err, body);
});
});
it('should build from a json doc', function (done) {
var builder = new RequestBuilder(require('./request-template.json'));
// console.log(builder.parse());
builder.invoke({p: 1, a: 100, b: false},
function (err, body, response) {
// console.log(response.headers);
assert.equal(200, response.statusCode);
if (typeof body === 'string') {
body = JSON.parse(body);
}
// console.log(body);
assert.equal(0, body.url.indexOf('/1'));
assert.equal(100, body.query.x);
assert.equal(2, body.query.y);
assert.equal(100, body.body.a);
assert.equal(false, body.body.b);
done(err, body);
});
});
});
}); | sunyardtc/git | node_modules/loopback-connector-rest/test/rest-builder.test.js | JavaScript | mit | 8,351 |
/**
* Copyright 2015 aixigo AG
* Released under the MIT license.
* http://laxarjs.org/license
*/
require( [
'laxar',
'laxar-application/var/flows/embed/dependencies',
'json!laxar-application/var/flows/embed/resources.json'
], function( ax, mainDependencies, mainResources ) {
'use strict';
window.laxar.fileListings = {
application: mainResources,
bower_components: mainResources,
includes: mainResources
};
ax.bootstrap( mainDependencies );
} );
| jpommerening/release-station | init-embed.js | JavaScript | mit | 490 |
import React from 'react';
import Tap from '../hahoo/Tap';
class BtnUpLevel extends React.Component {
static propTypes = {
onItemClick: React.PropTypes.func
}
state = {}
render() {
const { onItemClick, ...rest } = this.props;
return (<Tap
onTap={onItemClick}
className="btn btn-default"
{...rest}
><i className="fa fa-arrow-circle-up fa-fw" /> 上级</Tap>);
}
}
export default BtnUpLevel;
| hahoocn/hahoo-admin | src/components/Btns/BtnUpLevel.js | JavaScript | mit | 439 |
"use strict";Object.defineProperty(exports, "__esModule", { value: true });exports.default = void 0;
var _graphqlRelay = require("graphql-relay");
var _EnsayoType = _interopRequireDefault(require("./EnsayoType"));function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { default: obj };}var _default =
(0, _graphqlRelay.connectionDefinitions)({
name: 'Ensayos',
nodeType: _EnsayoType.default });exports.default = _default;
//# sourceMappingURL=EnsayosConnection.js.map | codefoundries/UniversalRelayBoilerplate | deployment/units/rb-example-ensayo-server/graphql/type/EnsayosConnection.js | JavaScript | mit | 494 |
/**
* @author Phuluong
* Feb 13, 2016
*/
/** Exports **/
module.exports = new Config();
/** Imports **/
var fs = require("fs");
var util = require(__dir + '/core/app/util');
/** Modules **/
function Config() {
var configContainer = {};
/**
* Get config value by key
* @param {String} key
* @param {} defaultValue
* @returns {}
*/
this.get = function (key, defaultValue) {
var retval = defaultValue;
if (configContainer[key] != null) {
retval = configContainer[key];
} else {
key = key.replaceAll(".", "/");
var path = __dir + "/config/" + key;
var parentPath = path.substring(0, path.lastIndexOf("/"));
try {
var property = path.substring(path.lastIndexOf("/") + 1, path.length);
if (fs.existsSync(path + ".js")) {
retval = require(path);
} else if (fs.existsSync(parentPath + ".js")) {
if ((require(parentPath))[property] != null) {
retval = (require(parentPath))[property];
}
} else if (key.indexOf("package") == 0) {
retval = (require(__dir + "/package.json"))[property];
}
configContainer[key] = retval;
} catch (exc) {
}
}
if (retval == null) {
}
return retval;
};
/**
* Set config value
* @param {String} key
* @param {} value
*/
this.set = function (key, value) {
configContainer[key] = value;
};
}
| phult/adu | framework/core/app/config.js | JavaScript | mit | 1,664 |
/* jshint node: true */
module.exports = function(environment) {
var ENV = {
modulePrefix: 'addressbook-app',
environment: environment,
baseURL: '/',
locationType: 'auto',
emberPouch: {
localDb: 'dentone-addressbook',
remoteDb: 'https://wasilleptichandfurningio:6c01f93f266bb3cf6dfd579de0e8e51354ee3bf3@dentone.cloudant.com/addressbook/'
},
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
}
},
contentSecurityPolicy:{
'default-src': "'none'",
'script-src': "'self' 'unsafe-inline'",
'style-src': "'self' 'unsafe-inline' https://fonts.googleapis.com",
'font-src': "'self' fonts.gstatic.com",
'connect-src': "'self' https://dentone.cloudant.com/",
'img-src': "'self' data:",
'media-src': "'self'"
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
}
};
if (environment === 'development') {
// ENV.APP.LOG_RESOLVER = true;
// ENV.APP.LOG_ACTIVE_GENERATION = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
// ENV.APP.LOG_VIEW_LOOKUPS = true;
}
if (environment === 'test') {
// Testem prefers this...
ENV.baseURL = '/';
ENV.locationType = 'none';
// keep test console output quieter
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
}
if (environment === 'production') {
}
return ENV;
};
| adentone/addressbook-app | config/environment.js | JavaScript | mit | 1,639 |
/* global describe, before, it */
require('mocha')
require('should')
var async = require('async')
var testUtils = require('./testUtils')
var errorMessage = require('../errorMessages/errorMessages')
var mongo_dcms_core = require('../index')
describe('should get file Content by file id', function () {
var filepath = './test/testAsset/testTextFile.txt'
var savedFileId
var document = {
filePath: filepath,
fileName: 'testTextFile.txt',
contentType: 'binary/octet-stream',
identityMetaData: {
projectId: 10
}
}
before(function (done) {
this.timeout(5000)
async.series([
function (callback) {
testUtils.clearDb(callback)
},
function (callback) {
mongo_dcms_core.connect(testUtils.dbUrl)
mongo_dcms_core.uploadFile(document, {}, function (err, sucess) {
if (err) {
callback(err)
} else {
savedFileId = sucess.fileId
callback(null)
}
})
}
], done)
})
it('should get file Content by file id', function (done) {
mongo_dcms_core.getFileContentByFileId(savedFileId, function (err, sucess) {
if (err) {
err.should.equal(null)
done()
} else {
sucess.fileData.should.not.equal(null)
sucess.contentType.should.equal('binary/octet-stream')
sucess.fileName.should.equal('testTextFile.txt')
sucess.fileMetaData.should.not.equal(null)
sucess.fileMetaData.should.not.equal(undefined)
done()
}
})
})
it('should return message file not found', function (done) {
mongo_dcms_core.getFileContentByFileId('56f0dc0ca80f6cc01929cd1e', function (err, sucess) {
if (err) {
err.should.equal(errorMessage.fileNotFoundForSpecifiedFileId)
done()
} else {
sucess.should.equal(null)
done()
}
})
})
})
| RaykorTech/mongo-dcms-core | test/content.js | JavaScript | mit | 1,897 |
/**
* Lawnchair!
* ---
* clientside json store
*
*/
var Lawnchair = function () {
// lawnchair requires json
if (!JSON) throw 'JSON unavailable! Include http://www.json.org/json2.js to fix.'
// options are optional; callback is not
if (arguments.length <= 2 && arguments.length > 0) {
var callback = (typeof arguments[0] === 'function') ? arguments[0] : arguments[1]
, options = (typeof arguments[0] === 'function') ? {} : arguments[0]
} else {
throw 'Incorrect # of ctor args!'
}
if (typeof callback !== 'function') throw 'No callback was provided';
// default configuration
this.record = options.record || 'record' // default for records
this.name = options.name || 'records' // default name for underlying store
// mixin first valid adapter
var adapter
// if the adapter is passed in we try to load that only
if (options.adapter) {
adapter = Lawnchair.adapters[Lawnchair.adapters.indexOf(options.adapter)]
adapter = adapter.valid() ? adapter : undefined
// otherwise find the first valid adapter for this env
} else {
for (var i = 0, l = Lawnchair.adapters.length; i < l; i++) {
adapter = Lawnchair.adapters[i].valid() ? Lawnchair.adapters[i] : undefined
if (adapter) break
}
}
// we have failed
if (!adapter) throw 'No valid adapter.'
// yay! mixin the adapter
for (var j in adapter) {
this[j] = adapter[j]
}
// call init for each mixed in plugin
for (var i = 0, l = Lawnchair.plugins.length; i < l; i++)
Lawnchair.plugins[i].call(this)
// init the adapter
this.init(options, callback)
}
Lawnchair.adapters = []
/**
* queues an adapter for mixin
* ===
* - ensures an adapter conforms to a specific interface
*
*/
Lawnchair.adapter = function (id, obj) {
// add the adapter id to the adapter obj
// ugly here for a cleaner dsl for implementing adapters
obj['adapter'] = id
// methods required to implement a lawnchair adapter
var implementing = 'adapter valid init keys save batch get exists all remove nuke'.split(' ')
// mix in the adapter
for (var i in obj) if (implementing.indexOf(i) === -1) throw 'Invalid adapter! Nonstandard method: ' + i
// if we made it this far the adapter interface is valid
Lawnchair.adapters.push(obj)
}
Lawnchair.plugins = []
/**
* generic shallow extension for plugins
* ===
* - if an init method is found it registers it to be called when the lawnchair is inited
* - yes we could use hasOwnProp but nobody here is an asshole
*/
Lawnchair.plugin = function (obj) {
for (var i in obj)
i === 'init' ? Lawnchair.plugins.push(obj[i]) : this.prototype[i] = obj[i]
}
/**
* helpers
*
*/
Lawnchair.prototype = {
isArray: Array.isArray || function(o) { return Object.prototype.toString.call(o) === '[object Array]' },
// awesome shorthand callbacks as strings. this is shameless theft from dojo.
lambda: function (callback) {
return this.fn(this.record, callback)
},
// first stab at named parameters for terse callbacks; dojo: first != best // ;D
fn: function (name, callback) {
return typeof callback == 'string' ? new Function(name, callback) : callback
},
// returns a unique identifier (by way of Backbone.localStorage.js)
// TODO investigate smaller UUIDs to cut on storage cost
uuid: function () {
var S4 = function () {
return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
}
return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
},
// a classic iterator
each: function (callback) {
var cb = this.lambda(callback)
// iterate from chain
if (this.__results) {
for (var i = 0, l = this.__results.length; i < l; i++) cb.call(this, this.__results[i], i)
}
// otherwise iterate the entire collection
else {
this.all(function(r) {
for (var i = 0, l = r.length; i < l; i++) cb.call(this, r[i], i)
})
}
return this
}
// --
};
Lawnchair.adapter('webkit-sqlite', (function () {
// private methods
var fail = function (e, i) { console.log('error in sqlite adaptor!', e, i) }
, now = function () { return new Date() } // FIXME need to use better date fn
// not entirely sure if this is needed...
if (!Function.prototype.bind) {
Function.prototype.bind = function( obj ) {
var slice = [].slice
, args = slice.call(arguments, 1)
, self = this
, nop = function () {}
, bound = function () {
return self.apply(this instanceof nop ? this : (obj || {}), args.concat(slice.call(arguments)))
}
nop.prototype = self.prototype
bound.prototype = new nop()
return bound
}
}
// public methods
return {
valid: function() { return !!(window.openDatabase) },
init: function (options, callback) {
var that = this
, cb = that.fn(that.name, callback)
, create = "CREATE TABLE IF NOT EXISTS " + this.name + " (id NVARCHAR(32) UNIQUE PRIMARY KEY, value TEXT, timestamp REAL)"
, win = cb.bind(this)
// open a connection and create the db if it doesn't exist
this.db = openDatabase(this.name, '1.0.0', this.name, 65536)
this.db.transaction(function (t) {
t.executeSql(create, [], win, fail)
})
},
keys: function (callback) {
var cb = this.lambda(callback)
, that = this
, keys = "SELECT id FROM " + this.name + " ORDER BY timestamp DESC"
this.db.transaction(function(t) {
var win = function (xxx, results) {
if (results.rows.length == 0 ) {
cb.call(that, [])
} else {
var r = [];
for (var i = 0, l = results.rows.length; i < l; i++) {
r.push(results.rows.item(i).id);
}
cb.call(that, r)
}
}
t.executeSql(keys, [], win, fail)
})
return this
},
// you think thats air you're breathing now?
save: function (obj, callback) {
var that = this
, id = obj.key || that.uuid()
, ins = "INSERT INTO " + this.name + " (value, timestamp, id) VALUES (?,?,?)"
, up = "UPDATE " + this.name + " SET value=?, timestamp=? WHERE id=?"
, win = function () { if (callback) { obj.key = id; that.lambda(callback).call(that, obj) }}
, val = [now(), id]
// existential
that.exists(obj.key, function(exists) {
// transactions are like condoms
that.db.transaction(function(t) {
// TODO move timestamp to a plugin
var insert = function (obj) {
val.unshift(JSON.stringify(obj))
t.executeSql(ins, val, win, fail)
}
// TODO move timestamp to a plugin
var update = function (obj) {
delete(obj.key)
val.unshift(JSON.stringify(obj))
t.executeSql(up, val, win, fail)
}
// pretty
exists ? update(obj) : insert(obj)
})
});
return this
},
// FIXME this should be a batch insert / just getting the test to pass...
batch: function (objs, cb) {
var results = []
, done = false
, that = this
var updateProgress = function(obj) {
results.push(obj)
done = results.length === objs.length
}
var checkProgress = setInterval(function() {
if (done) {
if (cb) that.lambda(cb).call(that, results)
clearInterval(checkProgress)
}
}, 200)
for (var i = 0, l = objs.length; i < l; i++)
this.save(objs[i], updateProgress)
return this
},
get: function (keyOrArray, cb) {
var that = this
, sql = ''
// batch selects support
if (this.isArray(keyOrArray)) {
sql = 'SELECT id, value FROM ' + this.name + " WHERE id IN ('" + keyOrArray.join("','") + "')"
} else {
sql = 'SELECT id, value FROM ' + this.name + " WHERE id = '" + keyOrArray + "'"
}
// FIXME
// will always loop the results but cleans it up if not a batch return at the end..
// in other words, this could be faster
var win = function (xxx, results) {
var o = null
, r = []
if (results.rows.length) {
for (var i = 0, l = results.rows.length; i < l; i++) {
o = JSON.parse(results.rows.item(i).value)
o.key = results.rows.item(i).id
r.push(o)
}
}
if (!that.isArray(keyOrArray)) r = r.length ? r[0] : null
if (cb) that.lambda(cb).call(that, r)
}
this.db.transaction(function(t){ t.executeSql(sql, [], win, fail) })
return this
},
exists: function (key, cb) {
var is = "SELECT * FROM " + this.name + " WHERE id = ?"
, that = this
, win = function(xxx, results) { if (cb) that.fn('exists', cb).call(that, (results.rows.length > 0)) }
this.db.transaction(function(t){ t.executeSql(is, [key], win, fail) })
return this
},
all: function (callback) {
var that = this
, all = "SELECT * FROM " + this.name
, r = []
, cb = this.fn(this.name, callback) || undefined
, win = function (xxx, results) {
if (results.rows.length != 0) {
for (var i = 0, l = results.rows.length; i < l; i++) {
var obj = JSON.parse(results.rows.item(i).value)
obj.key = results.rows.item(i).id
r.push(obj)
}
}
if (cb) cb.call(that, r)
}
this.db.transaction(function (t) {
t.executeSql(all, [], win, fail)
})
return this
},
remove: function (keyOrObj, cb) {
var that = this
, key = typeof keyOrObj === 'string' ? keyOrObj : keyOrObj.key
, del = "DELETE FROM " + this.name + " WHERE id = ?"
, win = function () { if (cb) that.lambda(cb).call(that) }
this.db.transaction( function (t) {
t.executeSql(del, [key], win, fail);
});
return this;
},
nuke: function (cb) {
var nuke = "DELETE FROM " + this.name
, that = this
, win = cb ? function() { that.lambda(cb).call(that) } : function(){}
this.db.transaction(function (t) {
t.executeSql(nuke, [], win, fail)
})
return this
}
//////
}})())
| d2s/lawnchair | test/lib/lawnchair.js | JavaScript | mit | 10,887 |
(function(){function h(a){return function(){return this[a]}}var k=this;function n(a){return"string"==typeof a}function p(a,c){var b=a.split("."),d=k;!(b[0]in d)&&d.execScript&&d.execScript("var "+b[0]);for(var e;b.length&&(e=b.shift());)!b.length&&void 0!==c?d[e]=c:d=d[e]?d[e]:d[e]={}};var q="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");function s(a){var c=Number(a);return 0==c&&/^[\s\xa0]*$/.test(a)?NaN:c};function t(a,c){this.b=a|0;this.a=c|0}var v={};function w(a){if(-128<=a&&128>a){var c=v[a];if(c)return c}c=new t(a|0,0>a?-1:0);-128<=a&&128>a&&(v[a]=c);return c}function x(a){return isNaN(a)||!isFinite(a)?y:a<=-z?A:a+1>=z?aa:0>a?B(x(-a)):new t(a%C|0,a/C|0)}
function D(a,c){if(0==a.length)throw Error("number format error: empty string");var b=c||10;if(2>b||36<b)throw Error("radix out of range: "+b);if("-"==a.charAt(0))return B(D(a.substring(1),b));if(0<=a.indexOf("-"))throw Error('number format error: interior "-" character: '+a);for(var d=x(Math.pow(b,8)),e=y,f=0;f<a.length;f+=8){var g=Math.min(8,a.length-f),m=parseInt(a.substring(f,f+g),b);8>g?(g=x(Math.pow(b,g)),e=e.multiply(g).add(x(m))):(e=e.multiply(d),e=e.add(x(m)))}return e}
var C=4294967296,z=C*C/2,y=w(0),E=w(1),F=w(-1),aa=new t(-1,2147483647),A=new t(0,-2147483648),G=w(16777216);
t.prototype.toString=function(a){a=a||10;if(2>a||36<a)throw Error("radix out of range: "+a);if(H(this))return"0";if(0>this.a){if(I(this,A)){var c=x(a),b=J(this,c),c=L(b.multiply(c),this);return b.toString(a)+c.b.toString(a)}return"-"+B(this).toString(a)}for(var b=x(Math.pow(a,6)),c=this,d="";;){var e=J(c,b),f=L(c,e.multiply(b)).b.toString(a),c=e;if(H(c))return f+d;for(;6>f.length;)f="0"+f;d=""+f+d}};function M(a){return 0<=a.b?a.b:C+a.b}function H(a){return 0==a.a&&0==a.b}
function I(a,c){return a.a==c.a&&a.b==c.b}function N(a,c){if(I(a,c))return 0;var b=0>a.a,d=0>c.a;return b&&!d?-1:!b&&d?1:0>L(a,c).a?-1:1}function B(a){return I(a,A)?A:(new t(~a.b,~a.a)).add(E)}t.prototype.add=function(a){var c=this.a>>>16,b=this.a&65535,d=this.b>>>16,e=a.a>>>16,f=a.a&65535,g=a.b>>>16,m;m=0+((this.b&65535)+(a.b&65535));a=0+(m>>>16);a+=d+g;d=0+(a>>>16);d+=b+f;b=0+(d>>>16);b=b+(c+e)&65535;return new t((a&65535)<<16|m&65535,b<<16|d&65535)};function L(a,c){return a.add(B(c))}
t.prototype.multiply=function(a){if(H(this)||H(a))return y;if(I(this,A))return 1==(a.b&1)?A:y;if(I(a,A))return 1==(this.b&1)?A:y;if(0>this.a)return 0>a.a?B(this).multiply(B(a)):B(B(this).multiply(a));if(0>a.a)return B(this.multiply(B(a)));if(0>N(this,G)&&0>N(a,G))return x((this.a*C+M(this))*(a.a*C+M(a)));var c=this.a>>>16,b=this.a&65535,d=this.b>>>16,e=this.b&65535,f=a.a>>>16,g=a.a&65535,m=a.b>>>16;a=a.b&65535;var u,l,r,K;K=0+e*a;r=0+(K>>>16);r+=d*a;l=0+(r>>>16);r=(r&65535)+e*m;l+=r>>>16;r&=65535;
l+=b*a;u=0+(l>>>16);l=(l&65535)+d*m;u+=l>>>16;l&=65535;l+=e*g;u+=l>>>16;l&=65535;u=u+(c*a+b*m+d*g+e*f)&65535;return new t(r<<16|K&65535,u<<16|l)};
function J(a,c){if(H(c))throw Error("division by zero");if(H(a))return y;if(I(a,A)){if(I(c,E)||I(c,F))return A;if(I(c,A))return E;var b;b=1;if(0==b)b=a;else{var d=a.a;b=32>b?new t(a.b>>>b|d<<32-b,d>>b):new t(d>>b-32,0<=d?0:-1)}b=J(b,c).shiftLeft(1);if(I(b,y))return 0>c.a?E:F;d=L(a,c.multiply(b));return b.add(J(d,c))}if(I(c,A))return y;if(0>a.a)return 0>c.a?J(B(a),B(c)):B(J(B(a),c));if(0>c.a)return B(J(a,B(c)));for(var e=y,d=a;0<=N(d,c);){b=Math.max(1,Math.floor((d.a*C+M(d))/(c.a*C+M(c))));for(var f=
Math.ceil(Math.log(b)/Math.LN2),f=48>=f?1:Math.pow(2,f-48),g=x(b),m=g.multiply(c);0>m.a||0<N(m,d);)b-=f,g=x(b),m=g.multiply(c);H(g)&&(g=E);e=e.add(g);d=L(d,m)}return e}t.prototype.shiftLeft=function(a){a&=63;if(0==a)return this;var c=this.b;return 32>a?new t(c<<a,this.a<<a|c>>>32-a):new t(0,c<<a-32)};var O=Array.prototype,P=O.forEach?function(a,c,b){O.forEach.call(a,c,b)}:function(a,c,b){for(var d=a.length,e=n(a)?a.split(""):a,f=0;f<d;f++)f in e&&c.call(b,e[f],f,a)},Q=O.map?function(a,c,b){return O.map.call(a,c,b)}:function(a,c,b){for(var d=a.length,e=Array(d),f=n(a)?a.split(""):a,g=0;g<d;g++)g in f&&(e[g]=c.call(b,f[g],g,a));return e};function R(a,c,b){if(a.reduce)return a.reduce(c,b);var d=b;P(a,function(b,f){d=c.call(void 0,d,b,f,a)});return d}
function S(a,c,b){return 2>=arguments.length?O.slice.call(a,c):O.slice.call(a,c,b)};function T(a){return U(1,arguments,function(a,b){return a.add(b)})}function V(a,c){var b=W(2,[a,c]).d;return X(b[0]/b[1])}function Y(a){return U(3,arguments,function(a,b){return L(a,b)})}function Z(a){return U(4,arguments,function(a,b){return a.multiply(b)})}
function $(a){if("number"==typeof a)return a;var c=a.toString(),b=a.c;if(0!=b){var d;a=!1;"-"==c.charAt(0)&&(a=!0,c=c.replace(/^\-/,""));c.length<=b?(c=String(s(c)),d=c.indexOf("."),-1==d&&(d=c.length),b=Math.max(0,b-d),d=Array(b+1).join("0")+c,b="0"):(d=c.slice(-b),b=c.slice(0,-b));c=(a?"-":"")+b+"."+d}return s(c)}function U(a,c,b){c=W(a,c);b=R(S(c.d,1),b,c.d[0]);b.k(a,c.d.length,c.i);return b}
function X(a){if(!n(a)&&"number"!=typeof a)throw Error('Invalid value: "'+a+'"');a=s(String(a));var c=String(a),b,d;if(d=c.match(/\.(\d+)$/)){b=D;var e=RegExp,f;f=".".replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g,"\\$1").replace(/\x08/g,"\\x08");e=e(f,"");c=c.replace(e,"");b=b(c);b.e(a,d[1].length)}else b=D(c),b.e(a);return b}
function W(a,c){c=Q(c,function(a){return a instanceof t?a:X(a)});if(4==a){var b=R(c,function(a,b){return a+b.c},0);return{d:c,i:b}}var d=Math.max.apply(null,Q(c,function(a){return a.c}));if(0!=d){var e,f;c=Q(c,function(a){e=d-a.c;return 0!=e?(f=a.multiply(x(Math.pow(10,e))),f.j(a),f):a})}return{d:c,i:d}}
(function(a,c){for(var b,d,e=1;e<arguments.length;e++){d=arguments[e];for(b in d)a[b]=d[b];for(var f=0;f<q.length;f++)b=q[f],Object.prototype.hasOwnProperty.call(d,b)&&(a[b]=d[b])}})(t.prototype,{f:void 0,c:0,h:null,g:0,k:function(a,c,b){this.h=a;this.g=c;this.c=b},n:h("h"),m:h("g"),e:function(a,c){a&&(this.f=a);this.c=c||0},j:function(a){this.e(a.f,a.c)},p:h("f"),o:h("c"),l:function(){return 0!=this.c}});
p("sao.calc",function(a){var c,b=[],d=[];P(arguments,function(a){n(a)&&/^\+|\-|\*|\/$/.test(a)?b[b.length]=a:d[d.length]=a});c=R(S(d,1),function(a,c){switch(b.shift()){case "+":return T(a,c);case "-":return Y(a,c);case "/":return V(a,c);case "*":return Z(a,c)}},d[0]);return $(c)});p("sao.add",T);p("sao.div",V);p("sao.sub",Y);p("sao.mul",Z);p("sao.finalize",$);
p("sao.round",function(a,c){var b="number"==typeof a?X(a):a,d=b.toString().replace(/^\-/,""),e=c||0;if(b.l()&&!(b.c<=e)){var f=b.c,d=d.charAt(d.length-f+e),b=X(b.toString().slice(0,-(f-e)));b.e(void 0,e);4<s(d)?(e=x(1),e=0>b.a?B(e):e,e=b.add(e),e.j(b)):e=b;return $(e)}return $(b)});})()
| matsukei/sao.js | sao.js | JavaScript | mit | 6,640 |
/**
* drcProcess
* Created by dcorns on 1/2/15.
*/
'use strict';
var RunApp = require('./runApp');
var Server = require('./server');
var parseInput = require('./parseInput');
var CommandList = require('./commandList');
var runApp = new RunApp();
var cmds = new CommandList();
cmds.add(['ls', 'pwd', 'service', 'ps']);
var firstServer = new Server('firstServer');
firstServer.start(3000, function(err, cnn){
cnn.on('data', function(data){
parseInput(data, function(err, obj){
if(err) cnn.write(err);
else {
if(obj.cmd.substr(0, 6) === 'login:'){
cnn.loginID = obj.cmd.substr(6);
cnn.write('Welcome ' + cnn.loginID + '\r\n');
cnn.write('Valid Commands: ' + cmds.listCommands() + '\r\n');
cnn.write('Use # to add parameters: example: ls#/\r\n');
cnn.write('Use - to add options: example: ls#/ -al or ls#-al\r\n');
console.log(cnn.loginID + ' connected');
}
else {
if(cmds.validate(obj.cmd) > -1){
runApp.run(obj.params, cnn, obj.cmd);
}
else{
cnn.write('Valid commands: ' + cmds.listCommands());
}
}
}
});
});
});
| dcorns/processThis | drcProcess.js | JavaScript | mit | 1,200 |
"use strict";
const tester = require("./framework");
const repeatAsyncUntil = require("../source/regularly");
module.exports = tester.run([
tester.make("repeatAsyncUntil() should repeat calls to λ while predicate returns false", async () => {
let executionsCount = 0;
const λ = async () => ++executionsCount;
const predicate = async () => executionsCount === 2;
await repeatAsyncUntil(λ, predicate);
return executionsCount === 2;
})
]);
| tentwentyfour/helpbox | tests/repeat-async-until-tests.js | JavaScript | mit | 511 |
import {ATTACHMENTS} from "../constants";
export default (...args) => {
// Use one or the other
const attachments = args.length ? args : ATTACHMENTS;
return {
props: {
attach: {
type: String,
validator: value => value === "" || attachments.includes(value)
}
},
computed: {
getAttach() {
if(typeof this.attach === "string") {
return this.attach ? `${this.attach} attached` : "attached";
}
}
}
};
}; | iFaxity/Semantic-UI-Vue | src/mixins/attach.js | JavaScript | mit | 489 |
'use strict';
module.exports = Source;
const inherits = require('util').inherits;
const Stream = require('../stream');
const Chunk = require('../chunk');
const Compose = require('../through/compose');
const Break = require('../through/break');
const Filter = require('../through/filter');
const Map = require('../through/map');
const Take = require('../through/take');
const Each = require('../feed/each');
const Value = require('../feed/value');
module.exports = Source;
inherits(Source, Stream);
function Source(){
Stream.call(this);
this.async = false;
}
Source.prototype.iterator = function iterator() {
return new this.constructor.Iterator(this);
};
Source.prototype.pipe = function pipe(feed) {
return feed.feed([this]);
};
Source.prototype.break = function breake(fn, async){
return this.pipe(new Break(fn, async));
};
Source.prototype.filter = function filter(fn, async){
return this.pipe(new Filter(fn, async));
};
Source.prototype.map = function map(fn, async){
return this.pipe(new Map(fn, async));
};
Source.prototype.take = function take(max){
return this.pipe(new Take(max));
};
Source.prototype.each = function each(fn){
return this.pipe(new Each(fn));
};
Source.prototype.value = function value(async){
return this.pipe(new Value(async));
};
| shishidosoichiro/lazy | src/source/source.js | JavaScript | mit | 1,283 |
// Idea and initial code from https://github.com/aomra015/ember-cli-chart
import Ember from 'ember';
export default Ember.Component.extend({
tagName: 'canvas',
attributeBindings: ['width', 'height'],
onlyValues: false,
chartData: {},
didInsertElement: function(){
var context = this.get('element').getContext('2d');
var type = Ember.String.classify(this.get('type'));
var options = {
responsive: true,
showTooltips: true,
pointDot: true,
pointDotRadius: 3,
pointHitDetectionRadius: 8,
bezierCurve: false,
barValueSpacing: 1,
datasetStrokeWidth: 3
};
// animation is very sexy, but it hogs browser. Waiting for chart.js 2.0
// https://github.com/nnnick/Chart.js/issues/653
options.animation = false;
if (this.get("onlyValues")) {
options.showScale = false;
}
var data = {labels: [], datasets: []};
this.get("chartData.labels").forEach((l) => {
data.labels.push(l);
});
this.get("chartData.datasets").forEach((ds) => {
var dataSet = this._chartColors(ds.label);
dataSet.data = ds.data.map((v) => { return v; });
data.datasets.push(dataSet);
});
var chart = new Chart(context)[type](data, options);
this.set('chart', chart);
},
willDestroyElement: function(){
this.get('chart').destroy();
},
updateChart: function() {
//// redraw
// this.willDestroyElement();
// this.didInsertElement();
var chart = this.get("chart");
while (chart.scale.xLabels.length && chart.scale.xLabels[0] !== this.get("chartData.labels")[0]) {
chart.removeData();
}
this.get("chartData.labels").forEach((label, i) => {
if (i < chart.scale.xLabels.length) {
this.get("chartData.datasets").forEach((ds, j) => {
if (this.get("type") === "Line") {
chart.datasets[j].points[i].value = ds.data[i];
} else {
chart.datasets[j].bars[i].value = ds.data[i];
}
});
} else {
var values = [];
this.get("chartData.datasets").forEach((ds) => {
values.push(ds.data[i]);
});
chart.addData(values, label);
}
});
chart.update();
}.observes("chartData", "chartData.[]"),
_chartColors: function(label) {
if (label === "count") {
return {
fillColor: "rgba(151,187,205,1)",
strokeColor: "rgba(151,187,205,1)"
};
} else {
var base = {
max: "203,46,255",
up: "46,255,203",
avg: "46,203,255",
min: "46,98,255",
sum: "98,56,255",
}[label] || "151,187,205";
return {
fillColor: "rgba(" + base + ",0.03)",
strokeColor: "rgba(" + base + ",0.5)",
pointColor: "rgba(" + base + ",0.5)",
// pointStrokeColor: "red", //"rgba(" + base + ")",
// pointHighlightFill: "green", //"rgba(" + base + ")",
// pointHighlightStroke: "blue",// "rgba(" + base + ")",
// pointStrokeColor: "#fff",
// pointHighlightFill: "#fff",
// pointHighlightStroke: "rgba(220,220,220,1)",
};
}
}
});
| snowman-io/snowman-io | ui/app/components/ember-chart.js | JavaScript | mit | 3,145 |
/*
* Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global define, $, CodeMirror, window */
/**
* Editor is a 1-to-1 wrapper for a CodeMirror editor instance. It layers on Brackets-specific
* functionality and provides APIs that cleanly pass through the bits of CodeMirror that the rest
* of our codebase may want to interact with. An Editor is always backed by a Document, and stays
* in sync with its content; because Editor keeps the Document alive, it's important to always
* destroy() an Editor that's going away so it can release its Document ref.
*
* For now, there's a distinction between the "master" Editor for a Document - which secretly acts
* as the Document's internal model of the text state - and the multitude of "slave" secondary Editors
* which, via Document, sync their changes to and from that master.
*
* For now, direct access to the underlying CodeMirror object is still possible via _codeMirror --
* but this is considered deprecated and may go away.
*
* The Editor object dispatches the following events:
* - keyEvent -- When any key event happens in the editor (whether it changes the text or not).
* Event handlers are passed ({Editor}, {KeyboardEvent}). The 2nd arg is the raw DOM event.
* Note: most listeners will only want to respond when event.type === "keypress".
* - cursorActivity -- When the user moves the cursor or changes the selection, or an edit occurs.
* Note: do not listen to this in order to be generally informed of edits--listen to the
* "change" event on Document instead.
* - scroll -- When the editor is scrolled, either by user action or programmatically.
* - lostContent -- When the backing Document changes in such a way that this Editor is no longer
* able to display accurate text. This occurs if the Document's file is deleted, or in certain
* Document->editor syncing edge cases that we do not yet support (the latter cause will
* eventually go away).
*
* The Editor also dispatches "change" events internally, but you should listen for those on
* Documents, not Editors.
*
* These are jQuery events, so to listen for them you do something like this:
* $(editorInstance).on("eventname", handler);
*/
define(function (require, exports, module) {
"use strict";
var EditorManager = require("editor/EditorManager"),
CodeHintManager = require("editor/CodeHintManager"),
Commands = require("command/Commands"),
CommandManager = require("command/CommandManager"),
Menus = require("command/Menus"),
PerfUtils = require("utils/PerfUtils"),
PreferencesManager = require("preferences/PreferencesManager"),
Strings = require("strings"),
TextRange = require("document/TextRange").TextRange,
ViewUtils = require("utils/ViewUtils");
var PREFERENCES_CLIENT_ID = "com.adobe.brackets.Editor",
defaultPrefs = { useTabChar: false, tabSize: 4, indentUnit: 4 };
/** Editor preferences */
var _prefs = PreferencesManager.getPreferenceStorage(PREFERENCES_CLIENT_ID, defaultPrefs);
/** @type {boolean} Global setting: When inserting new text, use tab characters? (instead of spaces) */
var _useTabChar = _prefs.getValue("useTabChar");
/** @type {boolean} Global setting: Tab size */
var _tabSize = _prefs.getValue("tabSize");
/** @type {boolean} Global setting: Indent unit (i.e. number of spaces when indenting) */
var _indentUnit = _prefs.getValue("indentUnit");
/**
* @private
* Handle Tab key press.
* @param {!CodeMirror} instance CodeMirror instance.
*/
function _handleTabKey(instance) {
// Tab key handling is done as follows:
// 1. If the selection is before any text and the indentation is to the left of
// the proper indentation then indent it to the proper place. Otherwise,
// add another tab. In either case, move the insertion point to the
// beginning of the text.
// 2. If the selection is after the first non-space character, and is not an
// insertion point, indent the entire line(s).
// 3. If the selection is after the first non-space character, and is an
// insertion point, insert a tab character or the appropriate number
// of spaces to pad to the nearest tab boundary.
var from = instance.getCursor(true),
to = instance.getCursor(false),
line = instance.getLine(from.line),
indentAuto = false,
insertTab = false;
if (from.line === to.line) {
if (line.search(/\S/) > to.ch || to.ch === 0) {
indentAuto = true;
}
}
if (indentAuto) {
var currentLength = line.length;
CodeMirror.commands.indentAuto(instance);
// If the amount of whitespace didn't change, insert another tab
if (instance.getLine(from.line).length === currentLength) {
insertTab = true;
to.ch = 0;
}
} else if (instance.somethingSelected()) {
CodeMirror.commands.indentMore(instance);
} else {
insertTab = true;
}
if (insertTab) {
if (instance.getOption("indentWithTabs")) {
CodeMirror.commands.insertTab(instance);
} else {
var i, ins = "", numSpaces = _indentUnit;
numSpaces -= to.ch % numSpaces;
for (i = 0; i < numSpaces; i++) {
ins += " ";
}
instance.replaceSelection(ins, "end");
}
}
}
/**
* @private
* Handle left arrow, right arrow, backspace and delete keys when soft tabs are used.
* @param {!CodeMirror} instance CodeMirror instance
* @param {number} direction Direction of movement: 1 for forward, -1 for backward
* @param {function} functionName name of the CodeMirror function to call
* @return {boolean} true if key was handled
*/
function _handleSoftTabNavigation(instance, direction, functionName) {
var handled = false;
if (!instance.getOption("indentWithTabs")) {
var cursor = instance.getCursor(),
jump = cursor.ch % _indentUnit,
line = instance.getLine(cursor.line);
if (direction === 1) {
jump = _indentUnit - jump;
if (cursor.ch + jump > line.length) { // Jump would go beyond current line
return false;
}
if (line.substr(cursor.ch, jump).search(/\S/) === -1) {
instance[functionName](jump, "char");
handled = true;
}
} else {
// Quick exit if we are at the beginning of the line
if (cursor.ch === 0) {
return false;
}
// If we are on the tab boundary, jump by the full amount,
// but not beyond the start of the line.
if (jump === 0) {
jump = _indentUnit;
}
// Search backwards to the first non-space character
var offset = line.substr(cursor.ch - jump, jump).search(/\s*$/g);
if (offset !== -1) { // Adjust to jump to first non-space character
jump -= offset;
}
if (jump > 0) {
instance[functionName](-jump, "char");
handled = true;
}
}
}
return handled;
}
/**
* Checks if the user just typed a closing brace/bracket/paren, and considers automatically
* back-indenting it if so.
*/
function _checkElectricChars(jqEvent, editor, event) {
var instance = editor._codeMirror;
if (event.type === "keypress") {
var keyStr = String.fromCharCode(event.which || event.keyCode);
if (/[\]\{\}\)]/.test(keyStr)) {
// If all text before the cursor is whitespace, auto-indent it
var cursor = instance.getCursor();
var lineStr = instance.getLine(cursor.line);
var nonWS = lineStr.search(/\S/);
if (nonWS === -1 || nonWS >= cursor.ch) {
// Need to do the auto-indent on a timeout to ensure
// the keypress is handled before auto-indenting.
// This is the same timeout value used by the
// electricChars feature in CodeMirror.
window.setTimeout(function () {
instance.indentLine(cursor.line);
}, 75);
}
}
}
}
function _handleKeyEvents(jqEvent, editor, event) {
_checkElectricChars(jqEvent, editor, event);
// Pass the key event to the code hint manager. It may call preventDefault() on the event.
CodeHintManager.handleKeyEvent(editor, event);
}
function _handleSelectAll() {
var editor = EditorManager.getFocusedEditor();
if (editor) {
editor._selectAllVisible();
}
}
/**
* List of all current (non-destroy()ed) Editor instances. Needed when changing global preferences
* that affect all editors, e.g. tabbing or color scheme settings.
* @type {Array.<Editor>}
*/
var _instances = [];
/**
* @constructor
*
* Creates a new CodeMirror editor instance bound to the given Document. The Document need not have
* a "master" Editor realized yet, even if makeMasterEditor is false; in that case, the first time
* an edit occurs we will automatically ask EditorManager to create a "master" editor to render the
* Document modifiable.
*
* ALWAYS call destroy() when you are done with an Editor - otherwise it will leak a Document ref.
*
* @param {!Document} document
* @param {!boolean} makeMasterEditor If true, this Editor will set itself as the (secret) "master"
* Editor for the Document. If false, this Editor will attach to the Document as a "slave"/
* secondary editor.
* @param {!string} mode Syntax-highlighting language mode; "" means plain-text mode.
* See {@link EditorUtils#getModeFromFileExtension()}.
* @param {!jQueryObject} container Container to add the editor to.
* @param {!Object<string, function(Editor)>} additionalKeys Mapping of keyboard shortcuts to
* custom handler functions. Mapping is in CodeMirror format
* @param {{startLine: number, endLine: number}=} range If specified, range of lines within the document
* to display in this editor. Inclusive.
*/
function Editor(document, makeMasterEditor, mode, container, additionalKeys, range) {
var self = this;
_instances.push(this);
// Attach to document: add ref & handlers
this.document = document;
document.addRef();
if (range) { // attach this first: want range updated before we process a change
this._visibleRange = new TextRange(document, range.startLine, range.endLine);
}
// store this-bound version of listeners so we can remove them later
this._handleDocumentChange = this._handleDocumentChange.bind(this);
this._handleDocumentDeleted = this._handleDocumentDeleted.bind(this);
$(document).on("change", this._handleDocumentChange);
$(document).on("deleted", this._handleDocumentDeleted);
// (if makeMasterEditor, we attach the Doc back to ourselves below once we're fully initialized)
this._inlineWidgets = [];
// Editor supplies some standard keyboard behavior extensions of its own
var codeMirrorKeyMap = {
"Tab": _handleTabKey,
"Shift-Tab": "indentLess",
"Left": function (instance) {
if (!_handleSoftTabNavigation(instance, -1, "moveH")) {
CodeMirror.commands.goCharLeft(instance);
}
},
"Right": function (instance) {
if (!_handleSoftTabNavigation(instance, 1, "moveH")) {
CodeMirror.commands.goCharRight(instance);
}
},
"Backspace": function (instance) {
if (!_handleSoftTabNavigation(instance, -1, "deleteH")) {
CodeMirror.commands.delCharLeft(instance);
}
},
"Delete": function (instance) {
if (!_handleSoftTabNavigation(instance, 1, "deleteH")) {
CodeMirror.commands.delCharRight(instance);
}
},
"Esc": function (instance) {
self.removeAllInlineWidgets();
},
"'>'": function (cm) { cm.closeTag(cm, '>'); },
"'/'": function (cm) { cm.closeTag(cm, '/'); }
};
EditorManager.mergeExtraKeys(self, codeMirrorKeyMap, additionalKeys);
// We'd like null/"" to mean plain text mode. CodeMirror defaults to plaintext for any
// unrecognized mode, but it complains on the console in that fallback case: so, convert
// here so we're always explicit, avoiding console noise.
if (!mode) {
mode = "text/plain";
}
// Create the CodeMirror instance
// (note: CodeMirror doesn't actually require using 'new', but jslint complains without it)
this._codeMirror = new CodeMirror(container, {
electricChars: false, // we use our own impl of this to avoid CodeMirror bugs; see _checkElectricChars()
indentWithTabs: _useTabChar,
tabSize: _tabSize,
indentUnit: _indentUnit,
lineNumbers: true,
matchBrackets: true,
dragDrop: false, // work around issue #1123
extraKeys: codeMirrorKeyMap
});
// Can't get CodeMirror's focused state without searching for
// CodeMirror-focused. Instead, track focus via onFocus and onBlur
// options and track state with this._focused
this._focused = false;
this._installEditorListeners();
$(this)
.on("keyEvent", _handleKeyEvents)
.on("change", this._handleEditorChange.bind(this));
// Set code-coloring mode BEFORE populating with text, to avoid a flash of uncolored text
this._codeMirror.setOption("mode", mode);
// Initially populate with text. This will send a spurious change event, so need to make
// sure this is understood as a 'sync from document' case, not a genuine edit
this._duringSync = true;
this._resetText(document.getText());
this._duringSync = false;
if (range) {
// Hide all lines other than those we want to show. We do this rather than trimming the
// text itself so that the editor still shows accurate line numbers.
this._codeMirror.operation(function () {
var i;
for (i = 0; i < range.startLine; i++) {
self._hideLine(i);
}
var lineCount = self.lineCount();
for (i = range.endLine + 1; i < lineCount; i++) {
self._hideLine(i);
}
});
this.setCursorPos(range.startLine, 0);
}
// Now that we're fully initialized, we can point the document back at us if needed
if (makeMasterEditor) {
document._makeEditable(this);
}
// Add scrollTop property to this object for the scroll shadow code to use
Object.defineProperty(this, "scrollTop", {
get: function () {
return this._codeMirror.getScrollInfo().y;
}
});
}
/**
* Removes this editor from the DOM and detaches from the Document. If this is the "master"
* Editor that is secretly providing the Document's backing state, then the Document reverts to
* a read-only string-backed mode.
*/
Editor.prototype.destroy = function () {
// CodeMirror docs for getWrapperElement() say all you have to do is "Remove this from your
// tree to delete an editor instance."
$(this.getRootElement()).remove();
_instances.splice(_instances.indexOf(this), 1);
// Disconnect from Document
this.document.releaseRef();
$(this.document).off("change", this._handleDocumentChange);
$(this.document).off("deleted", this._handleDocumentDeleted);
if (this._visibleRange) { // TextRange also refs the Document
this._visibleRange.dispose();
}
// If we're the Document's master editor, disconnecting from it has special meaning
if (this.document._masterEditor === this) {
this.document._makeNonEditable();
}
// Destroying us destroys any inline widgets we're hosting. Make sure their closeCallbacks
// run, at least, since they may also need to release Document refs
this._inlineWidgets.forEach(function (inlineWidget) {
inlineWidget.onClosed();
});
};
/**
* Handles Select All specially when we have a visible range in order to work around
* bugs in CodeMirror when lines are hidden.
*/
Editor.prototype._selectAllVisible = function () {
var startLine = this.getFirstVisibleLine(),
endLine = this.getLastVisibleLine();
this.setSelection({line: startLine, ch: 0},
{line: endLine, ch: this.document.getLine(endLine).length});
};
/**
* Ensures that the lines that are actually hidden in the inline editor correspond to
* the desired visible range.
*/
Editor.prototype._updateHiddenLines = function () {
if (this._visibleRange) {
var cm = this._codeMirror,
self = this;
cm.operation(function () {
// TODO: could make this more efficient by only iterating across the min-max line
// range of the union of all changes
var i;
for (i = 0; i < cm.lineCount(); i++) {
if (i < self._visibleRange.startLine || i > self._visibleRange.endLine) {
self._hideLine(i);
} else {
// Double-check that the set of NON-hidden lines matches our range too
console.assert(!cm.getLineHandle(i).hidden);
}
}
});
}
};
Editor.prototype._applyChanges = function (changeList) {
// _visibleRange has already updated via its own Document listener. See if this change caused
// it to lose sync. If so, our whole view is stale - signal our owner to close us.
if (this._visibleRange) {
if (this._visibleRange.startLine === null || this._visibleRange.endLine === null) {
$(this).triggerHandler("lostContent");
return;
}
}
// Apply text changes to CodeMirror editor
var cm = this._codeMirror;
cm.operation(function () {
var change, newText;
for (change = changeList; change; change = change.next) {
newText = change.text.join('\n');
if (!change.from || !change.to) {
if (change.from || change.to) {
console.assert(false, "Change record received with only one end undefined--replacing entire text");
}
cm.setValue(newText);
} else {
cm.replaceRange(newText, change.from, change.to);
}
}
});
// The update above may have inserted new lines - must hide any that fall outside our range
this._updateHiddenLines();
};
/**
* Responds to changes in the CodeMirror editor's text, syncing the changes to the Document.
* There are several cases where we want to ignore a CodeMirror change:
* - if we're the master editor, editor changes can be ignored because Document is already listening
* for our changes
* - if we're a secondary editor, editor changes should be ignored if they were caused by us reacting
* to a Document change
*/
Editor.prototype._handleEditorChange = function (event, editor, changeList) {
// we're currently syncing from the Document, so don't echo back TO the Document
if (this._duringSync) {
return;
}
// Secondary editor: force creation of "master" editor backing the model, if doesn't exist yet
this.document._ensureMasterEditor();
if (this.document._masterEditor !== this) {
// Secondary editor:
// we're not the ground truth; if we got here, this was a real editor change (not a
// sync from the real ground truth), so we need to sync from us into the document
// (which will directly push the change into the master editor).
// FUTURE: Technically we should add a replaceRange() method to Document and go through
// that instead of talking to its master editor directly. It's not clear yet exactly
// what the right Document API would be, though.
this._duringSync = true;
this.document._masterEditor._applyChanges(changeList);
this._duringSync = false;
// Update which lines are hidden inside our editor, since we're not going to go through
// _applyChanges() in our own editor.
this._updateHiddenLines();
}
// Else, Master editor:
// we're the ground truth; nothing else to do, since Document listens directly to us
// note: this change might have been a real edit made by the user, OR this might have
// been a change synced from another editor
CodeHintManager.handleChange(this);
};
/**
* Responds to changes in the Document's text, syncing the changes into our CodeMirror instance.
* There are several cases where we want to ignore a Document change:
* - if we're the master editor, Document changes should be ignored becuase we already have the right
* text (either the change originated with us, or it has already been set into us by Document)
* - if we're a secondary editor, Document changes should be ignored if they were caused by us sending
* the document an editor change that originated with us
*/
Editor.prototype._handleDocumentChange = function (event, doc, changeList) {
var change;
// we're currently syncing to the Document, so don't echo back FROM the Document
if (this._duringSync) {
return;
}
if (this.document._masterEditor !== this) {
// Secondary editor:
// we're not the ground truth; and if we got here, this was a Document change that
// didn't come from us (e.g. a sync from another editor, a direct programmatic change
// to the document, or a sync from external disk changes)... so sync from the Document
this._duringSync = true;
this._applyChanges(changeList);
this._duringSync = false;
}
// Else, Master editor:
// we're the ground truth; nothing to do since Document change is just echoing our
// editor changes
};
/**
* Responds to the Document's underlying file being deleted. The Document is now basically dead,
* so we must close.
*/
Editor.prototype._handleDocumentDeleted = function (event) {
// Pass the delete event along as the cause (needed in MultiRangeInlineEditor)
$(this).triggerHandler("lostContent", [event]);
};
/**
* Install singleton event handlers on the CodeMirror instance, translating them into multi-
* listener-capable jQuery events on the Editor instance.
*/
Editor.prototype._installEditorListeners = function () {
var self = this;
// FUTURE: if this list grows longer, consider making this a more generic mapping
// NOTE: change is a "private" event--others shouldn't listen to it on Editor, only on
// Document
this._codeMirror.setOption("onChange", function (instance, changeList) {
$(self).triggerHandler("change", [self, changeList]);
});
this._codeMirror.setOption("onKeyEvent", function (instance, event) {
$(self).triggerHandler("keyEvent", [self, event]);
return event.defaultPrevented; // false tells CodeMirror we didn't eat the event
});
this._codeMirror.setOption("onCursorActivity", function (instance) {
$(self).triggerHandler("cursorActivity", [self]);
});
this._codeMirror.setOption("onScroll", function (instance) {
// If this editor is visible, close all dropdowns on scroll.
// (We don't want to do this if we're just scrolling in a non-visible editor
// in response to some document change event.)
if (self.isFullyVisible()) {
Menus.closeAll();
}
$(self).triggerHandler("scroll", [self]);
// notify all inline widgets of a position change
self._fireWidgetOffsetTopChanged(self.getFirstVisibleLine() - 1);
});
// Convert CodeMirror onFocus events to EditorManager activeEditorChanged
this._codeMirror.setOption("onFocus", function () {
self._focused = true;
EditorManager._notifyActiveEditorChanged(self);
});
this._codeMirror.setOption("onBlur", function () {
self._focused = false;
// EditorManager only cares about other Editors gaining focus, so we don't notify it of anything here
});
};
/**
* Sets the contents of the editor and clears the undo/redo history. Dispatches a change event.
* Semi-private: only Document should call this.
* @param {!string} text
*/
Editor.prototype._resetText = function (text) {
var perfTimerName = PerfUtils.markStart("Edtitor._resetText()\t" + (!this.document || this.document.file.fullPath));
var cursorPos = this.getCursorPos(),
scrollPos = this.getScrollPos();
// This *will* fire a change event, but we clear the undo immediately afterward
this._codeMirror.setValue(text);
// Make sure we can't undo back to the empty state before setValue()
this._codeMirror.clearHistory();
// restore cursor and scroll positions
this.setCursorPos(cursorPos);
this.setScrollPos(scrollPos.x, scrollPos.y);
PerfUtils.addMeasurement(perfTimerName);
};
/**
* Gets the current cursor position within the editor. If there is a selection, returns whichever
* end of the range the cursor lies at.
* @param {boolean} expandTabs If true, return the actual visual column number instead of the character offset in
* the "ch" property.
* @return !{line:number, ch:number}
*/
Editor.prototype.getCursorPos = function (expandTabs) {
var cursor = this._codeMirror.getCursor();
if (expandTabs) {
var line = this._codeMirror.getRange({line: cursor.line, ch: 0}, cursor),
tabSize = Editor.getTabSize(),
column = 0,
i;
for (i = 0; i < line.length; i++) {
if (line[i] === '\t') {
column += (tabSize - (column % tabSize));
} else {
column++;
}
}
cursor.ch = column;
}
return cursor;
};
/**
* Sets the cursor position within the editor. Removes any selection.
* @param {number} line The 0 based line number.
* @param {number=} ch The 0 based character position; treated as 0 if unspecified.
*/
Editor.prototype.setCursorPos = function (line, ch) {
this._codeMirror.setCursor(line, ch);
};
/**
* Given a position, returns its index within the text (assuming \n newlines)
* @param {!{line:number, ch:number}}
* @return {number}
*/
Editor.prototype.indexFromPos = function (coords) {
return this._codeMirror.indexFromPos(coords);
};
/**
* Returns true if pos is between start and end (inclusive at both ends)
* @param {{line:number, ch:number}} pos
* @param {{line:number, ch:number}} start
* @param {{line:number, ch:number}} end
*
*/
Editor.prototype.posWithinRange = function (pos, start, end) {
var startIndex = this.indexFromPos(start),
endIndex = this.indexFromPos(end),
posIndex = this.indexFromPos(pos);
return posIndex >= startIndex && posIndex <= endIndex;
};
/**
* @return {boolean} True if there's a text selection; false if there's just an insertion point
*/
Editor.prototype.hasSelection = function () {
return this._codeMirror.somethingSelected();
};
/**
* Gets the current selection. Start is inclusive, end is exclusive. If there is no selection,
* returns the current cursor position as both the start and end of the range (i.e. a selection
* of length zero).
* @return {!{start:{line:number, ch:number}, end:{line:number, ch:number}}}
*/
Editor.prototype.getSelection = function () {
var selStart = this._codeMirror.getCursor(true),
selEnd = this._codeMirror.getCursor(false);
return { start: selStart, end: selEnd };
};
/**
* @return {!string} The currently selected text, or "" if no selection. Includes \n if the
* selection spans multiple lines (does NOT reflect the Document's line-endings style).
*/
Editor.prototype.getSelectedText = function () {
return this._codeMirror.getSelection();
};
/**
* Sets the current selection. Start is inclusive, end is exclusive. Places the cursor at the
* end of the selection range.
* @param {!{line:number, ch:number}} start
* @param {!{line:number, ch:number}} end
*/
Editor.prototype.setSelection = function (start, end) {
this._codeMirror.setSelection(start, end);
};
/**
* Selects word that the given pos lies within or adjacent to. If pos isn't touching a word
* (e.g. within a token like "//"), moves the cursor to pos without selecting a range.
* Adapted from selectWordAt() in CodeMirror v2.
* @param {!{line:number, ch:number}}
*/
Editor.prototype.selectWordAt = function (pos) {
var line = this.document.getLine(pos.line),
start = pos.ch,
end = pos.ch;
function isWordChar(ch) {
return (/\w/).test(ch) || ch.toUpperCase() !== ch.toLowerCase();
}
while (start > 0 && isWordChar(line.charAt(start - 1))) {
--start;
}
while (end < line.length && isWordChar(line.charAt(end))) {
++end;
}
this.setSelection({line: pos.line, ch: start}, {line: pos.line, ch: end});
};
/**
* Gets the total number of lines in the the document (includes lines not visible in the viewport)
* @returns {!number}
*/
Editor.prototype.lineCount = function () {
return this._codeMirror.lineCount();
};
/**
* Gets the number of the first visible line in the editor.
* @returns {number} The 0-based index of the first visible line.
*/
Editor.prototype.getFirstVisibleLine = function () {
return (this._visibleRange ? this._visibleRange.startLine : 0);
};
/**
* Gets the number of the last visible line in the editor.
* @returns {number} The 0-based index of the last visible line.
*/
Editor.prototype.getLastVisibleLine = function () {
return (this._visibleRange ? this._visibleRange.endLine : this.lineCount() - 1);
};
// FUTURE change to "hideLines()" API that hides a range of lines at once in a single operation, then fires offsetTopChanged afterwards.
/* Hides the specified line number in the editor
* @param {!number}
*/
Editor.prototype._hideLine = function (lineNumber) {
var value = this._codeMirror.hideLine(lineNumber);
// when this line is hidden, notify all following inline widgets of a position change
this._fireWidgetOffsetTopChanged(lineNumber);
return value;
};
/**
* Gets the total height of the document in pixels (not the viewport)
* @param {!boolean} includePadding
* @returns {!number} height in pixels
*/
Editor.prototype.totalHeight = function (includePadding) {
return this._codeMirror.totalHeight(includePadding);
};
/**
* Gets the scroller element from the editor.
* @returns {!HTMLDivElement} scroller
*/
Editor.prototype.getScrollerElement = function () {
return this._codeMirror.getScrollerElement();
};
/**
* Gets the root DOM node of the editor.
* @returns {Object} The editor's root DOM node.
*/
Editor.prototype.getRootElement = function () {
return this._codeMirror.getWrapperElement();
};
/**
* Gets the lineSpace element within the editor (the container around the individual lines of code).
* FUTURE: This is fairly CodeMirror-specific. Logic that depends on this may break if we switch
* editors.
* @returns {Object} The editor's lineSpace element.
*/
Editor.prototype._getLineSpaceElement = function () {
return $(".CodeMirror-lines", this.getScrollerElement()).children().get(0);
};
/**
* Returns the current scroll position of the editor.
* @returns {{x:number, y:number}} The x,y scroll position in pixels
*/
Editor.prototype.getScrollPos = function () {
return this._codeMirror.getScrollInfo();
};
/**
* Sets the current scroll position of the editor.
* @param {number} x scrollLeft position in pixels
* @param {number} y scrollTop position in pixels
*/
Editor.prototype.setScrollPos = function (x, y) {
this._codeMirror.scrollTo(x, y);
};
/**
* Adds an inline widget below the given line. If any inline widget was already open for that
* line, it is closed without warning.
* @param {!{line:number, ch:number}} pos Position in text to anchor the inline.
* @param {!InlineWidget} inlineWidget The widget to add.
*/
Editor.prototype.addInlineWidget = function (pos, inlineWidget) {
var self = this;
inlineWidget.id = this._codeMirror.addInlineWidget(pos, inlineWidget.htmlContent, inlineWidget.height, function (id) {
self._removeInlineWidgetInternal(id);
inlineWidget.onClosed();
});
this._inlineWidgets.push(inlineWidget);
inlineWidget.onAdded();
// once this widget is added, notify all following inline widgets of a position change
this._fireWidgetOffsetTopChanged(pos.line);
};
/**
* Removes all inline widgets
*/
Editor.prototype.removeAllInlineWidgets = function () {
// copy the array because _removeInlineWidgetInternal will modifying the original
var widgets = [].concat(this.getInlineWidgets());
widgets.forEach(function (widget) {
this.removeInlineWidget(widget);
}, this);
};
/**
* Removes the given inline widget.
* @param {number} inlineWidget The widget to remove.
*/
Editor.prototype.removeInlineWidget = function (inlineWidget) {
var lineNum = this._getInlineWidgetLineNumber(inlineWidget);
// _removeInlineWidgetInternal will get called from the destroy callback in CodeMirror.
this._codeMirror.removeInlineWidget(inlineWidget.id);
// once this widget is removed, notify all following inline widgets of a position change
this._fireWidgetOffsetTopChanged(lineNum);
};
/**
* Cleans up the given inline widget from our internal list of widgets.
* @param {number} inlineId id returned by addInlineWidget().
*/
Editor.prototype._removeInlineWidgetInternal = function (inlineId) {
var i;
var l = this._inlineWidgets.length;
for (i = 0; i < l; i++) {
if (this._inlineWidgets[i].id === inlineId) {
this._inlineWidgets.splice(i, 1);
break;
}
}
};
/**
* Returns a list of all inline widgets currently open in this editor. Each entry contains the
* inline's id, and the data parameter that was passed to addInlineWidget().
* @return {!Array.<{id:number, data:Object}>}
*/
Editor.prototype.getInlineWidgets = function () {
return this._inlineWidgets;
};
/**
* Sets the height of an inline widget in this editor.
* @param {!InlineWidget} inlineWidget The widget whose height should be set.
* @param {!number} height The height of the widget.
* @param {boolean} ensureVisible Whether to scroll the entire widget into view.
*/
Editor.prototype.setInlineWidgetHeight = function (inlineWidget, height, ensureVisible) {
var info = this._codeMirror.getInlineWidgetInfo(inlineWidget.id),
oldHeight = (info && info.height) || 0;
this._codeMirror.setInlineWidgetHeight(inlineWidget.id, height, ensureVisible);
// update position for all following inline editors
if (oldHeight !== height) {
var lineNum = this._getInlineWidgetLineNumber(inlineWidget);
this._fireWidgetOffsetTopChanged(lineNum);
}
};
/**
* @private
* Get the starting line number for an inline widget.
* @param {!InlineWidget} inlineWidget
* @return {number} The line number of the widget or -1 if not found.
*/
Editor.prototype._getInlineWidgetLineNumber = function (inlineWidget) {
var info = this._codeMirror.getInlineWidgetInfo(inlineWidget.id);
return (info && info.line) || -1;
};
/**
* @private
* Fire "offsetTopChanged" events when inline editor positions change due to
* height changes of other inline editors.
* @param {!InlineWidget} inlineWidget
*/
Editor.prototype._fireWidgetOffsetTopChanged = function (lineNum) {
var self = this,
otherLineNum;
this.getInlineWidgets().forEach(function (other) {
otherLineNum = self._getInlineWidgetLineNumber(other);
if (otherLineNum > lineNum) {
$(other).triggerHandler("offsetTopChanged");
}
});
};
/** Gives focus to the editor control */
Editor.prototype.focus = function () {
this._codeMirror.focus();
};
/** Returns true if the editor has focus */
Editor.prototype.hasFocus = function () {
return this._focused;
};
/**
* Re-renders the editor UI
*/
Editor.prototype.refresh = function () {
this._codeMirror.refresh();
};
/**
* Re-renders the editor, and all children inline editors.
*/
Editor.prototype.refreshAll = function () {
this.refresh();
this.getInlineWidgets().forEach(function (multilineEditor, i, arr) {
multilineEditor.sizeInlineWidgetToContents(true);
multilineEditor._updateRelatedContainer();
multilineEditor.editors.forEach(function (editor, j, arr) {
editor.refresh();
});
});
};
/**
* Shows or hides the editor within its parent. Does not force its ancestors to
* become visible.
* @param {boolean} show true to show the editor, false to hide it
*/
Editor.prototype.setVisible = function (show) {
$(this.getRootElement()).css("display", (show ? "" : "none"));
this._codeMirror.refresh();
if (show) {
this._inlineWidgets.forEach(function (inlineWidget) {
inlineWidget.onParentShown();
});
}
};
/**
* Returns true if the editor is fully visible--i.e., is in the DOM, all ancestors are
* visible, and has a non-zero width/height.
*/
Editor.prototype.isFullyVisible = function () {
return $(this.getRootElement()).is(":visible");
};
/**
* Gets the syntax-highlighting mode for the current selection or cursor position. (The mode may
* vary within one file due to embedded languages, e.g. JS embedded in an HTML script block).
*
* Returns null if the mode at the start of the selection differs from the mode at the end -
* an *approximation* of whether the mode is consistent across the whole range (a pattern like
* A-B-A would return A as the mode, not null).
*
* @return {?(Object|String)} Object or Name of syntax-highlighting mode; see {@link EditorUtils#getModeFromFileExtension()}.
*/
Editor.prototype.getModeForSelection = function () {
var sel = this.getSelection();
// Check for mixed mode info (meaning mode varies depending on position)
// TODO (#921): this only works for certain mixed modes; some do not expose this info
var startState = this._codeMirror.getTokenAt(sel.start).state;
if (startState.mode) {
var startMode = startState.mode;
// If mixed mode, check that mode is the same at start & end of selection
if (sel.start.line !== sel.end.line || sel.start.ch !== sel.end.ch) {
var endState = this._codeMirror.getTokenAt(sel.end).state;
var endMode = endState.mode;
if (startMode !== endMode) {
return null;
}
}
return startMode;
} else {
// Mode does not vary: just use the editor-wide mode
return this._codeMirror.getOption("mode");
}
};
/**
* Gets the syntax-highlighting mode for the document.
*
* @return {Object|String} Object or Name of syntax-highlighting mode; see {@link EditorUtils#getModeFromFileExtension()}.
*/
Editor.prototype.getModeForDocument = function () {
return this._codeMirror.getOption("mode");
};
/**
* Sets the syntax-highlighting mode for the document.
*
* @param {string} mode Name of syntax highlighting mode.
*/
Editor.prototype.setModeForDocument = function (mode) {
this._codeMirror.setOption("mode", mode);
};
/**
* The Document we're bound to
* @type {!Document}
*/
Editor.prototype.document = null;
/**
* If true, we're in the middle of syncing to/from the Document. Used to ignore spurious change
* events caused by us (vs. change events caused by others, which we need to pay attention to).
* @type {!boolean}
*/
Editor.prototype._duringSync = false;
/**
* @private
* NOTE: this is actually "semi-private": EditorManager also accesses this field... as well as
* a few other modules. However, we should try to gradually move most code away from talking to
* CodeMirror directly.
* @type {!CodeMirror}
*/
Editor.prototype._codeMirror = null;
/**
* @private
* @type {!Array.<{id:number, data:Object}>}
*/
Editor.prototype._inlineWidgets = null;
/**
* @private
* @type {?TextRange}
*/
Editor.prototype._visibleRange = null;
// Global settings that affect all Editor instances (both currently open Editors as well as those created
// in the future)
/**
* Sets whether to use tab characters (vs. spaces) when inserting new text. Affects all Editors.
* @param {boolean} value
*/
Editor.setUseTabChar = function (value) {
_useTabChar = value;
_instances.forEach(function (editor) {
editor._codeMirror.setOption("indentWithTabs", _useTabChar);
});
_prefs.setValue("useTabChar", Boolean(_useTabChar));
};
/** @type {boolean} Gets whether all Editors use tab characters (vs. spaces) when inserting new text */
Editor.getUseTabChar = function (value) {
return _useTabChar;
};
/**
* Sets tab character width. Affects all Editors.
* @param {number} value
*/
Editor.setTabSize = function (value) {
_tabSize = value;
_instances.forEach(function (editor) {
editor._codeMirror.setOption("tabSize", _tabSize);
});
_prefs.setValue("tabSize", _tabSize);
};
/** @type {number} Get indent unit */
Editor.getTabSize = function (value) {
return _tabSize;
};
/**
* Sets indentation width. Affects all Editors.
* @param {number} value
*/
Editor.setIndentUnit = function (value) {
_indentUnit = value;
_instances.forEach(function (editor) {
editor._codeMirror.setOption("indentUnit", _indentUnit);
});
_prefs.setValue("indentUnit", _indentUnit);
};
/** @type {number} Get indentation width */
Editor.getIndentUnit = function (value) {
return _indentUnit;
};
// Global commands that affect the currently focused Editor instance, wherever it may be
CommandManager.register(Strings.CMD_SELECT_ALL, Commands.EDIT_SELECT_ALL, _handleSelectAll);
// Define public API
exports.Editor = Editor;
});
| nikmeiser/temboo-geocode | node_modules/brackets/brackets-src/src/editor/Editor.js | JavaScript | mit | 49,257 |
'use strict';
/**
* Email.js service
*
* @description: A set of functions similar to controller's actions to avoid code duplication.
*/
const _ = require('lodash');
const sendmail = require('sendmail')({
silent: true
});
module.exports = {
send: (options, cb) => {
return new Promise((resolve, reject) => {
// Default values.
options = _.isObject(options) ? options : {};
options.from = options.from || '"Administration Panel" <no-reply@strapi.io>';
options.replyTo = options.replyTo || '"Administration Panel" <no-reply@strapi.io>';
options.text = options.text || options.html;
options.html = options.html || options.text;
// Send the email.
sendmail({
from: options.from,
to: options.to,
replyTo: options.replyTo,
subject: options.subject,
text: options.text,
html: options.html
}, function (err) {
if (err) {
reject([{ messages: [{ id: 'Auth.form.error.email.invalid' }] }]);
} else {
resolve();
}
});
});
}
};
| strapi/strapi-examples | jekyll-strapi-tutorial/api/plugins/email/services/Email.js | JavaScript | mit | 1,088 |
DS.classes.Message = function(create){
var relations = [];
//check
check(create, {
time: DS.classes.Time,
data: Match.Optional(Object)
});
//create
_.extend(this, create);
//add relations
this.addRelation = function(relation, reversed){
check(relation, DS.classes.Relation);
check(reversed, Boolean);
relations.push({
'relation': relation,
'reversed': reversed
});
};
this.getRelations = function(){
return relations;
}
};
| dpwoert/deepspace | packages/deepspace/classes/Message.js | JavaScript | mit | 556 |
'use strict';
import React from 'react';
import {BootstrapTable, TableHeaderColumn} from 'react-bootstrap-table';
var products = [];
function addProducts(quantity) {
var startId = products.length;
for (var i = 0; i < quantity; i++) {
var id = startId + i;
products.push({
id: id,
name: "Item name " + id,
price: 100 + i
});
}
}
addProducts(5);
var order = 'desc';
export default class SortTable extends React.Component{
handleBtnClick = e => {
if(order === 'desc'){
this.refs.table.handleSort('asc', 'name');
order = 'asc';
} else {
this.refs.table.handleSort('desc', 'name');
order = 'desc';
}
}
render(){
return (
<div>
<p style={{color:'red'}}>You cam click header to sort or click following button to perform a sorting by expose API</p>
<button onClick={this.handleBtnClick}>Sort Product Name</button>
<BootstrapTable ref="table" data={products}>
<TableHeaderColumn dataField="id" isKey={true} dataSort={true}>Product ID</TableHeaderColumn>
<TableHeaderColumn dataField="name" dataSort={true}>Product Name</TableHeaderColumn>
<TableHeaderColumn dataField="price">Product Price</TableHeaderColumn>
</BootstrapTable>
</div>
);
}
};
| opensourcegeek/react-bootstrap-table | examples/js/sort/sort-table.js | JavaScript | mit | 1,308 |
////////////////////////////////////////////////////////////////////////////////////
////// Events
////////////////////////////////////////////////////////////////////////////////////
'use strict';
// DI
var db,
responseHandler;
/**
*
* @param req the HTTP requests, contains header and body parameters
* @param res the callback to which send HTTP response
* @param next facilitate restify function chaining
*/
exports.findAll = function (req, res, next) {
req.check('appid', '"appid": must be a valid identifier').notNull();
var errors = req.validationErrors(),
appid;
if (errors) {
responseHandler(res).error(400, errors);
return;
}
appid = req.params.appid;
db.findAllEvents({'application_id': appid}, responseHandler(res, next));
};
/**
*
* @param req the HTTP requests, contains header and body parameters
* @param res the callback to which send HTTP response
* @param next facilitate restify function chaining
*/
exports.findById = function (req, res, next) {
req.check('appid', '"appid": must be a valid identifier').notNull();
req.check('eventid', '"eventid": must be a valid identifier').notNull();
var errors = req.validationErrors(),
appid,
eventid;
if (errors) {
responseHandler(res).error(400, errors);
return;
}
appid = req.params.appid;
eventid = req.params.eventid;
db.findEventById({'application_id': appid, 'event_id': eventid}, responseHandler(res, next));
};
/**
*
* @param req the HTTP requests, contains header and body parameters
* @param res the callback to which send HTTP response
* @param next facilitate restify function chaining
*/
exports.create = function (req, res, next) {
req.check('appid', '"appid": must be a valid identifier').notNull();
req.check('type', '"type": must be a valid identifier').notNull();
req.check('user', '"user": must be a valid identifier').notNull();
req.check('issued', '"date": must be a valid date').isDate();
var errors = req.validationErrors(),
appid,
type,
user,
issued;
if (errors) {
responseHandler(res).error(400, errors);
return;
}
appid = req.params.appid;
type = req.params.type;
user = req.params.user;
issued = req.params.issued; // or "2013-02-26"; // TODO today or specified
db.createEvent(
{'application_id': appid, 'type': type, 'user': user, 'issued': issued},
responseHandler(res, next)
);
};
| Gitification/gitification-server | controllers/events.js | JavaScript | mit | 2,351 |
'use strict';
const path = require('path');
const request = require('supertest');
const pedding = require('pedding');
const assert = require('assert');
const sleep = require('ko-sleep');
const mm = require('..');
const fixtures = path.join(__dirname, 'fixtures');
const baseDir = path.join(fixtures, 'app-event');
describe('test/app_event.test.js', () => {
afterEach(mm.restore);
describe('after ready', () => {
let app;
before(() => {
app = mm.app({
baseDir,
cache: false,
});
return app.ready();
});
after(() => app.close());
it('should listen by eventByRequest', done => {
done = pedding(3, done);
app.once('eventByRequest', done);
app.on('eventByRequest', done);
request(app.callback())
.get('/event')
.expect(200)
.expect('done', done);
});
});
describe('before ready', () => {
let app;
beforeEach(() => {
app = mm.app({
baseDir,
cache: false,
});
});
afterEach(() => app.ready());
afterEach(() => app.close());
it('should listen after app ready', done => {
done = pedding(2, done);
app.once('appReady', done);
app.on('appReady', done);
});
it('should listen after app instantiate', done => {
done = pedding(2, done);
app.once('appInstantiated', done);
app.on('appInstantiated', done);
});
});
describe('throw before app init', () => {
let app;
beforeEach(() => {
const baseDir = path.join(fixtures, 'app');
const customEgg = path.join(fixtures, 'error-framework');
app = mm.app({
baseDir,
customEgg,
cache: false,
});
});
afterEach(() => app.close());
it('should listen using app.on', done => {
app.on('error', err => {
assert(err.message === 'start error');
done();
});
});
it('should listen using app.once', done => {
app.once('error', err => {
assert(err.message === 'start error');
done();
});
});
it('should throw error from ready', function* () {
try {
yield app.ready();
} catch (err) {
assert(err.message === 'start error');
}
});
it('should close when app init failed', function* () {
app.once('error', () => {});
yield sleep(1000);
// app._app is undefined
yield app.close();
});
});
});
| eggjs/egg-mock | test/app_event.test.js | JavaScript | mit | 2,448 |
/*!
* Kaiseki
* Copyright(c) 2012 BJ Basañes / Shiki (shikishiji@gmail.com)
* MIT Licensed
*
* See the README.md file for documentation.
*/
var request = require('request');
var _ = require('underscore');
var Kaiseki = function(options) {
if (!_.isObject(options)) {
// Original signature
this.applicationId = arguments[0];
this.restAPIKey = arguments[1];
this.masterKey = null;
this.sessionToken = arguments[2] || null;
this.request = request;
this.baseURL = 'https://api.parse.com';
} else {
// New interface to allow masterKey and custom request function
options = options || {};
this.applicationId = options.applicationId;
this.restAPIKey = options.restAPIKey;
this.masterKey = options.masterKey || null;
this.sessionToken = options.sessionToken || null;
this.request = options.request || request;
this.baseURL = options.serverURL;
}
};
Kaiseki.prototype = {
applicationId: null,
restAPIKey: null,
masterKey: null, // required for deleting files
sessionToken: null,
createUser: function(data, callback) {
this._jsonRequest({
method: 'POST',
url: '/1/users',
params: data,
callback: function(err, res, body, success) {
if (!err && success)
body = _.extend({}, data, body);
callback(err, res, body, success);
}
});
},
getUser: function(objectId, params, callback) {
this._jsonRequest({
url: '/1/users/' + objectId,
params: _.isFunction(params) ? null : params,
callback: _.isFunction(params) ? params : callback
});
},
// Also used for validating a session token
// https://parse.com/docs/rest#users-validating
getCurrentUser: function(sessionToken, callback) {
if (_.isFunction(sessionToken)) {
callback = sessionToken;
sessionToken = undefined;
}
this._jsonRequest({
url: '/1/users/me',
sessionToken: sessionToken,
callback: callback
});
},
loginFacebookUser: function(facebookAuthData, callback) {
this._socialLogin({facebook: facebookAuthData}, callback);
},
loginTwitterUser: function(twitterAuthData, callback) {
this._socialLogin({twitter: twitterAuthData}, callback);
},
loginUser: function(username, password, callback) {
this._jsonRequest({
url: '/1/login',
params: {
username: username,
password: password
},
callback: callback
});
},
updateUser: function(objectId, data, callback) {
this._jsonRequest({
method: 'PUT',
url: '/1/users/' + objectId,
params: data,
callback: callback
});
},
deleteUser: function(objectId, callback) {
this._jsonRequest({
method: 'DELETE',
url: '/1/users/' + objectId,
callback: callback
});
},
getUsers: function(params, callback) {
this._jsonRequest({
url: '/1/users',
params: _.isFunction(params) ? null : params,
callback: _.isFunction(params) ? params : callback
});
},
requestPasswordReset: function(email, callback) {
this._jsonRequest({
method: 'POST',
url: '/1/requestPasswordReset',
params: {'email': email},
callback: callback
});
},
createObjects: function(className, data, callback) {
var requests = [];
for (var i = 0; i < data.length; i++) {
requests.push({
'method': 'POST',
'path': '/1/classes/' + className,
'body': data[i]
});
}
this._jsonRequest({
method: 'POST',
url: '/1/batch/',
params: {
requests: requests
},
callback: function(err, res, body, success) {
if (!err && success)
body = _.extend({}, data, body);
callback(err, res, body, success);
}
});
},
createObject: function(className, data, callback) {
this._jsonRequest({
method: 'POST',
url: '/1/classes/' + className,
params: data,
callback: function(err, res, body, success) {
if (!err && success)
body = _.extend({}, data, body);
callback(err, res, body, success);
}
});
},
getObject: function(className, objectId, params, callback) {
this._jsonRequest({
url: '/1/classes/' + className + '/' + objectId,
params: _.isFunction(params) ? null : params,
callback: _.isFunction(params) ? params : callback
});
},
updateObjects: function(className, updates, callback) {
var requests = [],
update = null;
for (var i = 0; i < updates.length; i++) {
update = updates[i];
requests.push({
'method': 'PUT',
'path': '/1/classes/' + className + '/' + update.objectId,
'body': update.data
});
}
this._jsonRequest({
method: 'POST',
url: '/1/batch/',
params: {
requests: requests
},
callback: callback
});
},
updateObject: function(className, objectId, data, callback) {
this._jsonRequest({
method: 'PUT',
url: '/1/classes/' + className + '/' + objectId,
params: data,
callback: callback
});
},
deleteObject: function(className, objectId, callback) {
this._jsonRequest({
method: 'DELETE',
url: '/1/classes/' + className + '/' + objectId,
callback: callback
});
},
getObjects: function(className, params, callback) {
this._jsonRequest({
url: '/1/classes/' + className,
params: _.isFunction(params) ? null : params,
callback: _.isFunction(params) ? params : callback
});
},
countObjects: function(className, params, callback) {
var paramsMod = params;
if (_.isFunction(params)) {
paramsMod = {};
paramsMod['count'] = 1;
paramsMod['limit'] = 0;
} else {
paramsMod['count'] = 1;
paramsMod['limit'] = 0;
}
this._jsonRequest({
url: '/1/classes/' + className,
params: paramsMod,
callback: _.isFunction(params) ? params : callback
});
},
createRole: function(data, callback) {
this._jsonRequest({
method: 'POST',
url: '/1/roles',
params: data,
callback: function(err, res, body, success) {
if (!err && success)
body = _.extend({}, data, body);
callback(err, res, body, success);
}
});
},
getRole: function(objectId, params, callback) {
this._jsonRequest({
url: '/1/roles/' + objectId,
params: _.isFunction(params) ? null : params,
callback: _.isFunction(params) ? params : callback
});
},
updateRole: function(objectId, data, callback) {
this._jsonRequest({
method: 'PUT',
url: '/1/roles/' + objectId,
params: data,
callback: callback
});
},
deleteRole: function(objectId, callback) {
this._jsonRequest({
method: 'DELETE',
url: '/1/roles/' + objectId,
callback: callback
});
},
getRoles: function(params, callback) {
this._jsonRequest({
url: '/1/roles',
params: _.isFunction(params) ? null : params,
callback: _.isFunction(params) ? params : callback
});
},
uploadFile: function(filePath, fileName, callback) {
if (_.isFunction(fileName)) {
callback = fileName;
fileName = null;
}
var contentType = require('mime').lookup(filePath);
if (!fileName)
fileName = filePath.replace(/^.*[\\\/]/, ''); // http://stackoverflow.com/a/423385/246142
var buffer = require('fs').readFileSync(filePath);
this.uploadFileBuffer(buffer, contentType, fileName, callback);
},
uploadFileBuffer: function(buffer, contentType, fileName, callback) {
this._jsonRequest({
method: 'POST',
url: '/1/files/' + fileName,
body: buffer,
headers: { 'Content-type': contentType },
callback: callback
});
},
deleteFile: function(name, callback) {
this._jsonRequest({
method: 'DELETE',
url: '/1/files/' + name,
callback: callback
});
},
sendPushNotification: function(data, callback) {
this._jsonRequest({
method: 'POST',
url: '/1/push',
params: data,
callback: function(err, res, body, success) {
if (!err && success)
body = _.extend({}, data, body);
callback.apply(this, arguments);
}
});
},
sendAnalyticsEvent: function(eventName, dimensionsOrCallback, callback) {
this._jsonRequest({
method: 'POST',
url: '/1/events/' + eventName,
params: _.isFunction(dimensionsOrCallback) ? {} : dimensionsOrCallback,
callback: _.isFunction(dimensionsOrCallback) ? dimensionsOrCallback : callback
});
},
stringifyParamValues: function(params) {
if (!params || _.isEmpty(params))
return null;
var values = _(params).map(function(value, key) {
if (_.isObject(value) || _.isArray(value))
return JSON.stringify(value);
else
return value;
});
var keys = _(params).keys();
var ret = {};
for (var i = 0; i < keys.length; i++)
ret[keys[i]] = values[i];
return ret;
},
_socialLogin: function(authData, callback) {
this._jsonRequest({
method: 'POST',
url: '/1/users',
params: {
authData: authData
},
callback: callback
});
},
_jsonRequest: function(opts) {
var sessionToken = opts.sessionToken || this.sessionToken;
opts = _.omit(opts, 'sessionToken');
opts = _.extend({
method: 'GET',
url: null,
params: null,
body: null,
headers: null,
callback: null
}, opts);
var reqOpts = {
method: opts.method,
headers: {
'X-Parse-Application-Id': this.applicationId,
'X-Parse-REST-API-Key': this.restAPIKey
}
};
if (sessionToken)
reqOpts.headers['X-Parse-Session-Token'] = sessionToken;
if (this.masterKey)
reqOpts.headers['X-Parse-Master-Key'] = this.masterKey;
if (opts.headers)
_.extend(reqOpts.headers, opts.headers);
if (opts.params) {
if (opts.method == 'GET')
opts.params = this.stringifyParamValues(opts.params);
var key = 'qs';
if (opts.method === 'POST' || opts.method === 'PUT')
key = 'json';
reqOpts[key] = opts.params;
} else if (opts.body) {
reqOpts.body = opts.body;
}
this.request(this.baseURL + opts.url, reqOpts, function(err, res, body) {
var isCountRequest = opts.params && !_.isUndefined(opts.params['count']) && !!opts.params.count;
var success = !err && res && (res.statusCode === 200 || res.statusCode === 201);
if (res && res.headers['content-type'] &&
res.headers['content-type'].toLowerCase().indexOf('application/json') >= 0) {
if (body != null && !_.isObject(body) && !_.isArray(body)) // just in case it's been parsed already
body = JSON.parse(body);
if (body != null) {
if (body.error) {
success = false;
} else if (body.results && _.isArray(body.results) && !isCountRequest) {
// If this is a "count" request. Don't touch the body/result.
body = body.results;
}
}
}
opts.callback(err, res, body, success);
});
}
};
module.exports = Kaiseki;
| GiantThinkwell/kaiseki | lib/kaiseki.js | JavaScript | mit | 11,280 |
(function(app) {
"use strict";
app.directive("ratingInput", [
"$rootScope", function($rootScope) {
return {
restrict: "A",
link: function($scope, $element, $attrs) {
$element.raty({
score: $attrs.cdRatingInput,
half: true,
halfShow: true,
starHalf: "/Content/Images/star-half-big.png",
starOff: "/Content/Images/star-off-big.png",
starOn: "/Content/Images/star-on-big.png",
hints: ["Poor", "Average", "Good", "Very Good", "Excellent"],
target: "#Rating",
targetKeep: true,
noRatedMsg: "Not Rated yet!",
scoreName: "Rating",
click: function(score) {
$rootScope.$broadcast("Broadcast::RatingAvailable", score);
}
});
}
};
}
]);
})(angular.module("books")); | shibbir/bookarena | Source/BookArena.Presentation/Scripts/books/directives/books.ratinginput.directive.js | JavaScript | mit | 1,138 |
{
"status": {
"error": false,
"code": 200,
"type": "success",
"message": "Success"
},
"pagination": {
"before_cursor": null,
"after_cursor": null,
"previous_link": null,
"next_link": null
},
"data": [
{
"id": 1111,
"name": "marketing"
}
]
}
| oswell/onelogin-go | testdata/get_roles.js | JavaScript | mit | 369 |
var gulp = require('gulp');
var connect = require('gulp-connect');
var uglify = require('gulp-uglify');
var concat = require('gulp-concat');
var opn = require('opn');
var config = {
rootDir: '.',
servingPort: 8080,
servingDir: './dist',
paths: {
src: {
scripts: './src/**/*.js',
styles: './src/**/*.css',
images: '',
index: './src/index.html',
partials: ['./src/**/*.html', '!./index.html'],
},
distDev: './dist.dev',
distProd: './dist.prod'
}
}
gulp.task('build', function() {
});
gulp.task('serve', ['connect'], function() {
return opn('http://localhost:' + config.servingPort);
});
gulp.task('livereload', function() {
console.log('reloading')
gulp.src(config.filesToWatch)
.pipe(connect.reload());
});
gulp.task('connect', function() {
connect.server({
root: config.servingDir,
port: config.servingPort,
livereload: false,
fallback: config.servingDir + '/index.html'
});
});
gulp.task('watch', function() {
gulp.watch([config.sourcePaths.css, config.sourcePaths.html, config.sourcePaths.js], ['livereload']);
});
gulp.task('default', ['serve']);
//default: clean-build-prod
//serve dev
| codehangar/agenda-codehangar | gulpfile.js | JavaScript | mit | 1,188 |
import React from 'react'
import {Observable} from 'rx'
import {TextField} from 'material-ui'
import ThemeManager from 'material-ui/lib/styles/theme-manager';
import MyRawTheme from '../components/Theme.js';
import ThemeDecorator from 'material-ui/lib/styles/theme-decorator';
import {compose} from 'recompose'
import {observeProps, createEventHandler} from 'rx-recompose'
import {clickable} from '../style.css'
import {View} from '../components'
let Search = compose(
// ASDFGHJKL:
ThemeDecorator(ThemeManager.getMuiTheme(MyRawTheme))
,
observeProps(props$ => {
// Create search query observable
let setQuery = createEventHandler()
let query$ = setQuery.share()
query$
// Only search for songs that are not only spaces 😂
.filter(x => x.trim() !== '')
// Only every 300 ms
.debounce(300)
// Get the `doSearch` method from props
.withLatestFrom(props$.pluck('doSearch'), (query, doSearch) => doSearch(query))
// Search for the query
.subscribe(func => {
func()
})
return {
// Pass down function to set the query
setQuery: Observable.just(setQuery),
// Pass down the current query value
query: query$.startWith(''),
// Pass down force-search function when pressing enter
doSearch: props$.pluck('doSearch'),
// Function to start playing song when clicked on
playSong: props$.pluck('playSong'),
// Searchresults to display
searchResults:
Observable.merge(
// Results from the search
props$.pluck('results$') // Get results observable
.distinctUntilChanged() // Only when unique
.flatMapLatest(x => x) // Morph into the results$
.startWith([]) // And set off with a empty array
,
query$
// When query is only spaces
.filter(x => x.trim() === '')
// Reset the results to empty array
.map(() => [])
),
}
})
)(({query, setQuery, searchResults, playSong, doSearch}) => (
<View>
<TextField
hintText="Search for a song! :D"
onChange={(e,value) => setQuery(e.target.value)}
value={query}
onEnterKeyDown={doSearch(query)}
fullWidth={true}
underlineStyle={{borderWidth: 2}}
/>
<View>
{ /* List all the results */ }
{ searchResults.map(result =>
<View
key={result.nid}
className={clickable}
// On click, reset the query and play the song!
onClick={() => {
playSong(result)()
setQuery('')
}}
// Same as setting the text, but more compact
children={`${result.title} - ${result.artist}`}
/>
)}
</View>
</View>
))
export default Search
| dralletje/Tonlist | client/components/Search.js | JavaScript | mit | 2,794 |
(function(ns) {
/**
* JSON CORS utility
* Wraps up all the cors stuff into a simple post or get. Falls back to jsonp
*/
var JSONCORS = function() {
var self = this;
var supportsCORS = ('withCredentials' in new XMLHttpRequest()) || (typeof XDomainRequest != 'undefined');
/********************************************************************************/
// Utils
/********************************************************************************/
/**
* Serializes a dictionary into a url query
* @param m: the map to serialize
* @return the url query (no preceeding ?)
*/
var serializeURLQuery = function(m) {
var args = [];
for (var k in m) {
args.push(encodeURIComponent(k) + '=' + encodeURIComponent(m[k]))
}
return args.join('&');
};
/********************************************************************************/
// CORS
/********************************************************************************/
/**
* Performs a CORS request which wraps the response through our marshalled API
* @param url: the url to visit
* @param method: GET|POST the http method
* @param payload: the payload to send (undefined for GET)
* @param success: executed on success. Given response then http status then xhr
* @param failure: executed on failure. Given http status then error then xhr
* @return the XHR object
*/
self.requestCORS = function(url, method, payload, success, failure) {
method = method.toUpperCase();
var xhr;
if (typeof XDomainRequest != 'undefined') {
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
xhr = new XMLHttpRequest();
xhr.open(method, url, true);
}
xhr.onload = function() {
var json;
try { json = JSON.parse(xhr.responseText); } catch(e) { /* noop */ }
var status = (json && json.http_status !== undefined) ? json.http_status : xhr.status;
if (status >= 200 && status <= 299) {
success(json, status, xhr);
} else {
failure(xhr.status, json ? json.error : undefined, xhr);
}
};
xhr.onerror = function() {
failure(xhr.status, undefined, xhr);
};
if (method === 'POST') {
xhr.setRequestHeader("Content-type","application/json");
xhr.send(JSON.stringify(payload));
} else {
xhr.send();
}
return xhr;
};
/********************************************************************************/
// JSONP
/********************************************************************************/
/**
* Performs a JSONP request which wraps the response through our marshalled API
* @param url: the url to visit
* @param method: GET|POST the http method
* @param payload: the payload to send (undefined for GET)
* @param success: executed on success. Given response then http status then xhr
* @param failure: executed on failure. Given http status then error then xhr
* @return the XHR object
*/
self.requestJSONP = function(url, method, payload, success, failure) {
method = method.toUpperCase();
var jsonp = document.createElement('script');
jsonp.type = 'text/javascript';
// Success callback
var id = '__jsonp_' + Math.ceil(Math.random() * 10000);
var dxhr = { jsonp:true, id:id, response:undefined };
window[id] = function(r) {
jsonp.parentElement.removeChild(jsonp);
delete window[id];
dxhr.response = r;
if (r === undefined || r === null) {
success(undefined, 200, dxhr);
} else {
if (r.http_status >= 200 && r.http_status <= 299) {
success(r, r.http_status, dxhr);
} else {
failure(r.http_status, r.error, dxhr);
}
}
};
// Error callback
jsonp.onerror = function() {
jsonp.parentElement.removeChild(jsonp);
dxhr.jsonp_transport_error = 'ScriptErrorFailure';
failure(0, undefined, dxhr);
};
var urlQuery;
if (method === 'POST') {
urlQuery = '?' + serializeURLQuery(payload) + '&callback=' + id + '&_=' + new Date().getTime();
} else {
urlQuery = '?' + 'callback=' + id + '&_=' + new Date().getTime();
}
jsonp.src = url + urlQuery;
document.head.appendChild(jsonp);
return dxhr;
};
/********************************************************************************/
// GET
/********************************************************************************/
/**
* Makes a get request
* @param url=/: the url to post to
* @param success=undefined: executed on http success with the response
* @param failure=undefined: executed on http failure
* @param complete=undefined: executed after http success or failure
* Returns either the xhr request or a jsonp holding object
*/
self.get = function(options) {
var method = supportsCORS ? 'requestCORS' : 'requestJSONP';
return self[method](options.url || window.location.href, 'GET', undefined, function(response, status, xhr) {
if (options.success) { options.success(response, status, xhr); }
if (options.complete) { options.complete(); }
}, function(status, error, xhr) {
if (options.failure) { options.failure(status, error, xhr); }
if (options.complete) { options.complete(); }
});
};
/********************************************************************************/
// POST
/********************************************************************************/
/**
* Makes a post request
* @param url=/: the url to post to
* @param payload={}: the payload to send
* @param success=undefined: executed on http success with the response
* @param failure=undefined: executed on http failure
* @param complete=undefined: executed after http success or failure
* Returns either the xhr request or a jsonp holding object
*/
self.post = function(options) {
var method = supportsCORS ? 'requestCORS' : 'requestJSONP';
return self[method](options.url || window.location.href, 'POST', options.payload || {}, function(response, status, xhr) {
if (options.success) { options.success(response, status, xhr); }
if (options.complete) { options.complete(); }
}, function(status, error, xhr) {
if (options.failure) { options.failure(status, error, xhr); }
if (options.complete) { options.complete(); }
});
};
return self;
};
ns.stacktodo = ns.stacktodo || {};
ns.stacktodo.core = ns.stacktodo.core || {};
ns.stacktodo.core.jsoncors = new JSONCORS();
})(window); | stacktodo/stacktodo_js_api | stacktodo/api/core/jsoncors.js | JavaScript | mit | 6,394 |
{ //using constants
const a = 2;
console.log( a ); // 2
a = 3; // TypeError!
}
{ //an array constant
const a = [1,2,3];
a.push( 4 );
console.log( a ); // [1,2,3,4]
a = 42; // TypeError!
} //we can change the object using its methods, we just cannot reassign it...
| zerkotin/javascript | ES6/constants.js | JavaScript | mit | 284 |
import {ProviderSpecification} from 'dxref-core/system/provider/provider-specification';
import { module, test } from 'qunit';
module('Unit | dxref-core | system | provider | provider-specification');
test('provider-specification', function(assert) {
var myFunc = function() {};
var providerSpec = new ProviderSpecification(['VALUE$Date', 'A', 'B', 'C', myFunc]);
assert.deepEqual(providerSpec.getDependencies(), ['A', 'B', 'C']);
assert.strictEqual(providerSpec.getFunctionArg(), myFunc);
assert.equal(providerSpec.getOutputType(), 'VALUE$Date');
});
/** Validation of non-provider-specification conformance is tested in
the bootstrap-validators-test.js */ | jmccune/dxref-core | tests/unit/system/provider/provider-specification-test.js | JavaScript | mit | 685 |
version https://git-lfs.github.com/spec/v1
oid sha256:c1d57d1ad50c4639ecd398deb6c1db998e272cc6faf1314dec77ca509ca49153
size 1303
| yogeshsaroya/new-cdnjs | ajax/libs/uikit/2.10.0/js/addons/cover.min.js | JavaScript | mit | 129 |
team1 = {"name" : "Iron Patriot",
"key": "MURICA",
"puzzles" :
[{"idPz": 0}, // Breakfast
{"idPz": 1}, // Blueprints, all
{"idPz": 2}, // Morning Rotation # 1
// {"idPz": 14}, // Morning Rotation # 1 Item! (to alieviate routing issues slightly)
{"idPz": 3}, // Morning Rotation # 2
// {"idPz": 15}, // Morning Rotation # 2 Item! (to alieviate routing issues slightly)
{"idPz": 4}, // Morning Rotation # 3
// {"idPz": 16}, // Morning Rotation # 3 Item! (to alieviate routing issues slightly)
{"idPz": 5}, // Morning Rotation # 4
// {"idPz": 17}, // Morning Rotation # 4 Item! (to alieviate routing issues slightly)
{"idPz": 6}, // All together now.
{"idPz": 7}, // Lunch Time
{"idPz": 8}, // Evening Rotation # 1
{"idPz": 9}, // Evening Rotation # 2
{"idPz": 10}, // Evening Rotation # 3
{"idPz": 11}, // Evening Rotation # 4
{"idPz": 12}, // All together now (Blueprints)
{"idPz": 13}, // All together now (Final)
],
"wordweb":[],
"jarvisStream" : {},
"wordwebUnknown":[0],
"currentPuzzle" : 0,
"teamNum" : 1,
"eveningBufferIndex" : 0
}
team2 = {"name" : "War Machine",
"key": "WARMACHINEROX",
"puzzles" :
[{"idPz": 0}, // Breakfast
{"idPz": 1}, // Blueprints, all
{"idPz": 3}, // Morning Rotation # 2
// {"idPz": 15}, // Morning Rotation # 2 Item! (to alieviate routing issues slightly)
{"idPz": 4}, // Morning Rotation # 3
// {"idPz": 16}, // Morning Rotation # 3 Item! (to alieviate routing issues slightly)
{"idPz": 5}, // Morning Rotation # 4
// {"idPz": 17}, // Morning Rotation # 4 Item! (to alieviate routing issues slightly)
{"idPz": 2}, // Morning Rotation # 1
// {"idPz": 14}, // Morning Rotation # 1 Item! (to alieviate routing issues slightly)
{"idPz": 6}, // All together now.
{"idPz": 7}, // Lunch Time
{"idPz": 9}, // Evening Rotation # 2
{"idPz": 10}, // Evening Rotation # 3
{"idPz": 11}, // Evening Rotation # 4
{"idPz": 8}, // Evening Rotation # 1
{"idPz": 12}, // All together now (Blueprints)
{"idPz": 13}, // All together now (Final)
],
"wordweb":[],
"jarvisStream" : {},
"wordwebUnknown":[0],
"currentPuzzle" : 0,
"teamNum" : 2,
"eveningBufferIndex" : 0
}
team3 = {"name" : "Hulkbuster",
"key": "IRONSMASH",
"puzzles" :
[{"idPz": 0}, // Breakfast
{"idPz": 1}, // Blueprints, all
{"idPz": 4}, // Morning Rotation # 3
// {"idPz": 16}, // Morning Rotation # 3 Item! (to alieviate routing issues slightly)
{"idPz": 5}, // Morning Rotation # 4
// {"idPz": 17}, // Morning Rotation # 4 Item! (to alieviate routing issues slightly)
{"idPz": 2}, // Morning Rotation # 1
// {"idPz": 14}, // Morning Rotation # 1 Item! (to alieviate routing issues slightly)
{"idPz": 3}, // Morning Rotation # 2
// {"idPz": 15}, // Morning Rotation # 2 Item! (to alieviate routing issues slightly)
{"idPz": 6}, // All together now.
{"idPz": 7}, // Lunch Time
{"idPz": 10}, // Evening Rotation # 3
{"idPz": 11}, // Evening Rotation # 4
{"idPz": 8}, // Evening Rotation # 1
{"idPz": 9}, // Evening Rotation # 2
{"idPz": 12}, // All together now (Blueprints)
{"idPz": 13}, // All together now (Final)
],
"wordweb":[],
"jarvisStream" : {},
"wordwebUnknown":[0],
"currentPuzzle" : 0,
"teamNum" : 3,
"eveningBufferIndex" : 0
}
team4 = {"name" : "Mark I",
"key": "OLDSKOOL",
"puzzles" :
[{"idPz": 0}, // Breakfast
{"idPz": 1}, // Blueprints, all
{"idPz": 5}, // Morning Rotation # 4
// {"idPz": 17}, // Morning Rotation # 4 Item! (to alieviate routing issues slightly)
{"idPz": 2}, // Morning Rotation # 1
// {"idPz": 14}, // Morning Rotation # 1 Item! (to alieviate routing issues slightly)
{"idPz": 3}, // Morning Rotation # 2
// {"idPz": 15}, // Morning Rotation # 2 Item! (to alieviate routing issues slightly)
{"idPz": 4}, // Morning Rotation # 3
// {"idPz": 16}, // Morning Rotation # 3 Item! (to alieviate routing issues slightly)
{"idPz": 6}, // All together now.
{"idPz": 7}, // Lunch Time
{"idPz": 11}, // Evening Rotation # 4
{"idPz": 8}, // Evening Rotation # 1
{"idPz": 9}, // Evening Rotation # 2
{"idPz": 10}, // Evening Rotation # 3
{"idPz": 12}, // All together now (Blueprints)
{"idPz": 13}, // All together now (Final)
],
"wordweb":[],
"jarvisStream" : {},
"wordwebUnknown":[0],
"currentPuzzle" : 0,
"teamNum" : 4,
"eveningBufferIndex" : 0
}
allPuzzles = [{"name": "Breakfast", //0
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
// "showInput": false,
"endCondition" : {"websocket": "breakfastOver"},
// "puzzIntro": {"name": "<a href='www.skeenan.com'>Something to help, take it with you.</a>",
// ".mp3": null,
// "action": null},
"hint": [{"name": "Welcome to breakfast, relax, eat some.",
".mp3": null,
"trig": {'time': 10},
"action": null}]
},
{"name": "Blueprints", //1
"desc": "Our first Puzzle!",
"file": "./puzzles/puzzle1",
"estTime": 40,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"isStatPuzzle": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"wrong": "Did you really think that was the right answer?",
"menace": true,
"insect": true,
"pluto": true,
"cable": true
},
"puzzIntro": {"name": "Go pick up physics quizzes",
".mp3": null,
"action": null},
"hint": [{"name": "This puzzle isn't about QR codes",
// ".mp3": "./audio/puzzle1/hint1",
"trig": {'time': 60*10},
"text": "I can't see what you're doing from here, but have you tried to stack them?",
"action": null},
{"name": "Look for letters",
// ".mp3": "./audio/puzzle1/hint1",
"trig": {'time': 60*15},
"text": "I can't see what you're doing from here, but have you tried to stack them?",
"action": null},
{"name": "You can use an anagram solver if you want",
// ".mp3": "./audio/puzzle1/hint1",
"trig": {'time': 60*20},
"text": "I can't see what you're doing from here, but have you tried to stack them?",
"action": null}]
},
{"name": "The Grid", //2
"desc": "Our second Puzzle!",
"file": "./puzzles/puzzle2",
"estTime": 60,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"isStatPuzzle": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"wolverine": true},
"puzzIntro": {"name": "We need you at the Admissions conference room",
".mp3": null,
"action": null},
"hint": [{"name": "It's a Sudoku",
// ".mp3": "./audio/puzzle2/hint1",
"trig": {'time': 60*20},
"action": null},
{"name": "Oh look, semaphore!",
// ".mp3": "./audio/puzzle2/hint1",
"trig": {'time': 60*25},
"action": null},
{"name": "You should probably look at it from the side the flags are on",
// ".mp3": "./audio/puzzle2/hint1",
"trig": {'time': 60*30},
"action": null}]
},
{"name": "The Arc", //3
"desc": "Our second Puzzle!",
"file": "./puzzles/puzzle2",
"estTime": 60,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"isStatPuzzle": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"Colston": true},
"puzzIntro": {"name": "Eat",
".mp3": null,
"action": null},
"hint": []
},
{"name": "Lasers", //4
"desc": "Our second Puzzle!",
"file": "./puzzles/puzzle2",
"estTime": 60,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"isStatPuzzle": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"nefaria": true},
"puzzIntro": {"name": "Spalding sub-basement",
".mp3": null,
"action": null},
"hint": [{"name": "If you give me power, I can give you information",
// ".mp3": "./audio/puzzle2/hint1",
"trig": {'time': 60*15},
"action": null},
{"name": "The dates are important",
// ".mp3": "./audio/puzzle2/hint1",
"trig": {'time': 60*15},
"action": null},
{"name": "Have you tried putting them in order?",
// ".mp3": "./audio/puzzle2/hint1",
"trig": {'time': 60*20},
"action": null},
{"name": "More information about the songs is better (feel free to use Google)",
// ".mp3": "./audio/puzzle2/hint1",
"trig": {'time': 60*25},
"action": null}]
},
{"name": "Rebus", //5
"desc": "Our second Puzzle!",
"file": "./puzzles/puzzle2",
"estTime": 60,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"isStatPuzzle": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"Harold Hogan": true},
"puzzIntro": {"name": "Lloyd Deck",
".mp3": null,
"action": null},
"hint": [{"name": "The number of the puzzle will prove of use",
// ".mp3": "./audio/puzzle2/hint1",
"trig": {'time':60*10},
"action": null},
{"name": "index puzzle answer by puzzle number",
// ".mp3": "./audio/puzzle2/hint1",
"trig": {'time':60*15},
"action": null}]
},
{"name": "Squares", //6 - Last before lunch
"desc": "Our second Puzzle!",
"file": "./puzzles/puzzle2",
"estTime": 60,
"overlap": true,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"allSolveTogether": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"jhammer": true},
"puzzIntro": {"name": "Everyone meet at the BBB front patio",
".mp3": null,
"action": null},
"hint": []
},
{"name": "Lunch", //7 - Lunch
"desc": "Our second Puzzle!",
"file": "./puzzles/puzzle2",
"estTime": 60,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"showInput": false,
"endCondition" : {"websocket": "lunchOver"},
// "responses": {"": "You could try to give me something, anything before you press enter you know.",
// "answer": true},
// "puzzIntro": {"name": "Eat",
// ".mp3": null,
// "action": null},
"hint": []
},
{"name": "Teamwork", //8
"desc": "Our second Puzzle!",
"file": "./puzzles/puzzle2",
"estTime": 60,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"endCondition" : {"websocket": "nextAfternoonPuzzle"},
"isAfternoon" : true,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"stop hammer time!": true
},
"puzzIntro": {"name": "We need you at CDC 257",
".mp3": null,
"action": null},
"hint": []
},
{"name": "Laserz", //9
"desc": "Our second Puzzle!",
"file": "./puzzles/puzzle2",
"estTime": 60,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"endCondition" : {"websocket": "nextAfternoonPuzzle"},
"isAfternoon" : true,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"answer": true},
"puzzIntro": {"name": "Moore (070 - 2)",
".mp3": null,
"action": null},
"hint": []
},
{"name": "The Game", //10
"desc": "Our second Puzzle!",
"file": "./puzzles/puzzle2",
"estTime": 60,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"endCondition" : {"websocket": "nextAfternoonPuzzle"},
"isAfternoon" : true,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"YAYYYYYYYYYyYYYyY": true},
"puzzIntro": {"name": "A projector room close to home",
".mp3": null,
"action": null},
"hint": []
},
{"name": "The Web", //11
"desc": "Our second Puzzle!",
"file": "./puzzles/puzzle2",
"estTime": 60,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"endCondition" : {"websocket": "nextAfternoonPuzzle"},
"overlap": true,
"isAfternoon" : true,
"overlap": true,
"isWordWeb": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"answer": true},
"puzzIntro": {"name": "",
".mp3": null,
"action": null},
"hint": []
},
{"name": "Take two on Blueprints", //12
"desc": "Our second Puzzle!",
"file": "./puzzles/puzzle2",
"estTime": 60,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"allSolveTogether": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"answer": true},
// "puzzIntro": {"name": "Eat",
// ".mp3": null,
// "action": null},
"hint": []
},
{"name": "This is it", //13
"desc": "Our second Puzzle!",
"file": "./puzzles/puzzle2",
"estTime": 60,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"answer": false}, //Can't have a "correct answer" for the last puzzle, or else crash
// "puzzIntro": {"name": "Eat",
// ".mp3": null,
// "action": null},
"hint": []
},
{"name": "The Mask", //14
"desc": "Our second Puzzle!",
"file": "./puzzles/puzzle2",
"estTime": 60,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"answer": true},
// "puzzIntro": {"name": "Eat",
// ".mp3": null,
// "action": null},
"hint": []
},
{"name": "The Glove", //15
"desc": "Our second Puzzle!",
"file": "./puzzles/puzzle2",
"estTime": 60,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"answer": true},
// "puzzIntro": {"name": "Eat",
// ".mp3": null,
// "action": null},
"hint": []
},
{"name": "The Core", //16
"desc": "Our second Puzzle!",
"file": "./puzzles/puzzle2",
"estTime": 60,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"answer": true},
// "puzzIntro": {"name": "Eat",
// ".mp3": null,
// "action": null},
"hint": []
},
{"name": "The Repulsor", //17
"desc": "Our second Puzzle!",
"file": "./puzzles/puzzle2",
"estTime": 60,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"answer": true},
// "puzzIntro": {"name": "Eat",
// ".mp3": null,
// "action": null},
"hint": []
}
]
morningBuffers = [{"name": "First Square", //0
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"dues": true,
"birth": true,
"oracle": true,
"yolk": true
},
"puzzIntro": {"name": "<a href='squares/1987.jpg'>Something to help, take it with you.</a>",
".mp3": null,
"action": null},
"hint": []
},{"name": "Second Square", //1
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"unix": true,
"choose": true,
"him": true,
"graft": true
},
"puzzIntro": {"name": "<a href='squares/2631.jpg'>Something to help, take it with you.</a>",
".mp3": null,
"action": null},
"hint": []
},{"name": "Another Square", //2
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"seer": true,
"kraft": true,
"eunuchs": true
},
"puzzIntro": {"name": "<a href='squares/3237.jpg'>Something to help, take it with you.</a>",
".mp3": null,
"action": null},
"hint": []
},{"name": "The fourth", //3
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"paced": true,
"idle": true,
"paws": true,
"tea": true
},
"puzzIntro": {"name": "<a href='squares/4126.jpg'>Something to help, take it with you.</a>",
".mp3": null,
"action": null},
"hint": []
},{"name": "Num Five.", //4
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"bode": true,
"idyll": true,
"grease": true,
"laze": true
},
"puzzIntro": {"name": "<a href='squares/5346.jpg'>Something to help, take it with you.</a>",
".mp3": null,
"action": null},
"hint": []
},{"name": "Square six start", //5
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"lies": true,
"ax": true,
"tax": true,
"bask": true
},
"puzzIntro": {"name": "<a href='squares/6987.jpg'>Something to help, take it with you.</a>",
".mp3": null,
"action": null},
"hint": []
},{"name": "Square 7 begin", //6
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"ail": true,
"tacks": true,
"yolk": true
},
"puzzIntro": {"name": "<a href='squares/7123.jpg'>Something to help, take it with you.</a>",
".mp3": null,
"action": null},
"hint": []
},{"name": "Eight Squares In", //7
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"cedar": true,
"chorale": true,
"marquis": true
},
"puzzIntro": {"name": "<a href='squares/8873.jpg'>Something to help, take it with you.</a>",
".mp3": null,
"action": null},
"hint": []
},{"name": "Nine lives, nine squares", //8
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"corral": true,
"bruise": true,
"sics": true,
"pair": true
},
"puzzIntro": {"name": "<a href='squares/9314.jpg'>Something to help, take it with you.</a>",
".mp3": null,
"action": null},
"hint": []
},{"name": "Ten Four", //9
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"oohs": true,
"six": true,
"quire": true,
"stayed": true
},
"puzzIntro": {"name": "<a href='squares/10242.jpg'>Something to help, take it with you.</a>",
".mp3": null,
"action": null},
"hint": []
},{"name": "Square 11", //9
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"want": true,
"few": true,
"avricle": true
},
"puzzIntro": {"name": "<a href='squares/11235.jpg'>Something to help, take it with you.</a>",
".mp3": null,
"action": null},
"hint": []
},{"name": "A Dozen!", //9
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"pride": true,
"staid": true,
"paste": true,
"woe": true
},
"puzzIntro": {"name": "<a href='squares/12198.jpg'>Something to help, take it with you.</a>",
".mp3": null,
"action": null},
"hint": []
},{"name": "Lucky 13", //9
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"reads": true,
"place": true,
"whoa": true,
"bowed": true
},
"puzzIntro": {"name": "<a href='squares/13124.jpg'>Something to help, take it with you.</a>",
".mp3": null,
"action": null},
"hint": []
},{"name": "14 it is", //9
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"profit": true,
"yule": true,
"basque": true,
"plaice": true
},
"puzzIntro": {"name": "<a href='squares/14092.jpg'>Something to help, take it with you.</a>",
".mp3": null,
"action": null},
"hint": []
},{"name": "You're at 15!", //9
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"lichen": true,
"you'll": true,
"ale": true
},
"puzzIntro": {"name": "<a href='squares/15098.jpg'>Something to help, take it with you.</a>",
".mp3": null,
"action": null},
"hint": []
},{"name": "Sweet 16", //9
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"feeder": true,
"cere": true,
"sorted": true
},
"puzzIntro": {"name": "<a href='squares/16981.jpg'>Something to help, take it with you.</a>",
".mp3": null,
"action": null},
"hint": []
},{"name": "Boring 17", //9
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"pare": true,
"none": true,
"chews": true,
"sordid": true
},
"puzzIntro": {"name": "<a href='squares/17092.jpg'>Something to help, take it with you.</a>",
".mp3": null,
"action": null},
"hint": []
},{"name": "Old enough to go to War(machine)", //9
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"nun": true,
"cache": true,
"ooze": true,
"wave": true
},
"puzzIntro": {"name": "<a href='squares/18923.jpg'>Something to help, take it with you.</a>",
".mp3": null,
"action": null},
"hint": []
},{"name": "19", //9
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"coin": true,
"maid": true,
"pryed": true,
"waive": true
},
"puzzIntro": {"name": "<a href='squares/19238.jpg'>Something to help, take it with you.</a>",
".mp3": null,
"action": null},
"hint": []
},
{"name": "20", //9
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"plait": true,
"made": true,
"reeds": true,
"lynx": true
},
"puzzIntro": {"name": "<a href='squares/20.jpg'>Something to help, take it with you.</a>",
".mp3": null,
"action": null},
"hint": []
},
{"name": "21", //9
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"links": true,
"prophet": true,
"floes": true,
"rain": true
},
"puzzIntro": {"name": "<a href='squares/21.jpg'>Something to help, take it with you.</a>",
".mp3": null,
"action": null},
"hint": []
},
{"name": "22", //9
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"root": true,
"reign": true,
"liken": true
},
"puzzIntro": {"name": "<a href='squares/22.jpg'>Something to help, take it with you.</a>",
".mp3": null,
"action": null},
"hint": []
},
{"name": "23", //9
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"phew": true,
"crewel": true,
"tapir": true
},
"puzzIntro": {"name": "<a href='squares/23.jpg'>Something to help, take it with you.</a>",
".mp3": null,
"action": null},
"hint": []
},
{"name": "24", //9
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"taper": true,
"allowed": true
},
"puzzIntro": {"name": "<a href='squares/24.jpg'>Something to help, take it with you.</a>",
".mp3": null,
"action": null},
"hint": []
},
{"name": "25", //9
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"cents": true,
"ewe": true
},
"puzzIntro": {"name": "<a href='squares/25.jpg'>Something to help, take it with you.</a>",
".mp3": null,
"action": null},
"hint": []
},{"name": "26", //9
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"jewel": true,
"whore": true,
"sense": true
},
"puzzIntro": {"name": "<a href='squares/26.jpg'>Something to help, take it with you.</a>",
".mp3": null,
"action": null},
"hint": []
},{"name": "27", //9
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"cyclet": true,
"liar": true,
"joule": true
},
"puzzIntro": {"name": "<a href='squares/27.jpg'>Something to help, take it with you.</a>",
".mp3": null,
"action": null},
"hint": []
},{"name": "28", //9
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"mood": true,
"pause": true,
"islet": true
},
"puzzIntro": {"name": "<a href='squares/28.jpg'>Something to help, take it with you.</a>",
".mp3": null,
"action": null},
"hint": []
},{"name": "29", //9
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"epoch": true,
"phlox": true,
"want": true
},
"puzzIntro": {"name": "<a href='squares/29.jpg'>Something to help, take it with you.</a>",
".mp3": null,
"action": null},
"hint": []
},{"name": "30", //9
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"mooed": true,
"Greece": true,
"word": true
},
"puzzIntro": {"name": "<a href='squares/30.jpg'>Something to help, take it with you.</a>",
".mp3": null,
"action": null},
"hint": []
},{"name": "31", //9
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"acts": true,
"whirred": true,
"palate": true
},
"puzzIntro": {"name": "<a href='squares/31.jpg'>Something to help, take it with you.</a>",
".mp3": null,
"action": null},
"hint": []
},{"name": "32", //9
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"maize": true,
"pallette": true
},
"puzzIntro": {"name": "<a href='squares/32.jpg'>Something to help, take it with you.</a>",
".mp3": null,
"action": null},
"hint": []
},{"name": "33", //9
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"you": true,
"sine": true,
"marqaee": true
},
"puzzIntro": {"name": "<a href='squares/33.jpg'>Something to help, take it with you.</a>",
".mp3": null,
"action": null},
"hint": []
},{"name": "34", //9
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"brews": true,
"massed": true,
"hoar": true,
"sign": true
},
"puzzIntro": {"name": "<a href='squares/34.jpg'>Something to help, take it with you.</a>",
".mp3": null,
"action": null},
"hint": []
},{"name": "35", //9
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"potpourri": true,
"doe": true,
"epic": true
},
"puzzIntro": {"name": "<a href='squares/35.jpg'>Something to help, take it with you.</a>",
".mp3": null,
"action": null},
"hint": []
},{"name": "36", //9
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"rabbit": true,
"rose": true,
"popery": true
},
"puzzIntro": {"name": "<a href='squares/36.jpg'>Something to help, take it with you.</a>",
".mp3": null,
"action": null},
"hint": []
},{"name": "37", //9
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"rabbet": true,
"illicit": true
},
"puzzIntro": {"name": "<a href='squares/37.jpg'>Something to help, take it with you.</a>",
".mp3": null,
"action": null},
"hint": []
} ]
eveningBuffers = [{"name": "To Find", //0
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"showInput": false,
"endCondition" : {"websocket": "breakfastOver"},
"puzzIntro": {"name": "<a href='www.skeenan.com'>Something to help, take it with you.</a>",
".mp3": null,
"action": null},
"hint": []
}]
morningBufferIndex = 0
stats = {}
adminSockets = {sockets: []};
teams = [team1, team2, team3, team4];
function initTeams() {
for (var team in teams) {
teams[team].aboutToStart = 0;
teams[team].sockets = [];
for (var aPuzzle in teams[team].puzzles) {
aPuzzle = teams[team].puzzles[aPuzzle];
aPuzzle.puzzle = allPuzzles[aPuzzle.idPz];
aPuzzle.startTime = null;
aPuzzle.elapsed = null;
aPuzzle.hints = [];
}
startPuzzle(teams[team])
}
}
function reloadAllPuzzles(){
for (var team in teams) {
for (var aPuzzle in teams[team].puzzles) {
aPuzzle = teams[team].puzzles[aPuzzle];
aPuzzle.puzzle = allPuzzles[aPuzzle.idPz];
}
}
}
function startPuzzle(team) {
//Init Jarvis stream
team.jarvisStream[team.currentPuzzle] = {"name": team.puzzles[team.currentPuzzle].puzzle.name, "desc": team.puzzles[team.currentPuzzle].puzzle.desc, "data": []}
var nextIntro = team.puzzles[team.currentPuzzle].puzzle.puzzIntro
if (team.puzzles[team.currentPuzzle].puzzIntro){
nextIntro = team.puzzles[team.currentPuzzle].puzzIntro
}
if (nextIntro){
newJarvisMessageOut(team, nextIntro)
}
if (team.puzzles[team.currentPuzzle].puzzle.name === "Squares"){
for (var i = morningBufferIndex; i < morningBuffers.length; i++) {
newJarvisMessageOut(team, morningBuffers[i].puzzIntro)
};
}
if (team.puzzles[team.currentPuzzle].puzzle.name === "Lunch"){
morningBufferIndex = morningBuffers.length
}
startPuzzleTimer(team)
}
function resaveAllTeams(){
//Save all the teams
}
function logNewStat(team, statName, value, isIncrement){
// if (!stats[statName]){
// stats[statName] = {1: 0, 2: 0, 3: 0, 4: 0}
// }
// if (isIncrement){
// stats[statName][team.teamNum] += value
// } else {
// stats[statName][team.teamNum] = value
// }
// updateAllCompetitionData()
}
function logStatsOnTime(team){
if (team.puzzles[team.currentPuzzle].puzzle.isStatPuzzle){
logNewStat(team, team.puzzles[team.currentPuzzle].puzzle.name + " time", Math.floor(team.puzzles[team.currentPuzzle].elapsed/60), false)
}
}
function startNextPuzzle(team){
logStatsOnTime(team)
team.puzzles[team.currentPuzzle].puzzle.isActive = false
if (team.currentPuzzle === -1) {
team.currentPuzzle = team.lastPuzzleIndex
}
if (team.puzzles[team.currentPuzzle + 1].puzzle.overlap || !team.puzzles[team.currentPuzzle + 1].puzzle.isActive) {
if (team.puzzles[team.currentPuzzle].puzzle.isWordWeb){
emitToAllTeams(team, "bootOffWeb", true)
}
team.currentPuzzle ++
team.puzzles[team.currentPuzzle].puzzle.isActive = true
} else {
team.lastPuzzleIndex = team.currentPuzzle
team.currentPuzzle = -1
team.puzzles[-1] = {}
team.puzzles[-1].puzzle = getNextBuffer(team)
}
startPuzzle(team)
}
function getNextBuffer(team){
if (morningBufferIndex < morningBuffers.length){
logNewStat(team, "Pieces Found", 1, true)
output = morningBuffers[morningBufferIndex]
morningBufferIndex ++
return output
} else {
// I'm just going to assume that we're in the afternoon
// if (team.eveningBufferIndex < eveningBuffers.length){
// output = eveningBuffers[team.eveningBufferIndex]
// team.eveningBufferIndex ++
// return output
// } else {
return {"name": "Error finding next puzzle. Let's say SEGFAULT",
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"answer": true}}
// }
}
}
function startPuzzleTimer(team){
if (team.timer == null){
team.puzzles[team.currentPuzzle].elapsed = 0;
team.timer = function(){
if (typeof this.puzzles[this.currentPuzzle].elapsed === 'undefined'){
return;
}
this.puzzles[this.currentPuzzle].elapsed ++;
emitToAllTeams(this, 'tick', {'elapsed' : this.puzzles[this.currentPuzzle].elapsed})
checkPuzzTimerHints(this);
}
var myVar=setInterval(function(){team.timer()},1000);
}
team.puzzles[team.currentPuzzle].start
}
function checkPuzzTimerHints(team){
var outHint = null;
var puzzHints = allPuzzles[team.currentPuzzle].hint;
// var outHintIndex = 0;
var isUpdated = false;
for (var hint in puzzHints){
if (puzzHints[hint].trig.time != null &&
puzzHints[hint].trig.time == team.puzzles[team.currentPuzzle].elapsed) {
outHint = puzzHints[hint];
isUpdated = true;
// isUpdated = (isUpdated || (hint != oldHints[outHintIndex]));
// outHintIndex ++;
}
}
if (isUpdated){
newJarvisMessageOut(team, outHint)
}
}
function sendAllPuzzleData(team){
//TODO: Send all relevant puzzle data, how do we make sure client only
// renders the most recent hint?
var puzzleOut = constructAllPuzzleData(team);
emitToAllTeams(team, 'jarvisUpdate', puzzleOut)
emitToAllTeams(adminSockets, 'jarvisUpdate', puzzleOut)
}
function constructAllPuzzleData(team){
out = {};
out.name = team.name
out.currentPuzzle = team.currentPuzzle
out.currentPuzzleName = team.puzzles[team.currentPuzzle].puzzle.name
out.jarvisStream = team.jarvisStream
out.teamNum = team.teamNum
out.showInput = team.puzzles[team.currentPuzzle].puzzle.showInput
out.stats = stats
return out
}
function updateAllCompetitionData(){
try{
var puzzleOut = {}
for (team in teams){
team = teams[team]
puzzleOut = constructAllPuzzleData(team);
emitToAllTeams(team, 'compUpdate', puzzleOut)
}
emitToAllTeams(adminSockets, 'jarvisUpdate', puzzleOut)
} catch (err) {
console.log(err)
}
}
function newJarvisMessageOut(team, message){
team.jarvisStream[team.currentPuzzle].data.push(message);
// TODO: Persist!
sendAllPuzzleData(team);
emitToAllTeams(team, 'jarvisMessage', message)
}
if (teams[0].sockets == null) {
initTeams()
}
reloadAllPuzzles();
module.exports.teams = teams;
module.exports.allPuzzles = allPuzzles;
module.exports.reloadAllPuzzles = reloadAllPuzzles;
module.exports.resaveAllTeams = resaveAllTeams;
module.exports.startPuzzle = startPuzzle;
module.exports.startNextPuzzle = startNextPuzzle;
module.exports.sendAllPuzzleData = sendAllPuzzleData;
module.exports.emitToAllTeams = emitToAllTeams;
module.exports.constructAllPuzzleData = constructAllPuzzleData;
module.exports.adminSockets = adminSockets;
module.exports.newJarvisMessageOut = newJarvisMessageOut;
module.exports.stats = stats;
module.exports.logNewStat = logNewStat;
| sean9keenan/WordWeb | backend/puzzles.js | JavaScript | mit | 48,757 |
import Off from './Off';
import On from './On';
// ==============================
// CONCRETE CONTEXT
// ==============================
export default class Computer {
constructor() {
this._currentState = null;
this._states = {
off: new Off(),
on: new On()
};
}
power() {
this._currentState.power(this);
}
getCurrentState() {
return this._currentState;
}
setCurrentState(state) {
this._currentState = state;
}
getStates() {
return this._states;
}
}
| Badacadabra/PatternifyJS | GoF/classic/Behavioral/State/ECMAScript/ES6/API/Computer.js | JavaScript | mit | 579 |
var dir_f4703b3db1bd5f8d2d3fca771c570947 =
[
[ "led.c", "led_8c.html", "led_8c" ],
[ "tick.c", "tick_8c.html", "tick_8c" ],
[ "usart2.c", "usart2_8c.html", "usart2_8c" ]
]; | hedrickbt/TempSensor | firmware/Temperature/Documents/Code_Document/html/dir_f4703b3db1bd5f8d2d3fca771c570947.js | JavaScript | mit | 184 |
import { h } from 'omi';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(h(h.f, null, h("circle", {
cx: "7.2",
cy: "14.4",
r: "3.2"
}), h("circle", {
cx: "14.8",
cy: "18",
r: "2"
}), h("circle", {
cx: "15.2",
cy: "8.8",
r: "4.8"
})), 'BubbleChart'); | AlloyTeam/Nuclear | components/icon/esm/bubble-chart.js | JavaScript | mit | 299 |
var Nightmare = require('nightmare')
var NTU = require('./NightmareTestUtils')
const NounPhraseTest = (nightmare, delay) => {
return nightmare
// Can I open the addedit form and make it go away by clicking cancel?
.click('#add-np').wait(delay)
.click('#np-addedit-form #cancel').wait(delay)
.then( res => {return NTU.lookFor(nightmare, '#np-addedit-form', false)})
// If I open the addedit form, enter and a save a noun,
// will the form then go away and can I see the insertNounPhraseCheck mark in the quiz?
/*.then( res => {
return nightmare
.click('#add-np').wait(delay)
.type('#base', 'carrot').wait(delay)
.click('#save-np').wait(delay)
})
.then( res => {return NTU.lookFor(nightmare, '#np-addedit-form', false)})
.then( res => {return NTU.lookFor(nightmare, '#insertNounPhraseCheck', true)})
// Can I open the addedit form via editing and make it go away by clicking cancel?
.then( res => {
return nightmare
.click('#id1').wait(delay)
.click('#cancel').wait(delay)
})
.then( res => {return NTU.lookFor(nightmare, '#np-addedit-form', false)})
// If I open the addedit form via editing, change and a save a noun,
// will the form then go away and can I see the updateNounPhraseCheck mark in the quiz?
.then( res => {
return nightmare
.click('#id1').wait(delay)
.type('#base', 'beaver').wait(delay)
.click('#save-np').wait(delay)
})
.then( res => {return NTU.lookFor(nightmare, '#np-addedit-form', false)})
.then( res => {return NTU.lookFor(nightmare, '#updateNounPhraseCheck', true)})
// If I open the addedit form via editing and delete the noun,
// will the form then go away and can I see the deleteNounPhraseCheck mark in the quiz?
.then( res => {
return nightmare
.click('#id1').wait(delay)
.click('#delete-np').wait(delay)
})
.then( res => {return NTU.lookFor(nightmare, '#np-addedit-form', false)})
.then( res => {return NTU.lookFor(nightmare, '#deleteNounPhraseCheck', true)})
//.then( res => {return NTU.lookFor(nightmare, '#quiz', false)})
.then( res => {
return nightmare
.click('#add-np').wait(delay)
.type('#base', 'carrot').wait(delay)
.click('#save-np').wait(delay)
})*/
// Can I see the examples button?
//.then( res => {return NTU.lookFor(nightmare, '#examples', true)})
// Does it go away after I click it?
//.then( res => {return nightmare.click('#examples')})
//.then( res => {return NTU.lookFor(nightmare, '#examples', false)})
}
module.exports = NounPhraseTest
| bostontrader/senmaker | src/nightmare/NounPhraseTest.js | JavaScript | mit | 2,952 |
import { UIPanel, UIRow, UIHorizontalRule } from './libs/ui.js';
import { AddObjectCommand } from './commands/AddObjectCommand.js';
import { RemoveObjectCommand } from './commands/RemoveObjectCommand.js';
import { MultiCmdsCommand } from './commands/MultiCmdsCommand.js';
import { SetMaterialValueCommand } from './commands/SetMaterialValueCommand.js';
function MenubarEdit( editor ) {
var strings = editor.strings;
var container = new UIPanel();
container.setClass( 'menu' );
var title = new UIPanel();
title.setClass( 'title' );
title.setTextContent( strings.getKey( 'menubar/edit' ) );
container.add( title );
var options = new UIPanel();
options.setClass( 'options' );
container.add( options );
// Undo
var undo = new UIRow();
undo.setClass( 'option' );
undo.setTextContent( strings.getKey( 'menubar/edit/undo' ) );
undo.onClick( function () {
editor.undo();
} );
options.add( undo );
// Redo
var redo = new UIRow();
redo.setClass( 'option' );
redo.setTextContent( strings.getKey( 'menubar/edit/redo' ) );
redo.onClick( function () {
editor.redo();
} );
options.add( redo );
// Clear History
var option = new UIRow();
option.setClass( 'option' );
option.setTextContent( strings.getKey( 'menubar/edit/clear_history' ) );
option.onClick( function () {
if ( confirm( 'The Undo/Redo History will be cleared. Are you sure?' ) ) {
editor.history.clear();
}
} );
options.add( option );
editor.signals.historyChanged.add( function () {
var history = editor.history;
undo.setClass( 'option' );
redo.setClass( 'option' );
if ( history.undos.length == 0 ) {
undo.setClass( 'inactive' );
}
if ( history.redos.length == 0 ) {
redo.setClass( 'inactive' );
}
} );
// ---
options.add( new UIHorizontalRule() );
// Clone
var option = new UIRow();
option.setClass( 'option' );
option.setTextContent( strings.getKey( 'menubar/edit/clone' ) );
option.onClick( function () {
var object = editor.selected;
if ( object.parent === null ) return; // avoid cloning the camera or scene
object = object.clone();
editor.execute( new AddObjectCommand( editor, object ) );
} );
options.add( option );
// Delete
var option = new UIRow();
option.setClass( 'option' );
option.setTextContent( strings.getKey( 'menubar/edit/delete' ) );
option.onClick( function () {
var object = editor.selected;
if ( object !== null && object.parent !== null ) {
editor.execute( new RemoveObjectCommand( editor, object ) );
}
} );
options.add( option );
// Minify shaders
var option = new UIRow();
option.setClass( 'option' );
option.setTextContent( strings.getKey( 'menubar/edit/minify_shaders' ) );
option.onClick( function () {
var root = editor.selected || editor.scene;
var errors = [];
var nMaterialsChanged = 0;
var path = [];
function getPath( object ) {
path.length = 0;
var parent = object.parent;
if ( parent !== undefined ) getPath( parent );
path.push( object.name || object.uuid );
return path;
}
var cmds = [];
root.traverse( function ( object ) {
var material = object.material;
if ( material !== undefined && material.isShaderMaterial ) {
try {
var shader = glslprep.minifyGlsl( [
material.vertexShader, material.fragmentShader ] );
cmds.push( new SetMaterialValueCommand( editor, object, 'vertexShader', shader[ 0 ] ) );
cmds.push( new SetMaterialValueCommand( editor, object, 'fragmentShader', shader[ 1 ] ) );
++ nMaterialsChanged;
} catch ( e ) {
var path = getPath( object ).join( "/" );
if ( e instanceof glslprep.SyntaxError )
errors.push( path + ":" +
e.line + ":" + e.column + ": " + e.message );
else {
errors.push( path +
": Unexpected error (see console for details)." );
console.error( e.stack || e );
}
}
}
} );
if ( nMaterialsChanged > 0 ) {
editor.execute( new MultiCmdsCommand( editor, cmds ), 'Minify Shaders' );
}
window.alert( nMaterialsChanged +
" material(s) were changed.\n" + errors.join( "\n" ) );
} );
options.add( option );
options.add( new UIHorizontalRule() );
// Set textures to sRGB. See #15903
var option = new UIRow();
option.setClass( 'option' );
option.setTextContent( strings.getKey( 'menubar/edit/fixcolormaps' ) );
option.onClick( function () {
editor.scene.traverse( fixColorMap );
} );
options.add( option );
var colorMaps = [ 'map', 'envMap', 'emissiveMap' ];
function fixColorMap( obj ) {
var material = obj.material;
if ( material !== undefined ) {
if ( Array.isArray( material ) === true ) {
for ( var i = 0; i < material.length; i ++ ) {
fixMaterial( material[ i ] );
}
} else {
fixMaterial( material );
}
editor.signals.sceneGraphChanged.dispatch();
}
}
function fixMaterial( material ) {
var needsUpdate = material.needsUpdate;
for ( var i = 0; i < colorMaps.length; i ++ ) {
var map = material[ colorMaps[ i ] ];
if ( map ) {
map.encoding = THREE.sRGBEncoding;
needsUpdate = true;
}
}
material.needsUpdate = needsUpdate;
}
return container;
}
export { MenubarEdit };
| fraguada/three.js | editor/js/Menubar.Edit.js | JavaScript | mit | 5,225 |
import React from 'react';
class Icon extends React.Component {
constructor(props) {
super(props);
this.displayName = 'Icon';
this.icon = "fa " + this.props.icon + " " + this.props.size;
}
render() {
return (
<i className={this.icon}></i>
);
}
}
export default Icon;
| evilfaust/lyceum9sass | scripts/components/ui/icon.js | JavaScript | mit | 330 |
module.exports={A:{A:{"2":"L H G E A B jB"},B:{"1":"8","2":"C D e K I N J"},C:{"1":"DB EB O GB HB","2":"0 1 2 3 4 5 7 9 gB BB F L H G E A B C D e K I N J P Q R S T U V W X Y Z a b c d f g h i j k l m n o M q r s t u v w x y z JB IB CB aB ZB"},D:{"1":"8 HB TB PB NB mB OB LB QB RB","2":"0 1 2 3 4 5 7 9 F L H G E A B C D e K I N J P Q R S T U V W X Y Z a b c d f g h i j k l m n o M q r s t u v w x y z JB IB CB DB EB O GB"},E:{"1":"6 C D p bB","2":"4 F L H G E A SB KB UB VB WB XB YB","132":"B"},F:{"1":"0 1 2 3 z","2":"5 6 7 E B C K I N J P Q R S T U V W X Y Z a b c d f g h i j k l m n o M q r s t u v w x y cB dB eB fB p AB hB"},G:{"1":"D tB uB vB","2":"G KB iB FB kB lB MB nB oB pB qB rB","132":"sB"},H:{"2":"wB"},I:{"1":"O","2":"BB F xB yB zB 0B FB 1B 2B"},J:{"2":"H A"},K:{"2":"6 A B C M p AB"},L:{"1":"LB"},M:{"1":"O"},N:{"2":"A B"},O:{"2":"3B"},P:{"2":"F 4B 5B 6B 7B 8B"},Q:{"2":"9B"},R:{"2":"AC"},S:{"2":"BC"}},B:7,C:"CSS Environment Variables env()"};
| Dans-labs/dariah | client/node_modules/caniuse-lite/data/features/css-env-function.js | JavaScript | mit | 962 |
import './init'
import React from 'react'
import ReactDom from 'react-dom'
import Root from './root'
import {APP_THEMES_LIGHT, APP_THEMES_DARK} from 'reducers/settings/constants'
import LocalStorage from 'lib/localStorage'
import {initializeStore} from './redux/store'
import {initServiceWorker} from './swWindow'
// render app
const renderApp = (Component, appRoot, store) => {
initServiceWorker(store)
ReactDom.render(
<Component store={store} />,
appRoot, () => {
// need to make this for feature tests - application ready for testing
window.__isAppReady = true
})
}
const prepareStoreData = () => {
let theme = LocalStorage.getItem('theme')
if (!theme) {
if (window.matchMedia('(prefers-color-scheme: dark)')?.matches) {
theme = APP_THEMES_DARK
}
}
return {
settings: {
theme: theme || APP_THEMES_LIGHT
}
}
}
// init store and start app
const appRoot = document.getElementById('app-root')
const store = initializeStore(prepareStoreData())
renderApp(Root, appRoot, store)
| le0pard/pgtune | assets/app.js | JavaScript | mit | 1,045 |
/**
* @author Kai Salmen / www.kaisalmen.de
*/
'use strict';
if ( KSX.test.projectionspace === undefined ) KSX.test.projectionspace = {};
KSX.test.projectionspace.VerifyPP = (function () {
PPCheck.prototype = Object.create(KSX.core.ThreeJsApp.prototype, {
constructor: {
configurable: true,
enumerable: true,
value: PPCheck,
writable: true
}
});
function PPCheck(elementToBindTo, loader) {
KSX.core.ThreeJsApp.call(this);
this.configure({
name: 'PPCheck',
htmlCanvas: elementToBindTo,
useScenePerspective: true,
loader: loader
});
this.controls = null;
this.projectionSpace = new KSX.instancing.ProjectionSpace({
low: { index: 0, name: 'Low', x: 240, y: 100, defaultHeightFactor: 9, mesh: null },
medium: { index: 1, name: 'Medium', x: 720, y: 302, defaultHeightFactor: 18, mesh: null }
}, 0);
this.cameraDefaults = {
posCamera: new THREE.Vector3( 300, 300, 300 ),
far: 100000
};
}
PPCheck.prototype.initPreGL = function() {
var scope = this;
var callbackOnSuccess = function () {
scope.preloadDone = true;
};
scope.projectionSpace.loadAsyncResources( callbackOnSuccess );
};
PPCheck.prototype.initGL = function () {
this.projectionSpace.initGL();
this.projectionSpace.flipTexture( 'linkPixelProtest' );
this.scenePerspective.scene.add( this.projectionSpace.dimensions[this.projectionSpace.index].mesh );
this.scenePerspective.setCameraDefaults( this.cameraDefaults );
this.controls = new THREE.TrackballControls( this.scenePerspective.camera );
};
PPCheck.prototype.resizeDisplayGL = function () {
this.controls.handleResize();
};
PPCheck.prototype.renderPre = function () {
this.controls.update();
};
return PPCheck;
})();
| kaisalmen/kaisalmen.de | test/projectionspace/VerifyPP.js | JavaScript | mit | 2,021 |
import test from 'ava'
import Vue from 'vue'
import {createRenderer} from 'vue-server-renderer'
import ContentPlaceholder from '../src'
test.cb('ssr', t => {
const rows = [{height: '5px', boxes: [[0, '40px']]}]
const renderer = createRenderer()
const app = new Vue({
template: '<content-placeholder :rows="rows"></content-placeholder>',
components: {ContentPlaceholder},
data: {rows}
})
renderer.renderToString(app, (err, html) => {
t.falsy(err)
t.true(html.includes('data-server-rendered'))
t.end()
})
})
| StevenYuysy/vue-content-placeholder | test/ssr.spec.js | JavaScript | mit | 543 |
import { dealsService } from '../services';
const fetchDealsData = () => {
return dealsService().getDeals()
.then(res => {
return res.data
})
// Returning [] as a placeholder now so it does not error out when this service
// fails. We should be handling this in our DISPATCH_REQUEST_FAILURE
.catch(() => []);
};
export default fetchDealsData;
| mohammed52/something.pk | app/fetch-data/fetchDealsData.js | JavaScript | mit | 374 |
import { createPlugin } from 'draft-extend';
// TODO(mime): can't we just use LINK? i forget why we're using ANCHOR separately..., something with images probably :-/
const ENTITY_TYPE = 'ANCHOR';
// TODO(mime): one day, maybe switch wholesale to draft-extend. for now, we have a weird hybrid
// of draft-extend/draft-convert/draft-js-plugins
export default createPlugin({
htmlToEntity: (nodeName, node, create) => {
if (nodeName === 'a') {
const mutable = node.firstElementChild?.nodeName === 'IMG' ? 'IMMUTABLE' : 'MUTABLE';
const { href, target } = node;
return create(ENTITY_TYPE, mutable, { href, target });
}
},
entityToHTML: (entity, originalText) => {
if (entity.type === ENTITY_TYPE) {
const { href } = entity.data;
return `<a href="${href}" target="_blank" rel="noopener noreferrer">${originalText}</a>`;
}
return originalText;
},
});
export const AnchorDecorator = (props) => {
const { href } = props.contentState.getEntity(props.entityKey).getData();
return (
<a href={href} target="_blank" rel="noopener noreferrer">
{props.children}
</a>
);
};
export function anchorStrategy(contentBlock, callback, contentState) {
contentBlock.findEntityRanges((character) => {
const entityKey = character.getEntity();
return entityKey !== null && contentState.getEntity(entityKey).getType() === ENTITY_TYPE;
}, callback);
}
| mimecuvalo/helloworld | packages/hello-world-editor/plugins/Anchor.js | JavaScript | mit | 1,418 |
'use strict';
var assert = require('../../helpers/assert');
var commandOptions = require('../../factories/command-options');
var stub = require('../../helpers/stub').stub;
var Promise = require('../../../lib/ext/promise');
var Task = require('../../../lib/models/task');
var TestCommand = require('../../../lib/commands/test');
describe('test command', function() {
var tasks;
var options;
var buildRun;
var testRun;
beforeEach(function(){
tasks = {
Build: Task.extend(),
Test: Task.extend()
};
options = commandOptions({
tasks: tasks,
testing: true
});
stub(tasks.Test.prototype, 'run', Promise.resolve());
stub(tasks.Build.prototype, 'run', Promise.resolve());
buildRun = tasks.Build.prototype.run;
testRun = tasks.Test.prototype.run;
});
it('builds and runs test', function() {
return new TestCommand(options).validateAndRun([]).then(function() {
assert.equal(buildRun.called, 1, 'expected build task to be called once');
assert.equal(testRun.called, 1, 'expected test task to be called once');
});
});
it('has the correct options', function() {
return new TestCommand(options).validateAndRun([]).then(function() {
var buildOptions = buildRun.calledWith[0][0];
var testOptions = testRun.calledWith[0][0];
assert.equal(buildOptions.environment, 'development', 'has correct env');
assert.ok(buildOptions.outputPath, 'has outputPath');
assert.equal(testOptions.configFile, './testem.json', 'has config file');
assert.equal(testOptions.port, 7357, 'has config file');
});
});
it('passes through custom configFile option', function() {
return new TestCommand(options).validateAndRun(['--config-file=some-random/path.json']).then(function() {
var testOptions = testRun.calledWith[0][0];
assert.equal(testOptions.configFile, 'some-random/path.json');
});
});
it('passes through custom port option', function() {
return new TestCommand(options).validateAndRun(['--port=5678']).then(function() {
var testOptions = testRun.calledWith[0][0];
assert.equal(testOptions.port, 5678);
});
});
});
| rwjblue/ember-cli | tests/unit/commands/test-test.js | JavaScript | mit | 2,241 |
import Vector from '../prototype'
import {componentOrder, allComponents} from './components'
export const withInvertedCurryingSupport = f => {
const curried = right => left => f(left, right)
return (first, second) => {
if (second === undefined) {
// check for function to allow usage by the pipeline function
if (Array.isArray(first) && first.length === 2 && !(first[0] instanceof Function) && !(first[0] instanceof Number)) {
return f(first[0], first[1])
}
// curried form uses the given single parameter as the right value for the operation f
return curried(first)
}
return f(first, second)
}
}
export const skipUndefinedArguments = (f, defaultValue) => (a, b) => a === undefined || b === undefined
? defaultValue
: f(a, b)
export const clone = v => {
if (Array.isArray(v)) {
const obj = Object.create(Vector.prototype)
v.forEach((value, i) => {
obj[allComponents[i]] = value
})
return [...v]
}
const prototype = Object.getPrototypeOf(v)
return Object.assign(Object.create(prototype === Object.prototype ? Vector.prototype : prototype), v)
}
| senritsu/grid-utils | vector/util/misc.js | JavaScript | mit | 1,138 |
module.exports = function() {
return {
server: {
src: ['<%= tmp %>/index.html'],
ignorePath: /\.\.\//
}
}
};
| genu/lowkey | grunt/wiredep.js | JavaScript | mit | 133 |
'use strict';
angular.module('mpApp')
.factory(
'preloader',
function($q, $rootScope) {
// I manage the preloading of image objects. Accepts an array of image URLs.
function Preloader(imageLocations) {
// I am the image SRC values to preload.
this.imageLocations = imageLocations;
// As the images load, we'll need to keep track of the load/error
// counts when announing the progress on the loading.
this.imageCount = this.imageLocations.length;
this.loadCount = 0;
this.errorCount = 0;
// I am the possible states that the preloader can be in.
this.states = {
PENDING: 1,
LOADING: 2,
RESOLVED: 3,
REJECTED: 4
};
// I keep track of the current state of the preloader.
this.state = this.states.PENDING;
// When loading the images, a promise will be returned to indicate
// when the loading has completed (and / or progressed).
this.deferred = $q.defer();
this.promise = this.deferred.promise;
}
// ---
// STATIC METHODS.
// ---
// I reload the given images [Array] and return a promise. The promise
// will be resolved with the array of image locations. 111111
Preloader.preloadImages = function(imageLocations) {
var preloader = new Preloader(imageLocations);
return (preloader.load());
};
// ---
// INSTANCE METHODS.
// ---
Preloader.prototype = {
// Best practice for "instnceof" operator.
constructor: Preloader,
// ---
// PUBLIC METHODS.
// ---
// I determine if the preloader has started loading images yet.
isInitiated: function isInitiated() {
return (this.state !== this.states.PENDING);
},
// I determine if the preloader has failed to load all of the images.
isRejected: function isRejected() {
return (this.state === this.states.REJECTED);
},
// I determine if the preloader has successfully loaded all of the images.
isResolved: function isResolved() {
return (this.state === this.states.RESOLVED);
},
// I initiate the preload of the images. Returns a promise. 222
load: function load() {
// If the images are already loading, return the existing promise.
if (this.isInitiated()) {
return (this.promise);
}
this.state = this.states.LOADING;
for (var i = 0; i < this.imageCount; i++) {
this.loadImageLocation(this.imageLocations[i]);
}
// Return the deferred promise for the load event.
return (this.promise);
},
// ---
// PRIVATE METHODS.
// ---
// I handle the load-failure of the given image location.
handleImageError: function handleImageError(imageLocation) {
this.errorCount++;
// If the preload action has already failed, ignore further action.
if (this.isRejected()) {
return;
}
this.state = this.states.REJECTED;
this.deferred.reject(imageLocation);
},
// I handle the load-success of the given image location.
handleImageLoad: function handleImageLoad(imageLocation) {
this.loadCount++;
// If the preload action has already failed, ignore further action.
if (this.isRejected()) {
return;
}
// Notify the progress of the overall deferred. This is different
// than Resolving the deferred - you can call notify many times
// before the ultimate resolution (or rejection) of the deferred.
this.deferred.notify({
percent: Math.ceil(this.loadCount / this.imageCount * 100),
imageLocation: imageLocation
});
// If all of the images have loaded, we can resolve the deferred
// value that we returned to the calling context.
if (this.loadCount === this.imageCount) {
this.state = this.states.RESOLVED;
this.deferred.resolve(this.imageLocations);
}
},
// I load the given image location and then wire the load / error
// events back into the preloader instance.
// --
// NOTE: The load/error events trigger a $digest. 333
loadImageLocation: function loadImageLocation(imageLocation) {
var preloader = this;
// When it comes to creating the image object, it is critical that
// we bind the event handlers BEFORE we actually set the image
// source. Failure to do so will prevent the events from proper
// triggering in some browsers.
var image = angular.element(new Image())
.bind('load', function(event) {
// Since the load event is asynchronous, we have to
// tell AngularJS that something changed.
$rootScope.$apply(
function() {
preloader.handleImageLoad(event.target.src);
// Clean up object reference to help with the
// garbage collection in the closure.
preloader = image = event = null;
}
);
})
.bind('error', function(event) {
// Since the load event is asynchronous, we have to
// tell AngularJS that something changed.
$rootScope.$apply(
function() {
preloader.handleImageError(event.target.src);
// Clean up object reference to help with the
// garbage collection in the closure.
preloader = image = event = null;
}
);
})
.attr('src', imageLocation);
}
};
// Return the factory instance.
return (Preloader);
}
);
| 59023g/mpdotcom | app/scripts/services/preloader.js | JavaScript | mit | 6,121 |
var gulp = require('gulp');
gulp.task('dist', ['setProduction', 'sass:dist', 'browserify:dist']);
| wearemechanic/generator-mechanic | app/templates/gulp/tasks/dist.js | JavaScript | mit | 99 |
/*
json2.js
2013-05-26
Public Domain.
NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
See http://www.JSON.org/js.html
This code should be minified before deployment.
See http://javascript.crockford.com/jsmin.html
USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
NOT CONTROL.
This file creates a global JSON object containing two methods: stringify
and parse.
JSON.stringify(value, replacer, space)
value any JavaScript value, usually an object or array.
replacer an optional parameter that determines how object
values are stringified for objects. It can be a
function or an array of strings.
space an optional parameter that specifies the indentation
of nested structures. If it is omitted, the text will
be packed without extra whitespace. If it is a number,
it will specify the number of spaces to indent at each
level. If it is a string (such as '\t' or ' '),
it contains the characters used to indent at each level.
This method produces a JSON text from a JavaScript value.
When an object value is found, if the object contains a toJSON
method, its toJSON method will be called and the result will be
stringified. A toJSON method does not serialize: it returns the
value represented by the name/value pair that should be serialized,
or undefined if nothing should be serialized. The toJSON method
will be passed the key associated with the value, and this will be
bound to the value
For example, this would serialize Dates as ISO strings.
Date.prototype.toJSON = function (key) {
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
return this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z';
};
You can provide an optional replacer method. It will be passed the
key and value of each member, with this bound to the containing
object. The value that is returned from your method will be
serialized. If your method returns undefined, then the member will
be excluded from the serialization.
If the replacer parameter is an array of strings, then it will be
used to select the members to be serialized. It filters the results
such that only members with keys listed in the replacer array are
stringified.
Values that do not have JSON representations, such as undefined or
functions, will not be serialized. Such values in objects will be
dropped; in arrays they will be replaced with null. You can use
a replacer function to replace those with JSON values.
JSON.stringify(undefined) returns undefined.
The optional space parameter produces a stringification of the
value that is filled with line breaks and indentation to make it
easier to read.
If the space parameter is a non-empty string, then that string will
be used for indentation. If the space parameter is a number, then
the indentation will be that many spaces.
Example:
text = JSON.stringify(['e', {pluribus: 'unum'}]);
// text is '["e",{"pluribus":"unum"}]'
text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
// text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
text = JSON.stringify([new Date()], function (key, value) {
return this[key] instanceof Date ?
'Date(' + this[key] + ')' : value;
});
// text is '["Date(---current time---)"]'
JSON.parse(text, reviver)
This method parses a JSON text to produce an object or array.
It can throw a SyntaxError exception.
The optional reviver parameter is a function that can filter and
transform the results. It receives each of the keys and values,
and its return value is used instead of the original value.
If it returns what it received, then the structure is not modified.
If it returns undefined then the member is deleted.
Example:
// Parse the text. Values that look like ISO date strings will
// be converted to Date objects.
myData = JSON.parse(text, function (key, value) {
var a;
if (typeof value === 'string') {
a =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
if (a) {
return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
+a[5], +a[6]));
}
}
return value;
});
myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
var d;
if (typeof value === 'string' &&
value.slice(0, 5) === 'Date(' &&
value.slice(-1) === ')') {
d = new Date(value.slice(5, -1));
if (d) {
return d;
}
}
return value;
});
This is a reference implementation. You are free to copy, modify, or
redistribute.
*/
/*jslint evil: true, regexp: true */
/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
lastIndex, length, parse, prototype, push, replace, slice, stringify,
test, toJSON, toString, valueOf
*/
// Create a JSON object only if one does not already exist. We create the
// methods in a closure to avoid creating global variables.
if (typeof JSON !== 'object') {
JSON = {};
}
(function () {
'use strict';
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
if (typeof Date.prototype.toJSON !== 'function') {
Date.prototype.toJSON = function () {
return isFinite(this.valueOf())
? this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z'
: null;
};
String.prototype.toJSON =
Number.prototype.toJSON =
Boolean.prototype.toJSON = function () {
return this.valueOf();
};
}
var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
gap,
indent,
meta = { // table of character substitutions
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"': '\\"',
'\\': '\\\\'
},
rep;
function quote(string) {
// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.
escapable.lastIndex = 0;
return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
var c = meta[a];
return typeof c === 'string'
? c
: '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
}) + '"' : '"' + string + '"';
}
function str(key, holder) {
// Produce a string from holder[key].
var i, // The loop counter.
k, // The member key.
v, // The member value.
length,
mind = gap,
partial,
value = holder[key];
// If the value has a toJSON method, call it to obtain a replacement value.
if (value && typeof value === 'object' &&
typeof value.toJSON === 'function') {
value = value.toJSON(key);
}
// If we were called with a replacer function, then call the replacer to
// obtain a replacement value.
if (typeof rep === 'function') {
value = rep.call(holder, key, value);
}
// What happens next depends on the value's type.
switch (typeof value) {
case 'string':
return quote(value);
case 'number':
// JSON numbers must be finite. Encode non-finite numbers as null.
return isFinite(value) ? String(value) : 'null';
case 'boolean':
case 'null':
// If the value is a boolean or null, convert it to a string. Note:
// typeof null does not produce 'null'. The case is included here in
// the remote chance that this gets fixed someday.
return String(value);
// If the type is 'object', we might be dealing with an object or an array or
// null.
case 'object':
// Due to a specification blunder in ECMAScript, typeof null is 'object',
// so watch out for that case.
if (!value) {
return 'null';
}
// Make an array to hold the partial results of stringifying this object value.
gap += indent;
partial = [];
// Is the value an array?
if (Object.prototype.toString.apply(value) === '[object Array]') {
// The value is an array. Stringify every element. Use null as a placeholder
// for non-JSON values.
length = value.length;
for (i = 0; i < length; i += 1) {
partial[i] = str(i, value) || 'null';
}
// Join all of the elements together, separated with commas, and wrap them in
// brackets.
v = partial.length === 0
? '[]'
: gap
? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']'
: '[' + partial.join(',') + ']';
gap = mind;
return v;
}
// If the replacer is an array, use it to select the members to be stringified.
if (rep && typeof rep === 'object') {
length = rep.length;
for (i = 0; i < length; i += 1) {
if (typeof rep[i] === 'string') {
k = rep[i];
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
} else {
// Otherwise, iterate through all of the keys in the object.
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
}
// Join all of the member texts together, separated with commas,
// and wrap them in braces.
v = partial.length === 0
? '{}'
: gap
? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}'
: '{' + partial.join(',') + '}';
gap = mind;
return v;
}
}
// If the JSON object does not yet have a stringify method, give it one.
if (typeof JSON.stringify !== 'function') {
JSON.stringify = function (value, replacer, space) {
// The stringify method takes a value and an optional replacer, and an optional
// space parameter, and returns a JSON text. The replacer can be a function
// that can replace values, or an array of strings that will select the keys.
// A default replacer method can be provided. Use of the space parameter can
// produce text that is more easily readable.
var i;
gap = '';
indent = '';
// If the space parameter is a number, make an indent string containing that
// many spaces.
if (typeof space === 'number') {
for (i = 0; i < space; i += 1) {
indent += ' ';
}
// If the space parameter is a string, it will be used as the indent string.
} else if (typeof space === 'string') {
indent = space;
}
// If there is a replacer, it must be a function or an array.
// Otherwise, throw an error.
rep = replacer;
if (replacer && typeof replacer !== 'function' &&
(typeof replacer !== 'object' ||
typeof replacer.length !== 'number')) {
throw new Error('JSON.stringify');
}
// Make a fake root object containing our value under the key of ''.
// Return the result of stringifying the value.
return str('', { '': value });
};
}
// If the JSON object does not yet have a parse method, give it one.
if (typeof JSON.parse !== 'function') {
JSON.parse = function (text, reviver) {
// The parse method takes a text and an optional reviver function, and returns
// a JavaScript value if the text is a valid JSON text.
var j;
function walk(holder, key) {
// The walk method is used to recursively walk the resulting structure so
// that modifications can be made.
var k, v, value = holder[key];
if (value && typeof value === 'object') {
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = walk(value, k);
if (v !== undefined) {
value[k] = v;
} else {
delete value[k];
}
}
}
}
return reviver.call(holder, key, value);
}
// Parsing happens in four stages. In the first stage, we replace certain
// Unicode characters with escape sequences. JavaScript handles many characters
// incorrectly, either silently deleting them, or treating them as line endings.
text = String(text);
cx.lastIndex = 0;
if (cx.test(text)) {
text = text.replace(cx, function (a) {
return '\\u' +
('0000' + a.charCodeAt(0).toString(16)).slice(-4);
});
}
// In the second stage, we run the text against regular expressions that look
// for non-JSON patterns. We are especially concerned with '()' and 'new'
// because they can cause invocation, and '=' because it can cause mutation.
// But just to be safe, we want to reject all unexpected forms.
// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
if (/^[\],:{}\s]*$/
.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
.replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.
j = eval('(' + text + ')');
// In the optional fourth stage, we recursively walk the new structure, passing
// each name/value pair to a reviver function for possible transformation.
return typeof reviver === 'function'
? walk({ '': j }, '')
: j;
}
// If the text is not JSON parseable, then a SyntaxError is thrown.
throw new SyntaxError('JSON.parse');
};
}
} ()); | DanielLangdon/ExpressForms | ExpressForms/ExpressFormsExample/Scripts/json2.js | JavaScript | mit | 16,986 |
'use strict';
import Chart from 'chart.js';
import Controller from './controller';
import Scale, {defaults} from './scale';
// Register the Controller and Scale
Chart.controllers.smith = Controller;
Chart.defaults.smith = {
aspectRatio: 1,
scale: {
type: 'smith',
},
tooltips: {
callbacks: {
title: () => null,
label: (bodyItem, data) => {
const dataset = data.datasets[bodyItem.datasetIndex];
const d = dataset.data[bodyItem.index];
return dataset.label + ': ' + d.real + ' + ' + d.imag + 'i';
}
}
}
};
Chart.scaleService.registerScaleType('smith', Scale, defaults);
| chartjs/Chart.smith.js | src/index.js | JavaScript | mit | 602 |
var packageInfo = require('./package.json');
var taskList = [{name:'default'},{name:'delete'},{name:'build'},{name:'copy'},{name:'minify'}];
var gulpTalk2me = require('gulp-talk2me');
var talk2me = new gulpTalk2me(packageInfo,taskList);
var del = require('del');
var gulp = require('gulp');
var runSequence = require('run-sequence');
var sourcemaps = require('gulp-sourcemaps');
var rename = require('gulp-rename');
var ngAnnotate = require('gulp-ng-annotate');
var bytediff = require('gulp-bytediff');
var uglify = require('gulp-uglify');
var concat = require('gulp-concat');
var templateCache = require('gulp-angular-templatecache');
var series = require('stream-series');
var angularFilesort = require('gulp-angular-filesort');
console.log(talk2me.greeting);
gulp.task('default',function(callback){
runSequence('build',callback);
});
gulp.task('delete',function(callback){
del('dist/**/*', callback());
});
gulp.task('build',function(callback){
runSequence('delete',['copy','minify'],callback);
});
gulp.task('copy',function(){
return series(genTemplateStream(),gulp.src(['src/**/*.js','!src/**/*.spec.js']))
.pipe(sourcemaps.init())
.pipe(angularFilesort())
.pipe(concat('bs-fa-boolean-directive.js', {newLine: ';\n'}))
.pipe(ngAnnotate({
add: true
}))
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest('dist'));
});
gulp.task('minify',function(){
return series(genTemplateStream(),gulp.src(['src/**/*.js','!src/**/*.spec.js']))
.pipe(sourcemaps.init())
.pipe(angularFilesort())
.pipe(concat('bs-fa-boolean-directive.js', {newLine: ';'}))
.pipe(rename(function (path) {
path.basename += ".min";
}))
.pipe(ngAnnotate({
add: true
}))
.pipe(bytediff.start())
.pipe(uglify({mangle: true}))
.pipe(bytediff.stop())
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest('dist'));
});
function genTemplateStream () {
return gulp.src(['src/**/*.view.html'])
.pipe(templateCache({standalone:true,module:'bs-fa-boolean.template'}));
} | belgac/bs-fa-boolean-directive | Gulpfile.js | JavaScript | mit | 2,022 |
//https://github.com/nothingrandom/project_euler.js
var square=0;var sum=0;var answer=0;var number2=0;for(var i=0;i<=100;i++){var number=Math.pow(i,2);square+=number}for(var i=0;i<=100;i++){number2+=i;sum=Math.pow(number2,2)}var answer=sum-square;console.log(answer) | nothingrandom/project_euler.js | minified/006.js | JavaScript | mit | 266 |
var BasicMathLib = artifacts.require("./BasicMathLib.sol");
var Array256Lib = artifacts.require("./Array256Lib.sol");
var TokenLib = artifacts.require("./TokenLib.sol");
var CrowdsaleLib = artifacts.require("./CrowdsaleLib.sol");
var EvenDistroCrowdsaleLib = artifacts.require("./EvenDistroCrowdsaleLib.sol");
var CrowdsaleTestTokenEteenD = artifacts.require("./CrowdsaleTestTokenEteenD");
var EvenDistroTestEteenD = artifacts.require("./EvenDistroTestEteenD.sol");
var CrowdsaleTestTokenTenD = artifacts.require("./CrowdsaleTestTokenTenD");
var EvenDistroTestTenD = artifacts.require("./EvenDistroTestTenD.sol");
module.exports = function(deployer, network, accounts) {
deployer.deploy(BasicMathLib,{overwrite: false});
deployer.deploy(Array256Lib, {overwrite: false});
deployer.link(BasicMathLib, TokenLib);
deployer.deploy(TokenLib, {overwrite: false});
deployer.link(BasicMathLib,CrowdsaleLib);
deployer.link(TokenLib,CrowdsaleLib);
deployer.deploy(CrowdsaleLib, {overwrite: false});
deployer.link(BasicMathLib,EvenDistroCrowdsaleLib);
deployer.link(TokenLib,EvenDistroCrowdsaleLib);
deployer.link(CrowdsaleLib,EvenDistroCrowdsaleLib);
deployer.deploy(EvenDistroCrowdsaleLib, {overwrite:false});
if(network === "development" || network === "coverage"){
deployer.link(TokenLib,CrowdsaleTestTokenEteenD);
deployer.link(CrowdsaleLib,EvenDistroTestEteenD);
deployer.link(EvenDistroCrowdsaleLib, EvenDistroTestEteenD);
deployer.link(TokenLib,CrowdsaleTestTokenTenD);
deployer.link(CrowdsaleLib,EvenDistroTestTenD);
deployer.link(EvenDistroCrowdsaleLib, EvenDistroTestTenD);
// startTime 3 days + 1 hour in the future
var startTime = (Math.floor((new Date().valueOf()/1000))) + 262800;
// first price step in 7 days
var stepOne = startTime + 604800;
// second price step in 14 days
var stepTwo = stepOne + 604800;
// endTime in 30 days
var endTime = startTime + 2592000;
deployer.deploy(CrowdsaleTestTokenEteenD,
accounts[0],
"Eighteen Decimals",
"ETEEN",
18,
50000000000000000000000000,
false,
{from:accounts[5]})
.then(function() {
var purchaseData =[startTime,600000000000000000000,100,
stepOne,600000000000000000000,100,
stepTwo,300000000000000000000,0];
return deployer.deploy(EvenDistroTestEteenD,
accounts[5],
purchaseData,
endTime,
100,
10000000000000000000000,
false,
CrowdsaleTestTokenEteenD.address,
{from:accounts[5]})
})
.then(function(){
return deployer.deploy(CrowdsaleTestTokenTenD,
accounts[0],
"Ten Decimals",
"TEN",
10,
1000000000000000,
false,
{from:accounts[5]})
})
.then(function() {
// start next sale in 7 days
startTime = endTime + 604800;
stepOne = startTime + 604800;
stepTwo = stepOne + 604800;
endTime = startTime + 2592000;
purchaseData =[startTime,4000000000000,0,
stepOne,8000000000000,20000000000000,
stepTwo,16000000000000,0];
return deployer.deploy(EvenDistroTestTenD,
accounts[0],
purchaseData,
endTime,
25,
0,
true,
CrowdsaleTestTokenTenD.address,
{from:accounts[5]})
});
}
};
| Majoolr/ethereum-libraries | CrowdsaleLib/EvenDistroCrowdsale/truffle/migrations/2_deploy_test_contracts.js | JavaScript | mit | 3,987 |
//
// Adapted from:
// http://stackoverflow.com/questions/22330103/how-to-include-node-modules-in-a-separate-browserify-vendor-bundle
//
var gulp = require('gulp');
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var bust = require('gulp-buster');
var streamify = require('gulp-streamify');
var htmlreplace = require('gulp-html-replace');
var fs = require('fs');
var packageJson = require('./package.json');
var dependencies = Object.keys(packageJson && packageJson.dependencies || {});
function handleErrors(error) {
console.error(error.stack);
// Emit 'end' as the stream wouldn't do it itself.
// Without this, the gulp task won't end and the watch stops working.
this.emit('end');
}
gulp.task('libs', function () {
return browserify({debug: true})
.require(dependencies)
.bundle()
.on('error', handleErrors)
.pipe(source('libs.js'))
.pipe(gulp.dest('./dist/'))
.pipe(streamify(bust()))
.pipe(gulp.dest('.'));
});
gulp.task('scripts', function () {
return browserify('./src/index.js', {debug: true})
.external(dependencies)
.bundle()
.on('error', handleErrors)
.on('end', ()=>{console.log("ended")})
.pipe(source('scripts.js'))
.pipe(gulp.dest('./dist/'))
.pipe(streamify(bust()))
.pipe(gulp.dest('.'));
});
gulp.task('css', function () {
return gulp.src('./styles/styles.css')
.pipe(gulp.dest('./dist/'))
.pipe(streamify(bust()))
.pipe(gulp.dest('.'));
});
gulp.task('icons', function () {
return gulp.src('./icons/**/*')
.pipe(gulp.dest('./dist/icons'));
});
gulp.task('favicons', function () {
return gulp.src('./favicons/**/*')
.pipe(gulp.dest('./dist/'));
});
gulp.task('html', function () {
var busters = JSON.parse(fs.readFileSync('busters.json'));
return gulp.src('index.html')
.pipe(htmlreplace({
'css': 'styles.css?v=' + busters['dist/styles.css'],
'js': [
'libs.js?v=' + busters['dist/libs.js'],
'scripts.js?v=' + busters['dist/scripts.js']
]
}))
.pipe(gulp.dest('./dist/'));
});
gulp.task('watch', function(){
gulp.watch('package.json', ['libs']);
gulp.watch('src/**', ['scripts']);
gulp.watch('styles/styles.css', ['css']);
gulp.watch('icons/**', ['icons']);
gulp.watch('favicons/**', ['favicons']);
gulp.watch(['busters.json', 'index.html'], ['html']);
});
gulp.task('default', ['libs', 'scripts', 'css', 'icons', 'favicons', 'html', 'watch']);
| pafalium/gd-web-env | gulpfile.js | JavaScript | mit | 2,513 |
BrowserPolicy.content.allowOriginForAll("*.googleapis.com");
BrowserPolicy.content.allowOriginForAll("*.gstatic.com");
BrowserPolicy.content.allowOriginForAll("*.bootstrapcdn.com");
BrowserPolicy.content.allowOriginForAll("*.geobytes.com");
BrowserPolicy.content.allowFontDataUrl();
| ameletyan/LeaveWithFriends | server/config/security.js | JavaScript | mit | 284 |
'use strict'
if (!process.addAsyncListener) require('async-listener')
var noop = function () {}
module.exports = function () {
return new AsyncState()
}
function AsyncState () {
var state = this
process.addAsyncListener({
create: asyncFunctionInitialized,
before: asyncCallbackBefore,
error: noop,
after: asyncCallbackAfter
})
// Record the state currently set on on the async-state object and return a
// snapshot of it. The returned object will later be passed as the `data`
// arg in the functions below.
function asyncFunctionInitialized () {
var data = {}
for (var key in state) {
data[key] = state[key]
}
return data
}
// We just returned from the event-loop: We'll now restore the state
// previously saved by `asyncFunctionInitialized`.
function asyncCallbackBefore (context, data) {
for (var key in data) {
state[key] = data[key]
}
}
// Clear the state so that it doesn't leak between isolated async stacks.
function asyncCallbackAfter (context, data) {
for (var key in state) {
delete state[key]
}
}
}
| watson/async-state | index.js | JavaScript | mit | 1,118 |
/**
Problem 9. Extract e-mails
Write a function for extracting all email addresses from given text.
All sub-strings that match the format @
should be recognized as emails.
Return the emails as array of strings.
*/
console.log('Problem 9. Extract e-mails');
var text='gosho@gmail.com bla bla bla pesho_peshev@yahoo.com bla bla gosho_geshev@outlook.com'
function extractEmails(text) {
var result=text.match(/[A-Z0-9._-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/gi);
return result;
}
console.log('Text: '+text);
console.log('E-mail: '+extractEmails(text));
console.log('#########################################');
| ztodorova/Telerik-Academy | JavaScript Fundamentals/Strings/scripts/9. Extract e-mails.js | JavaScript | mit | 605 |
/**
* Border Left Radius
*/
module.exports = function (decl, args) {
var radius = args[1] || '3px';
decl.replaceWith({
prop: 'border-bottom-left-radius',
value: radius,
source: decl.source
}, {
prop: 'border-top-left-radius',
value: radius,
source: decl.source
});
};
| ismamz/postcss-utilities | lib/border-left-radius.js | JavaScript | mit | 335 |
//=====================================================================
// This sample demonstrates using TeslaJS
//
// https://github.com/mseminatore/TeslaJS
//
// Copyright (c) 2016 Mark Seminatore
//
// Refer to included LICENSE file for usage rights and restrictions
//=====================================================================
"use strict";
require('colors');
var program = require('commander');
var framework = require('./sampleFramework.js');
//
//
//
program
.usage('[options]')
.option('-i, --index <n>', 'vehicle index (first car by default)', parseInt)
.option('-U, --uri [string]', 'URI of test server (e.g. http://127.0.0.1:3000)')
.parse(process.argv);
//
var sample = new framework.SampleFramework(program, sampleMain);
sample.run();
//
//
//
function sampleMain(tjs, options) {
var streamingOptions = {
vehicle_id: options.vehicle_id,
authToken: options.authToken
};
console.log("\nNote: " + "Inactive vehicle streaming responses can take up to several minutes.".green);
console.log("\nStreaming starting...".cyan);
console.log("Columns: timestamp," + tjs.streamingColumns.toString());
tjs.startStreaming(streamingOptions, function (error, response, body) {
if (error) {
console.log(error);
return;
}
// display the streaming results
console.log(body);
console.log("...Streaming ended.".cyan);
});
}
| mseminatore/TeslaJS | samples/simpleStreaming.js | JavaScript | mit | 1,453 |
module.exports = {
dist: {
files: {
'dist/geo.js': ['src/index.js'],
}
}
}; | javascriptHustler/geo | grunt/browserify.js | JavaScript | mit | 94 |
var Model = require('./model');
var schema = {
name : String,
stuff: {
electronics: [{
type: String
}],
computing_dev: [{
type: String
}]
},
age:{
biological: Number
},
fruits: [
{
name: String,
fav: Boolean,
about: [{
type: String
}]
}
]
};
var person = function(data){
Model.call(this, schema, data);
}
person.prototype = Object.create(Model.prototype);
module.exports = person; | dpkshrma/NoSQL-Schema-Validator | demo/person.js | JavaScript | mit | 559 |
// Depends on jsbn.js and rng.js
// Version 1.1: support utf-8 encoding in pkcs1pad2
// convert a (hex) string to a bignum object
function parseBigInt(str,r) {
return new BigInteger(str,r);
}
function linebrk(s,n) {
var ret = "";
var i = 0;
while(i + n < s.length) {
ret += s.substring(i,i+n) + "\n";
i += n;
}
return ret + s.substring(i,s.length);
}
function byte2Hex(b) {
if(b < 0x10)
return "0" + b.toString(16);
else
return b.toString(16);
}
// PKCS#1 (type 2, random) pad input string s to n bytes, and return a bigint
function pkcs1pad2(s,n) {
if(n < s.length + 11) { // TODO: fix for utf-8
alert("Message too long for RSA");
return null;
}
var ba = new Array();
var i = s.length - 1;
while(i >= 0 && n > 0) {
var c = s.charCodeAt(i--);
if(c < 128) { // encode using utf-8
ba[--n] = c;
}
else if((c > 127) && (c < 2048)) {
ba[--n] = (c & 63) | 128;
ba[--n] = (c >> 6) | 192;
}
else {
ba[--n] = (c & 63) | 128;
ba[--n] = ((c >> 6) & 63) | 128;
ba[--n] = (c >> 12) | 224;
}
}
ba[--n] = 0;
var rng = new SecureRandom();
var x = new Array();
while(n > 2) { // random non-zero pad
x[0] = 0;
while(x[0] == 0) rng.nextBytes(x);
ba[--n] = x[0];
}
ba[--n] = 2;
ba[--n] = 0;
return new BigInteger(ba);
}
// "empty" RSA key constructor
function RSAKey() {
this.n = null;
this.e = 0;
this.d = null;
this.p = null;
this.q = null;
this.dmp1 = null;
this.dmq1 = null;
this.coeff = null;
}
// Set the public key fields N and e from hex strings
function RSASetPublic(N,E) {
if(N != null && E != null && N.length > 0 && E.length > 0) {
this.n = parseBigInt(N,16);
this.e = parseInt(E,16);
}
else
alert("Invalid RSA public key");
}
// Perform raw public operation on "x": return x^e (mod n)
function RSADoPublic(x) {
return x.modPowInt(this.e, this.n);
}
// Return the PKCS#1 RSA encryption of "text" as an even-length hex string
function RSAEncrypt(text) {
var m = pkcs1pad2(text,(this.n.bitLength()+7)>>3);
if(m == null) return null;
var c = this.doPublic(m);
if(c == null) return null;
var h = c.toString(16);
if((h.length & 1) == 0) return h; else return "0" + h;
}
// Return the PKCS#1 RSA encryption of "text" as a Base64-encoded string
function RSAEncryptB64(text) {
var h = this.encrypt(text);
if(h) return hex2b64(h); else return null;
}
// protected
RSAKey.prototype.doPublic = RSADoPublic;
// public
RSAKey.prototype.setPublic = RSASetPublic;
RSAKey.prototype.encrypt = RSAEncrypt;
RSAKey.prototype.encrypt_b64 = RSAEncryptB64;
//my encrypt function, using fixed mudulus
var modulus = "BEB90F8AF5D8A7C7DA8CA74AC43E1EE8A48E6860C0D46A5D690BEA082E3A74E1"
+"571F2C58E94EE339862A49A811A31BB4A48F41B3BCDFD054C3443BB610B5418B"
+"3CBAFAE7936E1BE2AFD2E0DF865A6E59C2B8DF1E8D5702567D0A9650CB07A43D"
+"E39020969DF0997FCA587D9A8AE4627CF18477EC06765DF3AA8FB459DD4C9AF3";
var publicExponent = "10001";
function MyRSAEncryptB64(text)
{
var rsa = new RSAKey();
rsa.setPublic(modulus, publicExponent);
return rsa.encrypt_b64(text);
}
| Wolfrax/Traffic | B593js/RSA.js | JavaScript | mit | 3,146 |
var ShaderTool = new (function ShaderTool(){
function catchReady(fn) {
var L = 'loading';
if (document.readyState != L){
fn();
} else if (document.addEventListener) {
document.addEventListener('DOMContentLoaded', fn);
} else {
document.attachEvent('onreadystatechange', function() {
if (document.readyState != L){
fn();
}
});
}
}
this.VERSION = '0.01';
this.modules = {};
this.helpers = {};
this.classes = {};
var self = this;
catchReady(function(){
self.modules.GUIHelper.init();
self.modules.UniformControls.init();
self.modules.Editor.init();
self.modules.Rendering.init();
self.modules.SaveController.init();
self.modules.PopupManager.init();
document.documentElement.className = '_ready';
});
})();
// Utils
ShaderTool.Utils = {
trim: function( string ){
return string.replace(/^\s+|\s+$/g, '');
},
isSet: function( object ){
return typeof object != 'undefined' && object != null
},
isArray: function( object ){
var str = Object.prototype.toString.call(object);
return str == '[object Array]' || str == '[object Float32Array]';
// return Object.prototype.toString.call(object) === '[object Array]';
},
isArrayLike: function( object ){
if( this.isArray(object) ){
return true
}
if( typeof object.length == 'number' && typeof object[0] != 'undefined' && typeof object[object.length] != 'undefined'){
return true;
}
return false;
},
isArrayLike: function( object ){
if(this.isArray(object)){ return true; }
if(this.isObject(object) && this.isNumber(object.length) ){ return true; }
return false;
},
isNumber: function( object ){
return typeof object == 'number' && !isNaN(object);
},
isFunction: function( object ){
return typeof object == 'function';
},
isObject: function( object ){
return typeof object == 'object';
},
isString: function( object ){
return typeof object == 'string';
},
createNamedObject: function( name, props ){
return internals.createNamedObject( name, props );
},
testCallback: function( callback, applyArguments, context ){
if(this.isFunction(callback)){
return callback.apply(context, applyArguments || []);
}
return null;
},
copy: function( from, to ){
for(var i in from){ to[i] = from[i]; }
return to;
},
delegate: function( context, method ){
return function delegated(){
for(var argumentsLength = arguments.length, args = new Array(argumentsLength), k=0; k<argumentsLength; k++){
args[k] = arguments[k];
}
return method.apply( context, args );
}
},
debounce: function(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate){
func.apply(context, args);
}
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow){
func.apply(context, args);
}
};
},
throttle: function(func, ms) {
var isThrottled = false, savedArgs, savedThis;
function wrapper() {
if (isThrottled) {
savedArgs = arguments;
savedThis = this;
return;
}
func.apply(this, arguments);
isThrottled = true;
setTimeout(function() {
isThrottled = false;
if (savedArgs) {
wrapper.apply(savedThis, savedArgs);
savedArgs = savedThis = null;
}
}, ms);
}
return wrapper;
},
now: function(){
var P = 'performance';
if (window[P] && window[P]['now']) {
this.now = function(){ return window.performance.now() }
} else {
this.now = function(){ return +(new Date()) }
}
return this.now();
},
isFunction: function( object ){
return typeof object == 'function';
},
isNumberKey: function(e){
var charCode = (e.which) ? e.which : e.keyCode;
if (charCode == 46) {
//Check if the text already contains the . character
if (txt.value.indexOf('.') === -1) {
return true;
} else {
return false;
}
} else {
// if (charCode > 31 && (charCode < 48 || charCode > 57)){
if(charCode > 31 && (charCode < 48 || charCode > 57) && !(charCode == 46 || charCode == 8)){
if(charCode < 96 && charCode > 105){
return false;
}
}
}
return true;
},
toDecimalString: function( string ){
if(this.isNumber(string)){
return string;
}
if(string.substr(0,1) == '0'){
if(string.substr(1,1) != '.'){
string = '0.' + string.substr(1, string.length);
}
}
return string == '0.' ? '0' : string;
},
/*
hexToRgb: function(hex) {
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? [
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16)
] : [];
}
*/
};
// Callback (Signal?)
ShaderTool.Utils.Callback = (function(){
// Callback == Signal ?
function Callback() {
this._handlers = [];
var self = this;
this.callShim = function(){
self.call.apply(self, arguments);
}
}
Callback.prototype = {
_throwError: function() {
throw new TypeError('Callback handler must be function!');
},
add: function(handler, context) {
if (typeof handler != 'function') {
this._throwError();
return;
}
this.remove(handler);
this._handlers.push({handler:handler, context: context});
},
remove: function(handler) {
if (typeof handler != 'function') {
this._throwError();
return;
}
var totalHandlers = this._handlers.length;
for (var k = 0; k < totalHandlers; k++) {
if (handler === this._handlers[k].handler) {
this._handlers.splice(k, 1);
return;
}
}
},
call: function() {
var totalHandlers = this._handlers.length;
for (var k = 0; k < totalHandlers; k++) {
var handlerData = this._handlers[k];
handlerData.handler.apply(handlerData.context || null, arguments);
}
}
};
return Callback;
})();
ShaderTool.Utils.Float32Array = (function(){
return typeof Float32Array === 'function' ? Float32Array : Array;
})();
ShaderTool.Utils.DOMUtils = (function(){
function addSingleEventListener(element, eventName, handler){
if (element.addEventListener) {
element.addEventListener(eventName, handler);
} else {
element.attachEvent('on' + eventName, function(e){
handler.apply(element,[e]);
});
}
}
var tempDiv = document.createElement('div');
function DOMUtils(){};
DOMUtils.prototype = {
addEventListener : function(element, eventName, handler){
if(ShaderTool.Utils.isArrayLike(element)){
var totalElements = element.length;
for(var k=0; k<totalElements; k++){
this.addEventListener(element[k], eventName, handler);
}
} else {
var eventName = ShaderTool.Utils.isArray(eventName) ? eventName : eventName.split(' ').join('|').split(',').join('|').split('|');
if(eventName.length > 1){
var totalEvents = eventName.length;
for(var k=0; k<totalEvents; k++){
addSingleEventListener(element, eventName[k], handler );
}
} else {
addSingleEventListener(element, eventName[0], handler);
}
}
},
addClass : function(element, className){
if (element.classList){
element.classList.add(className);
} else {
element.className += SPACE + className;
}
},
removeClass : function(element, className){
if (element.classList){
element.classList.remove(className);
} else{
element.className = element.className.replace(new RegExp('(^|\\b)' + className.split(SPACE).join('|') + '(\\b|$)', 'gi'), SPACE);
}
},
injectCSS: function( cssText ){
try{
var styleElement = document.createElement('style');
styleElement.type = 'text/css';
if (styleElement.styleSheet) {
styleElement.styleSheet.cssText = cssText;
} else {
styleElement.appendChild(document.createTextNode(cssText));
}
document.getElementsByTagName('head')[0].appendChild(styleElement);
return true;
} catch( e ){
return false;
}
},
createFromHTML: function( html ){
tempDiv.innerHTML = html.trim();
var result = tempDiv.childNodes;
if(result.length > 1){
tempDiv.innerHTML = '<div>' + html.trim() + '<div/>'
result = tempDiv.childNodes;
}
return result[0];
}
}
return new DOMUtils();
})();
// Helpers
// LSHelper
ShaderTool.helpers.LSHelper = (function(){
var ALLOW_WORK = window.localStorage != null || window.sessionStorage != null;
function LSHelper(){
this._storage = window.localStorage || window.sessionStorage;
}
LSHelper.prototype = {
setItem: function( key, data ){
if( !ALLOW_WORK ){ return null }
var json = JSON.stringify(data)
this._storage.setItem( key, json );
return json;
},
getItem: function( key ){
if( !ALLOW_WORK ){ return null }
return JSON.parse(this._storage.getItem( key ))
},
clearItem: function( key ){
if( !ALLOW_WORK ){ return null }
this._storage.removeItem( key )
}
}
return new LSHelper();
})();
// FSHelper
ShaderTool.helpers.FSHelper = (function(){
function FSHelper(){};
FSHelper.prototype = {
request: function( element ){
if (element.requestFullscreen) {
element.requestFullscreen();
} else if (element.mozRequestFullScreen) {
element.mozRequestFullScreen();
} else if (element.webkitRequestFullScreen) {
element.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
}
},
exit: function(){
if (document.cancelFullScreen) {
document.cancelFullScreen();
} else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
} else if (document.webkitCancelFullScreen) {
document.webkitCancelFullScreen();
}
}
}
return new FSHelper();
})();
// Ticker
ShaderTool.helpers.Ticker = (function(){
var raf;
var lastTime = 0;
var vendors = ['ms', 'moz', 'webkit', 'o'];
for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame'];
}
if (!window.requestAnimationFrame){
raf = function( callback ) {
var currTime = Utils.now();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = window.setTimeout( function(){
callback(currTime + timeToCall);
}, timeToCall);
lastTime = currTime + timeToCall;
return id;
};
} else {
raf = function( callback ){
return window.requestAnimationFrame( callback );
}
}
function Ticker(){
this.onTick = new ShaderTool.Utils.Callback();
var activeState = true;
var applyArgs = [];
var listeners = [];
var prevTime = ShaderTool.Utils.now();
var elapsedTime = 0;
var timeScale = 1;
var self = this;
var skippedFrames = 0;
var maxSkipFrames = 3;
this.stop = this.pause = this.sleep = function(){
activeState = false;
return this;
}
this.start = this.wake = function(){
activeState = true;
return this;
}
this.reset = function(){
elapsedTime = 0;
}
this.timeScale = function( value ){
if(ShaderTool.Utils.isSet(value)){ timeScale = value; }
return timeScale;
}
this.toggle = function(){
return (activeState ? this.stop() : this.start());
}
this.isActive = function(){
return activeState;
}
this.getTime = function(){
return elapsedTime;
}
function tickHandler( nowTime ){
var delta = (nowTime - prevTime) * timeScale;
prevTime = nowTime;
if(skippedFrames < maxSkipFrames){
skippedFrames++;
} else {
if(activeState){
elapsedTime += delta;
self.onTick.call(delta, elapsedTime)
}
}
raf( tickHandler );
}
raf( tickHandler );
};
return new Ticker();
})();
// Modules
// Future module
ShaderTool.modules.GUIHelper = (function(){
function GUIHelper(){}
GUIHelper.prototype = {
init: function(){
console.log('ShaderTool.modules.GUIHelper.init')
},
showError: function( message ){
console.error('GUIHelper: ' + message)
}
}
return new GUIHelper();
})();
// Editor
ShaderTool.modules.Editor = (function(){
function Editor(){}
Editor.prototype = {
init: function(){
console.log('ShaderTool.modules.Editor.init');
this._container = document.getElementById('st-editor');
this._editor = ace.edit(this._container);
this._editor.getSession().setMode('ace/mode/glsl');
// https://ace.c9.io/build/kitchen-sink.html
// this._editor.getSession().setTheme();
this._editor.$blockScrolling = Infinity;
this.onChange = new ShaderTool.Utils.Callback();
var self = this;
//this._editor.on('change', function(){
//self.onChange.call();
//});
this._editor.on('change', ShaderTool.Utils.throttle(function(){
if(!self._skipCallChange){
self.onChange.call();
}
}, 1000 / 60 * 10));
},
getData: function(){
return this._editor.getSession().getValue();
},
setData: function( value, skipCallChangeFlag ){
this._skipCallChange = skipCallChangeFlag;
this._editor.getSession().setValue( value );
this._skipCallChange = false;
if(!skipCallChangeFlag){
this.onChange.call();
}
},
clear: function(){
this.setValue('');
},
// future methods:
//lock: function(){},
//unlock: function(){},
//load: function( url ){}
}
return new Editor();
})();
ShaderTool.modules.Rendering = (function(){
var VERTEX_SOURCE = 'attribute vec2 av2_vtx;varying vec2 vv2_v;void main(){vv2_v = av2_vtx;gl_Position = vec4(av2_vtx, 0., 1.);}';
function Rendering(){}
Rendering.prototype = {
init: function(){
console.log('ShaderTool.modules.Rendering.init');
this._canvas = document.getElementById('st-canvas');
this._context = D3.createContextOnCanvas(this._canvas);
this._initSceneControls();
this.onChange = new ShaderTool.Utils.Callback();
// this._sourceChanged = true;
var fragmentSource = 'precision mediump float;\n';
fragmentSource += 'uniform sampler2D us2_source;\n';
fragmentSource += 'uniform float uf_time;\n';
fragmentSource += 'uniform vec2 uv2_resolution;\n';
fragmentSource += 'void main() {\n';
fragmentSource += '\tgl_FragColor = \n';
// fragmentSource += 'vec4(gl_FragCoord.xy / uv2_resolution, sin(uf_time), 1.);\n';
fragmentSource += '\t\ttexture2D(us2_source, gl_FragCoord.xy / uv2_resolution);\n';
fragmentSource += '}\n';
this._program = this._context.createProgram({
vertex: VERTEX_SOURCE,
fragment: fragmentSource
});
this._buffer = this._context.createVertexBuffer().upload(new ShaderTool.Utils.Float32Array([1,-1,1,1,-1,-1,-1,1]));
this._resolution = null;
this._texture = null;
this._framebuffer = null;
this._writePosition = 0;
this._source = {
program: this._program,
attributes: {
'av2_vtx': {
buffer: this._buffer,
size: 2,
type: this._context.AttribType.Float,
offset: 0
}
},
uniforms: {
'us2_source': this._context.UniformSampler(this._texture)
},
mode: this._context.Primitive.TriangleStrip,
count: 4
};
this._rasterizers = [];
this._rasterizers.push(new ShaderTool.classes.Rasterizer( this._context ));
// this._updateSource();
ShaderTool.modules.Editor.onChange.add(this._updateSource, this);
ShaderTool.modules.UniformControls.onChangeUniformList.add(this._updateSource, this);
ShaderTool.modules.UniformControls.onChangeUniformValue.add(this._updateUniforms, this);
ShaderTool.helpers.Ticker.onTick.add(this._render, this);
},
_updateSource: function( skipCallChangeFlag ){
var uniformSource = ShaderTool.modules.UniformControls.getUniformsCode();
var shaderSource = ShaderTool.modules.Editor.getData();
var fullSource = 'precision mediump float;\n\n' + uniformSource + '\n\n\n' + shaderSource;
var totalRasterizers = this._rasterizers.length;
for(var k=0; k<totalRasterizers; k++){
var rasterizer = this._rasterizers[k];
rasterizer.updateSource(fullSource);
}
this._updateUniforms( skipCallChangeFlag );
},
_updateUniforms: function( skipCallChangeFlag ){
var uniforms = ShaderTool.modules.UniformControls.getUniformsData( this._context );
var totalRasterizers = this._rasterizers.length;
for(var k=0; k<totalRasterizers; k++){
var rasterizer = this._rasterizers[k];
rasterizer.updateUniforms(uniforms);
}
if(!skipCallChangeFlag){
this.onChange.call();
}
},
_setResolution: function (width, height) {
if (!this._resolution) {
this._texture = [
this._context.createTexture().uploadEmpty(this._context.TextureFormat.RGBA_8, width, height),
this._context.createTexture().uploadEmpty(this._context.TextureFormat.RGBA_8, width, height)
];
framebuffer = [
this._context.createFramebuffer().attachColor(this._texture[1]),
this._context.createFramebuffer().attachColor(this._texture[0])
];
} else if (this._resolution[0] !== width || this._resolution[1] !== height) {
this._texture[0].uploadEmpty(this._context.TextureFormat.RGBA_8, width, height);
this._texture[1].uploadEmpty(this._context.TextureFormat.RGBA_8, width, height);
}
this._resolution = [width, height];
},
_initSceneControls: function(){
var self = this;
this.dom = {};
this.dom.playButton = document.getElementById('st-play');
this.dom.pauseButton = document.getElementById('st-pause');
this.dom.rewindButton = document.getElementById('st-rewind');
this.dom.fullscreenButton = document.getElementById('st-fullscreen');
this.dom.timescaleRange = document.getElementById('st-timescale');
this.dom.renderWidthLabel = document.getElementById('st-renderwidth');
this.dom.renderHeightLabel = document.getElementById('st-renderheight');
this.dom.sceneTimeLabel = document.getElementById('st-scenetime');
function setPlayingState( state ){
if(state){
ShaderTool.helpers.Ticker.start();
self.dom.playButton.style.display = 'none';
self.dom.pauseButton.style.display = '';
} else {
ShaderTool.helpers.Ticker.stop();
self.dom.playButton.style.display = '';
self.dom.pauseButton.style.display = 'none';
}
}
ShaderTool.Utils.DOMUtils.addEventListener(this.dom.playButton, 'mousedown', function( e ){
e.preventDefault();
setPlayingState( true );
});
ShaderTool.Utils.DOMUtils.addEventListener(this.dom.pauseButton, 'mousedown', function( e ){
e.preventDefault();
setPlayingState( false );
});
ShaderTool.Utils.DOMUtils.addEventListener(this.dom.rewindButton, 'mousedown', function( e ){
e.preventDefault();
ShaderTool.helpers.Ticker.reset();
});
ShaderTool.Utils.DOMUtils.addEventListener(this.dom.fullscreenButton, 'mousedown', function( e ){
e.preventDefault();
ShaderTool.helpers.FSHelper.request(self._canvas);
});
ShaderTool.Utils.DOMUtils.addEventListener(this._canvas, 'dblclick', function( e ){
e.preventDefault();
ShaderTool.helpers.FSHelper.exit();
});
this.dom.timescaleRange.setAttribute('step', '0.001');
this.dom.timescaleRange.setAttribute('min', '0.001');
this.dom.timescaleRange.setAttribute('max', '10');
this.dom.timescaleRange.setAttribute('value', '1');
ShaderTool.Utils.DOMUtils.addEventListener(this.dom.timescaleRange, 'input change', function( e ){
ShaderTool.helpers.Ticker.timeScale( parseFloat(self.dom.timescaleRange.value) )
});
setPlayingState( true );
},
_render: function( delta, elapsedTime ){
// To seconds:
delta = delta * 0.001;
elapsedTime = elapsedTime * 0.001;
this.dom.sceneTimeLabel.innerHTML = elapsedTime.toFixed(2);;
if (this._canvas.clientWidth !== this._canvas.width ||
this._canvas.clientHeight !== this._canvas.height) {
var pixelRatio = window.devicePixelRatio || 1;
var cWidth = this._canvas.width = this._canvas.clientWidth * pixelRatio;
var cHeight = this._canvas.height = this._canvas.clientHeight * pixelRatio;
this._setResolution(cWidth, cHeight);
this.dom.renderWidthLabel.innerHTML = cWidth + 'px';
this.dom.renderHeightLabel.innerHTML = cHeight + 'px';
}
var previosFrame = this._texture[this._writePosition];
var resolution = this._resolution;
var destination = { framebuffer: framebuffer[this._writePosition] };
var totalRasterizers = this._rasterizers.length;
for(var k=0; k<totalRasterizers; k++){
var rasterizer = this._rasterizers[k];
rasterizer.render(elapsedTime, previosFrame, resolution, destination);
}
if (!this._resolution) {
return;
}
this._writePosition = (this._writePosition + 1) & 1;
this._source.uniforms['uf_time'] = this._context.UniformFloat( elapsedTime );
this._source.uniforms['uv2_resolution'] = this._context.UniformVec2( this._resolution );
this._source.uniforms['us2_source'] = this._context.UniformSampler( this._texture[this._writePosition] );
this._context.rasterize(this._source);
},
getData: function(){
return {
uniforms: ShaderTool.modules.UniformControls.getData(),
source: ShaderTool.modules.Editor.getData()
}
},
setData: function( data, skipCallChangeFlag ){
ShaderTool.modules.UniformControls.setData( data.uniforms, true );
ShaderTool.modules.Editor.setData( data.source, true );
this._updateSource( skipCallChangeFlag );
ShaderTool.helpers.Ticker.reset();
if(!skipCallChangeFlag){
this.onChange.call();
}
}
}
return new Rendering();
})();
// Controls
ShaderTool.modules.UniformControls = (function(){
function UniformControls(){}
UniformControls.prototype = {
init: function(){
console.log('ShaderTool.modules.UniformControls.init');
this.onChangeUniformList = new ShaderTool.Utils.Callback();
this.onChangeUniformValue = new ShaderTool.Utils.Callback();
this._changed = true;
this._callChangeUniformList = function(){
this._changed = true;
this.onChangeUniformList.call();
}
this._callChangeUniformValue = function(){
this._changed = true;
this.onChangeUniformValue.call();
}
this._container = document.getElementById('st-uniforms-container');
this._controls = [];
this._uniforms = {};
this._createMethods = {};
this._createMethods[UniformControls.FLOAT] = this._createFloat;
this._createMethods[UniformControls.VEC2] = this._createVec2;
this._createMethods[UniformControls.VEC3] = this._createVec3;
this._createMethods[UniformControls.VEC4] = this._createVec4;
this._createMethods[UniformControls.COLOR3] = this._createColor3;
this._createMethods[UniformControls.COLOR4] = this._createColor4;
// Templates:
this._templates = {};
var totalTypes = UniformControls.TYPES.length;
for(var k=0; k<totalTypes; k++){
var type = UniformControls.TYPES[k]
var templateElement = document.getElementById('st-template-control-' + type);
if(templateElement){
this._templates[type] = templateElement.innerHTML;
templateElement.parentNode.removeChild(templateElement);
} else {
console.warn('No template html for ' + type + ' type!');
}
}
this._container.innerHTML = ''; // Clear container
// Tests:
/*
for(var k=0; k<totalTypes; k++){
this._createControl('myControl' + (k+1), UniformControls.TYPES[k], null, true );
}
//uniform float slide;
//uniform vec3 color1;
this._createControl('slide', UniformControls.FLOAT, [{max: 10, value: 10}], true );
// this._createControl('color1', UniformControls.COLOR3, null, true );
this._createControl('color1', UniformControls.VEC3, [{value:1},{},{}], true );
this._createControl('test', UniformControls.FLOAT, null, true );
this._createControl('test2', UniformControls.FLOAT, [{value: 1}], true );
this._createControl('test3', UniformControls.FLOAT, [{ value: 1 }], true );
//
//this._callChangeUniformList();
//this._callChangeUniformValue();
*/
this._initCreateControls();
},
/* Public methods */
getUniformsCode: function(){
var result = [];
var totalControls = this._controls.length;
for(var k=0; k<totalControls; k++){
result.push(this._controls[k].code);
}
return result.join('\n');
},
getUniformsData: function( context ){
if(!this._changed){
return this._uniforms;
}
this._changed = false;
this._uniforms = {};
var totalControls = this._controls.length;
for(var k=0; k<totalControls; k++){
var control = this._controls[k];
var value = control.getUniformValue();
if(control.type == UniformControls.FLOAT){
this._uniforms[control.name] = context.UniformFloat(value);
} else if(control.type == UniformControls.VEC2){
this._uniforms[control.name] = context.UniformVec2(value);
} else if(control.type == UniformControls.VEC3 || control.type == UniformControls.COLOR3){
this._uniforms[control.name] = context.UniformVec3(value);
} else if(control.type == UniformControls.VEC4 || control.type == UniformControls.COLOR4){
this._uniforms[control.name] = context.UniformVec4(value);
}
}
return this._uniforms;
},
getData: function(){
var uniforms = [];
var totalControls = this._controls.length;
for(var k=0; k<totalControls; k++){
var control = this._controls[k];
uniforms.push({
name: control.name,
type: control.type,
data: control.data
})
}
return uniforms;
},
setData: function( uniforms, skipCallChangeFlag){
this._clearControls( skipCallChangeFlag );
// TODO;
var totalUniforms = uniforms.length;
for(var k=0; k<totalUniforms; k++){
var uniformData = uniforms[k];
this._createControl(uniformData.name, uniformData.type, uniformData.data, true)
}
if(!skipCallChangeFlag){
this._callChangeUniformList();
}
},
/* Private methods */
_checkNewUniformName: function( name ){
// TODO;
return name != '';
},
_initCreateControls: function(){
var addUniformNameInput = document.getElementById('st-add-uniform-name');
var addUniformTypeSelect = document.getElementById('st-add-uniform-type');
var addUniformSubmit = document.getElementById('st-add-uniform-submit');
var self = this;
ShaderTool.Utils.DOMUtils.addEventListener(addUniformSubmit, 'click', function( e ){
e.preventDefault();
var name = addUniformNameInput.value;
if( !self._checkNewUniformName(name) ){
// TODO: Show info about incorrect uniforn name?
addUniformNameInput.focus();
} else {
var type = addUniformTypeSelect.value;
self._createControl( name, type, null, false );
addUniformNameInput.value = '';
}
});
},
_createControl: function( name, type, initialData, skipCallChangeFlag ){
this._changed = true;
var self = this;
var control;
var elementTemplate = this._templates[type];
if( typeof elementTemplate == 'undefined' ){
console.error('No control template for type ' + type);
return;
}
var element = ShaderTool.Utils.DOMUtils.createFromHTML(elementTemplate);
var createMethod = this._createMethods[type];
if( createMethod ){
initialData = ShaderTool.Utils.isArray(initialData) ? initialData : [];
control = createMethod.apply(this, [name, element, initialData] );
} else {
throw new ShaderTool.Exception('Unknown uniform control type: ' + type);
return null;
}
control.name = name;
control.type = type;
control.element = element;
this._controls.push(control);
this._container.appendChild(element);
// name element
var nameElement = element.querySelector('[data-uniform-name]');
if(nameElement){
nameElement.setAttribute('title', 'Uniform ' + name + ' settings');
nameElement.innerHTML = name;
ShaderTool.Utils.DOMUtils.addEventListener(nameElement, 'dblclick', function( e ){
e.preventDefault();
alert('Show uniform rename dialog?')
});
}
// delete element
var deleteElement = element.querySelector('[data-uniform-delete]');
if(deleteElement){
ShaderTool.Utils.DOMUtils.addEventListener(deleteElement, 'click', function( e ){
e.preventDefault();
if (confirm('Delete uniform?')) {
self._removeControl( control );
}
});
}
if(!skipCallChangeFlag){
this._callChangeUniformList();
}
},
_removeControl: function( control, skipCallChangeFlag ){
var totalControls = this._controls.length;
for(var k=0; k<totalControls; k++){
if(this._controls[k] === control){
this._controls.splice(k, 1);
control.element.parentNode.removeChild( control.element );
break;
}
}
if(!skipCallChangeFlag){
this._callChangeUniformList();
}
},
_clearControls: function(skipCallChangeFlag){
var c = 0;
for(var k=0;k<this._controls.length; k++){
c++;
if(c > 100){
return;
}
this._removeControl( this._controls[k], true );
k--;
}
if(!skipCallChangeFlag){
this._callChangeUniformList();
}
},
_createFloat: function( name, element, initialData ){
var self = this;
var saveData = [ this._prepareRangeData( initialData[0]) ];
var uniformValue = saveData[0].value;
this._initRangeElementGroup(element, '1', saveData[0], function(){
uniformValue = saveData[0].value;
self._callChangeUniformValue();
});
return {
code: 'uniform float ' + name + ';',
data: saveData,
getUniformValue: function(){
return uniformValue;
}
}
},
_createVec2: function( name, element, initialData ){
var self = this;
var saveData = [
this._prepareRangeData( initialData[0] ),
this._prepareRangeData( initialData[1] )
];
var uniformValue = [saveData[0].value, saveData[1].value];
this._initRangeElementGroup(element, '1', saveData[0], function(){
uniformValue[0] = saveData[0].value;
self._callChangeUniformValue();
});
this._initRangeElementGroup(element, '2', saveData[1], function(){
uniformValue[1] = saveData[1].value;
self._callChangeUniformValue();
});
return {
code: 'uniform vec2 ' + name + ';',
data: saveData,
getUniformValue: function(){
return uniformValue;
}
}
},
_createVec3: function( name, element, initialData ){
var self = this;
var saveData = [
this._prepareRangeData( initialData[0] ),
this._prepareRangeData( initialData[1] ),
this._prepareRangeData( initialData[2] )
];
var uniformValue = [saveData[0].value, saveData[1].value, saveData[2].value];
this._initRangeElementGroup(element, '1', saveData[0], function(){
uniformValue[0] = saveData[0].value;
self._callChangeUniformValue();
});
this._initRangeElementGroup(element, '2', saveData[1], function(){
uniformValue[1] = saveData[1].value;
self._callChangeUniformValue();
});
this._initRangeElementGroup(element, '3', saveData[2], function(){
uniformValue[2] = saveData[2].value;
self._callChangeUniformValue();
});
return {
code: 'uniform vec3 ' + name + ';',
data: saveData,
getUniformValue: function(){
return uniformValue;
}
}
},
_createVec4: function( name, element, initialData ){
var self = this;
var saveData = [
this._prepareRangeData( initialData[0] ),
this._prepareRangeData( initialData[1] ),
this._prepareRangeData( initialData[2] ),
this._prepareRangeData( initialData[3] )
];
var uniformValue = [saveData[0].value, saveData[1].value, saveData[2].value, saveData[3].value];
this._initRangeElementGroup(element, '1', saveData[0], function(){
uniformValue[0] = saveData[0].value;
self._callChangeUniformValue();
});
this._initRangeElementGroup(element, '2', saveData[1], function(){
uniformValue[1] = saveData[1].value;
self._callChangeUniformValue();
});
this._initRangeElementGroup(element, '3', saveData[2], function(){
uniformValue[2] = saveData[2].value;
self._callChangeUniformValue();
});
this._initRangeElementGroup(element, '4', saveData[3], function(){
uniformValue[3] = saveData[3].value;
self._callChangeUniformValue();
});
return {
code: 'uniform vec4 ' + name + ';',
data: saveData,
getUniformValue: function(){
return uniformValue;
}
}
},
_createColor3: function( name, element, initialData ){
var self = this;
var saveData = this._prepareColorData(initialData, false)
this._initColorSelectElementGroup( element, false, saveData, function(){
self._callChangeUniformValue();
})
return {
code: 'uniform vec3 ' + name + ';',
data: saveData,
getUniformValue: function(){
return saveData;
}
}
},
_createColor4: function( name, element, initialData ){
var self = this;
var saveData = this._prepareColorData(initialData, true);
this._initColorSelectElementGroup( element, true, saveData, function(){
self._callChangeUniformValue();
})
return {
code: 'uniform vec4 ' + name + ';',
data: saveData,
getUniformValue: function(){
return saveData;
}
}
},
_prepareColorData: function( inputData, vec4Format ){
inputData = ShaderTool.Utils.isArray( inputData ) ? inputData : [];
var resultData = vec4Format ? [0,0,0,1] : [0,0,0];
var counter = vec4Format ? 4 : 3;
for(var k=0; k<counter;k++){
var inputComponent = inputData[k];
if( typeof inputComponent != 'undefined' ){
resultData[k] = inputComponent;
}
}
return resultData;
},
_prepareRangeData: function( inputData ){
inputData = typeof inputData == 'undefined' ? {} : inputData;
var resultData = { value: 0, min: 0, max: 1 };
for(var i in resultData){
if(typeof inputData[i] != 'undefined'){
resultData[i] = inputData[i];
}
}
return resultData;
},
_componentToHex: function(c){
var hex = c.toString(16);
return hex.length == 1 ? '0' + hex : hex;
},
_hexFromRGB: function(r, g, b){
return '#' + this._componentToHex(r) + this._componentToHex(g) + this._componentToHex(b);
},
_initColorSelectElementGroup: function( element, useAlpha, initialData, changeHandler ){
var colorElement = element.querySelector('[data-color]');
colorElement.value = this._hexFromRGB(initialData[0] * 256 << 0, initialData[1] * 256 << 0, initialData[2] * 256 << 0);
ShaderTool.Utils.DOMUtils.addEventListener(colorElement, 'change', function( e ){
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(colorElement.value);
initialData[0] = parseInt( result[1], 16 ) / 256;
initialData[1] = parseInt( result[2], 16 ) / 256;
initialData[2] = parseInt( result[3], 16 ) / 256;
changeHandler();
});
if(useAlpha){
var rangeElement = element.querySelector('[data-range]');
rangeElement.setAttribute('min', '0');
rangeElement.setAttribute('max', '1');
rangeElement.setAttribute('step', '0.001');
rangeElement.setAttribute('value', initialData[3] );
ShaderTool.Utils.DOMUtils.addEventListener(rangeElement, 'input', function( e ){
initialData[3] = parseFloat(rangeElement.value);
changeHandler();
})
}
},
_initRangeElementGroup: function( element, attrIndex, initialData, changeHandler, stepValue ){
var minValue = initialData.min;
var maxValue = initialData.max;
var minElement = element.querySelector('[data-range-min-' + attrIndex + ']');// || document.createElement('input');
var maxElement = element.querySelector('[data-range-max-' + attrIndex + ']');// || document.createElement('input');
var rangeElement = element.querySelector('[data-range-' + attrIndex + ']');
var valueElement = element.querySelector('[data-range-value-' + attrIndex + ']') || document.createElement('div');
rangeElement.setAttribute('step', typeof stepValue != 'undefined' ? stepValue : '0.0001');
var prevMinValue;
var prevMaxValue;
minElement.setAttribute('title', 'Minimum value');
maxElement.setAttribute('title', 'Maximum value');
prevMinValue = minElement.value = valueElement.innerHTML = minValue;
prevMaxValue = maxElement.value = maxValue;
rangeElement.value = initialData.value;
ShaderTool.Utils.DOMUtils.addEventListener(rangeElement, 'input', function( e ){
if(minElement.value == ''){
minElement.value = prevMinValue;
}
if(maxElement.value == ''){
maxElement.value = prevMaxValue;
}
if(minValue > maxValue){
prevMinValue = minElement.value = maxValue;
prevMaxValue = maxElement.value = minValue;
}
valueElement.innerHTML = rangeElement.value;
initialData.min = minValue;
initialData.max = maxValue;
initialData.value = parseFloat(rangeElement.value);
changeHandler( initialData );
});
function updateRangeSettings(){
if(minElement.value == '' || maxElement.value == ''){
return;
}
prevMinValue = minElement.value;
prevMaxValue = maxElement.value;
minValue = ShaderTool.Utils.toDecimalString(minElement.value);
maxValue = ShaderTool.Utils.toDecimalString(maxElement.value);
var min = minValue = parseFloat(minValue);
var max = maxValue = parseFloat(maxValue);
if(min > max){
max = [min, min = max][0];
}
rangeElement.setAttribute('min', min);
rangeElement.setAttribute('max', max);
initialData.min = min;
initialData.max = max;
}
ShaderTool.Utils.DOMUtils.addEventListener([minElement, maxElement], 'keydown input change', function( e ){
if(!ShaderTool.Utils.isNumberKey( e )){
e.preventDefault();
return false;
}
updateRangeSettings();
});
updateRangeSettings();
}
}
UniformControls.FLOAT = 'float';
UniformControls.VEC2 = 'vec2';
UniformControls.VEC3 = 'vec3';
UniformControls.VEC4 = 'vec4';
UniformControls.COLOR3 = 'color3';
UniformControls.COLOR4 = 'color4';
UniformControls.TYPES = [UniformControls.FLOAT, UniformControls.VEC2, UniformControls.VEC3, UniformControls.VEC4, UniformControls.COLOR3, UniformControls.COLOR4];
return new UniformControls();
})();
// SaveController
ShaderTool.modules.SaveController = (function(){
var DEFAULT_CODE = '{"uniforms":[{"name":"bgcolor","type":"color3","data":[0.99609375,0.8046875,0.56640625]}],"source":"void main() {\\n gl_FragColor = vec4(bgcolor, 1.);\\n}"}';
function SaveController(){}
SaveController.prototype = {
init: function(){
console.log('ShaderTool.modules.SaveController.init');
var savedData = ShaderTool.helpers.LSHelper.getItem('lastShaderData');
if(savedData){
ShaderTool.modules.Rendering.setData(savedData, true);
} else {
ShaderTool.modules.Rendering.setData(JSON.parse(DEFAULT_CODE), true);
}
this._initSaveDialogs();
ShaderTool.modules.Rendering.onChange.add( this._saveLocalState, this);
this._saveLocalState();
},
_initSaveDialogs: function(){
this.dom = {};
this.dom.setCodeInput = document.getElementById('st-set-code-input');
this.dom.setCodeSubmit = document.getElementById('st-set-code-submit');
this.dom.getCodeInput = document.getElementById('st-get-code-input');
var self = this;
ShaderTool.Utils.DOMUtils.addEventListener(this.dom.setCodeSubmit, 'click', function( e ){
var code = self.dom.setCodeInput.value;
if(code != ''){
ShaderTool.modules.Rendering.setData(JSON.parse(code), true)
}
})
},
_saveLocalState: function(){
var saveData = ShaderTool.modules.Rendering.getData();
ShaderTool.helpers.LSHelper.setItem('lastShaderData', saveData);
this.dom.getCodeInput.value = JSON.stringify(saveData);
}
}
return new SaveController();
})();
ShaderTool.modules.PopupManager = (function(){
var OPENED_CLASS_NAME = '_opened';
function PopupManager(){}
PopupManager.prototype = {
init: function(){
console.log('ShaderTool.modules.PopupManager.init');
this.dom = {};
this.dom.overlay = document.getElementById('st-popup-overlay');
this._opened = false;
var self = this;
ShaderTool.Utils.DOMUtils.addEventListener(this.dom.overlay, 'mousedown', function( e ){
if( e.target === self.dom.overlay ){
self.close();
}
})
var openers = document.querySelectorAll('[data-popup-opener]');
ShaderTool.Utils.DOMUtils.addEventListener(openers, 'click', function( e ){
self.open( this.getAttribute('data-popup-opener') )
})
},
open: function( popupName ){
this.close();
var popup = this.dom.overlay.querySelector(popupName);
if( popup ){
this._opened = true;
this._currentPopup = popup;
ShaderTool.Utils.DOMUtils.addClass(this._currentPopup, OPENED_CLASS_NAME);
ShaderTool.Utils.DOMUtils.addClass(this.dom.overlay, OPENED_CLASS_NAME);
} else {
// TODO;
}
},
close: function(){
if(!this._opened){
return;
}
this._opened = false;
ShaderTool.Utils.DOMUtils.removeClass(this.dom.overlay, OPENED_CLASS_NAME);
ShaderTool.Utils.DOMUtils.removeClass(this._currentPopup, OPENED_CLASS_NAME);
}
}
return new PopupManager();
})();
// classes
ShaderTool.classes.Rasterizer = (function(){
var VERTEX_SOURCE = 'attribute vec2 av2_vtx;varying vec2 vv2_v;void main(){vv2_v = av2_vtx;gl_Position = vec4(av2_vtx, 0., 1.);}';
function Rasterizer( context ){
this._context = context;
this._program = null;
this._prevProgram = null;
this._buffer = this._context.createVertexBuffer().upload(new ShaderTool.Utils.Float32Array([1,-1,1,1,-1,-1,-1,1]));
this._source = {
program: this._program,
attributes: {
'av2_vtx': {
buffer: this._buffer,
size: 2,
type: this._context.AttribType.Float,
offset: 0
}
},
uniforms: {},
mode: this._context.Primitive.TriangleStrip,
count: 4
};
}
Rasterizer.prototype = {
updateSource: function (fragmentSource) {
var savePrevProgramFlag = true;
try{
var newProgram = this._context.createProgram({
vertex: VERTEX_SOURCE,
fragment: fragmentSource
});
this._source.program = newProgram;
} catch( e ){
console.warn('Error updating Rasterizer fragmentSource: ' + e.message);
savePrevProgramFlag = false;
if(this._prevProgram){
this._source.program = this._prevProgram;
}
}
if(savePrevProgramFlag){
this._prevProgram = newProgram;
}
},
updateUniforms: function(uniforms){
this._source.uniforms = uniforms;
},
render: function ( elapsedTime, frame, resolution, destination ) {
this._source.uniforms['us2_frame'] = this._context.UniformSampler( frame );
this._source.uniforms['uv2_resolution'] = this._context.UniformVec2( resolution );
this._source.uniforms['uf_time'] = this._context.UniformFloat( elapsedTime);
this._context.rasterize(this._source, null, destination);
}
}
return Rasterizer;
})();
| w23/tool.gl | front/js/shadertool.js | JavaScript | mit | 52,669 |
import React, { PureComponent } from "react";
import { graphql } from 'gatsby'
import Link from "gatsby-link";
import path from "ramda/src/path";
import ScrollReveal from "scrollreveal";
import Layout from "../components/Layout";
import "prismjs/themes/prism.css";
import styles from "./post.module.scss";
const getPost = path(["data", "markdownRemark"]);
const getContext = path(["pageContext"]);
const PostNav = ({ prev, next }) => (
<div className={styles.postNav}>
{prev && (
<Link to={`/${prev.fields.slug}`}>
上一篇:
{prev.frontmatter.title}
</Link>
)}
{next && (
<Link to={`/${next.fields.slug}`}>
下一篇:
{next.frontmatter.title}
</Link>
)}
</div>
);
export default class Post extends PureComponent {
componentDidMount() {
ScrollReveal().reveal(".article-header>h1", {
delay: 500,
useDelay: "onload",
reset: true,
origin: "top",
distance: "120px"
});
ScrollReveal().reveal(".article-content", {
delay: 500,
useDelay: "onload",
reset: true,
origin: "bottom",
distance: "120px"
});
}
componentWillUnmount() {
ScrollReveal().destroy();
}
render() {
const post = getPost(this.props);
const { next, prev } = getContext(this.props); // Not to be confused with react context...
return (
<Layout>
<header className="article-header">
<h1>{post.frontmatter.title}</h1>
</header>
<div
className="article-content"
dangerouslySetInnerHTML={{ __html: post.html }}
/>
<PostNav prev={prev} next={next} />
</Layout>
);
}
}
export const query = graphql`
query BlogPostQuery($slug: String!) {
markdownRemark(fields: { slug: { eq: $slug } }) {
html
frontmatter {
title
}
}
}
`;
| EvKylin/Kylin | Example/blog/src/templates/post.js | JavaScript | mit | 1,886 |
import React, {Component} from 'react';
import {View, Text} from 'react-native';
import {xdateToData} from '../../interface';
import XDate from 'xdate';
import dateutils from '../../dateutils';
import styleConstructor from './style';
class ReservationListItem extends Component {
constructor(props) {
super(props);
this.styles = styleConstructor(props.theme);
}
shouldComponentUpdate(nextProps) {
const r1 = this.props.item;
const r2 = nextProps.item;
let changed = true;
if (!r1 && !r2) {
changed = false;
} else if (r1 && r2) {
if (r1.day.getTime() !== r2.day.getTime()) {
changed = true;
} else if (!r1.reservation && !r2.reservation) {
changed = false;
} else if (r1.reservation && r2.reservation) {
if ((!r1.date && !r2.date) || (r1.date && r2.date)) {
changed = this.props.rowHasChanged(r1.reservation, r2.reservation);
}
}
}
return changed;
}
renderDate(date, item) {
if (this.props.renderDay) {
return this.props.renderDay(date ? xdateToData(date) : undefined, item);
}
const today = dateutils.sameDate(date, XDate()) ? this.styles.today : undefined;
if (date) {
return (
<View style={this.styles.day}>
<Text style={[this.styles.dayNum, today]}>{date.getDate()}</Text>
<Text style={[this.styles.dayText, today]}>{XDate.locales[XDate.defaultLocale].dayNamesShort[date.getDay()]}</Text>
</View>
);
} else {
return (
<View style={this.styles.day}/>
);
}
}
render() {
const {reservation, date} = this.props.item;
let content;
if (reservation) {
const firstItem = date ? true : false;
content = this.props.renderItem(reservation, firstItem);
} else {
content = this.props.renderEmptyDate(date);
}
return (
<View style={this.styles.container}>
{this.renderDate(date, reservation)}
<View style={{flex:1}}>
{content}
</View>
</View>
);
}
}
export default ReservationListItem; | eals/react-native-calender-pn-wix-extended | src/agenda/reservation-list/reservation.js | JavaScript | mit | 2,094 |
/*global module:false*/
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
// Metadata.
pkg: grunt.file.readJSON('package.json'),
banner: '/*! <%= pkg.title || pkg.name %> - v<%= pkg.version %> - ' +
'<%= grunt.template.today("yyyy-mm-dd") %>\n' +
'<%= pkg.homepage ? "* " + pkg.homepage + "\\n" : "" %>' +
'* Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %>;' +
' Licensed <%= _.pluck(pkg.licenses, "type").join(", ") %> */\n',
// Task configuration.
concat: {
options: {
banner: '<%= banner %>',
stripBanners: true
},
dist: {
src: ['lib/<%= pkg.name %>.js'],
dest: 'dist/<%= pkg.name %>.js'
}
},
uglify: {
options: {
banner: '<%= banner %>'
},
dist: {
src: '<%= concat.dist.dest %>',
dest: 'dist/<%= pkg.name %>.min.js'
}
},
jshint: {
options: {
curly: true,
eqeqeq: true,
immed: true,
latedef: true,
newcap: true,
noarg: true,
sub: true,
undef: true,
unused: true,
boss: true,
eqnull: true,
browser: true,
globals: {
jQuery: true
}
},
gruntfile: {
src: 'Gruntfile.js'
},
lib_test: {
src: ['lib/**/*.js', 'test/**/*.js']
}
},
qunit: {
files: ['test/**/*.html']
},
watch: {
gruntfile: {
files: '<%= jshint.gruntfile.src %>',
tasks: ['jshint:gruntfile']
},
lib_test: {
files: '<%= jshint.lib_test.src %>',
tasks: ['jshint:lib_test', 'qunit']
},
stylesheets: {
files: 'stylesheets/sass/**/*.scss',
tasks:['sass:dist']
}
},
sass: {
dist: {
files: [{
expand: true,
cwd: 'stylesheets/sass/project',
src: ['*.scss'],
dest: 'stylesheets/styles',
ext: '.css'
}]
}
}
});
// These plugins provide necessary tasks.
//grunt.loadNpmTasks('grunt-contrib-concat');
//grunt.loadNpmTasks('grunt-contrib-uglify');
//grunt.loadNpmTasks('grunt-contrib-qunit');
//grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-sass');
// Default task.
//grunt.registerTask('default', ['jshint', 'qunit', 'concat', 'uglify']);
};
| quekshuy/advocado-overlays | Gruntfile.js | JavaScript | mit | 2,527 |
version https://git-lfs.github.com/spec/v1
oid sha256:2566f139073c240a090aee1fb4254ec2b799a9402dd6494447afbe4e12c97654
size 6184
| yogeshsaroya/new-cdnjs | ajax/libs/yui/3.5.1/matrix/matrix-min.js | JavaScript | mit | 129 |
import React from 'react'
export default class NoteItem extends React.Component {
render () {
return (
<div>
<p>Category = {this.props.note.category}</p>
<p>The Note = {this.props.note.noteText}</p>
<hr />
</div>
)
}
} | josedigital/koala-app | src/components/Note/NoteItem.js | JavaScript | mit | 276 |
///<reference path="./otmword.ts" />
///<reference path="./wmmodules.ts" />
///<reference path="./wgenerator.ts" />
///<reference path="./ntdialog.ts" />
/**
* 単語作成部で使用するViewModel
*/
class WordDisplayVM {
/**
* コンストラクタ
* @param el バインディングを適用するタグのid
* @param dict OTM形式辞書クラス
* @param createSetting 単語文字列作成に使用する設定
*/
constructor(el, dict, createSetting, equivalent) {
this.el = el;
this.data = {
dictionary: dict,
isDisabled: false,
createSetting: createSetting,
id: 1,
equivalent: equivalent,
};
this.initMethods();
}
/**
* VMで使用するメソッドを定義するメソッド
*/
initMethods() {
this.methods = {
/**
* 単語文字列を作成するメソッド
*/
create: function _create() {
let form = "";
switch (this.createSetting.mode) {
case WordGenerator.SIMPLE_SYMBOL:
form = WordGenerator.simple(this.createSetting.simple);
break;
case WordGenerator.SIMPLECV_SYMBOL:
form = WordGenerator.simplecv(this.createSetting.simplecv);
break;
case WordGenerator.DEPENDENCYCV_SYMBOL:
form = WordGenerator.dependencycv(this.createSetting.dependencycv);
break;
default:
break;
}
let word = new OtmWord(this.id++, form);
word.add("");
this.dictionary.add(word);
},
/**
* 設定されている全ての訳語に対して単語を作成するメソッド
*/
createAll: function _createAll() {
this.equivalent.equivalentsList.data.forEach((x) => {
let form = "";
switch (this.createSetting.mode) {
case WordGenerator.SIMPLE_SYMBOL:
form = WordGenerator.simple(this.createSetting.simple);
break;
case WordGenerator.SIMPLECV_SYMBOL:
form = WordGenerator.simplecv(this.createSetting.simplecv);
break;
case WordGenerator.DEPENDENCYCV_SYMBOL:
form = WordGenerator.dependencycv(this.createSetting.dependencycv);
break;
default:
break;
}
let word = new OtmWord(this.id++, form);
word.add(x.equivalents.join(","));
this.dictionary.add(word);
});
},
/**
* 作成した全ての単語を削除するメソッド
*/
removeAll: function _removeAll() {
this.dictionary.removeAll();
// idを初期値にする
this.id = 1;
},
/**
* 作成した単語一覧をOTM-JSON形式で出力するメソッド
*/
outputOtmJSON: function _outputOtmJSON() {
// idを振り直す
let id = 1;
this.dictionary.words.forEach((x) => {
x.entry.id = id++;
});
WMModules.exportJSON(this.dictionary, "dict.json");
// 引き続き作成する場合を考えてidを更新する
this.id = id;
},
// 個々で使用する部分
/**
* 訳語選択ダイアログを呼び出すメソッド
* @param 訳語を設定する単語クラス
*/
showEquivalentDialog: function _showEquivalentDialog(word) {
this.equivalent.selectedWordId = word.entry.id.toString();
WMModules.equivalentDialog.show();
},
/**
* 単語を削除するメソッド
* @param 削除する単語クラス
*/
remove: function _remove(word) {
this.dictionary.remove(word.entry.id);
},
/**
* 単語の区切りの","で文字列を区切って配列にするためのメソッド
* @param 単語の訳語(カンマ区切り)
* @return カンマを区切り文字として分割した結果の文字列配列
*/
splitter: function _splitter(value) {
return value.split(",").map(function (x) { return x.trim(); });
},
};
}
}
//# sourceMappingURL=worddisplayvm.js.map | Nobuyuki-Tokuchi/wordmaker_web | scripts/worddisplayvm.js | JavaScript | mit | 5,118 |
var CategoryLevel = function(){
'use strict';
var categorys = {};
this.addCategory = function(_name) {
categorys[_name] = [];
};
this.addDataToLastCategory = function(_categoryName, _lineData, _className) {
var category = categorys[_categoryName];
};
};
| russellmt/PortfolioProject | app/js/categoryLevel.js | JavaScript | mit | 298 |
/* global $:true */
+ function($) {
var defaults;
var Photos = function(config) {
this.initConfig(config);
this.index = 0;
}
Photos.prototype = {
initConfig: function (config) {
this.config = $.extend({}, defaults, config);
this.activeIndex = this.lastActiveIndex = this.config.initIndex;
this.config.items = this.config.items.map(function(d, i) {
if(typeof d === typeof 'a') {
return {
image: d,
caption: ''
}
}
return d;
});
this.tpl = $.t7.compile(this.config.tpl);
if(this.config.autoOpen) this.open();
},
open: function (index) {
if (this._open) return false;
if (!this.modal) {
this.modal = $(this.tpl(this.config)).appendTo(document.body);
this.container = this.modal.find('.swiper-container');
this.wrapper = this.modal.find('.swiper-wrapper');
var hammer = new Hammer(this.container[0]);
hammer.get('pinch').set({ enable: true });
hammer.on('pinchstart', $.proxy(this.onGestureStart, this));
hammer.on('pinchmove', $.proxy(this.onGestureChange, this));
hammer.on('pinchend', $.proxy(this.onGestureEnd, this));
this.modal.on($.touchEvents.start, $.proxy(this.onTouchStart, this));
this.modal.on($.touchEvents.move, $.proxy(this.onTouchMove, this));
this.modal.on($.touchEvents.end, $.proxy(this.onTouchEnd, this));
//init index
this.wrapper.transition(0);
this.wrapper.transform('translate3d(-' + $(window).width()*this.config.initIndex + 'px,0,0)');
this.container.find('.caption-item').eq(this.config.initIndex).addClass('active');
this.container.find('.swiper-pagination-bullet').eq(this.config.initIndex).addClass('swiper-pagination-bullet-active');
}
var self = this;
this.modal.show().height();
this.modal.addClass('weui-photo-browser-modal-visible');
this.container.addClass('swiper-container-visible').transitionEnd(function() {
self.initParams();
if(index !== undefined) {
self.slideTo(index);
}
if(self.config.onOpen) {
self.config.onOpen.call(self);
}
});
this._open = true;
},
close: function() {
this.container.transitionEnd($.proxy(function() {
this.modal.hide();
this._open = false;
if(this.config.onClose) this.config.onClose.call(this);
}, this));
this.container.removeClass('swiper-container-visible');
this.modal.removeClass('weui-photo-browser-modal-visible');
},
initParams: function () {
if(this.containerHeight) return false;
this.windowWidth = $(window).width();
this.containerHeight = this.container.height();
this.containerWidth = this.container.width();
this.touchStart = {};
this.wrapperTransform = 0;
this.wrapperLastTransform = - $(window).width()*this.config.initIndex;
this.wrapperDiff = 0;
this.lastScale = 1;
this.currentScale = 1;
this.imageLastTransform = { x: 0, y: 0 };
this.imageTransform = { x: 0, y: 0 };
this.imageDiff = { x: 0, y: 0 };
this.imageLastDiff = { x: 0, y: 0 };
},
onTouchStart: function (e) {
if(this.scaling) return false;
this.touching = true;
this.touchStart = $.getTouchPosition(e);
this.touchMove = null;
this.touchStartTime = + new Date;
this.wrapperDiff = 0;
this.breakpointPosition = null;
},
onTouchMove: function (e) {
if(!this.touching || this.scaling) return false;
e.preventDefault();
if(this.gestureImage) {
var rect = this.gestureImage[0].getBoundingClientRect();
if (rect.left >= 0 || rect.right <= this.windowWidth) {
this.overflow = true;
} else {
this.overflow = false;
}
} else {
this.oveflow = false;
}
var p = this.touchMove = $.getTouchPosition(e);
if(this.currentScale === 1 || this.overflow) {
if(this.breakpointPosition) {
this.wrapperDiff = p.x - this.breakpointPosition.x;
} else {
this.wrapperDiff = p.x - this.touchStart.x;
}
if(this.activeIndex === 0 && this.wrapperDiff > 0) this.wrapperDiff = Math.pow(this.wrapperDiff, .8);
if(this.activeIndex === this.config.items.length - 1 && this.wrapperDiff < 0) this.wrapperDiff = - Math.pow(-this.wrapperDiff, .8);
this.wrapperTransform = this.wrapperLastTransform + this.wrapperDiff;
this.doWrapperTransform();
} else {
var img = this.gestureImage;
this.imageDiff = {
x: p.x - this.touchStart.x,
y: p.y - this.touchStart.y
}
this.imageTransform = {
x: this.imageDiff.x + this.imageLastTransform.x,
y: this.imageDiff.y + this.imageLastTransform.y
};
this.doImageTransform();
this.breakpointPosition = p;
this.imageLastDiff = this.imageDiff;
}
},
onTouchEnd: function (e) {
if(!this.touching) return false;
this.touching = false;
if(this.scaling) return false;
var duration = (+ new Date) - this.touchStartTime;
if(duration < 200 && (!this.touchMove || Math.abs(this.touchStart.x - this.touchMove.x) <= 2 && Math.abs(this.touchStart.y - this.touchMove.y) <= 2)) {
this.onClick();
return;
}
if(this.wrapperDiff > 0) {
if(this.wrapperDiff > this.containerWidth/2 || (this.wrapperDiff > 20 && duration < 300)) {
this.slidePrev();
} else {
this.slideTo(this.activeIndex, 200);
}
} else {
if(- this.wrapperDiff > this.containerWidth/2 || (-this.wrapperDiff > 20 && duration < 300)) {
this.slideNext();
} else {
this.slideTo(this.activeIndex, 200);
}
}
this.imageLastTransform = this.imageTransform;
this.adjust();
},
onClick: function () {
var self = this;
if (this._lastClickTime && ( + new Date - this._lastClickTime < 300)) {
this.onDoubleClick();
clearTimeout(this._clickTimeout);
} else {
this._clickTimeout = setTimeout(function () {
self.close();
}, 300);
}
this._lastClickTime = + new Date;
},
onDoubleClick: function () {
this.gestureImage = this.container.find('.swiper-slide').eq(this.activeIndex).find('img');
this.currentScale = this.currentScale > 1 ? 1 : 2;
this.doImageTransform(200);
this.adjust();
},
onGestureStart: function (e) {
this.scaling = true;
this.gestureImage = this.container.find('.swiper-slide').eq(this.activeIndex).find('img');
},
onGestureChange: function (e) {
var s = this.lastScale * e.scale;
if (s > this.config.maxScale) {
s = this.config.maxScale + Math.pow((s - this.config.maxScale), 0.5);
} else if (s < 1) {
s = Math.pow(s, .5);
}
this.currentScale = s;
this.doImageTransform();
},
onGestureEnd: function (e) {
if (this.currentScale > this.config.maxScale) {
this.currentScale = this.config.maxScale;
this.doImageTransform(200);
} else if (this.currentScale < 1) {
this.currentScale = 1;
this.doImageTransform(200);
}
this.lastScale = this.currentScale;
this.scaling = false;
this.adjust();
},
doWrapperTransform: function(duration, callback) {
if (duration === 0) {
var origin = this.wrapper.css('transition-property')
this.wrapper.css('transition-property', 'none').transform('translate3d(' + this.wrapperTransform + 'px, 0, 0)');
this.wrapper.css('transition-property', origin);
callback()
} else {
this.wrapper.transitionEnd(function() {
callback && callback();
});
this.wrapper.transition(duration || defaults.duration).transform('translate3d(' + this.wrapperTransform + 'px, 0, 0)');
}
},
doImageTransform: function(duration, callback) {
if(!this.gestureImage) return;
this.gestureImage.transition(duration || 0).transform('translate3d(' + this.imageTransform.x + 'px,' + this.imageTransform.y + 'px, 0) scale(' + this.currentScale + ')');
this._needAdjust = true;
},
adjust: function() {
if(!this._needAdjust) return false;
var img = this.gestureImage;
if(!img) return false;
if(this.currentScale === 1) {
this.imageTransform = this.imageLastDiff = {x:0,y:0};
this.doImageTransform(200);
return;
}
var rect = img[0].getBoundingClientRect();
//调整上下
if(rect.height < this.containerHeight) { // 如果高度没容器高,则自动居中
this.imageTransform.y = this.imageLastTransform.y = 0;
} else { //如果比容器高,那么要保证上下不能有空隙
if(rect.top > 0) this.imageTransform.y = this.imageTransform.y - rect.top;
else if(rect.bottom < this.containerHeight) this.imageTransform.y = this.imageTransform.y + this.containerHeight - rect.bottom;
}
this.doImageTransform(200);
this._needAdjust = false; // must at last line, because doImageTransform will set this._needAdjust true
},
slideTo: function(index, duration) {
if(index < 0) index = 0;
if(index > this.config.items.length-1) index = this.config.items.length - 1;
this.lastActiveIndex = this.activeIndex;
this.activeIndex = index;
this.wrapperTransform = - (index * this.containerWidth);
this.wrapperLastTransform = this.wrapperTransform;
this.doWrapperTransform(duration, $.proxy(function() {
if(this.lastActiveIndex === this.activeIndex) return false; // active index not change
this.container.find('.caption-item.active').removeClass('active');
this.container.find('.swiper-slide-active').removeClass('swiper-slide-active');
this.container.find('.swiper-pagination-bullet-active').removeClass('swiper-pagination-bullet-active');
this.container.find('.caption-item').eq(this.activeIndex).addClass('active');
this.container.find('.swiper-slide').eq(this.activeIndex).addClass('swiper-slide-active');
this.container.find('.swiper-pagination-bullet').eq(this.activeIndex).addClass('swiper-pagination-bullet-active');
//reset image transform
this.container.find('.swiper-slide img[style]').transition(0).transform('translate3d(0,0,0) scale(1)');
this.lastScale = 1;
this.currentScale = 1;
this.imageLastTransform = { x: 0, y: 0 };
this.imageTransform = { x: 0, y: 0 };
this.imageDiff = { x: 0, y: 0 };
this.imageLastDiff = { x: 0, y: 0 };
if(this.config.onSlideChange) {
this.config.onSlideChange.call(this, this.activeIndex);
}
}, this));
},
slideNext: function() {
return this.slideTo(this.activeIndex+1, 200);
},
slidePrev: function() {
return this.slideTo(this.activeIndex-1, 200);
}
}
defaults = Photos.prototype.defaults = {
items: [],
autoOpen: false, //初始化完成之后立刻打开
onOpen: undefined,
onClose: undefined,
initIndex: 0, //打开时默认显示第几张
maxScale: 3,
onSlideChange: undefined,
duration: 200, // 默认动画时间,如果没有在调用函数的时候指定,则使用这个值
tpl: '<div class="weui-photo-browser-modal">\
<div class="swiper-container">\
<div class="swiper-wrapper">\
{{#items}}\
<div class="swiper-slide">\
<div class="photo-container">\
<img src="{{image}}" />\
</div>\
</div>\
{{/items}}\
</div>\
<div class="caption">\
{{#items}}\
<div class="caption-item caption-item-{{@index}}">{{caption}}</div>\
{{/items}}\
</div>\
<div class="swiper-pagination swiper-pagination-bullets">\
{{#items}}\
<span class="swiper-pagination-bullet"></span>\
{{/items}}\
</div>\
</div>\
</div>'
}
$.photoBrowser = function(params) {
return new Photos(params);
}
}($);
| lihongxun945/jquery-weui | src/js/photos.js | JavaScript | mit | 12,514 |
define(function(){
var config = {};
config.app = 'pregapp'; // Your App name
//config.jqueryMobileTheme = "/francine/css/theme.css";
//config.jqueryMobilePath="/francine/js/jquery.mobile-1.2.0";
//config.jqueryMobileCss="/francine/css/mobile.css";
config.extraScripts = [];
config.quickformsEnding = ""; // "" or ".asp"
config.defaultPageTransition = "none"; // slide, pop, none
config.defaultDialogTransition = "none"; // slide, pop, none
return config;
}); | uoForms/quickforms3 | QF3 Apps/emailSent/js/config.js | JavaScript | mit | 517 |
describe('A Feature', function() {
it('A Scenario', function() {
// ### Given missing code
});
});
| BonsaiDen/featureful | test/validator/step/tests/missingCode.test.js | JavaScript | mit | 121 |
/**
* FlowrouteNumbersLib
*
* This file was automatically generated for flowroute by APIMATIC BETA v2.0 on 02/08/2016
*/
var configuration = {
//The base Uri for API calls
BASEURI : "https://api.flowroute.com/v1",
//Tech Prefix
//TODO: Replace the Username with an appropriate value
username : "TODO: Replace",
//API Secret Key
//TODO: Replace the Password with an appropriate value
password : "TODO: Replace"
};
module.exports = configuration;
| flowroute/flowroute-numbers-nodejs | flowroutenumberslib/lib/configuration.js | JavaScript | mit | 509 |
$(document).ready(function(){
//The user will be prompted to continue and go down the page by clicking on an HTML element
//The result will be a smooth transition of the word ">>>Continue" and then a smooth scroll down the page
//to the next stage of the user's process in the application: making an account(probably done through Google and Facebook)
$(document).ready(function(){
$('#userPrompt>span:nth-child(1)').delay(350).fadeTo(450,1.0);
$('#userPrompt>span:nth-child(2)').delay(450).fadeTo(450,1.0);
$('#userPrompt>span:nth-child(3)').delay(550).fadeTo(450,1.0); //this div represents the bottom option, or the 'quick presentation div'
$('#Continue').delay(700).fadeTo(850,1.0); //Continue button
});
/*$('#userPrompt').click(function(){
$('#promptOverlay').fadeTo(850,0.0);
$(this).delay(850).animate({marginLeft: '900px'}, 850)
$(this).delay(100).fadeOut(850);
});
The "#promptOverlay" div is not longer in use, and as a result, we do not need to use this line of code...
Let's keep things....simpler...
*/
$('#userPrompt').one("click",function(){
$(this).fadeTo(850,0);
//Scroll Down
var height = $("#navBar").css('height');
$('html , body').animate({
scrollTop: 725
}, 1250);
//Create Options on Options Bar div, first by making a dividing line
$('#imagine').delay(1250).animate({
height: '330px'
});
//Create Third option by making it now visible...
$('#quick').delay(1850).fadeTo(300, 1);
//Time to make options visible...
$('.heading').delay(2000).fadeTo(300, 1);
});
//With options now created, we can create some functionality to those options, making the user's experience both meaningful and aesthetically pleasing.
/*$('#returner, #imagine').click(function(){
//alert("Log into account"); Test
$('.heading').fadeTo(850, 0);
$('#quick').fadeOut();
$('#imagine').delay(250).animate({
height: '0px'
});
$('#optionsBar').delay(1400).css("background-color", "rgb(215,215,215)");
$('#optionsBar');
});*/
/*$('#newUser').one("click", function(){
//alert("Make account"); Test
$('#optionsBar>div').fadeOut(850);
$('#optionsBar').delay(1400).css("background-color", "rgb(215,215,215)");
var welcomeHeader = '<h3 margin-top="20px" class="heading">Welcome to ShowCase. Please Log In Below...</h3>';
var inputTypeOne = '<input type="text/plain">keep'
//$('h3').delay(1900).html("Welcome to ShowCase. Please Log In Below...").appendTo("#optionsBar");
$(welcomeHeader).hide().delay(2000).appendTo('#optionsBar').fadeIn(100);
var styles = {
fontFamily: 'Lato',
color: 'rgba(16,16,14,0.65)',
paddingTop: '10px',
};
// $(welcomeHeader).css(headerStyle);
$('#optionsBar').css(styles);
});//End of Account Creation Process...*
$('#quick').click(function(){
//alert("I just don't care."); Test
$('.heading').fadeTo(850, 0);
$('#quick').fadeOut();
$('#imagine').delay(250).animate({
height: '0px'
});
$('#optionsBar').delay(1400).css("background-color", "rgb(215,215,215)");
});*/
}); | clutchRoy/treeBranc | script.js | JavaScript | mit | 3,028 |