code
stringlengths 2
1.05M
|
|---|
var example_8 = switcher.items({eventMethod: "mouseover"});
// Табы
example_8.addTabs('#tab_7 span', function () {
this.classList.add('tab_active');
}, function () {
this.classList.remove('tab_active');
});
// Блоки
example_8.addBlocks('#block_7 img', function() {
var
i=0,
that = this;
this.style.opacity = 0;
this.style.display = "block";
// Удаляем таймер от предыдущего элемента, если есть
clearInterval(example_8.varTimer);
// Таймер
example_8.varTimer = setInterval(function() {
if(i >= 1) {
clearInterval(example_8.varTimer);
}
i+=0.1;
that.style.opacity = i;
}, 50);
}, function() {
this.style.display = "none";
});
example_8.turnOn(4);
|
angular
.module('app')
.config(['$stateProvider', '$urlRouterProvider', '$ocLazyLoadProvider', '$breadcrumbProvider', '$authProvider',
function ($stateProvider, $urlRouterProvider, $ocLazyLoadProvider, $breadcrumbProvider, $authProvider) {
$urlRouterProvider.otherwise('/dashboard');
$ocLazyLoadProvider.config({
// Set to true if you want to see what and when is dynamically loaded
debug: true
});
$breadcrumbProvider.setOptions({
prefixStateName: 'app.main',
includeAbstract: true,
template: '<li class="breadcrumb-item" ng-repeat="step in steps" ng-class="{active: $last}" ng-switch="$last || !!step.abstract"><a ng-switch-when="false" href="{{step.ncyBreadcrumbLink}}">{{step.ncyBreadcrumbLabel}}</a><span ng-switch-when="true">{{step.ncyBreadcrumbLabel}}</span></li>'
});
$authProvider.httpInterceptor = function () {
return true;
}
$authProvider.withCredentials = false;
$authProvider.tokenRoot = null;
$authProvider.baseUrl = '/';
$authProvider.loginUrl = '/data/user';
$authProvider.tokenName = 'token';
$authProvider.tokenPrefix = 'satellizer';
$authProvider.tokenHeader = 'Authorization';
$authProvider.tokenType = 'Bearer';
$authProvider.storageType = 'localStorage';
/**
* Helper auth functions
*/
var skipIfLoggedIn = ['$auth', function ($auth) {
if ($auth.isAuthenticated()) {
return true;
} else {
return false;
}
}];
var loginRequired = ['$location', '$auth', '$state',function ($location, $auth,$state) {
if ($auth.isAuthenticated()) {
return true;
} else {
$state.go('appSimple.login', {}, {reload: true});
}
}];
$stateProvider
.state('app', {
abstract: true,
templateUrl: 'views/common/layouts/full.html',
controller: 'branchesCtrl',
//page title goes here
ncyBreadcrumb: {
label: 'Root',
skip: true
},
resolve: {
loadCSS: ['$ocLazyLoad', function ($ocLazyLoad) {
// you can lazy load CSS files
return $ocLazyLoad.load([{
serie: true,
name: 'Font Awesome',
files: ['node_modules/font-awesome/css/font-awesome.min.css']
}, {
serie: true,
name: 'Simple Line Icons',
files: ['node_modules/simple-line-icons/css/simple-line-icons.css']
}]);
}],
loadPlugin: ['$ocLazyLoad', function ($ocLazyLoad) {
// you can lazy load files for an existing module
return $ocLazyLoad.load([{
serie: true,
name: 'chart.js',
files: [
'node_modules/chart.js/dist/Chart.min.js',
'node_modules/angular-chart.js/dist/angular-chart.min.js'
]
}]);
}],
}
})
.state('app.main', {
url: '/dashboard',
templateUrl: 'views/main.html',
//page title goes here
ncyBreadcrumb: {
label: 'Dashboard',
},
//page subtitle goes here
params: {subtitle: 'Welcome to ROOT powerfull Bootstrap & AngularJS UI Kit'},
resolve: {
loadPlugin: ['$ocLazyLoad', function ($ocLazyLoad) {
// you can lazy load files for an existing module
return $ocLazyLoad.load([
{
serie: true,
name: 'chart.js',
files: [
'node_modules/chart.js/dist/Chart.min.js',
'node_modules/angular-chart.js/dist/angular-chart.min.js'
]
},
]);
}],
loadMyCtrl: ['$ocLazyLoad', function ($ocLazyLoad) {
// you can lazy load controllers
return $ocLazyLoad.load({
files: ['js/controllers/main.js']
});
}],
loginRequired: loginRequired
}
})
.state('appSimple', {
abstract: true,
templateUrl: 'views/common/layouts/simple.html',
resolve: {
loadCSS: ['$ocLazyLoad', function ($ocLazyLoad) {
// you can lazy load CSS files
return $ocLazyLoad.load([{
serie: true,
name: 'Font Awesome',
files: ['node_modules/font-awesome/css/font-awesome.min.css']
}, {
serie: true,
name: 'Simple Line Icons',
files: ['node_modules/simple-line-icons/css/simple-line-icons.css']
}]);
}],
}
})
// Additional Pages
.state('appSimple.login', {
url: '/login',
templateUrl: 'views/login/login.html',
controller: 'loginCtrl',
resolve: {
skipIfLoggedIn: skipIfLoggedIn
}
})
.state('appSimple.logout', {
url: '/logout',
template: null,
controller: 'logoutCtrl'
})
.state('appSimple.register', {
url: '/register',
templateUrl: 'views/pages/register.html'
})
.state('appSimple.404', {
url: '/404',
templateUrl: 'views/pages/404.html'
})
.state('appSimple.500', {
url: '/500',
templateUrl: 'views/pages/500.html'
})
.state('display', {
url: '/screen/{url:.*}',
param: {url: null},
templateUrl: 'views/display/display.html',
controller: 'displayCtrl',
resolve: {
creds: ['$http', function (r) {
return r.get('data/keys.json').then(function (res) {
return res.data;
});
}]
},
})
}]);
|
/* eslint-disable jsx-a11y/anchor-is-valid */
import '../src/bootstrap';
// --- Post bootstrap -----
import React from 'react';
import Button from '@material-ui/core/Button';
import Dialog from '@material-ui/core/Dialog';
import DialogTitle from '@material-ui/core/DialogTitle';
import DialogContent from '@material-ui/core/DialogContent';
import DialogContentText from '@material-ui/core/DialogContentText';
import DialogActions from '@material-ui/core/DialogActions';
import Typography from '@material-ui/core/Typography';
import { makeStyles } from '@material-ui/styles';
import Link from 'next/link';
const useStyles = makeStyles(theme => ({
root: {
textAlign: 'center',
paddingTop: theme.spacing.unit * 20,
},
}));
function Index() {
const classes = useStyles();
const [open, setState] = React.useState(false);
const handleClose = () => {
setState(false);
};
const handleClick = () => {
setState(true);
};
return (
<div className={classes.root}>
<Dialog open={open} onClose={handleClose}>
<DialogTitle>Super Secret Password</DialogTitle>
<DialogContent>
<DialogContentText>1-2-3-4-5</DialogContentText>
</DialogContent>
<DialogActions>
<Button color="primary" onClick={handleClose}>
OK
</Button>
</DialogActions>
</Dialog>
<Typography variant="h4" gutterBottom>
Material-UI
</Typography>
<Typography variant="subtitle1" gutterBottom>
example project
</Typography>
<Typography gutterBottom>
<Link href="/about">
<a>Go to the about page</a>
</Link>
</Typography>
<Button variant="contained" color="secondary" onClick={handleClick}>
Super Secret Password
</Button>
</div>
);
}
export default Index;
|
/**
* IMG
* preFlash
*
* All functions related to img files
* management.
*/
// PACKAGES
const gulp = require("gulp");
const g = {
cached: require("gulp-cached"),
favicon: require("gulp-real-favicon"),
if: require("gulp-if"),
imagemin: require("gulp-imagemin"),
plumber: require("gulp-plumber"),
rename: require("gulp-rename"),
util: require("gulp-util")
};
const cson = require("cson");
const fs = require("fs");
// !!! Run-sequence in to delete in gulp version 4 !!!
const run = require("run-sequence");
// CONFIG & HELPERS
const CONFIG = cson.requireFile("preFlash.config.cson");
const HELPERS = require("./../helpers.js");
// MAIN
gulp.task("img", function() {
g.util.log(g.util.colors.green("Images"), "running!");
return gulp.src(CONFIG.paths.sources.img)
.pipe(g.plumber({errorHandler: HELPERS.alert}))
.pipe(g.cached('img'))
.pipe(g.imagemin(
[
g.imagemin.gifsicle(CONFIG.packages.img.plugins.gifsicle),
g.imagemin.jpegtran(CONFIG.packages.img.plugins.jpegtran),
g.imagemin.optipng(CONFIG.packages.img.plugins.optipng),
g.imagemin.svgo(CONFIG.packages.img.plugins.svgo)
],
CONFIG.packages.img.options
))
.pipe(g.if(CONFIG.packages.img.rename, g.rename({suffix: '.min'})))
.pipe(gulp.dest(HELPERS.getPath() + CONFIG.packages.img.dir));
});
// WATCH
gulp.task("img.watch", (cb) => {
gulp.watch(CONFIG.paths.watch.img, ["img"]);
gulp.watch(CONFIG.packages.img.favicon.masterPicture, ["generate-favicon"]);
cb();
});
// FAVICONS
// http://realfavicongenerator.net/favicon/gulp
gulp.task("img.favicon", (cb) => {
run(
"generate-favicon",
"check-for-favicon-update",
cb
);
});
// Generate the icons. This task takes a few seconds to complete.
// You should run it at least once to create the icons. Then,
// you should run it whenever RealFaviconGenerator updates its
// package (see the check-for-favicon-update task below).
gulp.task('generate-favicon', (done) => {
g.util.log(g.util.colors.green("Favicon Generator"), "running!");
g.favicon.generateFavicon(
Object.assign(
{},
CONFIG.packages.img.favicon,
{ dest: HELPERS.getPath() }
),
() => done()
);
});
// Check for updates on RealFaviconGenerator (think: Apple has just
// released a new Touch icon along with the latest version of iOS).
// Run this task from time to time. Ideally, make it part of your
// continuous integration system.
gulp.task('check-for-favicon-update', function(done) {
g.util.log(g.util.colors.green("Favicon Generator Update"), "running!");
var currentVersion = JSON.parse(fs.readFileSync(CONFIG.packages.img.favicon.markupFile)).version;
g.favicon.checkForUpdates(currentVersion, function(err) {
if (err) {
throw err;
}
});
done();
});
|
/**
* Created by @axiat on 2017. 4. 10..
*/
// This script will keep the footer always at the bottom of the page
$(document).ready(function () {
var docHeight = $(window).height();
var footerHeight = $('#footer').height();
var footerTop = $('#footer').position().top + footerHeight;
if (footerTop < docHeight) {
$('#footer').css('margin-top', 10+ (docHeight - footerTop) + 'px');
}
});
|
!function () {
'use strict';
var Class = require('ee-class')
, ORM = require('related')
, EventEmitter = require('ee-event-emitter')
, fs = require('fs')
, path = require('path')
, semver = require('semver')
, Promise = require('promise')
, async = require("ee-async")
, sqlFiles = []
, schemaDirs = []
, filesLength
, ormObject
, error;
module.exports = new Class({
inherits: EventEmitter
, config: {}
, init: function (options) {
this.config = options;
}
/**
*@param {String} data
*/
, _getSchemaDirectories: function _getSchemaDirectories(data) {
return new Promise(function (resolve, reject) {
fs.stat(data.absolutePath, function (err, stats) {
if (err) {
reject(err);
} else {
if (stats && stats.isDirectory() && path.basename(data.absolutePath)[0] !== '.') {
if (semver.valid(data.file)) {
resolve(data);
} else {
resolve({});
}
} else {
resolve({});
}
}
});
});
}
/**
*@param {String} data
*/
, _getSqlFiles: function _getSqlFiles(data) {
return new Promise(function (resolve, reject) {
fs.stat(data.absolutePath, function (err, stats) {
if (err) {
reject(err);
} else {
if (stats && !stats.isDirectory() && path.extname(data.absolutePath) === '.sql') {
resolve(data);
} else {
resolve({});
}
}
});
});
}
/**
*@param {String} data
*/
, _readSqlFromFile: function _readSqlFromFile(data) {
var sqlStatements;
return new Promise(function (resolve, reject) {
fs.readFile(data.absolutePath, function (err, fileContent) {
if (err) {
reject(err);
} else {
sqlStatements = fileContent.toString().split(';').map(function (input) {
return input.trim().replace(/\n/gi, ' ').replace(/\s{2,}/g, ' ');
}).filter(function (item) {
return item.length;
});
resolve(sqlStatements);
}
});
});
}
/**
*@param ormObject
*@param sqlStatements
*@param callback
*/
, _executeSqlStatements: function _executeSqlStatements(ormObject, sqlStatements, callback) {
var dbName = this.config.schema ? this.config.schema : this.config.database
, ormDatabase = ormObject[dbName];
if (sqlStatements.length) {
sqlStatements.forEach(function (data) {
ormDatabase.schemaVersion({version: data.version}, ['*']).findOne(function (err, results) {
if (err) {
callback(err);
} else {
if (!results) {
ormObject.getDatabase(dbName).getConnection(function (err, connection) {
if (err) callback(err);
else {
if (data.data.length) {
async.each(data.data[0], connection.queryRaw.bind(connection), function (err, response) {
if (err) {
callback(err);
} else {
new ormDatabase.schemaVersion({version: data.version}).save(callback);
}
});
}
}
}.bind(this));
} else {
var err = new Error('Version already exists');
err.name = 'AlreadyExists';
callback(err);
}
}
});
}.bind(this));
}
}
/**
* Return all schema version directories
*
* @param {String} migrationPath
* @param {Function} callback
*/
, _readSchemaDir: function (migrationPath, callback) {
fs.readdir(migrationPath, function (err, files) {
if (err) callback(err);
else {
if (!files.length) callback(null, []);
else {
Promise.all(files.map(function (file) {
return {absolutePath: path.resolve(migrationPath, file), file: file};
}).map(this._getSchemaDirectories.bind(this))).done(function (response) {
callback(null, response);
}, function (err) {
callback(err);
});
}
}
}.bind(this));
}
/**
* Return all sql files
* @param {String} versionPath
* @param {Function} callback
*/
, _readSqlFiles: function _readSqlFiles(data, callback) {
if (data.absolutePath) {
fs.readdir(data.absolutePath, function (err, files) {
if (err) {
callback(err);
} else {
filesLength = files.length;
if (!filesLength) {
callback(null, sqlFiles);
} else {
Promise.all(files.map(function (file) {
return {
absolutePath: path.resolve(data.absolutePath, file),
file: file,
versionName: data.file
};
}).map(this._getSqlFiles.bind(this))).done(function (response) {
callback(null, response);
}, function (err) {
callback(err);
});
}
}
}.bind(this));
} else {
callback(null)
}
}
/**
* Migrate all sql files of schema version
* @param {Function} callback
*/
, migrate: function migration(callback) {
var options = this.config
, ormDatabase;
ormObject = new ORM(options.user
, options.password
, options.host
, options.schema
, options.database
, options.type);
ormObject.load(function (err) {
if (err) {
callback(err);
} else {
ormDatabase = ormObject[options.schema];
if (!ormDatabase) {
error = new Error('Database doesn\'t exists');
error.name = 'errorNotFound';
callback(error);
} else if (!ormDatabase.schemaVersion) {
error = new Error('Table schemaVersion doesn\'t exists');
error.name = 'errorNotFound';
callback(error);
} else if (!fs.existsSync(options.migrationPath)) {
error = new Error('Migration path doesn\'t exists');
error.name = 'InvalidPath';
callback(error);
} else {
this._readSchemaDir(options.migrationPath, function (err, dirs) {
if (err) {
callback(err);
} else {
if (!dirs.length) {
error = new Error('No migration found!');
error.name = 'errorEmptyPath';
callback(error);
} else {
async.each(dirs, function (item, next) {
var schemaDirectoryObject = {version: item.file};
this._readSqlFiles(item, function (err, files) {
if (err) {
next(err);
} else {
if (!files) {
error = new Error('No migration sql found!');
error.name = 'errorEmptyPath';
next(error);
} else {
Promise.all(files.map(this._readSqlFromFile.bind(this))).done(function (response) {
schemaDirectoryObject['data'] = response;
next(null, schemaDirectoryObject);
}.bind(this), function (err) {
next(err);
});
}
}
}.bind(this));
}.bind(this),
function (err, results) {
if (err) {
callback(err);
} else {
this._executeSqlStatements(ormObject, results, function (err, response) {
console.log(err, response);
});
}
}.bind(this));
}
}
}.bind(this));
}
}
}.bind(this));
}
});
}();
|
import React from 'react';
import MarkdownDocs from 'docs/src/modules/components/MarkdownDocs';
import { prepareMarkdown } from 'docs/src/modules/utils/parseMarkdown';
const pageFilename = 'components/tree-view';
const requireDemo = require.context('docs/src/pages/components/tree-view', false, /\.(js|tsx)$/);
const requireRaw = require.context(
'!raw-loader!../../src/pages/components/tree-view',
false,
/\.(js|md|tsx)$/,
);
export default function Page({ demos, docs }) {
return <MarkdownDocs demos={demos} docs={docs} requireDemo={requireDemo} />;
}
Page.getInitialProps = () => {
const { demos, docs } = prepareMarkdown({ pageFilename, requireRaw });
return { demos, docs };
};
|
Router.map(function () {
this.route('home', {
path: '/', layoutTemplate: 'mainLayout'
});
this.route('hashtags', { path: '/admin', layoutTemplate: 'mainLayout' }, function () {
this.render('hashtags');
});
this.route('display', {
path: '/display', layoutTemplate: 'mainLayout', onAfterAction: function (pause) {
Tweets = new Meteor.Collection(null);
var hashtags = Hashtags.find().fetch();// Template.display.helpers.hashtags();
for (var j = hashtags.length-1; j >= 0 ; j--) {
var hashtag = hashtags[j].text;
Meteor.call("checkTwitter", hashtag, function (err, result, data) {
console.log(result);
for (var i = 0; i < result.length; i++) {
result[i].html = result[i].text; //this does not work => result[i].text.replace(hashtag, "<span style='background-color:yellow;'>" + hashtag + "</span>");
Tweets.insert(result[i]);
}
});
}
}
});
});
// Default routing settings
Router.configure({
layoutTemplate: 'mainLayout',
notFoundTemplate: '404'
});
Hashtags = new Mongo.Collection("hashtags");
Tweets = new Meteor.Collection(null);
if (Meteor.isClient) {
// This code only runs on the client
Meteor.subscribe("hashtags");
Template.hashtags.helpers({
hashtags: function () {
if (Session.get("hideCompleted")) {
// If hide completed is checked, filter hashtags
return Hashtags.find({checked: {$ne: true}}, {sort: {createdAt: -1}});
} else {
// Otherwise, return all of the hashtags
return Hashtags.find({}, {sort: {createdAt: -1}});
}
},
hideCompleted: function () {
return Session.get("hideCompleted");
},
incompleteCount: function () {
return Hashtags.find({checked: {$ne: true}}).count();
}
});
Template.hashtags.events({
"submit .new-hashtag": function (event) {
// This function is called when the new hashtag form is submitted
var text = event.target.text.value;
Meteor.call("addHashtag", text);
// Clear form
event.target.text.value = "";
event.preventDefault();
// Prevent default form submit
return false;
},
"change .hide-completed input": function (event) {
Session.set("hideCompleted", event.target.checked);
}
});
Template.hashtag.events({
"click .toggle-checked": function () {
// Set the checked property to the opposite of its current value
Meteor.call("setChecked", this._id, ! this.checked);
},
"click .delete": function () {
Meteor.call("deleteHashtag", this._id);
},
"click .toggle-private": function () {
Meteor.call("setPrivate", this._id, ! this.private);
}
});
Template.hashtag.helpers({
isOwner: function () {
return this.owner === Meteor.userId();
}
});
Template.display.helpers({
tweets: function () {
return Tweets.find({});
},
hashtags: function () {
return Hashtags.find({}, { sort: { createdAt: -1 } });
}
});
Accounts.ui.config({
passwordSignupFields: "USERNAME_ONLY"
});
}
Meteor.methods({
addHashtag: function (text) {
if (text.indexOf('#') == 0 && text.length > 1)
text = text.substring(1);
Hashtags.insert({
text: text,
createdAt: new Date(),
owner: Meteor.userId(),
username: Meteor.user().username
});
},
deleteHashtag: function (hashtagId) {
var hashtag = Hashtags.findOne(hashtagId);
if (hashtag.private && hashtag.owner !== Meteor.userId()) {
// If the hashtag is private, make sure only the owner can delete it
throw new Meteor.Error("not-authorized");
}
Hashtags.remove(hashtagId);
},
setChecked: function (hashtagId, setChecked) {
var hashtag = Hashtags.findOne(hashtagId);
if (hashtag.private && hashtag.owner !== Meteor.userId()) {
// If the hashtag is private, make sure only the owner can check it off
throw new Meteor.Error("not-authorized");
}
Hashtags.update(hashtagId, { $set: { checked: setChecked} });
},
setPrivate: function (hashtagId, setToPrivate) {
var hashtag = Hashtags.findOne(hashtagId);
// Make sure only the hashtag owner can make a hashtag private
if (hashtag.owner !== Meteor.userId()) {
throw new Meteor.Error("not-authorized");
}
Hashtags.update(hashtagId, { $set: { private: setToPrivate } });
}
});
if (Meteor.isServer) {
var Twit = Meteor.npmRequire('twit');
var T = new Twit({
consumer_key: Meteor.settings.twitter_consumer_key, // API key
consumer_secret: Meteor.settings.twitter_consumer_secret,// API secret
access_token: Meteor.settings.twitter_access_token,
access_token_secret: Meteor.settings.twitter_access_token_secret,
});
var wrapGet = Meteor.wrapAsync(T.get, T);
// Only publish hashtags that are public or belong to the current user
Meteor.publish("hashtags", function () {
return Hashtags.find({
$or: [
{ private: {$ne: true} },
{ owner: this.userId }
]
});
});
Meteor.methods({
checkTwitter: function (hashtag) {
// search twitter for all tweets containing the word 'banana'
// since 2015
data = wrapGet('search/tweets',
{
q: '#'+hashtag + ' since:2015-03-11',
count: 10
}
);
if (data)
return data.statuses;
},
checkInstagram: function (hashtag) {
var api = 'https://api.instagram.com/v1/tags/search?q=' + hashtag + '&access_token=' + Meteor.settings.InstagramAPI.CLIENT_SECRET;
data = Meteor.wrapAsync(HTTP.call("GET", api));
return data;
//this.unblock();
//try {
// var result = ;
// return true;
//} catch (e) {
// // Got a network error, time-out or HTTP error in the 400 or 500 range.
// return false;
//}
}
});
Meteor.publish('instagramSearch', function (hashtag) {
var self = this;
try {
var response = HTTP.get('https://api.instagram.com/v1/tags/search', {
params: {
q: hashtag,
access_token: Meteor.settings.InstagramAPI.CLIENT_SECRET
}
});
_.each(response.data.items, function (item) {
var doc = {
title: item.title,
};
self.added('pictures', Random.id(), doc);
});
self.ready();
} catch (error) {
console.log(error);
}
});
}
|
import React, { PropTypes } from 'react'
import { connect } from 'react-redux'
import { actions as userActions, USER_ENUM } from '../../redux/modules/UserReducer'
class AuthRequiredWrapper extends React.Component {
static propTypes = {
children: PropTypes.element.isRequired,
isAuthenticated: PropTypes.bool.isRequired,
user: PropTypes.object.isRequired,
unauthorizedRoute: PropTypes.func.isRequired
};
componentWillMount() {
const { isAuthenticated, user } = this.props
if (!(isAuthenticated && user.user &&
([USER_ENUM.ROLE_ADMIN, USER_ENUM.ROLE_OWNER].includes(user.user.role)))) {
this.props.unauthorizedRoute()
}
}
render() {
const { children } = this.props
return (
<div>
{children}
</div>
)
}
}
const mapStateToProps = (state) => ({
isAuthenticated : state.user.isAuthenticated,
user : state.user
})
export default connect(mapStateToProps, userActions)(AuthRequiredWrapper)
|
GrandCentral.Dashboard = DS.Model.extend({
title: DS.attr('string'),
published: DS.attr('boolean')
});
|
function getMemoryList() {
var memoryList = [{
round: 1,
position: undefined,
valuee: undefined
},
{
round: 2,
position: undefined,
valuee: undefined
},
{
round: 3,
position: undefined,
valuee: undefined
},
{
round: 4,
position: undefined,
valuee: undefined
},
{
round: 5,
position: undefined,
valuee: undefined
},
];
return memoryList;
}
function memory(display, round, memoryList) {
if (round==1) {
if (display ==1) {
memoryList[0].position = 2;
return("Press the button in the second position")
}
if (display ==2) {
memoryList[0].position = 2;
return("Press the button in the second position")
}
if (display ==3) {
memoryList[0].position = 3;
return("Press the button in the third position")
}
if (display ==4) {
memoryList[0].position = 4;
return("Press the button in the fourth position")
}
}
if (round==2) {
if (display ==1) {
memoryList[1].valuee = 4;
return("Press the button labeled 4")
}
if (display ==2 || display ==4) {
answer = memoryList[0].position;
memoryList[1].position = answer;
return("Press the button in the position of " + answer);
}
if (display ==3) {
memoryList[1].position = 1;
return("Press the button in the first position")
}
}
if (round==3) {
if (display ==1) {
answer = memoryList[1].valuee;
memoryList[2].valuee = answer;
return("Press the button with the label " + answer);
}
if (display ==2) {
answer = memoryList[0].valuee;
memoryList[2].valuee = answer;
return("Press the button with the label " + answer);
}
if (display ==3) {
memoryList[2].position = 3;
return("Press the button in the third position")
}
if (display ==4) {
memoryList[2].valuee = 4;
return("Press the button labeled 4")
}
}
if (round==4) {
if (display ==1) {
answer = memoryList[0].position;
memoryList[3].position = answer;
return("Press the button with the position " + answer);
}
if (display ==2) {
memoryList[3].position = 1;
return("Press the button in the first position")
}
if (display ==3 || display==4) {
//same position as stage 2
answer = memoryList[1].position;
memoryList[3].position = answer;
return("Press the button with the position " + answer)
}
}
if (round==5) {
if (display ==1) {
//same label as stage 1
answer = memoryList[0].valuee;
memoryList[4].valuee = answer;
return("Press the button with the label " + answer)
}
if (display ==2) {
answer = memoryList[1].valuee;
memoryList[4].position = answer;
return("Press the button with the label " + answer)
}
if (display ==3) {
//same label as stage 4
answer = memoryList[3].valuee;
memoryList[4].valuee = answer;
return("Press the button with the label " + answer)
}
if (display ==4) {
//same label as stage 3
answer = memoryList[2].valuee;
memoryList[4].valuee = answer;
return("Press the button with the label " + answer)
}
}
}
|
/*
The MIT License (MIT)
Copyright (c) 2015 Los Andes University
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
(function (ng) {
var mod = ng.module('tripModule');
mod.controller('tripCategoryEditCtrl', ['$scope', 'category', 'pool', 'model', '$state',
function ($scope, category, available, model, $state) {
$scope.records = category;
$scope.model = model;
$scope.available = available.plain();
$scope.actions = {
save: {
displayName: 'Save',
icon: 'save',
fn: function () {
$scope.records.customPUT().then(function () {
$state.go('tripCategoryList', null, {reload: true});
});
}
},
cancel: {
displayName: 'Cancel',
icon: 'remove',
fn: function () {
$state.go('tripCategoryList');
}
}
};
}]);
})(window.angular);
|
module.exports.parse = function (object) {
statement = "";
statement += String(object).toUpperCase() == "AND" ? " AND " : " OR ";
return statement;
};
|
/**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component, PropTypes } from 'react';
import { AppRegistry, NativeModules, StyleSheet, Text, View } from 'react-native';
import ActionExtensionScreen from './app/ActionExtensionScreen';
export default class ReactNativeExampleBrowserExtension extends Component {
static propTypes = {
isActionExtension: PropTypes.bool
};
static defaultProps = {
isActionExtension: false
};
render() {
if (this.props.isActionExtension) {
return <ActionExtensionScreen />;
} else {
return (
<View style={styles.container}>
<Text style={styles.welcome}>Welcome to ReactNativeExampleBrowserExtension!</Text>
<Text style={styles.instructions}>
This app shows how to create a browser extension using React Native
</Text>
<Text style={styles.instructions}>
You can mostly ignore this main app code, all the fun is in the extension and the
README, which contains the instructions you should follow
</Text>
</View>
);
}
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF'
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5
}
});
AppRegistry.registerComponent(
'ReactNativeExampleBrowserExtension',
() => ReactNativeExampleBrowserExtension
);
|
TextVisApp.factory('dataService', ['$http', function ($http) {
}]);
|
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { CellModule } from '../cell/cell.module';
import { Ng2SmartTableTbodyComponent } from './tbody.component';
import { TbodyCreateCancelComponent } from './cells/create-cancel.component';
import { TbodyEditDeleteComponent } from './cells/edit-delete.component';
import { TbodyCustomComponent } from './cells/custom.component';
var TBODY_COMPONENTS = [
TbodyCreateCancelComponent,
TbodyEditDeleteComponent,
TbodyCustomComponent,
Ng2SmartTableTbodyComponent
];
var TBodyModule = (function () {
function TBodyModule() {
}
return TBodyModule;
}());
TBodyModule = __decorate([
NgModule({
imports: [
CommonModule,
FormsModule,
CellModule,
],
declarations: TBODY_COMPONENTS.slice(),
exports: TBODY_COMPONENTS.slice(),
})
], TBodyModule);
export { TBodyModule };
//# sourceMappingURL=tbody.module.js.map
|
var chai = require('chai');
var chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised);
var expect = chai.expect;
var Promise = require('bluebird');
var messages = require('../server/messages');
var Chat = require('../server/database.js');
describe('Chat Timing', function() {
before(function(done) {
Promise.mapSeries(Array.apply(null, Array(11)), function(item, index) {
return new Chat({user: 'user', text: 'text' + index, session: '4'}).save();
}).then(() => done()).catch(done);
});
describe('#getPosts', function(done) {
it('should return 10', function(done) {
expect(messages.getPosts()).to.eventually.have.lengthOf(10)
.then((m) => done()).catch(done);
});
it('should return only the new ones when sent a date', function(done) {
var lastDate;
messages.getPosts()
.then((r) => {
lastDate = r[r.length - 1].createdOn;
expect(lastDate).to.not.be.null;
})
.then(() => messages.addPost('bill', 'new post', 'session'))
.then(() => messages.getPosts(lastDate))
.then((updated) => {
expect(updated).to.have.lengthOf(1);
})
.then(() => done()).catch(done);
});
});
after(function(done) {
Chat.remove().then(() => done()).catch(done);
done();
});
});
|
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
* @format
*/
'use strict';var _slicedToArray = function () {function sliceIterator(arr, i) {var _arr = [];var _n = true;var _d = false;var _e = undefined;try {for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {_arr.push(_s.value);if (i && _arr.length === i) break;}} catch (err) {_d = true;_e = err;} finally {try {if (!_n && _i["return"]) _i["return"]();} finally {if (_d) throw _e;}}return _arr;}return function (arr, i) {if (Array.isArray(arr)) {return arr;} else if (Symbol.iterator in Object(arr)) {return sliceIterator(arr, i);} else {throw new TypeError("Invalid attempt to destructure non-iterable instance");}};}();
const babel = require('babel-core');
const babelGenerate = require('babel-generator').default;
const babylon = require('babylon');
const assetPropertyBlacklist = new Set(['files', 'fileSystemLocation', 'path']);
function generateAssetCodeFileAst(
assetRegistryPath,
assetDescriptor)
{
const properDescriptor = filterObject(
assetDescriptor,
assetPropertyBlacklist);
const descriptorAst = babylon.parseExpression(
JSON.stringify(properDescriptor));
const t = babel.types;
const moduleExports = t.memberExpression(
t.identifier('module'),
t.identifier('exports'));
const requireCall = t.callExpression(t.identifier('require'), [
t.stringLiteral(assetRegistryPath)]);
const registerAssetFunction = t.memberExpression(
requireCall,
t.identifier('registerAsset'));
const registerAssetCall = t.callExpression(registerAssetFunction, [
descriptorAst]);
return t.file(
t.program([
t.expressionStatement(
t.assignmentExpression('=', moduleExports, registerAssetCall))]));
}
function generateAssetTransformResult(
assetRegistryPath,
assetDescriptor)
{var _babelGenerate =
babelGenerate(
generateAssetCodeFileAst(assetRegistryPath, assetDescriptor),
{ comments: false, compact: true });const code = _babelGenerate.code;
const dependencies = [assetRegistryPath];
const dependencyOffsets = [code.indexOf(assetRegistryPath) - 1];
return { code, dependencies, dependencyOffsets };
}
// Test extension against all types supported by image-size module.
// If it's not one of these, we won't treat it as an image.
function isAssetTypeAnImage(type) {
return (
['png', 'jpg', 'jpeg', 'bmp', 'gif', 'webp', 'psd', 'svg', 'tiff'].indexOf(
type) !==
-1);
}
function filterObject(object, blacklist) {
const copied = Object.assign({}, object);
for (const key of blacklist) {
delete copied[key];
}
return copied;
}
function createRamBundleGroups(
ramGroups,
groupableModules,
subtree)
{
// build two maps that allow to lookup module data
// by path or (numeric) module id;
const byPath = new Map();
const byId = new Map();
groupableModules.forEach(m => {
byPath.set(m.sourcePath, m);
byId.set(m.id, m.sourcePath);
});
// build a map of group root IDs to an array of module IDs in the group
const result = new Map(
ramGroups.map(modulePath => {
const root = byPath.get(modulePath);
if (root == null) {
throw Error(`Group root ${modulePath} is not part of the bundle`);
}
return [
root.id,
// `subtree` yields the IDs of all transitive dependencies of a module
new Set(subtree(root, byPath))];
}));
if (ramGroups.length > 1) {
// build a map of all grouped module IDs to an array of group root IDs
const all = new ArrayMap();
for (const _ref of result) {var _ref2 = _slicedToArray(_ref, 2);const parent = _ref2[0];const children = _ref2[1];
for (const module of children) {
all.get(module).push(parent);
}
}
// find all module IDs that are part of more than one group
const doubles = filter(all, _ref3 => {var _ref4 = _slicedToArray(_ref3, 2);let parents = _ref4[1];return parents.length > 1;});
for (const _ref5 of doubles) {var _ref6 = _slicedToArray(_ref5, 2);const moduleId = _ref6[0];const parents = _ref6[1];
const parentNames = parents.map(byId.get, byId);
const lastName = parentNames.pop();
throw new Error(
`Module ${byId.get(moduleId) ||
moduleId} belongs to groups ${parentNames.join(', ')}, and ${String(
lastName)
}. Ensure that each module is only part of one group.`);
}
}
return result;
}
function* filter(iterator, predicate) {
for (const value of iterator) {
if (predicate(value)) {
yield value;
}
}
}
class ArrayMap extends Map {
get(key) {
let array = super.get(key);
if (!array) {
array = [];
this.set(key, array);
}
return array;
}}
module.exports = {
createRamBundleGroups,
generateAssetCodeFileAst,
generateAssetTransformResult,
isAssetTypeAnImage };
|
/* eslint-env node */
'use strict';
const assert = require('assert');
const fs = require('fs');
const {join} = require('path');
const ohm = require('../../packages/ohm-js');
const contents = fs.readFileSync(join(__dirname, 'csv.ohm'));
const g = ohm.grammar(contents);
const semantics = g.createSemantics().addOperation('value', {
csv(r, _, rs, eol) {
return [r.value()].concat(rs.children.map(c => c.value()));
},
row(c, _, cs) {
return [c.value()].concat(cs.children.map(c => c.value()));
},
col(_) {
return this.sourceString;
},
});
const someInput = 'foo,bar,baz\n' + 'foo,bar\n' + '\n' + 'foo,,baz\n' + ',bar,baz\n' + 'foo';
function parse(input) {
const match = g.match(input);
assert(match.succeeded());
return semantics(match).value();
}
assert.deepEqual(parse(someInput), [
['foo', 'bar', 'baz'],
['foo', 'bar'],
[''],
['foo', '', 'baz'],
['', 'bar', 'baz'],
['foo'],
]);
assert.deepEqual(parse(someInput + '\n'), [
['foo', 'bar', 'baz'],
['foo', 'bar'],
[''],
['foo', '', 'baz'],
['', 'bar', 'baz'],
['foo'],
]);
|
/*
* ______ _____ _____ _ _____________ _________________ ____________
* | ___ \ _ / __ \| | / /_ _| ___ \ ___| ___| ___| | ___ \ ___ \
* | |_/ / | | | / \/| |/ / | | | |_/ / |__ | |_ | |_ | |_/ / |_/ /
* | /| | | | | | \ | | | /| __|| _| | _| | ___ \ ___ \
* | |\ \\ \_/ / \__/\| |\ \ | | | |\ \| |___| | | | | |_/ / |_/ /
* \_| \_|\___/ \____/\_| \_/ \_/ \_| \_\____/\_| \_| \____/\____/
*
* "THE BEER-WARE LICENSE" (Revision 42):
* <rob ∂ rocktreff de> wrote this file. As long as you retain this notice you
* can do whatever you want with this stuff. If we meet some day, and you think
* this stuff is worth it, you can buy me a beer in return.
*
*/
'use strict';
var _ = require( 'lodash' )
var Promise = require( 'promise' )
function createFromSchema( schema ) {
var obj = {}
if ( !schema || !schema.properties ) return obj
var properties = schema.properties
for ( var key in properties ) {
if ( !properties.hasOwnProperty( key ) ) continue
var property = properties[ key ]
switch ( property.type.toLowerCase() ) {
case 'object':
obj[ key ] = createFromSchema( property.properties )
case 'string':
obj[ key ] = property.default || ''
case 'array':
obj[ key ] = property.default || []
case 'boolean':
obj[ key ] = property.default || false
case 'number':
obj[ key ] = property.default || 0
}
}
return obj
}
module.exports = function ( template ) {
template = createFromSchema( template )
return {
create: function ( obj ) {
return new Promise( function ( resolve ) {
resolve( _.defaults( obj, template ) )
})
},
omit: function () {
var args = Array.prototype.slice.call( arguments )
return function ( obj ) {
var foo = obj instanceof Array ?
_.map( obj, function ( o ) {
return _.omit( o, args )
})
: _.omit( obj, args )
return foo
}
},
merge: _.curry( function ( src, obj ) {
return _.merge( obj, src )
})
}
}
|
(function(){
'use strict';
/**
* jQuery UI date pciker range filter model
* @constructor
* @param {string} dataPath - DatePickerRangeFilter data-path attribute
* @param {string} dateTimeFormat
* @param {Date|string} prevDate
* @param {Date|string} nextDate
*/
jQuery.fn.jplist.ui.controls.DatePickerRangeFilterDTO = function(dataPath, dateTimeFormat, prevDate, nextDate){
var result = {
path: dataPath
,format: dateTimeFormat
,filterType: 'dateRange'
,prev_year: ''
,prev_month: ''
,prev_day: ''
,next_year: ''
,next_month: ''
,next_day: ''
};
if(prevDate){
result.prev_year = prevDate.getFullYear();
result.prev_month = prevDate.getMonth();
result.prev_day = prevDate.getDate();
}
if(nextDate){
result.next_year = nextDate.getFullYear();
result.next_month = nextDate.getMonth();
result.next_day = nextDate.getDate();
}
return result;
};
})();
|
const {PI} = Math
import SphericalMercator from './sphericalmercator'
import Transformation from './transformation'
class CRS {
constructor(opts) {
this.projection = new SphericalMercator()
this.tileSize = 256 + 256 * (opts.zoom % 1)
const earthRadius = 6378137
const scale = 0.5 / (PI * earthRadius);
this.transformation = new Transformation(scale, 0.5, -scale, 0.5)
}
// @method scale(zoom: Number): Number
// Returns the scale used when transforming projected coordinates into
// pixel coordinates for a particular zoom.
// `256 * 2^zoom` for Mercator-based CRS.
scale(zoom) {
return this.tileSize * Math.pow(2, zoom);
}
// @method zoom(scale: Number): Number
// Inverse of `scale()`, returns the zoom level corresponding to a scale
// factor of `scale`.
zoom(scale) {
return Math.log(scale / this.tileSize) / Math.LN2;
}
// @method latLngToPoint(latlng: LatLng, zoom: Number): Point
// Projects geographical coordinates into pixel coordinates for a given zoom.
latLngToPoint(latlng, zoom) {
const projectedPoint = this.projection.project(latlng)
const scale = this.scale(zoom)
return this.transformation.transform(projectedPoint, scale)
}
// @method pointToLatLng(point: Point, zoom: Number): LatLng
// The inverse of `latLngToPoint`. Projects pixel coordinates on a given
// zoom into geographical coordinates.
pointToLatLng(point, zoom) {
const scale = this.scale(zoom)
const untransformedPoint = this.transformation.untransform(point, scale);
const result = this.projection.unproject(untransformedPoint);
return result
}
}
module.exports = CRS
|
(function() {
var Walrus;
Walrus = (typeof exports !== "undefined" && exports !== null ? require('./walrus') : this).Walrus;
/**
* *:reverse*
* Reverses a string.
*
* Parameters: none
*
* Usage:
*
* {{ "hello" | :reverse }} // => "olleh"
*/
Walrus.addFilter('reverse', function(value) {
return value.split('').reverse().join('');
});
/**
* *:downcase*
* Converts a string to lowercase characters. Opposite of `:upcase`.
*
* Parameters: none
*
* Usage:
*
* {{ "HelLO!" | :downcase }} // => "hello!"
*/
Walrus.addFilter('downcase', function(value) {
return value.toLowerCase();
});
/**
* *:upcase*
* Converts a string to uppercase characters. Opposite of `:downcase`.
*
* Parameters: none
*
* Usage:
*
* {{ "HelLO!" | :upcase }} // => "HELLO!"
*/
Walrus.addFilter('upcase', function(value) {
return value.toUpperCase();
});
/**
* *:squish*
* Removes all leading and trailing whitespace, then condenses any internal whitespace
* groups to a single space each.
*
* Parameters: none
*
* Usage:
*
* {{ " foo bar \n baz" | :squish }} // => "foo bar baz"
*/
Walrus.addFilter('squish', function(string) {
return Walrus.Utils.trim(string).replace(/\s+/g, ' ');
});
/**
* *:truncate*
* Truncates a string to the specified `length`, optionally breaking at a separator
* or providing a custom string to denote an omission.
*
* Parameters:
* length (int) - the number of characters to keep, at most
* separator (string) - Optional: a specified string to break on
* omission (string) - Optional: a string to denote an omission
*
* Usage:
*
* {{ "Once upon a time in a world far far away" | :truncate( 27, ' ' ) }} // => "Once upon a time in a..."
*/
Walrus.addFilter('truncate', function(string, length, separator, omission) {
var chars, stop;
if (separator == null) separator = false;
if (omission == null) omission = '...';
chars = length - omission.length;
stop = separator ? string.lastIndexOf(separator, chars) || chars : chars;
if (string.length > length) {
return string.substr(0, stop) + omission;
} else {
return string;
}
});
/**
* *:titleize*
* Capitalizes all words within a string
*
* Parameters: none
*
* Usage:
*
* { "man from the boondocks" | :titleize } // => "Man From The Boondocks"
* { "x-men: the last stand" | :titleize } // => "X Men: The Last Stand"
* { "TheManWithoutAPast" | :titleize } // => "The Man Without A Past"
* { "raiders_of_the_lost_ark" | :titleize } // => "Raiders Of The Lost Ark"
*/
Walrus.addFilter('titleize', function(string) {
var capitalize, title, word, words;
title = string.replace(/[ \-_]+/g, ' ');
words = Walrus.Utils.trim(title.replace(/([A-Z])/g, " $&")).split(' ');
capitalize = function(word) {
return word.charAt(0).toUpperCase() + word.slice(1);
};
return ((function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = words.length; _i < _len; _i++) {
word = words[_i];
_results.push(capitalize(word));
}
return _results;
})()).join(' ');
});
}).call(this);
|
ya.$onReady(function () {
"use strict";
var view = app.view.Bar.$create({
config: {
models: [
ya.$factory({
module: 'ya',
alias: 'Model',
namespace: 'likes',
data: {
count: 0
},
methods: {
incrementCount: function () {
var me = this;
me.data('count', me.data('count') + 1);
}
}
})
],
id: 'bar',
tpl: {
id: 'tpl-bar',
tpl: [
'<div class="bar">',
'Count : {{likes.count}}',
'<button css="cursor: pointer;">+</button>',
'</div>'
]
},
renderTo: '#container'
}
});
// create main controller to
ya.Controller.$create({
config: {
name: 'Main',
events: {
'$bar button': {
click: function (view, event) {
view.getModel('likes').incrementCount();
}
}
}
}
});
view.render();
});
|
(function ($, kv) {
var $fSetToggler = $('<a href="#" class="fSetToggler">advanced</a>');
/**
*
* @param event
* @context {ExpandableSet}
*/
function handleToggleClick(event) {
event.preventDefault();
event.data.expandableSet.expandableToggle();
}
/**
*
*/
kv.FormSet.prototype.expandable = function () {
this.settings.expandable = $.extend({}, kv.FormSet.expandable.defaults, this.settings.expandable);
var $expandableSet = this.$formSet
, $toggler = $fSetToggler.clone().appendTo($('.fSetHead .fSetInner', $expandableSet))
, $nestedSet = $('> .fSetHead + .fSet', $expandableSet);
// Make sure everything is structured the way we need it
$.each({expandableSet: $expandableSet, toggler: $toggler, nestedSet: $nestedSet}, function (key, val) {
if (val.length === 0) {
throw 'missing ' + key;
}
});
this.decorate('expandable', {
$toggler: $toggler
, $nestedSet: $nestedSet
/**
* Toggles the display of the expandableSet
*/
, expandableToggle: function () {
if (this.attr('expandableState') == 'expanded') {
this.close();
} else {
this.expand();
}
}
/**
* Expands the expandableSet
*/
, expand: function () {
var self = this;
self.$nestedSet.stop().slideDown(function () {
self.$toggler.text(self.settings.expandedText);
self.attr('expandableState', 'expanded');
$(this).addClass(self.settings.expandable.openClass);
});
}
/**
* Closes the expandableSet
*/
, close: function () {
var self = this;
self.$nestedSet.stop().slideUp(function () {
self.$toggler.text(self.settings.closedText);
self.attr('expandableState', 'closed');
$(this).removeClass(self.settings.expandable.openClass);
});
}
});
if (this.settings.expandable.expandOnLoad) {
this.expand();
} else {
this.attr('expandableState', 'closed');
}
this.$toggler.click({expandableSet: this}, handleToggleClick);
};
kv.FormSet.expandable = {
defaults: {
openClass: 'open'
, expandedText: 'close'
, closedText: 'advanced'
, expandOnLoad: false
}
};
}(jQuery, kv));
|
"use strict"
;(function(m) {
if (typeof module !== "undefined") module["exports"] = m()
else window.o = m()
})(function init(name) {
console.warn(
"Please switch to the `ospec` package to remove this warning and see " +
"the most recent features. Using the `ospec` bundled within Mithril.js " +
"is deprecated, and it will be removed in the next major release."
)
var spec = {}, subjects = [], results, only = [], ctx = spec, start, stack = 0, nextTickish, hasProcess = typeof process === "object", hasOwn = ({}).hasOwnProperty
var ospecFileName = getStackName(ensureStackTrace(new Error), /[\/\\](.*?):\d+:\d+/), timeoutStackName
var globalTimeout = noTimeoutRightNow
var currentTestError = null
if (name != null) spec[name] = ctx = {}
try {throw new Error} catch (e) {
var ospecFileName = e.stack && (/[\/\\](.*?):\d+:\d+/).test(e.stack) ? e.stack.match(/[\/\\](.*?):\d+:\d+/)[1] : null
}
function o(subject, predicate) {
if (predicate === undefined) {
if (!isRunning()) throw new Error("Assertions should not occur outside test definitions.")
return new Assert(subject)
} else {
if (isRunning()) throw new Error("Test definitions and hooks shouldn't be nested. To group tests, use 'o.spec()'.")
subject = String(subject)
if (subject.charCodeAt(0) === 1) throw new Error("test names starting with '\\x01' are reserved for internal use.")
ctx[unique(subject)] = new Task(predicate, ensureStackTrace(new Error))
}
}
o.before = hook("\x01before")
o.after = hook("\x01after")
o.beforeEach = hook("\x01beforeEach")
o.afterEach = hook("\x01afterEach")
o.specTimeout = function (t) {
if (isRunning()) throw new Error("o.specTimeout() can only be called before o.run().")
if (hasOwn.call(ctx, "\x01specTimeout")) throw new Error("A default timeout has already been defined in this context.")
if (typeof t !== "number") throw new Error("o.specTimeout() expects a number as argument.")
ctx["\x01specTimeout"] = t
}
o.new = init
o.spec = function(subject, predicate) {
var parent = ctx
ctx = ctx[unique(subject)] = {}
predicate()
ctx = parent
}
o.only = function(subject, predicate, silent) {
if (!silent) console.log(
highlight("/!\\ WARNING /!\\ o.only() mode") + "\n" + o.cleanStackTrace(ensureStackTrace(new Error)) + "\n",
cStyle("red"), ""
)
only.push(predicate)
o(subject, predicate)
}
o.spy = function(fn) {
var spy = function() {
spy.this = this
spy.args = [].slice.call(arguments)
spy.calls.push({this: this, args: spy.args})
spy.callCount++
if (fn) return fn.apply(this, arguments)
}
if (fn)
Object.defineProperties(spy, {
length: {value: fn.length},
name: {value: fn.name}
})
spy.args = []
spy.calls = []
spy.callCount = 0
return spy
}
o.cleanStackTrace = function(error) {
// For IE 10+ in quirks mode, and IE 9- in any mode, errors don't have a stack
if (error.stack == null) return ""
var i = 0, header = error.message ? error.name + ": " + error.message : error.name, stack
// some environments add the name and message to the stack trace
if (error.stack.indexOf(header) === 0) {
stack = error.stack.slice(header.length).split(/\r?\n/)
stack.shift() // drop the initial empty string
} else {
stack = error.stack.split(/\r?\n/)
}
if (ospecFileName == null) return stack.join("\n")
// skip ospec-related entries on the stack
while (stack[i] != null && stack[i].indexOf(ospecFileName) !== -1) i++
// now we're in user code (or past the stack end)
return stack[i]
}
o.timeout = function(n) {
globalTimeout(n)
}
o.run = function(reporter) {
results = []
start = new Date
test(spec, [], [], new Task(function() {
setTimeout(function () {
timeoutStackName = getStackName({stack: o.cleanStackTrace(ensureStackTrace(new Error))}, /([\w \.]+?:\d+:\d+)/)
if (typeof reporter === "function") reporter(results)
else {
var errCount = o.report(results)
if (hasProcess && errCount !== 0) process.exit(1) // eslint-disable-line no-process-exit
}
})
}, null), 200 /*default timeout delay*/)
function test(spec, pre, post, finalize, defaultDelay) {
if (hasOwn.call(spec, "\x01specTimeout")) defaultDelay = spec["\x01specTimeout"]
pre = [].concat(pre, spec["\x01beforeEach"] || [])
post = [].concat(spec["\x01afterEach"] || [], post)
series([].concat(spec["\x01before"] || [], Object.keys(spec).reduce(function(tasks, key) {
if (key.charCodeAt(0) !== 1 && (only.length === 0 || only.indexOf(spec[key].fn) !== -1 || !(spec[key] instanceof Task))) {
tasks.push(new Task(function(done) {
o.timeout(Infinity)
subjects.push(key)
var pop = new Task(function pop() {subjects.pop(), done()}, null)
if (spec[key] instanceof Task) series([].concat(pre, spec[key], post, pop), defaultDelay)
else test(spec[key], pre, post, pop, defaultDelay)
}, null))
}
return tasks
}, []), spec["\x01after"] || [], finalize), defaultDelay)
}
function series(tasks, defaultDelay) {
var cursor = 0
next()
function next() {
if (cursor === tasks.length) return
var task = tasks[cursor++]
var fn = task.fn
currentTestError = task.err
var timeout = 0, delay = defaultDelay, s = new Date
var current = cursor
var arg
globalTimeout = setDelay
var isDone = false
// public API, may only be called once from use code (or after returned Promise resolution)
function done(err) {
if (!isDone) isDone = true
else throw new Error("'" + arg + "()' should only be called once.")
if (timeout === undefined) console.warn("# elapsed: " + Math.round(new Date - s) + "ms, expected under " + delay + "ms\n" + o.cleanStackTrace(task.err))
finalizeAsync(err)
}
// for internal use only
function finalizeAsync(err) {
if (err == null) {
if (task.err != null) succeed(new Assert)
} else {
if (err instanceof Error) fail(new Assert, err.message, err)
else fail(new Assert, String(err), null)
}
if (timeout !== undefined) timeout = clearTimeout(timeout)
if (current === cursor) next()
}
function startTimer() {
timeout = setTimeout(function() {
timeout = undefined
finalizeAsync("async test timed out after " + delay + "ms")
}, Math.min(delay, 2147483647))
}
function setDelay (t) {
if (typeof t !== "number") throw new Error("timeout() and o.timeout() expect a number as argument.")
delay = t
}
if (fn.length > 0) {
var body = fn.toString()
arg = (body.match(/^(.+?)(?:\s|\/\*[\s\S]*?\*\/|\/\/.*?\n)*=>/) || body.match(/\((?:\s|\/\*[\s\S]*?\*\/|\/\/.*?\n)*(.+?)(?:\s|\/\*[\s\S]*?\*\/|\/\/.*?\n)*[,\)]/) || []).pop()
if (body.indexOf(arg) === body.lastIndexOf(arg)) {
var e = new Error
e.stack = "'" + arg + "()' should be called at least once\n" + o.cleanStackTrace(task.err)
throw e
}
try {
fn(done, setDelay)
}
catch (e) {
if (task.err != null) finalizeAsync(e)
// The errors of internal tasks (which don't have an Err) are ospec bugs and must be rethrown.
else throw e
}
if (timeout === 0) {
startTimer()
}
} else {
try{
var p = fn()
if (p && p.then) {
startTimer()
p.then(function() { done() }, done)
} else {
nextTickish(next)
}
} catch (e) {
if (task.err != null) finalizeAsync(e)
// The errors of internal tasks (which don't have an Err) are ospec bugs and must be rethrown.
else throw e
}
}
globalTimeout = noTimeoutRightNow
}
}
}
function unique(subject) {
if (hasOwn.call(ctx, subject)) {
console.warn("A test or a spec named '" + subject + "' was already defined.")
while (hasOwn.call(ctx, subject)) subject += "*"
}
return subject
}
function hook(name) {
return function(predicate) {
if (ctx[name]) throw new Error(name.slice(1) + " should be defined outside of a loop or inside a nested test group.")
ctx[name] = new Task(predicate, ensureStackTrace(new Error))
}
}
define("equals", "should equal", function(a, b) {return a === b})
define("notEquals", "should not equal", function(a, b) {return a !== b})
define("deepEquals", "should deep equal", deepEqual)
define("notDeepEquals", "should not deep equal", function(a, b) {return !deepEqual(a, b)})
define("throws", "should throw a", throws)
define("notThrows", "should not throw a", function(a, b) {return !throws(a, b)})
function isArguments(a) {
if ("callee" in a) {
for (var i in a) if (i === "callee") return false
return true
}
}
function deepEqual(a, b) {
if (a === b) return true
if (a === null ^ b === null || a === undefined ^ b === undefined) return false // eslint-disable-line no-bitwise
if (typeof a === "object" && typeof b === "object") {
var aIsArgs = isArguments(a), bIsArgs = isArguments(b)
if (a.constructor === Object && b.constructor === Object && !aIsArgs && !bIsArgs) {
for (var i in a) {
if ((!(i in b)) || !deepEqual(a[i], b[i])) return false
}
for (var i in b) {
if (!(i in a)) return false
}
return true
}
if (a.length === b.length && (a instanceof Array && b instanceof Array || aIsArgs && bIsArgs)) {
var aKeys = Object.getOwnPropertyNames(a), bKeys = Object.getOwnPropertyNames(b)
if (aKeys.length !== bKeys.length) return false
for (var i = 0; i < aKeys.length; i++) {
if (!hasOwn.call(b, aKeys[i]) || !deepEqual(a[aKeys[i]], b[aKeys[i]])) return false
}
return true
}
if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime()
if (typeof Buffer === "function" && a instanceof Buffer && b instanceof Buffer) {
for (var i = 0; i < a.length; i++) {
if (a[i] !== b[i]) return false
}
return true
}
if (a.valueOf() === b.valueOf()) return true
}
return false
}
function throws(a, b){
try{
a()
}catch(e){
if(typeof b === "string"){
return (e.message === b)
}else{
return (e instanceof b)
}
}
return false
}
function isRunning() {return results != null}
function Assert(value) {
this.value = value
this.i = results.length
results.push({pass: null, context: "", message: "Incomplete assertion in the test definition starting at...", error: currentTestError, testError: currentTestError})
}
function Task(fn, err) {
this.fn = fn
this.err = err
}
function define(name, verb, compare) {
Assert.prototype[name] = function assert(value) {
var self = this
var message = serialize(self.value) + "\n " + verb + "\n" + serialize(value)
if (compare(self.value, value)) succeed(self, message)
else fail(self, message)
var result = results[self.i]
return function(message) {
if (!result.pass) {
result.message = message + "\n\n" + result.message
}
}
}
}
function succeed(assertion, message) {
results[assertion.i].pass = true
results[assertion.i].context = subjects.join(" > ")
results[assertion.i].message = message
}
function fail(assertion, message, error) {
results[assertion.i].pass = false
results[assertion.i].context = subjects.join(" > ")
results[assertion.i].message = message
results[assertion.i].error = error != null ? error : ensureStackTrace(new Error)
}
function serialize(value) {
if (hasProcess) return require("util").inspect(value) // eslint-disable-line global-require
if (value === null || (typeof value === "object" && !(value instanceof Array)) || typeof value === "number") return String(value)
else if (typeof value === "function") return value.name || "<anonymous function>"
try {return JSON.stringify(value)} catch (e) {return String(value)}
}
function noTimeoutRightNow() {
throw new Error("o.timeout must be called snchronously from within a test definition or a hook.")
}
var colorCodes = {
red: "31m",
red2: "31;1m",
green: "32;1m"
}
function highlight(message, color) {
var code = colorCodes[color] || colorCodes.red;
return hasProcess ? (process.stdout.isTTY ? "\x1b[" + code + message + "\x1b[0m" : message) : "%c" + message + "%c "
}
function cStyle(color, bold) {
return hasProcess||!color ? "" : "color:"+color+(bold ? ";font-weight:bold" : "")
}
function ensureStackTrace(error) {
// mandatory to get a stack in IE 10 and 11 (and maybe other envs?)
if (error.stack === undefined) try { throw error } catch(e) {return e}
else return error
}
function getStackName(e, exp) {
return e.stack && exp.test(e.stack) ? e.stack.match(exp)[1] : null
}
o.report = function (results) {
var errCount = 0
for (var i = 0, r; r = results[i]; i++) {
if (r.pass == null) {
r.testError.stack = r.message + "\n" + o.cleanStackTrace(r.testError)
r.testError.message = r.message
throw r.testError
}
if (!r.pass) {
var stackTrace = o.cleanStackTrace(r.error)
var couldHaveABetterStackTrace = !stackTrace || timeoutStackName != null && stackTrace.indexOf(timeoutStackName) !== -1
if (couldHaveABetterStackTrace) stackTrace = r.testError != null ? o.cleanStackTrace(r.testError) : r.error.stack || ""
console.error(
(hasProcess ? "\n" : "") +
highlight(r.context + ":", "red2") + "\n" +
highlight(r.message, "red") +
(stackTrace ? "\n" + stackTrace + "\n" : ""),
cStyle("black", true), "", // reset to default
cStyle("red"), cStyle("black")
)
errCount++
}
}
var pl = results.length === 1 ? "" : "s"
var resultSummary = (errCount === 0) ?
highlight((pl ? "All " : "The ") + results.length + " assertion" + pl + " passed", "green"):
highlight(errCount + " out of " + results.length + " assertion" + pl + " failed", "red2")
var runningTime = " in " + Math.round(Date.now() - start) + "ms"
console.log(
(hasProcess ? "––––––\n" : "") +
(name ? name + ": " : "") + resultSummary + runningTime,
cStyle((errCount === 0 ? "green" : "red"), true), ""
)
return errCount
}
if (hasProcess) {
nextTickish = process.nextTick
} else {
nextTickish = function fakeFastNextTick(next) {
if (stack++ < 5000) next()
else setTimeout(next, stack = 0)
}
}
return o
})
|
version https://git-lfs.github.com/spec/v1
oid sha256:c06f2e9547bd4de53c941d51fe6cb23a056852096115e73799c03835b88d9b1f
size 63066
|
// fixtures/basic.fixture.html
var template = function (_swig,_ctx,_filters,_utils,_fn) {
var _ext = _swig.extensions,
_output = "";
_output += _filters["e"]((((typeof _ctx.foo !== "undefined" && _ctx.foo !== null) ? ((typeof _ctx.foo !== "undefined" && _ctx.foo !== null) ? _ctx.foo : "") : ((typeof foo !== "undefined" && foo !== null) ? foo : "")) !== null ? ((typeof _ctx.foo !== "undefined" && _ctx.foo !== null) ? ((typeof _ctx.foo !== "undefined" && _ctx.foo !== null) ? _ctx.foo : "") : ((typeof foo !== "undefined" && foo !== null) ? foo : "")) : "" ));
return _output;
};
|
'use strict';
var vkey = require('vkey');
var fromUnicode = require('./utext').fromUnicode;
// map virtual key to Unicode corresponding to trit-text, with modifiers
var _keymap = {
// vkey: normal, shifted, control, shift-control
A: ['a', 'A', '☺', ''],
B: ['b', 'B', '☻', ''],
C: ['c', 'C', '♥', ''],
D: ['d', 'D', '♦', ''],
E: ['e', 'E', '•', ''],
F: ['f', 'F', '◘', ''],
G: ['g', 'G', '○', ''],
H: ['h', 'H', '◙', ''],
I: ['i', 'I', '♂', ''],
J: ['j', 'J', '♀', ''],
K: ['k', 'K', '☼', ''],
L: ['l', 'L', '▒', ''],
M: ['m', 'M', '←', ''],
N: ['n', 'N', '→', ''],
O: ['o', 'O', '↑', ''],
P: ['p', 'P', '↓', ''],
Q: ['q', 'Q', '', ''],
R: ['r', 'R', '', ''],
S: ['s', 'S', '', ''],
T: ['t', 'T', '', ''],
U: ['u', 'U', '', ''],
V: ['v', 'V', '', ''],
W: ['w', 'W', '', ''],
X: ['x', 'X', '≈', ''],
Y: ['y', 'Y', '', ''],
Z: ['z', 'Z', '', ''],
'`': ['`', '~', '', ''],
1: ['1', '!', '', ''],
2: ['2', '@', '', '\u0000'],
3: ['3', '#', '', ''],
4: ['4', '$', '', ''],
5: ['5', '%', '', ''],
6: ['6', '^', '', ''],
7: ['7', '&', '', ''],
8: ['8', '*', '', ''],
9: ['9', '(', '', ''],
0: ['0', ')', '', ''],
'-': ['-', '_', '‾', ''],
'=': ['=', '+', '±', '∓'],
'[': ['[', '{', '', ''],
']': [']', '}', '', ''],
'\\': ['\\', '|', '', ''],
';': [';', ':', '', ''],
'\'': ['\\', '"', '', ''],
',': [',', '<', '«', ''],
'.': ['.', '>', '»', ''],
'/': ['/', '?', '', ''],
'<backspace>': ['\u0000', '\u0000', '', ''], // null for now, seems reasonable TODO: shift/control backspace?
'<escape>': ['⌂', '⌂', '', ''],
'<enter>': ['\n', '\n', '', ''],
'<space>': [' ', ' ', ' ', ' '],
};
function fromEvent(ev) {
var vkeyChar = vkey[ev.keyCode];
var flags = (ev.shiftKey ? 1 : 0) + (ev.ctrlKey ? 2 : 0); // TODO: metaKey(cmd)? altKey(opt)?
var varChars = _keymap[vkeyChar];
if (!varChars) return null;
if (varChars[flags] === '' && flags === 3) flags = 2; // no shift-control variant, try control
if (varChars[flags] === '' && flags === 2) flags = 0; // no control variant, try normal
var c = varChars[flags];
var tt = fromUnicode(c);
if (tt == null) return null;
if (ev.altKey) tt = -tt; // alt/option key inverts
return tt;
}
module.exports = fromEvent;
|
module.exports = function isPrimitive(arg) {
return arg === null ||
typeof arg === 'boolean' ||
typeof arg === 'number' ||
typeof arg === 'string' ||
typeof arg === 'symbol' || // ES6 symbol
typeof arg === 'undefined';
}
|
import React, { Component } from 'react';
import {
Text,
View
} from 'react-native';
import styles from './style';
const Favorite = () => (
<View style={styles.container}>
<Text>
This is the Favorite page, I beg to be implemented
</Text>
</View>
);
export default Favorite;
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";
// Include required modules
var prefs = require("../../../../lib/prefs");
var tabs = require("../../../lib/tabs");
var utils = require("../../../../lib/utils");
var browser = require("../../../lib/ui/browser");
const BASE_URL = collector.addHttpResource("../../../../data/");
const TEST_DATA = BASE_URL + "geolocation/position.html";
const PREF_WIFI_LOGGING = "geo.wifi.logging.enabled";
const TIMEOUT_POSITION = 30000;
function setupModule(aModule) {
// Only geolocation test that tests 3rd party services
// Run this test only against Nightly
if (!utils.appInfo.version.contains("a1")) {
var message = "Geolocation service integration test runs only on Nightly";
testVerifyDisplayGeolocationNotification.__force_skip__ = message;
teardownModule.__force_skip__ = message;
}
aModule.browserWindow = new browser.BrowserWindow();
aModule.controller = aModule.browserWindow.controller;
aModule.locationBar = aModule.browserWindow.navBar.locationBar;
aModule.tabBrowser = new tabs.tabBrowser(aModule.controller);
prefs.setPref(PREF_WIFI_LOGGING, true);
aModule.tabBrowser.closeAllTabs();
}
function teardownModule(aModule) {
prefs.clearUserPref(PREF_WIFI_LOGGING);
aModule.tabBrowser.closeAllTabs();
}
/**
* Test displaying geolocation notification
*/
function testVerifyDisplayGeolocationNotification() {
// Wait for the notification to be opened and check its icon in the location bar
locationBar.waitForNotificationPanel(() => {
controller.open(TEST_DATA);
controller.waitForPageLoad();
}, {type: "notification"});
// Check the geolocation icon is visible in the location bar
var geolocationIcon = locationBar.getElement({type: "notificationIcon",
subtype: "geo"});
expect.ok(geolocationIcon.getNode(), "The notification icon has been found");
// Check the icon inside the popup notification exists
var icon = locationBar.getNotificationElement("geolocation-notification",
{type: "popupid", value: "geolocation"});
expect.ok(icon, "The geolocation icon appears in the notification popup");
// Check if a Share Location button is visible
var locationLabel = utils.getProperty("chrome://browser/locale/browser.properties",
"geolocation.shareLocation");
var button = locationBar.getNotificationElement("geolocation-notification",
{type: "label", value: locationLabel});
expect.ok(button, "'Share location' button appears in the notification popup");
// Wait for the notification to unload
locationBar.waitForNotificationPanel(() => {
button.click();
}, {type: "notification", open: false});
// Check if the location is displayed
// The position updates lazily so additional timeout is needed
var result = new elementslib.ID(controller.tabs.activeTab, "result");
var regExp = /\d+(\.\d*)?\.\d+/;
try {
assert.waitFor(function () {
return regExp.test(result.getNode().textContent);
}, "", TIMEOUT_POSITION);
}
catch (e) {
assert.fail("Geolocation position is: " + result.getNode().textContent);
}
}
|
this["templates"] = this["templates"] || {};
this["templates"]["Basic"] = (function() {
var frag;
function anonymous(data_0) {
var frag = document.createDocumentFragment();
var data = data_0;
var el0 = document.createTextNode("I'm a basic template, yippee!");
frag.appendChild(el0);
return frag;
}
return function template() {
if (!frag) {
frag = anonymous();
}
return frag.cloneNode(true);
};
}());
|
$('ul.dropdown-menu [data-toggle=dropdown]').on('click', function(event) {
// Avoid following the href location when clicking
event.preventDefault();
// Avoid having the menu to close when clicking
event.stopPropagation();
// Re-add .open to parent sub-menu item
$(this).parent().addClass('open');
$(this).parent().find("ul").parent().find("li.dropdown").addClass('open');
});
//making the carousel have a 10 seconds delay
$('.carousel').carousel({
interval: 10000
})
|
export let redditPost = function(state = {}, action) {
return state;
};
|
module.exports = {
publicPath: process.env.NODE_ENV === 'production'
? '/dist/'
: '/',
devServer: {
proxy: {
'/api/v1': {
target: 'http://localhost:8078',
secure: false
},
'/static/': {
target: 'http://localhost:8078',
secure: false
}
}
}
};
|
// Copyright (c) 2014 The Polymer Project Authors. All rights reserved.
// This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
// The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
// The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
// Code distributed by Google as part of the polymer project is also
// subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
var console = {
log: print,
error: print
};
var timeouts = []
function setTimeout(fn) {
timeouts.push(fn);
}
function runTimeouts() {
while (timeouts.length) {
if (Object.deliverAllChangeRecords)
Object.deliverAllChangeRecords();
timeouts.shift()();
}
}
function Window() {}
var window = new Window();
function Event(type) {
this.type = type;
}
Event.prototype = {
initMouseEvent: function() {}
}
function Node(owner) {
this.ownerDocument = owner;
this.parentNode = null;
this.nextSibling = null;
this.previousSibling = null;
this.firstChild = null;
this.lastChild = null;
}
Node.prototype = {
addEventListener: function() {},
set textContent(content) {
this.data = content;
},
get textContent() {
return this.data;
},
dispatchEvent: function() {},
appendChild: function(node) {
if (node instanceof DocumentFragment) {
while (node.firstChild) {
this.appendChild(node.firstChild);
}
return;
}
if (node.parentNode) {
node.parentNode.removeChild(node);
}
node.parentNode = this;
if (!this.firstChild) {
this.firstChild = node;
this.lastChild = node;
} else {
this.lastChild.nextSibling = node;
node.previousSibling = this.lastChild;
this.lastChild = node;
}
return node;
},
removeChild: function(node) {
if (node.parentNode != this) {
throw Error('NotFoundError');
}
if (!node.previousSibling && !node.nextSibling) {
this.firstChild = null;
this.lastChild = null;
} else if (!node.previousSibling) {
this.firstChild = node.nextSibling;
node.nextSibling.previousSibling = null;
} else if (!node.nextSibling) {
this.lastChild = node.previousSibling;
node.previousSibling.nextSibling = null;
} else {
node.previousSibling.nextSibling = node.nextSibling;
node.nextSibling.previousSibling = node.previousSibling;
}
node.parentNode = null;
node.previousSibling = null;
node.nextSibling = null;
return node;
},
insertBefore: function(node, otherNode) {
if (node.parentNode)
node.parentNode.removeChild(node);
if (node instanceof DocumentFragment) {
while (node.firstChild) {
this.insertBefore(node.firstChild, otherNode);
}
return node;
}
if (!otherNode || otherNode.parentNode !== this)
return this.appendChild(node);
if (!otherNode.previousSibling) {
otherNode.previousSibling = node;
node.previousSibling = null;
node.nextSibling = otherNode;
this.firstChild = node;
} else {
otherNode.previousSibling.nextSibling = node;
node.previousSibling = node.previousSibling;
node.nextSibling = otherNode;
otherNode.previousSibling = node;
}
node.parentNode = this;
return node;
},
cloneNode: function(deep) {
var clone = this.cloneNode_();
if (deep) {
for (var child = this.firstChild; child; child = child.nextSibling) {
var c = child.cloneNode(deep);
clone.appendChild(c);
}
}
return clone;
},
get childNodes() {
var retval = [];
for (var child = this.firstChild; child; child = child.nextSibling)
retval.push(child);
return retval;
},
set innerHTML(_) {
while (this.firstChild) {
this.removeChild(this.firstChild);
}
},
dump: function(pre) {
var prefix = '';
for (var i = 0; i < pre; i++)
prefix += ' ';
print(prefix + this.toString());
for (var child = this.firstChild; child; child = child.nextSibling)
child.dump(pre + 2);
}
}
Node.ELEMENT_NODE = 1;
Node.TEXT_NODE = 3;
Node.DOCUMENT_FRAGMENT_NODE = 11;
Node.DOCUMENT_NODE = 9;
function Document(defaultView) {
Node.call(this, null);
this.defaultView = defaultView;
this.templateContentsOwnerDocument = defaultView ? new Document() : this;
}
Document.prototype = {
__proto__: Node.prototype,
nodeType: Node.DOCUMENT_NODE,
implementation: {
createHTMLDocument: function() {
var doc = new Document();
var html = doc.appendChild(doc.createElement('HTML'));
var head = html.appendChild(doc.createElement('HEAD'));
doc.head = head;
var body = html.appendChild(doc.createElement('BODY'));
doc.body = body;
return doc;
}
},
importNode: function(node) {
var clone = node.cloneNode(false);
clone.ownerDocument = this;
return clone;
},
createElement: function(tagName) {
var n = this.createElement_(tagName);
return n;
},
createElement_: function(tagName) {
tagName = tagName.toUpperCase();
switch(tagName) {
case 'DIV':
return new HTMLDivElement(this, tagName);
case 'INPUT':
return new HTMLInputElement(this, tagName);
case 'P':
return new HTMLParagraphElement(this, tagName);
case 'SPAN':
return new HTMLSpanElement(this, tagName);
case 'H1':
case 'H2':
return new HTMLHeadingElement(this, tagName);
case 'TEMPLATE':
return new HTMLTemplateElement(this, tagName);
case 'HTML':
return new HTMLHtmlElement(this, tagName);
case 'HEAD':
return new HTMLHeadElement(this, tagName);
case 'BODY':
return new HTMLBodyElement(this, tagName);
case 'BASE':
return new HTMLBaseElement(this, tagName)
default:
throw Error('Unknown tag: ' + tagName);
}
},
createEvent: function(type) {
return new Event(type);
},
createDocumentFragment: function() {
return new DocumentFragment();
},
createTextNode: function(data) {
return new Text(this, data);
}
}
var document = new Document(window);
function DocumentFragment(owner) {
Node.call(this, owner);
}
DocumentFragment.prototype = {
__proto__: Node.prototype,
nodeType: Node.DOCUMENT_FRAGMENT_NODE,
cloneNode_: function() {
return new DocumentFragment(this.ownerDocument);
},
toString: function() {
return '#document-fragment';
},
querySelectorAll: function() {
return [];
}
};
function Text(owner, data) {
Node.call(this, owner);
this.data = data;
}
Text.prototype = {
__proto__: Node.prototype,
nodeType: Node.TEXT_NODE,
cloneNode_: function() {
return new Text(this.ownerDocument, this.data);
},
toString: function() {
return '#text: ' + this.data;
}
};
function Element(owner, tagName) {
Node.call(this, owner);
this.tagName = tagName;
this.attributes = [];
};
Element.prototype = {
__proto__: Node.prototype,
nodeType: Node.ELEMENT_NODE,
cloneNode_: function() {
var c = this.ownerDocument.createElement(this.tagName);
for (var i = 0; i < this.attributes.length; i++)
c.attributes.push(this.attributes[i]);
return c;
},
setAttribute: function(name, value) {
this.attributes.push({ name: name, value: value });
},
getAttribute: function(name) {
var count = this.attributes.length;
while (count-- > 0) {
if (this.attributes[count].name === name)
return this.attributes[count].value;
}
return null;
},
hasAttribute: function(name) {
var count = this.attributes.length;
while (count-- > 0) {
if (this.attributes[count].name === name)
return true;
}
return false;
},
toString: function() {
var string = '<' + this.tagName + '>[';
var attrs = {};
var count = this.attributes.length;
while (count-- > 0) {
var attr = this.attributes[count];
if (attrs[attr.name])
continue;
string += attr.name + '=' + attr.value + ', ';
attrs[attr.name] = true;
}
string += ']';
return string;
},
};
function HTMLElement(owner, tagName) {
Element.call(this, owner, tagName);
}
HTMLElement.prototype = {
__proto__: Element.prototype
};
function HTMLDivElement(owner, tagName) {
HTMLElement.call(this, owner, tagName);
}
HTMLDivElement.prototype = {
__proto__: HTMLElement.prototype
};
function HTMLInputElement(owner, tagName) {
HTMLElement.call(this, owner, tagName);
}
HTMLInputElement.prototype = {
__proto__: HTMLElement.prototype
};
function HTMLTextAreaElement(owner, tagName) {
HTMLElement.call(this, owner, tagName);
}
HTMLTextAreaElement.prototype = {
__proto__: HTMLElement.prototype
};
function HTMLOptionElement(owner, tagName) {
HTMLElement.call(this, owner, tagName);
}
HTMLOptionElement.prototype = {
__proto__: HTMLElement.prototype
};
function HTMLSelectElement(owner, tagName) {
HTMLElement.call(this, owner, tagName);
}
HTMLSelectElement.prototype = {
__proto__: HTMLElement.prototype
};
function HTMLParagraphElement(owner, tagName) {
HTMLElement.call(this, owner, tagName);
}
HTMLParagraphElement.prototype = {
__proto__: HTMLElement.prototype
};
function HTMLSpanElement(owner, tagName) {
HTMLElement.call(this, owner, tagName);
}
HTMLSpanElement.prototype = {
__proto__: HTMLElement.prototype
};
function HTMLHeadingElement(owner, tagName) {
HTMLElement.call(this, owner, tagName);
}
HTMLHeadingElement.prototype = {
__proto__: HTMLElement.prototype
};
function HTMLTemplateElement(owner, tagName) {
HTMLElement.call(this, owner, tagName);
this.content = new DocumentFragment(owner.templateContentsOwnerDocument);
}
HTMLTemplateElement.prototype = {
__proto__: HTMLElement.prototype,
};
function HTMLHtmlElement(owner, tagName) {
HTMLElement.call(this, owner, tagName);
}
HTMLHtmlElement.prototype = {
__proto__: HTMLElement.prototype
};
function HTMLHeadElement(owner, tagName) {
HTMLElement.call(this, owner, tagName);
}
HTMLHeadElement.prototype = {
__proto__: HTMLElement.prototype
};
function HTMLBodyElement(owner, tagName) {
HTMLElement.call(this, owner, tagName);
}
HTMLBodyElement.prototype = {
__proto__: HTMLElement.prototype
};
function HTMLBaseElement(owner, tagName) {
HTMLElement.call(this, owner, tagName);
}
HTMLBaseElement.prototype = {
__proto__: HTMLElement.prototype
};
|
import { gql, graphql } from 'react-apollo'
import persist from '../lib/persist'
import React from 'react'
import {
Button,
} from 'react-native'
const Logout = ({ logout }) => {
return (
<Button onPress={logout} title='LogOut'></Button>
)
}
const logout = gql`
mutation logout {
logout {
loggedOutAt
}
errors {
code
message
}
}
`
Logout.propTypes = () => ({
logout: React.PropTypes.func.isRequired
})
export default graphql(logout, {
props: ({ mutate }) => ({
logout: () => mutate({
updateQueries: {
userProfile: () => {
// Clear session
persist.willRemoveSessionToken()
// Provide no user
return { user: null, errors: [] }
}
}
})
})
})(Logout)
|
import Em from 'ember';
import { test } from 'ember-qunit';
import startApp from '../helpers/start-app';
import config from 'dummy/config/environment';
var App;
module('Ember CLI Concat', {
setup: function() {
App = startApp();
},
teardown: function() {
Em.run(App, 'reset');
}
});
var checkTagExists = function(fileName) {
var isCSS = fileName.indexOf('.css') > -1;
var attribute = isCSS ? 'href' : 'src';
var element = isCSS ? 'link' : 'script';
var tagExists = $(element + '[' + attribute + '="/assets/' + fileName + '"]').length === 1;
ok(tagExists, fileName + ' ' + element + ' tag should be written to to the index.html file');
};
test('Assets added to index.html file', function() {
andThen(function() {
var env = config.environment;
var appFiles, vendorFiles, testFiles;
if (env === 'development') {
checkTagExists('dummy.css');
checkTagExists('vendor.css');
checkTagExists('dummy.js');
checkTagExists('vendor.js');
if (App.testing) {
checkTagExists('test-support.css');
checkTagExists('test-support.js');
}
} else if (env === 'production') {
/* TODO - Currently can't run tests in production environment */
checkTagExists('app.css');
checkTagExists('app.js');
} else {
expect(0);
}
});
});
|
var PeerServer = require('peer').PeerServer
var Topics = require('./public/js/Topics.js')
var Hapi = require('hapi')
var server = new Hapi.Server({})
server.connection({
port: Number(process.env.PORT) || 8000
})
server.register(require('inert'), function (err) {
if (err) {
throw err
}
server.route({
method: 'GET',
path: '/{param*}',
handler: {
directory: {
path: __dirname + '/public'
}
}
})
server.start(function (err) {
if (err) {
throw err
}
console.log('Server running at:', server.info.uri)
})
})
var io = require('socket.io').listen(server.listener)
var peerServer = new PeerServer({ port: 9000, path: '/chat' })
peerServer.on('connection', function (id) {
io.emit(Topics.USER_CONNECTED, id)
console.log('User connected with #', id)
})
peerServer.on('disconnect', function (id) {
io.emit(Topics.USER_DISCONNECTED, id)
console.log('With #', id, 'user disconnected.')
})
|
/* globals makeAuthRequest,Materialize,micromarkdown,cleanMarkdown */
/* jshint -W003 */ // ugh I'm done with rearranging
"use strict";
var drug, allDrugs, allConsumptions = [],
allExperiences;
var analyticsCount = 0;
var analyticsFinished = 0;
// just get jshint off our back. these are defined in their respective files
var vitals, experience_list, top_listings, hours_days, purchasing;
var autoStart, countdown = 5,
updateInterval;
var hasSelected = false;
function drugSelected() {
if ($('#drug').val().indexOf('dup') > -1) {
$('#drug').val($('#drug').val().split('-')[1]); // break out dups from menu
}
allDrugs.forEach(function(singleDrug) {
if (singleDrug.id === parseInt($('#drug').val())) {
if (location.search.length < 1) {
// only set if we haven't set already, otherwise the page refreshes and we infiniloop
location.search = singleDrug.id;
}
drug = singleDrug;
return;
}
});
document.title = drug.name.substr(0, 1).toUpperCase() + drug.name.substr(1) + ' | SupTracked';
$('.drugName').text(drug.name);
$('#unit').html(drug.unit);
$('#classification').html(drug.classification);
$('#family').html(drug.family);
switch (parseInt(drug.rarity)) {
case 0:
$('#rarity').html('<span class="blue white-text" style="padding: 3px; border-radius: 24px;">Very Common</span>');
break;
case 1:
$('#rarity').html('<span class="green white-text" style="padding: 3px; border-radius: 24px;">Common</span>');
break;
case 2:
$('#rarity').html('<span class="purple white-text" style="padding: 3px; border-radius: 24px;">Uncommon</span>');
break;
case 3:
$('#rarity').html('<span class="red white-text" style="padding: 3px; border-radius: 24px;">Rare</span>');
break;
default:
$('#rarity').html('<span class="grey white-text" style="padding: 3px; border-radius: 24px;">???</span>');
}
$('#notes').html(cleanMarkdown(micromarkdown.parse(drug.notes.split('$$$purchasedata$$$')[0])));
// compile all consumptions
makeAuthRequest('/consumption/search', 'POST', JSON.stringify({
drug_id: drug.id
}), 'json', function(err, data, code) {
allExperiences = data;
if (data) {
data.forEach(function(experience) {
experience.consumptions.forEach(function(consumption) {
if (consumption.drug.id === drug.id) {
consumption.title = experience.title;
consumption.exp_id = experience.id;
allConsumptions.push(consumption);
}
});
});
// sort in ascending date
allConsumptions.sort(function(a, b) {
return (a.date < b.date) ? -1 : (a.date > b.date) ? 1 : 0;
});
$('#drugEntry').attr('href', '/drugs.html?' + drug.id);
// off we go!
startAnalytics();
} else {
$('#selection').hide();
$('#none').show();
analyticsFinished = analyticsCount;
}
});
}
// set up the completion listener
updateInterval = setInterval(function updateCompletion() {
var percentage = Math.round(analyticsFinished / analyticsCount) * 100;
$('#analyticsComplete').text(percentage + '%');
$('#analyticsProgress').css('width', percentage + '%');
if (analyticsFinished === analyticsCount || window.location.hash.substring(1).indexOf('skip') > -1) {
// we're done here; display it after an aesthetic delay for the progress bar to hit 100%
setTimeout(function() {
clearInterval(updateInterval);
$('#loading').hide();
$('#analytics').show();
}, 500);
}
}, 100);
function startAnalytics() {
vitals();
experience_list();
top_listings();
hours_days();
purchasing();
}
// populate the drug dropdown
makeAuthRequest('/drug/all', 'GET', null, 'json', function(err, data, code) {
if (data.length < 1) {
$('#none').show();
return;
}
allDrugs = data.sort(function(a, b) {
a = a.name.toLowerCase();
b = b.name.toLowerCase();
return (a < b) ? -1 : (a > b) ? 1 : 0;
});
var drugsByUsage = allDrugs.slice();
drugsByUsage = drugsByUsage.sort(function(a, b) {
return b.use_count - a.use_count;
}).slice(0, 5);
$('#drug').append('<optgroup label="Common" id="common_dropdwngroup"></optgroup>');
drugsByUsage.forEach(function(drug, index, orig) {
$('#common_dropdwngroup').append('<option value="' + drug.id + '">' + drug.name + '</option>');
orig[index] = drug.id;
});
$('#drug').append('<optgroup label="All" id="all_dropdwngroup"></optgroup>');
allDrugs.forEach(function(drug) {
if (drugsByUsage.indexOf(drug.id) === -1) {
$('#all_dropdwngroup').append('<option value="' + drug.id + '">' + drug.name + '</option>');
} else {
$('#all_dropdwngroup').append('<option value="dup-' + drug.id + '">' + drug.name + '</option>');
}
});
var allIds = allDrugs.map(function(drug) {
return drug.id;
});
// we have a search
if (location.search.length > 1 && allIds.indexOf(Number(location.search.substr(1))) > -1) {
$('#drug').val(location.search.substr(1));
drugSelected();
} else {
$('#drug').val(drugsByUsage[0]);
drugSelected();
}
});
$('#drug').change(function(){
if($('#drug').val().indexOf('dup') > -1){
$('#drug').val($('#drug').val().split('dup-')[1]);
}
location.search = $('#drug').val();
});
|
import {log} from 'node-bits';
const select = (table, column) =>
`select max(${column}) from ${table}`;
const selectPostgres = (table, column) =>
`select max(${column}) from "${table}"`;
const resetPostgres = (table, column, max) =>
`alter sequence "${table}_${column}_seq" restart with ${max + 1}`;
const resetMssql = (table, column, max) =>
`DBCC CHECKIDENT ('[${table}]', RESEED, ${max + 1});`;
const resetMySQL = (sequelize, table, max) =>
`alter table ${table} AUTO_INCREMENT = ${max + 1};`;
const map = {
mysql: {select, reset: resetMySQL},
postgres: {select: selectPostgres, reset: resetPostgres},
mssql: {select, reset: resetMssql},
};
export const resetAutoIncrement = (sequelize, model) => {
const sqlGen = map[sequelize.getDialect()];
if (!sqlGen) {
return Promise.resolve();
}
const table = model.getTableName();
const column = 'id';
const select = sqlGen.select(table, column);
log(select);
return sequelize.query(select).then(result => {
const max = result[0][0].max;
const reset = sqlGen.reset(table, column, max);
log(reset);
return sequelize.query(reset);
});
};
|
'use strict';
module.exports = {
up: function (queryInterface, Sequelize) {
/*
Add altering commands here.
Return a promise to correctly handle asynchronicity.
Example:
return queryInterface.createTable('users', { id: Sequelize.INTEGER });
*/
return queryInterface.createTable(
'procedures',
{
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
rank: {
type: Sequelize.INTEGER,
defaultValue: 0,
allowNull: false
},
categoryId: {
type: Sequelize.INTEGER,
references: {
model: 'categories',
key: 'id'
}
},
createdAt: {
type: Sequelize.DATE,
defaultValue: Sequelize.NOW
},
updatedAt: {
type: Sequelize.DATE,
defaultValue: Sequelize.NOW
}
}
);
},
down: function (queryInterface, Sequelize) {
/*
Add reverting commands here.
Return a promise to correctly handle asynchronicity.
Example:
return queryInterface.dropTable('users');
*/
return queryInterface.dropTable('procedures');
}
};
|
/**
* @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 LoadTexture component manages the loading of a texture into the Game Object and the changing of frames.
*
* @class
*/
Phaser.Component.LoadTexture = function () {};
Phaser.Component.LoadTexture.prototype = {
/**
* @property {boolean} customRender - Does this texture require a custom render call? (as set by BitmapData, Video, etc)
* @private
*/
customRender: false,
/**
* @property {Phaser.Rectangle} _frame - Internal cache var.
* @private
*/
_frame: null,
/**
* Changes the base texture the Game Object is using. The old texture is removed and the new one is referenced or fetched from the Cache.
*
* If your Game Object is using a frame from a texture atlas and you just wish to change to another frame, then see the `frame` or `frameName` properties instead.
*
* You should only use `loadTexture` if you want to replace the base texture entirely.
*
* Calling this method causes a WebGL texture update, so use sparingly or in low-intensity portions of your game, or if you know the new texture is already on the GPU.
*
* You can use the new const `Phaser.PENDING_ATLAS` as the texture key for any sprite.
* Doing this then sets the key to be the `frame` argument (the frame is set to zero).
*
* This allows you to create sprites using `load.image` during development, and then change them
* to use a Texture Atlas later in development by simply searching your code for 'PENDING_ATLAS'
* and swapping it to be the key of the atlas data.
*
* Note: You cannot use a RenderTexture as a texture for a TileSprite.
*
* @method
* @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture.
* @param {string|number} [frame] - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index.
* @param {boolean} [stopAnimation=true] - If an animation is already playing on this Sprite you can choose to stop it or let it carry on playing.
*/
loadTexture: function (key, frame, stopAnimation)
{
if (key === Phaser.PENDING_ATLAS)
{
key = frame;
frame = 0;
}
else
{
frame = frame || 0;
}
if ((stopAnimation || stopAnimation === undefined) && this.animations)
{
this.animations.stop();
}
this.key = key;
this.customRender = false;
var cache = this.game.cache;
var setFrame = true;
var smoothed = !this.texture.baseTexture.scaleMode;
if (Phaser.RenderTexture && key instanceof Phaser.RenderTexture)
{
this.key = key.key;
this.setTexture(key);
}
else if (Phaser.BitmapData && key instanceof Phaser.BitmapData)
{
this.customRender = true;
this.setTexture(key.texture);
if (cache.hasFrameData(key.key, Phaser.Cache.BITMAPDATA))
{
setFrame = !this.animations.loadFrameData(cache.getFrameData(key.key, Phaser.Cache.BITMAPDATA), frame);
}
else
{
setFrame = !this.animations.loadFrameData(key.frameData, 0);
}
}
else if (Phaser.Video && key instanceof Phaser.Video)
{
this.customRender = true;
// This works from a reference, which probably isn't what we need here
var valid = key.texture.valid;
this.setTexture(key.texture);
this.setFrame(key.texture.frame.clone());
key.onChangeSource.add(this.resizeFrame, this);
this.texture.valid = valid;
}
else if (Phaser.Tilemap && key instanceof Phaser.TilemapLayer)
{
// this.customRender = true;
this.setTexture(PIXI.Texture.fromCanvas(key.canvas));
}
else if (key instanceof PIXI.Texture)
{
this.setTexture(key);
}
else
{
var img = cache.getImage(key, true);
this.key = img.key;
this.setTexture(new PIXI.Texture(img.base));
if (key === '__default')
{
this.texture.baseTexture.skipRender = true;
}
else
{
this.texture.baseTexture.skipRender = false;
}
setFrame = !this.animations.loadFrameData(img.frameData, frame);
}
if (setFrame)
{
this._frame = Phaser.Rectangle.clone(this.texture.frame);
}
if (!smoothed)
{
this.texture.baseTexture.scaleMode = 1;
}
},
/**
* Sets the texture frame the Game Object uses for rendering.
*
* This is primarily an internal method used by `loadTexture`, but is exposed for the use of plugins and custom classes.
*
* @method
* @param {Phaser.Frame} frame - The Frame to be used by the texture.
*/
setFrame: function (frame)
{
this._frame = frame;
this.texture.frame.x = frame.x;
this.texture.frame.y = frame.y;
this.texture.frame.width = frame.width;
this.texture.frame.height = frame.height;
this.texture.crop.x = frame.x;
this.texture.crop.y = frame.y;
this.texture.crop.width = frame.width;
this.texture.crop.height = frame.height;
if (frame.trimmed)
{
if (this.texture.trim)
{
this.texture.trim.x = frame.spriteSourceSizeX;
this.texture.trim.y = frame.spriteSourceSizeY;
this.texture.trim.width = frame.sourceSizeW;
this.texture.trim.height = frame.sourceSizeH;
}
else
{
this.texture.trim = { x: frame.spriteSourceSizeX, y: frame.spriteSourceSizeY, width: frame.sourceSizeW, height: frame.sourceSizeH };
}
this.texture.width = frame.sourceSizeW;
this.texture.height = frame.sourceSizeH;
this.texture.frame.width = frame.sourceSizeW;
this.texture.frame.height = frame.sourceSizeH;
}
else if (!frame.trimmed && this.texture.trim)
{
this.texture.trim = null;
}
if (frame.rotated)
{
this.texture.rotated = true;
}
if (this.cropRect)
{
this.updateCrop();
}
this.texture.requiresReTint = true;
this.texture._updateUvs();
if (this.tilingTexture)
{
this.refreshTexture = true;
}
},
/**
* Resizes the Frame dimensions that the Game Object uses for rendering.
*
* You shouldn't normally need to ever call this, but in the case of special texture types such as Video or BitmapData
* it can be useful to adjust the dimensions directly in this way.
*
* @method
* @param {object} parent - The parent texture object that caused the resize, i.e. a Phaser.Video object.
* @param {integer} width - The new width of the texture.
* @param {integer} height - The new height of the texture.
*/
resizeFrame: function (parent, width, height)
{
this.texture.frame.resize(width, height);
this.texture.setFrame(this.texture.frame);
},
/**
* Resets the texture frame dimensions that the Game Object uses for rendering.
*
* @method
*/
resetFrame: function ()
{
if (this._frame)
{
this.setFrame(this._frame);
}
},
/**
* Gets or sets the current frame index of the texture being used to render this Game Object.
*
* To change the frame set `frame` to the index of the new frame in the sprite sheet you wish this Game Object to use,
* for example: `player.frame = 4`.
*
* If the frame index given doesn't exist it will revert to the first frame found in the texture.
*
* If you are using a texture atlas then you should use the `frameName` property instead.
*
* If you wish to fully replace the texture being used see `loadTexture`.
* @property {integer} frame
*/
frame: {
get: function ()
{
return this.animations.frame;
},
set: function (value)
{
this.animations.frame = value;
}
},
/**
* Gets or sets the current frame name of the texture being used to render this Game Object.
*
* To change the frame set `frameName` to the name of the new frame in the texture atlas you wish this Game Object to use,
* for example: `player.frameName = "idle"`.
*
* If the frame name given doesn't exist it will revert to the first frame found in the texture and throw a console warning.
*
* If you are using a sprite sheet then you should use the `frame` property instead.
*
* If you wish to fully replace the texture being used see `loadTexture`.
* @property {string} frameName
*/
frameName: {
get: function ()
{
return this.animations.frameName;
},
set: function (value)
{
this.animations.frameName = value;
}
}
};
|
/**
* Created by zhoujialin on 2016/5/4.
*/
const LinkedStateMixin = React.addons.LinkedStateMixin;
// 数据双向绑定
const Comp = React.createClass({
displayname: 'Comp',
mixins:[LinkedStateMixin],
getInitialState(){
return {
name:''
}
},
render(){
return <div>
{this.state.name}
<input type="text" valueLink={this.linkState('name')} />
</div>
}
});
ReactDOM.render(<Comp/>, document.body);
|
import Component from '@ember/component'
import layout from '../../templates/components/bs-table-pagination/table-row'
export default Component.extend({
layout,
tagName: 'tr'
})
|
import {ObserverLocator} from 'aurelia-binding';
import {HttpClient} from 'aurelia-fetch-client';
import breeze from 'breeze-client';
import {Q} from './promise-adapter';
import {BreezeObservationAdapter} from './observation-adapter';
import {AjaxAdapter} from './ajax-adapter'; //eslint-disable-line no-unused-vars
export function configure(frameworkConfig) {
// ensure breeze is using the modelLibrary backing store (vs Knockout or Backbone)
breeze.config.initializeAdapterInstance('modelLibrary', 'backingStore');
// make breeze use our ES6 Promise based version of Q.
breeze.config.setQ(Q);
// provide aurelia with a way to observe breeze properties.
frameworkConfig.container.get(ObserverLocator).addAdapter(new BreezeObservationAdapter());
// provide the ajax adapter with an HttpClient factory...
// the adapter lazily gets the HttpClient instance to enable scenarios where
// the aurelia-breeze plugin is installed prior to the HttpClient being
// configured in the container.
let adapter = breeze.config.initializeAdapterInstance('ajax', 'aurelia', true);
adapter.setHttpClientFactory(() => frameworkConfig.container.get(HttpClient));
}
|
(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', 'UA-51965342-1', 'yaggirbalochi.github.io');
ga('send', 'pageview');
|
'use strict';
angular.module('myApp.products', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/products', {
templateUrl: 'views/products/products-tpl.html',
controller: 'ProductsCtrl'
});
}])
.controller('ProductsCtrl', function($scope, apiInterfaceSrv) {
$scope.apiInterfaceSrv = apiInterfaceSrv;
apiInterfaceSrv.fetch();
$scope.paginationSettings = {
currentPage: 1,
itemsPerPage: 5,
maxSize: 5
}
}
);
|
Array.prototype.splice = function(start, num) {
var additions = $A(arguments).slice(2);
var delta = additions.length - num;
var newlen = this.length + delta;
if (delta >= 0) {
this.length += delta;
}
for (var i = start + num + delta; i < newlen + delta + 1; i++) {
this[i] = this[i - delta];
}
for (var j = start; j < start + additions.length; j++) {
this[j] = additions[j - start];
}
this.length = newlen;
return this;
};
|
const DEGREES_SYMBOL = '\u00B0';
const MINUTES_SYMBOL = "'";
function parseLatitude(latitude) {
return {
degrees: parseInt(latitude.substring(0, 2), 10),
minutes: parseInt(latitude.substring(2, 7), 10) / 1000.0,
direction: latitude[latitude.length - 1]
};
}
function parseLongitude(longitude) {
return {
degrees: parseInt(longitude.substring(0, 3), 10),
minutes: parseInt(longitude.substring(3, 8), 10) / 1000.0,
direction: longitude[longitude.length - 1]
};
}
function toDecimalDegrees(degreesAndMinutes) {
let direction = degreesAndMinutes.direction.toUpperCase();
let sign = (direction === 'N' || direction === 'E') ? 1 : -1;
return sign * (degreesAndMinutes.degrees + degreesAndMinutes.minutes / 60.0);
}
function formatDegreesMinutes(degMin) {
let deg = degMin.degrees.toFixed(0);
let min = degMin.minutes.toFixed(3);
let direction = degMin.direction;
return deg + DEGREES_SYMBOL + min + MINUTES_SYMBOL + direction;
}
export default function parseLatitudeLongitude(latLonString) {
let latitude = parseLatitude(latLonString.substring(0, 8));
let longitude = parseLongitude(latLonString.substring(8));
return {
lat: toDecimalDegrees(latitude),
lng: toDecimalDegrees(longitude),
formatted: formatDegreesMinutes(latitude) + ", " + formatDegreesMinutes(longitude)
};
}
|
import {Buttons} from '../game/input';
import {Menu, MenuPage, ButtonMenuItem, LabelMenuItem} from './menu';
import {DummyInputTarget, ProxyInputTarget} from '../player';
import StageSelectMenuPage from './stage-selection';
import React from 'react';
import {BabylonJS} from '../react-babylonjs';
import BABYLON from 'babylonjs';
import {render} from 'react-dom';
import MenuCamera from '../game/menuCamera';
export const heroesContext = require.context('../game/heroes', false, /\.js$/);
export const heroKeys = heroesContext.keys().filter(key => key !== './baseHero.js');
const styles = {
viewBlock: {
display: 'flex',
flexDirection: 'row',
},
playerViewFullBlock: {
margin: '20px',
},
playerViewBlock: {
border: '3px solid black',
backgroundColor: '#fefefe',
height: '220px',
width: '220px',
},
playerViewBlockText: {
fontSize: '1.2em',
fontWeight: '700',
padding: '10px 5px 10px 5px',
backgroundColor: '#fefefe',
border: '4px solid black',
},
lockedInText: {
fontSize: '1.5em',
fontWeight: '800',
padding: '10px 5px 10px 5px',
backgroundColor: '#66ff66',
border: '4px solid black',
},
};
class StageMenuPlayer extends React.Component {
constructor(props) {
super(props);
this.state = {
active: false,
lockedIn: false,
characterIndex: 0,
};
this.props.input.setTarget(Object.assign(new DummyInputTarget(), {
buttonDown: button => {
if (this.state.active) {
switch (button) {
case Buttons.A:
this.setState({
lockedIn: true,
});
break;
case Buttons.B:
if (this.state.lockedIn) {
this.setState({
lockedIn: false,
});
} else {
this.setState({
active: false,
});
}
}
if (!this.state.lockedIn) {
let changeHeroNumber = 0;
switch (button) {
case Buttons.JoyLeft:
changeHeroNumber = -1;
break;
case Buttons.JoyRight:
changeHeroNumber = 1;
break;
}
if (changeHeroNumber != 0) {
let newCharacterindex = (this.state.characterIndex + changeHeroNumber) % heroKeys.length;
if (newCharacterindex < 0) {
newCharacterindex = heroKeys.length - 1;
}
this.setState({
characterIndex: newCharacterindex,
});
//console.log(this.state.character)
this.loadDiffScene();
}
}
} else { // If not active
switch (button) {
case Buttons.A:
this.setState({
active: true,
});
break;
case Buttons.B:
this.props.wantsBack();
break;
}
}
},
}));
}
componentDidUpdate() {
this.props.stateChanged();
}
get active() {
return this.state.active;
}
get characterIndex() {
return this.state.characterIndex;
}
get lockedIn() {
return this.state.lockedIn;
}
doRenderLoop() {
this.scene.render();
}
loadDiffScene() {
if (this.mesh) {
this.mesh.dispose();
}
//loadMenuScene(this, 1);
require(`../../models/heroes/${heroesContext(heroKeys[this.state.characterIndex]).heroName}.blend`).ImportMesh(BABYLON.SceneLoader, null, this.scene, loadedMeshes => {
this.mesh = loadedMeshes[0];//.clone(this.name);
this.mesh.position.y -= 3;
console.log('props', this.props);
let id = this.props.player.index;
console.log(id);
let material = new BABYLON.StandardMaterial(id + 'playermaterialscene', this.scene);
let colId = function (id, mult) {
return Math.abs(((id * mult) % 255) / 255);
}
let color = new BABYLON.Color3(colId(id + .1, 50), colId(id + .2, -100), colId(id + 1, 200));
console.log(color);
material.diffuseColor = color;
material.specularColor = new BABYLON.Color3(1, 1, 1);
this.mesh.material = material;
let idleAnimation = this.mesh.skeleton.getAnimationRange('idle');
this.scene.beginAnimation(this.mesh.skeleton, idleAnimation.from+1, idleAnimation.to, true, 1);
});
}
onEngineCreated(engine) {
this.engine = engine;
engine.runRenderLoop(this.handleRenderLoop = () => this.doRenderLoop());
this.scene = new BABYLON.Scene(this.engine);
let camera = new MenuCamera(this, {min:7, max:9});
let dirLight = new BABYLON.DirectionalLight("dir01", new BABYLON.Vector3(1, -.7, 0), this.scene);
let dirLightStrength = 1;
dirLight.diffuse = new BABYLON.Color3(dirLightStrength,dirLightStrength,dirLightStrength);
dirLight.specular = new BABYLON.Color3(dirLightStrength,dirLightStrength,dirLightStrength);
dirLightStrength = .8;
let dirLight2 = new BABYLON.DirectionalLight("dir01", new BABYLON.Vector3(-1, -.3, .4), this.scene);
dirLight2.diffuse = new BABYLON.Color3(dirLightStrength,dirLightStrength,dirLightStrength);
dirLight2.specular = new BABYLON.Color3(dirLightStrength,dirLightStrength,dirLightStrength);
this.scene.clearColor = new BABYLON.Color3(.7, .7, .7);
this.loadDiffScene();
}
onEngineAbandoned() {
this.engine.stopRenderLoop(this.handleRenderLoop);
this.handleRenderLoop = null;
this.engine = null;
}
render() {
if (this.state.active) {
return <div style={styles.playerViewFullBlock}>
<p style={styles.playerViewBlockText}> {this.props.player.name} </p>
<div style={styles.playerViewBlock}>
<BabylonJS
onEngineCreated={engine => this.onEngineCreated(engine)}
onEngineAbandoned={engine => this.onEngineAbandoned(engine)}/>
<p style={styles.playerViewBlockText}> {heroesContext(heroKeys[this.state.characterIndex]).heroName} </p>
{this.state.lockedIn &&
<p style={styles.lockedInText}> LOCKED IN </p>
}
</div>
</div>;
}
return <div>
<p style={styles.playerViewBlockText}>{this.props.player.name} <br/>Press [attack1] to join.</p>
</div>
}
}
export default class CharacterSelectMenuPage extends React.Component {
constructor(props) {
super(props);
this.state = {
players: [],
};
this.playerRefs = [];
}
playerAskedForBack() {
// Only go back out of this menu if all players are inactive.
console.log(this);
if (this.playerRefs.find(p => p.active)) {
return;
}
this.props.menu.popMenuPage();
}
playerStateChanged() {
console.log('Player state changed');
if (!this.playerRefs.find(p => p.active && !p.lockedIn)
&& this.playerRefs.find(p => p.active && p.lockedIn)) {
console.log('Start Game');
console.log(this.playerRefs);
const playerInfo = this.playerRefs.reduce((acc, val, i) => {
if (val.active) {
acc[i] = {
characterIndex: val.characterIndex,
};
}
return acc;
}, {});
this.props.menu.pushMenuPage(<StageSelectMenuPage game={this.props.game} playerInfo={playerInfo}/>);
}
}
componentDidMount() {
this.props.players.setInputTargetFinder((i, player) => {
const proxy = new ProxyInputTarget(new DummyInputTarget());
// setState is not synchronous. To mutate an array in it multiple
// times before it applies the state update to this.state, must
// use the callback pattern: http://stackoverflow.com/a/41445812
this.setState(state => {
console.log(JSON.stringify(state.newPlayers));
const newPlayers = state.players.slice();
newPlayers[i] = <StageMenuPlayer
key={i}
player={player}
input={proxy}
ref={playerRef => this.playerRefs[i] = playerRef}
wantsBack={() => this.playerAskedForBack()}
stateChanged={() => this.playerStateChanged()} />;
return {
players: newPlayers,
};
});
return proxy;
});
}
render() {
return <div className="menu-page" style={styles.viewBlock}>
{this.state.players.filter(player => player)}
</div>;
}
}
|
version https://git-lfs.github.com/spec/v1
oid sha256:522e5fb03690b037ed9132d4318611bdd12b069343ae441a28118f819f94f2cf
size 678
|
!function(e){if("object"==typeof exports)module.exports=e();else if("function"==typeof define&&define.amd)define(e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.appstax=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
var hasOwn = Object.prototype.hasOwnProperty;
var toString = Object.prototype.toString;
var undefined;
var isPlainObject = function isPlainObject(obj) {
"use strict";
if (!obj || toString.call(obj) !== '[object Object]' || obj.nodeType || obj.setInterval) {
return false;
}
var has_own_constructor = hasOwn.call(obj, 'constructor');
var has_is_property_of_method = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf');
// Not own constructor property must be Object
if (obj.constructor && !has_own_constructor && !has_is_property_of_method) {
return false;
}
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
var key;
for (key in obj) {}
return key === undefined || hasOwn.call(obj, key);
};
module.exports = function extend() {
"use strict";
var options, name, src, copy, copyIsArray, clone,
target = arguments[0],
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if (typeof target === "boolean") {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
} else if (typeof target !== "object" && typeof target !== "function" || target == undefined) {
target = {};
}
for (; i < length; ++i) {
// Only deal with non-null/undefined values
if ((options = arguments[i]) != null) {
// Extend the base object
for (name in options) {
src = target[name];
copy = options[name];
// Prevent never-ending loop
if (target === copy) {
continue;
}
// Recurse if we're merging plain objects or arrays
if (deep && copy && (isPlainObject(copy) || (copyIsArray = Array.isArray(copy)))) {
if (copyIsArray) {
copyIsArray = false;
clone = src && Array.isArray(src) ? src : [];
} else {
clone = src && isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[name] = extend(deep, clone, copy);
// Don't bring in undefined values
} else if (copy !== undefined) {
target[name] = copy;
}
}
}
}
// Return the modified object
return target;
};
},{}],2:[function(_dereq_,module,exports){
// shim for using process in browser
var process = module.exports = {};
process.nextTick = (function () {
var canSetImmediate = typeof window !== 'undefined'
&& window.setImmediate;
var canPost = typeof window !== 'undefined'
&& window.postMessage && window.addEventListener
;
if (canSetImmediate) {
return function (f) { return window.setImmediate(f) };
}
if (canPost) {
var queue = [];
window.addEventListener('message', function (ev) {
var source = ev.source;
if ((source === window || source === null) && ev.data === 'process-tick') {
ev.stopPropagation();
if (queue.length > 0) {
var fn = queue.shift();
fn();
}
}
}, true);
return function nextTick(fn) {
queue.push(fn);
window.postMessage('process-tick', '*');
};
}
return function nextTick(fn) {
setTimeout(fn, 0);
};
})();
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.binding = function (name) {
throw new Error('process.binding is not supported');
}
// TODO(shtylman)
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
},{}],3:[function(_dereq_,module,exports){
(function (process){
/**
* An object representing a "promise" for a future value
*
* @param {?function(T, ?)=} onSuccess a function to handle successful
* resolution of this promise
* @param {?function(!Error, ?)=} onFail a function to handle failed
* resolution of this promise
* @constructor
* @template T
*/
function Promise(onSuccess, onFail) {
this.promise = this
this._isPromise = true
this._successFn = onSuccess
this._failFn = onFail
this._scope = this
this._boundArgs = null
this._hasContext = false
this._nextContext = undefined
this._currentContext = undefined
}
/**
* Specify that the current promise should have a specified context
* @param {*} context context
* @private
*/
Promise.prototype._useContext = function (context) {
this._nextContext = this._currentContext = context
this._hasContext = true
return this
}
Promise.prototype.clearContext = function () {
this._hasContext = false
this._nextContext = undefined
return this
}
/**
* Set the context for all promise handlers to follow
*
* NOTE(dpup): This should be considered deprecated. It does not do what most
* people would expect. The context will be passed as a second argument to all
* subsequent callbacks.
*
* @param {*} context An arbitrary context
*/
Promise.prototype.setContext = function (context) {
this._nextContext = context
this._hasContext = true
return this
}
/**
* Get the context for a promise
* @return {*} the context set by setContext
*/
Promise.prototype.getContext = function () {
return this._nextContext
}
/**
* Resolve this promise with a specified value
*
* @param {*=} data
*/
Promise.prototype.resolve = function (data) {
if (this._error || this._hasData) throw new Error("Unable to resolve or reject the same promise twice")
var i
if (data && isPromise(data)) {
this._child = data
if (this._promises) {
for (i = 0; i < this._promises.length; i += 1) {
data._chainPromise(this._promises[i])
}
delete this._promises
}
if (this._onComplete) {
for (i = 0; i < this._onComplete.length; i+= 1) {
data.fin(this._onComplete[i])
}
delete this._onComplete
}
} else if (data && isPromiseLike(data)) {
data.then(
function(data) { this.resolve(data) }.bind(this),
function(err) { this.reject(err) }.bind(this)
)
} else {
this._hasData = true
this._data = data
if (this._onComplete) {
for (i = 0; i < this._onComplete.length; i++) {
this._onComplete[i]()
}
}
if (this._promises) {
for (i = 0; i < this._promises.length; i += 1) {
this._promises[i]._withInput(data)
}
delete this._promises
}
}
}
/**
* Reject this promise with an error
*
* @param {!Error} e
*/
Promise.prototype.reject = function (e) {
if (this._error || this._hasData) throw new Error("Unable to resolve or reject the same promise twice")
var i
this._error = e
if (this._ended) {
process.nextTick(function onPromiseThrow() {
throw e
})
}
if (this._onComplete) {
for (i = 0; i < this._onComplete.length; i++) {
this._onComplete[i]()
}
}
if (this._promises) {
for (i = 0; i < this._promises.length; i += 1) {
this._promises[i]._withError(e)
}
delete this._promises
}
}
/**
* Provide a callback to be called whenever this promise successfully
* resolves. Allows for an optional second callback to handle the failure
* case.
*
* @param {?function(this:void, T, ?): RESULT|undefined} onSuccess
* @param {?function(this:void, !Error, ?): RESULT=} onFail
* @return {!Promise.<RESULT>} returns a new promise with the output of the onSuccess or
* onFail handler
* @template RESULT
*/
Promise.prototype.then = function (onSuccess, onFail) {
var promise = new Promise(onSuccess, onFail)
if (this._nextContext) promise._useContext(this._nextContext)
if (this._child) this._child._chainPromise(promise)
else this._chainPromise(promise)
return promise
}
/**
* Provide a callback to be called whenever this promise successfully
* resolves. The callback will be executed in the context of the provided scope.
*
* @param {function(this:SCOPE, T, ?): RESULT} onSuccess
* @param {SCOPE} scope Object whose context callback will be executed in.
* @param {...*} var_args Additional arguments to be passed to the promise callback.
* @return {!Promise.<RESULT>} returns a new promise with the output of the onSuccess
* @template SCOPE, RESULT
*/
Promise.prototype.thenBound = function (onSuccess, scope, var_args) {
var promise = new Promise(onSuccess)
if (this._nextContext) promise._useContext(this._nextContext)
promise._scope = scope
if (arguments.length > 2) {
promise._boundArgs = Array.prototype.slice.call(arguments, 2)
}
// Chaining must happen after setting args and scope since it may fire callback.
if (this._child) this._child._chainPromise(promise)
else this._chainPromise(promise)
return promise
}
/**
* Provide a callback to be called whenever this promise is rejected
*
* @param {function(this:void, !Error, ?)} onFail
* @return {!Promise.<T>} returns a new promise with the output of the onFail handler
*/
Promise.prototype.fail = function (onFail) {
return this.then(null, onFail)
}
/**
* Provide a callback to be called whenever this promise is rejected.
* The callback will be executed in the context of the provided scope.
*
* @param {function(this:SCOPE, Error, ?)} onFail
* @param {SCOPE} scope Object whose context callback will be executed in.
* @param {...?} var_args
* @return {!Promise.<T>} returns a new promise with the output of the onSuccess
* @template SCOPE
*/
Promise.prototype.failBound = function (onFail, scope, var_args) {
var promise = new Promise(null, onFail)
if (this._nextContext) promise._useContext(this._nextContext)
promise._scope = scope
if (arguments.length > 2) {
promise._boundArgs = Array.prototype.slice.call(arguments, 2)
}
// Chaining must happen after setting args and scope since it may fire callback.
if (this._child) this._child._chainPromise(promise)
else this._chainPromise(promise)
return promise
}
/**
* Provide a callback to be called whenever this promise is either resolved
* or rejected.
*
* @param {function()} onComplete
* @return {!Promise.<T>} returns the current promise
*/
Promise.prototype.fin = function (onComplete) {
if (this._hasData || this._error) {
onComplete()
return this
}
if (this._child) {
this._child.fin(onComplete)
} else {
if (!this._onComplete) this._onComplete = [onComplete]
else this._onComplete.push(onComplete)
}
return this
}
/**
* Mark this promise as "ended". If the promise is rejected, this will throw an
* error in whatever scope it happens to be in
*
* @return {!Promise.<T>} returns the current promise
* @deprecated Prefer done(), because it's consistent with Q.
*/
Promise.prototype.end = function () {
this._end()
return this
}
/**
* Mark this promise as "ended".
* @private
*/
Promise.prototype._end = function () {
if (this._error) {
throw this._error
}
this._ended = true
return this
}
/**
* Close the promise. Any errors after this completes will be thrown to the global handler.
*
* @param {?function(this:void, T, ?)=} onSuccess a function to handle successful
* resolution of this promise
* @param {?function(this:void, !Error, ?)=} onFailure a function to handle failed
* resolution of this promise
* @return {void}
*/
Promise.prototype.done = function (onSuccess, onFailure) {
var self = this
if (onSuccess || onFailure) {
self = self.then(onSuccess, onFailure)
}
self._end()
}
/**
* Return a new promise that behaves the same as the current promise except
* that it will be rejected if the current promise does not get fulfilled
* after a certain amount of time.
*
* @param {number} timeoutMs The timeout threshold in msec
* @param {string=} timeoutMsg error message
* @return {!Promise.<T>} a new promise with timeout
*/
Promise.prototype.timeout = function (timeoutMs, timeoutMsg) {
var deferred = new Promise()
var isTimeout = false
var timeout = setTimeout(function() {
deferred.reject(new Error(timeoutMsg || 'Promise timeout after ' + timeoutMs + ' ms.'))
isTimeout = true
}, timeoutMs)
this.then(function (data) {
if (!isTimeout) {
clearTimeout(timeout)
deferred.resolve(data)
}
},
function (err) {
if (!isTimeout) {
clearTimeout(timeout)
deferred.reject(err)
}
})
return deferred.promise
}
/**
* Attempt to resolve this promise with the specified input
*
* @param {*} data the input
*/
Promise.prototype._withInput = function (data) {
if (this._successFn) {
try {
this.resolve(this._call(this._successFn, [data, this._currentContext]))
} catch (e) {
this.reject(e)
}
} else this.resolve(data)
// context is no longer needed
delete this._currentContext
}
/**
* Attempt to reject this promise with the specified error
*
* @param {!Error} e
* @private
*/
Promise.prototype._withError = function (e) {
if (this._failFn) {
try {
this.resolve(this._call(this._failFn, [e, this._currentContext]))
} catch (thrown) {
this.reject(thrown)
}
} else this.reject(e)
// context is no longer needed
delete this._currentContext
}
/**
* Calls a function in the correct scope, and includes bound arguments.
* @param {Function} fn
* @param {Array} args
* @return {*}
* @private
*/
Promise.prototype._call = function (fn, args) {
if (this._boundArgs) {
args = this._boundArgs.concat(args)
}
return fn.apply(this._scope, args)
}
/**
* Chain a promise to the current promise
*
* @param {!Promise} promise the promise to chain
* @private
*/
Promise.prototype._chainPromise = function (promise) {
var i
if (this._hasContext) promise._useContext(this._nextContext)
if (this._child) {
this._child._chainPromise(promise)
} else if (this._hasData) {
promise._withInput(this._data)
} else if (this._error) {
promise._withError(this._error)
} else if (!this._promises) {
this._promises = [promise]
} else {
this._promises.push(promise)
}
}
/**
* Utility function used for creating a node-style resolver
* for deferreds
*
* @param {!Promise} deferred a promise that looks like a deferred
* @param {Error=} err an optional error
* @param {*=} data optional data
*/
function resolver(deferred, err, data) {
if (err) deferred.reject(err)
else deferred.resolve(data)
}
/**
* Creates a node-style resolver for a deferred by wrapping
* resolver()
*
* @return {function(?Error, *)} node-style callback
*/
Promise.prototype.makeNodeResolver = function () {
return resolver.bind(null, this)
}
/**
* Return true iff the given object is a promise of this library.
*
* Because kew's API is slightly different than other promise libraries,
* it's important that we have a test for its promise type. If you want
* to test for a more general A+ promise, you should do a cap test for
* the features you want.
*
* @param {*} obj The object to test
* @return {boolean} Whether the object is a promise
*/
function isPromise(obj) {
return !!obj._isPromise
}
/**
* Return true iff the given object is a promise-like object, e.g. appears to
* implement Promises/A+ specification
*
* @param {*} obj The object to test
* @return {boolean} Whether the object is a promise-like object
*/
function isPromiseLike(obj) {
return typeof obj === 'object' && typeof obj.then === 'function'
}
/**
* Static function which creates and resolves a promise immediately
*
* @param {T} data data to resolve the promise with
* @return {!Promise.<T>}
* @template T
*/
function resolve(data) {
var promise = new Promise()
promise.resolve(data)
return promise
}
/**
* Static function which creates and rejects a promise immediately
*
* @param {!Error} e error to reject the promise with
* @return {!Promise}
*/
function reject(e) {
var promise = new Promise()
promise.reject(e)
return promise
}
/**
* Replace an element in an array with a new value. Used by .all() to
* call from .then()
*
* @param {!Array} arr
* @param {number} idx
* @param {*} val
* @return {*} the val that's being injected into the array
*/
function replaceEl(arr, idx, val) {
arr[idx] = val
return val
}
/**
* Replace an element in an array as it is resolved with its value.
* Used by .allSettled().
*
* @param {!Array} arr
* @param {number} idx
* @param {*} value The value from a resolved promise.
* @return {*} the data that's being passed in
*/
function replaceElFulfilled(arr, idx, value) {
arr[idx] = {
state: 'fulfilled',
value: value
}
return value
}
/**
* Replace an element in an array as it is rejected with the reason.
* Used by .allSettled().
*
* @param {!Array} arr
* @param {number} idx
* @param {*} reason The reason why the original promise is rejected
* @return {*} the data that's being passed in
*/
function replaceElRejected(arr, idx, reason) {
arr[idx] = {
state: 'rejected',
reason: reason
}
return reason
}
/**
* Takes in an array of promises or literals and returns a promise which returns
* an array of values when all have resolved. If any fail, the promise fails.
*
* @param {!Array.<!Promise>} promises
* @return {!Promise.<!Array>}
*/
function all(promises) {
if (arguments.length != 1 || !Array.isArray(promises)) {
promises = Array.prototype.slice.call(arguments, 0)
}
if (!promises.length) return resolve([])
var outputs = []
var finished = false
var promise = new Promise()
var counter = promises.length
for (var i = 0; i < promises.length; i += 1) {
if (!promises[i] || !isPromiseLike(promises[i])) {
outputs[i] = promises[i]
counter -= 1
} else {
promises[i].then(replaceEl.bind(null, outputs, i))
.then(function decrementAllCounter() {
counter--
if (!finished && counter === 0) {
finished = true
promise.resolve(outputs)
}
}, function onAllError(e) {
if (!finished) {
finished = true
promise.reject(e)
}
})
}
}
if (counter === 0 && !finished) {
finished = true
promise.resolve(outputs)
}
return promise
}
/**
* Takes in an array of promises or values and returns a promise that is
* fulfilled with an array of state objects when all have resolved or
* rejected. If a promise is resolved, its corresponding state object is
* {state: 'fulfilled', value: Object}; whereas if a promise is rejected, its
* corresponding state object is {state: 'rejected', reason: Object}.
*
* @param {!Array} promises or values
* @return {!Promise.<!Array>} Promise fulfilled with state objects for each input
*/
function allSettled(promises) {
if (!Array.isArray(promises)) {
throw Error('The input to "allSettled()" should be an array of Promise or values')
}
if (!promises.length) return resolve([])
var outputs = []
var promise = new Promise()
var counter = promises.length
for (var i = 0; i < promises.length; i += 1) {
if (!promises[i] || !isPromiseLike(promises[i])) {
replaceElFulfilled(outputs, i, promises[i])
if ((--counter) === 0) promise.resolve(outputs)
} else {
promises[i]
.then(replaceElFulfilled.bind(null, outputs, i), replaceElRejected.bind(null, outputs, i))
.then(function () {
if ((--counter) === 0) promise.resolve(outputs)
})
}
}
return promise
}
/**
* Create a new Promise which looks like a deferred
*
* @return {!Promise}
*/
function defer() {
return new Promise()
}
/**
* Return a promise which will wait a specified number of ms to resolve
*
* @param {*} delayMsOrVal A delay (in ms) if this takes one argument, or ther
* return value if it takes two.
* @param {number=} opt_delayMs
* @return {!Promise}
*/
function delay(delayMsOrVal, opt_delayMs) {
var returnVal = undefined
var delayMs = delayMsOrVal
if (typeof opt_delayMs != 'undefined') {
delayMs = opt_delayMs
returnVal = delayMsOrVal
}
if (typeof delayMs != 'number') {
throw new Error('Bad delay value ' + delayMs)
}
var defer = new Promise()
setTimeout(function onDelay() {
defer.resolve(returnVal)
}, delayMs)
return defer
}
/**
* Returns a promise that has the same result as `this`, but fulfilled
* after at least ms milliseconds
* @param {number} ms
*/
Promise.prototype.delay = function (ms) {
return this.then(function (val) {
return delay(val, ms)
})
}
/**
* Return a promise which will evaluate the function fn in a future turn with
* the provided args
*
* @param {function(...)} fn
* @param {...*} var_args a variable number of arguments
* @return {!Promise}
*/
function fcall(fn, var_args) {
var rootArgs = Array.prototype.slice.call(arguments, 1)
var defer = new Promise()
process.nextTick(function onNextTick() {
try {
defer.resolve(fn.apply(undefined, rootArgs))
} catch (e) {
defer.reject(e)
}
})
return defer
}
/**
* Returns a promise that will be invoked with the result of a node style
* callback. All args to fn should be given except for the final callback arg
*
* @param {function(...)} fn
* @param {...*} var_args a variable number of arguments
* @return {!Promise}
*/
function nfcall(fn, var_args) {
// Insert an undefined argument for scope and let bindPromise() do the work.
var args = Array.prototype.slice.call(arguments, 0)
args.splice(1, 0, undefined)
return bindPromise.apply(undefined, args)()
}
/**
* Binds a function to a scope with an optional number of curried arguments. Attaches
* a node style callback as the last argument and returns a promise
*
* @param {function(...)} fn
* @param {Object} scope
* @param {...*} var_args a variable number of arguments
* @return {function(...)}: !Promise}
*/
function bindPromise(fn, scope, var_args) {
var rootArgs = Array.prototype.slice.call(arguments, 2)
return function onBoundPromise(var_args) {
var defer = new Promise()
try {
fn.apply(scope, rootArgs.concat(Array.prototype.slice.call(arguments, 0), defer.makeNodeResolver()))
} catch (e) {
defer.reject(e)
}
return defer
}
}
module.exports = {
all: all
, bindPromise: bindPromise
, defer: defer
, delay: delay
, fcall: fcall
, isPromise: isPromise
, isPromiseLike: isPromiseLike
, nfcall: nfcall
, resolve: resolve
, reject: reject
, allSettled: allSettled
, Promise: Promise
}
}).call(this,_dereq_("1YiZ5S"))
},{"1YiZ5S":2}],4:[function(_dereq_,module,exports){
/*!
* Reqwest! A general purpose XHR connection manager
* license MIT (c) Dustin Diaz 2014
* https://github.com/ded/reqwest
*/
!function (name, context, definition) {
if (typeof module != 'undefined' && module.exports) module.exports = definition()
else if (typeof define == 'function' && define.amd) define(definition)
else context[name] = definition()
}('reqwest', this, function () {
var win = window
, doc = document
, httpsRe = /^http/
, protocolRe = /(^\w+):\/\//
, twoHundo = /^(20\d|1223)$/ //http://stackoverflow.com/questions/10046972/msie-returns-status-code-of-1223-for-ajax-request
, byTag = 'getElementsByTagName'
, readyState = 'readyState'
, contentType = 'Content-Type'
, requestedWith = 'X-Requested-With'
, head = doc[byTag]('head')[0]
, uniqid = 0
, callbackPrefix = 'reqwest_' + (+new Date())
, lastValue // data stored by the most recent JSONP callback
, xmlHttpRequest = 'XMLHttpRequest'
, xDomainRequest = 'XDomainRequest'
, noop = function () {}
, isArray = typeof Array.isArray == 'function'
? Array.isArray
: function (a) {
return a instanceof Array
}
, defaultHeaders = {
'contentType': 'application/x-www-form-urlencoded'
, 'requestedWith': xmlHttpRequest
, 'accept': {
'*': 'text/javascript, text/html, application/xml, text/xml, */*'
, 'xml': 'application/xml, text/xml'
, 'html': 'text/html'
, 'text': 'text/plain'
, 'json': 'application/json, text/javascript'
, 'js': 'application/javascript, text/javascript'
}
}
, xhr = function(o) {
// is it x-domain
if (o['crossOrigin'] === true) {
var xhr = win[xmlHttpRequest] ? new XMLHttpRequest() : null
if (xhr && 'withCredentials' in xhr) {
return xhr
} else if (win[xDomainRequest]) {
return new XDomainRequest()
} else {
throw new Error('Browser does not support cross-origin requests')
}
} else if (win[xmlHttpRequest]) {
return new XMLHttpRequest()
} else {
return new ActiveXObject('Microsoft.XMLHTTP')
}
}
, globalSetupOptions = {
dataFilter: function (data) {
return data
}
}
function succeed(r) {
var protocol = protocolRe.exec(r.url);
protocol = (protocol && protocol[1]) || window.location.protocol;
return httpsRe.test(protocol) ? twoHundo.test(r.request.status) : !!r.request.response;
}
function handleReadyState(r, success, error) {
return function () {
// use _aborted to mitigate against IE err c00c023f
// (can't read props on aborted request objects)
if (r._aborted) return error(r.request)
if (r.request && r.request[readyState] == 4) {
r.request.onreadystatechange = noop
if (succeed(r)) success(r.request)
else
error(r.request)
}
}
}
function setHeaders(http, o) {
var headers = o['headers'] || {}
, h
headers['Accept'] = headers['Accept']
|| defaultHeaders['accept'][o['type']]
|| defaultHeaders['accept']['*']
var isAFormData = o['data'] instanceof FormData;
// breaks cross-origin requests with legacy browsers
if (!o['crossOrigin'] && !headers[requestedWith]) headers[requestedWith] = defaultHeaders['requestedWith']
if (!headers[contentType] && !isAFormData) headers[contentType] = o['contentType'] || defaultHeaders['contentType']
for (h in headers)
headers.hasOwnProperty(h) && 'setRequestHeader' in http && http.setRequestHeader(h, headers[h])
}
function setCredentials(http, o) {
if (typeof o['withCredentials'] !== 'undefined' && typeof http.withCredentials !== 'undefined') {
http.withCredentials = !!o['withCredentials']
}
}
function generalCallback(data) {
lastValue = data
}
function urlappend (url, s) {
return url + (/\?/.test(url) ? '&' : '?') + s
}
function handleJsonp(o, fn, err, url) {
var reqId = uniqid++
, cbkey = o['jsonpCallback'] || 'callback' // the 'callback' key
, cbval = o['jsonpCallbackName'] || reqwest.getcallbackPrefix(reqId)
, cbreg = new RegExp('((^|\\?|&)' + cbkey + ')=([^&]+)')
, match = url.match(cbreg)
, script = doc.createElement('script')
, loaded = 0
, isIE10 = navigator.userAgent.indexOf('MSIE 10.0') !== -1
if (match) {
if (match[3] === '?') {
url = url.replace(cbreg, '$1=' + cbval) // wildcard callback func name
} else {
cbval = match[3] // provided callback func name
}
} else {
url = urlappend(url, cbkey + '=' + cbval) // no callback details, add 'em
}
win[cbval] = generalCallback
script.type = 'text/javascript'
script.src = url
script.async = true
if (typeof script.onreadystatechange !== 'undefined' && !isIE10) {
// need this for IE due to out-of-order onreadystatechange(), binding script
// execution to an event listener gives us control over when the script
// is executed. See http://jaubourg.net/2010/07/loading-script-as-onclick-handler-of.html
script.htmlFor = script.id = '_reqwest_' + reqId
}
script.onload = script.onreadystatechange = function () {
if ((script[readyState] && script[readyState] !== 'complete' && script[readyState] !== 'loaded') || loaded) {
return false
}
script.onload = script.onreadystatechange = null
script.onclick && script.onclick()
// Call the user callback with the last value stored and clean up values and scripts.
fn(lastValue)
lastValue = undefined
head.removeChild(script)
loaded = 1
}
// Add the script to the DOM head
head.appendChild(script)
// Enable JSONP timeout
return {
abort: function () {
script.onload = script.onreadystatechange = null
err({}, 'Request is aborted: timeout', {})
lastValue = undefined
head.removeChild(script)
loaded = 1
}
}
}
function getRequest(fn, err) {
var o = this.o
, method = (o['method'] || 'GET').toUpperCase()
, url = typeof o === 'string' ? o : o['url']
// convert non-string objects to query-string form unless o['processData'] is false
, data = (o['processData'] !== false && o['data'] && typeof o['data'] !== 'string')
? reqwest.toQueryString(o['data'])
: (o['data'] || null)
, http
, sendWait = false
// if we're working on a GET request and we have data then we should append
// query string to end of URL and not post data
if ((o['type'] == 'jsonp' || method == 'GET') && data) {
url = urlappend(url, data)
data = null
}
if (o['type'] == 'jsonp') return handleJsonp(o, fn, err, url)
// get the xhr from the factory if passed
// if the factory returns null, fall-back to ours
http = (o.xhr && o.xhr(o)) || xhr(o)
http.open(method, url, o['async'] === false ? false : true)
setHeaders(http, o)
setCredentials(http, o)
if (win[xDomainRequest] && http instanceof win[xDomainRequest]) {
http.onload = fn
http.onerror = err
// NOTE: see
// http://social.msdn.microsoft.com/Forums/en-US/iewebdevelopment/thread/30ef3add-767c-4436-b8a9-f1ca19b4812e
http.onprogress = function() {}
sendWait = true
} else {
http.onreadystatechange = handleReadyState(this, fn, err)
}
o['before'] && o['before'](http)
if (sendWait) {
setTimeout(function () {
http.send(data)
}, 200)
} else {
http.send(data)
}
return http
}
function Reqwest(o, fn) {
this.o = o
this.fn = fn
init.apply(this, arguments)
}
function setType(header) {
// json, javascript, text/plain, text/html, xml
if (header.match('json')) return 'json'
if (header.match('javascript')) return 'js'
if (header.match('text')) return 'html'
if (header.match('xml')) return 'xml'
}
function init(o, fn) {
this.url = typeof o == 'string' ? o : o['url']
this.timeout = null
// whether request has been fulfilled for purpose
// of tracking the Promises
this._fulfilled = false
// success handlers
this._successHandler = function(){}
this._fulfillmentHandlers = []
// error handlers
this._errorHandlers = []
// complete (both success and fail) handlers
this._completeHandlers = []
this._erred = false
this._responseArgs = {}
var self = this
fn = fn || function () {}
if (o['timeout']) {
this.timeout = setTimeout(function () {
self.abort()
}, o['timeout'])
}
if (o['success']) {
this._successHandler = function () {
o['success'].apply(o, arguments)
}
}
if (o['error']) {
this._errorHandlers.push(function () {
o['error'].apply(o, arguments)
})
}
if (o['complete']) {
this._completeHandlers.push(function () {
o['complete'].apply(o, arguments)
})
}
function complete (resp) {
o['timeout'] && clearTimeout(self.timeout)
self.timeout = null
while (self._completeHandlers.length > 0) {
self._completeHandlers.shift()(resp)
}
}
function success (resp) {
var type = o['type'] || resp && setType(resp.getResponseHeader('Content-Type')) // resp can be undefined in IE
resp = (type !== 'jsonp') ? self.request : resp
// use global data filter on response text
var filteredResponse = globalSetupOptions.dataFilter(resp.responseText, type)
, r = filteredResponse
try {
resp.responseText = r
} catch (e) {
// can't assign this in IE<=8, just ignore
}
if (r) {
switch (type) {
case 'json':
try {
resp = win.JSON ? win.JSON.parse(r) : eval('(' + r + ')')
} catch (err) {
return error(resp, 'Could not parse JSON in response', err)
}
break
case 'js':
resp = eval(r)
break
case 'html':
resp = r
break
case 'xml':
resp = resp.responseXML
&& resp.responseXML.parseError // IE trololo
&& resp.responseXML.parseError.errorCode
&& resp.responseXML.parseError.reason
? null
: resp.responseXML
break
}
}
self._responseArgs.resp = resp
self._fulfilled = true
fn(resp)
self._successHandler(resp)
while (self._fulfillmentHandlers.length > 0) {
resp = self._fulfillmentHandlers.shift()(resp)
}
complete(resp)
}
function error(resp, msg, t) {
resp = self.request
self._responseArgs.resp = resp
self._responseArgs.msg = msg
self._responseArgs.t = t
self._erred = true
while (self._errorHandlers.length > 0) {
self._errorHandlers.shift()(resp, msg, t)
}
complete(resp)
}
this.request = getRequest.call(this, success, error)
}
Reqwest.prototype = {
abort: function () {
this._aborted = true
this.request.abort()
}
, retry: function () {
init.call(this, this.o, this.fn)
}
/**
* Small deviation from the Promises A CommonJs specification
* http://wiki.commonjs.org/wiki/Promises/A
*/
/**
* `then` will execute upon successful requests
*/
, then: function (success, fail) {
success = success || function () {}
fail = fail || function () {}
if (this._fulfilled) {
this._responseArgs.resp = success(this._responseArgs.resp)
} else if (this._erred) {
fail(this._responseArgs.resp, this._responseArgs.msg, this._responseArgs.t)
} else {
this._fulfillmentHandlers.push(success)
this._errorHandlers.push(fail)
}
return this
}
/**
* `always` will execute whether the request succeeds or fails
*/
, always: function (fn) {
if (this._fulfilled || this._erred) {
fn(this._responseArgs.resp)
} else {
this._completeHandlers.push(fn)
}
return this
}
/**
* `fail` will execute when the request fails
*/
, fail: function (fn) {
if (this._erred) {
fn(this._responseArgs.resp, this._responseArgs.msg, this._responseArgs.t)
} else {
this._errorHandlers.push(fn)
}
return this
}
, 'catch': function (fn) {
return this.fail(fn)
}
}
function reqwest(o, fn) {
return new Reqwest(o, fn)
}
// normalize newline variants according to spec -> CRLF
function normalize(s) {
return s ? s.replace(/\r?\n/g, '\r\n') : ''
}
function serial(el, cb) {
var n = el.name
, t = el.tagName.toLowerCase()
, optCb = function (o) {
// IE gives value="" even where there is no value attribute
// 'specified' ref: http://www.w3.org/TR/DOM-Level-3-Core/core.html#ID-862529273
if (o && !o['disabled'])
cb(n, normalize(o['attributes']['value'] && o['attributes']['value']['specified'] ? o['value'] : o['text']))
}
, ch, ra, val, i
// don't serialize elements that are disabled or without a name
if (el.disabled || !n) return
switch (t) {
case 'input':
if (!/reset|button|image|file/i.test(el.type)) {
ch = /checkbox/i.test(el.type)
ra = /radio/i.test(el.type)
val = el.value
// WebKit gives us "" instead of "on" if a checkbox has no value, so correct it here
;(!(ch || ra) || el.checked) && cb(n, normalize(ch && val === '' ? 'on' : val))
}
break
case 'textarea':
cb(n, normalize(el.value))
break
case 'select':
if (el.type.toLowerCase() === 'select-one') {
optCb(el.selectedIndex >= 0 ? el.options[el.selectedIndex] : null)
} else {
for (i = 0; el.length && i < el.length; i++) {
el.options[i].selected && optCb(el.options[i])
}
}
break
}
}
// collect up all form elements found from the passed argument elements all
// the way down to child elements; pass a '<form>' or form fields.
// called with 'this'=callback to use for serial() on each element
function eachFormElement() {
var cb = this
, e, i
, serializeSubtags = function (e, tags) {
var i, j, fa
for (i = 0; i < tags.length; i++) {
fa = e[byTag](tags[i])
for (j = 0; j < fa.length; j++) serial(fa[j], cb)
}
}
for (i = 0; i < arguments.length; i++) {
e = arguments[i]
if (/input|select|textarea/i.test(e.tagName)) serial(e, cb)
serializeSubtags(e, [ 'input', 'select', 'textarea' ])
}
}
// standard query string style serialization
function serializeQueryString() {
return reqwest.toQueryString(reqwest.serializeArray.apply(null, arguments))
}
// { 'name': 'value', ... } style serialization
function serializeHash() {
var hash = {}
eachFormElement.apply(function (name, value) {
if (name in hash) {
hash[name] && !isArray(hash[name]) && (hash[name] = [hash[name]])
hash[name].push(value)
} else hash[name] = value
}, arguments)
return hash
}
// [ { name: 'name', value: 'value' }, ... ] style serialization
reqwest.serializeArray = function () {
var arr = []
eachFormElement.apply(function (name, value) {
arr.push({name: name, value: value})
}, arguments)
return arr
}
reqwest.serialize = function () {
if (arguments.length === 0) return ''
var opt, fn
, args = Array.prototype.slice.call(arguments, 0)
opt = args.pop()
opt && opt.nodeType && args.push(opt) && (opt = null)
opt && (opt = opt.type)
if (opt == 'map') fn = serializeHash
else if (opt == 'array') fn = reqwest.serializeArray
else fn = serializeQueryString
return fn.apply(null, args)
}
reqwest.toQueryString = function (o, trad) {
var prefix, i
, traditional = trad || false
, s = []
, enc = encodeURIComponent
, add = function (key, value) {
// If value is a function, invoke it and return its value
value = ('function' === typeof value) ? value() : (value == null ? '' : value)
s[s.length] = enc(key) + '=' + enc(value)
}
// If an array was passed in, assume that it is an array of form elements.
if (isArray(o)) {
for (i = 0; o && i < o.length; i++) add(o[i]['name'], o[i]['value'])
} else {
// If traditional, encode the "old" way (the way 1.3.2 or older
// did it), otherwise encode params recursively.
for (prefix in o) {
if (o.hasOwnProperty(prefix)) buildParams(prefix, o[prefix], traditional, add)
}
}
// spaces should be + according to spec
return s.join('&').replace(/%20/g, '+')
}
function buildParams(prefix, obj, traditional, add) {
var name, i, v
, rbracket = /\[\]$/
if (isArray(obj)) {
// Serialize array item.
for (i = 0; obj && i < obj.length; i++) {
v = obj[i]
if (traditional || rbracket.test(prefix)) {
// Treat each array item as a scalar.
add(prefix, v)
} else {
buildParams(prefix + '[' + (typeof v === 'object' ? i : '') + ']', v, traditional, add)
}
}
} else if (obj && obj.toString() === '[object Object]') {
// Serialize object item.
for (name in obj) {
buildParams(prefix + '[' + name + ']', obj[name], traditional, add)
}
} else {
// Serialize scalar item.
add(prefix, obj)
}
}
reqwest.getcallbackPrefix = function () {
return callbackPrefix
}
// jQuery and Zepto compatibility, differences can be remapped here so you can call
// .ajax.compat(options, callback)
reqwest.compat = function (o, fn) {
if (o) {
o['type'] && (o['method'] = o['type']) && delete o['type']
o['dataType'] && (o['type'] = o['dataType'])
o['jsonpCallback'] && (o['jsonpCallbackName'] = o['jsonpCallback']) && delete o['jsonpCallback']
o['jsonp'] && (o['jsonpCallback'] = o['jsonp'])
}
return new Reqwest(o, fn)
}
reqwest.ajaxSetup = function (options) {
options = options || {}
for (var k in options) {
globalSetupOptions[k] = options[k]
}
}
return reqwest
});
},{}],5:[function(_dereq_,module,exports){
/**
* Module dependencies.
*/
var global = (function() { return this; })();
/**
* WebSocket constructor.
*/
var WebSocket = global.WebSocket || global.MozWebSocket;
/**
* Module exports.
*/
module.exports = WebSocket ? ws : null;
/**
* WebSocket constructor.
*
* The third `opts` options object gets ignored in web browsers, since it's
* non-standard, and throws a TypeError if passed to the constructor.
* See: https://github.com/einaros/ws/issues/227
*
* @param {String} uri
* @param {Array} protocols (optional)
* @param {Object) opts (optional)
* @api public
*/
function ws(uri, protocols, opts) {
var instance;
if (protocols) {
instance = new WebSocket(uri, protocols);
} else {
instance = new WebSocket(uri);
}
return instance;
}
if (WebSocket) ws.prototype = WebSocket.prototype;
},{}],6:[function(_dereq_,module,exports){
var extend = _dereq_("extend");
var Q = _dereq_("kew");
var encoding = _dereq_("./encoding");
var socket = _dereq_("./socket");
var http = _dereq_("./http-browser");
if(typeof window != "object") {
http = _dereq_("./http-node");
}
module.exports = createApiClient;
function createApiClient(options) {
var config = {};
var sessionId = null;
var sessionIdProvider = function() { return sessionId; }
var urlToken = "";
var socketInstance;
init();
var self = {
request: request,
url: urlFromTemplate,
formData: formData,
sessionId: function (id) { setSessionId(id); return getSessionId(); },
urlToken: function(token) { urlToken = (arguments.length > 0 ? token : urlToken); return urlToken },
appKey: function() { return config.appKey; },
baseUrl: function() { return config.baseUrl; },
socket: getSocket
}
return self;
function init() {
config = extend({}, config, options);
fixBaseUrl();
try { config.appKeyBase32 = encoding.base32.encode(config.appKey); } catch(e) {}
}
function fixBaseUrl() {
var u = config.baseUrl;
if(typeof u == "string" && u.lastIndexOf("/") != u.length - 1) {
config.baseUrl = u + "/";
}
}
function urlFromTemplate(template, parameters, query) {
var url = template;
var queryString = "";
if(url.indexOf("/") == 0) {
url = url.substr(1);
}
if(typeof parameters == "object") {
Object.keys(parameters).forEach(function(key) {
url = url.replace(":" + key, uriEncode(parameters[key]));
});
}
if(typeof query == "object") {
queryString = Object.keys(query).map(function(key) {
return key + "=" + uriEncode(query[key]);
}).join("&");
}
if(queryString != "") {
url += ((url.indexOf("?") == -1) ? "?" : "&") + queryString;
}
return config.baseUrl + url;
}
function uriEncode(string) {
return encodeURIComponent(string).replace(/'/g, "%27");
}
function request(method, url, data) {
var options = {};
options.url = url;
options.method = method
options.contentType = "application/json";
options.headers = getRequestHeaders();
options.processData = true;
options.data = data;
if(typeof FormData != "undefined" && data instanceof FormData) {
options.contentType = false;
options.processData = false;
} else if(typeof data == "object") {
options.data = JSON.stringify(data);
}
var defer = Q.defer();
http.request(options)
.fail(function(error) {
if(config.log) {
config.log("error", "Appstax Error: " + error.message);
}
defer.reject(error);
})
.then(function(result) {
if(typeof result.request != "undefined") {
var token = result.request.getResponseHeader("x-appstax-urltoken");
if(typeof token === "string") {
urlToken = token;
}
}
defer.resolve(result.response);
});
return defer.promise;
}
function getRequestHeaders() {
var h = {};
addAppKeyHeader(h);
addSessionIdHeader(h);
addPreflightHeader(h);
addUrlTokenHeader(h);
return h;
function addAppKeyHeader(headers) {
headers["x-appstax-appkey"] = config.appKey;
}
function addSessionIdHeader(headers) {
if(hasSession()) {
headers["x-appstax-sessionid"] = getSessionId();
}
}
function addPreflightHeader(headers) {
var header = [
"x-appstax-x",
hasSession() ? "u" : "n",
config.appKeyBase32
].join("");
headers[header] = header;
}
function addUrlTokenHeader(headers) {
headers["x-appstax-urltoken"] = "_";
}
}
function hasSession() {
var s = getSessionId();
return s !== null && s !== undefined;
}
function setSessionId(s) {
switch(typeof s) {
case "string":
case "object":
sessionId = s;
break;
case "function":
sessionIdProvider = s;
break;
}
}
function getSessionId() {
return sessionIdProvider();
}
function getSocket() {
if(!socketInstance) {
socketInstance = socket(self);
}
return socketInstance;
}
function formData() {
if(typeof FormData != "undefined") {
return new FormData();
} else {
return null;
}
}
}
},{"./encoding":9,"./http-browser":13,"./socket":18,"extend":1,"kew":3}],7:[function(_dereq_,module,exports){
module.exports = createChannelsContext;
function createChannelsContext(socket) {
var channels;
var handlers;
var idCounter = 0;
init();
return {
getChannel: getChannel
};
function init() {
socket.on("open", handleSocketOpen);
socket.on("error", handleSocketError);
socket.on("message", handleSocketMessage);
channels = {};
handlers = [];
}
function createChannel(channelName, usernames) {
var nameParts = channelName.split("/");
var channel = {
type: nameParts[0],
wildcard: channelName.indexOf("*") != -1,
on: function(eventName, handler) {
addHandler(channelName, eventName, handler)
},
send: function(message) {
sendPacket({
channel:channelName,
command:"publish",
message: message
});
},
grant: function(username, permissions) {
sendPermission(channelName, "grant", [username], permissions);
},
revoke: function(username, permissions) {
sendPermission(channelName, "revoke", [username], permissions);
}
};
if(channel.type == "private" && !channel.wildcard) {
sendPacket({channel:channelName, command:"channel.create"});
if(usernames && usernames.length > 0) {
sendPermission(channelName, "grant", usernames, ["read", "write"]);
}
} else {
sendPacket({channel:channelName, command:"subscribe"});
}
return channel;
}
function sendPermission(channelName, change, usernames, permissions) {
permissions.forEach(function(permission) {
sendPacket({
channel: channelName,
command: change + "." + permission,
data: usernames
})
});
}
function getChannel(name, permissions) {
var channel = channels[name];
if(!channel) {
channels[name] = channel = createChannel(name, permissions);
}
return channel;
}
function sendPacket(packet) {
packet.id = String(idCounter++);
socket.send(packet);
}
function notifyHandlers(channelName, eventName, event) {
getHandlers(channelName, eventName).forEach(function(handler) {
handler(event);
});
}
function getHandlers(channelName, eventName) {
var filtered = [];
if(channelName == "*") {
filtered = handlers.filter(function(handler) {
return handler.eventName == eventName;
});
} else {
filtered = handlers.filter(function(handler) {
return handler.eventName == eventName &&
handler.regexp.test(channelName)
});
}
return filtered.map(function(handler) {
return handler.fn;
});
}
function addHandler(channelPattern, eventName, handler) {
var regexp;
if(channelPattern.lastIndexOf("*") == channelPattern.length - 1) {
regexp = new RegExp("^" + channelPattern.replace("*", ""));
} else {
regexp = new RegExp("^" + channelPattern + "$");
}
handlers.push({
regexp: regexp,
eventName: eventName,
fn: handler
});
}
function handleSocketOpen(event) {
notifyHandlers("*", "open");
}
function handleSocketError(event) {
notifyHandlers("*", "error", {
type:"error",
error: new Error("Error connecting to realtime service")
});
}
function handleSocketMessage(event) {
var data = {};
try {
data = JSON.parse(event.data);
} catch(e) {}
if(typeof data.channel === "string" &&
typeof data.event === "string") {
notifyHandlers(data.channel, data.event, data);
}
}
}
},{}],8:[function(_dereq_,module,exports){
module.exports = createCollectionsContext;
function createCollectionsContext() {
var collections = {};
return {
defaultValues: defaultValues,
get: getCollection,
collection: function(c, p) { defineCollection(c, p); return getCollection(c); }
}
function defineCollection(name, options) {
collection = parseCollection(options);
collections["$" + name] = collection;
}
function parseCollection(options) {
var collection = {};
Object.keys(options).forEach(function(key) {
var option = options[key];
var column = {};
if(typeof option === "string") {
column.type = option;
} else if(typeof option === "object" && typeof option.type === "string") {
column.type = option.type;
}
if(column.type === "relation") {
column.relation = option.relation;
}
collection[key] = column;
});
return collection;
}
function getCollection(name) {
return collections["$" + name];
}
function defaultValues(collectionName) {
var collection = getCollection(collectionName);
var values = {};
if(collection) {
Object.keys(collection).forEach(function(key) {
values[key] = defaultValueForColumn(collection[key])
});
}
return values;
}
function defaultValueForColumn(column) {
switch(column.type) {
case "string": return "";
case "number": return 0;
case "array": return [];
case "file": return {sysDatatype:"file", filename:"", url:""};
case "relation": return {sysDatatype:"relation", sysRelationType:column.relation, sysObjectIds:[]};
}
return undefined;
}
}
},{}],9:[function(_dereq_,module,exports){
var nibbler = _dereq_("./nibbler");
var base64 = nibbler.create({
dataBits: 8,
codeBits: 6,
keyString: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
pad: "-"
})
var base32 = nibbler.create({
dataBits: 8,
codeBits: 5,
keyString: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",
pad: "-"
});
module.exports = {
base64: base64,
base32: base32,
base64ToBase32: function(source) {
return base32.encode(base64.decode(source));
}
}
},{"./nibbler":14}],10:[function(_dereq_,module,exports){
module.exports = {
log: function(error) {
if(console && console.error) {
if(error && error.message) {
console.error("Appstax Error: " + error.message, error);
} else {
console.error("Appstax Error");
}
if(error && error.stack) {
console.error(error.stack);
}
}
throw error;
}
}
},{}],11:[function(_dereq_,module,exports){
var extend = _dereq_("extend");
var objects = _dereq_("./objects");
var users = _dereq_("./users");
var files = _dereq_("./files");
var collections = _dereq_("./collections");
var apiClient = _dereq_("./apiclient");
var request = _dereq_("./request");
var channels = _dereq_("./channels");
var defaults = {
baseUrl: "https://appstax.com/api/latest/",
log: log
}
var mainContext = createContext(defaults);
module.exports = mainContext;
module.exports.app = createContext;
function createContext(options) {
var context = { init: init };
var config = {};
init(options);
return context;
function init(options) {
if(options == null) {
return;
}
if(typeof options === "string") {
options = {appKey:options};
}
config = extend({}, defaults, config, options);
if(config.log === false) { config.log = function() {} }
// init modules
context.apiClient = apiClient({baseUrl: config.baseUrl, appKey: config.appKey, log: config.log});
context.files = files(context.apiClient);
context.collections = collections();
context.objects = objects(context.apiClient, context.files, context.collections);
context.users = users(context.apiClient, context.objects);
context.request = request(context.apiClient)
context.channels = channels(context.apiClient.socket());
// expose shortcuts
context.object = context.objects.createObject;
context.status = context.objects.getObjectStatus;
context.findAll = context.objects.findAll;
context.find = context.objects.find;
context.search = context.objects.search;
context.signup = context.users.signup;
context.login = context.users.login;
context.logout = context.users.logout;
context.currentUser = context.users.currentUser;
context.collection = context.collections.collection;
context.file = context.files.createFile;
context.sessionId = context.apiClient.sessionId;
context.channel = context.channels.getChannel;
}
}
function log(level, message) {
if(console && console[level]) {
console[level].apply(console, Array.prototype.slice.call(arguments, 1));
}
}
},{"./apiclient":6,"./channels":7,"./collections":8,"./files":12,"./objects":15,"./request":17,"./users":19,"extend":1}],12:[function(_dereq_,module,exports){
var Q = _dereq_("kew");
var extend = _dereq_("extend");
module.exports = createFilesContext;
function createFilesContext(apiClient) {
var internalFiles = [];
return {
create: createFile,
isFile: isFile,
saveFile: saveFile,
status: fileStatus,
setUrl: setUrl,
urlForFile: urlForFile,
nativeFile: getNativeFile,
createFile: createFile
}
function createFile(options) {
var file = Object.create({});
var internal;
if(options instanceof Blob) {
var nativeFile = options;
internal = createInternalFile(file, {
filename: nativeFile.name,
nativeFile: nativeFile
});
} else {
internal = createInternalFile(file, options);
internal.status = "saved";
}
if(file && internal) {
Object.defineProperty(file, "filename", { get: function() { return internal.filename; }, enumerable:true });
Object.defineProperty(file, "url", { get: function() { return internal.url; }, enumerable:true });
Object.defineProperty(file, "preview", { value: function() { return previewFile(internal); }});
Object.defineProperty(file, "imageUrl", { value: function(operation, options) { return imageUrl(internal, operation, options); }});
} else {
throw new Error("Invalid file options");
}
return file;
}
function createInternalFile(file, options) {
var internal = {
file: file,
filename: options.filename,
nativeFile: options.nativeFile,
url: options.url || "",
status: "new"
}
internalFiles.push(internal);
return internal;
}
function previewFile(internalFile) {
if(!internalFile.previewPromise) {
var defer = Q.defer();
var reader = new FileReader();
reader.onload = function(event) {
internalFile.url = event.target.result;
defer.resolve(internalFile.file);
}
reader.readAsDataURL(internalFile.nativeFile);
internalFile.previewPromise = defer.promise;
}
return internalFile.previewPromise;
}
function imageUrl(internalFile, operation, options) {
var o = extend({
width: "-",
height: "-"
}, options);
return internalFile.url.replace("/files/", "/images/" + operation + "/" + o.width + "/" + o.height + "/");
}
function getInternalFile(file) {
for(var i = 0; i < internalFiles.length; i++) {
if(internalFiles[i].file == file) {
return internalFiles[i];
}
}
return null;
}
function saveFile(collectionName, objectId, propertyName, file) {
var defer = Q.defer();
var internal = getInternalFile(file);
internal.status = "saving";
var url = urlForFile(collectionName, objectId, propertyName, file.filename);
var data = new FormData();
data.append("file", internal.nativeFile);
apiClient.request("put", url, data).then(function(response) {
internal.status = "saved";
internal.url = url;
defer.resolve(file);
});
return defer.promise;
}
function urlForFile(collectionName, objectId, propertyName, filename) {
if(!filename) {
return "";
}
var tokenKey = "token";
var tokenValue = apiClient.urlToken();
if(tokenValue.length < 2) {
tokenKey = "appkey";
tokenValue = apiClient.appKey();
}
return apiClient.url("/files/:collectionName/:objectId/:propertyName/:filename?:tokenKey=:tokenValue", {
collectionName: collectionName,
objectId: objectId,
propertyName: propertyName,
filename: filename,
tokenKey: tokenKey,
tokenValue: tokenValue
})
}
function getNativeFile(file) {
var nativeFile = null;
var internal = getInternalFile(file);
if(internal != null) {
nativeFile = internal.nativeFile;
}
return nativeFile;
}
function isFile(file) {
return getInternalFile(file) != null;
}
function fileStatus(file, status) {
if(typeof status === "string") {
getInternalFile(file).status = status;
}
return getInternalFile(file).status;
}
function setUrl(file, url) {
var internal = getInternalFile(file);
if(internal) {
internal.url = url;
}
}
}
},{"extend":1,"kew":3}],13:[function(_dereq_,module,exports){
var extend = _dereq_("extend");
var Q = _dereq_("kew");
var reqwest = null;
if(typeof window == "object") {
reqwest = _dereq_("reqwest");
}
module.exports = {
request: function(options) {
var defer = Q.defer();
var r = reqwest(extend({
type: "json",
contentType: "application/json",
crossOrigin: true
}, options))
.then(function(response) {
defer.resolve({
response: response,
request: r.request
});
})
.fail(function(xhr) {
defer.reject(errorFromXhr(xhr));
});
return defer.promise;
}
}
function errorFromXhr(xhr) {
try {
var result = JSON.parse(xhr.responseText);
if(typeof result.errorMessage == "string") {
return new Error(result.errorMessage);
} else {
return result;
}
} catch(e) {}
return xhr.responseText;
}
},{"extend":1,"kew":3,"reqwest":4}],14:[function(_dereq_,module,exports){
/*
Copyright (c) 2010-2013 Thomas Peri
http://www.tumuski.com/
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/*jslint white: true, browser: true, onevar: true, undef: true, nomen: true,
eqeqeq: true, plusplus: true, regexp: true, newcap: true, immed: true */
// (good parts minus bitwise and strict, plus white.)
/**
* Nibbler - Multi-Base Encoder
*
* version 2013-04-24
*
* Options:
* dataBits: The number of bits in each character of unencoded data.
* codeBits: The number of bits in each character of encoded data.
* keyString: The characters that correspond to each value when encoded.
* pad (optional): The character to pad the end of encoded output.
* arrayData (optional): If truthy, unencoded data is an array instead of a string.
*
* Example:
*
* var base64_8bit = new Nibbler({
* dataBits: 8,
* codeBits: 6,
* keyString: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',
* pad: '='
* });
* base64_8bit.encode("Hello, World!"); // returns "SGVsbG8sIFdvcmxkIQ=="
* base64_8bit.decode("SGVsbG8sIFdvcmxkIQ=="); // returns "Hello, World!"
*
* var base64_7bit = new Nibbler({
* dataBits: 7,
* codeBits: 6,
* keyString: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',
* pad: '='
* });
* base64_7bit.encode("Hello, World!"); // returns "kZdmzesQV9/LZkQg=="
* base64_7bit.decode("kZdmzesQV9/LZkQg=="); // returns "Hello, World!"
*
*/
module.exports = {
create: function(options) {
return new Nibbler(options);
}
}
var Nibbler = function (options) {
"use strict";
// Code quality tools like jshint warn about bitwise operators,
// because they're easily confused with other more common operators,
// and because they're often misused for doing arithmetic. Nibbler uses
// them properly, though, for moving individual bits, so turn off the warning.
/*jshint bitwise:false */
var construct,
// options
pad, dataBits, codeBits, keyString, arrayData,
// private instance variables
mask, group, max,
// private methods
gcd, translate,
// public methods
encode, decode;
// pseudo-constructor
construct = function () {
var i, mag, prev;
// options
pad = options.pad || '';
dataBits = options.dataBits;
codeBits = options.codeBits;
keyString = options.keyString;
arrayData = options.arrayData;
// bitmasks
mag = Math.max(dataBits, codeBits);
prev = 0;
mask = [];
for (i = 0; i < mag; i += 1) {
mask.push(prev);
prev += prev + 1;
}
max = prev;
// ouput code characters in multiples of this number
group = dataBits / gcd(dataBits, codeBits);
};
// greatest common divisor
gcd = function (a, b) {
var t;
while (b !== 0) {
t = b;
b = a % b;
a = t;
}
return a;
};
// the re-coder
translate = function (input, bitsIn, bitsOut, decoding) {
var i, len, chr, byteIn,
buffer, size, output,
write;
// append a byte to the output
write = function (n) {
if (!decoding) {
output.push(keyString.charAt(n));
} else if (arrayData) {
output.push(n);
} else {
output.push(String.fromCharCode(n));
}
};
buffer = 0;
size = 0;
output = [];
len = input.length;
for (i = 0; i < len; i += 1) {
// the new size the buffer will be after adding these bits
size += bitsIn;
// read a character
if (decoding) {
// decode it
chr = input.charAt(i);
byteIn = keyString.indexOf(chr);
if (chr === pad) {
break;
} else if (byteIn < 0) {
throw 'the character "' + chr + '" is not a member of ' + keyString;
}
} else {
if (arrayData) {
byteIn = input[i];
} else {
byteIn = input.charCodeAt(i);
}
if ((byteIn | max) !== max) {
throw byteIn + " is outside the range 0-" + max;
}
}
// shift the buffer to the left and add the new bits
buffer = (buffer << bitsIn) | byteIn;
// as long as there's enough in the buffer for another output...
while (size >= bitsOut) {
// the new size the buffer will be after an output
size -= bitsOut;
// output the part that lies to the left of that number of bits
// by shifting the them to the right
write(buffer >> size);
// remove the bits we wrote from the buffer
// by applying a mask with the new size
buffer &= mask[size];
}
}
// If we're encoding and there's input left over, pad the output.
// Otherwise, leave the extra bits off, 'cause they themselves are padding
if (!decoding && size > 0) {
// flush the buffer
write(buffer << (bitsOut - size));
// add padding string for the remainder of the group
while (output.length % group > 0) {
output.push(pad);
}
}
// string!
return (arrayData && decoding) ? output : output.join('');
};
/**
* Encode. Input and output are strings.
*/
encode = function (input) {
return translate(input, dataBits, codeBits, false);
};
/**
* Decode. Input and output are strings.
*/
decode = function (input) {
return translate(input, codeBits, dataBits, true);
};
this.encode = encode;
this.decode = decode;
construct();
};
},{}],15:[function(_dereq_,module,exports){
var extend = _dereq_("extend");
var query = _dereq_("./query");
var failLogger = _dereq_("./faillogger");
var Q = _dereq_("kew");
module.exports = createObjectsContext;
var internalProperties = ["collectionName", "id", "internalId", "username", "created", "updated", "permissions", "save", "saveAll", "remove", "grant", "revoke", "sysCreated", "sysUpdated", "sysPermissions"];
var nextContextId = 0;
function createObjectsContext(apiClient, files, collections) {
var contextId = nextContextId++;
var internalIds = [];
var internalObjects = {};
var prototype = {
save: function() {
return failOnUnsavedRelations(this)
.then(saveObject)
.then(savePermissionChanges)
.then(saveFileProperties)
.fail(failLogger.log);
},
saveAll: function() {
return saveObjectsInGraph(this).fail(failLogger.log);
},
remove: function() {
return removeObject(this).fail(failLogger.log);
},
refresh: function() {
return refreshObject(this).fail(failLogger.log);
},
expand: function(options) {
return expandObject(this, options).fail(failLogger.log);
},
grant: function(usernames, permissions) {
if(typeof usernames === "string") {
usernames = [usernames];
}
var internal = getInternalObject(this);
usernames.forEach(function(username) {
internal.grants.push({
username: username,
permissions: permissions
});
});
},
revoke: function(usernames, permissions) {
if(typeof usernames === "string") {
usernames = [usernames];
}
var internal = getInternalObject(this);
usernames.forEach(function(username) {
internal.revokes.push({
username: username,
permissions: permissions
});
});
},
grantPublic: function(permissions) {
this.grant("*", permissions);
},
revokePublic: function(permissions) {
this.revoke("*", permissions);
},
hasPermission: function(permission) {
return this.permissions.indexOf(permission) != -1;
}
};
return {
create: createObject,
createQuery: createQuery,
getProperties: getProperties,
createObject: createObject,
getObjectStatus: getObjectStatus,
findAll: findAll,
find: find,
search: search
};
function createObject(collectionName, properties) {
var internal = createInternalObject(collectionName);
var object = Object.create(prototype);
Object.defineProperty(object, "id", { get: function() { return internal.id; }, enumerable:true });
Object.defineProperty(object, "internalId", { writable: false, value: internal.internalId, enumerable:true });
Object.defineProperty(object, "collectionName", { get: function() { return internal.collectionName; }, enumerable:true });
Object.defineProperty(object, "created", { get: function() { return internal.created; }, enumerable:true });
Object.defineProperty(object, "updated", { get: function() { return internal.updated; }, enumerable:true });
Object.defineProperty(object, "permissions", { get: function() { return internal.sysValues.sysPermissions; }, enumerable: true });
if(collectionName == "users") {
Object.defineProperty(object, "username", { get:function() { return internal.sysValues.sysUsername; }, enumerable:true });
}
properties = extend({}, collections.defaultValues(collectionName), properties);
fillObjectWithValues(object, properties);
if(object.id !== null) {
internal.status = "saved";
}
return object;
}
function fillObjectWithValues(object, properties) {
var internal = getInternalObject(object);
var filteredProperties = {};
if(typeof properties === "object") {
var sysValues = internal.sysValues;
internal.setId(properties.sysObjectId);
if(properties.sysCreated) {
internal.created = new Date(properties.sysCreated)
}
if(properties.sysUpdated) {
internal.updated = new Date(properties.sysUpdated)
}
Object.keys(properties).forEach(function(key) {
var value = properties[key];
if(key.indexOf("sys") === 0) {
sysValues[key] = value;
} else if(typeof value.sysDatatype == "string") {
filteredProperties[key] = createPropertyWithDatatype(key, value, object);
if(value.sysDatatype == "relation") {
internal.relations[key] = {
type: value.sysRelationType,
ids: (value.sysObjects || []).map(function(object) {
return object.sysObjectId || object;
})
}
}
} else {
filteredProperties[key] = value;
}
});
}
extend(object, filteredProperties);
}
function createPropertyWithDatatype(key, value, object) {
switch(value.sysDatatype) {
case "relation": return _createRelationProperty(value);
case "file": return files.create({
filename: value.filename,
url: files.urlForFile(object.collectionName, object.id, key, value.filename)
});
}
return null;
function _createRelationProperty(value) {
var results = [];
if(typeof value.sysObjects !== "undefined") {
results = value.sysObjects.map(function(object) {
if(typeof object === "string") {
return object
} else {
return createObject(value.sysCollection, object);
}
});
}
if("single" === value.sysRelationType) {
return results[0];
} else {
return results;
}
}
}
function createInternalObject(collectionName) {
var object = {
id: null,
internalId: createInternalId(),
collectionName: collectionName,
sysValues: {},
initialValues: {},
created: new Date(),
updated: new Date(),
status: "new",
grants: [],
revokes: [],
relations: {},
setId: function(id) { if(id) { this.id = id; }},
resetPermissions: function() { this.grants = []; this.revokes = []; }
}
internalObjects[object.internalId] = object;
return object;
}
function getInternalObject(object) {
return internalObjects[object.internalId];
}
function refreshObject(object) {
var defer = Q.defer();
var internal = getInternalObject(object);
if(internal.status === "new") {
defer.resolve(object);
} else {
findById(object.collectionName, object.id).then(function(updated) {
Object.keys(updated)
.filter(function(key) {
return internalProperties.indexOf(key) == -1
})
.forEach(function(key) {
object[key] = updated[key];
});
defer.resolve(object);
});
}
return defer.promise;
}
function saveObject(object, defer) {
var internal = getInternalObject(object)
var defer = typeof defer == "object" ? defer : Q.defer();
if(internal.status === "saving") {
setTimeout(function() {
saveObject(object, defer);
}, 100);
return defer.promise;
}
var url, method, data;
if(object.id == null) {
url = apiClient.url("/objects/:collection", {collection: object.collectionName});
method = "post";
data = getDataForSaving(object)
} else {
url = apiClient.url("/objects/:collection/:id", {collection: object.collectionName, id: object.id});
method = "put";
data = getPropertiesForSaving(object);
}
internal.status = "saving";
apiClient.request(method, url, data)
.then(function(response) {
internal.setId(response.sysObjectId);
internal.status = "saved";
applyRelationChanges(object, data);
if(typeof FormData != "undefined" && data instanceof FormData) {
markFilesSaved(object);
}
defer.resolve(object);
})
.fail(function(error) {
internal.status = "error";
defer.reject(error);
});
return defer.promise;
}
function removeObject(object) {
var defer = Q.defer();
var url = apiClient.url("/objects/:collection/:id", {collection: object.collectionName, id: object.id});
apiClient.request("DELETE", url)
.then(function(response) {
defer.resolve();
})
.fail(function(error) {
defer.reject(error);
});
return defer.promise;
}
function expandObject(object, options) {
if(isUnsaved(object)) {
throw new Error("Error calling expand() on unsaved object.")
}
var defer = Q.defer();
var depth = 1;
if(typeof options === "number") {
depth = options;
}
findById(object.collectionName, object.id, {expand:depth}).then(function(expanded) {
var internal = getInternalObject(object);
var relations = Object.keys(internal.relations);
relations.forEach(function(relation) {
object[relation] = expanded[relation];
});
defer.resolve(object);
});
return defer.promise;
}
function markFilesSaved(object) {
var fileProperties = getFileProperties(object);
return Object.keys(fileProperties).map(function(key) {
var file = fileProperties[key];
var url = files.urlForFile(object.collectionName, object.id, key, file.filename);
files.status(file, "saved");
files.setUrl(file, url);
});
}
function saveFileProperties(object) {
var fileProperties = getFileProperties(object);
var keys = Object.keys(fileProperties);
var promises = [];
keys.forEach(function(key) {
var file = fileProperties[key];
if(files.status(file) !== "saved") {
var promise = files.saveFile(object.collectionName, object.id, key, file)
promises.push(promise);
}
});
return Q.all(promises).then(function() {
return Q.resolve(object)
});
}
function savePermissionChanges(object) {
var defer = Q.defer();
var url = apiClient.url("/permissions");
var internal = getInternalObject(object);
var grants = internal.grants.map(_convertChange);
var revokes = internal.revokes.map(_convertChange);
internal.resetPermissions();
if(grants.length + revokes.length === 0) {
defer.resolve(object);
} else {
var data = {grants:grants, revokes:revokes};
apiClient.request("POST", url, data)
.then(function(response) {
defer.resolve(object);
})
.fail(function(error) {
defer.reject(error);
});
}
return defer.promise;
function _convertChange(change) {
return {
sysObjectId: object.id,
username: change.username,
permissions: change.permissions
}
}
}
function failOnUnsavedRelations(object) {
detectUndeclaredRelations(object);
var related = getRelatedObjects(object);
if(related.some(isUnsaved)) {
throw new Error("Error saving object. Found unsaved related objects. Save related objects first or consider using saveAll().")
} else {
return Q.resolve(object);
}
}
function saveObjectsInGraph(rootObject) {
var objects = getObjectsInGraph(rootObject);
var unsavedInbound = objects.inbound.filter(isUnsaved);
var outbound = objects.outbound;
var remaining = objects.inbound.filter(function(o) { return !isUnsaved(o) });
if(0 == outbound.length + unsavedInbound.length + remaining.length) {
return rootObject.save();
} else {
return _saveUnsavedInbound().then(_saveOutbound).then(_saveRemaining);
}
function _saveUnsavedInbound() {
return Q.all(unsavedInbound.map(saveObject));
}
function _saveOutbound() {
return Q.all(outbound.map(saveObject));
}
function _saveRemaining() {
return Q.all(remaining.map(saveObject));
}
}
function getObjectsInGraph(rootObject) {
var queue = [rootObject];
var all = {};
var inbound = {};
var outbound = {};
while(queue.length > 0) {
var object = queue.shift();
detectUndeclaredRelations(object);
if(all[object.internalId] == null) {
all[object.internalId] = object;
var allRelated = getRelatedObjects(object).filter(function(a) { return typeof a == "object" });
allRelated.forEach(function(related) {
inbound[related.internalId] = related;
});
if(allRelated.length > 0) {
outbound[object.internalId] = object;
queue = queue.concat(allRelated);
}
}
}
return {
all: _mapToArray(all),
inbound: _mapToArray(inbound),
outbound: _mapToArray(outbound)
}
function _mapToArray(map) {
return Object.keys(map).map(_objectForKey);
}
function _objectForKey(key) {
return all[key];
}
}
function getRelatedObjects(object) {
var related = [];
var internal = getInternalObject(object);
Object.keys(internal.relations).forEach(function(key) {
var property = object[key];
if(property == null) {
return;
}
related = related.concat(property);
});
return related;
}
function getRelationChanges(object, propertyName) {
var internal = getInternalObject(object);
var relation = internal.relations[propertyName];
var changes = {
additions: [],
removals: []
}
if(relation) {
var property = object[propertyName];
var objects = [];
if(property) {
objects = (relation.type == "array") ? property : [property];
}
var currentIds = objects.map(function(o) { return o.id || o; })
.filter(function(id) { return typeof id === "string"; });
changes.additions = currentIds.filter(function(id) {
return id != null && relation.ids.indexOf(id) == -1;
});
changes.removals = relation.ids.filter(function(id) {
return id != null && currentIds.indexOf(id) == -1;
});
}
return changes;
}
function applyRelationChanges(object, savedData) {
var internal = getInternalObject(object);
Object.keys(internal.relations).forEach(function(key) {
var relation = internal.relations[key];
var changes = savedData[key].sysRelationChanges;
relation.ids = relation.ids
.concat(changes.additions)
.filter(function(id) {
return changes.removals.indexOf(id) == -1;
});
});
}
function detectUndeclaredRelations(object) {
var collection = collections.get(object.collectionName);
var relations = getInternalObject(object).relations;
var properties = getProperties(object);
Object.keys(properties).forEach(function(key) {
if(relations[key]) {
return;
}
var property = properties[key]
var relationType = "";
if(property !== null && typeof property === "object") {
if(typeof property.length === "undefined") {
if(typeof property.collectionName === "string") {
relationType = "single"
}
} else {
property.some(function(item) {
if(typeof item.collectionName === "string") {
relationType = "array"
return true;
}
return false;
})
}
}
if(relationType !== "") {
relations[key] = { type:relationType, ids:[] };
}
});
}
function getPropertyNames(object) {
var keys = Object.keys(object);
return keys.filter(function(key) {
return internalProperties.indexOf(key) == -1;
});
}
function getProperties(object) {
if(!isObject(object)) { return {}; }
var data = {};
getPropertyNames(object).forEach(function(key) {
if(/^[a-zA-Z]/.test(key)) {
data[key] = object[key];
}
});
var sysValues = getInternalObject(object).sysValues;
Object.keys(sysValues).forEach(function(key) {
if(internalProperties.indexOf(key) == -1) {
data[key] = sysValues[key];
}
});
return data;
}
function getDataForSaving(object) {
var properties = getPropertiesForSaving(object);
var fileProperties = getFileProperties(object);
var hasFiles = false;
var formData = apiClient.formData();
Object.keys(fileProperties).forEach(function(key) {
var file = fileProperties[key];
var nativeFile = files.nativeFile(file);
if(nativeFile && files.status(file) !== "saved") {
hasFiles = true;
formData.append(key, nativeFile);
}
});
if(hasFiles) {
formData.append("sysObjectData", JSON.stringify(properties));
return formData;
} else {
return properties;
}
}
function getPropertiesForSaving(object) {
var internal = getInternalObject(object);
var properties = getProperties(object);
Object.keys(properties).forEach(function(key) {
var property = properties[key];
if(files.isFile(property)) {
properties[key] = {
sysDatatype: "file",
filename: property.filename
}
} else if(typeof internal.relations[key] === "object") {
properties[key] = {
sysRelationChanges: getRelationChanges(object, key)
}
}
});
return properties;
}
function getFileProperties(object) {
var properties = getProperties(object);
var fileProperties = {};
Object.keys(properties).forEach(function(key) {
var property = properties[key];
if(files.isFile(property)) {
fileProperties[key] = property;
}
});
return fileProperties;
}
function createInternalId() {
var id = "internal-id-" + contextId + "-" + internalIds.length;
internalIds.push(id);
return id;
}
function queryParametersFromQueryOptions(options) {
if(!options) { return; }
var parameters = {};
if(typeof options.expand === "number") {
parameters.expanddepth = options.expand;
} else if(options.expand === true) {
parameters.expanddepth = 1;
}
return parameters;
}
function findAll(collectionName, options) {
var defer = Q.defer();
var url = apiClient.url("/objects/:collection",
{collection: collectionName},
queryParametersFromQueryOptions(options));
apiClient.request("get", url)
.then(function(result) {
defer.resolve(createObjectsFromFindResult(collectionName, result));
})
.fail(function(error) {
defer.reject(error);
});
return defer.promise;
}
function find(collectionName) {
if(arguments.length < 2) { return; }
var a1 = arguments[1];
var a2 = arguments[2];
if(typeof a1 === "string" && a1.indexOf("=") == -1) {
return findById(collectionName, a1, a2);
} else if(typeof a1 === "string") {
return findByQueryString(collectionName, a1, a2);
} else if(typeof a1 === "object" && typeof a1.queryString === "function") {
return findByQueryObject(collectionName, a1, a2);
} else if(typeof a1 === "object") {
return findByPropertyValues(collectionName, a1, a2);
} else if(typeof a1 === "function") {
return findByQueryFunction(collectionName, a1, a2);
}
}
function findById(collectionName, id, options) {
var defer = Q.defer();
var url = apiClient.url("/objects/:collection/:id",
{collection: collectionName, id: id},
queryParametersFromQueryOptions(options));
apiClient.request("get", url)
.then(function(result) {
defer.resolve(createObject(collectionName, result));
})
.fail(function(error) {
defer.reject(error);
});
return defer.promise;
}
function findByQueryString(collectionName, queryString, options) {
var defer = Q.defer();
var url = apiClient.url("/objects/:collection?filter=:queryString",
{collection: collectionName, queryString: queryString},
queryParametersFromQueryOptions(options));
apiClient.request("get", url)
.then(function(result) {
defer.resolve(createObjectsFromFindResult(collectionName, result));
})
.fail(function(error) {
defer.reject(error);
});
return defer.promise;
}
function findByQueryObject(collectionName, queryObject, options) {
return findByQueryString(collectionName, queryObject.queryString(), options);
}
function findByQueryFunction(collectionName, queryFunction, options) {
var queryObject = createQuery();
queryFunction(queryObject);
return findByQueryString(collectionName, queryObject.queryString(), options);
}
function findByPropertyValues(collectionName, propertyValues, options) {
return findByQueryFunction(collectionName, function(query) {
Object.keys(propertyValues).forEach(function(property) {
var value = propertyValues[property];
if(typeof value === "object" && typeof value.id === "string") {
query.relation(property).has(value);
} else {
query.string(property).equals(value);
}
});
}, options);
}
function search(collectionName) {
var propertyValues = arguments[1];
var options = arguments[2];
if(arguments.length >= 3 && typeof arguments[1] === "string") {
propertyValues = {};
var searchString = arguments[1]
Array.prototype.forEach.call(arguments[2], function(property) {
propertyValues[property] = searchString;
});
if(arguments.length == 4) {
options = arguments[3];
}
}
return find(collectionName, function(query) {
query.operator("or");
Object.keys(propertyValues).forEach(function(property) {
var value = propertyValues[property];
query.string(property).contains(value);
});
}, options);
}
function createObjectsFromFindResult(collectionName, result) {
return result.objects.map(function(properties) {
return createObject(collectionName, properties);
});
}
function createQuery(options) {
return query(options);
}
function getObjectStatus(object) {
var internal = getInternalObject(object);
return internal ? internal.status : undefined;
}
function isUnsaved(object) {
return getObjectStatus(object) === "new";
}
function isObject(object) {
return object !== undefined && object !== null;
}
}
},{"./faillogger":10,"./query":16,"extend":1,"kew":3}],16:[function(_dereq_,module,exports){
module.exports = function(options) {
var operator = "and";
var predicates = [];
init();
return {
queryString: queryString,
string: createStringPredicate,
relation: createRelationPredicate,
operator: function(o) { operator = o; }
};
function init() {
if(typeof options === "string") {
addPredicate(options);
}
}
function addPredicate(predicate) {
predicates.push(predicate);
}
function createStringPredicate(property) {
return {
equals: function(value) {
addPredicate(format("$='$'", property, value));
},
contains: function(value) {
addPredicate(format("$ like '%$%'", property, value));
}
}
}
function createRelationPredicate(property) {
return {
has: function(objectsOrIds) {
var ids = _getQuotedIds(objectsOrIds);
addPredicate(format("$ has ($)", property, ids.join(",")));
}
}
function _getQuotedIds(objectsOrIds) {
return [].concat(objectsOrIds).map(function(item) {
return "'" + (item.id || item) + "'";
});
}
}
function queryString() {
return predicates.join(format(" $ ", operator));
}
function format(template) {
var parameters = Array.prototype.slice.call(arguments, 1);
var result = template;
parameters.forEach(function(parameter) {
result = result.replace("$", parameter);
});
return result;
}
};
},{}],17:[function(_dereq_,module,exports){
module.exports = createRequestContext;
function createRequestContext(apiClient) {
return request;
function request(method, url, data) {
url = apiClient.url("/server" + url);
return apiClient.request(method, url, data);
}
}
},{}],18:[function(_dereq_,module,exports){
var Q = _dereq_("kew");
var WS = _dereq_("ws");
module.exports = createSocket;
function createSocket(apiClient) {
var queue = [];
var realtimeSessionPromise = null;
var realtimeSessionId = "";
var webSocket = null;
var connectionIntervalId = null;
var handlers = {
open: [],
message: [],
error: [],
close: []
};
return {
connect: connect,
send: send,
on: on
}
function send(packet) {
if(typeof packet == "object") {
packet = JSON.stringify(packet);
}
if(webSocket && webSocket.readyState == 1) {
sendQueue();
webSocket.send(packet);
} else {
queue.push(packet);
connect();
}
}
function sendQueue() {
while(queue.length > 0) {
if(webSocket && webSocket.readyState == 1) {
var packet = queue.shift();
webSocket.send(packet);
} else {
connect();
break;
}
}
}
function on(event, handler) {
handlers[event].push(handler);
}
function connect() {
if(!realtimeSessionPromise) {
connectSession();
}
if(!connectionIntervalId) {
connectionIntervalId = setInterval(function() {
if(!webSocket || webSocket.readyState > 1) {
realtimeSessionPromise.then(connectSocket);
}
}, 100);
}
}
function connectSession() {
var defer = Q.defer();
realtimeSessionPromise = defer.promise;
var url = apiClient.url("/messaging/realtime/sessions");
apiClient.request("post", url)
.then(function(response) {
realtimeSessionId = response.realtimeSessionId;
defer.resolve();
})
.fail(function(error) {
notifyHandlers("error", {error:error});
});
return realtimeSessionPromise;
}
function connectSocket() {
var url = apiClient.url("/messaging/realtime", {}, {rsession: realtimeSessionId});
url = url.replace("http", "ws");
webSocket = createWebSocket(url);
webSocket.onopen = handleSocketOpen;
webSocket.onerror = handleSocketError;
webSocket.onmessage = handleSocketMessage;
webSocket.onclose = handleSocketClose;
}
function createWebSocket(url) {
if(typeof WebSocket != "undefined") {
return new WebSocket(url);
} else if(typeof WS != "undefined") {
return new WS(url);
}
}
function handleSocketOpen(event) {
sendQueue();
notifyHandlers("open", event);
}
function handleSocketError(event) {
notifyHandlers("error", event);
}
function handleSocketMessage(event) {
notifyHandlers("message", event);
}
function handleSocketClose(event) {
notifyHandlers("close", event);
}
function notifyHandlers(eventName, event) {
handlers[eventName].forEach(function(handler) {
handler(event);
});
}
}
},{"kew":3,"ws":5}],19:[function(_dereq_,module,exports){
var extend = _dereq_("extend");
var Q = _dereq_("kew");
module.exports = createUsersContext;
var internalProperties = ["id", "username", "save"];
function createUsersContext(apiClient, objects) {
var currentUser = null;
init();
return {
restoreSession: restoreSession,
signup: signup,
login: login,
logout: logout,
currentUser: function() { return currentUser; }
};
function init() {
restoreSession();
}
function createUser(username, properties) {
var allProperties = extend({}, properties, {sysUsername:username});
var user = objects.create("users", allProperties);
return user;
}
function signup(username, password, properties) {
var defer = Q.defer();
var url = apiClient.url("/users");
var data = extend({sysUsername:username, sysPassword:password}, properties);
apiClient.request("post", url, data)
.then(function(result) {
handleSignupOrLoginSuccess(username, result);
defer.resolve(currentUser);
})
.fail(function(error) {
defer.reject(error);
});
return defer.promise;
}
function login(username, password) {
var defer = Q.defer();
var url = apiClient.url("/sessions");
apiClient.request("post", url, {sysUsername:username, sysPassword:password})
.then(function(result) {
handleSignupOrLoginSuccess(username, result);
defer.resolve(currentUser);
})
.fail(function(error) {
defer.reject(error);
});
return defer.promise;
}
function handleSignupOrLoginSuccess(username, result) {
var id = result.user ? result.user.sysObjectId : null;
storeSession(result.sysSessionId, username, id);
currentUser = createUser(username, result.user);
}
function logout() {
currentUser = null;
apiClient.sessionId(null);
localStorage.removeItem("appstax_session_" + apiClient.appKey());
}
function storeSession(sessionId, username, id) {
apiClient.sessionId(sessionId);
localStorage.setItem("appstax_session_" + apiClient.appKey(), JSON.stringify({
username: username,
sessionId: sessionId,
userId: id
}));
}
function restoreSession() {
if(typeof localStorage == "undefined") {
return;
}
var sessionData = localStorage.getItem("appstax_session_" + apiClient.appKey());
if(sessionData) {
var session = JSON.parse(sessionData);
apiClient.sessionId(session.sessionId);
currentUser = createUser(session.username,
{sysObjectId:session.userId});
}
}
function getPropertyNames(user) {
var keys = Object.keys(user);
internalProperties.forEach(function(internal) {
var index = keys.indexOf(internal);
if(index >= 0) {
keys.splice(index, 1);
}
});
return keys;
}
function getProperties(user) {
var data = {};
getPropertyNames(user).forEach(function(key) {
data[key] = user[key];
});
return data;
}
}
},{"extend":1,"kew":3}]},{},[11])
(11)
});
|
define('blog/app', [
'jquery',
'list'
], function($, List) {
'use strict';
var timeData = [
'<li>',
'<h4><span class="open">▼</span>2014</h4>',
'<ul>',
'<li class="item"><a href="http://ianli-sc.github.io/performanceInspector/">Performance Inspector</a></li>',
'<li class="item"><a href="http://ianli-sc.github.io/jqDataTable/">jQuery data table</a></li>',
'</ul>',
'</li>'
];
List.init(timeData);
});
|
/**
* Это внутренний класс, который не должен использоваться приложением.
* @classdesc Box - это тип View, который умеет выбирать какие View показывать.
* @param {string} id
* @param {object} params
* @constructor
* @private
*/
ns.Box = function(id, params) {
this.id = id;
this.__setUniqueId();
this.params = params;
this.views = {};
// у бокса нет декларации и ключ строить не надо
this.key = ns.Box.getKey(id);
this.node = null;
/**
* Активные (видимые) в данный момент виды.
* @private
* @type {object}
*/
this.active = {};
this._visible = false;
this.info = {
isBox: true,
isCollection: false
};
};
/**
* Возвращает ключ вида
* @param {string} id Название вида
* @param {object} params Параметры для ключа
* @param {ns.L} type Тип
* @returns {string}
* @private
*/
ns.Box.prototype._getViewKey = function(id, params, type) {
var key;
if (type === ns.L.BOX) {
key = ns.Box.getKey(id);
} else {
key = ns.View.getKey(id, params);
}
return key;
};
/**
*
* @param {string} id
* @param {object} params
* @param {string} type Тип вида.
* @returns {ns.View}
* @private
*/
ns.Box.prototype._getView = function(id, params, type) {
var key = this._getViewKey(id, params, type);
return this.views[key];
};
/**
*
* @param {string} id
* @param {object} params
* @param {ns.L} type
* @returns {ns.View}
* @private
*/
ns.Box.prototype._addView = function(id, params, type) {
var view = this._getView(id, params, type);
if (!view) {
if (type === ns.L.BOX) {
view = new ns.Box(id, params);
} else {
view = ns.View.create(id, params, type === ns.L.ASYNC);
}
this.views[view.key] = view;
}
return view;
};
/**
*
* @param {array} descs
* @returns {array}
* @private
*/
ns.Box.prototype._getDescendantsAndSelf = function(descs) {
var views = this.views;
descs.push(this);
for (var id in views) {
var view = views[id];
view._getDescendantsAndSelf(descs);
}
return descs;
};
/**
* Ищем все новые блоки и блоки, требующие перерисовки.
* @param {object} updated
* @param {object} layout
* @param {object} params
* @private
*/
ns.Box.prototype._getRequestViews = function(updated, layout, params) {
var layoutViews = layout.views;
var layoutActive = {};
for (var id in layoutViews) {
var childViewLayout = layoutViews[id];
// Согласно новому layout'у здесь должен быть view с id/params.
// Создаем его (если он уже есть, он возьмется из this.views).
var view = this._addView(id, params, childViewLayout.type);
// Идем вниз рекурсивно.
view._getRequestViews(updated, childViewLayout, params);
layoutActive[id] = view.key;
}
// сохраняем новый активный layout, в дальнейшем работает с ним
this.active = layoutActive;
};
/**
* Боксы всегда валидные, т.е. не toplevel, поэтому просто идем вниз по дереву.
* @param {object} tree
* @private
*/
ns.Box.prototype._getUpdateTree = function(tree) {
if ( this.isNone() ) {
tree.views[this.id] = this._getViewTree();
} else {
for (var id in this.active) {
var viewKey = this.active[id];
this.views[viewKey]._getUpdateTree(tree);
}
}
};
/**
* Строим дерево блоков.
* @returns {object}
* @private
*/
ns.Box.prototype._getViewTree = function() {
var tree = this._getCommonTree();
for (var id in this.active) {
var viewKey = this.active[id];
tree.views[id] = this.views[viewKey]._getViewTree();
}
return tree;
};
ns.Box.prototype.beforeUpdateHTML = function(events, toHide) {
for (var viewKey in this.views) {
// Достаем ранее созданный блок (в _getRequestViews).
/** @type {ns.View} */
var view = this.views[viewKey];
toHide = toHide || (this.active[view.id] !== view.key);
view.beforeUpdateHTML(events, toHide);
}
};
/**
* Скрываем все неактивные виды в боксе
* @private
*/
ns.Box.prototype._hideInactiveViews = function() {
// Пройдёмся по всем вложенным видам, чтобы кинуть hide, которым не попали в newLayout
for (var key in this.views) {
var view = this.views[key];
// Если вид не входит в новый active
if (this.active[view.id] !== view.key) {
// Мы проверили большой эксперимент и выяснили,
// что если не скрывать вьюхи, а детачить их из DOM,
// то приложение работает быстрее, когда открыто продолжительное время.
// вид может не быть отрисован,
// но уже уйти в скрытие
if (view.node) {
ns.removeNode(view.node);
}
// Скроем виды, не попавшие в layout
var descs = view._getDescendantsAndSelf( [] );
for (var i = 0, l = descs.length; i < l; i++) {
descs[i].hideAndUnbindEvents();
}
}
}
};
/**
* Обновляем бокс.
* @param {HTMLElement} node
* @param {object} options
* @param {object} events
* @private
*/
ns.Box.prototype._updateHTML = function(node, options, events) {
var oldNode;
// Если
// - старой ноды не было
// - или этот box не toplevel (т.е. родительский view обновил свою ноду)
if (!this.node || !options.toplevel) {
// Ищем новую ноду бокса.
var newNode = ns.byClass('ns-view-' + this.id, node)[0];
// И если есть
if (newNode) {
// Сохраним ссылку на старую ноду
oldNode = this.node;
// Обновим ноду бокса
this.node = newNode;
}
}
if (!this.node) {
throw new Error("[ns.Box] Can't find node for '" + this.id + "'");
}
this._hideInactiveViews();
var views = this.views;
var boxLayout = this.active;
// Строим новый active согласно layout'у.
// Т.е. это тот набор блоков, которые должны быть видимы в боксе после окончания всего апдейта
// (включая синхронную и все асинхронные подапдейты).
for (var id in boxLayout) {
var viewKey = boxLayout[id];
// Достаем ранее созданный блок (в _getRequestViews).
/** @type {ns.View} */
var view = views[viewKey];
// Обновляем его.
view._updateHTML(node, options, events);
// Вставка ноды в DOM будет выполнена во время сортировки нод в боксе (ниже).
}
// Пройдёмся по всем вложенным видам,
// чтобы перенести ноды вложенных видов в новую ноду бокса (если есть)
this._transferViewsToNewNode(oldNode);
// Сортируем ноды видов внутри бокса. Попутно добавляются новые ноды видов.
this._sortViewNodes();
this._show();
};
/**
* Сортировка видов внутри бокса.
* Новые ноды видов также добавляются тут.
* @private
*/
ns.Box.prototype._sortViewNodes = function() {
var active = this.active;
var views = this.views;
// Итератор по HTMLCollection, который возвращает видимые ноды видов.
var viewNodesIterator = ns.childrenIterator(this.node);
for (var viewId in active) {
var viewKey = active[viewId];
var view = views[viewKey];
var cursorViewNode = viewNodesIterator.getNext();
if (cursorViewNode !== view.node) {
if (cursorViewNode) {
this.node.insertBefore(view.node, cursorViewNode);
} else {
this.node.appendChild(view.node);
}
}
}
};
/**
* Переносит неактивные виды из старой ноды в новую после перерисовки бокса.
* @param {HTMLElement} oldNode
* @private
*/
ns.Box.prototype._transferViewsToNewNode = function(oldNode) {
// если старой ноды нет, то значит бокс не перерисовывался
if (!oldNode) {
return;
}
var views = this.views;
for (var key in views) {
var view = views[key];
// Если вид не входит в новый active
if (this.active[view.id] !== view.key) {
var viewNode = view.node;
// Если нода вида лежит в старой ноде бокса
if (oldNode.contains(viewNode)) {
// Перенесём её в новую ноду бокса (сам вид скрыт).
this.node.appendChild(viewNode);
}
}
}
};
/**
*
* @returns {boolean}
* @private
*/
ns.Box.prototype._show = function() {
if (this._visible === false) {
this._visible = true;
// always returns false to prevent events trigger
}
return false;
};
/**
* Скрывает view
* @returns {Boolean}
* @protected
*/
ns.Box.prototype.hideAndUnbindEvents = function() {
if (this._visible === true) {
this._visible = false;
}
};
/**
* Returns true if box has status NONE
* @returns {boolean}
*/
ns.Box.prototype.isNone = function() {
return !this.node;
};
ns.Box.prototype.isValid = function() {
return !!this.node;
};
/**
* Очищает себя и все внутренние блоки.
* Этот блок больше никогда не будет живым, этот метод используется для очистки памяти.
*/
ns.Box.prototype.destroy = function() {
// уничтожаем детей
var views = this.views;
for (var id in views) {
views[id].destroy();
}
if (this.node) {
$(this.node)
// события
.off()
// данные
.removeData()
// удаляем из DOM
.remove();
this.node = null;
this.$node = null;
}
this.active = null;
this.key = null;
this.params = null;
this.views = null;
this._visible = false;
};
// копируем нужные методы из ns.View
ns.Box.prototype.__setUniqueId = ns.View.prototype.__setUniqueId;
ns.Box.prototype._getCommonTree = ns.View.prototype._getCommonTree;
ns.Box.prototype.isValidWithDesc = ns.View.prototype.isValidWithDesc;
ns.Box.prototype.isOk = no.true;
ns.Box.prototype.isLoading = no.false;
/**
* Создает ключ для ns.Box.
* @param {string} id Название ns.Box.
* @returns {string}
* @static
*/
ns.Box.getKey = function(id) {
return 'box=' + id;
};
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _IconBase = require('./../components/IconBase/IconBase');
var _IconBase2 = _interopRequireDefault(_IconBase);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var IosCrop = function (_React$Component) {
_inherits(IosCrop, _React$Component);
function IosCrop() {
_classCallCheck(this, IosCrop);
return _possibleConstructorReturn(this, Object.getPrototypeOf(IosCrop).apply(this, arguments));
}
_createClass(IosCrop, [{
key: 'render',
value: function render() {
if (this.props.bare) {
return _react2.default.createElement(
'g',
null,
_react2.default.createElement(
'g',
null,
_react2.default.createElement('rect', { x: '128', y: '64', width: '16', height: '48' }),
_react2.default.createElement('polygon', { points: '144,368 144,160 128,160 128,384 352,384 352,368 \t' }),
_react2.default.createElement('rect', { x: '400', y: '368', width: '48', height: '16' }),
_react2.default.createElement('polygon', { points: '64,128 64,144 368,144 368,448 384,448 384,128 \t' })
)
);
}return _react2.default.createElement(
_IconBase2.default,
null,
_react2.default.createElement(
'g',
null,
_react2.default.createElement('rect', { x: '128', y: '64', width: '16', height: '48' }),
_react2.default.createElement('polygon', { points: '144,368 144,160 128,160 128,384 352,384 352,368 \t' }),
_react2.default.createElement('rect', { x: '400', y: '368', width: '48', height: '16' }),
_react2.default.createElement('polygon', { points: '64,128 64,144 368,144 368,448 384,448 384,128 \t' })
)
);
}
}]);
return IosCrop;
}(_react2.default.Component);
exports.default = IosCrop;
;IosCrop.defaultProps = { bare: false };
|
// https://github.com/ed-lea/jquery-collagePlus
//= require jquery.collageplus/v0.3.3/jquery.collageplus.js
|
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker: */
// +---------------------------------------------------------------------------
// | SWAN [ $_SWANBR_SLOGAN_$ ]
// +---------------------------------------------------------------------------
// | Copyright $_SWANBR_COPYRIGHT_$
// +---------------------------------------------------------------------------
// | Version $_SWANBR_VERSION_$
// +---------------------------------------------------------------------------
// | Licensed ( $_SWANBR_LICENSED_URL_$ )
// +---------------------------------------------------------------------------
// | $_SWANBR_WEB_DOMAIN_$
// +---------------------------------------------------------------------------
/**
+------------------------------------------------------------------------------
* madapter attribute
+------------------------------------------------------------------------------
*
* @package
* @version $_SWANBR_VERSION_$
* @copyright $_SWANBR_COPYRIGHT_$
* @author $_SWANBR_AUTHOR_$
+------------------------------------------------------------------------------
*/
function SwanmAdapterAttr() {
ModuleBase.call(this);
/*{{{members*/
var __this = this;
/*}}}*/
/*{{{functions*/
/*{{{init Attr*/
/**
* init Attr
*/
this.init = function () {
D(12312123)
}
/*}}}*/
/*{{{show attr dataTable*/
/**
* show attr dataTable
*/
this.loadIndexList = function () {
$(document).ready(function () {
var madapter_id = $('#madapterAttr_table').attr('madapter_id');
$('#madapterAttr_table').dataTable({
'processing': false,
'serverSide': true,
'ordering': false,
'ajax': {
'url': gPrefixUrl + 'mAdapterAttr_index',
'type': 'post',
'data': {'madapter_id' : madapter_id}
},
'columns': [
{data: function (obj) {
var checkHtml = '<div class="checker"><span><input type="checkbox" value="' + obj.attr_id + '" class="checkboxes" name="attr_id[]"></span></div>';
return checkHtml;
}},
{data: 'attr_name'},
{data: 'attr_display_name'},
{data: 'form_type'},
{data: 'form_data'},
{data: 'attr_default'},
{data: function (obj) {
var __html = [];
__html.push('<a class="btn mini black" href="javascript:;"><i class="icon-edit"></i> Edit</a>');
__html.push('<a class="btn mini black" href="javascript:;"><i class="icon-trash"></i> Delete</a>');
return __html.join(' ');
}}
]
});
//分页
jQuery('#madapterAttr_table_wrapper .dataTables_filter input').addClass("m-wrap small");
jQuery('#madapterAttr_table_wrapper .dataTables_length select').addClass("m-wrap small");
jQuery('#madapterAttr_table_wrapper .dataTables_length select').select2();
});
}
/*}}}*/
/*{{{validate add attr */
/**
* validate add attr
*/
this.initAdd = function () {
},
/*}}}*/
/*{{{add attr data*/
/**
* add attr data
*/
this.addData = function () {
}
/*}}}*/
/*}}}*/
}
|
import OAuth2PasswordGrant from 'ember-simple-auth/authenticators/oauth2-password-grant';
export default OAuth2PasswordGrant.extend({
serverTokenEndpoint: 'http:///localhost:80/employees/admin'
// serverTokenEndpoint: 'http://localhost:80/intranet-api/admin'
});
|
'use strict';
var React = require('react');
var SvgIcon = require('../../svg-icon');
var ImageAssistant = React.createClass({
displayName: 'ImageAssistant',
render: function render() {
return React.createElement(
SvgIcon,
this.props,
React.createElement('path', { d: "M19 2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h4l3 3 3-3h4c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-5.12 10.88L12 17l-1.88-4.12L6 11l4.12-1.88L12 5l1.88 4.12L18 11l-4.12 1.88z" })
);
}
});
module.exports = ImageAssistant;
|
import React from 'react';
import IconBase from './../components/IconBase/IconBase';
export default class IosIonicOutline extends React.Component {
render() {
if(this.props.bare) {
return <g>
<g>
<path d="M425.5,134.8c4.7-5.9,7.5-13.5,7.5-21.6c0-19.2-15.6-34.9-34.8-34.9c-8.2,0-15.7,2.8-21.6,7.5c-34-24.2-75-37.8-119.9-37.8
C141.8,48,48,140.5,48,255.6C48,370.7,141.7,464,256.6,464C371.5,464,464,370.7,464,255.6C464,210.6,449.7,168.9,425.5,134.8z
M398,91.3c12.2,0,22,9.9,22,22c0,12.2-9.9,22-22,22c-12.2,0-22-9.9-22-22C376,101.2,385.8,91.3,398,91.3z M391.8,391.7
c-17.6,17.6-38.2,31.6-61.1,41.3c-23.7,10-48.2,15.2-74.2,15.2c-25.9,0-51.7-5.1-75.4-15.2c-22.9-9.7-43.4-23.5-61.1-41.3
c-17.6-17.6-31.5-38.3-41.2-61.2c-10-23.7-15.1-48.9-15.1-74.9c0-25.9,5.1-51.2,15.1-74.9c9.7-22.9,23.5-43.5,41.2-61.2
s38.2-31.6,61.1-41.3c23.7-10,49.4-14.1,75.4-14.1c25.9,0,50.5,4,74.2,14.1c12.7,5.4,24.7,12.1,35.9,20c-2.1,4.5-3.3,9.5-3.3,14.9
c0,19.2,15.6,34.9,34.8,34.9c5.3,0,10.3-1.2,14.9-3.3c7.9,11.2,14.6,23.2,20,36c10,23.7,15.1,48.9,15.1,74.9
c0,25.9-5.1,51.2-15.1,74.9C423.3,353.4,409.5,374,391.8,391.7z"></path>
<path d="M256.5,160.1c-53,0-96,42.8-96,95.9s42.9,96.1,96,96.1c53,0,96-43,96-96.1S309.5,160.1,256.5,160.1z M256.5,335.8
c-44.1,0-79.7-35.8-79.7-79.8c0-44.1,35.6-79.6,79.7-79.6s79.7,35.6,79.7,79.6C336.2,300.1,300.5,335.8,256.5,335.8z"></path>
</g>
</g>;
} return <IconBase>
<g>
<path d="M425.5,134.8c4.7-5.9,7.5-13.5,7.5-21.6c0-19.2-15.6-34.9-34.8-34.9c-8.2,0-15.7,2.8-21.6,7.5c-34-24.2-75-37.8-119.9-37.8
C141.8,48,48,140.5,48,255.6C48,370.7,141.7,464,256.6,464C371.5,464,464,370.7,464,255.6C464,210.6,449.7,168.9,425.5,134.8z
M398,91.3c12.2,0,22,9.9,22,22c0,12.2-9.9,22-22,22c-12.2,0-22-9.9-22-22C376,101.2,385.8,91.3,398,91.3z M391.8,391.7
c-17.6,17.6-38.2,31.6-61.1,41.3c-23.7,10-48.2,15.2-74.2,15.2c-25.9,0-51.7-5.1-75.4-15.2c-22.9-9.7-43.4-23.5-61.1-41.3
c-17.6-17.6-31.5-38.3-41.2-61.2c-10-23.7-15.1-48.9-15.1-74.9c0-25.9,5.1-51.2,15.1-74.9c9.7-22.9,23.5-43.5,41.2-61.2
s38.2-31.6,61.1-41.3c23.7-10,49.4-14.1,75.4-14.1c25.9,0,50.5,4,74.2,14.1c12.7,5.4,24.7,12.1,35.9,20c-2.1,4.5-3.3,9.5-3.3,14.9
c0,19.2,15.6,34.9,34.8,34.9c5.3,0,10.3-1.2,14.9-3.3c7.9,11.2,14.6,23.2,20,36c10,23.7,15.1,48.9,15.1,74.9
c0,25.9-5.1,51.2-15.1,74.9C423.3,353.4,409.5,374,391.8,391.7z"></path>
<path d="M256.5,160.1c-53,0-96,42.8-96,95.9s42.9,96.1,96,96.1c53,0,96-43,96-96.1S309.5,160.1,256.5,160.1z M256.5,335.8
c-44.1,0-79.7-35.8-79.7-79.8c0-44.1,35.6-79.6,79.7-79.6s79.7,35.6,79.7,79.6C336.2,300.1,300.5,335.8,256.5,335.8z"></path>
</g>
</IconBase>;
}
};IosIonicOutline.defaultProps = {bare: false}
|
import { moduleFor, test } from 'ember-qunit';
moduleFor('controller:login/settings', 'Unit | Controller | login/settings', {
// Specify the other units that are required for this test.
// needs: ['controller:foo']
});
// Replace this with your real tests.
test('it exists', function(assert) {
let controller = this.subject();
assert.ok(controller);
});
|
import {
GET_USER_RECIPES,
GET_USER_RECIPES_ERROR,
DELETE_RECIPE,
DELETE_RECIPE_ERROR
} from '../../actions/actionTypes';
import getUserRecipe from '../../reducers/getUserRecipe';
describe('Test for getUserRecipe reducer should', () => {
it('set recipe when action of type GET_USER_RECIPES is called', () => {
const initialState = {
recipe: { }
};
const action = {
type: GET_USER_RECIPES,
recipes: [
{
id: 3,
name: 'recipe 3',
userId: 1,
},
{
id: 2,
name: 'recipe 2',
userId: 1,
}
]
};
const newState = getUserRecipe(initialState, action);
expect(newState.userRecipes).toEqual(action.recipes);
expect(newState.getUserRecipeError).toEqual(false);
});
it('update store correctly when action of type GET_USER_RECIPES_ERROR is called', () => {
const initialState = {
recipe: { }
};
const action = {
type: GET_USER_RECIPES_ERROR,
addRecipeErrorMessage: 'error'
};
const newState = getUserRecipe(initialState, action);
expect(newState.userRecipes).toEqual([]);
expect(newState.getUserRecipeError).toEqual(true);
});
it('update store correctly when action of type DELETE_RECIPE_ERROR is called', () => {
const initialState = {
recipe: { }
};
const action = {
type: DELETE_RECIPE_ERROR,
addRecipeErrorMessage: 'error'
};
const newState = getUserRecipe(initialState, action);
expect(newState).toBeTruthy();
});
it('set recipe when action of type DELETE_RECIPE is called', () => {
const initialState = {
recipes: { },
userRecipes: [
{
id: 3,
name: 'recipe 3',
userId: 1,
},
{
id: 2,
name: 'recipe 2',
userId: 1,
}
]
};
const action = {
type: DELETE_RECIPE,
recipeId: 3,
recipes: [
{
id: 3,
name: 'recipe 3',
userId: 1
},
{
id: 2,
name: 'recipe 2',
userId: 1,
}
]
};
const newState = getUserRecipe(initialState, action);
expect((newState.userRecipes).length).toEqual(1);
});
});
|
import { Indicator, IndicatorInput } from '../indicator/indicator';
export class CrossInput extends IndicatorInput {
constructor(lineA, lineB) {
super();
this.lineA = lineA;
this.lineB = lineB;
}
}
export class CrossUp extends Indicator {
constructor(input) {
super(input);
this.lineA = input.lineA;
this.lineB = input.lineB;
var currentLineA = [];
var currentLineB = [];
const genFn = (function* () {
var current = yield;
var result = false;
while (true) {
currentLineA.unshift(current.valueA);
currentLineB.unshift(current.valueB);
result = current.valueA > current.valueB;
var pointer = 1;
while (result === true && currentLineA[pointer] >= currentLineB[pointer]) {
if (currentLineA[pointer] > currentLineB[pointer]) {
result = false;
}
else if (currentLineA[pointer] < currentLineB[pointer]) {
result = true;
}
else if (currentLineA[pointer] === currentLineB[pointer]) {
pointer += 1;
}
}
if (result === true) {
currentLineA = [current.valueA];
currentLineB = [current.valueB];
}
current = yield result;
}
});
this.generator = genFn();
this.generator.next();
this.result = [];
this.lineA.forEach((value, index) => {
var result = this.generator.next({
valueA: this.lineA[index],
valueB: this.lineB[index]
});
if (result.value !== undefined) {
this.result.push(result.value);
}
});
}
static reverseInputs(input) {
if (input.reversedInput) {
input.lineA ? input.lineA.reverse() : undefined;
input.lineB ? input.lineB.reverse() : undefined;
}
}
nextValue(valueA, valueB) {
return this.generator.next({
valueA: valueA,
valueB: valueB
}).value;
}
;
}
CrossUp.calculate = crossUp;
export function crossUp(input) {
Indicator.reverseInputs(input);
var result = new CrossUp(input).result;
if (input.reversedInput) {
result.reverse();
}
Indicator.reverseInputs(input);
return result;
}
|
function quadraticEquation(args){
//ax^2 + bx + c = 0
let a = +args[0],
b = +args[1],
c = +args[2];
let x1,x2;
const discriminant = Math.pow(b,2) - 4 * a * c;
if(discriminant === 0){
x1 = x2 =(-b/(2 * a)).toFixed(2);
console.log('x1=x2=' + x1);
}
else if(discriminant < 0){
console.log('no real roots');
}
else if( discriminant > 0){
x1 = ((-b - Math.sqrt(discriminant))/ (2 * a)).toFixed(2);
x2 = ((-b + Math.sqrt(discriminant))/ (2 * a)).toFixed(2);
console.log('x1='+ x1 + ';'+ ' '+ 'x2='+ x2);
}
}
quadraticEquation(['0.2', '9.572', '0.2']);
|
"use strict";
/**
* Created by johan on 27/04/16.
*
* Should be in a directory 1 level up.
*/
var express = require("express");
var vhost = require("vhost");
var tls = require("tls");
var fs = require("fs");
// pass your own objects/apps or use cody.makeWebApp to generate them
// apps should be an application object or an array of, each application object
// should have
// app [express application]
// host [ string or array of strings ]
// should have at least 1 of the 2 below
// http [ portnumber for the http services ]
// https [ portnumber for the https services ]
// should have -if https port is specified-
// certificate [ filename without extention of the key-pair ]
/*
startserver({ app: testApp, https: 443, host: "localhost", certificate: "mykey" });
or
startserver([{...}, {...}]);
or
host: ["localhost", "www.mysite.com", ...]
Cody production example:
------------------------
var cody = require("cody");
cody.makeWebApp(__dirname, "mysite", function(app) {
console.log("Loaded mysite web app with config:", cody.config);
startServer(app);
});
// for multi site hosting, collect all app's in an array
// and when all set up, pass the array to startServer.
Cody development startup:
-------------------------
var cody = require("cody");
cody.makeWebApp(__dirname, "mysite", "config-devel.json", function(app) {
console.log("loaded mysite");
app.app.listen(app.http, function() {
console.log("mysite listening on " + this.address().port);
});
}
*/
// global express app, wrapping all other apps
var exp;
// global object containing for each domain the certificates
var sites;
// collected ports -> example = { 80: false, 443: true }
var ports = {};
module.exports = function( apps ) {
// make our global express app and an empty site list
exp = express();
sites = [];
if (apps instanceof Array) {
for (let app of apps) {
startApp(app);
}
} else {
startApp(apps);
}
// get at least one listener
var http = false;
var https = false;
for (let port in ports) {
if (!ports[port]) http = true;
if (ports[port]) https = true;
}
if (!http && !https) {
http = true;
ports[3000] = false;
}
console.log("==> ports:", ports);
//////////
// http //
//////////
if (http) {
var httpFactory = require('http');
var httpServer = httpFactory.createServer(exp);
// http ports are "false"
for (let port in ports)
if (! ports[port])
httpServer.listen(port, function () {
console.log("Listening for http on port: " + this.address().port);
});
}
///////////
// https //
///////////
if (https) {
var secureOpts = {
SNICallback: function (domain, cb) {
if (typeof sites[domain] === "undefined") {
cb(new Error("domain not found"), null);
console.log("Error: domain not found: " + domain);
} else {
cb(null, sites[domain]);
}
}
/* left out the default keys:
key: fs.readFileSync('....key').toString(),
cert: fs.readFileSync('....crt').toString()
*/
};
var httpsFactory = require('https');
var httpsServer = httpsFactory.createServer(secureOpts, exp);
// https ports are "true"
for (let port in ports)
if (ports[port])
httpsServer.listen(port, function () {
console.log("Listening https on port: " + this.address().port);
console.log(" with certificates: ", sites);
});
}
};
function startApp( application ) {
// collect extra portnumbers
if (application.http && (typeof ports[application.http] === "undefined")) ports[application.http] = false;
if (application.https && (typeof ports[application.https] === "undefined")) ports[application.https] = true;
var certContext;
// if the application has a certificate, create a tls credential context of it
if ((application.certificate) && (application.certificate.length > 0)) {
certContext = tls.createSecureContext({
key: fs.readFileSync(application.certificate + '.key').toString(),
cert: fs.readFileSync(application.certificate + '.crt').toString()
}).context;
}
// start the application for each (virtual) host
if (application.host instanceof Array) {
for (let host of application.host) {
startHost( host, application.app, certContext );
}
} else {
startHost( application.host, application.app, certContext );
}
}
function startHost( host, app, certContext ) {
console.log("added host " + host);
exp.use(vhost(host, app));
if (certContext) {
// if we have a credential context, add it to our hashmap
console.log("added certificates for " + host);
sites[host] = certContext;
}
}
|
'use strict';
var _ = require('lodash');
var async = require('async');
var config = require('config');
var queue = require('./services/queue-service')(config);
var workers = require('./lib/workers');
var Message = require('./lib/message');
var process = function() {
queue.receiveMessage(function(err, data) {
if (data.Messages && data.Messages.length) {
var message = new Message().ingest(data.Messages[0]);
console.log('Processing message:', message);
async.series([
function(callback) {
async.applyEachSeries(_.pluck(workers, 'process'), message, callback);
},
function(callback) {
queue.deleteMessage(message, callback);
}
], function(err, data) {
if (err) {
console.log(err, err.stack);
} else {
console.log('Done');
}
});
} else {
console.log('No messages to process at this time');
}
});
};
console.log('Worker started');
(function poll() {
process();
setTimeout(poll, 30e3);
})();
|
args = Array.prototype.slice.call(args, 1);
// [0] = type, [1] = lib.jar [2] = blockX, [3] = classX
var File = java.io.File,
FileReader = java.io.FileReader,
FileInputStream = java.io.FileInputStream,
FRAMEWORK = args[0],
out = java.lang.System.out,
err = java.lang.System.err,
Modifier = java.lang.reflect.Modifier,
clz,
ZipInputStream = java.util.zip.ZipInputStream,
zis = new ZipInputStream(new FileInputStream(args[1])),
entry = null;
var content = [
'/*********************',
'## Events Helper Module (' + FRAMEWORK + ' version)',
'The Events helper module provides a suite of functions - one for each possible event.',
'For example, the events.' + args[2] + '() function is just a wrapper function which calls events.on(' + args[3] + ', callback, priority)',
'This module is a convenience wrapper for easily adding new event handling functions in JavaScript. ',
'At the in-game or server-console prompt, players/admins can type `events.` and use TAB completion ',
'to choose from any of the approx. 160 different event types to listen to.',
'',
'### Usage',
'',
' events.' + args[2] + '( function( event ) { ',
' echo( event.player, \'You broke a block!\'); ',
' });',
'',
'The crucial difference is that the events module now has functions for each of the built-in events. The functions are accessible via TAB-completion so will help beginning programmers to explore the events at the server console window.',
'',
'***/'
];
var canary = false;
if (FRAMEWORK == 'CanaryMod') {
canary = true;
}
for (var i = 0; i < content.length; i++) {
out.println(content[i]);
}
while ((entry = zis.nextEntry) != null) {
var name = new String(entry.name);
var re1 = /org\/bukkit\/event\/.+Event\.class$/;
if (canary) {
re1 = /net\/canarymod\/hook\/.+Hook\.class$/;
}
if (re1.test(name)) {
name = name.replace(/\//g, '.').replace('.class', '');
try {
clz = java.lang.Class.forName(name);
} catch (e) {
err.println('Warning: could not Class.forName("' + name + '")');
clz = engine.eval(name);
}
var isAbstract = Modifier.isAbstract(clz.getModifiers());
if (isAbstract) {
continue;
}
var parts = name.split('.');
var shortName = null;
if (canary) {
shortName = name.replace('net.canarymod.hook.', '');
}
if (!canary) {
shortName = name.replace('org.bukkit.event.', '');
}
var fname = parts.reverse().shift().replace(/^(.)/, function (a) {
return a.toLowerCase();
});
if (!canary) {
fname = fname.replace(/Event$/, '');
}
if (canary) {
fname = fname.replace(/Hook$/, '');
}
var javaDoc = canary ? 'https://ci.visualillusionsent.net/job/CanaryLib/javadoc/net/canarymod/hook/' : 'https://hub.spigotmc.org/javadocs/spigot/org/bukkit/event/';
var comment = [
'/*********************',
'### events.' + fname + '()',
'',
'#### Parameters ',
'',
' * callback - A function which is called whenever the [' + shortName + ' event](' + javaDoc + shortName.replace('.', '/') + '.html) is fired',
'',
' * priority - optional - see events.on() for more information.',
'',
'***/'
//http://jd.bukkit.org/rb/apidocs/org/bukkit/event/player/PlayerJoinEvent.html
];
for (var i = 0; i < comment.length; i++) {
out.println(comment[i]);
}
out.println('exports.' + fname + ' = function(callback,priority){ ');
if (canary) {
out.println(' return events.on(Packages.' + name + ',callback,priority);');
} else {
out.println(' return events.on(' + name + ',callback,priority);');
}
out.println('};');
}
}
|
(function() {
'use strict';
var logger = require('../my_modules/logHelper.js');
var common = require('../my_modules/common.js');
var edModel = require('../models/edModel.js');
var express = require('express');
var router = express.Router();
router.get('/account/regist', function(req, res, next) {
var api = [
{
name: 'seed',
url: '/api/ed25519-supercop/createSeed',
type: 'get',
params: {},
results: {
seed: null
}
},
{
name: 'keyPair',
url: '/api/ed25519-supercop/createKeyPair',
type: 'get',
params: {
seed: 'seed'
},
results: {}
}
];
var attach = {
};
var resource = [
'/public/css/animate.min.css',
'/public/css/common.css',
'/public/js/lib/socket.io.min.js',
'/public/js/lib/crypto-js.js',
'/public/js/account/regist.js'
];
common.dataFactory(req, res, api, attach, function(err, data) {
res.render('./account/regist.html', data, function(err, html) {
res.send(common.addResource(html, resource));
});
});
});
router.get('/account/login', function(req, res, next) {
var api = [];
var attach = {};
var resource = [
'/public/css/animate.min.css',
'/public/css/common.css',
'/public/js/lib/crypto-js.js',
'/public/js/account/login.js'
];
if (req.query.logout) {
req.session.keyPair = null;
}
common.dataFactory(req, res, api, attach, function(err, data) {
res.render('./account/login.html', data, function(err, html) {
res.send(common.addResource(html, resource));
});
});
});
router.post('/account/login', function(req, res, next) {
var data = {};
if (edModel.isKeyPair(req.body)) {
req.session.keyPair = req.body;
data.success = true;
data.message = '密钥文件正确';
} else {
data.success = false;
data.message = '密钥文件不正确';
}
res.json(data);
});
module.exports = router;
})();
|
$("#toogle-wms").css("visibility", "visible");
//swir wms
var swirwms = L.tileLayer.betterWms("http://landsatfact-data-dev.nemac.org/lsf-cr-swir-allchange?AOI_ID=368", {
layers: 'swir-archiveMaskForForestCloud',
format: 'image/png',
transparent: true,
attribution: '<a href="http://www.landsatfact.com">Landsat FACT</a>',
maxZoom: 15,
opacity: 0.65
});
//ndvi wms
var ndviwms = L.tileLayer.betterWms("http://landsatfact-data-dev.nemac.org/lsf-cr-ndvi?AOI_ID=368", {
layers: 'ndvi-archiveMaskForForestCloud',
format: 'image/png',
transparent: true,
attribution: '<a href="http://www.landsatfact.com">Landsat FACT</a>',
maxZoom: 15,
opacity: 0.65
});
//ndmi wms
var ndmiwms = L.tileLayer.betterWms("http://landsatfact-data-dev.nemac.org/lsf-cr-ndmi?AOI_ID=368", {
layers: 'ndmi-archiveMaskForForestCloud',
format: 'image/png',
transparent: true,
attribution: '<a href="http://www.landsatfact.com">Landsat FACT</a>',
maxZoom: 15,
opacity: 0.65
});
//set overlays for map
var wmsLayers = {
"SWIR(wms)":swirwms,
"NDMI(wms)":ndmiwms,
"NDVI(wms)":ndviwms
};
overlayMaps.push(wmsLayers);
|
module.exports.init = function (db, words, callback) {
var batch = db.batch()
words.forEach(function (word) {
var key = word.length + '!' + word
batch.put(key, word)
})
batch.write(function (err) {
if (err)
callback(err)
else
callback(null)
})
}
module.exports.query = function (db, word, callback) {
var start = word.length + '!' + word.replace(/\*/g, '')
var end = word.length + '!' + word.replace(/\*/g, '~')
var results = []
var options = { start: start,
end: end,
keys: false,
values: true }
db.createReadStream(options).on('data', function (word) {
results.push(word)
}).on('error', function(err) {
if (err)
callback(err)
}).on('end', function() {
callback(null, results)
})
}
|
import { makeIconComponent } from './utils/icon-wrapper'
import { MenuNav3 } from '@clair/icons'
export const IconMenuNav3 = /*@__PURE__*/ makeIconComponent({
name: 'CIconMenuNav3',
template: MenuNav3
})
|
import prop from "./prop";
import flip from "./flip";
/**
* Returns the value at the specified property.
* The only difference from `prop` is the parameter order.
*
* @func
* @memberOf R
* @see R.prop
* @category Object
* @param {Object} obj The object to query
* @param {String} prop The property name
* @return {*} The value at obj.p
* @example
*
* prop({x: 100}, 'x'); // => 100
*/
export default flip(prop);
|
var Screen = function (element, settings) {
var screen = this;
var FPS = 0;
// All notes and lines will be stored in this variable and managed
// in key which represents index.
this.items = {};
// default screen settings
this.settings = {
width: 1120, // pixel
height: 630, // pixel
hitPosition: 0.4, // ratio
speed: 0.5, // pixel per second
noteSize: 50, // pixel
lyricSize: 20, // pixel
rollYpos: 0.5, // ratio
longLineHeight: 150, // pixel
lineHeight: 120, // pixel
screenPadding: 30, // pixel
bufferTextPosition: [0.2, 0.8], // ratio in screen
currentLyricPosition: [0.5, 0.25], // ratio in screen
nextLyricPosition: [0.5, 0.3], // ratio in screen
kanaLyricPosition: [0.5, 0.8], // ratio in screen
scoreTextPosition: [0.9, 0.1], // ratio in screen
judgeColors: {
perfect: 'yellow',
great: '#2d1',
good: '#19a',
bad: '#aaa',
failed: '#a34',
neglect: '#39a'
},
cursorHideTime: 1000, // millisecond
onGameEnd: function () {}, // function
highScore: 0, // number
'3d': false, // boolean
romaji: true // boolean
};
// default YouTyping setting
var youTypingSettings = {
videoId: 'fQ_m5VLhqNg',
videoStop: 0,
dataFile: 'data.utx',
tableFile: 'convert/romaji.xml',
initial: false, // boolean
correction: 0, // millisecond
controlledCorrection: 0, // millisecond
offset: 0, // second
volume: 100, // percent
playbackQuality: 'default',
screen: screen,
mercyBorder: 13.5
};
this.initialize = function () {
paper.setup(screen.canvas);
screen.cover = new paper.Path.Rectangle(paper.view.bounds);
screen.cover.fillColor = 'black';
screen.cover.fillColor.alpha = 0.7;
screen.debugTexts = [];
for (var i = 0; i < 7; i++) {
var index = screen.debugTexts.push(new paper.PointText([20, 20 * (i + 1)]));
screen.debugText = screen.debugTexts[index - 1];
screen.debugText.justification = 'left';
screen.debugText.fillColor = 'white';
}
screen.scoreText = new paper.PointText({
point: paper.view.bounds.bottomRight.multiply(settings.scoreTextPosition),
content: '0',
fillColor: 'white',
justification: 'right',
fontSize: 36
});
screen.bufferText = new paper.PointText({
point: paper.view.bounds.bottomRight.multiply(settings.bufferTextPosition),
content: '',
fillColor: 'white',
justification: 'left',
fontSize: 24
});
screen.currentLyric = new paper.Group();
screen.nextLyric = new paper.Group();
screen.kanaLyric = new paper.PointText({
point: paper.view.bounds.bottomRight.multiply(settings.kanaLyricPosition),
content: '',
fillColor: 'white',
justification: 'center',
fontSize: 24
});
screen.judgeEffects = new paper.Group();
setInterval(function () {
screen.debugTexts[0].content = 'FPS: ' + FPS;
FPS = 0;
screen.debugTexts[2].content = 'Zerocall FPS: ' + youTyping.zeroCallFPS;
youTyping.zeroCallFPS = 0; // not good
}, 1000);
screen.scorePad = 0;
screen.highScore = screen.settings.highScore;
screen.newRecord = false;
logTrace('Screen Initialized.');
};
this.onResourceReady = function () {
var now = youTyping.now;
// distance from hit line to right edge
var paddingRight = settings.width * (1 - settings.hitPosition)
+ settings.noteSize + settings.screenPadding;
// distance from hit line to left edge
var paddingLeft = settings.width * settings.hitPosition
+ settings.noteSize + settings.screenPadding;
try {
// Computes emerge time and vanishing time of item.
// This is yet a very simple way without regards for speed changes.
youTyping.roll.forEach(function (item, index) {
item.emergeTime = (settings.speed * item.time - paddingRight) / settings.speed;
item.vanishTime = (settings.speed * item.time + paddingLeft) / settings.speed;
});
logTrace('Computed roll Parameters.');
} catch (error) {
logTrace('ERROR: Computing roll Parameters Faild: ' + error);
return -1;
}
youTyping.zeroTime = now;
screen.update();
screen.hitCircle = new paper.Path.Circle({
center: paper.view.bounds.bottomRight.multiply([
settings.hitPosition,
settings.rollYpos
]),
radius: settings.noteSize,
strokeWidth: 1,
strokeColor: 'white'
});
screen.nextLyric.content = youTyping.nextLyricIndex !== null
? youTyping.roll[youTyping.nextLyricIndex].text
: '';
};
this.onGameReady = function () {
screen.pressEnter = new paper.PointText({
point: paper.view.bounds.bottomRight.multiply([0.5, 0.8]),
content: 'Press enter or click here.',
justification: 'center',
fontSize: 45,
fillColor: 'white'
});
var triggerStartScreen = function (event) {
if ((event.type === 'keydown' && event.key === 'enter')
|| event.type === 'mousedown') {
screen.pressEnter.remove();
paper.tool.onKeyDown = null; // unbind
screen.start();
}
};
paper.tool.onKeyDown = triggerStartScreen;
screen.pressEnter.onMouseDown = triggerStartScreen;
logTrace('Game is Ready.');
};
this.start = function () {
logTrace('Starting game.');
// register onFrame event
paper.view.onFrame = screen.onFrame;
youTyping.play();
paper.tool.onKeyDown = triggerHitNote;
};
var triggerHitNote = function (event) {
if (event.type === 'keydown' && event.key === 'escape') {
event.preventDefault();
screen.reset();
}
if (youTyping.player.getPlayerState() === 1 && event.type === 'keydown') {
// suspend default operation on browser by keydown
event.preventDefault();
youTyping.hit(event.key);
}
};
this.reset = function () {
youTyping.reset();
// remove all items
for (var item in screen.items) {
if (screen.items.hasOwnProperty(item)) {
screen.items[item].remove();
}
}
screen.items = {};
screen.hitCircle.remove();
screen.onResourceReady();
// trigger onGameReady
screen.onGameReady();
};
// layout notes and lines fitting to current time
this.update = function () {
var items = screen.items;
var now = youTyping.now;
var runTime = now - youTyping.zeroTime;
youTyping.roll.forEach(function (item, index) {
// X position of the item
var position = (item.time - runTime) * settings.speed
+ settings.width * settings.hitPosition;
// if index-th item doesn't exists in screen
if (!(index in items)) {
if (item.emergeTime <= runTime && runTime <= item.vanishTime) {
// create item
items[index] = new paper.Group();
// long line which devides roll to measures
if (item.type === youTyping.itemType.LONGLINE) {
items[index].longLine = items[index].addChild(new paper.Path.Line({
from: [
position,
settings.rollYpos * settings.height - settings.longLineHeight / 2
],
to: [
position,
settings.rollYpos * settings.height + settings.longLineHeight / 2
],
strokeColor: 'white',
strokeWidth: 2
}));
}
// small line
if (item.type === youTyping.itemType.LINE) {
items[index].smallLine = items[index].addChild(new paper.Path.Line({
from: [
position,
settings.rollYpos * settings.height - settings.lineHeight / 2
],
to: [
position,
settings.rollYpos * settings.height + settings.lineHeight / 2
],
strokeColor: 'white',
strokeWidth: 1
}));
}
if (item.type === youTyping.itemType.NOTE) {
// note
items[index].note = items[index].addChild(new paper.Path.Circle({
center: [position, settings.rollYpos * settings.height],
radius: settings.noteSize,
strokeWidth: 1,
strokeColor: 'white'
}));
// lyric
items[index].lyric = items[index].addChild(new paper.PointText({
point: [
position,
settings.rollYpos * settings.height + settings.noteSize + 50
],
content: item.remainingText,
fillColor: 'white',
justification: 'center',
fontSize: settings.lyricSize,
fontFamily: 'sans-serif'
}));
// romaji
if (screen.settings.romaji) {
items[index].romaji = items[index].addChild(new paper.PointText({
point: [
position,
settings.rollYpos * settings.height + settings.noteSize + 80
],
content: item.remainingRomaji,
fillColor: 'white',
justification: 'center',
fontSize: settings.lyricSize,
fontFamily: 'sans-serif'
}));
items[index].mercy = items[index].addChild(new paper.PointText({
point: [
position,
settings.rollYpos * settings.height + settings.noteSize + 110
],
content: item.mercy ? item.mercy : '',
fillColor: 'white',
justification: 'center',
fontSize: settings.lyricSize,
fontFamily: 'sans-serif'
}));
}
}
// order stop mark
if (item.type === youTyping.itemType.STOP) {
items[index].orderStop = items[index].addChild(new paper.Path({
segments: [
[
position,
settings.rollYpos * settings.height - settings.noteSize - 30
]
],
fillColor: 'white'
}));
items[index].orderStop.lineBy([10, -10]);
items[index].orderStop.lineBy([-20, 0]);
items[index].orderStop.closed = true;
}
} else {
return;
}
} else { // if index-th item exists in screen
if (runTime < item.emergeTime || item.vanishTime < runTime) {
items[index].remove();
delete items[index];
return;
}
}
// update item style
if (item.type === youTyping.itemType.LONGLINE) {
items[index].position.x = position;
}
if (item.type === youTyping.itemType.LINE) {
items[index].position.x = position;
}
if (item.type === youTyping.itemType.STOP) {
items[index].position.x = position;
}
if (item.type === youTyping.itemType.NOTE) {
items[index].position.x = position;
if (item.state === youTyping.noteState.CLEARED) {
items[index].visible = false;
} else {
var fillColor;
switch (item.state) {
case youTyping.noteState.WAITING:
case youTyping.noteState.HITTING:
fillColor = item.mercy ? 'orange' : 'red'; break;
default:
fillColor = '#aaa'; break;
}
// note
items[index].note.style = {
fillColor: fillColor
};
items[index].note.opacity = (
item.state === youTyping.noteState.FAILED
|| item.state === youTyping.noteState.WAITING
) ? 1 : 0.5;
// lyric
items[index].lyric.content = item.remainingText;
// romaji
if (screen.settings.romaji) {
items[index].romaji.content = item.remainingRomaji;
}
}
}
});
};
this.onFrame = function (event) {
var kanaLyric;
if (youTyping.player.getPlayerState() === 1) {
screen.update();
}
screen.debugTexts[1].content = 'Measured Zero: ' + youTyping.estimatedZero.toFixed(2);
screen.debugTexts[3].content = 'Active Objects: ' + paper.project.activeLayer.children.length;
screen.debugTexts[4].content = 'Zero Time: ' + youTyping.zeroTime.toFixed(2);
screen.debugTexts[5].content = 'Time: ' + youTyping.time.toFixed(2);
screen.bufferText.content = youTyping.inputBuffer;
screen.scorePad += (youTyping.score - screen.scorePad) * 0.5;
screen.scoreText.content = Math.round(screen.scorePad);
// screen.kanaLyric.content = (kanaLyric = youTyping.getKanaLyric()) ? kanaLyric : '';
screen.judgeEffects.children.forEach(function (judgeEffect) {
judgeEffect.controller.onFrame();
});
FPS++;
};
var hideCursorId = null;
// YouTube onStateChange event supplied from YouTyping
this.onPlayerStateChange = function (event) {
// hide mouse cursor when playing
if (event.data === YT.PlayerState.PLAYING) {
paper.tool.onMouseMove = function () {
$(screen.DOM.screen).css({
cursor: 'auto'
});
clearTimeout(hideCursorId);
hideCursorId = setTimeout(function () {
$(screen.DOM.screen).css({
cursor: 'none'
});
}, settings.cursorHideTime);
};
} else {
$(screen.DOM.screen).css({
cursor: 'auto'
});
clearTimeout(hideCursorId);
paper.tool.onMouseMove = null;
}
};
this.onJudgement = function (event) {
var judgeEffect = new JudgeEffect(event.judgement);
judgeEffect.item.controller = judgeEffect;
screen.judgeEffects.addChild(judgeEffect.item);
};
// judge effect object
var JudgeEffect = function (judgement) {
var judgeEffect = this;
this.bornTime = new Date();
this.item = new paper.Group();
this.judgeColor = settings.judgeColors[judgement.judge];
this.judge = this.item.addChild(new paper.PointText({
point: screen.hitCircle.position.add([0, -settings.noteSize - 24]),
content: judgement.judge,
fillColor: this.judgeColor,
justification: 'center',
fontSize: 24,
fontFamily: 'sans-serif'
}));
this.combo = this.item.addChild(new paper.PointText({
point: screen.hitCircle.position.add([0, -settings.noteSize]),
content: judgement.combo,
fillColor: 'white',
justification: 'center',
fontSize: 15,
fontFamily: 'sans-serif'
}));
this.initialPosition = this.item.position;
this.onFrame = function (event) {
this.item.position.y = this.initialPosition.y
- (new Date() - this.bornTime) * 0.2;
this.item.opacity = 1 - (new Date() - this.bornTime) * 0.001;
if (this.item.opacity < 0) {
this.item.remove();
}
};
};
this.onLyricChange = function () {
screen.currentLyric.remove();
screen.currentLyric = new paper.Group();
var totalWidth;
if (youTyping.currentLyricIndex !== null) {
var currentLyrics = youTyping.roll[youTyping.currentLyricIndex].text.split('¥|');
// sum of length from the left side of beginning of text
totalWidth = 0;
currentLyrics.forEach(function (lyric, index) {
var currentLyric = screen.currentLyric.addChild(new paper.PointText({
point: paper.view.bounds.bottomRight.multiply(
settings.currentLyricPosition).add([totalWidth, 0]),
content: lyric,
fillColor: 'white',
justification: 'left',
opacity: index % 2 === 0 ? 1.0 : 0.3,
fontSize: 36
}));
totalWidth += currentLyric.bounds.width;
});
screen.currentLyric.translate([-totalWidth / 2, 0]);
}
screen.nextLyric.remove();
screen.nextLyric = new paper.Group();
if (youTyping.nextLyricIndex !== null) {
var nextLyrics = youTyping.roll[youTyping.nextLyricIndex].text.split('¥|');
// sum of length from the left side of beginning of text
totalWidth = 0;
nextLyrics.forEach(function (lyric, index) {
var nextLyric = screen.nextLyric.addChild(new paper.PointText({
point: paper.view.bounds.bottomRight.multiply(
settings.nextLyricPosition).add([totalWidth, 0]),
content: lyric,
fillColor: 'white',
justification: 'left',
opacity: index % 2 === 0 ? 1.0 : 0.3,
fontSize: 18
}));
totalWidth += nextLyric.bounds.width;
});
screen.nextLyric.translate([-totalWidth / 2, 0]);
}
};
this.onGameEnd = function () {
logTrace('Game Ended.');
// unbind keys
paper.tool.onKeyDown = null;
if (screen.highScore < youTyping.score) {
screen.highScore = youTyping.score;
screen.newRecord = true;
}
screen.resultCover = new paper.Path.Rectangle(paper.view.bounds);
screen.resultCover.fillColor = '#ddd';
screen.resultCover.fillColor.alpha = 0;
screen.resultCover.onFrame = function (event) {
this.fillColor.alpha += 0.01;
if (this.fillColor.alpha >= 1) {
screen.resultCover.onFrame = null;
showResult();
}
};
screen.settings.onGameEnd.call(screen);
};
var showResult = function () {
var screenSize = paper.view.bounds.bottomRight;
screen.result = [];
screen.result.push(new paper.PointText({
point: screenSize.multiply([0.2, 0]).add([0, 100]),
content: 'Result:',
fillColor: 'black',
justification: 'left',
fontSize: 48,
fontFamily: 'sans-serif'
}));
[
'perfect',
'great',
'good',
'bad',
'failed',
'neglect'
].forEach(function (judgement, index) {
var color = new paper.Color(settings.judgeColors[judgement]);
color.brightness -= 0.3;
color.saturation += 0.2;
var content = 0;
if (judgement === 'neglect') {
content = youTyping.scorebook.neglect;
} else if (judgement === 'failed') {
for (var score in youTyping.scorebook.failed) {
if (youTyping.scorebook.failed.hasOwnProperty(score)) {
content += youTyping.scorebook.failed[score];
}
}
} else {
content = youTyping.scorebook.cleared[judgement];
}
screen.result.push(new paper.PointText({
point: screenSize.multiply([0.2, 0]).add([0, 40 * index + 180]),
content: judgement + ': ' + content,
fillColor: color,
justification: 'left',
fontSize: 36,
fontFamily: 'sans-serif'
}));
});
screen.result.push(new paper.PointText({
point: screenSize.multiply([0.2, 0]).add([0, 450]),
content: 'Max Combo: ' + youTyping.maxCombo,
fillColor: 'black',
justification: 'left',
fontSize: 36,
fontFamily: 'sans-serif'
}));
screen.result.push(new paper.PointText({
point: screenSize.multiply([0.2, 0]).add([0, 500]),
content: 'Score: ' + youTyping.score,
fillColor: 'black',
justification: 'left',
fontSize: 36,
fontFamily: 'sans-serif'
}));
screen.result.push(new paper.PointText({
point: screenSize.multiply([0.2, 0]).add([0, 550]),
content: 'HighScore: ' + screen.highScore,
fillColor: 'black',
justification: 'left',
fontSize: 36,
fontFamily: 'sans-serif'
}));
};
// Initialization
// override default screen settings
for (var param in settings) {
if (settings.hasOwnProperty(param)) {
if (this.settings[param] === undefined) {
this.settings[param] = settings[param];
} else if (typeof this.settings[param] === 'number') {
this.settings[param] = parseFloat(settings[param], 10);
} else if (typeof this.settings[param] === 'string') {
this.settings[param] = settings[param];
} else if (typeof this.settings[param] === 'boolean') {
this.settings[param] = Boolean(settings[param]);
} else if (typeof this.settings[param] === 'function') {
this.settings[param] = settings[param];
} else if (typeof this.settings[param] === 'object') {
this.settings[param] = typeof settings[param] === 'object'
? settings[param]
: JSON.parse(settings[param]);
}
}
}
// override default YouTyping settings
for (param in youTypingSettings) {
if (youTypingSettings.hasOwnProperty(param)) {
if (typeof this.settings[param] !== 'undefined') {
youTypingSettings[param] = this.settings[param];
}
}
}
// shorthand
settings = this.settings;
// setup DOM
/*
* div(this.DOM.wrap)
* |-div#youtyping-player(this.DOM.player)
* \-canvas#youtyping-screen(this.DOM.screen)
*/
this.DOM = {
wrap: element.css({
width: this.settings.width + 'px',
height: this.settings.height + 'px',
margin: '0 auto',
position: 'relative',
'perspective': this.settings['3d'] ? '1000px' : '0px'
})[0],
player: $('<div/>', {
id: 'youtyping-player'
}).appendTo(element).css({
width: this.settings.width + 'px',
height: this.settings.height + 'px',
display: 'block',
'z-index': 0,
'transform': this.settings['3d']
? 'rotateY(-30deg) scale(0.8) translateX(-100px)'
: ''
})[0],
screen: $('<canvas/>', {
id: 'youtyping-screen',
'data-paper-keepalive': 'true',
width: this.settings.width.toString(),
height: this.settings.height.toString()
}).appendTo(element).css({
width: this.settings.width + 'px',
height: this.settings.height + 'px',
position: 'absolute',
top: 0,
left: 0,
'z-index': 100
})[0]
};
this.canvas = this.DOM.screen;
youTypingSettings.width = this.settings.width;
youTypingSettings.height = this.settings.height;
this.youTyping = new YouTyping(this.DOM.player, youTypingSettings);
var youTyping = this.youTyping; // just a shorthand
// apply event listeners
youTyping.addEventListener('resourceready', screen.onResourceReady);
youTyping.addEventListener('gameready', screen.onGameReady);
youTyping.addEventListener('playerstatechange', screen.onPlayerStateChange);
youTyping.addEventListener('judgement', screen.onJudgement);
youTyping.addEventListener('gameend', screen.onGameEnd);
youTyping.addEventListener('lyricchange', screen.onLyricChange);
this.initialize();
};
|
// tracknewcomments.js
// Copyright (c) 2017 Miles Bright, MIT License
// https://github.com/smilesbright/onewordeachbot
'use strict';
const snoowrap = require('snoowrap');
const jsonfile = require('jsonfile');
const requestParameters = {
client_id: process.env.CLIENTID,
client_secret: process.env.CLIENTSECRET,
username: process.env.USERNAME,
password: process.env.PASSWORD,
user_agent: process.env.USERAGENT
};
const request = new snoowrap(requestParameters);
//
// This method checks text for punctuation that ends a sentence.
//
function hasPunctuation(text) {
while (text[text.length - 1] === ' ') {
text = text.slice(0, text.length - 1);
}
var c = text[text.length - 1];
if (c == '.' || c == '?' || c == '!') {
return true;
}
else {
return false;
}
}
//
// This script requests new comments from /r/onewordeach and adds comments with
// punctuation to comments.json data storage file to be tracked.
//
jsonfile.readFile('./comments.json', function(err, obj) {
request.getNewComments('onewordeach').then(function(newComments) {
// go through the list of new comments
newComments.forEach(function(newComment) {
// if comment has a punctuation
if (hasPunctuation(newComment.body)) {
// if it's not already in comments list
var hasBeenAdded = 0;
obj.comments.forEach(function(commentListing) {
if (commentListing.id == newComment.id) {
hasBeenAdded = 1;
}
});
if (hasBeenAdded == 0) {
// and if its thread doesn't already have a comment from bot
var addNewComment = true;
for (var j=0; j < obj.comments.length; j++) {
if (obj.comments[j].thread == newComment.link_id && obj.comments[j].hasposted == 1) {
addNewComment = false;
}
//console.log(obj.comments[j].thread);
}
if (addNewComment == true) {
// add new comment to list.
var newComment = {id: newComment.id, thread: newComment.link_id,
hasposted: 0, daysOld: 0, score: newComment.score};
obj.comments.push(newComment);
jsonfile.writeFile('./comments.json', obj); // < completely rewrites entire json file.
}
}
}
});
});
});
|
/*!
* SeaUI: transition.js v1.0.0
* Copyright 2013-2014 chanh
* Licensed under MIT(https://github.com/seaui/transition/blob/master/LICENSE)
*/
define("seaui/transition/1.0.0/transition",["jquery/jquery/1.10.1/jquery"],function(a){function b(){var a=document.createElement("bootstrap"),b={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"};for(var c in b)if(void 0!==a.style[c])return{end:b[c]};return!1}var c=a("jquery/jquery/1.10.1/jquery");c.fn.emulateTransitionEnd=function(a){var b=!1,d=this;c(this).one(c.support.transition.end,function(){b=!0});var e=function(){b||c(d).trigger(c.support.transition.end)};return setTimeout(e,a),this},c(function(){c.support.transition=b()})});
|
'use strict';
(function(){
var camera, scene, renderer;
var projector;
setup();
function setup(){
setupCanvas();
setupScene();
requestAnimationFrame(function animate(){
renderer.render(scene, camera);
requestAnimationFrame(animate);
});
}
function setupCanvas(){
camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 10000);
camera.position.y = 10;
camera.position.z = 800;
scene = new THREE.Scene();
renderer = new THREE.WebGLRenderer({
antialias: true
});
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// Set up user click events
projector = new THREE.Projector();
renderer.domElement.addEventListener('mousedown', function(event){
var vector = new THREE.Vector3(
renderer.devicePixelRatio * (event.pageX - this.offsetLeft) / this.width * 2 - 1,
-renderer.devicePixelRatio * (event.pageY - this.offsetTop) / this.height * 2 + 1,
0
);
projector.unprojectVector(vector, camera);
var raycaster = new THREE.Raycaster(
camera.position,
vector.sub(camera.position).normalize()
);
var intersects = raycaster.intersectObjects(scene.children);
intersects[0].object.material.color.set(0xff0000);
intersects[0].object.position.y = 0;
}, false);
}
function setupScene(){
var light = new THREE.DirectionalLight(0xffffff, 1);
light.position.set(1, 1, 1).normalize();
scene.add(light);
// Cube model
var geometry = new THREE.IcosahedronGeometry(100, 2);
for (var i = 0; i < 20; i++) {
var cube = new THREE.Mesh(geometry, new THREE.MeshLambertMaterial({
color: Math.random() * 0xffffff,
wireframe: true,
wireframeLinewidth: 3
}));
cube.position.x = Math.floor(Math.random() * 200 - 100) * 4;
cube.position.y = Math.floor(Math.random() * 200 - 100) * 4;
cube.position.z = Math.floor(Math.random() * 200 - 100) * 4;
scene.add(cube);
}
}
})();
|
const shell = require('shelljs');
const path = require('path');
console.log('Patch react-devtools-core');
const rdStandalone = path.join(
__dirname,
'../dist/node_modules/react-devtools-core/dist/standalone.js'
);
// Avoid logging from react-devtools-core
// log: connected, disconnected
// error: listening error (can be seen directly in the panel)
shell.sed(
'-i',
// eslint-disable-next-line
/\(_console[0-9]* = console\).(log|warn|error).apply\(_console[0-9]*, \[ "\[React DevTools\]" \].concat\(args\)\)/,
'',
rdStandalone
);
console.log('Patch react-dev-utils/launchEditor');
shell.sed(
'-i',
/require\('chalk'\)/g,
'{red:f=>f,cyan:f=>f,green:f=>f}',
path.join(__dirname, '../node_modules/react-dev-utils/launchEditor.js')
);
|
'use strict';
describe('Controller: AboutCtrl', function () {
// load the controller's module
beforeEach(module('angularWeatherApp'));
var AboutCtrl,
scope;
// Initialize the controller and a mock scope
beforeEach(inject(function ($controller, $rootScope) {
scope = $rootScope.$new();
AboutCtrl = $controller('AboutCtrl', {
$scope: scope
});
}));
it('should attach a list of awesomeThings to the scope', function () {
expect(scope.awesomeThings.length).toBe(3);
});
});
|
var memory__heap__arbitrary_8cpp =
[
[ "hryky_empty", "memory__heap__arbitrary_8cpp.html#a6c8720dea12e6fd18764e6f527183950", null ],
[ "hryky_explicit_instantiation", "memory__heap__arbitrary_8cpp.html#a5faec7b8f35865e03cfca1e00a47e4ef", null ],
[ "hryky::memory::heap::reduce< hryky::uint16_t >", "memory__heap__arbitrary_8cpp.html#a47c34025dbc255b538c8a0a8d1423a58", null ],
[ "hryky::memory::heap::reduce< hryky::uint32_t >", "memory__heap__arbitrary_8cpp.html#a929eee2dbd173ed48a5bb0dddad0d843", null ],
[ "hryky::memory::heap::reduce< hryky::uint64_t >", "memory__heap__arbitrary_8cpp.html#abfb8b5f33bb6a84949484c3dbb8a8725", null ],
[ "hryky::memory::heap::reduce< hryky::uint8_t >", "memory__heap__arbitrary_8cpp.html#a9c941662cddf37788d3f550479898ffa", null ],
[ "hryky_explicit_instantiation", "memory__heap__arbitrary_8cpp.html#a23202a80cef1a0bda2dd36b6be442853", null ],
[ "hryky_explicit_instantiation", "memory__heap__arbitrary_8cpp.html#a5e34987f190bf444032ccb1ec699cbc9", null ],
[ "hryky_explicit_instantiation", "memory__heap__arbitrary_8cpp.html#a23a0daea43b8d002833bdc4c661a255f", null ],
[ "hryky_explicit_instantiation", "memory__heap__arbitrary_8cpp.html#a580444ddfb9433f813269e7330c46128", null ],
[ "hryky_explicit_instantiation", "memory__heap__arbitrary_8cpp.html#a127dedcd1da08907e7e765fe04a09f4a", null ],
[ "hryky_explicit_instantiation", "memory__heap__arbitrary_8cpp.html#ad9197cf61ace63482ec989b6b87e436a", null ],
[ "hryky_explicit_instantiation", "memory__heap__arbitrary_8cpp.html#a240a7ed9f1239baae0ed6df3ea8a7756", null ],
[ "hryky_explicit_instantiation", "memory__heap__arbitrary_8cpp.html#af7c114b09f51a312c667ee39de67d7a3", null ],
[ "hryky_explicit_instantiation", "memory__heap__arbitrary_8cpp.html#a4768de9caac5862ce0d3b01a9cb506da", null ],
[ "hryky_explicit_instantiation", "memory__heap__arbitrary_8cpp.html#ae796124832326ac4e5e9b1dbd526e464", null ],
[ "hryky_explicit_instantiation", "memory__heap__arbitrary_8cpp.html#aa5b497a0d063db8bfbb0432cde35a114", null ],
[ "hryky_explicit_instantiation", "memory__heap__arbitrary_8cpp.html#ac092737eec52f162ad1c81bcd8de2ce6", null ],
[ "hryky_explicit_instantiation", "memory__heap__arbitrary_8cpp.html#a34e84f903b87abbb789db0e05c446f18", null ],
[ "hryky_explicit_instantiation", "memory__heap__arbitrary_8cpp.html#ae40c523851f07ae3152e342ff6ae17ba", null ],
[ "hryky_explicit_instantiation", "memory__heap__arbitrary_8cpp.html#a4f8fdfccb172be1a6bf51288f99b5b79", null ]
];
|
var sage = require('../../../build/sage');
var Schema = sage.Schema;
var UserSchema = new Schema({
USER_ID: {
type: "number",
readonly: true
},
CREATED_AT: {
type: "timestamp",
readonly: true
},
USERNAME: {
type: "varchar"
},
POSTS: {
type: "association",
joinType: "hasMany",
joinsWith: "SAGE_TEST.POSTS",
foreignKeys: {
mine: "USER_ID",
theirs: "USER_ID"
},
model: "SAGE_TEST.POSTS"
},
PROFILE: {
type: "association",
joinType: "hasOne",
joinsWith: "SAGE_TEST.PROFILES",
foreignKeys: {
mine: "USER_ID",
theirs: "USER_ID"
},
model: "SAGE_TEST.PROFILES"
}
}, {
primaryKey: "USER_ID"
});
module.exports = sage.model("SAGE_TEST.USERS", UserSchema);
|
define(['views/attributes_view', 'views/attribute_view', 'views/topic_map_attribute_view'], function(AttributesView, AttributeView, TopicMapAttributeView){
var TopicHeaderView = AttributesView.extend({
ordinals: function(){
return this.model.constructor.headers;
},
items: function(){
var model = this.model;
return this.ordinals().map(function(attr){
var view;
if (attr === 'topic_map_id') {
var tm = model.client().db.topic_maps.get(model.topic_map_id());
view = new TopicMapAttributeView({model: tm, attribute: 'id'});
} else {
view = new AttributeView({model: model, attribute: attr});
}
return view;
});
}
});
return TopicHeaderView;
});
|
"use strict";
define(['backbone','model/DomoticModelMapper', 'config'],
function(Backbone, DomoticModelMapper, config) {
return Backbone.Collection.extend({
url: config.rest.domoticItems,
model: function (attrs, options) {
return new (DomoticModelMapper(attrs['@type']))(attrs, options);
},
//localStorage: new Backbone.LocalStorage('domotic-items'),
comparator: 'name',
startAutoRefresh: function(interval) {
var self = this;
this.autoRefreshID = setInterval(function() {
self.fetch();
}, interval);
},
stopAutoRefresh: function() {
clearInterval(this.autoRefreshID);
}
});
}
);
|
var express = require('express');
var router = express.Router();
var childProcess = require('child_process'),
jav;
router.get('/', function(req, res, next) {
var idModel = req.query.idModel,
predResult;
jav = childProcess.exec('java -jar C:\\Users\\AegisLabs\\irfan-db\\Dropbox\\THESIS\\c0d3\\TwitterPredictionWithSVR\\dist\\TwitterPredictionWithSVR.jar '+idModel+' jml_respon_pertahap timestamp', function (error, stdout, stderr) {
if (error) {
console.log(error.stack);
console.log('Error code: '+error.code);
console.log('Signal received: '+error.signal);
}
predResult = JSON.parse(stdout);
res.json(predResult);
});
jav.on('exit', function (code) {
console.log('Child process exited with exit code '+ code);
//res.send(predResult);
});
});
router.get('/listHashtag', function(req, res, next){
var idUser = req.query.idUser;
var UserHashtag = [
[{'id' : 999, 'label' : 'pilih tagar', 'id' : 0, 'label' : '#bebasLembab', 's' : '02:06:33', 'e': ' 02:56:33'}, {'id' : 3, 'label' : '#hostForInfinity', 's': '13:27:53', 'e': '14:17:53'}],
[{'id' : 999, 'label' : 'pilih tagar', 'id' : 1, 'label' : '#pestaKeluargaErtiga', 's': '16:48:25', 'e': '17:38:25'}],
[{'id' : 999, 'label' : 'pilih tagar', 'id' : 2, 'label' : '#jkw4p', 's' : '18:11:58', 'e' : '19:01:58'}],
[{'id' : 999, 'label' : 'pilih tagar', 'id' : 4, 'label' : '#happynest', 's' : '19:49:50', 'e' : '20:39:50'}]
]
res.json(UserHashtag[idUser]);
});
module.exports = router;
|
// generator: babel-node
// adapted from kangax's tests
var key1 = {};
var key2 = {};
var weakmap = new WeakMap([[key1, 123], [key2, 456]]);
console.log (weakmap.has(key1) && weakmap.get(key1) === 123 &&
weakmap.has(key2) && weakmap.get(key2) === 456);
|
define(['app'],function(UniversalDesignBootstrap) {
UniversalDesignBootstrap.module('Routers.WizardModule', function(WizardModuleRouter, UniversalDesignBootstrap, Backbone, Marionette, $, _) {
// Marionette uses an AppRouter to drop in Controllers. Basically is Controller.method, i.e. '': 'showWizard' = Controller.showWizard
WizardModuleRouter.Router = Marionette.AppRouter.extend({
before: function () {
App.startSubApp('WizardModule', {});
},
appRoutes:{
'': 'showStep',
'step/:stepNumber': 'showStep'
}
});
// Always check that WizardModule is started and do any necessary surrounding updates for general action execution in this module
var executeAction = function(action, arg) {
UniversalDesignBootstrap.startSubApp("WizardModule");
action(arg);
// UniversalDesignBootstrap.execute("set:active:header", "contacts");
};
// Public API for this Modules' routing
var API = {
// shows whatever step should be shown in url #step/:stepNumber
showStep: function(stepNumber){
require(['../apps/wizard/controllers/index'], function(WizardController) {
if (!stepNumber) {
stepNumber = 0;
}
UniversalDesignBootstrap.navigate('step/' + stepNumber);
executeAction(WizardController.showStep, stepNumber);
});
},
// add another model for the same collection
addAnother: function(stepNumber) {
require(['../apps/wizard/controllers/index'], function(WizardController) {
});
}
};
// Global events that can be triggered in this module
UniversalDesignBootstrap.on('WizardModule:step:showStep', function(stepNumber) {
UniversalDesignBootstrap.navigate('step/' + stepNumber);
API.showStep(stepNumber);
});
// Setup the Marionette controller
UniversalDesignBootstrap.addInitializer(function() {
new WizardModuleRouter.Router({
controller: API
});
});
});
return UniversalDesignBootstrap.WizardModuleRouter;
});
|
/**
* Backbone-tastypie.js 0.1
* (c) 2011 Paul Uithol
*
* Backbone-tastypie may be freely distributed under the MIT license.
* Add or override Backbone.js functionality, for compatibility with django-tastypie.
*/
(function( undefined ) {
"use strict";
// Backbone.noConflict support. Save local copy of Backbone object.
var Backbone = window.Backbone;
Backbone.Tastypie = {
doGetOnEmptyPostResponse: true,
doGetOnEmptyPutResponse: false,
apiKey: {
username: '',
key: ''
}
};
/**
* Override Backbone's sync function, to do a GET upon receiving a HTTP CREATED.
* This requires 2 requests to do a create, so you may want to use some other method in production.
* Modified from http://joshbohde.com/blog/backbonejs-and-django
*/
Backbone.oldSync = Backbone.sync;
Backbone.sync = function( method, model, options ) {
var headers = '';
if ( Backbone.Tastypie.apiKey && Backbone.Tastypie.apiKey.username.length ) {
headers = _.extend( {
'Authorization': 'ApiKey ' + Backbone.Tastypie.apiKey.username + ':' + Backbone.Tastypie.apiKey.key
}, options.headers );
options.headers = headers;
}
if ( ( method === 'create' && Backbone.Tastypie.doGetOnEmptyPostResponse ) ||
( method === 'update' && Backbone.Tastypie.doGetOnEmptyPutResponse ) ) {
var dfd = new $.Deferred();
// Set up 'success' handling
dfd.done( options.success );
options.success = function( resp, status, xhr ) {
// If create is successful but doesn't return a response, fire an extra GET.
// Otherwise, resolve the deferred (which triggers the original 'success' callbacks).
if ( !resp && ( xhr.status === 201 || xhr.status === 202 || xhr.status === 204 ) ) { // 201 CREATED, 202 ACCEPTED or 204 NO CONTENT; response null or empty.
var location = xhr.getResponseHeader( 'Location' ) || model.id;
return $.ajax( {
url: location,
headers: headers,
success: dfd.resolve,
error: dfd.reject
});
}
else {
return dfd.resolveWith( options.context || options, [ resp, status, xhr ] );
}
};
// Set up 'error' handling
dfd.fail( options.error );
options.error = function( xhr, status, resp ) {
dfd.rejectWith( options.context || options, [ xhr, status, resp ] );
};
// Make the request, make it accessibly by assigning it to the 'request' property on the deferred
dfd.request = Backbone.oldSync( method, model, options );
return dfd;
}
return Backbone.oldSync( method, model, options );
};
Backbone.Model.prototype.idAttribute = 'resource_uri';
Backbone.Model.prototype.url = function() {
// Use the id if possible
var url = this.id;
// If there's no idAttribute, use the 'urlRoot'. Fallback to try to have the collection construct a url.
// Explicitly add the 'id' attribute if the model has one.
if ( !url ) {
url = this.urlRoot;
url = url || this.collection && ( _.isFunction( this.collection.url ) ? this.collection.url() : this.collection.url );
if ( url && this.has( 'id' ) ) {
url = addSlash( url ) + this.get( 'id' );
}
}
url = url && addSlash( url );
return url || null;
};
/**
* Return the first entry in 'data.objects' if it exists and is an array, or else just plain 'data'.
*/
Backbone.Model.prototype.parse = function( data ) {
return data && data.objects && ( _.isArray( data.objects ) ? data.objects[ 0 ] : data.objects ) || data;
};
/**
* Return 'data.objects' if it exists.
* If present, the 'data.meta' object is assigned to the 'collection.meta' var.
*/
Backbone.Collection.prototype.parse = function( data ) {
if ( data && data.meta ) {
this.meta = data.meta;
}
return data && data.objects;
};
Backbone.Collection.prototype.url = function( models ) {
var url = this.urlRoot || ( models && models.length && models[0].urlRoot );
url = url && addSlash( url );
// Build a url to retrieve a set of models. This assume the last part of each model's idAttribute
// (set to 'resource_uri') contains the model's id.
if ( models && models.length ) {
var ids = _.map( models, function( model ) {
var parts = _.compact( model.id.split( '/' ) );
return parts[ parts.length - 1 ];
});
url += 'set/' + ids.join( ';' ) + '/';
}
return url || null;
};
var addSlash = function( str ) {
return str + ( ( str.length > 0 && str.charAt( str.length - 1 ) === '/' ) ? '' : '/' );
}
})();
|
'use strict';
angular.module( 'mmOrders', [] )
.provider( '$mmOrdersConfig', function() {
this.$get = function() {
return {
'itemFind': '/Shop/Parts/Search',
};
};
} )
.config( [
'$mmApiProvider',
function($mmApiProvider) {
$mmApiProvider.addRoute( 'website', 'shop', '/Shop' );
},
] )
.run( [
'$rootScope',
'mmOrders',
'dataStore',
function($rootScope, mmOrders, dataStore) {
$rootScope.$on( 'authentication:endSession', function(broadcastName, data) {
mmOrders.init();
$rootScope.$broadcast( 'mmOrders:change', null );
} );
$rootScope.$on( 'mmOrders:change', function() {
mmOrders.$save();
} );
if (angular.isObject( dataStore.get( 'mmOrders' ) )) {
mmOrders.$restore( dataStore.get( 'mmOrders' ) );
} else {
mmOrders.init();
}
},
] )
.directive( 'mmOrdersList', [
'mmOrders',
function(mmOrders) {
return {
restrict : 'EA',
transclude: true,
link : function(scope) {
scope.items = mmOrders.store.cart.items;
scope.cartTotalUniqueItems = function() {
return mmOrders.cartTotalUniqueItems();
};
},
};
},
] )
.service( 'mmOrders', [
'$mmOrdersConfig',
'$q',
'toasty',
'dataStore',
'$localStorage',
'mmProduct',
'$http',
'$rootScope',
'api',
function($mmOrdersConfig, $q, toasty, dataStore, $localStorage, mmProduct, $http, $rootScope, api) {
var self = this;
self.init = function() {
self.store = {
cart : {
items: [],
},
forms: [],
order: {},
};
};
$rootScope.$watch( function() {
return $localStorage.mmOrders;
}, function() {
if (angular.isObject( angular.fromJson( $localStorage.mmOrders ) )) {
var items = angular.fromJson( $localStorage.mmOrders ).cart.items;
self.store.cart.items.splice( 0, self.store.cart.items.length );
angular.forEach( items, function(item) {
self.store.cart.items.push( new mmProduct( item ) );
} );
}
}, true );
self.itemGet = function(item) {
var deferred = $q.defer();
api.get( 'website', 'parts', item ).then( function(response) {
deferred.resolve( new mmProduct( response.data.data.part ) );
} ).catch( function(response) {
deferred.reject( response.data.data );
} );
return deferred.promise;
};
self.itemFind = function(itemQuery) {
var deferred = $q.defer();
$http.post( $mmOrdersConfig.itemFind, {search: itemQuery} ).then( function(response) {
deferred.resolve( response.data.data.items );
} ).catch( function(response) {
deferred.reject( response.data.data.items );
} );
return deferred.promise;
};
},
] ).value( 'version', '0.0.1' );
|
Session.setDefault('showGame', 'false');
UI.body.helpers({
showGame: function (state) {
return Session.equals('showGame', state);
}
});
|
var Service, Characteristic;
var apcUps = require("./snmp.js");
var ipaddress = require("./ipaddress");
var ups = new apcUps(ipaddress);
const DEF_MIN_TEMPERATURE = -100,
DEF_MAX_TEMPERATURE = 100,
DEF_TIMEOUT = 5000;
module.exports = function(homebridge) {
Service = homebridge.hap.Service;
Characteristic = homebridge.hap.Characteristic;
homebridge.registerAccessory("homebridge-apc-snmp", "APC", APCAccessory);
}
function APCAccessory(log, config) {
this.log = log;
this.name = config["name"];
this.location = config["location"];
this.model = config["model"] || "Model not available";
this.serial = config["serial"] || "Non-defined serial";
this.minTemperature = config["min_temp"] || DEF_MIN_TEMPERATURE;
this.maxTemperature = config["max_temp"] || DEF_MAX_TEMPERATURE;
this.temperature = 0.0;
this.service = "Temperature Sensor";
}
APCAccessory.prototype = {
getState: function(callback) {
ups.getTemperature(function(error,temperature) {
console.log('The current temperature is:', temperature, 'C');
console.dir();
return(null,temperature);
}).bind(this)},
identify: function(callback) {
this.log("Identify requested!");
callback(); // success
},
getServices: function () {
var informationService = new Service.AccessoryInformation();
informationService
.setCharacteristic(Characteristic.Manufacturer, this.manufacturer)
.setCharacteristic(Characteristic.Model, this.model)
.setCharacteristic(Characteristic.SerialNumber, this.serial);
if (this.service == "Temperature Sensor") {
temperatureService = new Service.TemperatureSensor("Room Temperature");
temperatureService
.getCharacteristic(Characteristic.CurrentTemperature)
.on('get', this.getState.bind(this));
return [informationService, temperatureService];
}
}
};
|
'use strict';
System.register(['aurelia-pal', './aurelia-plugins-cookie-consent-config'], function (_export, _context) {
"use strict";
var PLATFORM, Config;
function configure(aurelia, configCallback) {
var instance = aurelia.container.get(Config);
if (configCallback !== undefined && typeof configCallback === 'function') configCallback(instance);
aurelia.globalResources([PLATFORM.moduleName('./aurelia-plugins-cookie-consent-element')]);
}
_export('configure', configure);
return {
setters: [function (_aureliaPal) {
PLATFORM = _aureliaPal.PLATFORM;
}, function (_aureliaPluginsCookieConsentConfig) {
Config = _aureliaPluginsCookieConsentConfig.Config;
}],
execute: function () {}
};
});
|
"use strict";
function render() {
return React.createElement("div", {className: 'component'}, React.createElement("div", {className: 'component__title'}, "Title"), React.createElement("div", {className: 'component__footer'}, "Title"));
}
|
let errorConstructors = {};
function generateErrorConstructor(options) {
function F(message) {
this.message = message || options.message;
this.code = options.code;
this.status = options.status;
this.name = options.name;
};
F.prototype = Error.prototype;
Object.defineProperty(F, 'name', {
value: options.name,
writable: false
});
errorConstructors[options.name] = F;
}
const definitions = [
{
name: 'LoginValidationError',
message: 'Login validation failed.',
code: 100,
status: 400
},
{
name: 'LoginNotFoundError',
message: 'A record could not be found with the credentials provided.',
code: 101,
status: 404
},
{
name: 'RegistrationValidationError',
message: 'Registration validation failed.',
code: 102,
status: 400
},
{
name: 'ForgottenPasswordValidationError',
message: 'Forgotten password validation failed.',
code: 104,
status: 400
},
{
name: 'ResetPasswordTokenValidationError',
message: 'The reset password token is invalid or has expired.',
code: 106,
status: 400
},
{
name: 'ResetPasswordValidationError',
message: 'Reset password validation failed.',
code: 107,
status: 400
},
{
name: 'EmailVerificationTokenValidationError',
message: 'The email address verification token is invalid or has expired.',
code: 109,
status: 400
},
{
name: 'UserNotFoundError',
message: 'User not found.',
code: 200,
status: 404
},
{
name: 'UserValidationError',
message: 'User validation failed.',
code: 201,
status: 400
},
{
name: 'UserPermissionError',
message: 'Permission denied to access user.',
code: 202,
status: 403
},
{
name: 'WishListNotFoundError',
message: 'Wish list not found.',
code: 300,
status: 404
},
{
name: 'WishListValidationError',
message: 'Wish list validation failed.',
code: 301,
status: 400
},
{
name: 'WishListPermissionError',
message: 'Permission denied to access wish list.',
code: 302,
status: 403
},
{
name: 'GiftNotFoundError',
message: 'Gift not found.',
code: 400,
status: 404
},
{
name: 'GiftValidationError',
message: 'Gift validation failed.',
code: 401,
status: 400
},
{
name: 'GiftPermissionError',
message: 'Permission denied to access gift.',
code: 402,
status: 403
},
{
name: 'CommentNotFoundError',
message: 'Comment not found.',
code: 500,
status: 404
},
{
name: 'CommentValidationError',
message: 'Comment validation failed.',
code: 501,
status: 400
},
{
name: 'CommentPermissionError',
message: 'Permission denied to access comment.',
code: 502,
status: 403
},
{
name: 'DibNotFoundError',
message: 'Dib not found.',
code: 600,
status: 404
},
{
name: 'DibValidationError',
message: 'Dib validation failed.',
code: 601,
status: 400
},
{
name: 'DibPermissionError',
message: 'Permission denied to access dib.',
code: 602,
status: 403
},
{
name: 'FriendshipNotFoundError',
message: 'Friendship not found.',
code: 700,
status: 404
},
{
name: 'FriendshipValidationError',
message: 'Friendship validation failed.',
code: 701,
status: 400
},
{
name: 'FriendshipPermissionError',
message: 'Permission denied to access friendship.',
code: 702,
status: 403
},
{
name: 'NotificationNotFoundError',
message: 'Notification not found.',
code: 800,
status: 404
},
{
name: 'NotificationValidationError',
message: 'Notification validation failed.',
code: 801,
status: 400
},
{
name: 'NotificationPermissionError',
message: 'Permission denied to access notification.',
code: 802,
status: 403
},
{
name: 'FeedbackValidationError',
message: 'Feedback validation failed.',
code: 901,
status: 400
}
];
definitions.forEach((definition) => {
generateErrorConstructor(definition);
});
module.exports = errorConstructors;
|
import React from 'react';
import { SubmitButton } from '../form-fields/submit-button.js';
export class CardSizeButton extends React.Component {
constructor(props) {
super(props);
this.updateSize = this.updateSize.bind(this);
};
updateCardSize(size) {
var cards = document.querySelector('.spell-card-container');
cards.setAttribute("data-card-size", size);
}
updateSize(e) {
let size = e.target.innerHTML;
let active = document.querySelector(".size-buttons .btn.active");
let buttons = document.querySelectorAll(".size-buttons");
if (e.target.className.indexOf("active") > -1) {
e.target.className = "btn";
size = "";
} else if (active) {
active.className = active.className.replace(/active/g,"");
e.target.className += " active";
} else {
e.target.className += " active";
}
this.updateCardSize(size);
}
render() {
return <div className="size-buttons">
<SubmitButton cssClass="sm" label="sm" onUpdate={this.updateSize} />
<SubmitButton cssClass="md" label="md" onUpdate={this.updateSize} />
<SubmitButton cssClass="lg" label="lg" onUpdate={this.updateSize} />
<SubmitButton cssClass="xl" label="xl" onUpdate={this.updateSize} />
</div>
}
}
|
'use strict';
var gulp = require('gulp');
var browserSync = require('browser-sync');
var runSequence = require('run-sequence');
gulp.task('reload', function() {
// runSequence('styles', 'ie8styles', 'ie7styles', 'views', 'images', 'js','scripts','copyfonts', 'watch',function(){
// });
console.log('reloading **************************************');
browserSync.reload();
});
|
import verifyAndAssertMessages from "../../helpers/verifyAndAssertMessages";
describe("verify", () => {
it("arrow function support (issue #1)", () => {
verifyAndAssertMessages("describe('stuff', () => {});");
});
it("EOL validation (issue #2)", () => {
verifyAndAssertMessages(
'module.exports = "something";',
{ "eol-last": 1, semi: 1 },
["1:30 Newline required at end of file but not found. eol-last"],
);
});
it("Readable error messages (issue #3)", () => {
verifyAndAssertMessages("{ , res }", {}, [
/1:2 Parsing error:.*Unexpected token \(1:2\)/,
]);
});
it("Modules support (issue #5)", () => {
verifyAndAssertMessages(
`
import Foo from 'foo';
export default Foo;
export const c = 'c';
export class Store {}
`,
);
});
it("Rest parameters (issue #7)", () => {
verifyAndAssertMessages("function foo(...args) { return args; }", {
"no-undef": 1,
});
});
it("Exported classes should be used (issue #8)", () => {
verifyAndAssertMessages("class Foo {} module.exports = Foo;", {
"no-unused-vars": 1,
});
});
it("super keyword in class (issue #10)", () => {
verifyAndAssertMessages("class Foo { constructor() { super() } }", {
"no-undef": 1,
});
});
it("Rest parameter in destructuring assignment (issue #11)", () => {
verifyAndAssertMessages(
"const [a, ...rest] = ['1', '2', '3']; module.exports = rest;",
{ "no-undef": 1 },
);
});
it("JSX attribute names marked as variables (issue #12)", () => {
verifyAndAssertMessages('module.exports = <div className="foo" />', {
"no-undef": 1,
});
});
it("Multiple destructured assignment with compound properties (issue #16)", () => {
verifyAndAssertMessages("module.exports = { ...a.a, ...a.b };", {
"no-dupe-keys": 1,
});
});
it("Arrow function with non-block bodies (issue #20)", () => {
verifyAndAssertMessages(
'"use strict"; () => 1',
{ strict: [1, "global"] },
[],
"script",
{ sourceType: "script" },
);
});
it("#242", () => {
verifyAndAssertMessages('"use strict"; asdf;', {
"no-irregular-whitespace": 1,
});
});
it("await keyword (issue #22)", () => {
verifyAndAssertMessages("async function foo() { await bar(); }", {
"no-unused-expressions": 1,
});
});
it("arrow functions (issue #27)", () => {
verifyAndAssertMessages("[1, 2, 3].map(i => i * 2);", {
"func-names": 1,
"space-before-blocks": 1,
});
});
it("comment with padded-blocks (issue #33)", () => {
verifyAndAssertMessages(
`
if (a) {
// i'm a comment!
let b = c
}
`,
{ "padded-blocks": [1, "never"] },
);
});
describe("flow", () => {
it("check regular function", () => {
verifyAndAssertMessages(
"function a(b, c) { b += 1; c += 1; return b + c; } a;",
{ "no-unused-vars": 1, "no-undef": 1 },
);
});
it("type alias", () => {
verifyAndAssertMessages("type SomeNewType = any;", { "no-undef": 1 });
});
it("type cast expression #102", () => {
verifyAndAssertMessages("for (let a of (a: Array)) {}");
});
it("multiple nullable type annotations and return #108", () => {
verifyAndAssertMessages(
`
import type Foo from 'foo';
import type Foo2 from 'foo';
import type Foo3 from 'foo';
function log(foo: ?Foo, foo2: ?Foo2): ?Foo3 {
console.log(foo, foo2);
}
log(1, 2);
`,
{ "no-unused-vars": 1, "no-undef": 1 },
);
});
it("interface declaration", () => {
verifyAndAssertMessages(
`
interface Foo {};
interface Bar {
foo: Foo,
};
`,
{ "no-unused-vars": 1, "no-undef": 1 },
["2:11 'Bar' is defined but never used. no-unused-vars"],
);
});
it("type parameter bounds (classes)", () => {
verifyAndAssertMessages(
`
import type {Foo, Foo2} from 'foo';
import Base from 'base';
class Log<T1: Foo, T2: Foo2, T3, T4> extends Base<T3> {
messages: {[T1]: T2};
}
new Log();
`,
{ "no-unused-vars": 1, "no-undef": 1 },
["3:34 'T4' is defined but never used. no-unused-vars"],
);
});
it("type parameter scope (classes)", () => {
verifyAndAssertMessages(
`
T;
class Foo<T> {}
T;
new Foo();
`,
{ "no-unused-vars": 1, "no-undef": 1 },
[
"1:1 'T' is not defined. no-undef",
"2:11 'T' is defined but never used. no-unused-vars",
"3:1 'T' is not defined. no-undef",
],
);
});
it("type parameter bounds (interfaces)", () => {
verifyAndAssertMessages(
`
import type {Foo, Foo2, Bar} from '';
interface Log<T1: Foo, T2: Foo2, T3, T4> extends Bar<T3> {
messages: {[T1]: T2};
}
`,
{ "no-unused-vars": 1, "no-undef": 1 },
[
"2:11 'Log' is defined but never used. no-unused-vars",
"2:38 'T4' is defined but never used. no-unused-vars",
],
);
});
it("type parameter scope (interfaces)", () => {
verifyAndAssertMessages(
`
T;
interface Foo<T> {};
T;
Foo;
`,
{ "no-unused-vars": 1, "no-undef": 1 },
[
"1:1 'T' is not defined. no-undef",
"2:15 'T' is defined but never used. no-unused-vars",
"3:1 'T' is not defined. no-undef",
],
);
});
it("type parameter bounds (type aliases)", () => {
verifyAndAssertMessages(
`
import type {Foo, Foo2, Foo3} from 'foo';
type Log<T1: Foo, T2: Foo2, T3> = {
messages: {[T1]: T2};
delay: Foo3;
};
`,
{ "no-unused-vars": 1, "no-undef": 1 },
[
"2:6 'Log' is defined but never used. no-unused-vars",
"2:29 'T3' is defined but never used. no-unused-vars",
],
);
});
it("type parameter scope (type aliases)", () => {
verifyAndAssertMessages(
`
T;
type Foo<T> = {};
T;
Foo;
`,
{ "no-unused-vars": 1, "no-undef": 1 },
[
"1:1 'T' is not defined. no-undef",
"2:10 'T' is defined but never used. no-unused-vars",
"3:1 'T' is not defined. no-undef",
],
);
});
it("type parameter bounds (functions)", () => {
verifyAndAssertMessages(
`
import type Foo from 'foo';
import type Foo2 from 'foo';
function log<T1: Foo, T2: Foo2, T3, T4>(a: T1, b: T2): T3 { return a + b; }
log(1, 2);
`,
{ "no-unused-vars": 1, "no-undef": 1 },
["3:37 'T4' is defined but never used. no-unused-vars"],
);
});
it("type parameter scope (functions)", () => {
verifyAndAssertMessages(
`
T;
function log<T>() {}
T;
log;
`,
{ "no-unused-vars": 1, "no-undef": 1 },
[
"1:1 'T' is not defined. no-undef",
"2:14 'T' is defined but never used. no-unused-vars",
"3:1 'T' is not defined. no-undef",
],
);
});
it("nested type annotations", () => {
verifyAndAssertMessages(
`
import type Foo from 'foo';
function foo(callback: () => Foo) {
return callback();
}
foo();
`,
{ "no-unused-vars": 1, "no-undef": 1 },
);
});
it("type in var declaration", () => {
verifyAndAssertMessages(
`
import type Foo from 'foo';
var x: Foo = 1;
x;
`,
{ "no-unused-vars": 1, "no-undef": 1 },
);
});
it("object type annotation", () => {
verifyAndAssertMessages(
`
import type Foo from 'foo';
var a: {numVal: Foo};
a;
`,
{ "no-unused-vars": 1, "no-undef": 1 },
);
});
it("object property types", () => {
verifyAndAssertMessages(
`
import type Foo from 'foo';
import type Foo2 from 'foo';
var a = {
circle: (null : ?{ setNativeProps(props: Foo): Foo2 })
};
a;
`,
{ "no-unused-vars": 1, "no-undef": 1 },
);
});
it("namespaced types", () => {
verifyAndAssertMessages(
`
var React = require('react-native');
var b = {
openExternalExample: (null: ?React.Component)
};
var c = {
render(): React.Component {}
};
b;
c;
`,
{ "no-unused-vars": 1, "no-undef": 1 },
);
});
it("ArrayTypeAnnotation", () => {
verifyAndAssertMessages(
`
import type Foo from 'foo';
var x: Foo[]; x;
`,
{ "no-unused-vars": 1, "no-undef": 1 },
);
});
it("ClassImplements", () => {
verifyAndAssertMessages(
`
import type Bar from 'foo';
export default class Foo implements Bar {}
`,
{ "no-unused-vars": 1, "no-undef": 1 },
);
});
it("type alias creates declaration + usage", () => {
verifyAndAssertMessages(
`
type Foo = any;
var x : Foo = 1; x;
`,
{ "no-unused-vars": 1, "no-undef": 1 },
);
});
it("type alias with type parameters", () => {
verifyAndAssertMessages(
`
import type Bar from 'foo';
import type Foo3 from 'foo';
type Foo<T> = Bar<T, Foo3>
var x : Foo = 1; x;
`,
{ "no-unused-vars": 1, "no-undef": 1 },
);
});
it("export type alias", () => {
verifyAndAssertMessages(
`
import type Foo2 from 'foo';
export type Foo = Foo2;
`,
{ "no-unused-vars": 1, "no-undef": 1 },
);
});
it("polymorphic types #109", () => {
verifyAndAssertMessages(
"export default function groupByEveryN<T>(array: Array<T>, n: number): Array<Array<?T>> { n; }",
{ "no-unused-vars": 1, "no-undef": 1 },
);
});
it("types definition from import", () => {
verifyAndAssertMessages(
`
import type Promise from 'bluebird';
type Operation = () => Promise;
x: Operation;
`,
{ "no-unused-vars": 1, "no-undef": 1 },
);
});
it("polymorphic/generic types for class #123", () => {
verifyAndAssertMessages(
`
class Box<T> {
value: T;
}
var box = new Box();
console.log(box.value);
`,
{ "no-unused-vars": 1, "no-undef": 1 },
);
});
it("polymorphic/generic types for function #123", () => {
verifyAndAssertMessages(
`
export function identity<T>(value) {
var a: T = value; a;
}
`,
{ "no-unused-vars": 1, "no-undef": 1 },
);
});
it("polymorphic/generic types for type alias #123", () => {
verifyAndAssertMessages(
`
import Bar from './Bar';
type Foo<T> = Bar<T>; var x: Foo = 1; console.log(x);
`,
{ "no-unused-vars": 1, "no-undef": 1 },
);
});
it("polymorphic/generic types - outside of fn scope #123", () => {
verifyAndAssertMessages(
`
export function foo<T>(value) { value; };
var b: T = 1; b;
`,
{ "no-unused-vars": 1, "no-undef": 1 },
[
"1:21 'T' is defined but never used. no-unused-vars",
"2:8 'T' is not defined. no-undef",
],
);
});
it("polymorphic/generic types - extending unknown #123", () => {
verifyAndAssertMessages(
`
import Bar from 'bar';
export class Foo extends Bar<T> {}
`,
{ "no-unused-vars": 1, "no-undef": 1 },
["2:30 'T' is not defined. no-undef"],
);
});
it("polymorphic/generic types - function calls", () => {
verifyAndAssertMessages(
`
function f<T>(): T {}
f<T>();
`,
{ "no-unused-vars": 1, "no-undef": 1 },
["2:3 'T' is not defined. no-undef"],
);
});
it("polymorphic/generic types - function calls #644", () => {
verifyAndAssertMessages(
`
import type {Type} from 'Type';
function f<T>(): T {}
f<Type>();
`,
{ "no-unused-vars": 1, "no-undef": 1 },
);
});
it("support declarations #132", () => {
verifyAndAssertMessages(
`
declare class A { static () : number }
declare module B { declare var x: number; }
declare function foo<T>(): void;
declare var bar
A; B; foo(); bar;
`,
{ "no-undef": 1, "no-unused-vars": 1 },
);
});
it("supports type spreading", () => {
verifyAndAssertMessages(
`
type U = {};
type T = {a: number, ...U, ...V};
`,
{ "no-undef": 1, "no-unused-vars": 1 },
[
"2:6 'T' is defined but never used. no-unused-vars",
"2:31 'V' is not defined. no-undef",
],
);
});
it("1", () => {
verifyAndAssertMessages(
`
import type Foo from 'foo';
import type Foo2 from 'foo';
export default function(a: Foo, b: ?Foo2, c){ a; b; c; }
`,
{ "no-unused-vars": 1, "no-undef": 1 },
);
});
it("2", () => {
verifyAndAssertMessages(
`
import type Foo from 'foo';
export default function(a: () => Foo){ a; }
`,
{ "no-unused-vars": 1, "no-undef": 1 },
);
});
it("3", () => {
verifyAndAssertMessages(
`
import type Foo from 'foo';
import type Foo2 from 'foo';
export default function(a: (_:Foo) => Foo2){ a; }
`,
{ "no-unused-vars": 1, "no-undef": 1 },
);
});
it("4", () => {
verifyAndAssertMessages(
`
import type Foo from 'foo';
import type Foo2 from 'foo';
import type Foo3 from 'foo';
export default function(a: (_1:Foo, _2:Foo2) => Foo3){ a; }
`,
{ "no-unused-vars": 1, "no-undef": 1 },
);
});
it("5", () => {
verifyAndAssertMessages(
`
import type Foo from 'foo';
import type Foo2 from 'foo';
export default function(a: (_1:Foo, ...foo:Array<Foo2>) => number){ a; }
`,
{ "no-unused-vars": 1, "no-undef": 1 },
);
});
it("6", () => {
verifyAndAssertMessages(
`
import type Foo from 'foo';
export default function(): Foo {}
`,
{ "no-unused-vars": 1, "no-undef": 1 },
);
});
it("7", () => {
verifyAndAssertMessages(
`
import type Foo from 'foo';
export default function():() => Foo {}
`,
{ "no-unused-vars": 1, "no-undef": 1 },
);
});
it("8", () => {
verifyAndAssertMessages(
`
import type Foo from 'foo';
import type Foo2 from 'foo';
export default function():(_?:Foo) => Foo2{}
`,
{ "no-unused-vars": 1, "no-undef": 1 },
);
});
it("9", () => {
verifyAndAssertMessages(
"export default function <T1, T2>(a: T1, b: T2) { b; }",
{ "no-unused-vars": 1, "no-undef": 1 },
);
});
it("10", () => {
verifyAndAssertMessages(
"var a=function<T1,T2>(a: T1, b: T2) {return a + b;}; a;",
{ "no-unused-vars": 1, "no-undef": 1 },
);
});
it("11", () => {
verifyAndAssertMessages("var a={*id<T>(x: T): T { x; }}; a;", {
"no-unused-vars": 1,
"no-undef": 1,
});
});
it("12", () => {
verifyAndAssertMessages("var a={async id<T>(x: T): T { x; }}; a;", {
"no-unused-vars": 1,
"no-undef": 1,
});
});
it("13", () => {
verifyAndAssertMessages("var a={123<T>(x: T): T { x; }}; a;", {
"no-unused-vars": 1,
"no-undef": 1,
});
});
it("14", () => {
verifyAndAssertMessages(
`
import type Foo from 'foo';
import type Foo2 from 'foo';
export default class Bar {set fooProp(value:Foo):Foo2{ value; }}
`,
{ "no-unused-vars": 1, "no-undef": 1 },
);
});
it("15", () => {
verifyAndAssertMessages(
`
import type Foo2 from 'foo';
export default class Foo {get fooProp(): Foo2{}}
`,
{ "no-unused-vars": 1, "no-undef": 1 },
);
});
it("16", () => {
verifyAndAssertMessages(
`
import type Foo from 'foo';
var numVal:Foo; numVal;
`,
{ "no-unused-vars": 1, "no-undef": 1 },
);
});
it("17", () => {
verifyAndAssertMessages(
`
import type Foo from 'foo';
var a: {numVal: Foo;}; a;
`,
{ "no-unused-vars": 1, "no-undef": 1 },
);
});
it("18", () => {
verifyAndAssertMessages(
`
import type Foo from 'foo';
import type Foo2 from 'foo';
import type Foo3 from 'foo';
var a: ?{numVal: Foo; [indexer: Foo2]: Foo3}; a;
`,
{ "no-unused-vars": 1, "no-undef": 1 },
);
});
it("19", () => {
verifyAndAssertMessages(
`
import type Foo from 'foo';
import type Foo2 from 'foo';
var a: {numVal: Foo; subObj?: ?{strVal: Foo2}}; a;
`,
{ "no-unused-vars": 1, "no-undef": 1 },
);
});
it("20", () => {
verifyAndAssertMessages(
`
import type Foo from 'foo';
import type Foo2 from 'foo';
import type Foo3 from 'foo';
import type Foo4 from 'foo';
var a: { [a: Foo]: Foo2; [b: Foo3]: Foo4; }; a;
`,
{ "no-unused-vars": 1, "no-undef": 1 },
);
});
it("21", () => {
verifyAndAssertMessages(
`
import type Foo from 'foo';
import type Foo2 from 'foo';
import type Foo3 from 'foo';
var a: {add(x:Foo, ...y:Array<Foo2>): Foo3}; a;
`,
{ "no-unused-vars": 1, "no-undef": 1 },
);
});
it("22", () => {
verifyAndAssertMessages(
`
import type Foo from 'foo';
import type Foo2 from 'foo';
import type Foo3 from 'foo';
var a: { id<Foo>(x: Foo2): Foo3; }; a;
`,
{ "no-unused-vars": 1, "no-undef": 1 },
);
});
it("23", () => {
verifyAndAssertMessages(
`
import type Foo from 'foo';
var a:Array<Foo> = [1, 2, 3]; a;
`,
{ "no-unused-vars": 1, "no-undef": 1 },
);
});
it("24", () => {
verifyAndAssertMessages(
`
import type Baz from 'baz';
export default class Bar<T> extends Baz<T> { };
`,
{ "no-unused-vars": 1, "no-undef": 1 },
);
});
it("25", () => {
verifyAndAssertMessages(
"export default class Bar<T> { bar(): T { return 42; }}",
{ "no-unused-vars": 1, "no-undef": 1 },
);
});
it("26", () => {
verifyAndAssertMessages(
`
import type Foo from 'foo';
import type Foo2 from 'foo';
export default class Bar { static prop1:Foo; prop2:Foo2; }
`,
{ "no-unused-vars": 1, "no-undef": 1 },
);
});
it("27", () => {
verifyAndAssertMessages(
`
import type Foo from 'foo';
import type Foo2 from 'foo';
var x : Foo | Foo2 = 4; x;
`,
{ "no-unused-vars": 1, "no-undef": 1 },
);
});
it("28", () => {
verifyAndAssertMessages(
`
import type Foo from 'foo';
import type Foo2 from 'foo';
var x : () => Foo | () => Foo2; x;
`,
{ "no-unused-vars": 1, "no-undef": 1 },
);
});
it("29", () => {
verifyAndAssertMessages(
`
import type Foo from 'foo';
import type Foo2 from 'foo';
var x: typeof Foo | number = Foo2; x;
`,
{ "no-unused-vars": 1, "no-undef": 1 },
);
});
it("30", () => {
verifyAndAssertMessages(
`
import type Foo from 'foo';
var {x}: {x: Foo; } = { x: 'hello' }; x;
`,
{ "no-unused-vars": 1, "no-undef": 1 },
);
});
it("31", () => {
verifyAndAssertMessages(
`
import type Foo from 'foo';
var [x]: Array<Foo> = [ 'hello' ]; x;
`,
{ "no-unused-vars": 1, "no-undef": 1 },
);
});
it("32", () => {
verifyAndAssertMessages(
`
import type Foo from 'foo';
export default function({x}: { x: Foo; }) { x; }
`,
{ "no-unused-vars": 1, "no-undef": 1 },
);
});
it("33", () => {
verifyAndAssertMessages(
`
import type Foo from 'foo';
function foo([x]: Array<Foo>) { x; } foo();
`,
{ "no-unused-vars": 1, "no-undef": 1 },
);
});
it("34", () => {
verifyAndAssertMessages(
`
import type Foo from 'foo';
import type Foo2 from 'foo';
var a: Map<Foo, Array<Foo2> >; a;
`,
{ "no-unused-vars": 1, "no-undef": 1 },
);
});
it("35", () => {
verifyAndAssertMessages(
`
import type Foo from 'foo';
var a: ?Promise<Foo>[]; a;
`,
{ "no-unused-vars": 1, "no-undef": 1 },
);
});
it("36", () => {
verifyAndAssertMessages(
`
import type Foo from 'foo';
import type Foo2 from 'foo';
var a:(...rest:Array<Foo>) => Foo2; a;
`,
{ "no-unused-vars": 1, "no-undef": 1 },
);
});
it("37", () => {
verifyAndAssertMessages(
`
import type Foo from 'foo';
import type Foo2 from 'foo';
import type Foo3 from 'foo';
import type Foo4 from 'foo';
var a: <Foo>(x: Foo2, ...y:Foo3[]) => Foo4; a;
`,
{ "no-unused-vars": 1, "no-undef": 1 },
);
});
it("38", () => {
verifyAndAssertMessages(
`
import type {foo, bar} from 'baz';
foo; bar;
`,
{ "no-unused-vars": 1, "no-undef": 1 },
);
});
it("39", () => {
verifyAndAssertMessages(
`
import type {foo as bar} from 'baz';
bar;
`,
{ "no-unused-vars": 1, "no-undef": 1 },
);
});
it("40", () => {
verifyAndAssertMessages(
`
import type from 'foo';
type;
`,
{ "no-unused-vars": 1, "no-undef": 1 },
);
});
it("41", () => {
verifyAndAssertMessages(
`
import type, {foo} from 'bar';
type; foo;
`,
{ "no-unused-vars": 1, "no-undef": 1 },
);
});
it("43", () => {
verifyAndAssertMessages(
`
import type Foo from 'foo';
var a: Foo[]; a;
`,
{ "no-unused-vars": 1, "no-undef": 1 },
);
});
it("44", () => {
verifyAndAssertMessages(
`
import type Foo from 'foo';
var a: ?Foo[]; a;
`,
{ "no-unused-vars": 1, "no-undef": 1 },
);
});
it("45", () => {
verifyAndAssertMessages(
`
import type Foo from 'foo';
var a: (?Foo)[]; a;
`,
{ "no-unused-vars": 1, "no-undef": 1 },
);
});
it("46", () => {
verifyAndAssertMessages(
`
import type Foo from 'foo';
var a: () => Foo[]; a;
`,
{ "no-unused-vars": 1, "no-undef": 1 },
);
});
it("47", () => {
verifyAndAssertMessages(
`
import type Foo from 'foo';
var a: (() => Foo)[]; a;
`,
{ "no-unused-vars": 1, "no-undef": 1 },
);
});
it("48", () => {
verifyAndAssertMessages(
`
import type Foo from 'foo';
var a: typeof Foo[]; a;
`,
{ "no-unused-vars": 1, "no-undef": 1 },
);
});
it("49", () => {
verifyAndAssertMessages(
`
import type Foo from 'foo';
import type Foo2 from 'foo';
import type Foo3 from 'foo';
var a : [Foo, Foo2<Foo3>,] = [123, 'duck',]; a;
`,
{ "no-unused-vars": 1, "no-undef": 1 },
);
});
});
it("class usage", () => {
verifyAndAssertMessages("class Lol {} module.exports = Lol;", {
"no-unused-vars": 1,
});
});
it("class definition: gaearon/redux#24", () => {
verifyAndAssertMessages(
`
export default function root(stores) {
return DecoratedComponent => class ReduxRootDecorator {
a() { DecoratedComponent; stores; }
};
}
`,
{ "no-undef": 1, "no-unused-vars": 1 },
);
});
it("class properties #71", () => {
verifyAndAssertMessages("class Lol { foo = 'bar'; }", { "no-undef": 1 });
});
it("template strings #31", () => {
verifyAndAssertMessages("console.log(`${a}, b`);", { "comma-spacing": 1 });
});
it("template with destructuring #31", () => {
verifyAndAssertMessages(
`
module.exports = {
render() {
var {name} = this.props;
return Math.max(null, \`Name: \${name}, Name: \${name}\`);
}
};
`,
{ "comma-spacing": 1 },
);
});
it("template with arrow returning template #603", () => {
verifyAndAssertMessages(
`
var a = \`\${() => {
\`\${''}\`
}}\`;
`,
{ indent: 1 },
[],
);
});
describe("decorators #72 (legacy)", () => {
function verifyDecoratorsLegacyAndAssertMessages(
code,
rules,
expectedMessages,
sourceType,
) {
const overrideConfig = {
parserOptions: {
sourceType,
babelOptions: {
configFile: require.resolve(
"@babel/eslint-shared-fixtures/config/babel.config.decorators-legacy.js",
),
},
},
};
return verifyAndAssertMessages(
code,
rules,
expectedMessages,
sourceType,
overrideConfig,
);
}
it("class declaration", () => {
verifyDecoratorsLegacyAndAssertMessages(
`
import classDeclaration from 'decorator';
import decoratorParameter from 'decorator';
@classDeclaration((parameter) => parameter)
@classDeclaration(decoratorParameter)
@classDeclaration
export class TextareaAutosize {}
`,
{ "no-unused-vars": 1 },
);
});
it("method definition", () => {
verifyDecoratorsLegacyAndAssertMessages(
`
import classMethodDeclarationA from 'decorator';
import decoratorParameter from 'decorator';
export class TextareaAutosize {
@classMethodDeclarationA((parameter) => parameter)
@classMethodDeclarationA(decoratorParameter)
@classMethodDeclarationA
methodDeclaration(e) {
e();
}
}
`,
{ "no-unused-vars": 1 },
);
});
it("method definition get/set", () => {
verifyDecoratorsLegacyAndAssertMessages(
`
import classMethodDeclarationA from 'decorator';
import decoratorParameter from 'decorator';
export class TextareaAutosize {
@classMethodDeclarationA((parameter) => parameter)
@classMethodDeclarationA(decoratorParameter)
@classMethodDeclarationA
get bar() { }
@classMethodDeclarationA((parameter) => parameter)
@classMethodDeclarationA(decoratorParameter)
@classMethodDeclarationA
set bar(val) { val; }
}
`,
{ "no-unused-vars": 1 },
);
});
it("object property", () => {
verifyDecoratorsLegacyAndAssertMessages(
`
import classMethodDeclarationA from 'decorator';
import decoratorParameter from 'decorator';
var obj = {
@classMethodDeclarationA((parameter) => parameter)
@classMethodDeclarationA(decoratorParameter)
@classMethodDeclarationA
methodDeclaration(e) {
e();
}
};
obj;
`,
{ "no-unused-vars": 1 },
);
});
it("object property get/set", () => {
verifyDecoratorsLegacyAndAssertMessages(
`
import classMethodDeclarationA from 'decorator';
import decoratorParameter from 'decorator';
var obj = {
@classMethodDeclarationA((parameter) => parameter)
@classMethodDeclarationA(decoratorParameter)
@classMethodDeclarationA
get bar() { },
@classMethodDeclarationA((parameter) => parameter)
@classMethodDeclarationA(decoratorParameter)
@classMethodDeclarationA
set bar(val) { val; }
};
obj;
`,
{ "no-unused-vars": 1 },
);
});
});
describe("decorators #72", () => {
it("class declaration", () => {
verifyAndAssertMessages(
`
import classDeclaration from 'decorator';
import decoratorParameter from 'decorator';
export
@classDeclaration((parameter) => parameter)
@classDeclaration(decoratorParameter)
@classDeclaration
class TextareaAutosize {}
`,
{ "no-unused-vars": 1 },
);
});
it("method definition", () => {
verifyAndAssertMessages(
`
import classMethodDeclarationA from 'decorator';
import decoratorParameter from 'decorator';
export class TextareaAutosize {
@classMethodDeclarationA((parameter) => parameter)
@classMethodDeclarationA(decoratorParameter)
@classMethodDeclarationA
methodDeclaration(e) {
e();
}
}
`,
{ "no-unused-vars": 1 },
);
});
it("method definition get/set", () => {
verifyAndAssertMessages(
`
import classMethodDeclarationA from 'decorator';
import decoratorParameter from 'decorator';
export class TextareaAutosize {
@classMethodDeclarationA((parameter) => parameter)
@classMethodDeclarationA(decoratorParameter)
@classMethodDeclarationA
get bar() { }
@classMethodDeclarationA((parameter) => parameter)
@classMethodDeclarationA(decoratorParameter)
@classMethodDeclarationA
set bar(val) { val; }
}
`,
{ "no-unused-vars": 1 },
);
});
});
it("detects minimal no-unused-vars case #120", () => {
verifyAndAssertMessages("var unused;", { "no-unused-vars": 1 }, [
"1:5 'unused' is defined but never used. no-unused-vars",
]);
});
// This two tests are disabled, as the feature to visit properties when
// there is a spread/rest operator has been removed as it caused problems
// with other rules #249
// eslint-disable-next-line jest/no-disabled-tests
it.skip("visits excluded properties left of spread #95", () => {
verifyAndAssertMessages(
"var originalObject = {}; var {field1, field2, ...clone} = originalObject;",
{ "no-unused-vars": 1 },
);
});
// eslint-disable-next-line jest/no-disabled-tests
it.skip("visits excluded properties left of spread #210", () => {
verifyAndAssertMessages(
"const props = { yo: 'yo' }; const { ...otherProps } = props;",
{ "no-unused-vars": 1 },
);
});
it("does not mark spread variables false-positive", () => {
verifyAndAssertMessages(
"var originalObject = {}; var {field1, field2, ...clone} = originalObject;",
{ "no-undef": 1, "no-redeclare": 1 },
);
});
it("does not mark spread variables false-positive", () => {
verifyAndAssertMessages(
"const props = { yo: 'yo' }; const { ...otherProps } = props;",
{ "no-undef": 1, "no-redeclare": 1 },
);
});
it("does not mark spread variables as use-before-define #249", () => {
verifyAndAssertMessages(
"var originalObject = {}; var {field1, field2, ...clone} = originalObject;",
{ "no-use-before-define": 1 },
);
});
it("detects no-unused-vars with object destructuring #142", () => {
verifyAndAssertMessages(
"const {Bacona} = require('baconjs')",
{ "no-undef": 1, "no-unused-vars": 1 },
["1:8 'Bacona' is assigned a value but never used. no-unused-vars"],
);
});
it("don't warn no-unused-vars with spread #142", () => {
verifyAndAssertMessages(
`
export default function test(data) {
return {
foo: 'bar',
...data
};
}
`,
{ "no-undef": 1, "no-unused-vars": 1 },
);
});
it("excludes comment tokens #153", () => {
verifyAndAssertMessages(
`
var a = [
1,
2, // a trailing comment makes this line fail comma-dangle (always-multiline)
];
`,
{ "comma-dangle": [2, "always-multiline"] },
);
verifyAndAssertMessages(
`
switch (a) {
// A comment here makes the above line fail brace-style
case 1:
console.log(a);
}
`,
{ "brace-style": 2 },
);
});
it("ternary and parens #149", () => {
verifyAndAssertMessages("true ? (true) : false;", { "space-infix-ops": 1 });
});
it("line comment space-in-parens #124", () => {
verifyAndAssertMessages(
`
React.createClass({
render() {
// return (
// <div />
// ); // <-- this is the line that is reported
}
});
`,
{ "space-in-parens": 1 },
);
});
it("block comment space-in-parens #124", () => {
verifyAndAssertMessages(
`
React.createClass({
render() {
/*
return (
<div />
); // <-- this is the line that is reported
*/
}
});
`,
{ "space-in-parens": 1 },
);
});
it("no no-undef error with rest #11", () => {
verifyAndAssertMessages("const [a, ...rest] = ['1', '2', '3']; a; rest;", {
"no-undef": 1,
"no-unused-vars": 1,
});
});
it("async function with space-before-function-paren #168", () => {
verifyAndAssertMessages("it('handles updates', async function() {});", {
"space-before-function-paren": [1, "never"],
});
});
it("default param flow type no-unused-vars #184", () => {
verifyAndAssertMessages(
`
type ResolveOptionType = {
depth?: number,
identifier?: string
};
export default function resolve(
options: ResolveOptionType = {}
): Object {
options;
}
`,
{ "no-unused-vars": 1, "no-undef": 1 },
);
});
it("no-use-before-define #192", () => {
verifyAndAssertMessages(
`
console.log(x);
var x = 1;
`,
{ "no-use-before-define": 1 },
["1:13 'x' was used before it was defined. no-use-before-define"],
);
});
it("jsx and stringliteral #216", () => {
verifyAndAssertMessages("<div className=''></div>");
});
it("getter/setter #218", () => {
verifyAndAssertMessages(
`
class Person {
set a (v) { }
}
`,
{
"space-before-function-paren": 1,
"keyword-spacing": [1, { before: true }],
indent: 1,
},
);
});
it("getter/setter #220", () => {
verifyAndAssertMessages(
`
var B = {
get x () {
return this.ecks;
},
set x (ecks) {
this.ecks = ecks;
}
};
`,
{ "no-dupe-keys": 1 },
);
});
it("fixes issues with flow types and ObjectPattern", () => {
verifyAndAssertMessages(
`
import type Foo from 'bar';
export default class Foobar {
foo({ bar }: Foo) { bar; }
bar({ foo }: Foo) { foo; }
}
`,
{ "no-unused-vars": 1, "no-shadow": 1 },
);
});
it("correctly detects redeclares if in script mode #217", () => {
verifyAndAssertMessages(
`
var a = 321;
var a = 123;
`,
{ "no-redeclare": 1 },
["2:5 'a' is already defined. no-redeclare"],
"script",
);
});
it("correctly detects redeclares if in module mode #217", () => {
verifyAndAssertMessages(
`
var a = 321;
var a = 123;
`,
{ "no-redeclare": 1 },
["2:5 'a' is already defined. no-redeclare"],
"module",
);
});
it("no-implicit-globals in script: globalReturn is false", () => {
verifyAndAssertMessages(
"var leakedGlobal = 1;",
{ "no-implicit-globals": 1 },
[
"1:5 Unexpected 'var' declaration in the global scope, wrap in an IIFE for a local variable, assign as global property for a global variable. no-implicit-globals",
],
"script",
{
env: {},
parserOptions: {
ecmaVersion: 6,
sourceType: "script",
ecmaFeatures: { globalReturn: false },
},
},
);
});
it("no-implicit-globals in script: globalReturn is true", () => {
verifyAndAssertMessages(
"var leakedGlobal = 1;",
{ "no-implicit-globals": 1 },
[],
"script",
{
env: {},
parserOptions: {
ecmaVersion: 6,
sourceType: "script",
ecmaFeatures: { globalReturn: true },
},
},
);
});
it("no-implicit-globals in module", () => {
verifyAndAssertMessages(
"var leakedGlobal = 1;",
{ "no-implicit-globals": 1 },
[],
"module",
{
env: {},
parserOptions: { ecmaVersion: 6, sourceType: "module" },
},
);
});
it("no-implicit-globals in default", () => {
verifyAndAssertMessages(
"var leakedGlobal = 1;",
{ "no-implicit-globals": 1 },
[],
undefined,
{
env: {},
parserOptions: { ecmaVersion: 6 },
},
);
});
it("allowImportExportEverywhere option (#327)", () => {
verifyAndAssertMessages(
`
if (true) { import Foo from 'foo'; }
function foo() { import Bar from 'bar'; }
switch (a) { case 1: import FooBar from 'foobar'; }
`,
{},
[],
"module",
{
env: {},
parserOptions: {
ecmaVersion: 6,
sourceType: "module",
allowImportExportEverywhere: true,
},
},
);
});
it("with does not crash parsing in script mode (strict off) #171", () => {
verifyAndAssertMessages("with (arguments) { length; }", {}, [], "script");
});
it("with does crash parsing in module mode (strict on) #171", () => {
verifyAndAssertMessages("with (arguments) { length; }", {}, [
/'with' in strict mode/,
]);
});
it("new.target is not reported as undef #235", () => {
verifyAndAssertMessages("function foo () { return new.target }", {
"no-undef": 1,
});
});
it("decorator does not create TypeError #229", () => {
verifyAndAssertMessages(
`
class A {
@test
f() {}
}
`,
{ "no-undef": 1 },
["2:4 'test' is not defined. no-undef"],
);
});
it("Flow definition does not trigger warnings #223", () => {
verifyAndAssertMessages(
`
import { Map as $Map } from 'immutable';
function myFunction($state: $Map, { a, b, c } : { a: ?Object, b: ?Object, c: $Map }) {}
`,
{ "no-dupe-args": 1, "no-redeclare": 1, "no-shadow": 1 },
);
});
it("newline-before-return with comments #289", () => {
verifyAndAssertMessages(
`
function a() {
if (b) {
/* eslint-disable no-console */
console.log('test');
/* eslint-enable no-console */
}
return hasGlobal;
}
`,
{ "newline-before-return": 1 },
);
});
it("spaced-comment with shebang #163", () => {
verifyAndAssertMessages(
`
#!/usr/bin/env babel-node
import {spawn} from 'foobar';
`,
{ "spaced-comment": 1 },
);
});
describe("Class Property Declarations", () => {
it("no-redeclare false positive 1", () => {
verifyAndAssertMessages(
`
class Group {
static propTypes = {};
}
class TypicalForm {
static propTypes = {};
}
`,
{ "no-redeclare": 1 },
);
});
it("no-redeclare false positive 2", () => {
verifyAndAssertMessages(
`
function validate() {}
class MyComponent {
static validate = validate;
}
`,
{ "no-redeclare": 1 },
);
});
it("check references", () => {
verifyAndAssertMessages(
`
var a;
class A {
prop1;
prop2 = a;
prop3 = b;
}
new A
`,
{ "no-undef": 1, "no-unused-vars": 1, "no-redeclare": 1 },
["5:11 'b' is not defined. no-undef"],
);
});
});
it("dynamic import support", () => {
verifyAndAssertMessages("import('test-module').then(() => {})");
});
it("regex with es6 unicodeCodePointEscapes", () => {
verifyAndAssertMessages(
"string.replace(/[\u{0000A0}-\u{10FFFF}<>&]/gmiu, (char) => `&#x${char.codePointAt(0).toString(16)};`);",
);
});
describe("class field declarations", () => {
describe("field declarations", () => {
it("should not be undefined", () => {
verifyAndAssertMessages(
`
class C {
d = 1;
}
`,
{ "no-undef": 1 },
);
});
it("should not be unused", () => {
verifyAndAssertMessages(
`
export class C {
d = 1;
}
`,
{ "no-unused-vars": 1 },
);
});
});
describe("private field declarations", () => {
it("should not be undefined", () => {
verifyAndAssertMessages(
`
class C {
#d = 1;
}
`,
{ "no-undef": 1 },
);
});
it("should not be unused", () => {
verifyAndAssertMessages(
`
export class C {
#d = 1;
}
`,
{ "no-unused-vars": 1 },
);
});
});
describe("private methods", () => {
it("should not be undefined", () => {
verifyAndAssertMessages(
`
class C {
#d() {};
}
`,
{ "no-undef": 1 },
);
});
it("should not be unused", () => {
verifyAndAssertMessages(
`
export class C {
#d() {};
}
`,
{ "no-unused-vars": 1 },
);
});
});
});
describe("optional chaining operator", () => {
it("should not be undefined #595", () => {
verifyAndAssertMessages(
`
const foo = {};
foo?.bar;
`,
{ "no-undef": 1 },
);
});
});
it("flow types on class method should be visited correctly", () => {
verifyAndAssertMessages(
`
import type NodeType from 'foo';
class NodeUtils {
finishNodeAt<T : NodeType>(node: T): T { return node; }
}
new NodeUtils();
`,
{ "no-unused-vars": 1 },
);
});
it("works with dynamicImport", () => {
verifyAndAssertMessages(
`
import('a');
`,
);
});
it("works with numericSeparator", () => {
verifyAndAssertMessages(
`
1_000
`,
);
});
it("works with optionalChaining", () => {
verifyAndAssertMessages(
`
a?.b
`,
);
});
it("works with import.meta", () => {
verifyAndAssertMessages(
`
import.meta
`,
);
});
it("works with classPrivateProperties", () => {
verifyAndAssertMessages(
`
class A { #a = 1; }
`,
);
});
it("works with classPrivateMethods", () => {
verifyAndAssertMessages(
`
class A { #a(b, c) {} }
`,
);
});
it("works with arrow function classPrivateProperties", () => {
verifyAndAssertMessages(
`
class A { #a = (a, b) => {}; }
`,
);
});
it("works with optionalCatchBinding", () => {
verifyAndAssertMessages(
`
try {} catch {}
try {} catch {} finally {}
`,
);
});
it("exportDefaultFrom", () => {
verifyAndAssertMessages(
`
export v from "mod"
`,
);
});
it("exportNamespaceFrom", () => {
verifyAndAssertMessages(
`
export * as ns from "mod"
`,
);
});
it("ignore eval in scope analysis", () => {
verifyAndAssertMessages(
`
const a = 1;
console.log(a);
eval('');
`,
{ "no-unused-vars": 1, "no-undef": 1 },
);
});
});
|
// All symbols in the `Zs` category as per Unicode v9.0.0:
[
'\x20',
'\xA0',
'\u1680',
'\u2000',
'\u2001',
'\u2002',
'\u2003',
'\u2004',
'\u2005',
'\u2006',
'\u2007',
'\u2008',
'\u2009',
'\u200A',
'\u202F',
'\u205F',
'\u3000'
];
|
var class_subclone_explorer_1_1_tree_traverse_delegate =
[
[ "TreeTraverseDelegate", "class_subclone_explorer_1_1_tree_traverse_delegate.html#af5e6a4a399fd6e4f0244c0517f044b30", null ],
[ "~TreeTraverseDelegate", "class_subclone_explorer_1_1_tree_traverse_delegate.html#a96b550503dc883a3512aea284630ae11", null ],
[ "isTerminated", "class_subclone_explorer_1_1_tree_traverse_delegate.html#aa85b12536ab25909e228d4698145da51", null ],
[ "postprocessNode", "class_subclone_explorer_1_1_tree_traverse_delegate.html#a7eae69d60eee2471c8d99b64c7cd9ed1", null ],
[ "preprocessNode", "class_subclone_explorer_1_1_tree_traverse_delegate.html#a5f8f42f1370d4bc8722808d22344ad55", null ],
[ "processNode", "class_subclone_explorer_1_1_tree_traverse_delegate.html#a1f3c8f8a76da15aefe11595a85511d52", null ],
[ "terminate", "class_subclone_explorer_1_1_tree_traverse_delegate.html#a27e36da1b845ab2502e8d42481a6958f", null ],
[ "_isTerminated", "class_subclone_explorer_1_1_tree_traverse_delegate.html#a035292ae93a3cce9a4317374dbd661dc", null ]
];
|
(function() {
angular.module('angular-linkto', []);
angular.module('angular-linkto').service('keymaster', function() {
return {
replaceKey: function(str, key, params) {
return str.replace(":" + key, params != null ? params[key] : void 0);
},
findKeys: function(str) {
return str.match(/:[\w\d_\-]+/g);
},
replaceKeys: function(str, params) {
var key, keys;
if (params != null ? typeof params.hasAttributes === "function" ? params.hasAttributes() : void 0 : void 0) {
params = params.toJSON();
}
keys = this.findKeys(str);
for (key in params) {
str = this.replaceKey(str, key, params);
}
return str;
}
};
});
angular.module('angular-linkto').filter('linkTo', function(keymaster) {
var containsColon, containsColonAfterProtocol, containsColonBeforeSlash, containsProtocol, dropLastParam, throwUnfilledParamError;
containsColon = function(str) {
return str.indexOf(':') > -1;
};
containsColonAfterProtocol = function(str) {
return str.match(/^\w+:\/\/.*:/);
};
containsColonBeforeSlash = function(str) {
return str.match(/:[\w\d_\-]+\//);
};
containsProtocol = function(str) {
return str.match(/^\w+:\/\/.*/);
};
dropLastParam = function(str) {
return str.substring(0, str.lastIndexOf('/'));
};
throwUnfilledParamError = function(str) {
throw new Error("Must provide all data for named params in linkTo(), missing: " + (keymaster.findKeys(str)) + ", in route: " + str);
};
return function(route, params) {
if (route == null) {
throw new Error('Route required for linkTo()');
}
route = keymaster.replaceKeys(route, params);
if (containsProtocol(route)) {
if (containsColonAfterProtocol(route)) {
if (containsColonBeforeSlash(route)) {
throwUnfilledParamError(route);
} else {
route = dropLastParam(route);
}
}
} else if (containsColon(route)) {
if (containsColonBeforeSlash(route)) {
throwUnfilledParamError(route);
} else {
route = dropLastParam(route);
}
}
return route;
};
});
}).call(this);
/*
//@ sourceMappingURL=angular-linkto.js.map
*/
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.