code stringlengths 2 1.05M |
|---|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var ic_open_in_new = exports.ic_open_in_new = { "viewBox": "0 0 24 24", "children": [{ "name": "path", "attribs": { "d": "M19 19H5V5h7V3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2v-7h-2v7zM14 3v2h3.59l-9.83 9.83 1.41 1.41L19 6.41V10h2V3h-7z" } }] }; |
var instanceURL = gs.getProperty("glide.servlet.uri");
var overrideURL = gs.getProperty("glide.email.override.url");
if (overrideURL){
instanceURL = overrideURL;
}
else{
instanceURL = instanceURL;
}
var url = instanceURL + 'com.glideapp.servicecatalog_cat_item_view.do?sysparm_id=299dbe0b0a0a3c4501c8951df102a2ae&manager_request=' + current.sys_id + '&first_name=' + current.u_first_name + '&last_name=' + current.u_last_name + '&known_as=' + current.u_known_as + '&job_title=' + current.u_job_title + '&grade=' + current.u_grade + '®ion=' + current.u_region + '§or=' + current.u_sector + '&service_line=' + current.u_service_line + '&employee_id=' + current.u_employee_id + '&manager_name=' + current.u_manager_name + '&start_date=' + current.u_start_date + '&contrator=' + current.u_contractor + '&end_date=' + current.u_end_date + '&hr_comments=' + current.u_hr_comments;
gs.log(url);
action.setRedirectURL(url);
//condition
current.u_request_id == '' && current.u_request_type == 'Starter' && current.u_assigned_to == gs.userID() || current.u_request_id == '' && current.u_request_type == 'Starter' && current.u_manager_name == gs.userID()
|
var Settings = {
TileSize: 32,
DebugCollision: false,
DebugSkipBootLogo: false,
MatchmakingUri: 'http://burningtomato.com:2013'
}; |
'use strict';
angular.module('core',['Repos']); |
/**
* controllers/signin.js
*/
var bcrypt = require('bcryptjs');
var request = require('request');
var jwt = require('jwt-simple');
module.exports = function( app, auth, config, User ) {
// Sign in with Email
app.post('/auth/login', function( req, res ) {
User.findOne({ email: req.body.email }, '+password', function( err, user ) {
if ( !user ) {
return res.status(401).send({ message: { email: 'Incorrect email' } });
}
bcrypt.compare(req.body.password, user.password, function(err, isMatch) {
if (!isMatch) {
return res.status(401).send({ message: { password: 'Incorrect password' } });
}
user = user.toObject();
delete user.password;
var token = auth.createToken( user );
res.send({ token: token, user: user });
});
});
});
// Create Email and Password Account
app.post('/auth/signup', function(req, res) {
User.findOne({ email: req.body.email }, function(err, existingUser) {
if (existingUser) {
return res.status(409).send({ message: 'Email is already taken.' });
}
var user = new User({
email: req.body.email,
password: req.body.password
});
bcrypt.genSalt(10, function(err, salt) {
bcrypt.hash(user.password, salt, function(err, hash) {
user.password = hash;
user.save(function() {
var token = auth.createToken(user);
res.send({ token: token, user: user });
});
});
});
});
});
// Sign in with Instagram
app.post('/auth/instagram', function(req, res) {
var accessTokenUrl = 'https://api.instagram.com/oauth/access_token';
var params = {
client_id: req.body.clientId,
redirect_uri: req.body.redirectUri,
client_secret: config.clientSecret,
code: req.body.code,
grant_type: 'authorization_code'
};
// Step 1. Exchange authorization code for access token.
request.post({ url: accessTokenUrl, form: params, json: true }, function(error, response, body) {
// Step 2a. Link user accounts.
if (req.headers.authorization) {
User.findOne({ instagramId: body.user.id }, function(err, existingUser) {
var token = req.headers.authorization.split(' ')[1];
var payload = jwt.decode(token, config.tokenSecret);
User.findById(payload.sub, '+password', function(err, localUser) {
if (!localUser) {
return res.status(400).send({ message: 'User not found.' });
}
// Merge two accounts. Instagram account takes precedence. Email account is deleted.
if (existingUser) {
existingUser.email = localUser.email;
existingUser.password = localUser.password;
localUser.remove();
existingUser.save(function() {
var token = auth.createToken(existingUser);
return res.send({ token: token, user: existingUser });
});
} else {
// Link current email account with the Instagram profile information.
localUser.instagramId = body.user.id;
localUser.username = body.user.username;
localUser.fullName = body.user.full_name;
localUser.picture = body.user.profile_picture;
localUser.accessToken = body.access_token;
localUser.save(function() {
var token = auth.createToken(localUser);
res.send({ token: token, user: localUser });
});
}
});
});
} else {
// Step 2b. Create a new user account or return an existing one.
User.findOne({ instagramId: body.user.id }, function(err, existingUser) {
if (existingUser) {
var token = auth.createToken(existingUser);
return res.send({ token: token, user: existingUser });
}
var user = new User({
instagramId: body.user.id,
username: body.user.username,
fullName: body.user.full_name,
picture: body.user.profile_picture,
accessToken: body.access_token
});
user.save(function() {
var token = auth.createToken(user);
res.send({ token: token, user: user });
});
});
}
});
});
} |
var express = require('express');
var app = express();
app.use('/', express.static('../'));
app.listen(9999); |
import React, { Component } from 'react'
import axios from 'axios'
import Form from "react-jsonschema-form";
import VerbalsList from '../components/verbals-form'
import {root_url} from './config'
class VerbalsComponent extends Component {
constructor (props) {
super(props)
this.state = {
selectedMessage: 'start_transfer_request',
newMessage: '',
schema: {
},
profiles: []
}
this.handleSelectChange = this.handleSelectChange.bind(this)
this.handleTextAreaChange = this.handleTextAreaChange.bind(this)
this.handleButtonSubmit = this.handleButtonSubmit.bind(this)
}
log (type) {
console.log.bind(console, type)
}
onSubmit ({formData}) {
const _this = this
axios.post(root_url + '/save-profile', formData)
.then(() => {
return axios.get(root_url + '/get-profiles')
})
.then(({data}) => {
_this.setState({
profiles: data
})
})
}
handleSelectChange(event) {
this.setState({
selectedMessage: event.target.value
}
)
console.log(this.state)
setTimeout(console.log(this.state), 1000)
}
handleTextAreaChange (event) {
this.setState({
newMessage: event.target.value
})
console.log(this.state)
}
handleButtonSubmit (event) {
event.preventDefault();
const _this = this
axios.post(root_url + '/save-message', {
[_this.state.selectedMessage] : _this.state.newMessage
})
.then(() => {
return window.location.reload()
})
}
componentDidMount () {
const _this = this
// Make a request for a user with a given ID
axios.get(root_url + '/get-schema/verbals')
.then(function (response) {
// handle success
_this.setState({
schema: response.data
})
})
.catch(function (error) {
// handle error
console.log(error);
})
.then(function () {
// always executed
});
}
render () {
return <div className="row mt-4">
<div className="col-md-6">
<form onSubmit={this.handleButtonSubmit}>
<div className="form-group">
<label>Select a message to change</label>
<select id="message_id" className="form-control" onChange={this.handleSelectChange}>
{
(this.state.schema && Object.keys(this.state.schema).length) &&
Object.entries(this.state.schema.properties).map((key, ink) => (
<option key={ink + `__key`}>{key[0]}</option>
))
}
</select>
</div>
<div className="form-group">
<label>Enter new message and submit</label>
<textarea className="form-control" onChange={this.handleTextAreaChange}>
</textarea>
</div>
<div className="form-group row">
<div className="col-sm-10">
<button type="submit" className="btn btn-primary">Request Change</button>
</div>
</div>
</form>
</div>
<div className="col-md-6" style={{"overflow":"auto"}}>
<VerbalsList />
</div>
</div>
}
}
export default VerbalsComponent |
/*eslint no-cond-assign: "error"*/
if (user.jobTitle = 'manager') {
// user.jobTitle is now incorrect
}
/*eslint valid-typeof: "error"*/
typeof foo === 'fucntion' // The typo in the 'function' word.
/*eslint no-self-compare: "error"*/
if (x === x) {
x = 20;
}
/*eslint no-sparse-arrays: "error"*/
var colors = ['red',, 'blue']; // extra comma
/*eslint array-callback-return: "error"*/
[1, 2, 3].map(function(value) {
value + 1; // forget to write `return`
}); // [undefined, undefined, undefined]
/*eslint curly: "error"*/
if (foo) foo++; bar++; // forget to wrap `bar++`
/*eslint no-redeclare: "error"*/
var a = 3;
var a = 10;
/*eslint no-new: "error"*/
new Person();
/*eslint no-return-assign: "error"*/
function doSomething() {
return foo = bar + 2; // The true intent was to do a comparison (`==` or `===`).
}
/*eslint no-throw-literal: "error"*/
throw "error";
/*eslint no-unexpected-multiline: "error"*/
var bar = 'bar'
var foo = bar // This entry is equivalent to `var foo = bar(1 || 2).toString()`.
(1 || 2).toString();
/*eslint no-unsafe-negation: "error"*/
if (!key in object) {
// Operator precedence makes it equivalent to (!key) in object
// and type conversion makes it equivalent to (key ? "false" : "true") in object.
}
if (!obj instanceof Ctor) {
// Operator precedence makes it equivalent to (!obj) instanceof Ctor
// and it equivalent to always false since boolean values are not objects.
}
/*eslint no-extra-bind: "error"*/
var x = function () {
return 'bla';
}.bind(bar); // useless bind, can be safely removed
|
/*
* Scenes are Dealers of Cards. Scenes must support a setStage() and a strikeStage() method,
* when any Cards they contain get dealt and/or removed/replaced.
* We make a distinction between Scene Cards and game Widgets, in that Scene Cards don't necessarily
* persist through the whole Game and don't need to interact with the Game.
* They're more decorative, but they can be functional wrt animations.
*/
Game.Scene = {}
Game.Scene.new = Game.new.bind(Game.Scene);
Game.Scene.SetPiece = {}
// a factory for creating Scenes (Dealers).
Game.SceneFactory = {
create: function (game, scene_spec, events) {
var scene_type_name = scene_spec.scene_type || "Basic";
var backdrop_spec = scene_spec.backdrop || "div";
var set_piece_specs = scene_spec.set_pieces || [];
var scene_type, scene;
in_production_try(this, function () {
if (Game.Scene.hasOwnProperty(scene_type_name)) {
scene_type = Game.Scene[scene_type_name];
} else {
scene_type = Game.Scene.Basic;
}
scene = new scene_type(scene_type_name, backdrop_spec, set_piece_specs, game);
scene.spec = scene_spec;
if (events === "mock") { return scene; }
scene.init(events);
// associate scene w the rounds it is used in.
scene.rounds = scene_spec.rounds || "all";
// pull rounds spec from scene YAML.
if ((typeof scene.rounds === "object") && (scene.rounds[0])) {
scene.rounds = scene.rounds[0];
}
if (scene.rounds instanceof Array) {
// do nothing. that's what we want.
} else if (!isNaN(Math.round(scene.rounds))) {
// if it is a number, put that in (make sure it is an integer).
scene.rounds = [Math.round(scene.rounds)];
} else if (typeof scene.rounds === "string") {
if (scene.rounds === "all") {
// make an array of all rounds.
scene.rounds = $(game.rounds).collect(function (i) { return i + 1; });
} else {
// match to a regex that will pull all numbers & indicate 'runs'.
// assemble an array.
scene.rounds = Util.numberArrayFromTokenList(scene.rounds);
}
} else {
console.warn("Can't assign scene to rounds", scene, scene.rounds);
scene.rounds = [];
}
});
return scene;
}
}
Game.Scene.Basic = Util.extendClass(Game.Dealer, function Game_Scene_Basic (scene_type_name, backdrop_spec, set_piece_specs, game) {
Game.Dealer.call(this, game);
this.scene_type_name = scene_type_name;
this.backdrop = new Game.Card(backdrop_spec);
this.set_piece_specs = set_piece_specs;
this.onstage = false; // we should be able to switch out scenes while saving their state.
},
{
init: function (events) {
// track all of the state transitions that happen in Rounds.
// *** insure that only one listener gets created for each enter and leave event.
var round_events = $.collect(events, function () {
return "Round.leave" + this.from + " Round.enter" + this.to;
});
// strip out duplicates and put into a space-delimited string.
round_events = Array.getUnique(round_events).join(" ");
var _this = this;
$(document).on(round_events, function (evt, state_info) {
return _this.followRoundEvent(evt, state_info)
});
},
// I respond to Round setup events by loading my background and dealing my cards.
setup: function (round) {
var dfd = $.Deferred();
if (!this.onstage) {
var backdrop_classes = "backdrop " + this.scene_type_name.underscore();
this.backdrop.style(backdrop_classes);
// put down the backdrop, then create and add the set pieces.
var _this = this;
var set_piece_id;
this.deal(this.backdrop).then(function () {
_this.set_pieces = $.collect(_this.set_piece_specs, function (i) {
var card_spec = this;
if (card_spec instanceof String) {
card_spec = card_spec.toString();
}
var set_piece = _this.addCard(Game.Scene.SetPieceFactory.create(_this, card_spec));
set_piece.style("set_piece");
// if the set_piece has an id associated with it, save its jQuery object as a member of the scene.
// (eg; div#tower yields this.tower).
if (set_piece.element.attr("id")) {
if (set_piece_id = set_piece.element.attr("id").replace("-", "_")) {
if (!_this.hasOwnProperty(set_piece_id)) {
_this[set_piece_id] = set_piece.element;
}
}
}
return set_piece;
});
if (_this.set_pieces.length) {
// deal the set pieces into the backdrop.
_this.deal(_this.set_pieces, _this.backdrop.element).then(function() {
// once all the Cards are dealt, call finalize(),
// so custom scripts will have access to them all.
round.scene = _this;
_this.finalize(round);
_this.onstage = true;
// all round to move on.
dfd.resolve();
});
} else {
_this.finalize(round);
dfd.resolve();
}
});
} else {
dfd.resolve();
}
return dfd.promise();
},
tearDown: function () {
$(this.cards).each(function () {
this.remove();
});
this.backdrop.remove();
},
finalize: function () {
// kept for custom code.
},
followRoundEvent: function (evt, state_info) {
// game scenes can have a handler function named for entering or leaving any Round state,
// which will get executed at that point.
// if an appropriate handler is defined on the scene,
// call it, passing the event and the info object.
// don't interrupt the game if there are any problems, as
// this is all for decoration.
try {
if (typeof this[evt.namespace] === "function") {
return (this[evt.namespace]).bind(this)(evt, state_info);
}
} catch (e) {
console.error("Scene error in responding to Round state transition.", evt, e, e.stack);
}
}
});
/*
* SetPieces are the Cards held by a Scene.
*/
// a factory for creating SetPieces (Cards).
Game.Scene.SetPieceFactory = {
create: function (scene, set_piece_spec) {
var set_piece_type_name;
try {
set_piece_type_name = set_piece_spec["set_piece_type"] || "Basic";
} catch (e) {
set_piece_type_name = "Basic";
}
return in_production_try(this, function () {
return new Game.Scene.SetPiece[set_piece_type_name](set_piece_spec);
});
}
}
Game.Scene.SetPiece.Basic = Util.extendClass(Game.Card, function Game_Scene_SetPiece_Basic (card_spec) {
Game.Card.call(this, card_spec)
}); |
import reducer from './credentials.reducer'
export default reducer
export * from './credentials.actions'
export * from './credentials.selectors'
|
'use strict';
ApplicationConfiguration.registerModule('ero-timesheet-template');
|
define([
"Praxigento_Core/js/grid/column/link"
], function (Column) {
"use strict";
return Column.extend({
defaults: {
/* see \Praxigento\BonusHybrid\Ui\DataProvider\Downline\Grid\A\Repo\Query\Grid::A_PARENT_MLM_ID */
idAttrName: "parentMlmId",
route: "/customer/downline/index/mlmId/"
}
});
});
|
'use strict';
/**
* Module dependencies.
*/
var passport = require('passport'),
url = require('url'),
LinkedInStrategy = require('passport-linkedin').Strategy,
config = require('../config'),
users = require('../../server/controllers/users');
module.exports = function() {
// Use linkedin strategy
passport.use(new LinkedInStrategy({
consumerKey: config.linkedin.clientID,
consumerSecret: config.linkedin.clientSecret,
callbackURL: config.linkedin.callbackURL,
passReqToCallback: true,
profileFields: ['id', 'first-name', 'last-name', 'email-address']
},
function(req, accessToken, refreshToken, profile, done) {
// Set the provider data and include tokens
var providerData = profile._json;
providerData.accessToken = accessToken;
providerData.refreshToken = refreshToken;
// Create the user OAuth profile
var providerUserProfile = {
firstName: profile.name.givenName,
lastName: profile.name.familyName,
displayName: profile.displayName,
email: profile.emails[0].value,
username: profile.username,
provider: 'linkedin',
providerIdentifierField: 'id',
providerData: providerData
};
// Save the user OAuth profile
users.saveOAuthUserProfile(req, providerUserProfile, done);
}
));
};
|
// # Demo Filters 017
// Filter parameters: displace
// [Run code](../../demo/filters-017.html)
import * as scrawl from '../source/scrawl.js';
import { reportSpeed, addImageDragAndDrop } from './utilities.js';
// Get Scrawl-canvas to recognise and act on device pixel ratios greater than 1
scrawl.setIgnorePixelRatio(false);
// #### Scene setup
const canvas = scrawl.library.canvas.mycanvas;
scrawl.importDomImage('.flowers');
// Create the filter
scrawl.makeFilter({
name: 'noise',
method: 'image',
asset: 'perlin',
width: 500,
height: 500,
copyWidth: '100%',
copyHeight: '100%',
lineOut: 'map',
});
const myFilter = scrawl.makeFilter({
name: 'displace',
method: 'displace',
lineMix: 'map',
offsetX: 0,
offsetY: 0,
scaleX: 1,
scaleY: 1,
});
// Create the target entity
const piccy = scrawl.makePicture({
name: 'base-piccy',
asset: 'iris',
width: '100%',
height: '100%',
copyWidth: '100%',
copyHeight: '100%',
method: 'fill',
filters: ['noise', 'displace'],
});
// #### Scene animation
// Function to display frames-per-second data, and other information relevant to the demo
const report = reportSpeed('#reportmessage', function () {
// @ts-expect-error
return ` Scales - x: ${scaleX.value}, y: ${scaleY.value}\n Offset - x: ${offsetX.value}, y: ${offsetY.value}\n Opacity: ${opacity.value}`;
});
// Create the Display cycle animation
const demoAnimation = scrawl.makeRender({
name: "demo-animation",
target: canvas,
afterShow: report,
});
// #### User interaction
// Setup form observer functionality
scrawl.observeAndUpdate({
event: ['input', 'change'],
origin: '.controlItem',
target: myFilter,
useNativeListener: true,
preventDefault: true,
updates: {
offset_x: ['offsetX', 'round'],
offset_y: ['offsetY', 'round'],
scale_x: ['scaleX', 'float'],
scale_y: ['scaleY', 'float'],
transparent_edges: ['transparentEdges', 'boolean'],
opacity: ['opacity', 'float'],
},
});
// Setup form
const offsetX = document.querySelector('#offset_x'),
offsetY = document.querySelector('#offset_y'),
scaleX = document.querySelector('#scale_x'),
scaleY = document.querySelector('#scale_y'),
opacity = document.querySelector('#opacity');
// @ts-expect-error
offsetX.value = 0;
// @ts-expect-error
offsetY.value = 0;
// @ts-expect-error
scaleX.value = 1;
// @ts-expect-error
scaleY.value = 1;
// @ts-expect-error
opacity.value = 1;
// @ts-expect-error
document.querySelector('#transparent_edges').options.selectedIndex = 0;
// #### Drag-and-Drop image loading functionality
addImageDragAndDrop(canvas, '#my-image-store', piccy);
// #### Development and testing
console.log(scrawl.library);
|
import React from 'react';
import _ from 'lodash';
import staticApi from '../static/api';
import ChampionIcon from './ChampionIcon';
import Picker from './Picker';
import setChampion from '../actions/setChampion';
class ChampionPicker extends React.Component {
constructor(props) {
super(props);
this.state = {target: null, picked: null, visible: false};
this.pickChampion = this.pickChampion.bind(this);
}
pickChampion(event, champion) {
this.setState({visible: false, target: null});
this.context.executeAction(setChampion, {champion: champion});
}
render() {
if (!this.state.target) {
return null;
}
let selected = this.state.champion;
let otherChampions = _.without(staticApi.getChampions(), selected);
// Display selected first
let champions = [selected].concat(otherChampions);
let championIcons = champions.map((champion) => {
return <ChampionIcon champion={champion} onClick={this.pickChampion}/>
});
return <Picker target={this.state.target} visible={this.state.visible}>
{championIcons}
</Picker>;
}
}
ChampionPicker.contextTypes = {
executeAction: React.PropTypes.func.isRequired
};
export default ChampionPicker;
|
var stackedy = require('../');
var test = require('tap').test;
var fs = require('fs');
var src = fs.readFileSync(__dirname + '/sources/deep.js', 'utf8');
test('nestDelay', function (t) {
t.plan(2);
var stack = stackedy(src).run({ process : process });
stack.on('error', function (err, c) {
stack.stop();
t.equal(err, 'moo');
t.deepEqual(
c.stack.map(function (s) { return s.functionName }),
[
'qualia', null, 'nextTick', 'zzz',
'setTimeout', null, 'setTimeout',
'yyy', 'xxx', 'setTimeout', 'h', 'g', 'f'
]
);
t.end();
});
});
|
import {fixPlusMinus} from '../../src/lib/symbols/plus-minus'
import assert from 'assert'
import Locale from '../../src/locale/locale'
describe('Fix plus-minus symbol ±\n', () => {
let testCase = {
'+-': '±',
'-+': '±',
}
Object.keys(testCase).forEach((key) => {
it('', () => {
assert.equal(fixPlusMinus(key, new Locale('en-us')), testCase[key])
})
})
})
|
(function () {
var Ext = window.Ext4 || window.Ext;
var appIDMap = {
milestone: -200004,
iteration: -200013,
release: -200012
};
Ext.define('Rally.apps.timeboxes.TimeboxesApp', {
extend: 'Rally.app.GridBoardApp',
requires: [
'Deft.Deferred',
'Rally.apps.timeboxes.IterationVelocityA0Chart',
'Rally.data.PreferenceManager',
'Rally.ui.combobox.plugin.PreferenceEnabledComboBox',
'Rally.ui.gridboard.GridBoardToggle'
],
enableGridBoardToggle: true,
xmlExportEnabled: function(){
return this.selectedType !== 'milestone';
},
loadSettingsAndLaunch: function () {
if (this.modelPicker) {
this.callParent(arguments);
} else {
this._createPicker().then({
success: function (selectedType) {
this.changeModelType(selectedType);
},
scope: this
});
}
},
changeModelType: function (newType) {
this.context = this.getContext().clone({
appID: appIDMap[newType]
});
this.selectedType = newType;
this.modelNames = [newType];
this.statePrefix = newType;
this.loadSettingsAndLaunch();
},
getGridBoardTogglePluginConfig: function () {
return _.merge(this.callParent(arguments), {
autoRefreshComponentOnToggle: false,
toggleButtonConfig: {
showBoardToggle: false,
showChartToggle: this._enableCharts() ? true : Rally.ui.gridboard.GridBoardToggle.BUTTON_DISABLED
}
});
},
getChartConfig: function () {
if (this._enableCharts()) {
return {
xtype: 'rallyiterationvelocitya0chart'
};
}
},
getFieldPickerConfig: function () {
var config = this.callParent(arguments);
if (this.selectedType === 'milestone') {
config.gridFieldBlackList = _.union(config.gridFieldBlackList, [
'Artifacts',
'CreationDate',
'Projects',
'VersionId'
]);
return _.merge(config, {
gridAlwaysSelectedValues: ['TargetDate', 'TotalArtifactCount', 'TargetProject']
});
}
return config;
},
getPermanentFilters: function () {
return this.selectedType === 'milestone' ? [
Rally.data.wsapi.Filter.or([
{ property: 'Projects', operator: 'contains', value: this.getContext().getProjectRef() },
{ property: 'TargetProject', operator: '=', value: null }
])
] : [];
},
getAddNewConfig: function () {
return _.merge(this.callParent(arguments), {
minWidth: 800,
openEditorAfterAddFailure: false,
showAddWithDetails: true,
showRank: false
});
},
getGridStoreConfig: function() {
return _.merge(this.callParent(arguments), {
sorters: [ {property: this._getStartDateFieldName(), direction: 'DESC'} ]
});
},
_getStartDateFieldName: function () {
return {
milestone: 'TargetDate',
iteration: 'StartDate',
release: 'ReleaseStartDate'
}[this.selectedType];
},
_enableCharts: function () {
return this.selectedType === 'iteration';
},
_createPicker: function () {
var deferred = new Deft.Deferred();
this.modelPicker = Ext.create('Rally.ui.combobox.ComboBox', {
context: this.getContext().clone({
appID: null
}),
displayField: 'name',
editable: false,
listeners: {
change: this._onTimeboxTypeChanged,
ready: {
fn: function (combo) {
deferred.resolve(combo.getValue());
},
single: true
},
scope: this
},
plugins: [{
ptype: 'rallypreferenceenabledcombobox',
preferenceName: 'timebox-combobox'
}],
queryMode: 'local',
renderTo: Ext.query('#content .titlebar .dashboard-timebox-container')[0],
storeType: 'Ext.data.Store',
storeConfig: {
fields: ['name', 'type'],
data: [
{ name: 'Iterations', type: 'iteration' },
{ name: 'Releases', type: 'release' },
{ name: 'Milestones', type: 'milestone' }
]
},
valueField: 'type'
});
return deferred.promise;
},
_onTimeboxTypeChanged: function () {
if (this.modelPicker) {
this.changeModelType(this.modelPicker.getValue());
}
}
});
})(); |
var class_max_flow =
[
[ "MaxFlow", "class_max_flow.html#ace10d45cfe4765a66c77c20f8f9b79ab", null ],
[ "~MaxFlow", "class_max_flow.html#a010a238596368ba8dcf2d79dbd16c126", null ],
[ "MaxFlow", "class_max_flow.html#ace10d45cfe4765a66c77c20f8f9b79ab", null ],
[ "~MaxFlow", "class_max_flow.html#a010a238596368ba8dcf2d79dbd16c126", null ],
[ "add_edge", "class_max_flow.html#a0db7214c4bfe7c0f6ba4c124fcf5c978", null ],
[ "add_edge", "class_max_flow.html#a0db7214c4bfe7c0f6ba4c124fcf5c978", null ],
[ "check_flow", "class_max_flow.html#ab5186f313e04f25e6a65bd3b3a7708c7", null ],
[ "check_flow", "class_max_flow.html#ab5186f313e04f25e6a65bd3b3a7708c7", null ],
[ "component_gap", "class_max_flow.html#a25a36d5b5077434d62d573e7a6908b5c", null ],
[ "component_gap", "class_max_flow.html#a25a36d5b5077434d62d573e7a6908b5c", null ],
[ "component_relabelling", "class_max_flow.html#a23e8d8fb67a77b1c9b8c24fe0e482f75", null ],
[ "component_relabelling", "class_max_flow.html#a23e8d8fb67a77b1c9b8c24fe0e482f75", null ],
[ "compute_thrs_project_l1", "class_max_flow.html#a933e25c3ebc85618e15bfbc8027573c7", null ],
[ "compute_thrs_project_l1", "class_max_flow.html#a933e25c3ebc85618e15bfbc8027573c7", null ],
[ "deactivate", "class_max_flow.html#a65662453300a06bafbb4a767b4f3aa8d", null ],
[ "deactivate", "class_max_flow.html#a65662453300a06bafbb4a767b4f3aa8d", null ],
[ "deactivate", "class_max_flow.html#ab9fac209f3b734d73c77729c9bcc51db", null ],
[ "deactivate", "class_max_flow.html#ab9fac209f3b734d73c77729c9bcc51db", null ],
[ "discharge", "class_max_flow.html#a1e2f2e3a003126517ebcdf88154082a3", null ],
[ "discharge", "class_max_flow.html#a1e2f2e3a003126517ebcdf88154082a3", null ],
[ "extractConnexComponents", "class_max_flow.html#a11bd9249f1fdb6ba2326a6a2d85d9d9f", null ],
[ "extractConnexComponents", "class_max_flow.html#a11bd9249f1fdb6ba2326a6a2d85d9d9f", null ],
[ "flow_component", "class_max_flow.html#abeced0faf38c3018483dc05c54d860b4", null ],
[ "flow_component", "class_max_flow.html#abeced0faf38c3018483dc05c54d860b4", null ],
[ "gap_relabelling", "class_max_flow.html#a7e6b6798caa3c73aa1157bcc62fc2f6d", null ],
[ "gap_relabelling", "class_max_flow.html#a7e6b6798caa3c73aa1157bcc62fc2f6d", null ],
[ "getMaxFlow", "class_max_flow.html#a3824039e63cd1c3f1aaaa799c44c75d2", null ],
[ "getMaxFlow", "class_max_flow.html#a3824039e63cd1c3f1aaaa799c44c75d2", null ],
[ "global_relabelling", "class_max_flow.html#a3e6e855f4f38a8950dd5ca37f8490c4a", null ],
[ "global_relabelling", "class_max_flow.html#a3e6e855f4f38a8950dd5ca37f8490c4a", null ],
[ "init_split_variables", "class_max_flow.html#a8c6fd7019f1094325ac6a67dbd64ad22", null ],
[ "init_split_variables", "class_max_flow.html#a8c6fd7019f1094325ac6a67dbd64ad22", null ],
[ "init_split_variables_aux", "class_max_flow.html#ab639fb1c0fb74a3babac4ec0e04e591e", null ],
[ "init_split_variables_aux", "class_max_flow.html#ab639fb1c0fb74a3babac4ec0e04e591e", null ],
[ "norm", "class_max_flow.html#a3f913881172eba6685847a5aeed6c022", null ],
[ "norm", "class_max_flow.html#a3f913881172eba6685847a5aeed6c022", null ],
[ "nzmax", "class_max_flow.html#af022d9e30793110375ee9aca18b10a5b", null ],
[ "nzmax", "class_max_flow.html#af022d9e30793110375ee9aca18b10a5b", null ],
[ "perform_maxflow", "class_max_flow.html#a2f328ee0b0134f01f1e6a83fcc1a5214", null ],
[ "perform_maxflow", "class_max_flow.html#a2f328ee0b0134f01f1e6a83fcc1a5214", null ],
[ "perform_maxflow_component", "class_max_flow.html#ab037d1cd17053ac5b34161da44860493", null ],
[ "perform_maxflow_component", "class_max_flow.html#ab037d1cd17053ac5b34161da44860493", null ],
[ "print_component", "class_max_flow.html#ac444c3ac0066b0b488a25739b0a638b5", null ],
[ "print_component", "class_max_flow.html#ac444c3ac0066b0b488a25739b0a638b5", null ],
[ "print_component2", "class_max_flow.html#abfee3ace0192774be4e34593a9087c19", null ],
[ "print_component2", "class_max_flow.html#abfee3ace0192774be4e34593a9087c19", null ],
[ "print_excess", "class_max_flow.html#a496c2bb78a9ec260772d47b1070ccafd", null ],
[ "print_excess", "class_max_flow.html#a496c2bb78a9ec260772d47b1070ccafd", null ],
[ "print_graph", "class_max_flow.html#a857ccd97cf80a29b8040a53a8fc00f69", null ],
[ "print_graph", "class_max_flow.html#a857ccd97cf80a29b8040a53a8fc00f69", null ],
[ "print_graph_aux", "class_max_flow.html#acf3649eefc99237feaab5dd4e8b230fc", null ],
[ "print_graph_aux", "class_max_flow.html#acf3649eefc99237feaab5dd4e8b230fc", null ],
[ "print_labels", "class_max_flow.html#a747693b7ac89357503b05806bbc89984", null ],
[ "print_labels", "class_max_flow.html#a747693b7ac89357503b05806bbc89984", null ],
[ "print_sink", "class_max_flow.html#ac5878a03e1a07664f5d8019585586a62", null ],
[ "print_sink", "class_max_flow.html#ac5878a03e1a07664f5d8019585586a62", null ],
[ "project", "class_max_flow.html#a3b9fc49aabfb910d2222c7829484e469", null ],
[ "project", "class_max_flow.html#a3b9fc49aabfb910d2222c7829484e469", null ],
[ "project_box", "class_max_flow.html#a9666d1cac3c9166564033cf65fb06e9c", null ],
[ "project_box", "class_max_flow.html#a9666d1cac3c9166564033cf65fb06e9c", null ],
[ "project_weighted", "class_max_flow.html#aa6a905e55ab2a46605917d9dd0738086", null ],
[ "project_weighted", "class_max_flow.html#aa6a905e55ab2a46605917d9dd0738086", null ],
[ "reset_component", "class_max_flow.html#abf8f984dba894b15c63ce87bc51bd54e", null ],
[ "reset_component", "class_max_flow.html#abf8f984dba894b15c63ce87bc51bd54e", null ],
[ "reset_flow", "class_max_flow.html#ae587b7f8117ce70c2c33673c5444c60e", null ],
[ "reset_flow", "class_max_flow.html#ae587b7f8117ce70c2c33673c5444c60e", null ],
[ "restore_capacities", "class_max_flow.html#acde0385691dfc8eb0333948f57a9158e", null ],
[ "restore_capacities", "class_max_flow.html#acde0385691dfc8eb0333948f57a9158e", null ],
[ "restore_capacities", "class_max_flow.html#ad1b44b2c4cb47497bccd6196ab274175", null ],
[ "restore_capacities", "class_max_flow.html#ad1b44b2c4cb47497bccd6196ab274175", null ],
[ "restore_flow", "class_max_flow.html#a25ca77b46c65ccbb5dae5d550ec186fd", null ],
[ "restore_flow", "class_max_flow.html#a25ca77b46c65ccbb5dae5d550ec186fd", null ],
[ "save_capacities", "class_max_flow.html#a206c0597bed908f17dc852a31c9b0378", null ],
[ "save_capacities", "class_max_flow.html#a206c0597bed908f17dc852a31c9b0378", null ],
[ "save_flow", "class_max_flow.html#ae8123882f6d3257a1d23032725fd7676", null ],
[ "save_flow", "class_max_flow.html#ae8123882f6d3257a1d23032725fd7676", null ],
[ "scale_flow", "class_max_flow.html#a53865215b0339004d36af023f1fe3dfe", null ],
[ "scale_flow", "class_max_flow.html#a53865215b0339004d36af023f1fe3dfe", null ],
[ "set_capacities_groups", "class_max_flow.html#aacc3c29d517e184261b9b7999c0e8cb3", null ],
[ "set_capacities_groups", "class_max_flow.html#aacc3c29d517e184261b9b7999c0e8cb3", null ],
[ "set_capacities_variables", "class_max_flow.html#ad9e5d5aca7eec90afb22c0f7f946c620", null ],
[ "set_capacities_variables", "class_max_flow.html#ad9e5d5aca7eec90afb22c0f7f946c620", null ],
[ "set_weights", "class_max_flow.html#ac8d76de2e68cc8f9d4bbe1e5592b90ea", null ],
[ "set_weights", "class_max_flow.html#ac8d76de2e68cc8f9d4bbe1e5592b90ea", null ],
[ "set_weights", "class_max_flow.html#a1f863db46670193cc0bd7947c140a35c", null ],
[ "set_weights", "class_max_flow.html#a1f863db46670193cc0bd7947c140a35c", null ],
[ "splitComponent", "class_max_flow.html#ad862fd5b85b64a059fd45598f991ac43", null ],
[ "splitComponent", "class_max_flow.html#ad862fd5b85b64a059fd45598f991ac43", null ],
[ "sub_gradient", "class_max_flow.html#afdf156d06860bb104110286b055261cf", null ],
[ "sub_gradient", "class_max_flow.html#afdf156d06860bb104110286b055261cf", null ],
[ "sub_gradient_aux", "class_max_flow.html#a7b30567c6acd921753f5bffc70875991", null ],
[ "sub_gradient_aux", "class_max_flow.html#a7b30567c6acd921753f5bffc70875991", null ],
[ "update_capacities", "class_max_flow.html#a8d47d1ea35a68f89694216e4fc6700fc", null ],
[ "update_capacities", "class_max_flow.html#a8d47d1ea35a68f89694216e4fc6700fc", null ],
[ "update_capacities_aux", "class_max_flow.html#a2bdb48266be6d8934b6881d74871f70e", null ],
[ "update_capacities_aux", "class_max_flow.html#a2bdb48266be6d8934b6881d74871f70e", null ]
]; |
(function() {
'use strict';
angular
.module('app.account')
.factory('RegisterDialog', RegisterDialog);
RegisterDialog.$inject = ['$uibModal'];
function RegisterDialog($uibModal) {
var service = {
open: open
};
var modalInstance = null;
return service;
function open() {
if (modalInstance !== null) {
return;
}
modalInstance = $uibModal.open({
templateUrl: 'app/account/register/register.html',
controller: 'RegisterController',
controllerAs: 'vm'
});
modalInstance.result
.then(resetModal, resetModal);
}
function resetModal() {
modalInstance = null;
}
}
})();
|
!function($, wysi) {
"use strict";
var tpl = {
"font-styles": function(locale, options) {
var size = (options && options.size) ? ' btn-'+options.size : '';
return "<li class='dropdown'>" +
"<a class='btn btn-default dropdown-toggle" + size + "' data-toggle='dropdown' href='#'>" +
"<i class='fa fa-font'></i> <span class='current-font'>" + locale.font_styles.normal + "</span> <i class='fa fa-angle-down'></i>" +
"</a>" +
"<ul class='dropdown-menu'>" +
"<li><a data-wysihtml5-command='formatBlock' data-wysihtml5-command-value='div' tabindex='-1'>" + locale.font_styles.normal + "</a></li>" +
"<li><a data-wysihtml5-command='formatBlock' data-wysihtml5-command-value='h1' tabindex='-1'>" + locale.font_styles.h1 + "</a></li>" +
"<li><a data-wysihtml5-command='formatBlock' data-wysihtml5-command-value='h2' tabindex='-1'>" + locale.font_styles.h2 + "</a></li>" +
"<li><a data-wysihtml5-command='formatBlock' data-wysihtml5-command-value='h3' tabindex='-1'>" + locale.font_styles.h3 + "</a></li>" +
"<li><a data-wysihtml5-command='formatBlock' data-wysihtml5-command-value='h4'>" + locale.font_styles.h4 + "</a></li>" +
"<li><a data-wysihtml5-command='formatBlock' data-wysihtml5-command-value='h5'>" + locale.font_styles.h5 + "</a></li>" +
"<li><a data-wysihtml5-command='formatBlock' data-wysihtml5-command-value='h6'>" + locale.font_styles.h6 + "</a></li>" +
"</ul>" +
"</li>";
},
"emphasis": function(locale, options) {
var size = (options && options.size) ? ' btn-'+options.size : '';
return "<li>" +
"<div class='btn-group'>" +
"<a class='btn btn-default" + size + "' data-wysihtml5-command='bold' title='CTRL+B' tabindex='-1'>" + locale.emphasis.bold + "</a>" +
"<a class='btn btn-default" + size + "' data-wysihtml5-command='italic' title='CTRL+I' tabindex='-1'>" + locale.emphasis.italic + "</a>" +
"<a class='btn btn-default" + size + "' data-wysihtml5-command='underline' title='CTRL+U' tabindex='-1'>" + locale.emphasis.underline + "</a>" +
"</div>" +
"</li>";
},
"lists": function(locale, options) {
var size = (options && options.size) ? ' btn-'+options.size : '';
return "<li>" +
"<div class='btn-group'>" +
"<a class='btn btn-default" + size + "' data-wysihtml5-command='insertUnorderedList' title='" + locale.lists.unordered + "' tabindex='-1'><i class='fa fa-list'></i></a>" +
"<a class='btn btn-default" + size + "' data-wysihtml5-command='insertOrderedList' title='" + locale.lists.ordered + "' tabindex='-1'><i class='fa fa-th-list'></i></a>" +
"<a class='btn btn-default" + size + "' data-wysihtml5-command='Outdent' title='" + locale.lists.outdent + "' tabindex='-1'><i class='fa fa-outdent'></i></a>" +
"<a class='btn btn-default" + size + "' data-wysihtml5-command='Indent' title='" + locale.lists.indent + "' tabindex='-1'><i class='fa fa-indent'></i></a>" +
"</div>" +
"</li>";
},
"link": function(locale, options) {
var size = (options && options.size) ? ' btn-'+options.size : '';
return "<li>" +
"<div class='bootstrap-wysihtml5-insert-link-modal modal fade'>" +
($.fn.modalmanager ? "" : "<div class='modal-dialog'>") +
" <div class='modal-content'>" +
"<div class='modal-header'>" +
"<a class='close' data-dismiss='modal'></a>" +
"<h4 class='modal-title'>" + locale.link.insert + "</h4>" +
"</div>" +
"<div class='modal-body'>" +
"<input type='text' value='http://' class='bootstrap-wysihtml5-insert-link-url1 form-control large'>" +
"<label style='margin-top:5px;'> <input type='checkbox' class='bootstrap-wysihtml5-insert-link-target' checked>" + locale.link.target + "</label>" +
"</div>" +
"<div class='modal-footer'>" +
"<a href='#' class='btn btn-default' data-dismiss='modal'>" + locale.link.cancel + "</a>" +
"<a href='#' class='btn btn-primary green' data-dismiss='modal'>" + locale.link.insert + "</a>" +
"</div>" +
"</div>" +
($.fn.modalmanager ? "" : "</div>") +
"</div>" +
"<a class='btn btn-default" + size + "' data-wysihtml5-command='createLink' title='" + locale.link.insert + "' tabindex='-1'><i class='fa fa-share'></i></a>" +
"</li>";
},
"image": function(locale, options) {
var size = (options && options.size) ? ' btn-'+options.size : '';
return "<li>" +
"<div class='bootstrap-wysihtml5-insert-image-modal modal fade'>" +
($.fn.modalmanager ? "" : "<div class='modal-dialog'>") +
" <div class='modal-content'>" +
"<div class='modal-header'>" +
"<a class='close' data-dismiss='modal'></a>" +
"<h4 class='modal-title'>" + locale.image.insert + "</h4>" +
"</div>" +
"<div class='modal-body'>" +
"<input type='text' value='http://' class='bootstrap-wysihtml5-insert-image-url form-control large'>" +
"</div>" +
"<div class='modal-footer'>" +
"<a href='#' class='btn btn-default' data-dismiss='modal'>" + locale.image.cancel + "</a>" +
"<a href='#' class='btn btn-primary green' data-dismiss='modal'>" + locale.image.insert + "</a>" +
"</div>" +
"</div>" +
($.fn.modalmanager ? "" : "</div>") +
"</div>" +
"<a class='btn btn-default" + size + "' data-wysihtml5-command='insertImage' title='" + locale.image.insert + "' tabindex='-1'><i class='fa fa-picture-o'></i></a>" +
"</li>";
},
"html": function(locale, options) {
var size = (options && options.size) ? ' btn-'+options.size : '';
return "<li>" +
"<div class='btn-group'>" +
"<a class='btn btn-default" + size + "' data-wysihtml5-action='change_view' title='" + locale.html.edit + "' tabindex='-1'><i class='fa fa-pencil'></i></a>" +
"</div>" +
"</li>";
},
"color": function(locale, options) {
var size = (options && options.size) ? ' btn-'+options.size : '';
return "<li class='dropdown'>" +
"<a class='btn btn-default dropdown-toggle" + size + "' data-toggle='dropdown' href='#' tabindex='-1'>" +
"<span class='current-color'>" + locale.colours.black + "</span> <i class='fa fa-angle-down'></i>" +
"</a>" +
"<ul class='dropdown-menu'>" +
"<li><div class='wysihtml5-colors' data-wysihtml5-command-value='black'></div><a class='wysihtml5-colors-title' data-wysihtml5-command='foreColor' data-wysihtml5-command-value='black'>" + locale.colours.black + "</a></li>" +
"<li><div class='wysihtml5-colors' data-wysihtml5-command-value='silver'></div><a class='wysihtml5-colors-title' data-wysihtml5-command='foreColor' data-wysihtml5-command-value='silver'>" + locale.colours.silver + "</a></li>" +
"<li><div class='wysihtml5-colors' data-wysihtml5-command-value='gray'></div><a class='wysihtml5-colors-title' data-wysihtml5-command='foreColor' data-wysihtml5-command-value='gray'>" + locale.colours.gray + "</a></li>" +
"<li><div class='wysihtml5-colors' data-wysihtml5-command-value='maroon'></div><a class='wysihtml5-colors-title' data-wysihtml5-command='foreColor' data-wysihtml5-command-value='maroon'>" + locale.colours.maroon + "</a></li>" +
"<li><div class='wysihtml5-colors' data-wysihtml5-command-value='red'></div><a class='wysihtml5-colors-title' data-wysihtml5-command='foreColor' data-wysihtml5-command-value='red'>" + locale.colours.red + "</a></li>" +
"<li><div class='wysihtml5-colors' data-wysihtml5-command-value='purple'></div><a class='wysihtml5-colors-title' data-wysihtml5-command='foreColor' data-wysihtml5-command-value='purple'>" + locale.colours.purple + "</a></li>" +
"<li><div class='wysihtml5-colors' data-wysihtml5-command-value='green'></div><a class='wysihtml5-colors-title' data-wysihtml5-command='foreColor' data-wysihtml5-command-value='green'>" + locale.colours.green + "</a></li>" +
"<li><div class='wysihtml5-colors' data-wysihtml5-command-value='olive'></div><a class='wysihtml5-colors-title' data-wysihtml5-command='foreColor' data-wysihtml5-command-value='olive'>" + locale.colours.olive + "</a></li>" +
"<li><div class='wysihtml5-colors' data-wysihtml5-command-value='navy'></div><a class='wysihtml5-colors-title' data-wysihtml5-command='foreColor' data-wysihtml5-command-value='navy'>" + locale.colours.navy + "</a></li>" +
"<li><div class='wysihtml5-colors' data-wysihtml5-command-value='blue'></div><a class='wysihtml5-colors-title' data-wysihtml5-command='foreColor' data-wysihtml5-command-value='blue'>" + locale.colours.blue + "</a></li>" +
"<li><div class='wysihtml5-colors' data-wysihtml5-command-value='orange'></div><a class='wysihtml5-colors-title' data-wysihtml5-command='foreColor' data-wysihtml5-command-value='orange'>" + locale.colours.orange + "</a></li>" +
"</ul>" +
"</li>";
}
};
var templates = function(key, locale, options) {
return tpl[key](locale, options);
};
var Wysihtml5 = function(el, options) {
this.el = el;
var toolbarOpts = options || defaultOptions;
for(var t in toolbarOpts.customTemplates) {
tpl[t] = toolbarOpts.customTemplates[t];
}
this.toolbar = this.createToolbar(el, toolbarOpts);
this.editor = this.createEditor(options);
window.editor = this.editor;
$('iframe.wysihtml5-sandbox').each(function(i, el){
$(el.contentWindow).off('focus.wysihtml5').on({
'focus.wysihtml5' : function(){
$('li.dropdown').removeClass('open');
}
});
});
};
Wysihtml5.prototype = {
constructor: Wysihtml5,
createEditor: function(options) {
options = options || {};
// Add the toolbar to a clone of the options object so multiple instances
// of the WYISYWG don't break because "toolbar" is already defined
options = $.extend(true, {}, options);
options.toolbar = this.toolbar[0];
var editor = new wysi.Editor(this.el[0], options);
if(options && options.events) {
for(var eventName in options.events) {
editor.on(eventName, options.events[eventName]);
}
}
return editor;
},
createToolbar: function(el, options) {
var self = this;
var toolbar = $("<ul/>", {
'class' : "wysihtml5-toolbar",
'style': "display:none"
});
var culture = options.locale || defaultOptions.locale || "en";
for(var key in defaultOptions) {
var value = false;
if(options[key] !== undefined) {
if(options[key] === true) {
value = true;
}
} else {
value = defaultOptions[key];
}
if(value === true) {
toolbar.append(templates(key, locale[culture], options));
if(key === "html") {
this.initHtml(toolbar);
}
if(key === "link") {
this.initInsertLink(toolbar);
}
if(key === "image") {
this.initInsertImage(toolbar);
}
}
}
if(options.toolbar) {
for(key in options.toolbar) {
toolbar.append(options.toolbar[key]);
}
}
toolbar.find("a[data-wysihtml5-command='formatBlock']").click(function(e) {
var target = e.target || e.srcElement;
var el = $(target);
self.toolbar.find('.current-font').text(el.html());
});
toolbar.find("a[data-wysihtml5-command='foreColor']").click(function(e) {
var target = e.target || e.srcElement;
var el = $(target);
self.toolbar.find('.current-color').text(el.html());
});
this.el.before(toolbar);
return toolbar;
},
initHtml: function(toolbar) {
var changeViewSelector = "a[data-wysihtml5-action='change_view']";
toolbar.find(changeViewSelector).click(function(e) {
toolbar.find('a.btn').not(changeViewSelector).toggleClass('disabled');
});
},
initInsertImage: function(toolbar) {
var self = this;
var insertImageModal = toolbar.find('.bootstrap-wysihtml5-insert-image-modal');
var urlInput = insertImageModal.find('.bootstrap-wysihtml5-insert-image-url');
var insertButton = insertImageModal.find('a.btn-primary');
var initialValue = urlInput.val();
var caretBookmark;
var insertImage = function() {
var url = urlInput.val();
urlInput.val(initialValue);
self.editor.currentView.element.focus();
if (caretBookmark) {
self.editor.composer.selection.setBookmark(caretBookmark);
caretBookmark = null;
}
self.editor.composer.commands.exec("insertImage", url);
};
urlInput.keypress(function(e) {
if(e.which == 13) {
insertImage();
insertImageModal.modal('hide');
}
});
insertButton.click(insertImage);
insertImageModal.on('shown', function() {
urlInput.focus();
});
insertImageModal.on('hide', function() {
self.editor.currentView.element.focus();
});
toolbar.find('a[data-wysihtml5-command=insertImage]').click(function() {
var activeButton = $(this).hasClass("wysihtml5-command-active");
if (!activeButton) {
self.editor.currentView.element.focus(false);
caretBookmark = self.editor.composer.selection.getBookmark();
insertImageModal.appendTo('body').modal('show');
insertImageModal.on('click.dismiss.modal', '[data-dismiss="modal"]', function(e) {
e.stopPropagation();
});
return false;
}
else {
return true;
}
});
},
initInsertLink: function(toolbar) {
var self = this;
var insertLinkModal = toolbar.find('.bootstrap-wysihtml5-insert-link-modal');
var urlInput = insertLinkModal.find('.bootstrap-wysihtml5-insert-link-url');
var targetInput = insertLinkModal.find('.bootstrap-wysihtml5-insert-link-target');
var insertButton = insertLinkModal.find('a.btn-primary');
var initialValue = urlInput.val();
var caretBookmark;
var insertLink = function() {
var url = urlInput.val();
urlInput.val(initialValue);
self.editor.currentView.element.focus();
if (caretBookmark) {
self.editor.composer.selection.setBookmark(caretBookmark);
caretBookmark = null;
}
var newWindow = targetInput.prop("checked");
self.editor.composer.commands.exec("createLink", {
'href' : url,
'target' : (newWindow ? '_blank' : '_self'),
'rel' : (newWindow ? 'nofollow' : '')
});
};
var pressedEnter = false;
urlInput.keypress(function(e) {
if(e.which == 13) {
insertLink();
insertLinkModal.modal('hide');
}
});
insertButton.click(insertLink);
insertLinkModal.on('shown', function() {
urlInput.focus();
});
insertLinkModal.on('hide', function() {
self.editor.currentView.element.focus();
});
toolbar.find('a[data-wysihtml5-command=createLink]').click(function() {
var activeButton = $(this).hasClass("wysihtml5-command-active");
if (!activeButton) {
self.editor.currentView.element.focus(false);
caretBookmark = self.editor.composer.selection.getBookmark();
insertLinkModal.appendTo('body').modal('show');
App.initUniform(); //initialize uniform checkboxes
insertLinkModal.on('click.dismiss.modal', '[data-dismiss="modal"]', function(e) {
e.stopPropagation();
});
return false;
}
else {
return true;
}
});
}
};
// these define our public api
var methods = {
resetDefaults: function() {
$.fn.wysihtml5.defaultOptions = $.extend(true, {}, $.fn.wysihtml5.defaultOptionsCache);
},
bypassDefaults: function(options) {
return this.each(function () {
var $this = $(this);
$this.data('wysihtml5', new Wysihtml5($this, options));
});
},
shallowExtend: function (options) {
var settings = $.extend({}, $.fn.wysihtml5.defaultOptions, options || {}, $(this).data());
var that = this;
return methods.bypassDefaults.apply(that, [settings]);
},
deepExtend: function(options) {
var settings = $.extend(true, {}, $.fn.wysihtml5.defaultOptions, options || {});
var that = this;
return methods.bypassDefaults.apply(that, [settings]);
},
init: function(options) {
var that = this;
return methods.shallowExtend.apply(that, [options]);
}
};
$.fn.wysihtml5 = function ( method ) {
if ( methods[method] ) {
return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof method === 'object' || ! method ) {
return methods.init.apply( this, arguments );
} else {
$.error( 'Method ' + method + ' does not exist on jQuery.wysihtml5' );
}
};
$.fn.wysihtml5.Constructor = Wysihtml5;
var defaultOptions = $.fn.wysihtml5.defaultOptions = {
"font-styles": true,
"color": false,
"emphasis": true,
"lists": true,
"html": false,
"link": true,
"image": true,
events: {},
parserRules: {
classes: {
// (path_to_project/lib/css/wysiwyg-color.css)
"wysiwyg-color-silver" : 1,
"wysiwyg-color-gray" : 1,
"wysiwyg-color-white" : 1,
"wysiwyg-color-maroon" : 1,
"wysiwyg-color-red" : 1,
"wysiwyg-color-purple" : 1,
"wysiwyg-color-fuchsia" : 1,
"wysiwyg-color-green" : 1,
"wysiwyg-color-lime" : 1,
"wysiwyg-color-olive" : 1,
"wysiwyg-color-yellow" : 1,
"wysiwyg-color-navy" : 1,
"wysiwyg-color-blue" : 1,
"wysiwyg-color-teal" : 1,
"wysiwyg-color-aqua" : 1,
"wysiwyg-color-orange" : 1
},
tags: {
"b": {},
"i": {},
"br": {},
"ol": {},
"ul": {},
"li": {},
"h1": {},
"h2": {},
"h3": {},
"h4": {},
"h5": {},
"h6": {},
"blockquote": {},
"u": 1,
"img": {
"check_attributes": {
"width": "numbers",
"alt": "alt",
"src": "url",
"height": "numbers"
}
},
"a": {
check_attributes: {
'href': "url", // important to avoid XSS
'target': 'alt',
'rel': 'alt'
}
},
"span": 1,
"div": 1,
// to allow save and edit files with code tag hacks
"code": 1,
"pre": 1
}
},
stylesheets: ["./wysiwyg-color.css"], // (path_to_project/lib/css/wysiwyg-color.css)
locale: "en"
};
if (typeof $.fn.wysihtml5.defaultOptionsCache === 'undefined') {
$.fn.wysihtml5.defaultOptionsCache = $.extend(true, {}, $.fn.wysihtml5.defaultOptions);
}
var locale = $.fn.wysihtml5.locale = {
en: {
font_styles: {
normal: "Normal text",
h1: "Heading 1",
h2: "Heading 2",
h3: "Heading 3",
h4: "Heading 4",
h5: "Heading 5",
h6: "Heading 6"
},
emphasis: {
bold: "Bold",
italic: "Italic",
underline: "Underline"
},
lists: {
unordered: "Unordered list",
ordered: "Ordered list",
outdent: "Outdent",
indent: "Indent"
},
link: {
insert: "Insert link",
cancel: "Cancel",
target: "Open link in new window"
},
image: {
insert: "Insert image",
cancel: "Cancel"
},
html: {
edit: "Edit HTML"
},
colours: {
black: "Black",
silver: "Silver",
gray: "Grey",
maroon: "Maroon",
red: "Red",
purple: "Purple",
green: "Green",
olive: "Olive",
navy: "Navy",
blue: "Blue",
orange: "Orange"
}
}
};
}(window.jQuery, window.wysihtml5);
|
var assert = require('assert')
var request = require('supertest')
var app = require('../app')
var req = request(app)
describe('app', function () {
function eq(a, b) { assert.strictEqual(a, b) }
it('has index', function (done) {
req
.get('')
.expect('content-type', 'text/html; charset=UTF-8')
.expect(200, done)
})
it('has favicon.ico', function (done) {
req
.get('/favicon.ico')
.expect('content-type', 'image/x-icon')
.expect('content-length', '1150')
.expect(200, done)
})
it('has robots.txt', function (done) {
req
.get('/robots.txt')
.expect('content-type', 'text/plain; charset=UTF-8')
.expect('content-length', '24')
.expect(200, done)
})
it('must not use X-Powered-By header', function (done) {
req
.get('')
.end(function (err, res) {
eq(res.get('x-powered-by'))
done(err)
})
})
it('redirects index.html', function (done) {
req
.get('/index.html')
.expect('location', '/')
.expect(301, done)
})
})
|
var express = require('express');
var router = express.Router();
var path = require('path');
var viewDir = '/Users/Kirsti/Documents/Koodi/helmet/views';
/* GET home page. */
router.get('/', function(req, res) {
//res.render('index', { title: 'Express' });
res.render('index', {title: 'Alkusivu'});
});
router.get('/lastenkirjoja', function(req, res) {
res.render('lastenkirjoja');
});
router.get('/romaaneja', function(req, res) {
res.render('romaaneja');
});
router.get('/tietokirjoja', function(req, res) {
res.render('tietokirjoja');
});
router.get('/kaikki', function(req, res) {
res.render('kaikki');
});
module.exports = router;
|
(function () {
'use strict';
}());
/*
* @author WMXPY
* @version 1.1.17
* This method is no longer recommended
*/
var Cs$ = {
}
var Cp$ = {
/**
*
* @param {object} init
* @returns
*/
animate: function (init) {
return setTimeout(next, init.duration);
function next() {
if (init.content.length > 0) {
let content = init.content.shift();
init.target[init.elem] = content;
setTimeout(next, init.duration);
return null;
} else {
return;
}
}
}
}
var Co$ = {
/**
* @param {target of Vuejs} target
* @param {data of Caper} data
*/
Typing: function (target, data) {
let capersettings = {
contect: []
};
for (var i in data) capersettings[i] = data[i];
return this.typing(target, capersettings);
},
Caper: function (target, data) {
var capersettings = {
frame: 'Vue',
elem: 'test',
data: {
start: null,
end: null
},
content: [],
duration: 500,
mode: 'rnimate'
};
for (var i in data) capersettings[i] = data[i];
return this.varify(target, capersettings);
},
caperjs: {
rnimate: function (target, data) {
return setInterval(() => {
target[data.elem] = data.content[Cp$.globol.randoms(data.content.length)];
}, data.duration);
},
animate: function (target, data) {
return setTimeout(() => {
if (data.content.length > 0) {
let content = data.content.shift();
target[data.elem] = content;
setTimeout(next, data.duration);
} else {
return null;
}
}, data.duration);
},
iter: function (target, data) {
let value = data.data.start;
let end = data.data.end;
if (end.length != value.length) value = caperfun.random.string(end.length);
let count = 0;
let dur = Math.max(data.duration, 50);
let safeword = setInterval(() => {
value = howmuchsame(end, value);
target[data.elem] = value;
if (value != end) {
count++;
} else {
clearInterval(safeword);
}
}, dur);
//todo
function howmuchsame(tar, val) {
var diff = tar.length;
for (var i = 0; i < tar.length; i++) {
if (val.charAt(i) != tar.charAt(i)) {
var ran = caperfun.random.instring(diff, tar.charAt(i))
val = val.substring(0, i) + ran + val.substring(i + 1, val.length);
} else {
diff--;
}
}
return val;
}
return data.data.start;
},
countup: function (elem, data) {
var startVal = data.start;
var endVal = data.end;
var decimal = data.decimal;
var duration = data.duration;
var value;
function startCount(time) {
// time is original function taht caalled
//after one run, requestAnimationFrame will applay timestamp to s
value = startVal + (endVal - startVal) * (time / duration);
value = Math.min(endVal, value);
elem.innerHTML = value.toFixed(decimal);
if (time < duration) requestAnimationFrame(startCount);
}
requestAnimationFrame(startCount);
},
countdown: function (elem, data, mode) {
var startVal = data.start;
var endVal = data.end;
var decimal = data.decimal;
var duration = data.duration;
var value = startVal;
//normal count
function startCount(time) {
//after one run, requestAnimationFrame will applay timestamp to s
value = Math.max(endVal, startVal - (startVal - endVal) * (time / duration));
elem.innerHTML = value.toFixed(decimal);
if (time < duration) requestAnimationFrame(startCount);
}
//sec count
function secCount() {
//Count as timer
value = value - 1;
if (value < endVal) {
data.endfunction();
return null;
} else {
elem.innerHTML = value.toFixed(decimal);
setTimeout(secCount, 1000);
}
}
//switch of modes
switch (mode) {
case 'normal':
requestAnimationFrame(startCount);
break;
case 'sec':
setTimeout(secCount, 100);
break;
default:
requestAnimationFrame(startCount);
}
}
},
varify: function (target, data) {
switch (data.mode) {
case 'animate':
return this.caperjs.animate(target, data);
case 'rnimate':
case 'ranimate':
case 'randomanimate':
return this.caperjs.rnimate(target, data);
case 'iter':
return this.caperjs.iter(target, data);
case 'countup':
return this.caperjs.countup(target, data);
default:
console.warn('Module Undefinded');
return 0;
}
},
globol: {
randoms: (limit) => {
return Math.floor(Math.random() * 10000) % limit;
}
}
}
var Ca$ = {
img: function (inin) {
//default
var ajaxsettings = {
target: 'default',
url: 'mengw.io',
data: '',
//default async
//true for ajax, false for delay
async: true,
//default cache
cache: true,
//default 40s timeout
//not really support yet
timeout: 40000,
//default call back json
callback: 'json',
//default IE 6
IEborwser: 'Microsoft.XMLHTTP',
//default form
contentType: 'application/x-www-form-urlencoded',
encode: [],
//default consolelog
success: function (data) {
console.log(data);
},
//default consoleerror
//updated to alert
error: function (error) {
console.debug(error);
}
};
//inin method
for (var i in inin) {
ajaxsettings[i] = inin[i];
}
if (ajaxsettings.encode.length > 0) {
for (let i = 0; i < ajaxsettings.encode.length; i++) {
if (ajaxsettings.encode[i]) {
ajaxsettings.data[ajaxsettings.encode[i]] = ajaxsettings.data[ajaxsettings.encode[i]].replace(/\+/g, "%2B").replace(/\&/g, "%26");
}
}
}
//create object
//convert object to string
if (typeof ajaxsettings.data === 'object') {
var str = '';
var value = '';
for (var key in ajaxsettings.data) {
value = ajaxsettings.data[key];
//replace & in url
if (ajaxsettings.data[key].indexOf('&') !== -1) {
value = ajaxsettings.data[key].replace(/\&/g, "%26");
}
//replace & in key
if (key.indexOf('&') !== -1) {
key = key.replace(/&/g, escape('&'));
}
str += key + '=' + value + '&';
}
str = str.replace(/\+/g, "%2B");
str = str.replace(/\&/g, "%26");
ajaxsettings.data = str.substring(0, str.length - 1);
}
//cache
let cache = '';
if (!ajaxsettings.cache) {
cache = '&' + new Date().getTime();
}
//for old browser
let ajaxobject = null;
if (window.XMLHttpRequest) {
//for Human Browser
ajaxobject = new XMLHttpRequest();
} else if (window.ActiveXObject) {
//for non-human Browser
ajaxobject = new ActiveXObject(ajaxsettings.IEborwser);
} else {
//for Borwser not support ajax
console.log('Not supported, im done');
}
//shake with server
ajaxobject.open('POST', ajaxsettings.url, ajaxsettings.async);
//send request
ajaxobject.setRequestHeader("Content-type", ajaxsettings.contentType);
ajaxobject.send(ajaxsettings.data);
//waiting for response
ajaxobject.onreadystatechange = function () {
if (ajaxobject.readyState === 4) {
if (ajaxobject.status === 200)
ajaxsettings.success.call(ajaxobject, ajaxobject.responseText);
else {
ajaxsettings.error.call(ajaxobject, ajaxobject.responseText);
}
}
};
},
get: function (inin) {
//default
var ajaxsettings = {
//default link
target: 'default',
url: '',
//default No data sended
data: '',
//default async
//true for ajax, false for delay
async: true,
//default cache
cache: true,
//default 40s timeout
//not really support yet
timeout: 40000,
//default call back json
callback: 'json',
encode: false,
//default IE 6
IEborwser: 'Microsoft.XMLHTTP',
//default form
contentType: 'application/x-www-form-urlencoded',
//default consolelog
success: function (data) {
console.log(data);
},
//default consolelog
//updated to alert
error: function (error) {
console.log(error);
}
};
//inin method
for (let i in inin) ajaxsettings[i] = inin[i];
if (ajaxsettings.encode == true) {
let stringfy = JSON.stringify(ajaxsettings.data);
stringfy = stringfy.replace(/\+/g, "%2B");
stringfy = stringfy.replace(/\&/g, "%26");
ajaxsettings.data = JSON.parse(stringfy);
}
//create object
//convert object to string
if (typeof ajaxsettings.data === 'object') {
var str = '';
var value = '';
for (var key in ajaxsettings.data) {
value = ajaxsettings.data[key];
//replace & in url
if (ajaxsettings.data[key].indexOf('&') !== -1) value = ajaxsettings.data[key].replace(/&/g, escape('&'));
//replace & in key
if (key.indexOf('&') !== -1) {
key = key.replace(/&/g, escape('&'));
}
str += key + '=' + value + '&';
}
ajaxsettings.data = str.substring(0, str.length - 1);
}
let cache = '';
if (!ajaxsettings.cache) {
cache = '&' + new Date().getTime();
}
//chche url
ajaxsettings.url += '?' + ajaxsettings.data + cache;
//for old browser
var ajaxobject = null;
if (window.XMLHttpRequest) {
//for Human Browser
ajaxobject = new XMLHttpRequest();
} else if (window.ActiveXObject) {
//for non-human Browser
ajaxobject = new ActiveXObject(ajaxsettings.IEborwser);
} else {
//for Borwser not support ajax
console.log('Not supported, im done');
}
//shake with server
ajaxobject.open('GET', ajaxsettings.url, ajaxsettings.async);
//send request
ajaxobject.send(null);
//waiting for response
ajaxobject.onreadystatechange = function () {
if (ajaxobject.readyState === 4) {
if (ajaxobject.status === 200)
ajaxsettings.success.call(ajaxobject, ajaxobject.responseText);
else {
ajaxsettings.error.call(ajaxobject, ajaxobject.responseText);
}
}
};
},
post: function (inin) {
//default
var ajaxsettings = {
target: 'default',
url: './main.php',
data: '',
//default async
//true for ajax, false for delay
async: true,
//default cache
cache: true,
//default 40s timeout
//not really support yet
timeout: 40000,
//default call back json
callback: 'json',
//default IE 6
IEborwser: 'Microsoft.XMLHTTP',
//default form
contentType: 'application/x-www-form-urlencoded',
encode: [],
//default consolelog
success: function (data) {
console.log(data);
},
//default consolelog
//updated to alert
error: function (error) {
console.log(error);
alert(error);
}
};
//inin method
for (var i in inin) {
ajaxsettings[i] = inin[i];
}
//encode
if (ajaxsettings.encode.length > 0) {
for (let i = 0; i < ajaxsettings.encode.length; i++) {
if (ajaxsettings.encode[i]) {
ajaxsettings.data[ajaxsettings.encode[i]] = ajaxsettings.data[ajaxsettings.encode[i]].replace(/\+/g, "%2B").replace(/\&/g, "%26");
}
}
}
//create object
//convert object to string
if (typeof ajaxsettings.data === 'object') {
var str = '';
var value = '';
for (var key in ajaxsettings.data) {
value = ajaxsettings.data[key];
//replace & in url
if (typeof ajaxsettings.data[key] == "string") {
if (ajaxsettings.data[key].indexOf('&') !== -1) {
value = ajaxsettings.data[key].replace(/\&/g, "%26");
}
}
//replace & in key
if (key.indexOf('&') !== -1) {
key = key.replace(/&/g, escape('&'));
}
str += key + '=' + value + '&';
}
ajaxsettings.data = str.substring(0, str.length - 1);
}
//cache
let cache = '';
if (!ajaxsettings.cache) {
cache = '&' + new Date().getTime();
}
//for old browser
var ajaxobject = null;
if (window.XMLHttpRequest) {
//for Human Browser
ajaxobject = new XMLHttpRequest();
} else if (window.ActiveXObject) {
//for non-human Browser
ajaxobject = new ActiveXObject(ajaxsettings.IEborwser);
} else {
//for Borwser not support ajax
console.log('Not supported, im done');
}
//shake with server
ajaxobject.open('POST', ajaxsettings.url, ajaxsettings.async);
//send request
ajaxobject.setRequestHeader("Content-type", ajaxsettings.contentType);
ajaxobject.send(ajaxsettings.data);
//waiting for response
ajaxobject.onreadystatechange = function () {
if (ajaxobject.readyState === 4) {
if (ajaxobject.status === 200) {
ajaxsettings.success.call(ajaxobject, ajaxobject.responseText);
} else {
ajaxsettings.error.call(ajaxobject, ajaxobject.responseText);
}
}
};
}
}
const Cr$ = {
ran: limit => {
const r = Math.floor(Math.random() * 10000);
return r % limit;
}
}
var Cf$ = {
read: function (inin, endfunction) {
let defaultinin = {
mode: 'content',
file: ''
}
for (let i in inin) {
defaultinin[i] = inin[i];
}
if (defaultinin.file.length < 1) return;
let reader = new FileReader();
reader.onloadend = function () {
endfunction(reader.result);
};
switch (inin.mode) {
case 'URL':
case 'base64':
case 'b64':
case 'url':
reader.readAsDataURL(inin.file);
break;
case 'Text':
case 'test':
reader.readAsText(inin.file);
break;
case 'BinaryString':
reader.readAsBinaryString(inin.file);
break;
default:
console.log('mode is not supported');
}
},
download: function (file, filename) {
const a = document.createElement('a');
const url = window.URL.createObjectURL(file);
a.href = url;
a.download = filename;
a.click();
window.URL.revokeObjectURL(url);
}
};
var caperfun = {
random: {
//random a length length string
string: function (length) {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 ,.!@#$%^&*()|?<>";
length = Math.max(0, length);
for (var i = 0; i < length; i++) text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
},
//random a int
//need to imporve feature
int: function (length) {
return Math.random(length);
},
//random with little
instring: function (length, little) {
length = Math.max(0, length);
var thisposs = little + this.string(length);
return thisposs.charAt(Math.floor(Math.random() * thisposs.length));
}
}
} |
var express = require('express'),
app = express(),
cons = require('consolidate'),
server = require('http').createServer(app),
io = require('socket.io').listen(server)
server.listen(3000)
app.engine('hbs', cons.handlebars)
app.set('view engine', 'hbs')
app.set('views', __dirname + '/views')
app.get('/', function (req, res) {
res.render('index.hbs')
})
io.sockets.on('connection', function (socket) {
io.sockets.emit('text', { text: 'New user connected '})
})
|
var express = require('express');
var app = express();
var fs = require('fs');
var port = process.env.PORT || 30025;
var fileName = 'person.json';
app.get('/', function(req, res) {
var html = fs.readFileSync('public/index.html');
res.writeHeader(200, {"Content-Type": "text/html"});
res.end(html);
});
app.get('/read', function(request, response){
console.log('Read called.');
var obj;
function readData(err, data) {
if (err) throw err;
obj = JSON.parse(data);
response.send(obj);
}
// Asynch call
fs.readFile(fileName, 'utf8', readData);
});
app.get('/write', function(request, response) {
console.log('Write called: ' + request.query);
var person = request.query;
var personString = JSON.stringify(person, null, 4);
console.log('PersonString: ' + personString);
fs.writeFile(fileName, personString, 'utf8', function(err, data){
if (err) throw err;
console.log('It\'s saved!');
});
response.send('{"result":"success"}');
});
app.use("/", express.static(__dirname + '/public'));
console.log('Listening on port :' + port);
app.listen(port);
|
/**
* @file tworowslayout.js
* @brief Two rows layout
* @author Frédéric SCHERMA (INRA UMR1095)
* @date 2016-12-10
* @copyright Copyright (c) 2016 INRA/CIRAD
* @license MIT (see LICENSE file)
* @details
*/
let Marionette = require('backbone.marionette');
let TwoRowsLayout = Marionette.View.extend({
template: require("../templates/tworowslayout.html"),
attributes: {
style: "height: 100%;"
},
regions: {
'up': "div.row-up",
'down': "div.row-down"
},
childViewEvents: {
'select:tab': function (region, child) {
this.triggerMethod('select:tab', region, child);
},
},
onResize: function() {
let view = this.getChildView('up');
if (view && view.onResize) {
view.onResize();
}
view = this.getChildView('down');
if (view && view.onResize) {
view.onResize();
}
}
});
module.exports = TwoRowsLayout;
|
console.log("Loaded joinGame.js");
app.controller("joinGameController", function($scope){
console.log("In joinGame controller");
$scope.gameList = [{gameName: "Test Game!"}];
$scope.rowClickedHandler = function(game){
console.log("In rowClickedHandler");
console.log(game);
if(game.hasPassword){
var password = prompt("Please enter password");
if(password != null){
game.password = password;
joinGame(game);
}
}
else{
joinGame(game);
}
}
function joinGame(game){
console.log($scope.playerUuid);
socket.emit("joinGame",
{
gameName : game.gameName,
gameUuid : game.uuid,
password : game.password,
playerUuid : $scope.playerUuid,
playerUsername : $scope.username,
}
);
};
$scope.$on("userLoggedIn", function(){
socket.emit("getOpenGameList", {});
});
socket.on("joinGameError", function(data){
console.log("Join Game Error!");
console.log(data);
$scope.$apply(function(){
$scope.joinGameErrorMsg = data.msg;
$scope.showError = 1;
});
});
socket.on("joinGameSuccessful", function(data){
console.log("Join Game Successful!");
console.log(data);
$scope.$apply(function(){
$scope.$emit("joinGameSuccessful", data);
});
});
socket.on("openGameList", function(data){
console.log("Received open game list");
console.log(data);
$scope.$apply(function(){
if(data.gameList)
$scope.gameList = data.gameList;
});
});
socket.on("gameAdded", function(data){
console.log("Received gameAdded");
$scope.$apply(function(){
$scope.gameList.push(data);
});
});
$scope.$on("gameJoined", function(event, data){
for(var i = 0; i < $scope.gameList.length; ++i){
if($scope.gameList[i].uuid === data.uuid){
$scope.gameList.splice(i, 1);
}
}
});
});
|
"use strict";
var platform_browser_dynamic_1 = require('@angular/platform-browser-dynamic');
var app_components_1 = require('./components/app/app.components');
var app_routes_1 = require('./components/routes/app.routes');
var core_1 = require('@angular/core');
if (_root.globals.enviroment != "development") {
core_1.enableProdMode();
}
platform_browser_dynamic_1.bootstrap(app_components_1.AppComponent, [
app_routes_1.APP_ROUTER_PROVIDERS
]);
//# sourceMappingURL=main.js.map |
var ClearModelObjectBufferCommand = function() {
this.Extends = ClearObjectBufferCommand;
this.execute = function(note) {
//alert("ClearModelObjectBufferCommand");
try {
var mediator = this.facade.retrieveMediator(ModelObjectsListMediator.ID);
this.parent(note);
mediator.list.setRootCommand(null);
//Reset Counter for Navigation commands.
//TODO: !!!!! _cNc = 0; //TODO: global !!!
//this.sendNotification(SjamayeeFacade.OLIST_BUFFER_CLEARED,mediator);
mediator.setMessageText("Object Buffer cleared.");
this.sendNotification(SjamayeeFacade.OLIST_MODEL_SHOW);
} catch(error) {
Utils.alert("ClearModelRelationBufferCommand - error: "+error.message,Utils.LOG_LEVEL_ERROR);
}
};
};
ClearModelObjectBufferCommand = new Class(new ClearModelObjectBufferCommand());
|
QUnit.test('Math.log1p', assert => {
const { log1p } = Math;
assert.isFunction(log1p);
assert.name(log1p, 'log1p');
assert.arity(log1p, 1);
assert.looksNative(log1p);
assert.nonEnumerable(Math, 'log1p');
assert.same(log1p(''), log1p(0));
assert.same(log1p(NaN), NaN);
assert.same(log1p(-2), NaN);
assert.same(log1p(-1), -Infinity);
assert.same(log1p(0), 0);
assert.same(log1p(-0), -0);
assert.same(log1p(Infinity), Infinity);
assert.epsilon(log1p(5), 1.791759469228055);
assert.epsilon(log1p(50), 3.9318256327243257);
});
|
import React, { Component } from 'react'
import { connect } from 'react-redux'
import * as actions from './actions'
import Arcade from './Arcade'
class ArcadeContainer extends Component {
constructor(props) {
super(props)
this.state = {time:0, timer: null, startTime: 0}
}
componentDidMount = () =>
this.createTrial()
createTrial = () => {
this.props.createTrial(this.props.level)
this.startTimer()
}
startTimer = () => {
let timer = setInterval(this.updateTimer, 50)
this.setState({timer, time:0, startTime: Date.now()})
}
updateTimer = () =>
this.setState({time: Date.now() - this.state.startTime})
stopTimer = () =>
clearInterval(this.state.timer)
componentWillUnmount = () =>
this.stopTimer()
submit = trial => {
this.stopTimer()
this.props.submitTrial(trial)
this.props.showFeedback(trial)
setTimeout(this.props.hideFeedback, 3000)
if (this.props.trials.length + 1 < this.props.totalTrials)
this.createTrial()
else
setTimeout(this.props.finishLevel, 3000)
}
render = () =>
<Arcade
submit={this.submit}
time={this.state.time}
countdown={this.state.countdown}
{...this.props}
/>
}
export default connect(
state => state.arcade,
actions
)(ArcadeContainer)
|
describe('Form directive tests', () => {
let $scope, compiledElement;
beforeEach(angular.mock.module(require('app/application').name));
beforeEach(() => {
angular.mock.inject(($rootScope, $compile) => {
$scope = $rootScope.$new();
$scope.submitSpy = function submitSpy(data, cb=angular.noop) {
cb();
};
spyOn($scope, 'submitSpy').and.callThrough();
compiledElement = $compile('<div my-form on-submit="submitSpy(data, cb)"></div>')($scope);
});
$scope.$digest();
});
it('should contain a form tag', () => {
expect(compiledElement[0].tagName).toBe('FORM');
});
it('should bind to a directive controller', () => {
let controller = compiledElement.controller('myForm');
expect(typeof controller.isSubmitting).toBe('boolean');
});
it('should pass a submit function to the controller instance', () => {
let controller = compiledElement.controller('myForm');
controller.onSubmit();
expect($scope.submitSpy).toHaveBeenCalled();
});
it('should prevent form submission when form is invalid', () => {
let controller = compiledElement.controller('myForm');
controller.todoForm.$invalid = true;
controller.submit();
expect($scope.submitSpy).not.toHaveBeenCalled();
});
it('should allow one submission action at a time', () => {
let controller = compiledElement.controller('myForm');
controller.todoForm.$invalid = false;
controller.isSubmitting = true;
controller.submit();
expect($scope.submitSpy).not.toHaveBeenCalled();
});
it('should submit form data and reset them', () => {
let controller = compiledElement.controller('myForm');
controller.todo = {
title: 'test'
};
controller.todoForm.$invalid = false;
controller.isSubmitting = false;
controller.submit();
expect($scope.submitSpy).toHaveBeenCalledWith({title: 'test'}, jasmine.any(Function));
expect(controller.todo.title).toBe('');
});
});
|
/*
Copyright 2013, KISSY UI Library v1.40dev
MIT Licensed
build time: Jul 3 13:58
*/
/*
Combined processedModules by KISSY Module Compiler:
swf/ua
swf
*/
/**
* @ignore
* Flash UA 探测
* @author oicuicu@gmail.com
*/
KISSY.add('swf/ua', function (S, undefined) {
var fpvCached,
firstRun = true,
win = S.Env.host;
/*
获取 Flash 版本号
返回数据 [M, S, R] 若未安装,则返回 undefined
*/
function getFlashVersion() {
var ver,
SF = 'ShockwaveFlash';
// for NPAPI see: http://en.wikipedia.org/wiki/NPAPI
if (navigator.plugins && navigator.mimeTypes.length) {
ver = (navigator.plugins['Shockwave Flash'] || 0).description;
}
// for ActiveX see: http://en.wikipedia.org/wiki/ActiveX
else if (win['ActiveXObject']) {
try {
ver = new ActiveXObject(SF + '.' + SF)['GetVariable']('$version');
} catch (ex) {
S.log('getFlashVersion failed via ActiveXObject');
// nothing to do, just return undefined
}
}
// 插件没安装或有问题时,ver 为 undefined
if (!ver) {
return undefined;
}
// 插件安装正常时,ver 为 "Shockwave Flash 10.1 r53" or "WIN 10,1,53,64"
return getArrayVersion(ver);
}
/*
getArrayVersion("10.1.r53") => ["10", "1", "53"]
*/
function getArrayVersion(ver) {
return ver.match(/\d+/g).splice(0, 3);
}
/*
格式:主版本号Major.次版本号Minor(小数点后3位,占3位)修正版本号Revision(小数点后第4至第8位,占5位)
ver 参数不符合预期时,返回 0
getNumberVersion("10.1 r53") => 10.00100053
getNumberVersion(["10", "1", "53"]) => 10.00100053
getNumberVersion(12.2) => 12.2
*/
function getNumberVersion(ver) {
var arr = typeof ver == 'string' ?
getArrayVersion(ver) :
ver,
ret = ver;
if (S.isArray(arr)) {
ret = parseFloat(arr[0] + '.' + pad(arr[1], 3) + pad(arr[2], 5));
}
return ret || 0;
}
/*
pad(12, 5) => "00012"
*/
function pad(num, n) {
num = num || 0;
num += '';
var padding = n + 1 - num.length;
return new Array(padding > 0 ? padding : 0).join('0') + num;
}
/**
* Get flash version
* @param {Boolean} [force] whether to avoid getting from cache
* @returns {String[]} eg: ["11","0","53"]
* @member KISSY.SWF
* @static
*/
function fpv(force) {
// 考虑 new ActiveX 和 try catch 的 性能损耗,延迟初始化到第一次调用时
if (force || firstRun) {
firstRun = false;
fpvCached = getFlashVersion();
}
return fpvCached;
}
/**
* Checks whether current version is greater than or equal the specific version.
* @param {String} ver eg. "10.1.53"
* @param {Boolean} force whether to avoid get current version from cache
* @returns {Boolean}
* @member KISSY.SWF
* @static
*/
function fpvGTE(ver, force) {
return getNumberVersion(fpv(force)) >= getNumberVersion(ver);
}
return {
fpv: fpv,
fpvGTE: fpvGTE
};
});
/**
* @ignore
*
* NOTES:
*
- ActiveXObject JS 小记
- newObj = new ActiveXObject(ProgID:String[, location:String])
- newObj 必需 用于部署 ActiveXObject 的变量
- ProgID 必选 形式为 "serverName.typeName" 的字符串
- serverName 必需 提供该对象的应用程序的名称
- typeName 必需 创建对象的类型或者类
- location 可选 创建该对象的网络服务器的名称
- Google Chrome 比较特别:
- 即使对方未安装 flashplay 插件 也含最新的 Flashplayer
- ref: http://googlechromereleases.blogspot.com/2010/03/dev-channel-update_30.html
*
*/
/**
* @ignore
* insert swf into document in an easy way
* @author yiminghe@gmail.com, oicuicu@gmail.com
*/
KISSY.add('swf', function (S, Dom, Json, Base, FlashUA, undefined) {
var UA = S.UA,
TYPE = 'application/x-shockwave-flash',
CID = 'clsid:d27cdb6e-ae6d-11cf-96b8-444553540000',
FLASHVARS = 'flashvars',
EMPTY = '',
SPACE = ' ',
EQUAL = '=',
DOUBLE_QUOTE = '"',
LT = '<',
GT = '>',
doc = S.Env.host.document,
fpv = FlashUA.fpv,
fpvGTE = FlashUA.fpvGTE,
OBJECT_TAG = 'object',
encode = encodeURIComponent,
// flash player 的参数范围
PARAMS = {
// swf 传入的第三方数据。支持复杂的 Object / XML 数据 / Json 字符串
// flashvars: EMPTY,
wmode: EMPTY,
allowscriptaccess: EMPTY,
allownetworking: EMPTY,
allowfullscreen: EMPTY,
// 显示 控制 删除
play: 'false',
loop: EMPTY,
menu: EMPTY,
quality: EMPTY,
scale: EMPTY,
salign: EMPTY,
bgcolor: EMPTY,
devicefont: EMPTY,
hasPriority: EMPTY,
// 其他控制参数
base: EMPTY,
swliveconnect: EMPTY,
seamlesstabbing: EMPTY
};
/**
* insert a new swf into container
* @class KISSY.SWF
* @extends KISSY.Base
*/
function SWF(config) {
var self = this;
SWF.superclass.constructor.apply(self, arguments);
var expressInstall = self.get('expressInstall'),
swf,
html,
id,
htmlMode = self.get('htmlMode'),
flashVars,
params = self.get('params'),
attrs = self.get('attrs'),
doc = self.get('document'),
placeHolder = Dom.create('<span>', undefined, doc),
elBefore = self.get('elBefore'),
installedSrc = self.get('src'),
version = self.get('version');
id = attrs.id = attrs.id || S.guid('ks-swf-');
// 2. flash 插件没有安装
if (!fpv()) {
self.set('status', SWF.Status.NOT_INSTALLED);
return;
}
// 3. 已安装,但当前客户端版本低于指定版本时
if (version && !fpvGTE(version)) {
self.set('status', SWF.Status.TOO_LOW);
// 有 expressInstall 时,将 src 替换为快速安装
if (expressInstall) {
installedSrc = expressInstall;
// from swfobject
if (!('width' in attrs) ||
(!/%$/.test(attrs.width) && parseInt(attrs.width, 10) < 310)) {
attrs.width = "310";
}
if (!('height' in attrs) ||
(!/%$/.test(attrs.height) && parseInt(attrs.height, 10) < 137)) {
attrs.height = "137";
}
flashVars = params.flashVars = params.flashVars || {};
// location.toString() crash ie6
S.mix(flashVars, {
MMredirectURL: location.href,
MMplayerType: UA.ie ? "ActiveX" : "PlugIn",
MMdoctitle: doc.title.slice(0, 47) + " - Flash Player Installation"
});
}
}
if (htmlMode == 'full') {
html = _stringSWFFull(installedSrc, attrs, params)
} else {
html = _stringSWFDefault(installedSrc, attrs, params)
}
// ie 再取 target.innerHTML 属性大写,很多多与属性,等
self.set('html', html);
if (elBefore) {
Dom.insertBefore(placeHolder, elBefore);
} else {
Dom.append(placeHolder, self.get('render'));
}
if ('outerHTML' in placeHolder) {
placeHolder.outerHTML = html;
} else {
placeHolder.parentNode.replaceChild(Dom.create(html),placeHolder);
}
swf = Dom.get('#' + id, doc);
self.set('swfObject', swf);
if (htmlMode == 'full') {
if (UA.ie) {
self.set('swfObject', swf);
} else {
self.set('swfObject', swf.parentNode);
}
}
// bug fix: 重新获取对象,否则还是老对象.
// 如 入口为 div 如果不重新获取则仍然是 div longzang | 2010/8/9
self.set('el', swf);
if (!self.get('status')) {
self.set('status', SWF.Status.SUCCESS);
}
}
S.extend(SWF, Base, {
/**
* Calls a specific function exposed by the SWF 's ExternalInterface.
* @param func {String} the name of the function to call
* @param args {Array} the set of arguments to pass to the function.
*/
'callSWF': function (func, args) {
var swf = this.get('el'),
ret,
params;
args = args || [];
try {
if (swf[func]) {
ret = swf[func].apply(swf, args);
}
} catch (e) {
// some version flash function is odd in ie: property or method not supported by object
params = "";
if (args.length !== 0) {
params = "'" + args.join("', '") + "'";
}
//avoid eval for compression
ret = (new Function('swf', 'return swf.' + func + '(' + params + ');'))(swf);
}
return ret;
},
/**
* remove its container and swf element from dom
*/
destroy: function () {
var self = this;
self.detach();
var swfObject = self.get('swfObject');
/* Cross-browser SWF removal
- Especially needed to safely and completely remove a SWF in Internet Explorer
*/
if (UA.ie) {
swfObject.style.display = 'none';
// from swfobject
(function () {
if (swfObject.readyState == 4) {
removeObjectInIE(swfObject);
}
else {
setTimeout(arguments.callee, 10);
}
})();
} else {
swfObject.parentNode.removeChild(swfObject);
}
}
}, {
ATTRS: {
/**
* express install swf url.
* Defaults to: swfobject 's express install
* @cfg {String} expressInstall
*/
/**
* @ignore
*/
expressInstall: {
value: S.config('base') + 'swf/assets/expressInstall.swf'
},
/**
* new swf 's url
* @cfg {String} src
*/
/**
* @ignore
*/
src: {
},
/**
* minimum flash version required. eg: "10.1.250"
* Defaults to "9".
* @cfg {String} version
*/
/**
* @ignore
*/
version: {
value: "9"
},
/**
* params for swf element
* - params.flashVars
* @cfg {Object} params
*/
/**
* @ignore
*/
params: {
value: {}
},
/**
* attrs for swf element
* @cfg {Object} attrs
*/
/**
* @ignore
*/
attrs: {
value: {}
},
/**
* container where flash will be appended.
* Defaults to: body
* @cfg {HTMLElement} render
*/
/**
* @ignore
*/
render: {
setter: function (v) {
if (typeof v == 'string') {
v = Dom.get(v, this.get('document'));
}
return v;
},
valueFn: function () {
return document.body;
}
},
/**
* element where flash will be inserted before.
* @cfg {HTMLElement} elBefore
*/
/**
* @ignore
*/
elBefore: {
setter: function (v) {
if (typeof v == 'string') {
v = Dom.get(v, this.get('document'));
}
return v;
}
},
/**
* html document current swf belongs.
* Defaults to: current document
* @cfg {HTMLElement} document
*/
/**
* @ignore
*/
document: {
value: doc
},
/**
* status of current swf
* @property status
* @type {KISSY.SWF.Status}
* @readonly
*/
/**
* @ignore
*/
status: {
},
/**
* swf element
* @readonly
* @type {HTMLElement}
* @property el
*/
/**
* @ignore
*/
el: {
},
/**
* @ignore
* @private
*/
swfObject: {
},
/**
* swf element 's outerHTML
* @property html
* @type {String}
* @readonly
*/
/**
* @ignore
*/
html: {
},
/**
* full or default(depends on browser object)
* @cfg {KISSY.SWF.HTMLMode} htmlMode
*/
/**
* @ignore
*/
htmlMode: {
value: 'default'
}
},
fpv: fpv,
fpvGTE: fpvGTE
});
// compatible
SWF.fpvGEQ = fpvGTE;
function removeObjectInIE(obj) {
for (var i in obj) {
if (typeof obj[i] == "function") {
obj[i] = null;
}
}
obj.parentNode.removeChild(obj);
}
function getSrcElements(swf) {
var url = "",
params, i, param,
elements = [],
nodeName = Dom.nodeName(swf);
if (nodeName == "object") {
url = Dom.attr(swf, "data");
if (url) {
elements.push(swf);
}
params = swf.childNodes;
for (i = 0; i < params.length; i++) {
param = params[i];
if (param.nodeType == 1) {
if ((Dom.attr(param, "name") || "").toLowerCase() == "movie") {
elements.push(param);
} else if (Dom.nodeName(param) == "embed") {
elements.push(param);
} else if (Dom.nodeName(params[i]) == "object") {
elements.push(param);
}
}
}
} else if (nodeName == "embed") {
elements.push(swf);
}
return elements;
}
// setSrc ie 不重新渲染
/**
* get src from existing oo/oe/o/e swf element
* @param {HTMLElement} swf
* @returns {String}
* @static
*/
SWF.getSrc = function (swf) {
swf = Dom.get(swf);
var srcElement = getSrcElements(swf)[0],
src,
nodeName = srcElement && Dom.nodeName(srcElement);
if (nodeName == 'embed') {
return Dom.attr(srcElement, 'src');
} else if (nodeName == 'object') {
return Dom.attr(srcElement, 'data');
} else if (nodeName == 'param') {
return Dom.attr(srcElement, 'value');
}
return null;
};
function collectionParams(params) {
var par = EMPTY;
S.each(params, function (v, k) {
k = k.toLowerCase();
if (k in PARAMS) {
par += stringParam(k, v);
}
// 特殊参数
else if (k == FLASHVARS) {
par += stringParam(k, toFlashVars(v));
}
});
return par;
}
function _stringSWFDefault(src, attrs, params) {
return _stringSWF(src, attrs, params, UA.ie) + LT + '/' + OBJECT_TAG + GT;
}
function _stringSWF(src, attrs, params, ie) {
var res,
attr = EMPTY,
par = EMPTY;
if (ie == undefined) {
ie = UA.ie;
}
// 普通属性
S.each(attrs, function (v, k) {
attr += stringAttr(k, v);
});
if (ie) {
attr += stringAttr('classid', CID);
par += stringParam('movie', src);
} else {
// 源
attr += stringAttr('data', src);
// 特殊属性
attr += stringAttr('type', TYPE);
}
par += collectionParams(params);
res = LT + OBJECT_TAG + attr + GT + par;
return res
}
// full oo 结构
function _stringSWFFull(src, attrs, params) {
var outside, inside;
if (UA.ie) {
outside = _stringSWF(src, attrs, params, 1);
delete attrs.id;
delete attrs.style;
inside = _stringSWF(src, attrs, params, 0);
} else {
inside = _stringSWF(src, attrs, params, 0);
delete attrs.id;
delete attrs.style;
outside = _stringSWF(src, attrs, params, 1);
}
return outside + inside + LT + '/' + OBJECT_TAG + GT + LT + '/' + OBJECT_TAG + GT;
}
/*
将普通对象转换为 flashvars
eg: {a: 1, b: { x: 2, z: 's=1&c=2' }} => a=1&b=encode({"x":2,"z":"s%3D1%26c%3D2"})
*/
function toFlashVars(obj) {
var arr = [],
ret;
S.each(obj, function (data, prop) {
if (typeof data != 'string') {
data = Json.stringify(data);
}
if (data) {
arr.push(prop + '=' + encode(data));
}
});
ret = arr.join('&');
return ret;
}
function stringParam(key, value) {
return '<param name="' + key + '" value="' + value + '"></param>';
}
function stringAttr(key, value) {
return SPACE + key + EQUAL + DOUBLE_QUOTE + value + DOUBLE_QUOTE;
}
/**
* swf status
* @enum {String} KISSY.SWF.Status
*/
SWF.Status = {
/**
* flash version is too low
*/
TOO_LOW: 'flash version is too low',
/**
* flash is not installed
*/
NOT_INSTALLED: 'flash is not installed',
/**
* success
*/
SUCCESS: 'success'
};
/**
* swf htmlMode
* @enum {String} KISSY.SWF.HTMLMode
*/
SWF.HTMLMode = {
/**
* generate object structure depending on browser
*/
DEFAULT: 'default',
/**
* generate object/object structure
*/
FULL: 'full'
};
return SWF;
}, {
requires: ['dom', 'json', 'base', 'swf/ua']
});
|
// Basic Loop with pre update expression
/*
var a = 0, b = 5;
for (var i = 0; i < 5; ++i) {
a = a + 1;
}
var c = a + 5;
*/
var a = 0, b = 5;
for(var i = 0; i < 5; ++i) {
a = a + 1;
}
var c = a + b;
|
module.exports = create;
create.usage = "\trappidjs create lib <libName> [<dir>] - Creates a rappidjs lib directory structure"
+ "\n\trappidjs create app <AppName> [<dir>] - Creates empty rappidjs application";
var fs = require("fs"),
path = require("path"),
flow = require("flow.js").flow,
ejs = require('ejs'),
args = process.argv.splice(2),
install = require(path.join(__dirname, "install.js"));
fs.existsSync || (fs.existsSync = path.existsSync);
var Helper = {
template: function (source, destination, options) {
var data = fs.readFileSync(source, "utf8");
fs.writeFileSync(destination, this.render(data, options));
},
render: function (string, options) {
if (options == null) options = {};
return ejs.render(string, options);
},
copy: function (source, destination) {
var data = fs.readFileSync(source, "utf8");
fs.writeFileSync(destination, data);
},
copyDirectory: function (srcDir, targetDir, callback) {
var subDirs = [], files = [];
if (!fs.existsSync(targetDir)) {
fs.mkdirSync(targetDir);
}
var source, dest;
fs.readdirSync(srcDir).forEach(function (name) {
source = path.join(srcDir, name);
dest = path.join(targetDir, name);
var stat = fs.statSync(source);
if (name.indexOf(".") !== 0) {
if (stat.isDirectory()) {
subDirs.push(name);
} else if (stat.isFile() || stat.isSymbolicLink()) {
files.push({
src: source,
dst: dest
});
}
}
});
flow()
.seqEach(files, function (file, cb) {
var inStr = fs.createReadStream(file.src);
var outStr = fs.createWriteStream(file.dst);
inStr.on('end', function () {
outStr.end();
cb();
});
inStr.pipe(outStr);
})
.seq(function (cb) {
if (subDirs.length) {
subDirs.forEach(function (dirName) {
source = path.join(srcDir, dirName);
dest = path.join(targetDir, dirName);
Helper.copyDirectory(source, dest, cb);
});
} else {
cb();
}
})
.exec(callback);
}
};
fs.mkdirIfNotExist = function (dirPath) {
if (!fs.existsSync(dirPath)) {
fs.mkdirSync(dirPath);
}
};
fs.mkdirParent = function (dirPath) {
if (!fs.existsSync(dirPath)) {
var parentDir = path.normalize(path.join(dirPath, ".."));
if (!fs.existsSync(parentDir)) {
fs.mkdirParent(parentDir);
}
fs.mkdirSync(dirPath);
}
};
function createDirectories(directories, where) {
for (var i = 0; i < directories.length; i++) {
fs.mkdirIfNotExist(path.join(where, directories[i]));
}
}
function create(args, callback) {
if (args.length === 0) {
callback("No args defined");
}
var cmd = args.shift();
var dir = process.cwd();
var name = args[0];
if (args.length > 1) {
dir = args[1];
}
dir = path.resolve(dir.replace(/^~\//, process.env.HOME + '/'));
if (cmd == "lib" || cmd == "library") {
createLibrary(name, dir, callback);
} else if (cmd == "app" || cmd == "application") {
createApplication(name, dir, callback);
} else if (cmd === "cls" || cmd == "class") {
var parentClassName = args.length > 1 ? args[1]: null;
createClass(name, parentClassName, callback);
} else {
callback(true);
}
}
function createLibrary(libName, dir, callback) {
dir = dir || process.cwd();
fs.mkdirParent(dir);
// create directories
var dirs = ["bin", "doc", "test", libName, "xsd"];
createDirectories(dirs, dir);
Helper.template(path.join(__dirname, "templates", "package.json"), path.join(dir, libName, "package.json"), {name: libName, type: "lib"});
}
function createApplication(appName, dir, callback) {
dir = dir || process.cwd();
fs.mkdirParent(dir);
if (!fs.existsSync(dir)) {
callback("Directory " + dir + " could not be created");
}
if (appName) {
// create sub directories
var subDirs = ["bin", "doc", "test", "public", "xsd", "server", "node_modules"];
// create sub directories
createDirectories(subDirs, dir);
// make first character of appName UPPERCASE
appName = appName.charAt(0).toUpperCase() + appName.substr(1);
var publicDir = path.join(dir, "public");
var serverDir = path.join(dir, "server");
// create app directory in public
var appDir = path.join(publicDir, "app");
var webDir = path.join(serverDir, "web");
fs.mkdirIfNotExist(appDir);
fs.mkdirIfNotExist(webDir);
var serverAppDir = path.join(serverDir, "app");
if (!fs.existsSync(serverAppDir)) {
var relativePath = path.join(path.relative(serverDir, publicDir), "app");
fs.symlinkSync(relativePath, serverAppDir, 'dir');
}
createDirectories(["collection", "model", "view", "locale", "module"], appDir);
// do the templating stuff
// scaffold index.html
Helper.template(path.join(__dirname, "templates", "index.html"), path.join(publicDir, "index.html"), {appName: appName});
// scaffold app/<AppName>.xml
Helper.template(path.join(__dirname, "templates", "app", "App.xml"), path.join(publicDir, "app", appName + ".xml"), {appName: appName});
// scaffold app/<AppName>Class.xml
Helper.template(path.join(__dirname, "templates", "app", "AppClass.js"), path.join(publicDir, "app", appName + "Class.js"), {appName: appName});
Helper.template(path.join(__dirname, "templates", "package.json"), path.join(dir, "package.json"), {name: appName, type: "app"});
// add server xml
Helper.template(path.join(__dirname, "templates", "Server.xml"), path.join(webDir, "Server.xml"), {});
var rappidPath = path.join(fs.realpathSync(process.argv[1]), "../..");
install(["rAppid.js", "latest", dir], function (err) {
if (!err) {
// link config json
var configPath = path.join(serverDir, "config.json");
if (!fs.existsSync(configPath)) {
var relativePath = path.join(path.relative(serverDir, publicDir), "config.json");
fs.symlinkSync(relativePath, configPath);
}
// scaffold default app directory structure
console.log("");
console.log("Application '" + appName + "' in directory '" + publicDir + "' successfully created.");
console.log("");
}
callback(err)
});
}
}
function createClass(fqClassName, fqParentCassName, callback){
var dir = process.cwd();
fs.mkdirParent(dir);
if (!fs.existsSync(dir)) {
callback("Directory " + dir + " could not be created");
}
var packages = fqClassName.split("."),
className = packages.pop(),
classDir = path.join(dir, packages.join("/"));
fs.mkdirParent(classDir);
if (!fs.existsSync(classDir)) {
callback("Directory " + classDir + " could not be created");
}
fqParentCassName = fqParentCassName || "js.core.Bindable";
fqParentCassName = fqParentCassName.replace(/\./g,"/");
var parentClassName = fqParentCassName.split("/").pop();
// scaffold index.html
Helper.template(path.join(__dirname, "templates", "Class.js"), path.join(classDir, className+".js"), {parentClassName: parentClassName, fqParentClassName: fqParentCassName, fqClassName: fqClassName});
} |
exports.SAMPLER = 'Sampler';
exports.OSC = 'Osc';
exports.GAIN = 'Gain';
exports.FILTER = 'Filter';
exports.ENVELOPE = 'Envelope';
exports.EFFECT = 'Effect';
exports.DATA = 'Data';
exports.CONTROL = 'Control';
exports.IN_OUT = 'In/Out';
// exports.OTHER = 'misc'; |
console.info("overview");
var x = 5;
var y;
var z = x + 5;
var o1;
var o2;
var o3;
var a1;
var a2;
var a3;
var f1;
var f2;
f2 = function (n) { return 5; };
console.log(f2());
var A = (function () {
function A() {
this.init = function (n) { };
}
A.prototype.foo = function () {
this.init2 = function (n) { return ""; };
};
return A;
})();
// lamda equivalent (arrow function)
var f = function (w, h) { return w * h; };
f = function (w, h) { return w * h; };
var f3 = function (w, h) { return w * h; };
// this form is not liked!
//f = function (w:number, h:number) => w*h;
var hello;
hello = function (name) { console.log("hello " + (name || "nobody")); };
// this is not liked
//hello = (name?:string) { console.log("hello " + (name || "nobody")); }
hello("me");
hello();
var computeArea;
computeArea = function (rect) {
if (rect.h === undefined) {
return rect.w * rect.w;
}
return rect.w * rect.h;
};
// this is interesting! interface for function def?
var af = computeArea;
console.info(af({ w: 5 }));
console.info(af({ w: 5, h: 10 }));
var p1 = {
name: 'me',
//age: 5,
greet: function (s) { console.log(s + " " + this.name); }
};
p1.greet('hello');
//# sourceMappingURL=overview.js.map |
module.exports = {
eslint: require('./eslint'),
npm: require('./npm'),
objectToSpawnArgs: function(object) {
function option(prop, value) {
var params = [];
if (prop.length === 1) {
params.push('-' + prop);
if (value !== true) {
params.push(value);
}
} else {
prop.trim().length && params.push('--' + prop);
if (value !== true) {
params.push(value);
}
}
return params;
}
var output = [];
Object.keys(object).sort().forEach(function(prop) {
var value = object[prop];
if (value === undefined) { return; }
value instanceof Array || (value = [value]);
value.forEach(function(val) {
output = output.concat(option(prop, val));
});
});
return output;
}
} |
var inherits = require('util').inherits;
var EventEmitter = require('events').EventEmitter;
var extend = require('extend');
var taxaprisma = require('taxaprisma');
inherits(SearchResult, EventEmitter);
function SearchResult(settings) {
if (!(this instanceof SearchResult)) { return new SearchResult(settings); }
this.settings = extend({
searchContext: { on: function() {} }
}, settings);
this.statistics = {
interactions: [],
sources: [],
targets: []
};
this.searchContext = this.settings['searchContext'];
delete this.settings['searchContext'];
this.init();
}
extend(SearchResult.prototype, {
init: function() {
var me = this;
me.events();
me.el = createElement('div', false, ['table-wrapper']);
},
events: function() {
var me = this;
me.on('searchresult:itemclick', me.itemClicked);
me.searchContext.on('searchfilter:showresults', proxy(me.showList, me));
me.searchContext.on('searchfilter:showitem', proxy(me.showItem, me));
},
appendTo: function(target) {
var me = this;
if (typeof target === 'string') target = document.querySelector(target);
var div = createElement('div', 'result-list');
div.appendChild(me.el);
target.appendChild(div);
me.emit('append', target);
},
clear: function() {
var me = this;
me.el.innerHTML = '';
},
showList: function(data, downloadlinks) {
var me = this;
me.clear();
downloadlinks = downloadlinks || [];
if (data.length > 0) {
var itemId, stats = { sources: [], targets: [], linkCount: 0}, row, th, sourceCell, targetCell, linkCell, odd = false;
var table = createElement('table', 'result-table');
var tableHead = createElement('thead');
var tableBody = createElement('tbody');
var itemIdCache = [];
data.forEach(function(item) {
itemId = me.stat(item);
if (!itemId) return;
row = createElement('tr', itemId, ['result-item', (odd ? 'odd' : 'even')]);
row.addEventListener('click', function() { me.emit('searchresult:itemclick', item); });
row.innerHTML = [
'<td class="source-cell" ' + getStyleAttribute(item['source'].path) + '>', item['source'].name, '</td>',
'<td class="link-cell">', item['link'].name, '</td>',
'<td class="target-cell" ' + getStyleAttribute(item['target'].path) + '">', item['target'].name, '</td>'
].join('');
tableBody.appendChild(row);
odd = !odd;
});
var linkRefs = downloadlinks.map(function(link) {
var downloadText = 'download csv data sample';
return '<a href="' + link.url + '" class="link" title="download up to 4096 related interaction records">' + downloadText + '</a>';
}).join(' ');
tableHead.innerHTML = [
'<tr><th class="source-cell">' + linkRefs + '</th>',
('<th></th>'),
'<th class="target-cell"><a href="/data#interaction-data-indexes">access full dataset</a></th></tr>',
'<tr>',
'<th class="source-cell">taxon</th>',
'<th class="download">',
camelCaseToRealWords(me.searchContext.getParameter('interactionType')),
'</th>',
'<th class="target-cell">taxon</th>',
'</tr>',
'<tr>',
'<th>(', me.statistics['sources'].length, ' distinct)</th>',
'<th>','(', me.statistics['interactions'].length, ' distinct interactions)</th>',
'<th>(', me.statistics['targets'].length, ' distinct)</th></tr>'
].join('');
table.appendChild(tableHead);
table.appendChild(tableBody);
me.el.appendChild(table);
} else {
me.el.innerHTML = '<p>No interaction data was found with your criteria. Bummer!</p>' +
'<br/><p>Suggest to make your search more general (e.g. Aves eats Insecta), increase your search area or <a href="https://github.com/globalbioticinteractions/globalbioticinteractions/wiki/How-to-Contribute-Data-to-Global-Biotic-Interactions%3F">contribute more data</a>.</p>' +
'<br/><p>Please <a href="https://github.com/globalbioticinteractions/globalbioticinteractions.github.io/issues/new">open an issue</a> if you have suggestions or questions.</p>';
}
me.searchContext.unlockFetching('SearchResult::showList');
},
showItem: function(item) {
var me = this, itemId, infoBox, activeRow;
activeRow = document.getElementsByClassName('active-row');
if (activeRow.length > 0) {
activeRow[0].classList.remove('active-row');
}
itemId = [item['source'].id, item['link'].id, item['target'].id].join('---');
infoBox = document.getElementById('info-box');
if (infoBox) {
infoBox.parentNode.removeChild(infoBox);
}
infoBox = createElement('tr', 'info-box', ['result-row']);
infoBox.innerHTML = [
'<td class="result-source">',
'<div class="source-label">' + item['source'].label + '</div>',
item['source'].data,
'</td>',
'<td class="result-link"><div class="link-label">' + item['link'].label + '</div><div class="link-data">' + item['link'].data + '</div></td>',
'<td class="result-target">',
'<div class="target-label">' + item['target'].label + '</div>',
item['target'].data,
'</td>',
].join('');
activeRow = document.getElementById(itemId);
activeRow.parentNode.insertBefore(infoBox, activeRow);
activeRow.classList.add('active-row');
me.searchContext.unlockFetching('SearchResult::showItem');
},
itemClicked: function(data) {
var me = this;
me.searchContext.emit('searchresult:itemselected', data);
},
stat: function(item) {
var s = this.statistics;
var interactionId = [
item['source'].id,
item['link'].id,
item['target'].id
].join('---');
if (s.interactions.indexOf(interactionId) !== -1) {
return false;
}
s.interactions.push(interactionId);
if (s.sources.indexOf(item['source'].id) === -1) {
s.sources.push(item['source'].id);
}
if (s.targets.indexOf(item['target'].id) === -1) {
s.targets.push(item['target'].id);
}
return interactionId;
}
});
function proxy(fn, context) {
return function() {
return fn.apply(context, arguments);
};
}
/**
* @param elementName
* @param id
* @param classes
* @returns {Element}
*/
function createElement(elementName, id, classes) {
elementName = elementName || 'div';
id = id || false;
classes = classes || [];
var div = document.createElement(elementName);
if (id) div.id = id;
if (classes.length > 0 ) div.className = classes.join(' ');
return div;
}
function camelCaseToRealWords(str) {
str = str.replace(/([A-Z])/g, function($1){return " "+$1.toLowerCase();});
var strParts = str.split(' '), lastPart = strParts[strParts.length - 1];
if (['of', 'by'].indexOf(lastPart) >= 0) {
strParts.unshift('is');
}
return strParts.join(' ');
}
function getStyleAttribute(path) {
return 'style="color: ' + taxaprisma.colorFor(path) + ';"'
}
module.exports = SearchResult;
|
// Regular expression that matches all symbols in the `Zs` category as per Unicode v2.0.14:
/[\x20\xA0\u2000-\u200B\u3000]/; |
// ---------------------------------------------------------------------------------------------------------------------
// Input Manager
//
// @module inputman.js
// ---------------------------------------------------------------------------------------------------------------------
function InputManagerFactory($rootScope, _, socket, configMan, keySvc, sceneMan)
{
function InputManager()
{
this.commands = [];
$rootScope.$on('config load', this.reloadConfig.bind(this));
} // end InputManager
// -----------------------------------------------------------------------------------------------------------------
InputManager.prototype._buildSingleShot = function(commandEvent, value)
{
var self = this;
return function singleShotFunc()
{
//console.log('single-shot "%s" with value:', commandEvent, value);
self.broadcast(commandEvent, value);
}; // end singleShotFunc
}; // end _buildSingleShot
InputManager.prototype._buildMomentary = function(commandEvent, onValue, offValue)
{
var self = this;
onValue = onValue === undefined ? true : onValue;
offValue = offValue === undefined ? false : offValue;
return [
function momentaryOnFunc()
{
//console.log('momentary "%s" set to value:', commandEvent, onValue);
self.broadcast(commandEvent, onValue);
}, // end momentaryOnFunc
function momentaryOffFunc()
{
//console.log('momentary "%s" reset to value:', commandEvent, offValue);
self.broadcast(commandEvent, offValue);
} // end momentaryOffFunc
];
}; // end _buildMomentary
InputManager.prototype._buildToggle = function(commandEvent, onValue, offValue)
{
var self = this;
var value;
var toggle = false;
return function toggleFunc()
{
toggle = !toggle;
value = toggle ? (onValue || true) : (offValue || false);
//console.log('toggle "%s" with value:', commandEvent, value);
self.broadcast(commandEvent, value);
}; // end toggleFunc
}; // end _buildToggle
// -----------------------------------------------------------------------------------------------------------------
InputManager.prototype.reloadConfig = function()
{
var self = this;
var config = configMan.activeConfig;
//--------------------------------------------------------------------------------------------------------------
// Keyboard support
//--------------------------------------------------------------------------------------------------------------
// Clear existing bindings
keySvc.clear();
// Now, we bind based on our config
_.forIn(config.keyboard, function(cmdConf, keys)
{
if(cmdConf.toggle)
{
keySvc.register(keys, self._buildToggle(cmdConf.command, cmdConf.onValue, cmdConf.offValue));
}
else if(cmdConf.singleShot)
{
keySvc.register(keys, self._buildSingleShot(cmdConf.command, cmdConf.value));
}
else
{
var handlers = self._buildMomentary(cmdConf.command, cmdConf.onValue, cmdConf.offValue);
keySvc.register(keys, handlers[0], handlers[1]);
} // end if
});
//--------------------------------------------------------------------------------------------------------------
}; // end reloadConfig
InputManager.prototype.broadcast = function(event, value)
{
$rootScope.$broadcast(event, value);
socket.sendEvent(event, { value: value });
}; // end broadcast
// -----------------------------------------------------------------------------------------------------------------
// Public API
// -----------------------------------------------------------------------------------------------------------------
InputManager.prototype.enableMouseLook = function()
{
//TODO: This needs to use PointerLock as well: https://developer.mozilla.org/en-US/docs/Web/API/Pointer_Lock_API
sceneMan.playerCamera.attachControl(sceneMan.canvas);
}; // end enableMouseLook
InputManager.prototype.disableMouseLook = function()
{
//TODO: This needs to use PointerLock as well: https://developer.mozilla.org/en-US/docs/Web/API/Pointer_Lock_API
sceneMan.playerCamera.detachControl(sceneMan.canvas);
}; // end disableMouseLook
InputManager.prototype.onCommand = function(command, callback)
{
// Register the command if it doesn't already exist in our list of commands.
if(this.commands.indexOf(command) === -1)
{
this.commands.push(command);
} // end if
return $rootScope.$on(command, function()
{
callback.apply(callback, arguments);
});
}; // end onCommand
// -----------------------------------------------------------------------------------------------------------------
return new InputManager();
} // end InputManagerFactory
// ---------------------------------------------------------------------------------------------------------------------
angular.module('rfi-client.services').service('InputManager', [
'$rootScope',
'lodash',
'SocketService',
'ConfigurationManager',
'KeyBindingService',
'SceneManager',
InputManagerFactory
]);
// ---------------------------------------------------------------------------------------------------------------------
|
angular.module("rt.iso8601",[]).factory("iso8601",function(){function a(a){return parseInt(a,10)}var b="substring",c="indexOf",d="length";return{parse:function(e){var f,g,h,i,j,k,l=0;if(i=j=k=0,!e||!e[d])return null;if(e[d]>=10){var m=e[b](0,10).split("-");f=a(m[0]),g=a(m[1])-1,h=a(m[2])}if(e[d]>=11){for(var n=e[b](11).split(":");n[d]<3;)n.push("");i=a(n[0]),j=a(n[1]),k=a(n[2][b](0,2))||0;var o=n[2][b](2)||"";if("."===o[0]){var p=Math.max(o[c]("Z"),o[c]("+"),o[c]("-"));o=p>-1?o[b](p):""}if(""===o)return new Date(f,g,h,i,j,k,0);if("Z"===o);else{if(3!==o[d])throw new Error("Unsupported timezone offset: "+o);var q=60*a(o[b](1));l=60*-q*1e3}}var r=Date.UTC(f,g,h,i,j,k,0),s=new Date(r+l);return s}}}); |
var net = require('net');
var util = require('util');
var events = require('events');
var proto = require('./protocol');
module.exports = Device;
function Device(conf) {
events.EventEmitter.call(this, conf);
var self = this;
this.backlog = [];
this.device_id = conf.device_id;
this.device_ip = conf.device_ip;
this.control_sock = net.createConnection(65001, this.device_ip,
function () {
self.emit('connected');
});
this.request_encoder = new proto.RequestEncoder();
this.reply_decoder = new proto.ReplyDecoder();
this.request_encoder.pipe(this.control_sock);
this.control_sock.pipe(this.reply_decoder);
this.reply_decoder.on('reply', function onReply(msg) {
var buf, item, cb, err;
if (msg.error_message)
err = new Error(msg.error_message);
if (self.backlog.length > 0) {
item = self.backlog.shift();
cb = item.callback;
clearTimeout(item.timeout);
cb(err, {name: msg.getset_name,
value: msg.getset_value});
} else {
console.log('unexpected reply');
}
});
this.on('CTS', function () {
if (self.backlog.length > 0) {
self.request_encoder.send(self.backlog[0].request);
} else {
console.log('CTS with empty backlog');
}
});
}
util.inherits(Device, events.EventEmitter);
Device.prototype.get = function (name, cb) {
get_set.call(this, name, cb);
}
Device.prototype.set = function (name, value, cb) {
get_set.call(this, name, value, cb);
}
function get_set(name, value, cb) {
var which = 'set';
if ((arguments.length == 2) && (typeof (value) == 'function')) {
cb = value;
value = null;
which = 'get';
}
var msg = {
type: proto.types.getset_req,
getset_name: name
};
if (which == 'set')
msg.getset_value = value;
this._request(msg, cb);
}
Device.prototype._request = function (msg, cb) {
var self = this;
var to = setTimeout(function () {
var unanswered = self.backlog.shift();
var cb = unanswered.callback;
var err = new Error('request timeout');
cb(err);
if (self.backlog.length > 0)
self.emit('CTS');
}, 2500);
this.backlog.push({request: msg, callback: cb, timeout: to});
if (this.backlog.length === 1)
this.emit('CTS');
}
|
import { default as Dungeon } from '../../../src/client/js/app/dungeons/Dungeon';
import { default as Tiles } from '../../../src/client/js/app/tiles/Tiles';
import { default as DashAttack } from '../../../src/client/js/app/abilities/DashAttack';
import { default as Dagger } from '../../../src/client/js/app/entities/weapons/Dagger';
import { default as PlayableCharacter } from '../../../src/client/js/app/entities/creatures/PlayableCharacter';
import { default as Ent } from '../../../src/client/js/app/entities/creatures/enemies/Ent';
var expect = require('chai').expect;
describe('DashAttack', function() {
var dungeon;
var attack;
var player;
var weapon;
beforeEach(function() {
dungeon = new Dungeon(4, 4);
attack = new DashAttack();
player = new PlayableCharacter();
weapon = new Dagger();
});
it('should require the target tile to contain an enemy', function() {
player.addItem(weapon);
dungeon.moveCreature(player, 0, 0);
dungeon.resolveUntilBlocked();
var reason = attack.getReasonIllegal(dungeon, player, dungeon.getTile(3, 3));
expect(reason).to.be.a('string');
});
it('should not allow the player to attack themself', function() {
player.addItem(weapon);
dungeon.moveCreature(player, 0, 0);
dungeon.resolveUntilBlocked();
var reason = attack.getReasonIllegal(dungeon, player, dungeon.getTile(0, 0));
expect(reason).to.be.a('string');
});
it('should now allow the player to attack an adjacent enemy', function() {
player.addItem(weapon);
dungeon.moveCreature(player, 0, 0);
dungeon.moveCreature(new Ent(), 1, 1);
dungeon.resolveUntilBlocked();
var reason = attack.getReasonIllegal(dungeon, player, dungeon.getTile(1, 1));
expect(reason).to.be.a('string');
});
it('should now allow the player to attack without a melee weapon', function() {
dungeon.moveCreature(player, 0, 0);
dungeon.moveCreature(new Ent(), 2, 2);
dungeon.resolveUntilBlocked();
var reason = attack.getReasonIllegal(dungeon, player, dungeon.getTile(2, 2));
expect(reason).to.be.a('string');
});
it('should not let the player dash onto enemies', function() {
player.addItem(weapon);
dungeon.moveCreature(player, 0, 0);
dungeon.moveCreature(new Ent(), 1, 1);
dungeon.moveCreature(new Ent(), 1, 2);
dungeon.moveCreature(new Ent(), 2, 1);
dungeon.moveCreature(new Ent(), 2, 2);
dungeon.resolveUntilBlocked();
var reason = attack.getReasonIllegal(dungeon, player, dungeon.getTile(2, 2));
expect(reason).to.be.a('string');
});
it('should not let the player dash into pit', function() {
player.addItem(weapon);
dungeon.moveCreature(player, 0, 0);
dungeon.setTile(new Tiles.PitTile(0, 1), 0, 1);
dungeon.moveCreature(new Ent(), 0, 2);
dungeon.resolveUntilBlocked();
var reason = attack.getReasonIllegal(dungeon, player, dungeon.getTile(2, 2));
expect(reason).to.be.a('string');
});
/*it('should not let the player dash through enemies', function() {
player.addItem(weapon);
dungeon.moveCreature(player, 0, 0);
dungeon.moveCreature(new Ent(), 0, 1);
dungeon.moveCreature(new Ent(), 0, 3);
dungeon.resolveUntilBlocked();
var reason = attack.getReasonIllegal(dungeon, player, dungeon.getTile(0, 3));
expect(reason).to.be.a('string');
});*/
it('should reposition the player', function() {
player.addItem(weapon);
dungeon.moveCreature(player, 0, 0);
dungeon.moveCreature(new Ent(), 2, 2);
dungeon.resolveUntilBlocked();
attack.use(dungeon, player, dungeon.getTile(2, 2));
var newLocation = dungeon.getTile(player);
expect(newLocation.getX()).to.equal(1);
expect(newLocation.getY()).to.equal(1);
});
it('should cause the player to attack', function() {
player.addItem(weapon);
dungeon.moveCreature(player, 0, 0);
dungeon.moveCreature(new Ent(), 2, 2);
dungeon.resolveUntilBlocked();
var reason = attack.getReasonIllegal(dungeon, player, dungeon.getTile(2, 2));
expect(reason).not.to.be.a('string');
});
it('should be considered a movement ability', function() {
expect(attack.isMovementAbility()).to.equal(true);
});
it('should have a description', function() {
var desc = attack.getDescription();
expect(desc).to.be.a('string');
expect(desc).to.have.length.above(0);
});
});
|
class Foo {
*[Symbol.iterator]() {}
}
let f = new Foo();
console.log(f[Symbol.iterator]());
// Generator {<suspended>}
|
/*****************************************************************************/
/* PagesShow: Event Handlers and Helpersss .js*/
/*****************************************************************************/
Template.PagesShow.events({
'click #new-paragraph-action': function (e) {
e.preventDefault();
Session.set('newParagraph', this._id);
},
'click #hide-admin-menu': function (e) {
e.preventDefault();
if (Session.get('hideAdminMenu')) {
Session.set('hideAdminMenu', false);
Alerts.set('Admin menu is visible.', 'info');
} else {
Session.set('hideAdminMenu', true);
Alerts.set('Admin menu is hidden', 'info');
}
}
});
Template.PagesShow.helpers({
newParagraph: function () {
if (Meteor.user() && Session.get('newParagraph') === this._id) {
return true;
} else {
return false;
}
},
paragraphs: function () {
var paragraphsOrder = this.paragraphsOrder || 1;
return Paragraphs.find({}, { sort: { rank: paragraphsOrder } });
},
editTitle: function () {
if (Meteor.user() && Session.get('editTitle') === this._id) {
return true;
} else {
return false;
}
},
editParagraph: function () {
if (Meteor.user() && Session.get('editParagraph') === this._id) {
return true;
} else {
return false;
}
},
showComments: function () {
var settings = Settings.findOne();
var page = Pages.findOne();
if (settings.disqusShortname && page.disqus) {
return true;
} else {
return false;
}
},
liveBlogging: function () {
var page = Pages.findOne();
if (page.paragraphsOrder === -1) {
return true;
} else {
return false;
}
}
});
/*****************************************************************************/
/* PagesShow: Lifecycle Hooks */
/*****************************************************************************/
Template.PagesShow.created = function () {
};
Template.PagesShow.rendered = function () {
Session.set('editTitle', null);
Session.set('newParagraph', null);
Session.set('editParagraph', null);
Session.set('pageSettings', null);
if (Session.get('smartEditor') === undefined) {
Session.set('smartEditor', true);
}
/* jshint ignore:start */
// set up Google Analytics for pages
var settings = Settings.findOne();
var controller = Iron.controller();
if (settings.googleTrackingId && !Meteor.user()) {
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', settings.googleTrackingId, 'auto');
ga('send', 'pageview', {
'page': '/pages/' + controller.params._id
});
}
/* jshint ignore:end */
};
Template.PagesShow.destroyed = function () {
};
|
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* The Phaser.Game object is the main controller for the entire Phaser game. It is responsible
* for handling the boot process, parsing the configuration values, creating the renderer,
* and setting-up all of the Phaser systems, such as physics, sound and input.
* Once that is complete it will start the default State, and then begin the main game loop.
*
* You can access lots of the Phaser systems via the properties on the `game` object. For
* example `game.renderer` is the Renderer, `game.sound` is the Sound Manager, and so on.
*
* Anywhere you can access the `game` property, you can access all of these core systems.
* For example a Sprite has a `game` property, allowing you to talk to the various parts
* of Phaser directly, without having to look after your own references.
*
* In its most simplest form, a Phaser game can be created by providing the arguments
* to the constructor:
*
* ```javascript
* var game = new Phaser.Game(800, 600, Phaser.AUTO, '', { preload: preload, create: create });
* ```
*
* In the example above it is passing in a State object directly. You can also use the State
* Manager to do this:
*
* ```javascript
* var game = new Phaser.Game(800, 600, Phaser.AUTO);
* game.state.add('Boot', BasicGame.Boot);
* game.state.add('Preloader', BasicGame.Preloader);
* game.state.add('MainMenu', BasicGame.MainMenu);
* game.state.add('Game', BasicGame.Game);
* game.state.start('Boot');
* ```
*
* In the example above, 4 States are added to the State Manager, and Phaser is told to
* start running the `Boot` state when it has finished initializing. There are example
* project templates you can use in the Phaser GitHub repo, inside the `resources` folder.
*
* Instead of specifying arguments you can also pass {@link GameConfig a single object} instead:
*
* ```javascript
* var config = {
* width: 800,
* height: 600,
* renderer: Phaser.AUTO,
* antialias: true,
* multiTexture: true,
* state: {
* preload: preload,
* create: create,
* update: update
* }
* }
*
* var game = new Phaser.Game(config);
* ```
*
* @class Phaser.Game
* @constructor
* @param {number|string|GameConfig} [width=800] - The width of your game in game pixels. If given as a string the value must be between 0 and 100 and will be used as the percentage width of the parent container, or the browser window if no parent is given.
* @param {number|string} [height=600] - The height of your game in game pixels. If given as a string the value must be between 0 and 100 and will be used as the percentage height of the parent container, or the browser window if no parent is given.
* @param {number} [renderer=Phaser.AUTO] - Which renderer to use: Phaser.AUTO will auto-detect, Phaser.WEBGL, Phaser.WEBGL_MULTI, Phaser.CANVAS or Phaser.HEADLESS (no rendering at all).
* @param {string|HTMLElement} [parent=''] - The DOM element into which this game canvas will be injected. Either a DOM `id` (string) or the element itself. If omitted (or no such element exists), the game canvas is appended to the document body.
* @param {object} [state=null] - The default state object. A object consisting of Phaser.State functions (preload, create, update, render) or null.
* @param {boolean} [transparent=false] - Use a transparent canvas background or not.
* @param {boolean} [antialias=true] - Draw all image textures anti-aliased or not. The default is for smooth textures, but disable if your game features pixel art.
* @param {object} [physicsConfig=null] - A physics configuration object to pass to the Physics world on creation.
*/
Phaser.Game = function (width, height, renderer, parent, state, transparent, antialias, physicsConfig)
{
/**
* @property {number} id - Phaser Game ID
* @readonly
*/
this.id = Phaser.GAMES.push(this) - 1;
/**
* @property {object} config - The Phaser.Game configuration object.
*/
this.config = null;
/**
* @property {object} physicsConfig - The Phaser.Physics.World configuration object.
*/
this.physicsConfig = physicsConfig;
/**
* @property {string|HTMLElement} parent - The Game's DOM parent (or name thereof), if any, as set when the game was created. The actual parent can be found in `game.canvas.parentNode`. Setting this has no effect after {@link Phaser.ScaleManager} is booted.
* @readonly
* @default
*/
this.parent = '';
/**
* The current Game Width in pixels.
*
* _Do not modify this property directly:_ use {@link Phaser.ScaleManager#setGameSize} - e.g. `game.scale.setGameSize(width, height)` - instead.
*
* @property {integer} width
* @readonly
* @default
*/
this.width = 800;
/**
* The current Game Height in pixels.
*
* _Do not modify this property directly:_ use {@link Phaser.ScaleManager#setGameSize} - e.g. `game.scale.setGameSize(width, height)` - instead.
*
* @property {integer} height
* @readonly
* @default
*/
this.height = 600;
/**
* The resolution of your game, as a ratio of canvas pixels to game pixels. This value is read only, but can be changed at start time it via a game configuration object.
*
* @property {integer} resolution
* @readonly
* @default
*/
this.resolution = 1;
/**
* @property {integer} _width - Private internal var.
* @private
*/
this._width = 800;
/**
* @property {integer} _height - Private internal var.
* @private
*/
this._height = 600;
/**
* @property {boolean} transparent - Use a transparent canvas background or not.
* @default
*/
this.transparent = false;
/**
* @property {boolean} antialias - Anti-alias graphics (as set when the Game is created). By default scaled and rotated images are smoothed in Canvas and WebGL; set `antialias` to false to disable this globally. After the game boots, use `game.stage.smoothed` instead.
* @readonly
* @default
*/
this.antialias = true;
/**
* Has support for Multiple bound Textures in WebGL been enabled? This is a read-only property.
* To set it you need to either specify `Phaser.WEBGL_MULTI` as the renderer type, or use the Game
* Configuration object with the property `multiTexture` set to true. It has to be enabled before
* Pixi boots, and cannot be changed after the game is running. Once enabled, take advantage of it
* via the `game.renderer.setTexturePriority` method.
*
* @property {boolean} multiTexture
* @readonly
* @default
*/
this.multiTexture = false;
/**
* @property {boolean} preserveDrawingBuffer - The value of the preserveDrawingBuffer flag affects whether or not the contents of the stencil buffer is retained after rendering.
* @default
*/
this.preserveDrawingBuffer = false;
/**
* Clear the Canvas each frame before rendering the display list.
* You can set this to `false` to gain some performance if your game always contains a background that completely fills the display.
* This must be `true` to show any {@link Phaser.Stage#backgroundColor} set on the Stage.
* This is effectively **read-only after the game has booted**.
* Use the {@link GameConfig} setting `clearBeforeRender` when creating the game, or set `game.renderer.clearBeforeRender` afterwards.
* @property {boolean} clearBeforeRender
* @default
*/
this.clearBeforeRender = true;
/**
* @property {PIXI.CanvasRenderer|PIXI.WebGLRenderer} renderer - The Pixi Renderer.
* @protected
*/
this.renderer = null;
/**
* @property {number} renderType - The Renderer this game will use. Either Phaser.AUTO, Phaser.CANVAS, Phaser.WEBGL, Phaser.WEBGL_MULTI or Phaser.HEADLESS. After the game boots, renderType reflects the renderer in use: AUTO changes to CANVAS or WEBGL and WEBGL_MULTI changes to WEBGL. HEADLESS skips `preRender`, `render`, and `postRender` hooks, just like {@link #lockRender}.
* @readonly
*/
this.renderType = Phaser.AUTO;
/**
* @property {Phaser.StateManager} state - The StateManager.
*/
this.state = null;
/**
* @property {boolean} isBooted - Whether the game engine is booted, aka available.
* @readonly
*/
this.isBooted = false;
/**
* @property {boolean} isRunning - Is game running or paused?
* @readonly
*/
this.isRunning = false;
/**
* @property {Phaser.RequestAnimationFrame} raf - Automatically handles the core game loop via requestAnimationFrame or setTimeout
* @protected
*/
this.raf = null;
/**
* @property {Phaser.GameObjectFactory} add - Reference to the Phaser.GameObjectFactory.
*/
this.add = null;
/**
* @property {Phaser.GameObjectCreator} make - Reference to the GameObject Creator.
*/
this.make = null;
/**
* @property {Phaser.Cache} cache - Reference to the assets cache.
*/
this.cache = null;
/**
* @property {Phaser.Input} input - Reference to the input manager
*/
this.input = null;
/**
* @property {Phaser.Loader} load - Reference to the assets loader.
*/
this.load = null;
/**
* @property {Phaser.Math} math - Reference to the math helper.
*/
this.math = null;
/**
* @property {Phaser.ScaleManager} scale - The game scale manager.
*/
this.scale = null;
/**
* @property {Phaser.SoundManager} sound - Reference to the sound manager.
*/
this.sound = null;
/**
* @property {Phaser.Stage} stage - Reference to the stage.
*/
this.stage = null;
/**
* @property {Phaser.Time} time - Reference to the core game clock.
*/
this.time = null;
/**
* @property {Phaser.TweenManager} tweens - Reference to the tween manager.
*/
this.tweens = null;
/**
* @property {Phaser.World} world - Reference to the world.
*/
this.world = null;
/**
* @property {Phaser.Physics} physics - Reference to the physics manager.
*/
this.physics = null;
/**
* @property {Phaser.PluginManager} plugins - Reference to the plugin manager.
*/
this.plugins = null;
/**
* @property {Phaser.RandomDataGenerator} rnd - Instance of repeatable random data generator helper.
*/
this.rnd = null;
/**
* @property {Phaser.Device} device - Contains device information and capabilities.
*/
this.device = Phaser.Device;
/**
* @property {Phaser.Camera} camera - A handy reference to world.camera.
*/
this.camera = null;
/**
* @property {HTMLCanvasElement} canvas - A handy reference to renderer.view, the canvas that the game is being rendered in to.
*/
this.canvas = null;
/**
* @property {CanvasRenderingContext2D} context - A handy reference to renderer.context (only set for CANVAS games, not WebGL)
*/
this.context = null;
/**
* @property {Phaser.Utils.Debug} debug - A set of useful debug utilities.
*/
this.debug = null;
/**
* @property {Phaser.Particles} particles - The Particle Manager.
*/
this.particles = null;
/**
* @property {Phaser.Create} create - The Asset Generator.
*/
this.create = null;
/**
* If `false` Phaser will automatically render the display list every update. If `true` the render loop will be skipped.
* You can toggle this value at run-time to gain exact control over when Phaser renders. This can be useful in certain types of game or application.
* Please note that if you don't render the display list then none of the game object transforms will be updated, so use this value carefully.
* @property {boolean} lockRender
* @default
*/
this.lockRender = false;
/**
* @property {boolean} pendingDestroy - Destroy the game at the next update.
* @default
*/
this.pendingDestroy = false;
/**
* @property {boolean} stepping - Enable core loop stepping with Game.enableStep().
* @default
* @readonly
*/
this.stepping = false;
/**
* @property {boolean} pendingStep - An internal property used by enableStep, but also useful to query from your own game objects.
* @default
* @readonly
*/
this.pendingStep = false;
/**
* @property {number} stepCount - When stepping is enabled this contains the current step cycle.
* @default
* @readonly
*/
this.stepCount = 0;
/**
* @property {Phaser.Signal} onPause - This event is fired when the game pauses.
*/
this.onPause = null;
/**
* @property {Phaser.Signal} onResume - This event is fired when the game resumes from a paused state.
*/
this.onResume = null;
/**
* @property {Phaser.Signal} onBlur - This event is fired when the game no longer has focus (typically on page hide).
*/
this.onBlur = null;
/**
* @property {Phaser.Signal} onFocus - This event is fired when the game has focus (typically on page show).
*/
this.onFocus = null;
/**
* @property {Phaser.Signal} onBoot - This event is fired after the game boots but before the first game update.
*/
this.onBoot = new Phaser.Signal();
/**
* @property {boolean} _paused - Is game paused?
* @private
*/
this._paused = false;
/**
* @property {boolean} _codePaused - Was the game paused via code or a visibility change?
* @private
*/
this._codePaused = false;
/**
* @property {boolean} _focusGained - The game has just regained focus.
* @private
*/
this._focusGained = false;
/**
* The ID of the current/last logic update applied this animation frame, starting from 0.
* The first update is `currentUpdateID === 0` and the last update is `currentUpdateID === updatesThisFrame.`
* @property {integer} currentUpdateID
* @protected
*/
this.currentUpdateID = 0;
/**
* Number of logic updates expected to occur this animation frame; will be 1 unless there are catch-ups required (and allowed).
* @property {integer} updatesThisFrame
* @protected
*/
this.updatesThisFrame = 1;
/**
* Number of renders expected to occur this animation frame. May be 0 if {@link #forceSingleRender} is off; otherwise it will be 1.
* @property {integer} rendersThisFrame
* @protected
*/
this.rendersThisFrame = 1;
/**
* @property {number} _deltaTime - Accumulate elapsed time until a logic update is due.
* @private
*/
this._deltaTime = 0;
/**
* @property {number} _lastCount - Remember how many 'catch-up' iterations were used on the logicUpdate last frame.
* @private
*/
this._lastCount = 0;
/**
* @property {number} _spiraling - If the 'catch-up' iterations are spiraling out of control, this counter is incremented.
* @private
*/
this._spiraling = 0;
/**
* @property {boolean} _kickstart - Force a logic update + render by default (always set on Boot and State swap)
* @private
*/
this._kickstart = true;
/**
* If the game is struggling to maintain the desired FPS, this signal will be dispatched.
* The desired/chosen FPS should probably be closer to the {@link Phaser.Time#suggestedFps} value.
* @property {Phaser.Signal} fpsProblemNotifier
* @public
*/
this.fpsProblemNotifier = new Phaser.Signal();
/**
* @property {boolean} forceSingleUpdate - Use a variable-step game loop (true) or a fixed-step game loop (false).
* @default
* @see Phaser.Time#desiredFps
*/
this.forceSingleUpdate = true;
/**
* @property {boolean} forceSingleRender - Should the game loop make one render per animation frame, even without a preceding logic update?
* @default
*/
this.forceSingleRender = false;
/**
* @property {boolean} dropFrames - Skip a logic update and render if the delta is too large (see {@link Phaser.Time#deltaMax}). When false, the delta is clamped to the maximum instead.
* @default
*/
this.dropFrames = false;
/**
* @property {string} powerPreference - When the WebGL renderer is used, hint to the browser which GPU to use.
* @readonly
* @default
*/
this.powerPreference = 'default';
/**
* @property {number} _nextNotification - The soonest game.time.time value that the next fpsProblemNotifier can be dispatched.
* @private
*/
this._nextFpsNotification = 0;
// Parse the configuration object (if any)
if (arguments.length === 1 && typeof arguments[0] === 'object')
{
this.parseConfig(arguments[0]);
}
else
{
this.config = { enableDebug: true };
if (typeof width !== 'undefined')
{
this._width = width;
}
if (typeof height !== 'undefined')
{
this._height = height;
}
if (typeof renderer !== 'undefined')
{
this.renderType = renderer;
}
if (typeof parent !== 'undefined')
{
this.parent = parent;
}
if (typeof transparent !== 'undefined')
{
this.transparent = transparent;
}
if (typeof antialias !== 'undefined')
{
this.antialias = antialias;
}
this.rnd = new Phaser.RandomDataGenerator([ (Date.now() * Math.random()).toString() ]);
this.state = new Phaser.StateManager(this, state);
}
this.device.whenReady(this.boot, this);
return this;
};
/**
* A configuration object for {@link Phaser.Game}.
*
* @typedef {object} GameConfig
* @property {boolean} [GameConfig.alignH=false] - Sets {@link Phaser.ScaleManager#pageAlignHorizontally}.
* @property {boolean} [GameConfig.alignV=false] - Sets {@link Phaser.ScaleManager#pageAlignVertically}.
* @property {boolean} [GameConfig.antialias=true]
* @property {number|string} [GameConfig.backgroundColor=0] - Sets {@link Phaser.Stage#backgroundColor}.
* @property {HTMLCanvasElement} [GameConfig.canvas] - An existing canvas to display the game in.
* @property {string} [GameConfig.canvasID] - `id` attribute value to assign to the game canvas.
* @property {string} [GameConfig.canvasStyle] - `style` attribute value to assign to the game canvas.
* @property {boolean} [GameConfig.clearBeforeRender=true] - Sets {@link Phaser.Game#clearBeforeRender}.
* @property {boolean} [GameConfig.crisp=false] - Sets the canvas's `image-rendering` property to `pixelated` or `crisp-edges`. See {@link Phaser.Canvas.setImageRenderingCrisp}.
* @property {boolean} [GameConfig.disableVisibilityChange=false] - Sets {@link Phaser.Stage#disableVisibilityChange}
* @property {boolean} [GameConfig.disableStart=false] - Prevents the game loop from starting, allowing you to call updates manually. Helpful for automated testing.
* @property {boolean} [GameConfig.enableDebug=true] - Enable {@link Phaser.Utils.Debug}. You can gain a little performance by disabling this in production.
* @property {boolean} [GameConfig.failIfMajorPerformanceCaveat] - Abort WebGL context creation if performance would be poor. You can use this with renderer AUTO.
* @property {boolean} [GameConfig.forceSetTimeOut] - Use {@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout setTimeout} for the game loop even if {@link https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame requestAnimationFrame} is available.
* @property {number} [GameConfig.fullScreenScaleMode] - The scaling method used by the ScaleManager when in fullscreen.
* @property {HTMLElement} [GameConfig.fullScreenTarget] - The DOM element on which the Fullscreen API enter request will be invoked.
* @property {number|string} [GameConfig.height=600]
* @property {boolean} [GameConfig.keyboard=true] - Starts the keyboard input handler.
* @property {number} [GameConfig.maxPointers=-1] - Sets {@link Phaser.Input#maxPointers}.
* @property {boolean} [GameConfig.mouse=true] - Starts the mouse input handler, if the mspointer and touch handlers were not started.
* @property {boolean} [GameConfig.mouseWheel=false] - Starts the {@link Phaser.MouseWheel mouse wheel} handler, if supported by the device.
* @property {boolean} [GameConfig.mspointer=true] - Starts the {@link Phaser.MSPointer Pointer Events} handler (mspointer), if supported by the device.
* @property {boolean} [GameConfig.multiTexture=false] - Enable support for multiple bound Textures in WebGL. Same as `{renderer: Phaser.WEBGL_MULTI}`.
* @property {string|HTMLElement} [GameConfig.parent=''] - The DOM element into which this games canvas will be injected.
* @property {object} [GameConfig.physicsConfig]
* @property {boolean} [GameConfig.pointerLock=true] - Starts the {@link Phaser.PointerLock Pointer Lock} handler, if supported by the device.
* @property {string} [GameConfig.powerPreference='default'] - Sets the WebGL renderer's powerPreference when the WebGL renderer is used.
* @property {boolean} [GameConfig.preserveDrawingBuffer=false] - Whether or not the contents of the stencil buffer is retained after rendering.
* @property {number} [GameConfig.renderer=Phaser.AUTO]
* @property {number} [GameConfig.resolution=1] - The resolution of your game, as a ratio of canvas pixels to game pixels.
* @property {boolean} [GameConfig.roundPixels=false] - Round pixel coordinates for rendering (rather than interpolating). Handy for crisp pixel art and speed on legacy devices.
* @property {number} [GameConfig.scaleH=1] - Horizontal scaling factor for USER_SCALE scale mode.
* @property {number} [GameConfig.scaleMode] - The scaling method used by the ScaleManager when not in fullscreen.
* @property {number} [GameConfig.scaleV=1] - Vertical scaling factor for USER_SCALE scale mode.
* @property {number} [GameConfig.seed] - Seed for {@link Phaser.RandomDataGenerator}.
* @property {object} [GameConfig.state]
* @property {boolean} [GameConfig.touch=true] - Starts the {@link Phaser.Touch touch} handler, if supported by the device and the Pointer Events handler (mspointer) was not started.
* @property {boolean|string} [GameConfig.transparent=false] - Sets {@link Phaser.Game#transparent}. `'notMultiplied'` disables the WebGL context attribute `premultipliedAlpha`.
* @property {number} [GameConfig.trimH=0] - Horizontal trim for USER_SCALE scale mode.
* @property {number} [GameConfig.trimV=0] - Vertical trim for USER_SCALE scale mode.
* @property {number|string} [GameConfig.width=800]
*/
// Documentation stub for linking.
Phaser.Game.prototype = {
/**
* Parses a Game configuration object.
*
* @method Phaser.Game#parseConfig
* @protected
*/
parseConfig: function (config)
{
this.config = config;
if (config.enableDebug === undefined)
{
this.config.enableDebug = true;
}
if (config.width)
{
this._width = config.width;
}
if (config.height)
{
this._height = config.height;
}
if (config.renderer)
{
this.renderType = config.renderer;
}
if (config.parent)
{
this.parent = config.parent;
}
if (config.transparent !== undefined)
{
this.transparent = config.transparent;
}
if (config.antialias !== undefined)
{
this.antialias = config.antialias;
}
if (config.clearBeforeRender !== undefined)
{
this.clearBeforeRender = config.clearBeforeRender;
}
if (config.multiTexture !== undefined)
{
this.multiTexture = config.multiTexture;
}
if (config.resolution)
{
this.resolution = config.resolution;
}
if (config.preserveDrawingBuffer !== undefined)
{
this.preserveDrawingBuffer = config.preserveDrawingBuffer;
}
if (config.powerPreference !== undefined)
{
this.powerPreference = config.powerPreference;
}
if (config.physicsConfig)
{
this.physicsConfig = config.physicsConfig;
}
var seed = [ (Date.now() * Math.random()).toString() ];
if (config.seed)
{
seed = config.seed;
}
this.rnd = new Phaser.RandomDataGenerator(seed);
var state = null;
if (config.state)
{
state = config.state;
}
this.state = new Phaser.StateManager(this, state);
},
/**
* Initialize engine sub modules and start the game.
*
* @method Phaser.Game#boot
* @protected
*/
boot: function ()
{
if (this.isBooted)
{
return;
}
this.onPause = new Phaser.Signal();
this.onResume = new Phaser.Signal();
this.onBlur = new Phaser.Signal();
this.onFocus = new Phaser.Signal();
this.isBooted = true;
PIXI.game = this;
this.math = Phaser.Math;
this.scale = new Phaser.ScaleManager(this, this._width, this._height);
this.stage = new Phaser.Stage(this);
this.setUpRenderer();
this.world = new Phaser.World(this);
this.add = new Phaser.GameObjectFactory(this);
this.make = new Phaser.GameObjectCreator(this);
this.cache = new Phaser.Cache(this);
this.load = new Phaser.Loader(this);
this.time = new Phaser.Time(this);
this.tweens = new Phaser.TweenManager(this);
this.input = new Phaser.Input(this);
this.sound = new Phaser.SoundManager(this);
this.physics = new Phaser.Physics(this, this.physicsConfig);
this.particles = new Phaser.Particles(this);
this.create = new Phaser.Create(this);
this.plugins = new Phaser.PluginManager(this);
this.time.boot();
this.stage.boot();
this.world.boot();
this.scale.boot();
this.input.boot(this.config);
this.sound.boot();
this.state.boot();
if (this.config.enableDebug)
{
this.debug = new Phaser.Utils.Debug(this);
this.debug.boot();
}
else
{
var noop = function () {};
this.debug = { preUpdate: noop, update: noop, reset: noop, destroy: noop, isDisabled: true };
}
this.showDebugHeader();
this.isRunning = true;
if (this.config && this.config.forceSetTimeOut)
{
this.raf = new Phaser.RequestAnimationFrame(this, this.config.forceSetTimeOut);
}
else
{
this.raf = new Phaser.RequestAnimationFrame(this, false);
}
this._kickstart = true;
this.focusWindow();
this.onBoot.dispatch(this);
if (this.config.disableStart)
{
return;
}
if (this.cache.isReady)
{
this.raf.start();
}
else
{
this.cache.onReady.addOnce(function ()
{
this.raf.start();
}, this);
}
},
/**
* Displays a Phaser version debug header in the console.
*
* @method Phaser.Game#showDebugHeader
* @protected
*/
showDebugHeader: function ()
{
if (window.PhaserGlobal && window.PhaserGlobal.hideBanner)
{
return;
}
var v = Phaser.VERSION;
var r = 'Canvas';
var a = 'HTML Audio';
var c = 1;
if (this.renderType === Phaser.WEBGL)
{
r = 'WebGL';
c++;
}
else if (this.renderType === Phaser.HEADLESS)
{
r = 'Headless';
}
if (this.device.webAudio)
{
a = 'WebAudio';
c++;
}
if (!this.device.ie) // https://developer.mozilla.org/en-US/docs/Web/API/Console/log#Browser_compatibility
{
var args = [
'%c %c %c Phaser CE v' + v + ' | Pixi.js | ' + r + ' | ' + a + ' %c %c ' + '%c http://phaser.io %c\u2665%c\u2665%c\u2665',
'background: #fb8cb3',
'background: #d44a52',
'color: #ffffff; background: #871905;',
'background: #d44a52',
'background: #fb8cb3',
'background: #ffffff'
];
for (var i = 0; i < 3; i++)
{
if (i < c)
{
args.push('color: #ff2424; background: #fff');
}
else
{
args.push('color: #959595; background: #fff');
}
}
console.log.apply(console, args);
}
else if (window.console)
{
console.log('Phaser v' + v + ' | Pixi.js | ' + r + ' | ' + a + ' | http://phaser.io');
}
},
/**
* Checks if the device is capable of using the requested renderer and sets it up or an alternative if not.
*
* @method Phaser.Game#setUpRenderer
* @protected
*/
setUpRenderer: function ()
{
if (!this.device.canvas)
{
// Nothing else to do
throw new Error('Phaser.Game - Cannot create Canvas 2d context, aborting.');
}
if (this.config.canvas)
{
this.canvas = this.config.canvas;
}
else
{
this.canvas = Phaser.Canvas.create(this, this.width, this.height, this.config.canvasID, true);
}
if (this.config.canvasStyle)
{
this.canvas.style = this.config.canvasStyle;
}
else
{
this.canvas.style['-webkit-full-screen'] = 'width: 100%; height: 100%';
}
if (this.config.crisp)
{
Phaser.Canvas.setImageRenderingCrisp(this.canvas);
}
if ((this.renderType === Phaser.WEBGL) ||
(this.renderType === Phaser.WEBGL_MULTI) ||
(this.renderType === Phaser.AUTO && this.device.webGL))
{
if (this.multiTexture || this.renderType === Phaser.WEBGL_MULTI)
{
PIXI.enableMultiTexture();
this.multiTexture = true;
}
try
{
this.renderer = new PIXI.WebGLRenderer(this, this.config);
this.renderType = Phaser.WEBGL;
this.context = null;
this.canvas.addEventListener('webglcontextlost', this.contextLost.bind(this), false);
this.canvas.addEventListener('webglcontextrestored', this.contextRestored.bind(this), false);
}
catch (webGLRendererError)
{
PIXI.defaultRenderer = null;
this.renderer = null;
this.multiTexture = false;
PIXI._enableMultiTextureToggle = false;
if (this.renderType === Phaser.WEBGL)
{
// No fallback
throw webGLRendererError;
}
}
}
if (!this.renderer)
{
this.renderer = new PIXI.CanvasRenderer(this, this.config);
this.context = this.renderer.context;
if (this.renderType === Phaser.AUTO)
{
this.renderType = Phaser.CANVAS;
}
}
if (this.device.cocoonJS)
{
this.canvas.screencanvas = (this.renderType === Phaser.CANVAS) ? true : false;
}
if (this.renderType !== Phaser.HEADLESS)
{
this.stage.smoothed = this.antialias;
Phaser.Canvas.addToDOM(this.canvas, this.parent, false);
Phaser.Canvas.setTouchAction(this.canvas);
}
},
/**
* Handles WebGL context loss.
*
* @method Phaser.Game#contextLost
* @private
* @param {Event} event - The webglcontextlost event.
*/
contextLost: function (event)
{
event.preventDefault();
this.renderer.contextLost = true;
},
/**
* Handles WebGL context restoration.
*
* @method Phaser.Game#contextRestored
* @private
*/
contextRestored: function ()
{
this.renderer.initContext();
this.cache.clearGLTextures();
this.renderer.contextLost = false;
},
/**
* The core game loop.
*
* @method Phaser.Game#update
* @protected
* @param {number} time - The current time in milliseconds as provided by RequestAnimationFrame.
*/
update: function (time)
{
if (this.pendingDestroy)
{
this.destroy();
return;
}
if (!this.isBooted)
{
return;
}
// Sets `elapsed`, `elapsedMS`, `now`, `time`
this.time.update(time);
if (this._kickstart)
{
this.updateLogic(this.time.desiredFpsMult);
this.updateRender();
this._kickstart = false;
return;
}
if (this._focusGained)
{
this._focusGained = false;
// Wait for next frame.
return;
}
var elapsed = this.time.elapsed;
if (elapsed <= 0)
{
return;
}
if (elapsed > this.time.deltaMax)
{
// `dropFrames` not so useful.
if (this.dropFrames)
{
return;
}
else
{
elapsed = this.time.deltaMax;
}
}
if (this.forceSingleUpdate)
{
this.updatesThisFrame = 1;
this.rendersThisFrame = 1;
this.updateLogic(0.001 * elapsed / this.time.slowMotion);
this.updateRender();
}
else if (this._spiraling > 2)
{
// Skip update and render completely
this.updatesThisFrame = 0;
this.rendersThisFrame = 0;
// Notify
if (this.time.time > this._nextFpsNotification)
{
this._nextFpsNotification = this.time.time + 10000;
this.fpsProblemNotifier.dispatch();
}
// Discard all pending late updates
this._deltaTime = 0;
this._spiraling = 0;
}
else
{
var count = 0;
var fixedStepSize = 1000 * this.time.desiredFpsMult;
this._deltaTime += elapsed;
this.updatesThisFrame = Math.floor(this._deltaTime / fixedStepSize);
this.rendersThisFrame = this.forceSingleRender ? 1 : Math.min(1, this.updatesThisFrame);
while (this._deltaTime >= fixedStepSize)
{
this._deltaTime -= fixedStepSize;
this.currentUpdateID = count;
this.updateLogic(this.time.desiredFpsMult / this.time.slowMotion);
this.time.refresh();
count++;
}
if (count > this._lastCount)
{
this._spiraling++;
}
else if (count < this._lastCount)
{
this._spiraling = 0;
}
this._lastCount = count;
if (this.rendersThisFrame > 0)
{
this.updateRender();
}
}
},
/**
* Updates all logic subsystems in Phaser. Called automatically by Game.update.
*
* @method Phaser.Game#updateLogic
* @protected
* @param {number} delta - The current time step value in seconds, as determined by Game.update.
*/
updateLogic: function (delta)
{
if (!this._paused && !this.pendingStep)
{
if (this.stepping)
{
this.pendingStep = true;
}
this.time.preUpdate(delta);
this.scale.preUpdate();
this.debug.preUpdate();
this.camera.preUpdate();
this.physics.preUpdate();
this.state.preUpdate(delta);
this.plugins.preUpdate(delta);
this.stage.preUpdate();
this.state.update();
this.stage.update();
this.tweens.update();
this.sound.update();
this.input.update();
this.physics.update();
this.plugins.update();
this.stage.postUpdate();
this.state.postUpdate();
this.plugins.postUpdate();
}
else
{
// Scaling and device orientation changes are still reflected when paused.
this.scale.pauseUpdate();
this.state.pauseUpdate(delta);
this.debug.preUpdate();
this.input.pauseUpdate();
}
this.stage.updateTransform();
},
/**
* Runs the Render cycle.
* It starts by calling State.preRender. In here you can do any last minute adjustments of display objects as required.
* It then calls the renderer, which renders the entire display list, starting from the Stage object and working down.
* It then calls plugin.render on any loaded plugins, in the order in which they were enabled.
* After this State.render is called. Any rendering that happens here will take place on-top of the display list.
* Finally plugin.postRender is called on any loaded plugins, in the order in which they were enabled.
* This method is called automatically by Game.update, you don't need to call it directly.
* Should you wish to have fine-grained control over when Phaser renders then use the `Game.lockRender` boolean.
* Phaser will only render when this boolean is `false`.
*
* @method Phaser.Game#updateRender
* @protected
*/
updateRender: function ()
{
if (this.lockRender || this.renderType === Phaser.HEADLESS)
{
return;
}
this.time.preRender();
this.state.preRender();
this.renderer.render(this.stage);
this.plugins.render();
this.state.render();
this.plugins.postRender();
this.renderer.postRender();
},
/**
* Enable core game loop stepping. When enabled you must call game.step() directly (perhaps via a DOM button?)
* Calling step will advance the game loop by one frame. This is extremely useful for hard to track down errors!
*
* @method Phaser.Game#enableStep
*/
enableStep: function ()
{
this.stepping = true;
this.pendingStep = false;
this.stepCount = 0;
},
/**
* Disables core game loop stepping.
*
* @method Phaser.Game#disableStep
*/
disableStep: function ()
{
this.stepping = false;
this.pendingStep = false;
},
/**
* When stepping is enabled you must call this function directly (perhaps via a DOM button?) to advance the game loop by one frame.
* This is extremely useful to hard to track down errors! Use the internal stepCount property to monitor progress.
*
* @method Phaser.Game#step
*/
step: function ()
{
this.pendingStep = false;
this.stepCount++;
},
/**
* Nukes the entire game from orbit.
*
* Calls destroy on Game.state, Game.sound, Game.scale, Game.stage, Game.input, Game.physics and Game.plugins.
*
* Then sets all of those local handlers to null, destroys the renderer, removes the canvas from the DOM
* and resets the PIXI default renderer.
*
* To destroy the game during an update callback, set {@link #pendingDestroy} instead.
*
* @method Phaser.Game#destroy
*/
destroy: function ()
{
this.raf.stop();
this.debug.destroy();
this.state.destroy();
this.sound.destroy();
this.scale.destroy();
this.stage.destroy();
this.input.destroy();
this.physics.destroy();
this.plugins.destroy();
this.tweens.destroy();
this.debug = null;
this.state = null;
this.sound = null;
this.scale = null;
this.stage = null;
this.input = null;
this.physics = null;
this.plugins = null;
this.tweens = null;
this.cache = null;
this.load = null;
this.time = null;
this.world = null;
this.isBooted = false;
this.renderer.destroy(false);
Phaser.Canvas.removeFromDOM(this.canvas);
if (PIXI.game === this)
{
PIXI.game = null;
}
PIXI.defaultRenderer = null;
Phaser.GAMES[this.id] = null;
},
/**
* Called by the Stage visibility handler.
*
* @method Phaser.Game#gamePaused
* @param {object} event - The DOM event that caused the game to pause, if any.
* @protected
*/
gamePaused: function (event)
{
// If the game is already paused it was done via game code, so don't re-pause it
if (!this._paused)
{
this._paused = true;
this.time.gamePaused();
this.sound.gamePaused();
this.onPause.dispatch(event);
// Avoids Cordova iOS crash event: https://github.com/photonstorm/phaser/issues/1800
if (this.device.cordova && this.device.iOS)
{
this.lockRender = true;
}
}
},
/**
* Called by the Stage visibility handler.
*
* @method Phaser.Game#gameResumed
* @param {object} event - The DOM event that caused the game to pause, if any.
* @protected
*/
gameResumed: function (event)
{
// Game is paused, but wasn't paused via code, so resume it
if (this._paused && !this._codePaused)
{
this._paused = false;
this.time.gameResumed();
this.input.reset();
this.sound.gameResumed();
this.onResume.dispatch(event);
// Avoids Cordova iOS crash event: https://github.com/photonstorm/phaser/issues/1800
if (this.device.cordova && this.device.iOS)
{
this.lockRender = false;
}
}
},
/**
* Called by the Stage visibility handler.
*
* @method Phaser.Game#focusLoss
* @param {object} event - The DOM event that caused the game to pause, if any.
* @protected
*/
focusLoss: function (event)
{
this.onBlur.dispatch(event);
if (!this.stage.disableVisibilityChange)
{
this.gamePaused(event);
}
},
/**
* Called by the Stage visibility handler.
*
* @method Phaser.Game#focusGain
* @param {object} event - The DOM event that caused the game to pause, if any.
* @protected
*/
focusGain: function (event)
{
this._focusGained = true;
this.focusWindow();
this.onFocus.dispatch(event);
if (!this.stage.disableVisibilityChange)
{
this.gameResumed(event);
}
},
/**
* Try to focus the browsing context, unless prohibited by PhaserGlobal.stopFocus.
*
* @private
*/
focusWindow: function ()
{
if (window.focus)
{
if (!window.PhaserGlobal || (window.PhaserGlobal && !window.PhaserGlobal.stopFocus))
{
window.focus();
}
}
}
};
Phaser.Game.prototype.constructor = Phaser.Game;
/**
* The paused state of the Game. A paused game doesn't update any of its subsystems.
* When a game is paused the onPause event is dispatched. When it is resumed the onResume event is dispatched.
* @name Phaser.Game#paused
* @property {boolean} paused - Gets and sets the paused state of the Game.
*/
Object.defineProperty(Phaser.Game.prototype, 'paused', {
get: function ()
{
return this._paused;
},
set: function (value)
{
if (value === true)
{
if (this._paused === false)
{
this._paused = true;
if (this.sound.muteOnPause)
{
this.sound.setMute();
}
this.time.gamePaused();
this.onPause.dispatch(this);
}
this._codePaused = true;
}
else
{
if (this._paused)
{
this._paused = false;
this.input.reset();
this.sound.unsetMute();
this.time.gameResumed();
this.onResume.dispatch(this);
}
this._codePaused = false;
}
}
});
/**
*
* "Deleted code is debugged code." - Jeff Sickel
*
* ヽ(〃^▽^〃)ノ
*
*/
|
(function () {
'use strict';
describe('Firewalls List Controller Tests', function () {
// Initialize global variables
var FirewallsListController,
$scope,
$httpBackend,
$state,
Authentication,
FirewallsService,
mockFirewall;
// The $resource service augments the response object with methods for updating and deleting the resource.
// If we were to use the standard toEqual matcher, our tests would fail because the test values would not match
// the responses exactly. To solve the problem, we define a new toEqualData Jasmine matcher.
// When the toEqualData matcher compares two objects, it takes only object properties into
// account and ignores methods.
beforeEach(function () {
jasmine.addMatchers({
toEqualData: function (util, customEqualityTesters) {
return {
compare: function (actual, expected) {
return {
pass: angular.equals(actual, expected)
};
}
};
}
});
});
// Then we can start by loading the main application module
beforeEach(module(ApplicationConfiguration.applicationModuleName));
// The injector ignores leading and trailing underscores here (i.e. _$httpBackend_).
// This allows us to inject a service but then attach it to a variable
// with the same name as the service.
beforeEach(inject(function ($controller, $rootScope, _$state_, _$httpBackend_, _Authentication_, _FirewallsService_) {
// Set a new global scope
$scope = $rootScope.$new();
// Point global variables to injected services
$httpBackend = _$httpBackend_;
$state = _$state_;
Authentication = _Authentication_;
FirewallsService = _FirewallsService_;
// create mock article
mockFirewall = new FirewallsService({
_id: '525a8422f6d0f87f0e407a33',
name: 'Firewall Name'
});
// Mock logged in user
Authentication.user = {
roles: ['user']
};
// Initialize the Firewalls List controller.
FirewallsListController = $controller('FirewallsListController as vm', {
$scope: $scope
});
// Spy on state go
spyOn($state, 'go');
}));
describe('Instantiate', function () {
var mockFirewallList;
beforeEach(function () {
mockFirewallList = [mockFirewall, mockFirewall];
});
it('should send a GET request and return all Firewalls', inject(function (FirewallsService) {
// Set POST response
$httpBackend.expectGET('api/firewalls').respond(mockFirewallList);
$httpBackend.flush();
// Test form inputs are reset
expect($scope.vm.firewalls.length).toEqual(2);
expect($scope.vm.firewalls[0]).toEqual(mockFirewall);
expect($scope.vm.firewalls[1]).toEqual(mockFirewall);
}));
});
});
}());
|
'use strict'
import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from './routes'
// Container Component
import Full from '../containers/Full'
Vue.use(VueRouter)
export default new VueRouter({
mode: 'history',
base: '/admin',
linkActiveClass: 'open active',
scrollBehavior: () => ({ y: 0 }),
routes: [
{
path: '/',
redirect: '/dashboard',
name: 'Home',
component: Full,
children: routes
}
]
})
|
// Enable source map support
// import 'source-map-support/register'
// Module Dependencies
import path from 'path'
import async from 'async'
import { Utils as UtilsClass } from './satellites/utils'
// FIXME: this is a temporary workaround, we must make this more professional
const Utils = new UtilsClass()
// This stores the number of times that Stellar was started. Every time that
// Stellar restarts this is incremented by 1
let startCount = 0
/**
* Main Stellar entry point class.
*
* This makes the system bootstrap, loading and execution all satellites. Each
* initializer load new features to the engine instance or perform a set of
* instruction to accomplish a certain goal.
*/
export default class Engine {
// --------------------------------------------------------------------------- [STATIC]
/**
* Default proprieties for the satellites.
*
* @type {{load: number, start: number, stop: number}}
*/
static defaultPriorities = {
load: 100,
start: 100,
stop: 100
}
/**
* Normalize satellite priorities.
*
* @param satellite Satellite instance to be normalized.
*/
static normalizeInitializerPriority (satellite) {
satellite.loadPriority = satellite.loadPriority || Engine.defaultPriorities.load
satellite.startPriority = satellite.startPriority || Engine.defaultPriorities.start
satellite.stopPriority = satellite.stopPriority || Engine.defaultPriorities.stop
}
/**
* Order satellites array by their priority.
*
* @param collection Satellites array to be ordered.
* @returns {Array} New ordered array.
*/
static flattenOrderedInitializer (collection) {
let keys = []
let output = []
// get keys from the collection
for (var key in collection) { keys.push(parseInt(key)) }
// sort the keys in ascendant way
keys.sort((a, b) => a - b)
// iterate the ordered keys and create the new ordered object to be
// outputted
keys.forEach(key => collection[ key ].forEach(d => output.push(d)))
// return the new ordered object
return output
}
/**
* Print fatal error on the console and exit from the engine execution.
*
* @private
* @param api API instance.
* @param errors String or array with the fatal error(s).
* @param type String with the error type.
*/
static fatalError (api, errors, type) {
// if errors variables if not defined return
if (!errors) { return }
// ensure the errors variable is an Array
if (!Array.isArray(errors)) { errors = [ errors ] }
// log an emergency message
console.log()
api.log(`Error with satellite step: ${type}`, 'emerg')
// log all the errors
errors.forEach(err => api.log(err, 'emerg'))
// finish the process execution
api.commands.stop.call(api, () => { process.exit(1) })
}
// --------------------------------------------------------------------------- [Class]
/**
* API object.
*
* This object will be shared across all the platform, it's here the
* satellites will load logic and the developers access the functions.
*
* @type {{}}
*/
api = {
bootTime: null,
status: 'stopped',
commands: {
initialize: null,
start: null,
stop: null,
restart: null
},
_self: null,
log: null,
scope: {}
}
/**
* List with all satellites.
*
* @type {{}}
*/
satellites = {}
/**
* Array with the initial satellites.
*
* @type {Array}
*/
initialSatellites = []
/**
* Array with the load satellites.
*
* This array contains all the satellites who has a load method.
*
* @type {Array}
*/
loadSatellites = []
/**
* Array with the start satellites.
*
* This array contains all the satellites who has a start method.
*
* @type {Array}
*/
startSatellites = []
/**
* Array with the stop satellites.
*
* This array contains all the satellites who has a stop method.
*
* @type {Array}
*/
stopSatellites = []
/**
* Create a new instance of the Engine.
*
* @param scope Initial scope
*/
constructor (scope) {
let self = this
// save current execution scope
self.api.scope = scope
// define args if them are not already defined
if (!self.api.scope.args) { self.api.scope.args = {} }
// save the engine reference for external calls
self.api._self = self
// define a dummy logger
//
// this only should print error, emergency levels
self.api.log = (msg, level = 'info') => {
// if we are on test environment don't use the console
if (process.env.NODE_ENV === 'test') { return }
if (level === 'emergency' || level === 'error') {
return console.error(`\x1b[31m[-] ${msg}\x1b[37m`)
} else if (level === 'info') {
return console.info(`[!] ${msg}`)
} else if (level !== 'debug') {
console.log(`[d] ${msg}`)
}
}
// define the available engine commands
self.api.commands = {
initialize: self.initialize,
start: self.start,
stop: self.stop,
restart: self.restart
}
}
// --------------------------------------------------------------------------- [State Manager Functions]
initialize (callback = null) {
let self = this
// if this function has called outside of the Engine the 'this'
// variable has an invalid reference
if (this._self) { self = this._self }
self.api._self = self
// print current execution path
self.api.log(`Current universe "${self.api.scope.rootPath}"`, 'info')
// execute the stage 0
this.stage0(callback)
}
/**
* Start engine execution.
*
* @param callback This function is called when the Engine finish their startup.
*/
start (callback = null) {
let self = this
// if this function has called outside of the Engine the 'this'
// variable has an invalid reference
if (this._self) { self = this._self }
self.api._self = self
// reset start counter
startCount = 0
// check if the engine was already initialized
if (self.api.status !== 'init_stage0') {
return self.initialize((error, api) => {
// if an error occurs we stop here
if (error) { return callback(error, api) }
// start stage1 loading method
self.stage1(callback)
})
}
// start stage1 loading method
return self.stage1(callback)
}
/**
* Stop the Engine execution.
*
* This method try shutdown the engine in a non violent way, this
* starts to execute all the stop method on the supported satellites.
*
* @param callback Callback function to be executed at the stop end execution.
*/
stop (callback = null) {
let self = this
// if this function has called outside of the Engine the 'this'
// variable has an invalid reference
if (this._self) { self = this._self }
if (self.api.status === 'running') {
// stop Engine
self.api.status = 'shutting_down'
// log a shutting down message
self.api.log('Shutting down open servers and stopping task processing', 'alert')
// if this is the second shutdown we need remove the `finalStopInitializer` callback
if (self.stopSatellites[ (self.stopSatellites.length - 1) ].name === 'finalStopInitializer') {
self.stopSatellites.pop()
}
// add the final callback
self.stopSatellites.push(function finalStopInitializer (next) {
// stop watch for file changes
self.api.configs.unwatchAllFiles()
// clear cluster PIDs
self.api.pids.clearPidFile()
// log a shutdown message
self.api.log('Stellar has been stopped', 'alert')
self.api.log('***', 'debug')
// mark server as stopped
self.api.status = 'stopped'
// execute the callback on the next tick
process.nextTick(() => {
if (callback !== null) { callback(null, self.api) }
})
// async callback
next()
})
// iterate all satellites and stop them
async.series(self.stopSatellites, errors => Engine.fatalError(self.api, errors, 'stop'))
} else if (self.api.status === 'shutting_down') {
// double sigterm; ignore it
} else {
// we can shutdown the Engine if it is not running
self.api.log('Cannot shutdown Stellar, not running', 'error')
// exists a callback?
if (callback !== null) { callback(null, self.api) }
}
}
/**
* Restart the Stellar Engine.
*
* This execute a stop action and execute the stage2 load actions.
*
* @param callback Callback function to be executed at the restart end.s
*/
restart (callback = null) {
let self = this
// if this function has called outside of the Engine the 'this'
// variable has an invalid reference
if (this._self) { self = this._self }
if (self.api.status === 'running') {
// stop the engine
self.stop(err => {
// log error if present
if (err) { self.api.log(err, 'error') }
// start the engine again
self.stage2(function (err) {
if (err) { self.api.log(err, 'error') }
// log a restart message
self.api.log('*** Stellar Restarted ***', 'info')
// exists a callback
if (callback !== null) { callback(null, self.api) }
})
})
} else {
self.stage2(err => {
// log any encountered error
if (err) { self.api.log(err, 'error') }
// log a restart message
self.api.log('*** Stellar Restarted ***', 'info')
// exists a callback
if (callback !== null) { callback(null, self.api) }
})
}
}
// --------------------------------------------------------------------------- [States Functions]
/**
* First startup stage.
*
* Steps:
* - executes the initial satellites;
* - call stage1
*
* @param callback This callback only are executed at the end of stage2.
*/
stage0 (callback = null) {
// set the state
this.api.status = 'init_stage0'
// we need to load the config first
let initialSatellites = [
path.resolve(`${__dirname}/satellites/utils.js`),
path.resolve(`${__dirname}/satellites/config.js`)
]
initialSatellites.forEach(file => {
// get full file name
let filename = file.replace(/^.*[\\\/]/, '')
// get the first part of the file name
let initializer = filename.split('.')[ 0 ]
// get the initializer
const Satellite = require(file).default
this.satellites[ initializer ] = new Satellite()
// add it to array
this.initialSatellites.push(next => this.satellites[ initializer ].load(this.api, next))
})
// execute stage0 satellites in series
async.series(this.initialSatellites, error => {
// execute the callback
callback(error, this.api)
// if an error occurs show
if (error) { Engine.fatalError(this.api, error, 'stage0') }
})
}
/**
* Second startup stage.
*
* Steps:
* - load all satellites into memory;
* - load satellites;
* - mark Engine like initialized;
* - call stage2.
*
* @param callback This callback only is executed at the stage2 end.
*/
stage1 (callback = null) {
// put the status in the next stage
this.api.status = 'init_stage1'
// ranked object for all stages
let loadSatellitesRankings = {}
let startSatellitesRankings = {}
let stopSatellitesRankings = {}
// reset satellites arrays
this.satellites = {}
// function to load the satellites in the right place
let loadSatellitesInPlace = satellitesFiles => {
// iterate all files
for (let key in satellitesFiles) {
let f = satellitesFiles[ key ]
// get satellite normalized file name and
let file = path.normalize(f)
let initializer = path.basename(f).split('.')[ 0 ]
let ext = file.split('.').pop()
// only load files with the `.js` extension
if (ext !== 'js') { continue }
// get initializer module and instantiate it
const Satellite = require(file).default
this.satellites[ initializer ] = new Satellite()
// initializer load function
let loadFunction = next => {
// check if the initializer have a load function
if (typeof this.satellites[ initializer ].load === 'function') {
this.api.log(` > load: ${initializer}`, 'debug')
// call `load` property
this.satellites[ initializer ].load(this.api, err => {
if (!err) { this.api.log(` loaded: ${initializer}`, 'debug') }
next(err)
})
} else {
next()
}
}
// initializer start function
let startFunction = next => {
// check if the initializer have a start function
if (typeof this.satellites[ initializer ].start === 'function') {
this.api.log(` > start: ${initializer}`, 'debug')
// execute start routine
this.satellites[ initializer ].start(this.api, err => {
if (!err) { this.api.log(` started: ${initializer}`, 'debug') }
next(err)
})
} else {
next()
}
}
// initializer stop function
let stopFunction = next => {
if (typeof this.satellites[ initializer ].stop === 'function') {
this.api.log(` > stop: ${initializer}`, 'debug')
this.satellites[ initializer ].stop(this.api, err => {
if (!err) { this.api.log(` stopped: ${initializer}`, 'debug') }
next(err)
})
} else {
next()
}
}
// normalize satellite priorities
Engine.normalizeInitializerPriority(this.satellites[ initializer ])
loadSatellitesRankings[ this.satellites[ initializer ].loadPriority ] = loadSatellitesRankings[ this.satellites[ initializer ].loadPriority ] || []
startSatellitesRankings[ this.satellites[ initializer ].startPriority ] = startSatellitesRankings[ this.satellites[ initializer ].startPriority ] || []
stopSatellitesRankings[ this.satellites[ initializer ].stopPriority ] = stopSatellitesRankings[ this.satellites[ initializer ].stopPriority ] || []
// push loader state function to ranked arrays
loadSatellitesRankings[ this.satellites[ initializer ].loadPriority ].push(loadFunction)
startSatellitesRankings[ this.satellites[ initializer ].startPriority ].push(startFunction)
stopSatellitesRankings[ this.satellites[ initializer ].stopPriority ].push(stopFunction)
}
}
// get an array with all satellites
loadSatellitesInPlace(Utils.getFiles(`${__dirname}/satellites`))
// load satellites from all the active modules
this.api.config.modules.forEach(moduleName => {
// build the full path to the satellites folder
let moduleSatellitePaths = `${this.api.scope.rootPath}/modules/${moduleName}/satellites`
// check if the folder exists
if (Utils.directoryExists(moduleSatellitePaths)) { loadSatellitesInPlace(Utils.getFiles(moduleSatellitePaths)) }
})
// organize final array to match the satellites priorities
this.loadSatellites = Engine.flattenOrderedInitializer(loadSatellitesRankings)
this.startSatellites = Engine.flattenOrderedInitializer(startSatellitesRankings)
this.stopSatellites = Engine.flattenOrderedInitializer(stopSatellitesRankings)
// on the end of loading all satellites set engine like initialized
this.loadSatellites.push(() => { this.stage2(callback) })
// start initialization process
async.series(this.loadSatellites, errors => Engine.fatalError(this.api, errors, 'stage1'))
}
/**
* Third startup stage.
*
* Steps:
* - start satellites;
* - mark Engine as running.
*
* @param callback
*/
stage2 (callback = null) {
// put the engine in the stage2 state
this.api.status = 'init_stage2'
if (startCount === 0) {
this.startSatellites.push(next => {
// set the state
this.api.status = 'running'
this.api.bootTime = new Date().getTime()
if (startCount === 0) {
this.api.log('** Server Started @ ' + new Date() + ' ***', 'alert')
} else {
this.api.log('** Server Restarted @ ' + new Date() + ' ***', 'alert')
}
// increment the number of starts
startCount++
// call the callback if it's present
if (callback !== null) { callback(null, this.api) }
next()
})
}
// start all initializers
async.series(this.startSatellites, err => Engine.fatalError(this.api, err, 'stage2'))
}
}
|
var expect = require("expect.js");
var properties = require(__filename.replace(/test/, "src").replace(/-test.js$/, ".js"));
describe("properties", function () {
it("getProperties should be empty for non-existing properties", function () {
var theProperties = properties.getProperties("NonExisting.properties");
expect(theProperties).to.be.empty();
});
it("getProperties should not be empty for non-existing properties", function () {
var theProperties = properties.getProperties(__dirname + "/testFiles/01_.properties");
expect(theProperties).not.to.be.empty();
});
it("getProperties should have expected value(s)", function () {
var theProperties = properties.getProperties(__dirname + "/testFiles/01_.properties");
expect(theProperties.foo).to.be("foo");
});
});
|
let db;
let idb_helper;
module.exports = idb_helper = {
set_graphene_db: database => {
db = database;
},
trx_readwrite: object_stores => {
return db.transaction(
[object_stores], "readwrite"
);
},
on_request_end: (request) => {
//return request => {
return new Promise((resolve, reject) => {
request.onsuccess = new ChainEvent(
request.onsuccess, resolve, request).event;
request.onerror = new ChainEvent(
request.onerror, reject, request).event;
});
//}(request)
},
on_transaction_end: (transaction) => {
return new Promise((resolve, reject) => {
transaction.oncomplete = new ChainEvent(
transaction.oncomplete, resolve).event;
transaction.onabort = new ChainEvent(
transaction.onabort, reject).event;
});
},
/** Chain an add event. Provide the @param store and @param object and
this method gives you convenient hooks into the database events.
@param event_callback (within active transaction)
@return Promise (resolves or rejects outside of the transaction)
*/
add: (store, object, event_callback) => {
return function(object, event_callback) {
let request = store.add(object);
let event_promise = null;
if(event_callback)
request.onsuccess = new ChainEvent(
request.onsuccess, event => {
event_promise = event_callback(event);
}).event;
let request_promise = idb_helper.on_request_end(request).then( event => {
//DEBUG console.log('... object',object,'result',event.target.result,'event',event)
if ( event.target.result != void 0) {
//todo does event provide the keyPath name? (instead of id)
object.id = event.target.result;
}
return [ object, event ];
});
if(event_promise)
return Promise.all([event_promise, request_promise]);
return request_promise;
}(object, event_callback); //copy let references for callbacks
},
/** callback may return <b>false</b> to indicate that iteration should stop */
cursor: (store_name, callback, transaction) => {
return new Promise((resolve, reject)=>{
if( ! transaction) {
transaction = db.transaction(
[store_name], "readonly"
);
transaction.onerror = error => {
console.error("ERROR idb_helper.cursor transaction", error);
reject(error);
};
}
let store = transaction.objectStore(store_name);
let request = store.openCursor();
request.onsuccess = e => {
let cursor = e.target.result;
let ret = callback(cursor, e);
if(ret === false) resolve();
if(!cursor) resolve(ret);
};
request.onerror = (e) => {
let error = {
error: e.target.error.message,
data: e
};
console.log("ERROR idb_helper.cursor request", error);
reject(error);
};
}).then();
},
autoIncrement_unique: (db, table_name, unique_index) => {
return db.createObjectStore(
table_name, { keyPath: "id", autoIncrement: true }
).createIndex(
"by_"+unique_index, unique_index, { unique: true }
);
}
};
class ChainEvent {
constructor(existing_on_event, callback, request) {
this.event = (event)=> {
if(event.target.error)
console.error("---- transaction error ---->", event.target.error);
//event.request = request
callback(event);
if(existing_on_event) existing_on_event(event);
};
}
}
|
define(["knockout"], function(ko){
var vm = function(){
this.testBind = ko.observable('2016-04-08');
this.show = ko.pureComputed(function(){
return 'You just picked : '+ this.testBind();
});
};
return vm;
}) |
var classHelix_1_1Logic_1_1admin_1_1Row =
[
[ "Row", "classHelix_1_1Logic_1_1admin_1_1Row.html#a5cca50abc389396e26ec68cbd3fb6596", null ],
[ "Row", "classHelix_1_1Logic_1_1admin_1_1Row.html#a9dbe8548daa0a4887688199e00c25ebe", null ],
[ "~Row", "classHelix_1_1Logic_1_1admin_1_1Row.html#a8cc0869c91dc94ee595069309ba15690", null ],
[ "Row", "classHelix_1_1Logic_1_1admin_1_1Row.html#ab03288f17c220e20c93ad9c0d09061ac", null ],
[ "checkSize", "classHelix_1_1Logic_1_1admin_1_1Row.html#a48bcdc5b9f9538ed41e080803d663678", null ],
[ "createXmlChildren", "classHelix_1_1Logic_1_1admin_1_1Row.html#a214f15c6d3d9f8fafb0e0c06eb11b055", null ],
[ "createXmlDoc", "classHelix_1_1Logic_1_1admin_1_1Row.html#a94214dcf9a6b54b4a6e9e29e22c7fdaf", null ],
[ "createXmlNode", "classHelix_1_1Logic_1_1admin_1_1Row.html#a6574128e020e000ed6d8f6237170b6ab", null ],
[ "deleteVector", "classHelix_1_1Logic_1_1admin_1_1Row.html#a0315f22e3e824261c07faa598b2924cb", null ],
[ "init", "classHelix_1_1Logic_1_1admin_1_1Row.html#a2b565af0d1dde980ea1554a9f2f701e2", null ],
[ "Name", "classHelix_1_1Logic_1_1admin_1_1Row.html#a4d274004c656534d5e53e2e71aa56ced", null ],
[ "operator=", "classHelix_1_1Logic_1_1admin_1_1Row.html#a87ba0481b0ca4da736c29902ae99ae16", null ],
[ "readXmlChildren", "classHelix_1_1Logic_1_1admin_1_1Row.html#af67bc7d9b68ddddbaa4c50877307a3eb", null ],
[ "readXmlNode", "classHelix_1_1Logic_1_1admin_1_1Row.html#ad725b5dab419e46fa1756db5723fe056", null ],
[ "unused", "classHelix_1_1Logic_1_1admin_1_1Row.html#aea46573efcd2acb8be86d94f3eeefd75", null ],
[ "unused", "classHelix_1_1Logic_1_1admin_1_1Row.html#a03fa2b5f39fc6e782c6d0bb50ff2fc1c", null ],
[ "unused_getSQL", "classHelix_1_1Logic_1_1admin_1_1Row.html#aa184ff4c1a1e4f0c5d60a423d82acda7", null ],
[ "unused_prepSQL", "classHelix_1_1Logic_1_1admin_1_1Row.html#a68b113538ca9e7713c8db5079acc469d", null ],
[ "Cols", "classHelix_1_1Logic_1_1admin_1_1Row.html#ac018a27345b236d23211f5a2d903b21d", null ],
[ "idx", "classHelix_1_1Logic_1_1admin_1_1Row.html#aa01047fcfb3bed97affba31071c65054", null ]
]; |
version https://git-lfs.github.com/spec/v1
oid sha256:136260763fa9e047fbd5342fdf7ea53cd2ef2b4e3fe7f26cd65770dd25614bec
size 29831
|
// Load modules
var Crypto = require('crypto');
var Url = require('url');
var Utils = require('./utils');
// Declare internals
var internals = {};
// MAC normalization format version
exports.headerVersion = '1'; // Prevent comparison of mac values generated with different normalized string formats
// Supported HMAC algorithms
exports.algorithms = ['sha1', 'sha256'];
// Calculate the request MAC
/*
type: 'header', // 'header', 'bewit', 'response'
credentials: {
key: 'aoijedoaijsdlaksjdl',
algorithm: 'sha256' // 'sha1', 'sha256'
},
options: {
method: 'GET',
resource: '/resource?a=1&b=2',
host: 'example.com',
port: 8080,
ts: 1357718381034,
nonce: 'd3d345f',
hash: 'U4MKKSmiVxk37JCCrAVIjV/OhB3y+NdwoCr6RShbVkE=',
ext: 'app-specific-data',
app: 'hf48hd83qwkj', // Application id (Oz)
dlg: 'd8djwekds9cj' // Delegated by application id (Oz), requires options.app
}
*/
exports.calculateMac = function (type, credentials, options) {
var normalized = exports.generateNormalizedString(type, options);
var hmac = Crypto.createHmac(credentials.algorithm, credentials.key).update(normalized);
var digest = hmac.digest('base64');
return digest;
};
exports.generateNormalizedString = function (type, options) {
var normalized = 'hawk.' + exports.headerVersion + '.' + type + '\n' +
options.ts + '\n' +
options.nonce + '\n' +
options.method.toUpperCase() + '\n' +
options.resource + '\n' +
options.host.toLowerCase() + '\n' +
options.port + '\n' +
(options.hash || '') + '\n';
if (options.ext) {
normalized += options.ext.replace('\\', '\\\\').replace('\n', '\\n');
}
normalized += '\n';
if (options.app) {
normalized += options.app + '\n' +
(options.dlg || '') + '\n';
}
return normalized;
};
exports.calculatePayloadHash = function (payload, algorithm, contentType) {
var hash = exports.initializePayloadHash(algorithm, contentType);
hash.update(payload || '');
return exports.finalizePayloadHash(hash);
};
exports.initializePayloadHash = function (algorithm, contentType) {
var hash = Crypto.createHash(algorithm);
hash.update('hawk.' + exports.headerVersion + '.payload\n');
hash.update(Utils.parseContentType(contentType) + '\n');
return hash;
};
exports.finalizePayloadHash = function (hash) {
hash.update('\n');
return hash.digest('base64');
};
exports.calculateTsMac = function (ts, credentials) {
var hmac = Crypto.createHmac(credentials.algorithm, credentials.key);
hmac.update('hawk.' + exports.headerVersion + '.ts\n' + ts + '\n');
return hmac.digest('base64');
};
|
// Ionic Starter App
// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
// 'starter.services' is found in services.js
// 'starter.controllers' is found in controllers.js
angular.module('starter', ['ionic', 'ngResource','starter.controllers', 'starter.services','starter.filters' ,'ionic-datepicker'])
.run(function ($ionicPlatform) {
$ionicPlatform.ready(function () {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
});
})
.config(function ($stateProvider, $urlRouterProvider, $ionicConfigProvider) {
$ionicConfigProvider.platform.ios.tabs.style('standard');
$ionicConfigProvider.platform.ios.tabs.position('bottom');
$ionicConfigProvider.platform.android.tabs.style('standard');
$ionicConfigProvider.platform.android.tabs.position('bottom');
$ionicConfigProvider.platform.ios.navBar.alignTitle('center');
$ionicConfigProvider.platform.android.navBar.alignTitle('center');
$ionicConfigProvider.platform.ios.backButton.previousTitleText('').icon('ion-ios-arrow-thin-left');
$ionicConfigProvider.platform.android.backButton.previousTitleText('').icon('ion-android-arrow-back');
$ionicConfigProvider.platform.ios.views.transition('ios');
$ionicConfigProvider.platform.android.views.transition('android');
// Ionic uses AngularUI Router which uses the concept of states
// Learn more here: https://github.com/angular-ui/ui-router
// Set up the various states which the app can be in.
// Each state's controller can be found in controllers.js
$stateProvider
// setup an abstract state for the tabs directive
.state('tab', {
url: '/tab',
abstract: true,
templateUrl: 'templates/tabs.html'
})
// Each tab has its own nav history stack:
.state('tab.dash', {
url: '/dash',
views: {
'tab-dash': {
templateUrl: 'templates/tab-dash.html',
controller: 'DashCtrl'
}
}
})
.state('tab.bills', {
url: '/bills',
views: {
'tab-bills': {
templateUrl: 'templates/tab-bills.html',
controller: 'BillsCtrl'
}
}
})
.state('tab.bill-detail', {
url: '/bills/:billId',
views: {
'tab-bills': {
templateUrl: 'templates/bill-detail.html',
controller: 'BillDetailCtrl'
}
}
})
.state('tab.account', {
url: '/account',
views: {
'tab-account': {
templateUrl: 'templates/tab-account.html',
controller: 'AccountCtrl'
}
}
})
.state('login', {
url: '/login',
templateUrl: 'templates/login.html',
controller: 'LoginCtrl'
});
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/tab/dash');
})
.config(
function ($httpProvider) {
// Use x-www-form-urlencoded Content-Type
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
/**
* The workhorse; converts an object to x-www-form-urlencoded serialization.
* @param {Object} obj
* @return {String}
*/
var param = function (obj) {
var query = '', name, value, fullSubName, subName, subValue, innerObj, i;
for (name in obj) {
value = obj[name];
if (value instanceof Array) {
for (i = 0; i < value.length; ++i) {
subValue = value[i];
fullSubName = name + '[' + i + ']';
innerObj = {};
innerObj[fullSubName] = subValue;
query += param(innerObj) + '&';
}
}
else if (value instanceof Object) {
for (subName in value) {
subValue = value[subName];
fullSubName = name + '[' + subName + ']';
innerObj = {};
innerObj[fullSubName] = subValue;
query += param(innerObj) + '&';
}
}
else if (value !== undefined && value !== null)
query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
}
return query.length ? query.substr(0, query.length - 1) : query;
};
// Override $http service's default transformRequest
$httpProvider.defaults.transformRequest = [function (data) {
return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data;
}];
});
|
{
data: (function() {
var ro = {};
ro.partname = 'Boozembly 2016 - intro';
ro.prewarm = true;
ro.partlength = 13965;
ro.cameras = {
'makkaracam': new THREE.PerspectiveCamera(45, global_engine.getAspectRatio(), 0.1, 8000),
'logocam': new THREE.PerspectiveCamera(45, global_engine.getAspectRatio(), 0.1, 10000)
};
ro.scenes = {};
ro.lights = {};
ro.objects = {};
ro.effects = {};
ro.composers = {};
ro.passes = {};
ro.rendertargets = {};
ro.renderpasses = {};
ro.scenes['makkara'] = (function(obj) {
var scene = new THREE.Scene();
var makkara_data = [" -- ---- -- ---- ",
" -- ---- -- ---- ",
"-- -- -- -- --- -- --",
"-- -- -- -- --- -- --",
" -- -- -- -- -- ",
" -- -- -- -- -- ",
" -- -- -- -- -- ",
" ---- -- -- -- ------",
" ---- -- -- -- ------",
"-- -- -- -- -- --",
"-- -- -- -- -- --",
"-- -- -- -- -- --",
"-- -- -- -- -- --",
"------ ---- ---- ---- ",
"------ ---- ---- ---- "];
var makkara_materials = [];
var makkara_texture_images = [
{map: image_makkaratexture.src, bump: image_makkarabump.src},
{map: image_makkaratexture3.src, bump: image_makkarabump3.src},
{map: image_makkaratexture4.src, bump: image_makkarabump4.src}
];
for (var i=0; i<makkara_texture_images.length; i++) {
var map = THREE.ImageUtils.loadTexture( makkara_texture_images[i].map );
map.flipY = false;
var bump = THREE.ImageUtils.loadTexture( makkara_texture_images[i].bump );
bump.flipY = false;
makkara_materials.push(
new THREE.MeshPhongMaterial({
map: map,
bumpMap: bump,
bumpScale: 2,
transparent: false
})
);
}
obj.objects['makkarat'] = [];
var half_x = makkara_data[i].length / 2;
var half_y = makkara_data.length / 2;
var buffermakkara = new THREE.BufferGeometry().fromGeometry(object_makkara2.children[1].geometry);
for (var i=0; i<makkara_data.length; i++) {
for (var j=0; j<makkara_data[i].length; j++) {
if (makkara_data[i].charAt(j) == '-') {
var mesh = new THREE.Mesh(buffermakkara, makkara_materials[0]);
var target_position = { x: (j-half_x) * 80, y: -(i-half_y) * 30, z: -500 };
var start_position = {x: target_position.x, y: target_position.y, z: 1100 };
mesh.position.set(start_position.x, start_position.y, start_position.z);
mesh.target_position = target_position;
mesh.start_position = start_position;
mesh.original_index = i * makkara_data.length + j;
mesh.original_index_y = i;
mesh.original_index_x = j;
mesh.rotation.x = Math.random() * Math.PI * 180 * 2;
mesh.scale.x = 1;
mesh.scale.y = 1;
mesh.scale.z = 1;
scene.add(mesh);
obj.objects['makkarat'].push(mesh);
}
}
}
obj.objects['makkarat'] = shuffle(obj.objects['makkarat']);
var light = new THREE.SpotLight(0xFFFFFF, 0.1);
light.position.set(200, 200, 1500);
scene.add(light);
obj.lights['makkaraspot1'] = light;
light = new THREE.SpotLight(0xFFFFFF, 0.1);
light.position.set(-200, -200, 1500);
scene.add(light);
obj.lights['makkaraspot2'] = light;
light = new THREE.SpotLight(0xFFFFFF, 0.1);
light.intensity = 1.2;
light.position.set(10, 10, 1500);
scene.add(light);
obj.lights['makkaraspot3'] = light;
scene.add(obj.cameras['makkaracam']);
obj.cameras['makkaracam'].position.z = 1000;
var rendertarget = new THREE.WebGLRenderTarget( global_engine.getWidth(), global_engine.getHeight(),
{ minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBAFormat, alpha: true, autoClear: false});
var composer = new THREE.EffectComposer(global_engine.renderers['main'], rendertarget);
var renderpass = new THREE.RenderPass(scene, obj.cameras['makkaracam']);
renderpass.renderToScreen = false;
composer.addPass(renderpass);
composer.clear = false;
obj.composers['makkarat'] = composer;
obj.rendertargets['makkarat'] = rendertarget;
return scene;
}(ro));
ro.scenes['logo'] = (function(obj) {
var scene = new THREE.Scene();
var geometry = new THREE.PlaneBufferGeometry(1920, 1080, 1, 1);
var material_boozembly = new THREE.MeshPhongMaterial( { map: THREE.ImageUtils.loadTexture( image_boozembly.src ), transparent: true } );
var mesh_boozembly = new THREE.Mesh(geometry, material_boozembly);
mesh_boozembly.position.x = 0;
mesh_boozembly.position.y = 0;
mesh_boozembly.position.z = 0;
scene.add(mesh_boozembly);
obj.objects['mesh_boozembly'] = mesh_boozembly;
var material_disorganizing = new THREE.MeshPhongMaterial( { map: THREE.ImageUtils.loadTexture( image_disorganizing.src ), transparent: true } );
var mesh_disorganizing = new THREE.Mesh(geometry, material_disorganizing);
mesh_disorganizing.position.x = 0;
mesh_disorganizing.position.y = 0;
mesh_disorganizing.position.z = 0;
scene.add(mesh_disorganizing);
obj.objects['mesh_disorganizing'] = mesh_disorganizing;
for (var i=0; i<3; i++) {
var light = new THREE.SpotLight(0xffffff);
light.intensity = 0.5;
light.penumbra = 1;
light.decay = 2;
light.angle = Math.PI / 3 / 2;
light.position.set(0, 0, 0);
light.name = 'logospot' + i;
light.target.position.set(0, 0, 0);
scene.add(light);
scene.add(light.target);
obj.lights[light.name] = light;
}
var directionallight = new THREE.DirectionalLight( 0xffffff, 0.05 );
directionallight.position.set( 0, 0, 1 );
scene.add( directionallight );
obj.lights['logodirectional'] = directionallight;
scene.add(obj.cameras['logocam']);
obj.cameras['logocam'].position.z = 1200;
var rendertarget = new THREE.WebGLRenderTarget( global_engine.getWidth(), global_engine.getHeight(),
{ minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBAFormat, alpha: true, autoClear: false});
var composer = new THREE.EffectComposer(global_engine.renderers['main'], rendertarget);
var renderpass = new THREE.RenderPass(scene, obj.cameras['logocam']);
renderpass.renderToScreen = false;
composer.addPass(renderpass);
composer.clear = false;
obj.composers['boozembly'] = composer;
obj.rendertargets['boozembly'] = rendertarget;
return scene;
}(ro));
ro.scenes['composer'] = (function(obj) {
var scene = new THREE.Scene();
var rendertarget = new THREE.WebGLRenderTarget(global_engine.getWidth(), global_engine.getHeight(),
{ minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBAFormat, alpha: true, autoClear: false }
);
var composer = new THREE.EffectComposer(global_engine.renderers['main'], rendertarget);
var combinerpass = new THREE.ShaderPass(THREE.CopyAlphaTexture);
combinerpass.uniforms['tDiffuse1'].value = obj.composers['makkarat'].renderTarget2.texture;
combinerpass.uniforms['tDiffuse2'].value = obj.composers['boozembly'].renderTarget2.texture;
combinerpass.renderToScreen = true;
composer.addPass(combinerpass);
obj.rendertargets['maintarget'] = rendertarget;
obj.composers['composer'] = composer;
return scene;
}(ro));
ro.functions = {
updateSausages: function(pd, pt, gt) {
var lights = pd.data.lights;
var makkarat = pd.data.objects['makkarat'];
var speed = 65;
for (var i=0; i<makkarat.length; i++) {
makkarat[i].rotation.x = (pt + makkarat[i].original_index * 10) / 600;
makkarat[i].rotation.z = Math.sin((pt + makkarat[i].original_index * 10) / 200) * Math.PI / 4;
if (pt > i * speed) {
makkarat[i].position.z = makkarat[i].target_position.z;
} else if ((pt + speed) > i * speed) {
var smoother = smootherstep(0, speed, (i * speed - pt)) * 1600;
makkarat[i].position.z = -500 + smoother;
} else {
makkarat[i].position.z = makkarat[i].start_position.z;
}
}
},
updateBoozembly: function(pd, pt, gt) {
var objects = pd.data.objects;
var lights = pd.data.lights;
var cameras = pd.data.cameras;
objects['mesh_boozembly'].position.z = pt / 1000 * 20 - 200;
objects['mesh_disorganizing'].position.z = pt / 1000 * 40 - 400;
objects['mesh_disorganizing'].position.y = pt / 1000 * 5;
var foo = 64 / 14;
for (var i=0; i<3; i++) {
lights['logospot' + i].target.position.x = Math.floor((pt / 1000 * foo / 8 + i) % 4) * 400 - 800;
lights['logospot' + i].target.position.y = Math.sin(pt / 1000 * foo / 8 * Math.PI + (i * Math.PI)) * 350;
lights['logospot' + i].position.x = lights['logospot0'].target.position.x;
lights['logospot' + i].position.y = -lights['logospot0'].target.position.y;
lights['logospot' + i].position.z = 400;
lights['logospot' + i].intensity = Math.min(Math.max(0.05, pt/13000), 0.7);
}
lights['logodirectional'].intensity = 0.05;
cameras['logocam'].position.x = -Math.sin(pt/1000 / 14 * Math.PI * 2) * 500;
var cutoff = 13000;
var remain = pd.data.partlength - cutoff;
if (pt > cutoff) {
var z = pt - cutoff;
cameras['logocam'].position.z = 1200 - (z / remain) * 200;
lights['logodirectional'].intensity = (z / remain);
objects['mesh_boozembly'].material.opacity = 1 - (z / remain);
objects['mesh_disorganizing'].material.opacity = 1 - (z / remain);
l(z/remain);
} else {
cameras['logocam'].position.z = 1200;
lights['logodirectional'].intensity = 0.05;
objects['mesh_boozembly'].material.opacity = 1;
objects['mesh_disorganizing'].material.opacity = 1;
}
}
}
ro.player = function(partdata, parttick, tick) {
this.functions.updateBoozembly(partdata, parttick, tick);
this.functions.updateSausages(partdata, parttick, tick);
var dt = global_engine.clock.getDelta();
this.composers['makkarat'].render(dt);
this.composers['boozembly'].render(dt);
this.composers['composer'].render(dt);
}
return ro;
}())
}
|
import request from 'request'
import { remote } from '../../../src'
import { ELEMENT_KEY } from '../../../src/constants'
import * as utils from '../../../src/utils'
describe('selectByIndex test', () => {
const getElementFromResponseSpy = jest.spyOn(utils, 'getElementFromResponse')
let browser
let elem
beforeEach(async () => {
browser = await remote({
baseUrl: 'http://foobar.com',
capabilities: {
browserName: 'foobar'
}
})
elem = await browser.$('some-elem-123')
})
afterEach(() => {
request.mockClear()
})
it('should select by index', async () => {
await elem.selectByIndex(1)
expect(request.mock.calls[1][0].uri.path).toBe('/wd/hub/session/foobar-123/element')
expect(request.mock.calls[2][0].uri.path).toBe('/wd/hub/session/foobar-123/element/some-elem-123/elements')
expect(request.mock.calls[3][0].uri.path).toBe('/wd/hub/session/foobar-123/element/some-elem-456/click')
expect(getElementFromResponseSpy).toBeCalledWith({
[ELEMENT_KEY]: 'some-elem-456'
})
})
it('should throw an error when index < 0', async () => {
expect.hasAssertions()
try {
await elem.selectByIndex(-2)
} catch (e) {
expect(e.toString()).toBe('Error: Index needs to be 0 or any other positive number')
}
})
})
|
Template.registerHelper('tweetToUser', function(twitterScreenName){
var urls = [
"text=Hello @"+twitterScreenName+" ! We shared an orbit on",
"url=http://www.friendsinspace.org",
"hashtags=friendsinspace"
];
return "https://twitter.com/intent/tweet?"+urls.join("&")+"&";
});
Template.registerHelper('hasTwitterAccount', function(profile){
return profile.service == 'twitter';
});
Template.registerHelper('hasGooglePlusAccount', function(profile){
return profile.service == 'google';
});
Template.registerHelper('hasFacebookAccount', function(profile){
return profile.service == 'facebook';
});
Template.registerHelper('showDisclaimer', function(){
return Session.get(FIS.KEYS.SHOW_DISCLAIMER);
}); |
export function isNullOrWhitespace ( str ) {
if (typeof str === 'undefined' || str == null)
return true;
return str.replace(/\s/g, '').length < 1;
}
export function intersperse(array, something) {
if (array.length < 2) { return array }
var result = [], i = 0, l = array.length
if (typeof something == 'function') {
for (; i < l; i ++) {
if (i !== 0) { result.push(something()) }
result.push(array[i])
}
}
else {
for (; i < l; i ++) {
if (i !== 0) { result.push(something) }
result.push(array[i])
}
}
return result
}
export function deleteAllFromFirebase(snapshot, cb) {
const hastable = snapshot.val();
if (hastable === null)
return;
const ref = snapshot.ref();
const update = Object.keys(hastable).reduce((result, k) => {
result[k] = null;
cb && cb(hastable[k]);
return result;
}, {});
console.log(update);
ref.update(update);
}
export function createReducer(initialState, handlers) {
return function reducer(state = initialState, action) {
if (handlers.hasOwnProperty(action.type)) {
return handlers[action.type](state, action)
} else {
return state
}
}
}
|
'use strict';
const autoprefixer = require('autoprefixer');
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const ManifestPlugin = require('webpack-manifest-plugin');
const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
const SWPrecacheWebpackPlugin = require('sw-precache-webpack-plugin');
const eslintFormatter = require('react-dev-utils/eslintFormatter');
const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
const paths = require('./paths');
const getClientEnvironment = require('./env');
// Webpack uses `publicPath` to determine where the app is being served from.
// It requires a trailing slash, or the file assets will get an incorrect path.
const publicPath = paths.servedPath;
// Some apps do not use client-side routing with pushState.
// For these, "homepage" can be set to "." to enable relative asset paths.
const shouldUseRelativeAssetPaths = publicPath === './';
// Source maps are resource heavy and can cause out of memory issue for large source files.
const shouldUseSourceMap = process.env.GENERATE_SOURCEMAP !== 'false';
// `publicUrl` is just like `publicPath`, but we will provide it to our app
// as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript.
// Omit trailing slash as %PUBLIC_URL%/xyz looks better than %PUBLIC_URL%xyz.
const publicUrl = publicPath.slice(0, -1);
// Get environment variables to inject into our app.
const env = getClientEnvironment(publicUrl);
// Assert this just to be safe.
// Development builds of React are slow and not intended for production.
if (env.stringified['process.env'].NODE_ENV !== '"production"') {
throw new Error('Production builds must have NODE_ENV=production.');
}
// Note: defined here because it will be used more than once.
const cssFilename = 'static/css/[name].[contenthash:8].css';
// ExtractTextPlugin expects the build output to be flat.
// (See https://github.com/webpack-contrib/extract-text-webpack-plugin/issues/27)
// However, our output is structured with css, js and media folders.
// To have this structure working with relative paths, we have to use custom options.
const extractTextPluginOptions = shouldUseRelativeAssetPaths
? // Making sure that the publicPath goes back to to build folder.
{ publicPath: Array(cssFilename.split('/').length).join('../') }
: {};
// This is the production configuration.
// It compiles slowly and is focused on producing a fast and minimal bundle.
// The development configuration is different and lives in a separate file.
module.exports = {
// Don't attempt to continue if there are any errors.
bail: true,
// We generate sourcemaps in production. This is slow but gives good results.
// You can exclude the *.map files from the build during deployment.
devtool: shouldUseSourceMap ? 'source-map' : false,
// In production, we only want to load the polyfills and the app code.
entry: [require.resolve('./polyfills'), paths.appIndexJs],
output: {
// The build folder.
path: paths.appBuild,
// Generated JS file names (with nested folders).
// There will be one main bundle, and one file per asynchronous chunk.
// We don't currently advertise code splitting but Webpack supports it.
filename: 'static/js/[name].[chunkhash:8].js',
chunkFilename: 'static/js/[name].[chunkhash:8].chunk.js',
// We inferred the "public path" (such as / or /my-project) from homepage.
publicPath: publicPath,
// Point sourcemap entries to original disk location (format as URL on Windows)
devtoolModuleFilenameTemplate: info =>
path
.relative(paths.appSrc, info.absoluteResourcePath)
.replace(/\\/g, '/'),
},
resolve: {
// This allows you to set a fallback for where Webpack should look for modules.
// We placed these paths second because we want `node_modules` to "win"
// if there are any conflicts. This matches Node resolution mechanism.
// https://github.com/facebookincubator/create-react-app/issues/253
modules: ['node_modules', paths.appNodeModules].concat(
// It is guaranteed to exist because we tweak it in `env.js`
process.env.NODE_PATH.split(path.delimiter).filter(Boolean)
),
// These are the reasonable defaults supported by the Node ecosystem.
// We also include JSX as a common component filename extension to support
// some tools, although we do not recommend using it, see:
// https://github.com/facebookincubator/create-react-app/issues/290
// `web` extension prefixes have been added for better support
// for React Native Web.
extensions: ['.web.js', '.js', '.json', '.web.jsx', '.jsx'],
alias: {
// Support React Native Web
// https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
'react-native': 'react-native-web',
'ps-react': path.resolve(__dirname, '../src/components'),
},
plugins: [
// Prevents users from importing files from outside of src/ (or node_modules/).
// This often causes confusion because we only process files within src/ with babel.
// To fix this, we prevent you from importing files out of src/ -- if you'd like to,
// please link the files into your node_modules/ and let module-resolution kick in.
// Make sure your source files are compiled, as they will not be processed in any way.
// new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson]),
],
},
module: {
strictExportPresence: true,
rules: [
// TODO: Disable require.ensure as it's not a standard language feature.
// We are waiting for https://github.com/facebookincubator/create-react-app/issues/2176.
// { parser: { requireEnsure: false } },
// First, run the linter.
// It's important to do this before Babel processes the JS.
{
test: /\.(js|jsx)$/,
enforce: 'pre',
use: [
{
options: {
formatter: eslintFormatter,
eslintPath: require.resolve('eslint'),
},
loader: require.resolve('eslint-loader'),
},
],
include: paths.appSrc,
},
{
// "oneOf" will traverse all following loaders until one will
// match the requirements. When no loader matches it will fall
// back to the "file" loader at the end of the loader list.
oneOf: [
// "url" loader works just like "file" loader but it also embeds
// assets smaller than specified size as data URLs to avoid requests.
{
test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
loader: require.resolve('url-loader'),
options: {
limit: 10000,
name: 'static/media/[name].[hash:8].[ext]',
},
},
// Process JS with Babel.
{
test: /\.(js|jsx)$/,
include: paths.appSrc,
loader: require.resolve('babel-loader'),
options: {
compact: true,
},
},
// The notation here is somewhat confusing.
// "postcss" loader applies autoprefixer to our CSS.
// "css" loader resolves paths in CSS and adds assets as dependencies.
// "style" loader normally turns CSS into JS modules injecting <style>,
// but unlike in development configuration, we do something different.
// `ExtractTextPlugin` first applies the "postcss" and "css" loaders
// (second argument), then grabs the result CSS and puts it into a
// separate file in our build process. This way we actually ship
// a single CSS file in production instead of JS code injecting <style>
// tags. If you use code splitting, however, any async bundles will still
// use the "style" loader inside the async code so CSS from them won't be
// in the main CSS file.
{
test: /\.css$/,
loader: ExtractTextPlugin.extract(
Object.assign(
{
fallback: require.resolve('style-loader'),
use: [
{
loader: require.resolve('css-loader'),
options: {
importLoaders: 1,
minimize: true,
sourceMap: shouldUseSourceMap,
modules: true,
localIdentName: '[name]_[local]__[hash:base64:5]'
},
},
{
loader: require.resolve('postcss-loader'),
options: {
// Necessary for external CSS imports to work
// https://github.com/facebookincubator/create-react-app/issues/2677
ident: 'postcss',
plugins: () => [
require('postcss-flexbugs-fixes'),
autoprefixer({
browsers: [
'>1%',
'last 4 versions',
'Firefox ESR',
'not ie < 9', // React doesn't support IE8 anyway
],
flexbox: 'no-2009',
}),
],
},
},
],
},
extractTextPluginOptions
)
),
// Note: this won't work without `new ExtractTextPlugin()` in `plugins`.
},
// "file" loader makes sure assets end up in the `build` folder.
// When you `import` an asset, you get its filename.
// This loader doesn't use a "test" so it will catch all modules
// that fall through the other loaders.
{
loader: require.resolve('file-loader'),
// Exclude `js` files to keep "css" loader working as it injects
// it's runtime that would otherwise processed through "file" loader.
// Also exclude `html` and `json` extensions so they get processed
// by webpacks internal loaders.
exclude: [/\.js$/, /\.html$/, /\.json$/],
options: {
name: 'static/media/[name].[hash:8].[ext]',
},
},
// ** STOP ** Are you adding a new loader?
// Make sure to add the new loader(s) before the "file" loader.
],
},
],
},
plugins: [
// Makes some environment variables available in index.html.
// The public URL is available as %PUBLIC_URL% in index.html, e.g.:
// <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
// In production, it will be an empty string unless you specify "homepage"
// in `package.json`, in which case it will be the pathname of that URL.
new InterpolateHtmlPlugin(env.raw),
// Generates an `index.html` file with the <script> injected.
new HtmlWebpackPlugin({
inject: true,
template: paths.appHtml,
minify: {
removeComments: true,
collapseWhitespace: true,
removeRedundantAttributes: true,
useShortDoctype: true,
removeEmptyAttributes: true,
removeStyleLinkTypeAttributes: true,
keepClosingSlash: true,
minifyJS: true,
minifyCSS: true,
minifyURLs: true,
},
}),
// Makes some environment variables available to the JS code, for example:
// if (process.env.NODE_ENV === 'production') { ... }. See `./env.js`.
// It is absolutely essential that NODE_ENV was set to production here.
// Otherwise React will be compiled in the very slow development mode.
new webpack.DefinePlugin(env.stringified),
// Minify the code.
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false,
// Disabled because of an issue with Uglify breaking seemingly valid code:
// https://github.com/facebookincubator/create-react-app/issues/2376
// Pending further investigation:
// https://github.com/mishoo/UglifyJS2/issues/2011
comparisons: false,
},
output: {
comments: false,
// Turned on because emoji and regex is not minified properly using default
// https://github.com/facebookincubator/create-react-app/issues/2488
ascii_only: true,
},
sourceMap: shouldUseSourceMap,
}),
// Note: this won't work without ExtractTextPlugin.extract(..) in `loaders`.
new ExtractTextPlugin({
filename: cssFilename,
}),
// Generate a manifest file which contains a mapping of all asset filenames
// to their corresponding output file so that tools can pick it up without
// having to parse `index.html`.
new ManifestPlugin({
fileName: 'asset-manifest.json',
}),
// Generate a service worker script that will precache, and keep up to date,
// the HTML & assets that are part of the Webpack build.
new SWPrecacheWebpackPlugin({
// By default, a cache-busting query parameter is appended to requests
// used to populate the caches, to ensure the responses are fresh.
// If a URL is already hashed by Webpack, then there is no concern
// about it being stale, and the cache-busting can be skipped.
dontCacheBustUrlsMatching: /\.\w{8}\./,
filename: 'service-worker.js',
logger(message) {
if (message.indexOf('Total precache size is') === 0) {
// This message occurs for every build and is a bit too noisy.
return;
}
if (message.indexOf('Skipping static resource') === 0) {
// This message obscures real errors so we ignore it.
// https://github.com/facebookincubator/create-react-app/issues/2612
return;
}
console.log(message);
},
minify: true,
// For unknown URLs, fallback to the index page
navigateFallback: publicUrl + '/index.html',
// Ignores URLs starting from /__ (useful for Firebase):
// https://github.com/facebookincubator/create-react-app/issues/2237#issuecomment-302693219
navigateFallbackWhitelist: [/^(?!\/__).*/],
// Don't precache sourcemaps (they're large) and build asset manifest:
staticFileGlobsIgnorePatterns: [/\.map$/, /asset-manifest\.json$/],
}),
// Moment.js is an extremely popular library that bundles large locale files
// by default due to how Webpack interprets its code. This is a practical
// solution that requires the user to opt into importing specific locales.
// https://github.com/jmblog/how-to-optimize-momentjs-with-webpack
// You can remove this if you don't use Moment.js:
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
],
// Some libraries import Node modules but don't use them in the browser.
// Tell Webpack to provide empty mocks for them so importing them works.
node: {
dgram: 'empty',
fs: 'empty',
net: 'empty',
tls: 'empty',
child_process: 'empty',
},
};
|
import React from 'react';
import PropTypes from 'prop-types';
import { connect} from 'react-redux';
import UmsgContainer from '../containers/UmsgContainer';
import Sidebar from '../components/Sidebar'
import Item from '../components/Item'
import { fetchCategory, searchItems } from '../store/actions/items'
class Products extends React.Component {
constructor(...props) {
super(...props);
this.state = {
items: []
};
}
componentDidMount() {
this.refresh();
}
componentDidUpdate(nextProps) {
if (nextProps.params !== this.props.params) {
this.refresh();
}
}
refresh() {
const { params } = this.props;
if (params.category) {
fetchCategory(params.category);
} else {
searchItems(encodeURIComponent(params.search));
}
}
render() {
const {items, isLoading} = this.props;
let content = items.map(i => (<Item key={i.get('_id')} item={i} />));
if (items.length === 0) {
content = (<h3>No items found with search "{this.props.params.search}"</h3>);
}
return (
<div>
<Sidebar {...this.props}/>
<UmsgContainer />
<div
id="item_list"
style={{
opacity: isLoading
? 0.1
: 1
}}>
{content}
</div>
</div>
);
}
}
Products.propTypes = {
params: PropTypes.object.isRequired,
items: PropTypes.array.isRequired,
isLoading: PropTypes.bool.isRequired
};
const mapStatetoProps = store => {
return ({
items: store.itemReducer.data,
isLoading: store.itemReducer.isLoading
});
};
export default connect(mapStatetoProps)(Products);
|
var auth = require('./lib/index.js');
var config = require('config');
const USERNAME = (process.env.USERNAME) ?
process.env.USERNAME :
config.get('icarus.username');
const PASSWORD = (process.env.PASSWORD) ?
(process.env.PASSWORD) :
config.get('icarus.password');
if (!(USERNAME && PASSWORD)) {
throw new Error("Missing config values!");
}
// constructor call
var parser = new auth(USERNAME, PASSWORD);
// execute and test module
parser.printStudent();
console.log(parser.getSessionInfo());
console.log(parser.getDepartmentName());
// authenticate and test the other api
parser.authenticate(function (error, response) {
console.log(response);
console.log((response.authenticated) ? "Authenticated" : "Authentication Failed.");
parser.getUserDetails(response.document, response.cookie, function (err, data) {
if (err) {
return console.log(err.message)
}
console.log(data)
});
parser.getSucceededGrades(response.document, function (err, value) {
if (err) {
return console.log(err.message)
}
console.log(value)
});
parser.getAnalyticGrades(response.document, function (err, value) {
if (err) {
return console.log(err.message)
}
console.log(value)
});
parser.getExamGrades(response.document, function (err, value) {
if (err) {
return console.log(err.message)
}
console.log(value)
});
parser.getIntercalaryExamGrades(response.document, function (err, value) {
if (err) {
return console.log(err.message)
}
console.log(value)
});
parser.getCurriculumToDeclare(response.cookie, function (err, value) {
if (err) {
console.log('error:', err.message); // Print the error if one occurred
}
var formData = [];
for (var i in value) {
if (value.hasOwnProperty(i)) {
formData.push(value[i].id);
}
}
console.log(value)
// call postCurriculumToDeclare(formData, (err, value) {....}) to post them
});
parser.postCurriculumToDeclare(['321-2450',
'331-2205',
'321-4120',
'311-0116',
'311-0238',
'311-0327',
'311-0437',
'331-2708'], response.cookie, function (err, value) {
if (err) {
console.log('error:', err.message); // Print the error if one occurred
}
console.log(value);
});
parser.postRequestToDepartment({
id: 'test',
surname: 'test',
name: 'test',
father: 'test',
semester: 'test',
address: 'test',
address2: 'test',
phone: 'test',
emergency: 'test',
method: 'test',
sent_address: 'test',
other: 'test',
requests: [
{name: 'Βεβαίωση Σπουδών', amount: '1'},
{name: 'Βεβαίωση Διαγραφής', amount: '3'},
{name: 'Αλλο', amount: '9', what: 'κάτι άλλο'}
]
}, response.cookie, function (err, value) {
if (err) {
console.log('error:', err.message); // Print the error if one occurred
}
console.log(value);
})
});
|
function SpeechBubbleObject(masta)
{
GameObject.call(this);
this.font = "18px Arial";
this.text = "";
this.master = masta;
this.position = new Vector2(0,0);
this.size = new Vector2(0,0);
this.depth = 90;
this.displayTimeLimit = 0;
this.display = false;
this.displayTimer = 0;
this.setText = function(text)
{
context.font = this.font;
this.size.x = 225;
this.size.y = 96;
this.text = text;
this.displayTimeLimit = (text.length+60)*2;
}
this.draw = function()
{
this.isDoomed = this.master.isDoomed;
if (!this.display)
return;
this.displayTimer++;
if (this.displayTimeLimit <= this.displayTimer)
{
this.display = false;
this.displayTimer = 0;
}
context.lineWidth = 2;
context.font = this.font;
context.fillStyle = "#FFFFFF";
context.drawBubble(this.position.x, this.position.y-200, this.size.x, this.size.y, this.position.x, this.position.y,25);
context.fillStyle = "#000000";
context.wrapText(this.text,this.position.x+10,this.position.y-167,200,18);
}
}
SpeechBubbleObject.prototype = new GameObject();
SpeechBubbleObject.constructor = SpeechBubbleObject; |
import { EventEmitter } from 'events';
import Constants from './Constants';
// searchers
import YoutubeSearcher from 'kaku-core/modules/searcher/YoutubeSearcher';
import VimeoSearcher from 'kaku-core/modules/searcher/VimeoSearcher';
import SoundCloudSearcher from 'kaku-core/modules/searcher/SoundCloudSearcher';
import MixCloudSearcher from 'kaku-core/modules/searcher/MixCloudSearcher';
import AudiusSearcher from 'kaku-core/modules/searcher/AudiusSearcher'
class Searcher extends EventEmitter {
constructor() {
super();
let self = this;
// default searcher
this._selectedSearcherName = 'youtube';
// supported searchers
this._searchers = {
'youtube': new YoutubeSearcher({
apiKey: Constants.API.YOUTUBE_API_KEY
}),
'vimeo': new VimeoSearcher({
clientId: Constants.API.VIMEO_API_CLIENT_ID,
clientSecret: Constants.API.VIMEO_API_CLIENT_SECRET
}),
'soundcloud': new SoundCloudSearcher({
clientId: Constants.API.SOUND_CLOUD_API_CLIENT_ID,
clientSecret: Constants.API.SOUND_CLOUD_API_CLIENT_SECRET
}),
'mixcloud': new MixCloudSearcher(),
'audius': new AudiusSearcher(),
'all': {
search: function(keyword, limit) {
let promises = [
self._searchers.youtube.search(keyword, limit),
self._searchers.vimeo.search(keyword, limit),
self._searchers.soundcloud.search(keyword, limit),
self._searchers.mixcloud.search(keyword, limit),
self._searchers.audius.search(keyword)
];
return Promise.all(promises);
}
}
};
this._searchResults = [];
}
get selectedSearcher() {
return this._searchers[this._selectedSearcherName];
}
get searchResults() {
return this._searchResults;
}
getSupportedSearchers() {
let promise = new Promise((resolve) => {
resolve(Object.keys(this._searchers));
});
return promise;
}
search(keyword, limit, toSave = false) {
if (!keyword) {
return Promise.resolve([]);
}
else {
return this.selectedSearcher.search(keyword, limit).then((results) => {
// merge arrays into one array
if (this._selectedSearcherName === 'all') {
results = [].concat.apply([], results);
}
if (toSave) {
this._searchResults = results;
this.emit('search-results-updated', results);
}
return results;
});
}
}
changeSearcher(searcherName) {
let searcher = this._searchers[searcherName];
if (searcher) {
this._selectedSearcherName = searcherName;
this.emit('searcher-changed', searcherName);
}
}
}
module.exports = new Searcher();
|
'use strict';
// Declare app level module which depends on views, and components
angular.module('myApp', [
'ngRoute',
'myApp.view1',
'myApp.view2',
'myApp.version',
'ngMdIcons'
]).
config(['$locationProvider', '$routeProvider', function($locationProvider, $routeProvider) {
$locationProvider.hashPrefix('!');
$routeProvider.otherwise({redirectTo: '/view1'});
}]);
|
define([
'utils/isEqual',
'shared/get/_get'
], function (
isEqual,
get
) {
'use strict';
var options = { evaluateWrapped: true };
return function updateMustache () {
var value = get( this.root, this.keypath, options );
if ( !isEqual( value, this.value ) ) {
this.render( value );
this.value = value;
}
};
});
|
const _ = require('lodash');
let defaults = {
PORT: 3000,
METADATA_CRON_SCHEDULE: '0 0 * * Monday', // update file from gprofiler etc. (Monday at midnight)
PC_URL: 'https://www.pathwaycommons.org/',
XREF_SERVICE_URL: 'https://biopax.baderlab.org/',
DOWNLOADS_FOLDER_NAME: 'downloads',
GPROFILER_URL: "https://biit.cs.ut.ee/gprofiler/",
GMT_ARCHIVE_URL: 'https://biit.cs.ut.ee/gprofiler/static/gprofiler_hsapiens.name.zip',
IDENTIFIERS_URL: 'https://identifiers.org',
NCBI_EUTILS_BASE_URL: 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils',
NCBI_API_KEY: 'b99e10ebe0f90d815a7a99f18403aab08008', // for dev testing only (baderlabsysmonitor ncbi key)
HGNC_BASE_URL: 'https://rest.genenames.org',
UNIPROT_API_BASE_URL: 'https://www.ebi.ac.uk/proteins/api',
PC_IMAGE_CACHE_MAX_SIZE: 10000,
PC_CACHE_MAX_SIZE: 1000,
PUB_CACHE_MAX_SIZE: 1000000,
ENT_CACHE_MAX_SIZE: 1000000,
ENT_SUMMARY_CACHE_MAX_SIZE: 1000000,
MAX_SIF_NODES: 25,
CLIENT_FETCH_TIMEOUT: 15000,
SERVER_FETCH_TIMEOUT: 5000,
// DB config values
DB_NAME: 'appui',
DB_HOST: '127.0.0.1',
DB_PORT: '28015',
DB_USER: undefined,
DB_PASS: undefined,
DB_CERT: undefined,
// factoid specific urls
FACTOID_URL: 'http://unstable.factoid.baderlab.org/',
NS_CHEBI: 'chebi',
NS_ENSEMBL: 'ensembl',
NS_GENECARDS: 'genecards',
NS_GENE_ONTOLOGY: 'go',
NS_HGNC: 'hgnc',
NS_HGNC_SYMBOL: 'hgnc.symbol',
NS_NCBI_GENE: 'ncbigene',
NS_PUBMED: 'pubmed',
NS_REACTOME: 'reactome',
NS_UNIPROT: 'uniprot'
};
let envVars = _.pick( process.env, Object.keys( defaults ) );
// these vars are always included in the bundle because they ref `process.env.${name}` directly
// NB DO NOT include passwords etc. here
let clientVars = {
NODE_ENV: process.env.NODE_ENV,
PC_URL: process.env.PC_URL,
FACTOID_URL: process.env.FACTOID_URL
};
_.assign(envVars, clientVars);
for( let key in envVars ){
let val = envVars[key];
if( val === '' || val == null ){
delete envVars[key];
}
}
let conf = Object.assign( {}, defaults, envVars );
Object.freeze( conf );
module.exports = conf;
|
var AppDispatcher = require('../dispatcher/AppDispatcher'),
Constants = require('../Constants');
module.exports = {
awardUsers: function (users, awardId, reason) {
AppDispatcher.dispatch({
actionType: Constants.EVENT_AWARD_USERS,
users : users,
award : awardId,
reason : reason
});
},
createAward: function (name, description, imageFileId) {
AppDispatcher.dispatch({
actionType: Constants.EVENT_CREATE_AWARD,
name : name,
desc : description,
fileId : imageFileId
});
},
deleteAward: function (awardEntity) {
AppDispatcher.dispatch({
actionType: Constants.EVENT_DELETE_AWARD,
id : awardEntity.aid
});
},
editAward: function (aid, name, desc, file) {
AppDispatcher.dispatch({
actionType: Constants.EVENT_EDIT_AWARD,
id : aid,
name : name,
desc : desc,
file : file
});
},
getAwards: function () {
AppDispatcher.dispatch({
actionType: Constants.EVENT_GET_ALL_AWARDS
});
},
getSettings: function () {
AppDispatcher.dispatch({
actionType: Constants.EVENT_GET_SETTINGS
});
},
offsetUserFromSearchOn: function (offset) {
AppDispatcher.dispatch({
actionType: Constants.EVENT_OFFSET_USER_FROM_SEARCH_ON,
offset : offset
})
},
panelCancel: function (panel) {
AppDispatcher.dispatch({
actionType: Constants.EVENT_PANEL_CANCEL,
panel : panel
});
},
pickUserFromSearch: function () {
AppDispatcher.dispatch({
actionType: Constants.EVENT_PICK_USER_FROM_SEARCH
});
},
pickUserFromSearchAt: function (index) {
AppDispatcher.dispatch({
actionType: Constants.EVENT_PICK_USER_FROM_SEARCH_AT,
index : index
});
},
saveSettings: function (settings) {
AppDispatcher.dispatch({
actionType: Constants.EVENT_SAVE_SETTINGS,
settings : settings
});
},
searchUser: function (name) {
AppDispatcher.dispatch({
actionType: Constants.EVENT_SEARCH_USER,
request : name
});
},
unpickUserFromSearch: function (index, uid) {
AppDispatcher.dispatch({
actionType: Constants.EVENT_UNPICK_USER_FROM_SEARCH,
index : index,
uid : uid
});
}
}; |
module.exports = {
extends: ["prettier"],
};
|
var React = require('React');
var Card = require('./Card');
var Parent = React.createClass({
render: function() {
return (
<div>
Parent component.
<Card />
</div>
);
}
});
module.exports = Parent; |
/**
* da-events is included in starter-kit
* it's a simple event listener that can register and trigger callbacks
* based on events that are triggered through its methods
*/
module.exports = ngModule => {
function daEvents($rootScope, $q, $log, SAMPLE_APP) {
// central place for documenting app events
const _eventRegistry = {
'app:loaded': 'This event is fired when the appFrame as finished loading.',
[SAMPLE_APP.E_CAT_FILTER_CHANGE]: 'This even is fired when the filters get updated'
};
// Create promise to reolve when appFrame has finished animating
const _diferred = $q.defer();
const offFn = $rootScope.$on('app:loaded', () => {
_diferred.resolve('The app has loaded!');
// This will un-register the event listener once its happend.
offFn();
});
// Public API here
const api = {
/**
* Registers an event listener if it is defined in `_eventRegistry` object.
* @param {string} name Name of event. Must match key in `_eventRegistry` object.
* @param {func} listener The function to be called when event is triggered. First param is $event obj.
* @return {unbind} Returns the unbind function for use of destroying event.
*/
on(name, listener) {
if (_eventRegistry.hasOwnProperty(name)) {
return $rootScope.$on(name, listener);
}
$log.error('No event registered with name: ' + name);
return null;
},
/**
* Triggers an event that has been defined in `eventRegistry` object.
* @param {string} name Name of event to trigger. Must be defined first.
* @param {[.]} args Args to pass to callback.
* @return {[type]} [description]
*/
trigger(name, args) {
if (_eventRegistry.hasOwnProperty(name)) {
return $rootScope.$emit(name, args);
}
$log.error('No event registered with name: ' + name);
return null;
},
};
// promise that is resolved when 'app:loaded' event is fired.
api.appLoadPromise = _diferred.promise;
return api;
}
daEvents.$inject = ['$rootScope', '$q', '$log', 'SAMPLE_APP'];
ngModule.factory('daEvents', daEvents);
if (ON_TEST) {
require('./da-events.factory.spec.js')(ngModule);
}
return ngModule;
};
|
(function() {
'use strict';
angular
.module('yobi.editor')
.controller('yobiEditorCtrl', ['yobiEditorSvc', yobiEditorCtrl])
function yobiEditorCtrl(yobiEditorSvc) {
/* jshint validthis: true */
var vm = this;
vm.mention = {
users: yobiEditorSvc.users(),
issues: yobiEditorSvc.issues()
};
}
})();
|
function reverseSentences(sentences) {
for (var i=0; i<sentences.length; i++) {
sentences.splice(i, 1, sentences[i].split(' ').reverse().join(' '));
}
return sentences;
}
console.log(reverseSentences(["Hello World", "Hello CodeEval"])); |
/**
* Created by dt on 2016/10/18.
*/
var utils = require('../tinyTool/utils.js');
var date = require('../tinyTool/date.js');
var http = require('http');
var urlParse = require('url').parse;
var querystring = require('querystring');
var interfaceTestData = {
data_URL : [],
data_UserId : [],
data_FunctionId : [],
data_key : []
}
//接口测试页面
defineAction("interfaceTest",function(req,res){
res.myRender("interfaceTest.html",{"haha":"hahahahahahaha.....","title":"我是hehe"})
});
//接口测试页面按钮点击
defineAction("interfaceTestClick",function(req,res){
var data=req.myBody;
var id = data.id;
var arr_id = "data_"+id;
var arr = interfaceTestData[arr_id];
res.mySend(arr);
});
defineAction("InterfaceTestApi",function(req,res){
var data = req.myBody;
var method = data.method_type;
var url = data.URL;
var UserId = data.UserId;
var FunctionId = data.FunctionId;
var key = data.key.toString();
var isMD5 = data.MD5;
var postData ;
try{
postData = JSON.parse(data.postData);
}catch (e){
res.mySend("[测试工具错误]JSON.parse解析错误:" + e);return
}
if(!(method &&url&&UserId&&FunctionId&&key&&postData)){
res.mySend("[测试工具错误]参数缺失");return
}
console.log(111)
insertData("data_URL",url);
insertData("data_UserId",UserId);
insertData("data_FunctionId",FunctionId);
insertData("data_key",key);
console.log(interfaceTestData)
//是否再加密
if(isMD5 ===true || isMD5 === "true"){
key = utils.toMD5(key);
}
var time = date.getFormatDate('yyyyMMddhhmmss');
var sign = utils.toMD5(UserId.toString() + key + FunctionId + time);
var _postData = {
"UserId": UserId,
"FunctionId": FunctionId,
"Time": time,
"RequestData":postData,
"Sign": sign
};
//var postData = querystring.stringify({
// "UserId": UserId,
// "FunctionId": FunctionId,
// "Time": time,
// "RequestData":postData,
// "Sign": sign
//});
//console.log()
var post_task_data = { "j": JSON.stringify(_postData) };
var post_data = querystring.stringify(post_task_data);
var opts = urlParse(url);
var options = {
hostname: opts.hostname,
port: opts.port,
path: opts.pathname,
method:method,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': post_data.length
}
};
var req = http.request(options, function(_res) {
_res.setEncoding('utf8');
var data = "";
_res.on('data', function (chunk) {
data += chunk;
});
_res.on('end', function() {
console.log(data);
res.mySend(data);
})
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
// write data to request body
req.write(post_data);
});
function insertData(arr_name,arr_data){
var bol = interfaceTestData[arr_name].indexOf(arr_data);
if(bol== -1){
interfaceTestData[arr_name].push(arr_data)
}
var l = interfaceTestData[arr_name].length;
if(l>10){
interfaceTestData[arr_name].shift();
}
} |
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import {
firebaseConnect,
isLoaded,
isEmpty,
dataToJS
} from 'react-redux-firebase';
import LoadingSpinner from '../../../../../Components/LoadingSpinner';
import classes from './ProjectContainer.scss';
// Get project path from firebase based on params prop (route params)
@firebaseConnect(({ params }) => [`projects/${params.projectname}`])
// Map state to props
@connect(({ firebase }, { params }) => ({
project: dataToJS(firebase, `projects/${params.projectname}`)
}))
export default class Project extends Component {
static propTypes = {
project: PropTypes.object,
params: PropTypes.object.isRequired
};
render () {
const { project, params } = this.props;
if (isEmpty(project)) {
return <div>Project not found</div>
}
if (!isLoaded(project)) {
return <LoadingSpinner />
}
return (
<div className={classes.container}>
<h2>Project Container</h2>
<pre>Project Key: {params.projectname}</pre>
<pre>{JSON.stringify(project, null, 2)}</pre>
</div>
)
}
} |
exports.getPromptConfig = async (options) => {
let { message } = options;
if (typeof options.message === 'function') {
message = message();
}
return {
validate: () => true,
...options,
message: await message,
};
};
|
const assert = require('assert');
const rewire = require('rewire');
const Player = rewire('../lib/player');
const { getClient } = require('./lib/mongo');
const mock = require('./lib/mock');
const getPlayerClient = function () {
return getClient(Player);
};
const getCollection = function () {
return getPlayerClient().collection('players');
};
const deletePlayers = function (...ids) {
return getCollection().deleteMany({ _id: {
$in: ids
}});
};
const createPlayer = async function () {
return await Player.create({
discordid: '123123',
discordnick: 'test player',
steamid64: '1234567890',
maxmmr: 1000
});
};
describe('Player', function () {
describe('#create()', async function () {
let player;
it('Should store a new player in the database and return the corresponding Player instance.', async function () {
player = await createPlayer();
assert.ok(player.hasOwnProperty('_id'));
assert.ok(player instanceof Player);
});
after(function () {
deletePlayers(player._id);
});
});
describe('#findByDiscordId(discordid)', function () {
let player;
before(async function () {
player = await createPlayer();
});
it('Should find a player in the database with the provided discord ID, and return a Player instance.', async function () {
let playerRecord = await Player.findByDiscordId(player.discordid);
assert.ok(playerRecord instanceof Player);
});
it('Should return null if a nonexistent discord id is supplied', async function () {
assert.strictEqual(await Player.findByDiscordId('NotValid'), null);
});
after(function () {
deletePlayers(player._id);
});
});
describe('#steamId64Taken(steamid64)', function () {
let player;
before(async function () {
player = await createPlayer();
});
it('It should return true if the provided steamid64 is already taken.', async function () {
assert.ok(await Player.steamId64Taken(player.steamid64));
});
it('It should return false if the provided steamid64 is available.', async function () {
assert.ok(!await Player.steamId64Taken('AvailableValue'));
});
after(function () {
deletePlayers(player._id);
});
});
describe('#updateMaxMMR()', function () {
let player;
before(async function () {
player = await createPlayer();
});
it('It should update the players MaxMMR by utilizing an external resource', function () {
Player.__with__({
rllv: mock
})(function () {
return player.updateMaxMMR();
}).then(async function () {
assert.equal(player.maxmmr, 2000);
const playerRecord = await getCollection().findOne({ _id: player._id });
assert.equal(playerRecord.maxmmr, 2000);
});
});
it('It should not raise an exception if a non-existing player is provided', function () {
let fakePlayer = new Player({
steamid64: 0,
maxmmr: 1000
});
Player.__with__({
rllv: mock
})(function () {
return fakePlayer.updateMaxMMR();
}).then(function () {
assert.equal(fakePlayer.maxmmr, 1000);
});
});
after(function () {
deletePlayers(player._id);
});
});
describe('#unsetSteamId64()', function () {
let player;
before(async function () {
player = await createPlayer();
});
it('It should unset the player\'s steamid64', async function () {
let playerRecord;
await player.unsetSteamId64();
playerRecord = await getCollection().findOne({ _id: player._id });
assert.ok(!player.hasOwnProperty('steamid64'));
assert.ok(!playerRecord.hasOwnProperty('steamid64'));
});
after(function () {
deletePlayers(player._id);
});
});
describe('#setParams(params)', function () {
let player;
before(async function () {
player = await createPlayer();
});
it('It should set the player\'s parameters both in the database and for the instance.', async function () {
let playerRecord;
await player.setParams({
discordid: '1',
someprop: 'string'
});
playerRecord = await getCollection().findOne({ _id: player._id });
assert.strictEqual(player.discordid, '1');
assert.strictEqual(player.someprop, 'string');
assert.strictEqual(playerRecord.discordid, '1');
assert.strictEqual(playerRecord.someprop, 'string');
});
after(function () {
deletePlayers(player._id);
});
});
describe('#delete()', function () {
let player;
before(async function () {
player = await createPlayer();
});
it('It should delete the corresponding player entry from the database.', async function () {
await player.delete();
assert.ok(!await getCollection().findOne({ _id: player._id }));
});
after(function () {
deletePlayers(player._id);
});
});
});
|
require('./dist/jk-rating-stars.js');
module.exports = 'angular-jk-rating-stars';
|
var combineAllArrays = (arr1, ...arr2) => {
return arr1.concat(...arr2);
};
var arr1 = [1, "peter", 5];
var arr2 = [1, 2, "45"];
var hege = ["Cecilie", "Lone"];
var stale = ["Emil", "Tobias", "Linus"];
console.log(combineAllArrays(arr1, arr2, hege, stale));
|
$(document).ready(function() {
// Better performance in replacing js in any browsers. http://jsperf.com/encode-html-entities
function htmlEscape(str) {
return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/ /g, ' ');
}
function userReplace(str) {
return str.replace(/^#/gi, '<root>[root@localhost]# </root>').replace(/^\$/gi, '<user>[loz@localhost]$ </user>');
}
// the html that will be inserted to replace the shortened code
// the terminal bar and body before the text is placed
var termTop = '\
<div id="terminal-window"> \
<div id="terminal-toolbar"> \
<div class="terminal-top"> \
<div class="terminal-menu"> \
</div> \
<div id="terminal-buttons"> \
<div class="terminal-button terminal-close"> \
<div class="terminal-close-icon">X</div> \
</div> \
</div> \
<div id="terminal-title"> \
loz@localhost:~ \
</div> \
</div> \
</div> \
<div id="terminal-body"><p><span class="element"></span> \
';
// closes the html that has been inserted, ends the terminal display
var termBot = '\
</p><span class="typed"></span> \
</div> \
</div> \
';
// tell jQuery to search for each instance of the shortened code
$(".cssterm").each(function() {
var myContent = $(this).text();
var arrayContent = myContent.split('\n');
var newString = "";
jQuery.each(arrayContent, function() {
// make sure there's text to avoid blank spaces
if (this.length != 0) {
// is string a root command
if (this.charAt(0) == "#" || this.charAt(0) == "$") {
newString += userReplace(this) + "<br>\n";
} else {
newString += htmlEscape(this) + "<br>\n";
}
}
});
$(this).replaceWith( termTop + newString + termBot );
});
}); |
/*********************************************************************
Component.js
This file is part of Heliwidgets library for Helios framework.
__Copying:___________________________________________________________
Copyright 2008, 2009 Dmitry Prokashev
Heliwidgets is free software: you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version.
Heliwidgets is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with the Heliwidgets library. If not, see
<http://www.gnu.org/licenses/>.
__Description:_______________________________________________________
Defines heliwidgets.Component Widget used for creating a widget
which will contain some component, defined in Platform API.
__Objects declared:__________________________________________________
heliwidgets.Component - Component constructor
--heliwidgets.Component public properties: --------------------------
componentConstructor - constructor function of the component
component - points to the component itself providing its API
*********************************************************************/
include( "heliwidgets.js" );
include( "Widget.js" );
init = function() {
// keeps heliwidgets routines
// a shorter name for better reading of this file
var hw = heliwidgets;
// Component constructor.
//
// Argument:
// - initStruc is a structure to initialize widget with
hw.Component = function( initStruc ) {
// overridding widget's name, used in _create() and _destroy()
// to find out corresponding engine routines
this._widgetType = "Component";
// particular widget type properties should be created before
// parent constructor is called
// keeps constructor of the component conforming the Platform
// Component API
this.componentConstructor = new js.Property( function(){} );
// will point to the component object itself providing its API
this.component = null;
//parent constructor
hw.Widget.call( this, initStruc );
}
hw.Component.prototype = new hw.Widget();
}
|
version https://git-lfs.github.com/spec/v1
oid sha256:76e07e15b3c4e8cf9879359445eb1d5ed7004acfec2b05ab10b1ebc317dcccca
size 1566591
|
/**
* Test dependencies.
*/
var Asana = require('asana-client')
, request = require('superagent');
describe('Asana client', function() {
var ctx = {}, asana;
before(function() {
asana = new Asana(ctx, '/');
});
afterEach(function() {
request.restore();
});
describe('addWorkspaces', function() {
it ('should add workspaces to context', function(done) {
});
})
});
|
/**
* Created by Administrator on 2015/12/26.
* 一些变量
$.fn.extend({
// 通过一定的条件,删选自身
find 查找子节点, 调用的是jQuery.find == Sizzle, jQuery.unique == Sizzle.unique ;
has 指子元素有没有,返回自身的。。
not filter 指自身有没有,返回自身的。。
is 返回true or false
closest 找满足条件的最近父节点(包括自身)
index 返回元素在兄弟节点中的索引值
add
addBack
});
function sibling(){}
jQuery.each({
parent // parentNode
parents // parentNode 循环
parentsUntil //
next // nextSibling
prev // previousSibling
nextAll // 循环
prevAll //
nextUntil
prevUntil // 下面的兄弟节点,直到一个
siblings // 所有兄弟节点
children // 只有元素节点
contents // 包括文本节点,elem.childNodes, iframe
});
jQuery.extend({
filter
dir
sibling
});
function winnow(){}
一些变量
jQuery.fn.extend({
text // 返回文本节点的文本形式
append // body.append(tr)在ie67中有问题,tbody.append(tr)
prepend //
before
after
remove // 返回自身,但是自身上绑定的事件都没有,调用jQuery.cleanData();
empty // elem.textContent, 678不支持
clone // clone(true)=clone(true,true) ,clone(false)=clone(false,false)=clone(), clone(true,false):父元素事件不清除,子元素清除
// 原生添加(addEventListener)的事件不会被克隆
html //"<script></scrip>" 与原生 innerHTML 插入不同
replaceWith
detach // 与remove差不多,但是原先绑定的data或是event都存在
domManip
});
jQuery.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
});
jQuery.extend({
clone
buildFragment
cleanData
_evalUrl
});
function manipulationTarget(){}
function disableScript(){}
function restoreScript(){}
function setGlobalEval(){}
function cloneCopyEvent(){}
function getAll(){}
function fixInput(){}
jQuery.fn.extend({
wrapAll //选择到的元素包装
wrapInner //包装每个元素的子节点
wrap //对每个元素进行包装
unwrap //删去每个元素的父级,除了body
});
*/
|
// NEED TO TEST THIS!
var Navigation = {
moveUp: function(startingGridIndex, placeHolder){
var destination = new Point(0, 0);
destination.x = startingGridIndex.x;
destination.y = startingGridIndex.y - 1;
return destination;
},
moveDown: function(startingGridIndex, placeHolder){
var destination = new Point(0, 0);
destination.x = startingGridIndex.x;
destination.y = startingGridIndex.y + 1;
return destination;
},
moveLeft: function(startingGridIndex, directionPreference){
var destination = new Point(0, 0);
if (typeof directionPreference === "undefined")
{
directionPreference = "up";
}
if (directionPreference.indexOf("u") === 0)
{
// move up and left
destination.x = startingGridIndex.x - 1;
destination.y = startingGridIndex.y;
}
else
{
// move down and left
destination.x = startingGridIndex.x - 1;
destination.y = startingGridIndex.y + 1;
}
return destination;
},
moveRight: function(startingGridIndex, directionPreference){
var destination = new Point(0, 0);
if (typeof directionPreference === "undefined")
{
directionPreference = "up";
}
if (directionPreference.indexOf("u") === 0)
{
// move up and right
destination.x = startingGridIndex.x + 1;
destination.y = startingGridIndex.y - 1;
}
else
{
// move down and right
destination.x = startingGridIndex.x + 1;
destination.y = startingGridIndex.y;
}
return destination;
},
jumpLeft: function(startingGridIndex){
var destination = this.moveLeft(startingGridIndex, "up");
return this.moveLeft(destination, "down");
},
jumpRight: function(startingGridIndex){
var destination = this.moveRight(startingGridIndex, "up");
return this.moveRight(destination, "down");
}
}; |
version https://git-lfs.github.com/spec/v1
oid sha256:e9ce49ab0d60ac1c1a2cc7d1d5363316866f0437e37dd7fc16e31b5e58559ba7
size 3993
|
import THREE from 'three';
const simplex = new(require('simplex-noise'))
const random = require('random-float')
const randomInt = require('random-int')
import NewtonParticle from '../Helpers/NewtonParticle'
const NUM_PARTICLES = 30
const MAX_HEIGHT = 4
/**
* CubeGeometry class
*/
class RainGeometry extends THREE.BufferGeometry {
/**
* Constructor function
*/
constructor() {
super();
this.gravity = new THREE.Vector3(0, 0.0001, 0)
this.particles = []
this.points = new THREE.Object3D()
this.positions = new Float32Array(NUM_PARTICLES * 3)
this.colors = new Float32Array(NUM_PARTICLES * 3)
this.opacities = new Float32Array(NUM_PARTICLES)
this.sizes = new Float32Array(NUM_PARTICLES)
for (var i = 0; i < NUM_PARTICLES; i++) {
const mover = new NewtonParticle()
mover.setPosition(this.getInitialPosition())
var h = randomInt(0, 45);
var s = randomInt(60, 90);
var color = new THREE.Color('hsl(' + h + ', ' + s + '%, 50%)');
color.setHSL((180+Math.random()*40)/360, 1.0, 0.5 + Math.random() * 0.2);
const accel = new THREE.Vector3(0, -0.001, 0)
accel.divideScalar(10)
mover.setVelocity(this.getInitialVelocity())
mover.setAcceleration(accel)
mover.setSize(random(0.1, 1))
this.particles.push(mover);
this.positions[i * 3 + 0] = mover.getPosition().x;
this.positions[i * 3 + 1] = mover.getPosition().y;
this.positions[i * 3 + 2] = mover.getPosition().z;
color.toArray(this.colors, i * 3);
this.opacities[i] = mover.getAlpha()
this.sizes[i] = mover.getSize()
}
this.addAttribute('position', new THREE.BufferAttribute(this.positions, 3));
this.addAttribute('customColor', new THREE.BufferAttribute(this.colors, 3));
this.addAttribute('vertexOpacity', new THREE.BufferAttribute(this.opacities, 1));
this.addAttribute('size', new THREE.BufferAttribute(this.sizes, 1));
}
/**
* Update function
* @param {number} time Time
*/
update(time) {
this.updateMover()
this.attributes.position.needsUpdate = true;
this.attributes.vertexOpacity.needsUpdate = true;
this.attributes.size.needsUpdate = true;
this.attributes.customColor.needsUpdate = true;
}
getInitialPosition() {
return new THREE.Vector3(random(-2, 2), random(3, 5), random(-1, 1))
}
getInitialVelocity() {
const vel = new THREE.Vector3(random(-0.01, 0.01), random(-0.1, -0.2), random(-0.01, 0.01))
vel.divideScalar(10)
return vel
}
setRaining(raining) {
for (var i = 0; i < this.particles.length; i++) {
var mover = this.particles[i];
mover.setActive(raining)
mover.setPosition(this.getInitialPosition())
}
}
updateMover() {
for (var i = 0; i < this.particles.length; i++) {
var mover = this.particles[i];
if (mover.getActive()) {
mover.updateVelocity();
mover.updatePosition();
mover.getPosition().sub(this.points.position);
this.positions[i * 3 + 0] = mover.getPosition().x - this.points.position.x;
this.positions[i * 3 + 1] = mover.getPosition().y - this.points.position.y;
this.positions[i * 3 + 2] = mover.getPosition().z - this.points.position.z;
this.opacities[i] = mover.getAlpha()
this.sizes[i] = mover.getSize()
if (mover.getPosition().y < 0) {
mover.setPosition(this.getInitialPosition())
mover.setVelocity(this.getInitialVelocity())
}
}
}
}
}
export default RainGeometry;
|
module.exports = {
"rules": {
"no-console": 0
},
}
|
/**
* @author Phuluong
* December 27, 2015
*/
/** Exports **/
module.exports = new SocketIOConnection();
/** Imports **/
var event = require(__dir + "/core/app/event");
/** Classes **/
function SocketIOConnection() {
this.messageListeners = [];
this.connectionListeners = [];
this.io = require("socket.io");
/**
* Add A messsage listener
* @param {interface[onClientMessage]} listener
* @returns {bool}
*/
this.addMessageListener = function (namespace, listener) {
this.messageListeners[namespace] = listener;
};
/**
* Add a messsage listener
* @param {function} listener
* @returns {bool}
*/
this.addConnectionListener = function (listener) {
this.connectionListeners.push(listener);
};
this.sendMessage = function (toUserId, type, message, ignoredClientSession) {
var users = this.sessionManager.getUserSessions(toUserId);
for (var i = 0; i < users.length; i++) {
if (ignoredClientSession != null && users[i].socket === ignoredClientSession.socket) {
continue;
}
users[i].socket.emit(type, message);
}
};
this.sendMessageToSession = function (session, type, message) {
session.socket.emit(type, message);
};
this.broadcastMessage = function (type, message) {
var users = this.sessionManager.getSocketIOSessions();
for (var i = 0; i < users.length; i++) {
users[i].socket.emit(type, message);
}
};
this.listen = function (httpServer, sessionManager) {
var self = this;
this.sessionManager = sessionManager;
socketIO = self.io(httpServer.getServer());
socketIO.sockets.on("connection", function (socket) {
// Initialize session
var session = self.sessionManager.initSocketIOSession(socket);
// Fire connection event
onConnectionEvent.bind(self)("connection", session);
socket.on("disconnect", function () {
onConnectionEvent.bind(self)("disconnect", session);
});
// Receive a message from the client
bindSocketMessageToListeners.bind(self)(socket, session);
});
};
/** Utils **/
function bindSocketMessageToListeners(socket, session) {
var self = this;
for (var namespace in self.messageListeners) {
if (self.messageListeners[namespace] != null) {
socket.on(namespace, function (data) {
self.messageListeners[namespace](data, session);
});
}
}
}
function onConnectionEvent(type, session) {
// Fire event
event.fire("connection.socketio." + type, session);
// Remove from sessions
if (type === "disconnect") {
this.sessionManager.destroy(session);
}
// Pass event to listeners
for (var i = 0; i < this.connectionListeners.length; i++) {
try {
this.connectionListeners[i](type, session);
} catch (exc) {
}
}
}
} |
var assert = require('assert');
var largestOfFour = require('../basic/largestOfFour').largestOfFour;
describe('largestOfFour', function() {
it('should return [27,5,39,1001] when arr is [[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]]', function() {
assert.deepEqual([27,5,39,1001], largestOfFour([[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]]));
});
it('should return [9, 35, 97, 1000000] when arr is [[4, 9, 1, 3], [13, 35, 18, 26], [32, 35, 97, 39], [1000000, 1001, 857, 1]]', function() {
assert.deepEqual([9, 35, 97, 1000000], largestOfFour([[4, 9, 1, 3], [13, 35, 18, 26], [32, 35, 97, 39], [1000000, 1001, 857, 1]]));
});
}); |
(function (angular) {
angular.module('shiverview')
.controller('progressCtrl', ['$scope', 'ngProgressFactory', function ($scope, ngProgressFactory) {
$scope.bar = ngProgressFactory.createInstance();
$scope.bar.setColor('#0091bf');
$scope.$on('$routeChangeStart', function (e) {
$scope.bar.reset();
$scope.bar.start();
});
$scope.$on('$routeChangeSuccess', function (e) {
$scope.bar.complete();
});
$scope.$on('$routeChangeError', function (e) {
$scope.bar.reset();
});
$scope.$on('setProgress', function (e, arg) {
if (arg === 0)
$scope.bar.start();
else if (arg >= 100)
$scope.bar.complete();
else if (arg < 0)
$scope.bar.reset();
else
$scope.bar.set(arg);
});
}])
.controller('bodyCtrl', ['$scope', '$http', function ($scope, $http) {
setTimeout(function () {
$scope.initDone = true;
}, 10);
}])
.controller('navCtrl', ['$scope', '$http', '$location', '$swipe', function ($scope, $http, $location, $swipe) {
$scope.$loc = $location;
$scope.collapsed = true;
$scope.toggleCollapse = function () {
$scope.collapsed = !$scope.collapsed;
};
$scope.updateNav = function () {
$http({
url: '/routes',
method: 'get'
}).then(function (res) {
if (res.data instanceof Array) {
res.data.sort(function (a, b) {return a.index - b.index});
$scope.navList = res.data;
}
});
};
$scope.checkActive = function (input) {
if (typeof input === 'undefined') return false;
return $location.path().search(input) === 0;
};
$scope.drawerAnimated = true;
$scope.drawer = document.getElementById('drawer');
var startCoords = {};
$swipe.bind(angular.element($scope.drawer), {
start: function (coords, e) {
startCoords = coords;
},
move: function (coords, e) {
var delta = startCoords.x - coords.x;
if (delta > 10)
$scope.$apply('drawerAnimated=false');
if (delta > 0)
$scope.drawer.style.left = '-' + (delta + Math.pow(1.5, delta/10 - 7)) + 'px';
},
end: function (coords, e) {
$scope.$apply('drawerAnimated=true');
if (startCoords.x - coords.x > 80)
$scope.$apply('drawerActive=false');
setTimeout(function () {
$scope.drawer.removeAttribute('style');
}, 200);
}
});
$scope.toggleDrawer = function () {
$scope.drawer.removeAttribute('style');
$scope.drawerAnimated = true;
$scope.drawerActive = !$scope.drawerActive;
};
$scope.updateNav();
$scope.$on('userStatusUpdate', $scope.updateNav);
$scope.$on('$routeChangeStart', function () {
$scope.drawerActive = false;
});
}])
.controller('toastCtrl', ['$scope', function ($scope) {
$scope.show = false;
$scope.display = function (style, msg) {
$scope.style = style;
$scope.message = msg;
$scope.show = true;
};
$scope.dismiss = function () {
$scope.show = false;
};
$scope.$on('errorMessage', function (e, msg) {
$scope.display('alert-danger', msg);
});
$scope.$on('warningMessage', function (e, msg) {
$scope.display('alert-warning', msg);
});
$scope.$on('infoMessage', function (e, msg) {
$scope.display('alert-info', msg);
});
$scope.$on('successMessage', function (e, msg) {
$scope.display('alert-success', msg);
});
}])
})(window.angular);
|
'use strict'
// Require
const fs = require( 'fs' )
const path = require( 'path' )
const { isDirectory, isFile, isExternal } = require( './is' )
/**
* Check all blocks and read jsons & deps then sort levels and write map.
*
* @param {Object} task
*
* @return {undefined}
*/
module.exports = function ( task ) {
// Options
const { paths, store, config, notify } = task
const levels = ( store.levels = [] )
const jsons = ( store.jsons = {} )
const deps = ( store.deps = {} )
const root = paths._root
const blocks = paths._blocks
const sortLevels = config.levels
const pugMap = config.build.pugMap
const mapPath = pugMap ? path.join( root, pugMap ) : false
const template = config.use.templates
try {
let writeMap = ( mapPath && template === '.pug' )
let mapContent = ''
// Read blocks
fs.readdirSync( blocks ).forEach( level => {
if ( !isDirectory( paths.blocks( level ) ) ) return
levels.push( level )
fs.readdirSync( paths.blocks( level ) ).forEach( block => {
const json = paths.blocks( level, block, 'data.json' )
const use = paths.blocks( level, block, 'deps.js' )
if ( !isDirectory( paths.blocks( level, block ) ) ) return
if ( writeMap ) fs.readdirSync( paths.blocks( level, block ) ).forEach( file => {
if ( path.extname( file ) !== template ) return
if ( path.basename( file, path.extname( file ) ) === 'layout' ) return
file = path.join( path.relative( path.dirname( mapPath ), blocks ), level, block, file )
mapContent += ( mapContent === '' ? '' : '\n' ) + `include ${file}`
})
// Read json
if ( isFile( json ) ) {
try {
const data = JSON.parse( fs.readFileSync( json ) )
if ( !jsons[block] )
jsons[block] = data
else
jsons[block] = Object.assign( jsons[block], data )
} catch (e) {
throw new Error( `\n\n\x1b[41mFAIL\x1b[0m: A JSON "\x1b[36m${path.join( level, block, 'data.json' )}\x1b[0m" have SyntaxError:\n${e.message}\n\n` )
}
}
// Read deps
if ( isFile( use ) ) {
delete require.cache[ require.resolve( use ) ]
const data = require( use )
if ( data && Array.isArray( data.modules ) ) {
data.modules.forEach( obj => {
if ( !obj || obj.constructor !== Object ) return
if ( !obj.from || typeof obj.from !== 'string' )
return ( obj.from = path.join( blocks, level, block, 'assets' ) )
if ( isExternal( obj.from ) ) return
return ( obj.from = path.join( root, obj.from ) )
})
}
if ( !deps[block] ) {
if ( data ) deps[block] = {
nodes: Array.isArray( data.nodes ) ? data.nodes : [],
modules: Array.isArray( data.modules ) ? data.modules : []
}
} else {
if ( data ) deps[block] = {
nodes: Array.isArray( data.nodes ) ? deps[block].nodes.concat( data.nodes ) : deps[block].nodes,
modules: Array.isArray( data.modules ) ? deps[block].modules.concat( data.modules ) : deps[block].modules
}
}
}
})
})
// Sort levels
levels.sort( ( one, two ) => {
const a = sortLevels && sortLevels[one] || 2
const b = sortLevels && sortLevels[two] || 2
if ( a > b ) return 1
if ( a < b ) return -1
})
// Write map
if ( writeMap ) {
if ( !isDirectory( path.dirname( mapPath ) ) ) fs.mkdirSync( path.dirname( mapPath ) )
fs.writeFileSync( mapPath, mapContent, 'utf8' )
}
} catch (e) {
console.log(e)
notify.onError( 'Error' )(e)
}
}
|
//function returning an object.
let getData = (num) => ({id : num});
//arrow function in map
let result = [1, 2, 3, 4].map(item => item * 2);
|
(function () {
'use strict';
/**
* @ngdoc overview
* @name ui.grid.rowEdit
* @description
*
* # ui.grid.rowEdit
*
* <div class="alert alert-success" role="alert"><strong>Stable</strong> This feature is stable. There should no longer be breaking api changes without a deprecation warning.</div>
*
* This module extends the edit feature to provide tracking and saving of rows
* of data. The tutorial provides more information on how this feature is best
* used {@link tutorial/205_row_editable here}.
* <br/>
* This feature depends on usage of the ui-grid-edit feature, and also benefits
* from use of ui-grid-cellNav to provide the full spreadsheet-like editing
* experience
*
*/
var module = angular.module('ui.grid.ie.rowEdit', ['ui.grid.ie', 'ui.grid.ie.edit', 'ui.grid.ie.cellNav']);
/**
* @ngdoc object
* @name ui.grid.rowEdit.constant:uiGridRowEditConstants
*
* @description constants available in row edit module
*/
module.constant('uiGridRowEditConstants', {
});
/**
* @ngdoc service
* @name ui.grid.rowEdit.service:uiGridRowEditService
*
* @description Services for row editing features
*/
module.service('uiGridRowEditService', ['$interval', '$q', 'uiGridConstants', 'uiGridRowEditConstants', 'gridUtil',
function ($interval, $q, uiGridConstants, uiGridRowEditConstants, gridUtil) {
var service = {
initializeGrid: function (scope, grid) {
/**
* @ngdoc object
* @name ui.grid.rowEdit.api:PublicApi
*
* @description Public Api for rowEdit feature
*/
grid.rowEdit = {};
var publicApi = {
events: {
rowEdit: {
/**
* @ngdoc event
* @eventOf ui.grid.rowEdit.api:PublicApi
* @name saveRow
* @description raised when a row is ready for saving. Once your
* row has saved you may need to use angular.extend to update the
* data entity with any changed data from your save (for example,
* lock version information if you're using optimistic locking,
* or last update time/user information).
*
* Your method should call setSavePromise somewhere in the body before
* returning control. The feature will then wait, with the gridRow greyed out
* whilst this promise is being resolved.
*
* <pre>
* gridApi.rowEdit.on.saveRow(scope,function(rowEntity){})
* </pre>
* and somewhere within the event handler:
* <pre>
* gridApi.rowEdit.setSavePromise( rowEntity, savePromise)
* </pre>
* @param {object} rowEntity the options.data element that was edited
* @returns {promise} Your saveRow method should return a promise, the
* promise should either be resolved (implying successful save), or
* rejected (implying an error).
*/
saveRow: function (rowEntity) {
}
}
},
methods: {
rowEdit: {
/**
* @ngdoc method
* @methodOf ui.grid.rowEdit.api:PublicApi
* @name setSavePromise
* @description Sets the promise associated with the row save, mandatory that
* the saveRow event handler calls this method somewhere before returning.
* <pre>
* gridApi.rowEdit.setSavePromise(rowEntity, savePromise)
* </pre>
* @param {object} rowEntity a data row from the grid for which a save has
* been initiated
* @param {promise} savePromise the promise that will be resolved when the
* save is successful, or rejected if the save fails
*
*/
setSavePromise: function ( rowEntity, savePromise) {
service.setSavePromise(grid, rowEntity, savePromise);
},
/**
* @ngdoc method
* @methodOf ui.grid.rowEdit.api:PublicApi
* @name getDirtyRows
* @description Returns all currently dirty rows
* <pre>
* gridApi.rowEdit.getDirtyRows(grid)
* </pre>
* @returns {array} An array of gridRows that are currently dirty
*
*/
getDirtyRows: function () {
return grid.rowEdit.dirtyRows ? grid.rowEdit.dirtyRows : [];
},
/**
* @ngdoc method
* @methodOf ui.grid.rowEdit.api:PublicApi
* @name getErrorRows
* @description Returns all currently errored rows
* <pre>
* gridApi.rowEdit.getErrorRows(grid)
* </pre>
* @returns {array} An array of gridRows that are currently in error
*
*/
getErrorRows: function () {
return grid.rowEdit.errorRows ? grid.rowEdit.errorRows : [];
},
/**
* @ngdoc method
* @methodOf ui.grid.rowEdit.api:PublicApi
* @name flushDirtyRows
* @description Triggers a save event for all currently dirty rows, could
* be used where user presses a save button or navigates away from the page
* <pre>
* gridApi.rowEdit.flushDirtyRows(grid)
* </pre>
* @returns {promise} a promise that represents the aggregate of all
* of the individual save promises - i.e. it will be resolved when all
* the individual save promises have been resolved.
*
*/
flushDirtyRows: function () {
return service.flushDirtyRows(grid);
},
/**
* @ngdoc method
* @methodOf ui.grid.rowEdit.api:PublicApi
* @name setRowsDirty
* @description Sets each of the rows passed in dataRows
* to be dirty. note that if you have only just inserted the
* rows into your data you will need to wait for a $digest cycle
* before the gridRows are present - so often you would wrap this
* call in a $interval or $timeout
* <pre>
* $interval( function() {
* gridApi.rowEdit.setRowsDirty(myDataRows);
* }, 0, 1);
* </pre>
* @param {array} dataRows the data entities for which the gridRows
* should be set dirty.
*
*/
setRowsDirty: function ( dataRows) {
service.setRowsDirty(grid, dataRows);
},
/**
* @ngdoc method
* @methodOf ui.grid.rowEdit.api:PublicApi
* @name setRowsClean
* @description Sets each of the rows passed in dataRows
* to be clean, removing them from the dirty cache and the error cache,
* and clearing the error flag and the dirty flag
* <pre>
* var gridRows = $scope.gridApi.rowEdit.getDirtyRows();
* var dataRows = gridRows.map( function( gridRow ) { return gridRow.entity; });
* $scope.gridApi.rowEdit.setRowsClean( dataRows );
* </pre>
* @param {array} dataRows the data entities for which the gridRows
* should be set clean.
*
*/
setRowsClean: function ( dataRows) {
service.setRowsClean(grid, dataRows);
}
}
}
};
grid.api.registerEventsFromObject(publicApi.events);
grid.api.registerMethodsFromObject(publicApi.methods);
grid.api.core.on.renderingComplete( scope, function ( gridApi ) {
grid.api.edit.on.afterCellEdit( scope, service.endEditCell );
grid.api.edit.on.beginCellEdit( scope, service.beginEditCell );
grid.api.edit.on.cancelCellEdit( scope, service.cancelEditCell );
if ( grid.api.cellNav ) {
grid.api.cellNav.on.navigate( scope, service.navigate );
}
});
},
defaultGridOptions: function (gridOptions) {
/**
* @ngdoc object
* @name ui.grid.rowEdit.api:GridOptions
*
* @description Options for configuring the rowEdit feature, these are available to be
* set using the ui-grid {@link ui.grid.class:GridOptions gridOptions}
*/
},
/**
* @ngdoc method
* @methodOf ui.grid.rowEdit.service:uiGridRowEditService
* @name saveRow
* @description Returns a function that saves the specified row from the grid,
* and returns a promise
* @param {object} grid the grid for which dirty rows should be flushed
* @param {GridRow} gridRow the row that should be saved
* @returns {function} the saveRow function returns a function. That function
* in turn, when called, returns a promise relating to the save callback
*/
saveRow: function ( grid, gridRow ) {
var self = this;
return function() {
gridRow.isSaving = true;
if ( gridRow.rowEditSavePromise ){
// don't save the row again if it's already saving - that causes stale object exceptions
return gridRow.rowEditSavePromise;
}
var promise = grid.api.rowEdit.raise.saveRow( gridRow.entity );
if ( gridRow.rowEditSavePromise ){
gridRow.rowEditSavePromise.then( self.processSuccessPromise( grid, gridRow ), self.processErrorPromise( grid, gridRow ));
} else {
gridUtil.logError( 'A promise was not returned when saveRow event was raised, either nobody is listening to event, or event handler did not return a promise' );
}
return promise;
};
},
/**
* @ngdoc method
* @methodOf ui.grid.rowEdit.service:uiGridRowEditService
* @name setSavePromise
* @description Sets the promise associated with the row save, mandatory that
* the saveRow event handler calls this method somewhere before returning.
* <pre>
* gridApi.rowEdit.setSavePromise(grid, rowEntity)
* </pre>
* @param {object} grid the grid for which dirty rows should be returned
* @param {object} rowEntity a data row from the grid for which a save has
* been initiated
* @param {promise} savePromise the promise that will be resolved when the
* save is successful, or rejected if the save fails
*
*/
setSavePromise: function (grid, rowEntity, savePromise) {
var gridRow = grid.getRow( rowEntity );
gridRow.rowEditSavePromise = savePromise;
},
/**
* @ngdoc method
* @methodOf ui.grid.rowEdit.service:uiGridRowEditService
* @name processSuccessPromise
* @description Returns a function that processes the successful
* resolution of a save promise
* @param {object} grid the grid for which the promise should be processed
* @param {GridRow} gridRow the row that has been saved
* @returns {function} the success handling function
*/
processSuccessPromise: function ( grid, gridRow ) {
var self = this;
return function() {
delete gridRow.isSaving;
delete gridRow.isDirty;
delete gridRow.isError;
delete gridRow.rowEditSaveTimer;
delete gridRow.rowEditSavePromise;
self.removeRow( grid.rowEdit.errorRows, gridRow );
self.removeRow( grid.rowEdit.dirtyRows, gridRow );
};
},
/**
* @ngdoc method
* @methodOf ui.grid.rowEdit.service:uiGridRowEditService
* @name processErrorPromise
* @description Returns a function that processes the failed
* resolution of a save promise
* @param {object} grid the grid for which the promise should be processed
* @param {GridRow} gridRow the row that is now in error
* @returns {function} the error handling function
*/
processErrorPromise: function ( grid, gridRow ) {
return function() {
delete gridRow.isSaving;
delete gridRow.rowEditSaveTimer;
delete gridRow.rowEditSavePromise;
gridRow.isError = true;
if (!grid.rowEdit.errorRows){
grid.rowEdit.errorRows = [];
}
if (!service.isRowPresent( grid.rowEdit.errorRows, gridRow ) ){
grid.rowEdit.errorRows.push( gridRow );
}
};
},
/**
* @ngdoc method
* @methodOf ui.grid.rowEdit.service:uiGridRowEditService
* @name removeRow
* @description Removes a row from a cache of rows - either
* grid.rowEdit.errorRows or grid.rowEdit.dirtyRows. If the row
* is not present silently does nothing.
* @param {array} rowArray the array from which to remove the row
* @param {GridRow} gridRow the row that should be removed
*/
removeRow: function( rowArray, removeGridRow ){
if (typeof(rowArray) === 'undefined' || rowArray === null){
return;
}
rowArray.forEach( function( gridRow, index ){
if ( gridRow.uid === removeGridRow.uid ){
rowArray.splice( index, 1);
}
});
},
/**
* @ngdoc method
* @methodOf ui.grid.rowEdit.service:uiGridRowEditService
* @name isRowPresent
* @description Checks whether a row is already present
* in the given array
* @param {array} rowArray the array in which to look for the row
* @param {GridRow} gridRow the row that should be looked for
*/
isRowPresent: function( rowArray, removeGridRow ){
var present = false;
rowArray.forEach( function( gridRow, index ){
if ( gridRow.uid === removeGridRow.uid ){
present = true;
}
});
return present;
},
/**
* @ngdoc method
* @methodOf ui.grid.rowEdit.service:uiGridRowEditService
* @name flushDirtyRows
* @description Triggers a save event for all currently dirty rows, could
* be used where user presses a save button or navigates away from the page
* <pre>
* gridApi.rowEdit.flushDirtyRows(grid)
* </pre>
* @param {object} grid the grid for which dirty rows should be flushed
* @returns {promise} a promise that represents the aggregate of all
* of the individual save promises - i.e. it will be resolved when all
* the individual save promises have been resolved.
*
*/
flushDirtyRows: function(grid){
var promises = [];
grid.api.rowEdit.getDirtyRows().forEach( function( gridRow ){
service.saveRow( grid, gridRow )();
promises.push( gridRow.rowEditSavePromise );
});
return $q.all( promises );
},
/**
* @ngdoc method
* @methodOf ui.grid.rowEdit.service:uiGridRowEditService
* @name endEditCell
* @description Receives an afterCellEdit event from the edit function,
* and sets flags as appropriate. Only the rowEntity parameter
* is processed, although other params are available. Grid
* is automatically provided by the gridApi.
* @param {object} rowEntity the data entity for which the cell
* was edited
*/
endEditCell: function( rowEntity, colDef, newValue, previousValue ){
var grid = this.grid;
var gridRow = grid.getRow( rowEntity );
if ( !gridRow ){ gridUtil.logError( 'Unable to find rowEntity in grid data, dirty flag cannot be set' ); return; }
if ( newValue !== previousValue || gridRow.isDirty ){
if ( !grid.rowEdit.dirtyRows ){
grid.rowEdit.dirtyRows = [];
}
if ( !gridRow.isDirty ){
gridRow.isDirty = true;
grid.rowEdit.dirtyRows.push( gridRow );
}
delete gridRow.isError;
service.considerSetTimer( grid, gridRow );
}
},
/**
* @ngdoc method
* @methodOf ui.grid.rowEdit.service:uiGridRowEditService
* @name beginEditCell
* @description Receives a beginCellEdit event from the edit function,
* and cancels any rowEditSaveTimers if present, as the user is still editing
* this row. Only the rowEntity parameter
* is processed, although other params are available. Grid
* is automatically provided by the gridApi.
* @param {object} rowEntity the data entity for which the cell
* editing has commenced
*/
beginEditCell: function( rowEntity, colDef ){
var grid = this.grid;
var gridRow = grid.getRow( rowEntity );
if ( !gridRow ){ gridUtil.logError( 'Unable to find rowEntity in grid data, timer cannot be cancelled' ); return; }
service.cancelTimer( grid, gridRow );
},
/**
* @ngdoc method
* @methodOf ui.grid.rowEdit.service:uiGridRowEditService
* @name cancelEditCell
* @description Receives a cancelCellEdit event from the edit function,
* and if the row was already dirty, restarts the save timer. If the row
* was not already dirty, then it's not dirty now either and does nothing.
*
* Only the rowEntity parameter
* is processed, although other params are available. Grid
* is automatically provided by the gridApi.
*
* @param {object} rowEntity the data entity for which the cell
* editing was cancelled
*/
cancelEditCell: function( rowEntity, colDef ){
var grid = this.grid;
var gridRow = grid.getRow( rowEntity );
if ( !gridRow ){ gridUtil.logError( 'Unable to find rowEntity in grid data, timer cannot be set' ); return; }
service.considerSetTimer( grid, gridRow );
},
/**
* @ngdoc method
* @methodOf ui.grid.rowEdit.service:uiGridRowEditService
* @name navigate
* @description cellNav tells us that the selected cell has changed. If
* the new row had a timer running, then stop it similar to in a beginCellEdit
* call. If the old row is dirty and not the same as the new row, then
* start a timer on it.
* @param {object} newRowCol the row and column that were selected
* @param {object} oldRowCol the row and column that was left
*
*/
navigate: function( newRowCol, oldRowCol ){
var grid = this.grid;
if ( newRowCol.row.rowEditSaveTimer ){
service.cancelTimer( grid, newRowCol.row );
}
if ( oldRowCol && oldRowCol.row && oldRowCol.row !== newRowCol.row ){
service.considerSetTimer( grid, oldRowCol.row );
}
},
/**
* @ngdoc property
* @propertyOf ui.grid.rowEdit.api:GridOptions
* @name rowEditWaitInterval
* @description How long the grid should wait for another change on this row
* before triggering a save (in milliseconds). If set to -1, then saves are
* never triggered by timer (implying that the user will call flushDirtyRows()
* manually)
*
* @example
* Setting the wait interval to 4 seconds
* <pre>
* $scope.gridOptions = { rowEditWaitInterval: 4000 }
* </pre>
*
*/
/**
* @ngdoc method
* @methodOf ui.grid.rowEdit.service:uiGridRowEditService
* @name considerSetTimer
* @description Consider setting a timer on this row (if it is dirty). if there is a timer running
* on the row and the row isn't currently saving, cancel it, using cancelTimer, then if the row is
* dirty and not currently saving then set a new timer
* @param {object} grid the grid for which we are processing
* @param {GridRow} gridRow the row for which the timer should be adjusted
*
*/
considerSetTimer: function( grid, gridRow ){
service.cancelTimer( grid, gridRow );
if ( gridRow.isDirty && !gridRow.isSaving ){
if ( grid.options.rowEditWaitInterval !== -1 ){
var waitTime = grid.options.rowEditWaitInterval ? grid.options.rowEditWaitInterval : 2000;
gridRow.rowEditSaveTimer = $interval( service.saveRow( grid, gridRow ), waitTime, 1);
}
}
},
/**
* @ngdoc method
* @methodOf ui.grid.rowEdit.service:uiGridRowEditService
* @name cancelTimer
* @description cancel the $interval for any timer running on this row
* then delete the timer itself
* @param {object} grid the grid for which we are processing
* @param {GridRow} gridRow the row for which the timer should be adjusted
*
*/
cancelTimer: function( grid, gridRow ){
if ( gridRow.rowEditSaveTimer && !gridRow.isSaving ){
$interval.cancel(gridRow.rowEditSaveTimer);
delete gridRow.rowEditSaveTimer;
}
},
/**
* @ngdoc method
* @methodOf ui.grid.rowEdit.service:uiGridRowEditService
* @name setRowsDirty
* @description Sets each of the rows passed in dataRows
* to be dirty. note that if you have only just inserted the
* rows into your data you will need to wait for a $digest cycle
* before the gridRows are present - so often you would wrap this
* call in a $interval or $timeout
* <pre>
* $interval( function() {
* gridApi.rowEdit.setRowsDirty( myDataRows);
* }, 0, 1);
* </pre>
* @param {object} grid the grid for which rows should be set dirty
* @param {array} dataRows the data entities for which the gridRows
* should be set dirty.
*
*/
setRowsDirty: function( grid, myDataRows ) {
var gridRow;
myDataRows.forEach( function( value, index ){
gridRow = grid.getRow( value );
if ( gridRow ){
if ( !grid.rowEdit.dirtyRows ){
grid.rowEdit.dirtyRows = [];
}
if ( !gridRow.isDirty ){
gridRow.isDirty = true;
grid.rowEdit.dirtyRows.push( gridRow );
}
delete gridRow.isError;
service.considerSetTimer( grid, gridRow );
} else {
gridUtil.logError( "requested row not found in rowEdit.setRowsDirty, row was: " + value );
}
});
},
/**
* @ngdoc method
* @methodOf ui.grid.rowEdit.service:uiGridRowEditService
* @name setRowsClean
* @description Sets each of the rows passed in dataRows
* to be clean, clearing the dirty flag and the error flag, and removing
* the rows from the dirty and error caches.
* @param {object} grid the grid for which rows should be set clean
* @param {array} dataRows the data entities for which the gridRows
* should be set clean.
*
*/
setRowsClean: function( grid, myDataRows ) {
var gridRow;
myDataRows.forEach( function( value, index ){
gridRow = grid.getRow( value );
if ( gridRow ){
delete gridRow.isDirty;
service.removeRow( grid.rowEdit.dirtyRows, gridRow );
service.cancelTimer( grid, gridRow );
delete gridRow.isError;
service.removeRow( grid.rowEdit.errorRows, gridRow );
} else {
gridUtil.logError( "requested row not found in rowEdit.setRowsClean, row was: " + value );
}
});
}
};
return service;
}]);
/**
* @ngdoc directive
* @name ui.grid.rowEdit.directive:uiGridEdit
* @element div
* @restrict A
*
* @description Adds row editing features to the ui-grid-edit directive.
*
*/
module.directive('uiGridRowEdit', ['gridUtil', 'uiGridRowEditService', 'uiGridEditConstants',
function (gridUtil, uiGridRowEditService, uiGridEditConstants) {
return {
replace: true,
priority: 0,
require: '^uiGrid',
scope: false,
compile: function () {
return {
pre: function ($scope, $elm, $attrs, uiGridCtrl) {
uiGridRowEditService.initializeGrid($scope, uiGridCtrl.grid);
},
post: function ($scope, $elm, $attrs, uiGridCtrl) {
}
};
}
};
}]);
/**
* @ngdoc directive
* @name ui.grid.rowEdit.directive:uiGridViewport
* @element div
*
* @description Stacks on top of ui.grid.uiGridViewport to alter the attributes used
* for the grid row to allow coloring of saving and error rows
*/
module.directive('uiGridViewport',
['$compile', 'uiGridConstants', 'gridUtil', '$parse',
function ($compile, uiGridConstants, gridUtil, $parse) {
return {
priority: -200, // run after default directive
scope: false,
compile: function ($elm, $attrs) {
var rowRepeatDiv = angular.element($elm.children().children()[0]);
var existingNgClass = rowRepeatDiv.attr("ng-class");
var newNgClass = '';
if ( existingNgClass ) {
newNgClass = existingNgClass.slice(0, -1) + ", 'ui-grid-row-dirty': row.isDirty, 'ui-grid-row-saving': row.isSaving, 'ui-grid-row-error': row.isError}";
} else {
newNgClass = "{'ui-grid-row-dirty': row.isDirty, 'ui-grid-row-saving': row.isSaving, 'ui-grid-row-error': row.isError}";
}
rowRepeatDiv.attr("ng-class", newNgClass);
return {
pre: function ($scope, $elm, $attrs, controllers) {
},
post: function ($scope, $elm, $attrs, controllers) {
}
};
}
};
}]);
})();
|
import CodeMirror from 'codemirror';
import Ember from 'ember';
import { moduleForComponent, test } from 'ember-qunit';
moduleForComponent('ivy-codemirror', {
unit: true
});
test('should update value property when CodeMirror changes', function(assert) {
var component = this.subject();
this.render();
var codeMirror = component.get('codeMirror');
Ember.run(function() {
codeMirror.setValue('1 + 1');
CodeMirror.signal(codeMirror, 'change', codeMirror);
});
assert.equal(component.get('value'), '1 + 1', 'value is updated');
});
test('should send valueUpdated action when CodeMirror changes', function(assert) {
var targetObject = Ember.Object.extend({
called: false,
valueUpdated: function() {
this.set('called', true);
}
}).create();
var component = this.subject({ targetObject: targetObject, valueUpdated: "valueUpdated" });
this.render();
var codeMirror = component.get('codeMirror');
Ember.run(function() {
codeMirror.setValue('1 + 1');
CodeMirror.signal(codeMirror, 'change', codeMirror);
});
assert.ok(targetObject.get('called'), 'valueUpdated action was sent');
});
test('should update CodeMirror value when value property is changed', function(assert) {
var component = this.subject();
this.render();
var codeMirror = component.get('codeMirror');
assert.equal(codeMirror.getValue(), '', 'precond - value is empty');
Ember.run(function() {
component.set('value', '1 + 1');
});
assert.equal(codeMirror.getValue(), '1 + 1', 'value is updated');
});
function optionTest(key, beforeValue, afterValue) {
test('should update CodeMirror ' + key + ' option when ' + key + ' property changes', function(assert) {
var component = this.subject();
this.render();
var codeMirror = component.get('codeMirror');
assert.equal(
codeMirror.getOption(key), beforeValue,
'precond - initial value of ' + key + ' option is correct');
Ember.run(function() {
component.set(key, afterValue);
});
assert.equal(
codeMirror.getOption(key), afterValue,
key + ' option is updated after ' + key + ' property is changed');
});
test('should update CodeMirror ' + key + ' option when bound to a property whose dependencies change', function(assert) {
var context = Ember.Object.extend({
computedValue: Ember.computed.readOnly('actualValue')
}).create({
actualValue: beforeValue
});
var componentOptions = { foo: context };
componentOptions[key + 'Binding'] = 'foo.computedValue';
var component = this.subject(componentOptions);
this.render();
var codeMirror = component.get('codeMirror');
assert.equal(
codeMirror.getOption(key), beforeValue,
'precond - initial value of ' + key + ' option is correct');
Ember.run(function() {
context.set('actualValue', afterValue);
});
assert.equal(
codeMirror.getOption(key), afterValue,
key + ' option is updated after ' + key + ' property is changed');
});
}
optionTest('autofocus', false, true);
optionTest('coverGutterNextToScrollbar', false, true);
optionTest('electricChars', true, false);
optionTest('extraKeys', null, 'basic');
optionTest('firstLineNumber', 1, 2);
optionTest('fixedGutter', true, false);
optionTest('historyEventDelay', 1250, 500);
optionTest('indentUnit', 2, 4);
optionTest('indentWithTabs', false, true);
optionTest('keyMap', 'default', 'basic');
optionTest('lineNumbers', false, true);
optionTest('lineWrapping', false, true);
optionTest('mode', null, 'ruby');
optionTest('readOnly', false, true);
optionTest('rtlMoveVisually', true, false);
optionTest('showCursorWhenSelecting', false, true);
optionTest('smartIndent', true, false);
optionTest('tabSize', 4, 2);
optionTest('tabindex', null, 1);
optionTest('theme', 'default', 'twilight');
optionTest('undoDepth', 200, 100);
test('should refresh when isVisible becomes true', function(assert) {
var component = this.subject();
this.render();
var codeMirror = component.get('codeMirror'),
refreshCalls = 0;
codeMirror.refresh = function() {
refreshCalls++;
};
Ember.run(function() {
component.set('isVisible', false);
});
assert.equal(refreshCalls, 0);
Ember.run(function() {
component.set('isVisible', true);
});
assert.equal(refreshCalls, 1);
});
|
version https://git-lfs.github.com/spec/v1
oid sha256:c12a4b6c29c5070050e0f8d3493a3af24d2f3c745620e2073fbef5e79a540534
size 3968
|
/* global Document */
'use strict';
const test = require('./../helper.js');
const _ = require('lodash');
let Doc;
describe('Document model', () => {
before(test.cleanDb);
before(() => {
Doc = _.partial(test.createModel, Document);
});
describe('isValid', () => {
it('should be able to validate a document that is complete', () => {
const documentData = test.getAllDocumentData()[0];
const document = test.createModel(Document, documentData);
document.isValid().should.be.true;
});
it('should be able to reject a document that is not complete', () => {
const documentData = test.getAllDocumentData()[1];
const document = test.createModel(Document, documentData);
document.isValid().should.be.false;
});
});
describe('getFullAuthorships', () => {
it('should return empty array with empty affiliations and authorships', () => {
const documentData = test.getAllDocumentData()[0];
const document = test.createModel(Document, documentData);
document.authorships = [];
document.affiliations = [];
document.getFullAuthorships().should.be.empty;
});
it('should return a consistent structure', () => {
const documentData = test.getAllDocumentData()[0];
const document = test.createModel(Document, documentData);
document.authorships = [
{id: 103, position: 0},
{id: 105, position: 1},
{id: 101, position: 2},
{id: 102, position: 3},
{id: 104, position: 4},
];
document.affiliations = [
{id: 6, authorship: 101, institute: 1},
{id: 8, authorship: 101, institute: 2},
{id: 9, authorship: 101, institute: 3},
{id: 10, authorship: 102, institute: 4},
{id: 11, authorship: 104, institute: 5},
{id: 14, authorship: 110, institute: 6},
{id: 24, authorship: 104, institute: 10},
{id: 34, authorship: 103, institute: 11},
{id: 76, authorship: 103, institute: 12},
{id: 19, authorship: 110, institute: 13},
];
const res1 = document.getFullAuthorships();
res1.should.have.length(5);
const auth103 = res1[0];
auth103.id.should.be.equal(103);
auth103.affiliations.should.have.length(2);
auth103.affiliations[0].id.should.be.equal(34);
auth103.affiliations[1].id.should.be.equal(76);
const auth105 = res1[1];
auth105.id.should.be.equal(105);
auth105.affiliations.should.have.length(0);
const auth101 = res1[2];
auth101.id.should.be.equal(101);
auth101.affiliations.should.have.length(3);
auth101.affiliations[0].id.should.be.equal(6);
auth101.affiliations[1].id.should.be.equal(8);
auth101.affiliations[2].id.should.be.equal(9);
const auth102 = res1[3];
auth102.id.should.be.equal(102);
auth102.affiliations.should.have.length(1);
auth102.affiliations[0].id.should.be.equal(10);
const auth104 = res1[4];
auth104.id.should.be.equal(104);
auth104.affiliations.should.have.length(2);
auth104.affiliations[0].id.should.be.equal(11);
auth104.affiliations[1].id.should.be.equal(24);
});
});
const usersData = test.getAllUserData();
const documentsData = test.getAllDocumentData();
const institutesData = test.getAllInstituteData();
const iitGroupData = test.getAllGroupData()[0];
let users = [];
let document;
let institutes;
let iitGroup;
describe('findCopies', () => {
it('should only find verified documents with same data and affiliations', async () => {
//TODO move db initialization to a more suitable place
iitGroup = await Group.create(iitGroupData);
users.push(await User.createCompleteUser(usersData[0]));
users.push(await User.createCompleteUser(usersData[1]));
institutes = await Institute.create(institutesData);
const docData = _.merge({}, documentsData[5], {
authorships: [
{
position: 0,
researchEntity: null,
affiliations: [institutes[0].id, institutes[1].id]
},
{
position: 1,
researchEntity: null,
affiliations: [institutes[0].id]
},
{
position: 2,
researchEntity: null,
affiliations: [institutes[1].id]
}
]
});
const doc = await User.createDraft(User, users[0].id, docData);
doc.kind = 'v';
doc.draftCreator = null;
doc.draftGroupCreator = null;
await doc.savePromise();
document = await Document.findOneById(doc.id)
.populate('authorships')
.populate('affiliations');
const a = document.authorships.find(a => a.position === 0);
const authorship = await Authorship.findOneById(a.id);
authorship.researchEntity = users[0].id;
await authorship.savePromise();
const draftData = _.merge({}, documentsData[5], {
authorships: [
{
position: 0,
researchEntity: null,
affiliations: [institutes[0].id, institutes[1].id]
},
{
position: 1,
researchEntity: null,
affiliations: [institutes[0].id]
},
{
position: 2,
researchEntity: null,
affiliations: [institutes[1].id]
}
]
});
const d = await User.createDraft(User, users[1].id, draftData);
const draft = await Document.findOneById(d.id)
.populate('authorships')
.populate('affiliations');
const copies = await Document.findCopies(draft, 1);
copies.should.have.length(1);
copies[0].id.should.be.equal(document.id);
copies[0].affiliations.should.have.length(4);
});
it('should not find verified documents with different data', () => {
const docData = _.merge({}, documentsData[1], {
authorships: [
{
position: 0,
researchEntity: null,
affiliations: [institutes[0].id, institutes[1].id]
},
{
position: 1,
researchEntity: null,
affiliations: [institutes[0].id]
},
{
position: 2,
researchEntity: null,
affiliations: [institutes[1].id]
}
]
});
return User.createDraft(User, users[1].id, docData)
.then(d => Document.findOneById(d.id)
.populate('authorships')
.populate('affiliations'))
.then(d => Document.findCopies(d, 1))
.then(copies => copies.should.have.length(0));
});
it('should not find verified documents with different institutes on empty positions', () => {
const docData = _.merge({}, documentsData[5], {
authorships: [
{
position: 0,
researchEntity: null,
affiliations: [institutes[0].id, institutes[1].id]
},
{
position: 1,
researchEntity: null,
affiliations: [institutes[0].id]
},
{
position: 2,
researchEntity: null,
affiliations: [institutes[0].id]
}
]
});
return User.createDraft(User, users[1].id, docData)
.then(d => Document.findOneById(d.id)
.populate('authorships')
.populate('affiliations'))
.then(d => Document.findCopies(d, 1))
.then(copies => copies.should.have.length(0));
});
});
describe('getSourceDetails', () => {
it('should return a compiled reference string', () => {
const documentData = test.getAllDocumentData()[0];
const document = test.createModel(Document, documentData);
document.getSourceDetails().should.not.be.empty;
});
});
}); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.