code
stringlengths
2
1.05M
export { default } from 'ember-kinetic-form/components/semantic-ui-kinetic-form/errors';
module.exports = exports = function( app, swrap ) { "use strict"; app.fooLib = app.fooLib || 0; return { context: this, args: arguments, loadCount: ++app.fooLib }; };
$(document).on( 'click', 'a', function(event){ alert('test'); event.preventDefault(); console.log('test'); });
var express = require("express"); var Mustache = require('mustache'); var resumeToText = require('resume-to-text'); var path = require('path'); var resumeToHTML = require('resume-to-html'); var resumeToMarkdown = require('resume-to-markdown'); var bodyParser = require('body-parser'); var bcrypt = require('bcrypt-nodejs'); var gravatar = require('gravatar'); var app = express(); var postmark = require("postmark")(process.env.POSTMARK_API_KEY); var MongoClient = require('mongodb').MongoClient; var mongo = require('mongodb'); var templateHelper = require('./template-helper'); var pdf = require('pdfcrowd'); var request = require('superagent'); var sha256 = require('sha256'); var redis = require("redis"), redisClient = redis.createClient(); redisClient.on("error", function(err) { console.log("error event - " + redisClient.host + ":" + redisClient.port + " - " + err); }); var client = new pdf.Pdfcrowd('thomasdavis', '7d2352eade77858f102032829a2ac64e'); app.use(bodyParser()); var fs = require('fs'); var guid = (function() { function s4() { return Math.floor((1 + Math.random()) * 0x10000) .toString(16) .substring(1); } return function() { return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4(); }; })(); function S4() { return Math.floor((1 + Math.random()) * 0x10000) .toString(16) .substring(1); }; MongoClient.connect(process.env.MONGOHQ_URL, function(err, db) { app.all('/*', function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "X-Requested-With"); next(); }); var renderHomePage = function(req, res) { db.collection('users').find({}).toArray(function(err, docs) { var usernameArray = []; docs.forEach(function(doc) { usernameArray.push({ username: doc.username, gravatar: gravatar.url(doc.email, { s: '80', r: 'pg', d: '404' }) }); }); var page = Mustache.render(templateHelper.get('home'), { usernames: usernameArray }); res.send(page); }); }; var renderResume = function(req, res) { console.log('hello') var themeName = req.query.theme || 'modern'; var uid = req.params.uid; var format = req.params.format || req.headers.accept || 'html'; db.collection('resumes').findOne({ 'jsonresume.username': uid, }, function(err, resume) { if (!resume) { var page = Mustache.render(templateHelper.get('noresume'), {}); res.send(page); return; } if (typeof resume.jsonresume.passphrase === 'string' && typeof req.body.passphrase === 'undefined') { var page = Mustache.render(templateHelper.get('password'), {}); res.send(page); return; } if (typeof req.body.passphrase !== 'undefined' && req.body.passphrase !== resume.jsonresume.passphrase) { res.send('Password was wrong, go back and try again'); return; } var content = ''; if (/json/.test(format)) { delete resume.jsonresume; // This removes our registry server config vars from the resume.json delete resume._id; // This removes the document id of mongo content = JSON.stringify(resume, undefined, 4); res.set({ 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(content, 'utf8') // TODO - This is a hack to try get the right content length // http://stackoverflow.com/questions/17922748/what-is-the-correct-method-for-calculating-the-content-length-header-in-node-js }); res.send(content); } else if (/txt/.test(format)) { content = resumeToText(resume, function(plainText) { res.set({ 'Content-Type': 'text/plain', 'Content-Length': plainText.length }); res.send(200, plainText); }); } else if (/md/.test(format)) { resumeToMarkdown(resume, function(markdown, errs) { res.set({ 'Content-Type': 'text/plain', 'Content-Length': markdown.length }); res.send(markdown); }) } else if (/pdf/.test(format)) { console.log('Come on PDFCROWD'); resumeToHTML(resume, { theme: resume.jsonresume.theme || themeName }, function(content, errs) { client.convertHtml(content, pdf.sendHttpResponse(res)); }); } else { var theme = req.query.theme || resume.jsonresume.theme || themeName; request .post('http://themes.jsonresume.org/theme/' + theme) .send({ resume: resume }) .set('Content-Type', 'application/json') .end(function(response) { res.send(response.text); }); /* resumeToHTML(resume, { }, function(content, errs) { console.log(content, errs); var page = Mustache.render(templateHelper.get('layout'), { output: content, resume: resume, username: uid }); res.send(content); }); */ } }); }; app.get('/', renderHomePage); var renderMembersPage = function(req, res) { console.log('================================'); db.collection('users').find({}).toArray(function(err, docs) { console.log(err); var usernameArray = []; docs.forEach(function(doc) { usernameArray.push({ username: doc.username, gravatar: gravatar.url(doc.email, { s: '80', r: 'pg', d: '404' }) }); }); var page = Mustache.render(templateHelper.get('members'), { usernames: usernameArray }); res.send(page); }); }; app.get('/members', renderMembersPage); app.get('/:uid.:format', renderResume); app.get('/:uid', renderResume); app.post('/resume', function(req, res) { var password = req.body.password; var email = req.body.email; // console.log(req.body); if (!req.body.guest) { db.collection('users').findOne({ 'email': email }, function(err, user) { console.log(err, user); // redisClient.get(req.body.session, function(err, value) { // console.log(sha256(value), sha256(user.email)); // if (sha256(value) === sha256(user.email)) { // console.log('success'); // var resume = req.body && req.body.resume || {}; // resume.jsonresume = { // username: user.username, // passphrase: req.body.passphrase || null, // theme: req.body.theme || null // }; // console.log('inserted'); // db.collection('resumes').update({ // 'jsonresume.username': user.username // }, resume, { // upsert: true, // safe: true // }, function(err, resume) { // res.send({ // url: 'http://registry.jsonresume.org/' + user.username // }); // }); // } else if (user && bcrypt.compareSync(password, user.hash)) { // var resume = req.body && req.body.resume || {}; // resume.jsonresume = { // username: user.username, // passphrase: req.body.passphrase || null, // theme: req.body.theme || null // }; // console.log('inserted'); // db.collection('resumes').update({ // 'jsonresume.username': user.username // }, resume, { // upsert: true, // safe: true // }, function(err, resume) { // res.send({ // url: 'http://registry.jsonresume.org/' + user.username // }); // }); // } else { // res.send({ // message: 'ERRORRRSSSS' // }); // } // }); }); } else { var guestUsername = S4() + S4(); var resume = req.body && req.body.resume || {}; resume.jsonresume = { username: guestUsername, passphrase: req.body.passphrase || null, theme: req.body.theme || null }; console.log('inserted'); db.collection('resumes').insert(resume, { safe: true }, function(err, resume) { res.send({ url: 'http://registry.jsonresume.org/' + guestUsername }); }); } }); // update theme app.put('/resume', function(req, res) { var password = req.body.password; var email = req.body.email; var theme = req.body.theme; console.log(theme, "theme update!!!!!!!!!!!!1111"); // console.log(req.body); db.collection('users').findOne({ 'email': email }, function(err, user) { if (user && bcrypt.compareSync(password, user.hash)) { db.collection('resumes').update({ //query 'jsonresume.username': user.username }, { // update set new theme $set: { 'jsonresume.theme': theme } }, { //options upsert: true, safe: true }, function(err, resume) { res.send({ url: 'http://registry.jsonresume.org/' + user.username }); }); } else { console.log('deleted'); res.send({ message: 'authentication error' }); } }); }); app.post('/user', function(req, res) { // console.log(req.body); db.collection('users').findOne({ 'email': req.body.email }, function(err, user) { if (user) { res.send({ error: { field: 'email', message: 'Email is already in use, maybe you forgot your password?' } }); } else { db.collection('users').findOne({ 'username': req.body.username }, function(err, user) { if (user) { res.send({ error: { field: 'username', message: 'This username is already taken, please try another one' } }); } else { var emailTemplate = fs.readFileSync('templates/email/welcome.html', 'utf8'); var emailCopy = Mustache.render(emailTemplate, { username: req.body.username }); var hash = bcrypt.hashSync(req.body.password); postmark.send({ "From": "admin@jsonresume.org", "To": req.body.email, "Subject": "Json Resume - Community driven HR", "TextBody": emailCopy }, function(error, success) { if (error) { console.error("Unable to send via postmark: " + error.message); return; } console.info("Sent to postmark for delivery") }); db.collection('users').insert({ username: req.body.username, email: req.body.email, hash: hash }, { safe: true }, function(err, user) { res.send({ // username: user.username, email: user[0].email, username: user[0].username, message: "success" }); }); } }); } }); }); function uid(len) { return Math.random().toString(35).substr(2, len); } app.post('/session', function(req, res) { var password = req.body.password; var email = req.body.email; // console.log(req.body); db.collection('users').findOne({ 'email': email }, function(err, user) { if (user && bcrypt.compareSync(password, user.hash)) { // console.log(email, bcrypt.hashSync(email)); // console.log(email, bcrypt.hashSync(email)); var sessionUID = uid(17); redisClient.set(sessionUID, sha256(email), redis.print); // var session = value.toString(); res.send({ message: 'loggedIn', username: user.username, email: email, session: sessionUID }); redisClient.quit(); } else { res.send({ message: 'authentication error' }); } }); }); //delete user app.delete('/account', function(req, res) { var password = req.body.password; var email = req.body.email; db.collection('users').findOne({ 'email': email }, function(err, user) { if (user && bcrypt.compareSync(password, user.hash)) { // console.log(req.body); //remove the users resume db.collection('resumes').remove({ 'jsonresume.username': user.username }, 1, function(err, numberRemoved) { console.log(err, numberRemoved, 'resume deleted'); // then remove user db.collection('users').remove({ 'email': email }, 1, function(err, numberRemoved) { console.log(err, numberRemoved, 'user deleted'); if (!err) { res.send({ message: "account deleted" }); } }); }); } }); }); //change password app.put('/account', function(req, res) { var email = req.body.email; var password = req.body.currentPassword; var hash = bcrypt.hashSync(req.body.newPassword); console.log(email, password, hash); db.collection('users').findOne({ 'email': email }, function(err, user) { if (user && bcrypt.compareSync(password, user.hash)) { // console.log(req.body); db.collection('users').update({ //query 'email': email }, { // update set new theme $set: { 'hash': hash } }, { //options upsert: true, safe: true }, function(err, user) { console.log(err, user); if (!err) { res.send({ message: "password updated" }); } }); } }); }); app.post('/:uid', renderResume); var port = Number(process.env.PORT || 5000); app.listen(port, function() { console.log("Listening on " + port); }); })
var should = require('chai').should(), envInfo = require('../nativescriptsetup/index'), getWinPath = envInfo.getWindowsPath; describe('command: getWindowsPath', function() { it('check if windows path is not undefined', function() { getWinPath().should.not.be.undefined }); it('path shouldn\'t be an empty string', function() { getWinPath().should.exist; }); it('path length should be greater than 0', function() { var length = getWinPath().length; length.should.be.above(0); }); }); describe('command: getWindowsPath', function() { it('check if windows path is not undefined', function() { getWinPath().should.not.be.undefined }); it('path shouldn\'t be an empty string', function() { getWinPath().should.exist; }); it('path length should be greater than 0', function() { var length = getWinPath().length; length.should.be.above(0); }); });
'use strict'; /** * FUNCTION: toString() * Returns a string representation of Matrix elements. Rows are delineated by semicolons. Column values are comma-delimited. * * @returns {String} string representation */ function toString() { /* jshint validthis: true */ var nRows = this.shape[ 0 ], nCols = this.shape[ 1 ], s0 = this.strides[ 0 ], s1 = this.strides[ 1 ], m = nRows - 1, n = nCols - 1, str = '', o, i, j; for ( i = 0; i < nRows; i++ ) { o = this.offset + i*s0; for ( j = 0; j < nCols; j++ ) { str += this.data[ o + j*s1 ]; if ( j < n ) { str += ','; } } if ( i < m ) { str += ';'; } } return str; } // end FUNCTION toString() // EXPORTS // module.exports = toString;
const async = require('async'); const crypto = require('crypto'); const nodemailer = require('nodemailer'); const passport = require('passport'); const User = require('../models/User'); var emailActivationRequest = function(req,res,token,user) { const mailOptions = { to: user.email, from: res.__("Activation-email-from"), subject: res.__("Activation-email-subject"), text: res.__("Activation-email-text")+`\nhttp://${req.headers.host}/activate/${token}\n\n` }; var helper = require('sendgrid').mail; var from_email = new helper.Email(mailOptions.from); var to_email = new helper.Email(mailOptions.to); var content = new helper.Content('text/plain', mailOptions.text); var mail = new helper.Mail(from_email, mailOptions.subject, to_email, content); var sg = require('sendgrid')(process.env.SENDGRID_PASSWORD); var request = sg.emptyRequest({ method: 'POST', path: '/v3/mail/send', body: mail.toJSON(), }); sg.API(request, function(error, response) { console.log(response.statusCode); console.log(response.body); console.log(response.headers); req.flash('success', { msg: res.__("Activation-email-sent") }); res.redirect('/actmail'); }); } /** * GET /login * Login page. */ exports.getLogin = (req, res) => { if (req.user) { return res.redirect('/'); } res.render('account/login', { title: 'Login' }); }; /** * POST /login * Sign in using email and password. */ exports.postLogin = (req, res, next) => { req.assert('email',res.__('Email is not valid')).isEmail(); req.assert('password', res.__('Password cannot be blank')).notEmpty(); req.sanitize('email').normalizeEmail({ remove_dots: false }); const errors = req.validationErrors(); if (errors) { req.flash('errors', errors); return res.redirect('/login'); } passport.authenticate('local', (err, user, info) => { if (err) { return next(err); } if (!user) { req.flash('errors', info); return res.redirect('/login'); } //console.log("Activation switch="+user.activated+ " Token="+user.activationToken); if (user.activated != 'Y') { req.flash('errors', { msg: 'Account not activated yet !. Please check your email to activate your account' }); return res.redirect('/login'); } req.logIn(user, (err) => { if (err) { return next(err); } req.flash('success', { msg: 'Success! You are logged in.' }); res.redirect(req.session.returnTo || '/'); }); })(req, res, next); }; /** * GET /logout * Log out. */ exports.logout = (req, res) => { req.logout(); res.redirect('/'); }; /** * GET /signup * Signup page. */ exports.getSignup = (req, res) => { if (req.user) { return res.redirect('/'); } res.render('account/signup', { title: 'Create Account' }); }; /** * POST /signup * Create a new local account. */ exports.postSignup = (req, res, next) => { req.assert('email', 'Email is not valid').isEmail(); req.assert('password', 'Password must be at least 4 characters long').len(4); req.assert('confirmPassword', 'Passwords do not match').equals(req.body.password); req.sanitize('email').normalizeEmail({ remove_dots: false }); const errors = req.validationErrors(); if (errors) { req.flash('errors', errors); return res.redirect('/signup'); } const user = new User({ email: req.body.email, password: req.body.password }); User.findOne({ email: req.body.email }, (err, existingUser) => { if (err) { return next(err); } if (existingUser) { req.flash('errors', { msg: 'Account with that email address already exists.' }); return res.redirect('/signup'); } async.waterfall([ function createRandomToken(done) { crypto.randomBytes(16, (err, buf) => { const token = buf.toString('hex'); done(err, token); }); }, function setRandomToken(token, done) { user.activationToken = token; user.activated = 'N'; user.activationExpires = Date.now() + (24*60*60*1000); // 24 hours done(err, token, user); }, function saveNewAccount(token, user, done) { user.save((err) => { if (err) { return next(err); } }); done(err, token, user); }, function sendActivaionEmail(token, user, done) { emailActivationRequest(req,res,token,user); } ], (err) => { if (err) { return next(err); } res.redirect('/signup'); }); }); }; /** * GET /activate/:token * Activate Account page. */ exports.getActivate = (req, res, next) => { if (req.isAuthenticated()) { return res.redirect('/'); } User .findOne({ activationToken: req.params.token }) .where('activationExpires').gt(Date.now()) .exec((err, user) => { if (err) { return next(err); } if (!user) { req.flash('errors', { msg: 'Activation token is invalid or has expired.' }); return res.redirect('/actmail'); } user.activationToken = undefined; user.activationExpires = undefined; user.activated = 'Y'; user.save((err) => { if (err) { return next(err); } req.flash('success', { msg: 'Account was successfully Activated ! Please login to your account.' }); return res.redirect('/login'); }); }); }; /** * GET /account * Profile page. */ exports.getAccount = (req, res) => { res.render('account/profile', { title: 'Account Management' }); }; /** * POST /account/profile * Update profile information. */ exports.postUpdateProfile = (req, res, next) => { req.assert('email', 'Please enter a valid email address.').isEmail(); req.sanitize('email').normalizeEmail({ remove_dots: false }); const errors = req.validationErrors(); if (errors) { req.flash('errors', errors); return res.redirect('/account'); } User.findById(req.user.id, (err, user) => { if (err) { return next(err); } user.email = req.body.email || ''; user.profile.name = req.body.name || ''; user.profile.gender = req.body.gender || ''; user.profile.location = req.body.location || ''; user.profile.website = req.body.website || ''; user.save((err) => { if (err) { if (err.code === 11000) { req.flash('errors', { msg: 'The email address you have entered is already associated with an account.' }); return res.redirect('/account'); } return next(err); } req.flash('success', { msg: 'Profile information has been updated.' }); res.redirect('/account'); }); }); }; /** * POST /account/password * Update current password. */ exports.postUpdatePassword = (req, res, next) => { req.assert('password', 'Password must be at least 4 characters long').len(4); req.assert('confirmPassword', 'Passwords do not match').equals(req.body.password); const errors = req.validationErrors(); if (errors) { req.flash('errors', errors); return res.redirect('/account'); } User.findById(req.user.id, (err, user) => { if (err) { return next(err); } user.password = req.body.password; user.save((err) => { if (err) { return next(err); } req.flash('success', { msg: 'Password has been changed.' }); res.redirect('/account'); }); }); }; /** * POST /account/delete * Delete user account. */ exports.postDeleteAccount = (req, res, next) => { User.remove({ _id: req.user.id }, (err) => { if (err) { return next(err); } req.logout(); req.flash('info', { msg: 'Your account has been deleted.' }); res.redirect('/'); }); }; /** * GET /account/unlink/:provider * Unlink OAuth provider. */ exports.getOauthUnlink = (req, res, next) => { const provider = req.params.provider; User.findById(req.user.id, (err, user) => { if (err) { return next(err); } user[provider] = undefined; user.tokens = user.tokens.filter(token => token.kind !== provider); user.save((err) => { if (err) { return next(err); } req.flash('info', { msg: `${provider} account has been unlinked.` }); res.redirect('/account'); }); }); }; /** * GET /reset/:token * Reset Password page. */ exports.getReset = (req, res, next) => { if (req.isAuthenticated()) { return res.redirect('/'); } User .findOne({ passwordResetToken: req.params.token }) .where('passwordResetExpires').gt(Date.now()) .exec((err, user) => { if (err) { return next(err); } if (!user) { req.flash('errors', { msg: 'Password reset token is invalid or has expired.' }); return res.redirect('/forgot'); } res.render('account/reset', { title: 'Password Reset' }); }); }; /** * POST /reset/:token * Process the reset password request. */ exports.postReset = (req, res, next) => { req.assert('password', 'Password must be at least 4 characters long.').len(4); req.assert('confirm', 'Passwords must match.').equals(req.body.password); const errors = req.validationErrors(); if (errors) { req.flash('errors', errors); return res.redirect('back'); } async.waterfall([ function resetPassword(done) { User .findOne({ passwordResetToken: req.params.token }) .where('passwordResetExpires').gt(Date.now()) .exec((err, user) => { if (err) { return next(err); } if (!user) { req.flash('errors', { msg: 'Password reset token is invalid or has expired.' }); return res.redirect('back'); } user.password = req.body.password; user.passwordResetToken = undefined; user.passwordResetExpires = undefined; user.activationToken = undefined; user.activated = 'Y'; user.save((err) => { if (err) { return next(err); } req.logIn(user, (err) => { done(err, user); }); }); }); }, function sendResetPasswordEmail(user, done) { const mailOptions = { to: user.email, from: 'hackathon@starter.com', subject: 'Your Hackathon Starter password has been changed', text: `Hello,\n\nThis is a confirmation that the password for your account ${user.email} has just been changed.\n` }; var helper = require('sendgrid').mail; var from_email = new helper.Email(mailOptions.from); var to_email = new helper.Email(mailOptions.to); var content = new helper.Content('text/plain', mailOptions.text); var mail = new helper.Mail(from_email, mailOptions.subject, to_email, content); var sg = require('sendgrid')(process.env.SENDGRID_PASSWORD); var request = sg.emptyRequest({ method: 'POST', path: '/v3/mail/send', body: mail.toJSON(), }); sg.API(request, function(error, response) { console.log(response.statusCode); console.log(response.body); console.log(response.headers); req.flash('success', { msg: 'Success! Password Reset Completed !' }); res.redirect('/'); }); } ], (err) => { if (err) { return next(err); } res.redirect('/'); }); }; /** * GET /forgot * Forgot Password page. */ exports.getForgot = (req, res) => { if (req.isAuthenticated()) { return res.redirect('/'); } res.render('account/forgot', { title: 'Forgot Password' }); }; /** * POST /forgot * Create a random token, then the send user an email with a reset link. */ exports.postForgot = (req, res, next) => { req.assert('email', 'Please enter a valid email address.').isEmail(); req.sanitize('email').normalizeEmail({ remove_dots: false }); const errors = req.validationErrors(); if (errors) { req.flash('errors', errors); return res.redirect('/forgot'); } async.waterfall([ function createRandomToken(done) { crypto.randomBytes(16, (err, buf) => { const token = buf.toString('hex'); done(err, token); }); }, function setRandomToken(token, done) { User.findOne({ email: req.body.email }, (err, user) => { if (err) { return done(err); } if (!user) { req.flash('errors', { msg: 'Account with that email address does not exist.' }); return res.redirect('/forgot'); } user.passwordResetToken = token; user.passwordResetExpires = Date.now() + 3600000; // 1 hour user.save((err) => { done(err, token, user); }); }); }, function sendForgotPasswordEmail(token, user, done) { const mailOptions = { to: user.email, from: 'hackathon@starter.com', subject: 'Reset your password on Hackathon Starter', text: `You are receiving this email because you (or someone else) have requested the reset of the password for your account.\n\n Please click on the following link, or paste this into your browser to complete the process:\n\n http://${req.headers.host}/reset/${token}\n\n If you did not request this, please ignore this email and your password will remain unchanged.\n` }; var helper = require('sendgrid').mail; var from_email = new helper.Email(mailOptions.from); var to_email = new helper.Email(mailOptions.to); var content = new helper.Content('text/plain', mailOptions.text); var mail = new helper.Mail(from_email, mailOptions.subject, to_email, content); var sg = require('sendgrid')(process.env.SENDGRID_PASSWORD); var request = sg.emptyRequest({ method: 'POST', path: '/v3/mail/send', body: mail.toJSON(), }); sg.API(request, function(error, response) { console.log(response.statusCode); console.log(response.body); console.log(response.headers); req.flash('success', { msg: 'Success! Reset Password Reset Request Sent. Please Click on your email request link to Complete Password Reset.' }); res.redirect('/forgot'); }); } ], (err) => { if (err) { return next(err); } res.redirect('/forgot'); }); }; /** * GET /forgot * Forgot Password page. */ exports.getActmail = (req, res) => { if (req.isAuthenticated()) { return res.redirect('/'); } res.render('account/actmail', { title: res.__("Resend Activation Email") }); }; /** * POST /forgot * Create a random token, then the send user an email with a reset link. */ exports.postActmail = (req, res, next) => { req.assert('email', 'Please enter a valid email address.').isEmail(); req.sanitize('email').normalizeEmail({ remove_dots: false }); const errors = req.validationErrors(); if (errors) { req.flash('errors', errors); return res.redirect('/actmail'); } async.waterfall([ function createRandomToken(done) { crypto.randomBytes(16, (err, buf) => { const token = buf.toString('hex'); done(err, token); }); }, function setRandomToken(token, done) { User.findOne({ email: req.body.email }, (err, user) => { if (err) { return done(err); } if (!user) { req.flash('errors', { msg: 'Account with that email address does not exist.' }); return res.redirect('/actmail'); } if (user.activated == 'Y') { req.flash('errors', { msg: 'Account already activated !' }); return res.redirect('/login'); } user.activationToken = token; user.activated = 'N'; user.activationExpires = Date.now() + (24*60*60*1000); // 24 hours user.save((err) => { done(err, token, user); }); }); }, function sendActivaionEmail(token, user, done) { emailActivationRequest(req,res,token,user); } ], (err) => { if (err) { return next(err); } res.redirect('/actmail'); }); };
function infoMessage() { var _ = require('lodash'); var text = '<%= name %> - <%= description %>\n' + ' version: <%= version %>\n' + ' author: <%= author %>\n' + ' more info at: <%= homepage %>'; var pkg = require('../package.json'); return _.template(text)(pkg); } var info = infoMessage(); var optimist = require('optimist'); var program = optimist .option('version', { boolean: true, alias: 'v', description: 'show version and exit', default: false }) .option('push', { boolean: true, alias: 'p', description: 'push changes (if any) to remote origin', default: true }) .option('repo', { string: true, alias: 'r', description: '<github username/repo>', default: null }) .option('config', { string: true, alias: 'c', description: 'JSON config filename', default: null }) .option('user', { string: true, alias: 'u', description: 'fetch list of repos for this github username', default: null }) .option('sort', { string: true, alias: 's', description: 'sort repos (listed, reverse, asc, desc)' }) .option('clean', { boolean: true, description: 'delete temp folder after finished', default: false }) .option('allow', { string: true, default: 'major', description: 'allow major / minor / patch updates' }) .option('tag', { boolean: true, default: false, alias: 't', description: 'tag changed code with new patch version' }) .option('publish', { boolean: true, default: false, description: 'publish to NPM (if updated and has package.json)' }) .option('npm-user', { string: true, alias: 'n', default: null, description: 'update all NPM published repos for the given user' }) .option('N', { int: true, default: 10000, description: 'Limit update to first N sorted repos' }) .usage(info) .argv; if (program.version) { console.log(info); process.exit(0); } if (program.help || program.h) { optimist.showHelp(); process.exit(0); } module.exports = program;
var TOTAL_TIME = 30000 var SIZE = 2000 var RADIUS = 1 var COUNT = 9001 var SIMULATORS = require("./simulators") console.log("Starting benchmark...") for(var i=0; i<SIMULATORS.length; ++i) { var simCons = SIMULATORS[i] var sim = new simCons(COUNT, SIZE, RADIUS) var score = 0 var prev = new Date() var start = prev while(true) { sim.step() var cur = new Date() var d = (cur - start)|0 if(d > TOTAL_TIME) { score += (TOTAL_TIME-((prev-start)|0)) / (cur - prev) break } else { ++score prev = cur } } console.log(simCons.name + ": " + Math.floor(score*60000/TOTAL_TIME) + " ticks/minute") }
module.exports = require('regenerate')().addRange(0x11100, 0x11134).addRange(0x11136, 0x11143);
import {Text, BlockQuote, OrderedList, BulletList, ListItem, HorizontalRule, Paragraph, Heading, CodeBlock, Image, HardBreak, EmStyle, StrongStyle, LinkStyle, CodeStyle, Pos} from "../model" import {defineTarget} from "./index" let doc = null function elt(tag, attrs, ...args) { let result = doc.createElement(tag) if (attrs) for (let name in attrs) { if (name == "style") result.style.cssText = attrs[name] else if (attrs[name]) result.setAttribute(name, attrs[name]) } for (let i = 0; i < args.length; i++) result.appendChild(typeof args[i] == "string" ? doc.createTextNode(args[i]) : args[i]) return result } // declare_global: window export function toDOM(node, options = {}) { doc = options.document || window.document return renderNodes(node.children, options) } defineTarget("dom", toDOM) export function toHTML(node, options) { let wrap = (options && options.document || window.document).createElement("div") wrap.appendChild(toDOM(node, options)) return wrap.innerHTML } defineTarget("html", toHTML) export function renderNodeToDOM(node, options, offset) { let dom = renderNode(node, options, offset) if (options.renderInlineFlat && node.isInline) { dom = wrapInlineFlat(node, dom, options) dom = options.renderInlineFlat(node, dom, offset) || dom } return dom } function wrap(node, options, type) { let dom = elt(type || node.type.name) if (!node.isTextblock) renderNodesInto(node.children, dom, options) else if (options.renderInlineFlat) renderInlineContentFlat(node, dom, options) else renderInlineContent(node.children, dom, options) return dom } function wrapIn(type) { return (node, options) => wrap(node, options, type) } function renderNodes(nodes, options) { let frag = doc.createDocumentFragment() renderNodesInto(nodes, frag, options) return frag } function renderNode(node, options, offset) { let dom = node.type.serializeDOM(node, options) for (let attr in node.type.attrs) { let desc = node.type.attrs[attr] if (desc.serializeDOM) desc.serializeDOM(dom, node.attrs[attr], options, node) } if (options.onRender && node.isBlock) dom = options.onRender(node, dom, offset) || dom return dom } function renderNodesInto(nodes, where, options) { for (let i = 0; i < nodes.length; i++) { if (options.path) options.path.push(i) where.appendChild(renderNode(nodes[i], options, i)) if (options.path) options.path.pop() } } function renderInlineContent(nodes, where, options) { let top = where let active = [] for (let i = 0; i < nodes.length; i++) { let node = nodes[i], styles = node.styles let keep = 0 for (; keep < Math.min(active.length, styles.length); ++keep) if (!styles[keep].eq(active[keep])) break while (keep < active.length) { active.pop() top = top.parentNode } while (active.length < styles.length) { let add = styles[active.length] active.push(add) top = top.appendChild(renderStyle(add, options)) } top.appendChild(renderNode(node, options, i)) } } function renderStyle(marker, options) { let dom = marker.type.serializeDOM(marker, options) for (let attr in marker.type.attrs) { let desc = marker.type.attrs[attr] if (desc.serializeDOM) desc.serializeDOM(dom, marker.attrs[attr], options) } return dom } function wrapInlineFlat(node, dom, options) { let styles = node.styles for (let i = styles.length - 1; i >= 0; i--) { let wrap = renderStyle(styles[i], options) wrap.appendChild(dom) dom = wrap } return dom } function renderInlineContentFlat(node, where, options) { let offset = 0 for (let i = 0; i < node.length; i++) { let child = node.child(i) let dom = wrapInlineFlat(child, renderNode(child, options, i), options) dom = options.renderInlineFlat(child, dom, offset) || dom where.appendChild(dom) offset += child.offset } if (!node.type.isCode && (!node.length || where.lastChild.nodeName == "BR")) where.appendChild(elt("br")).setAttribute("pm-force-br", "true") else if (where.lastChild.contentEditable == "false") where.appendChild(doc.createTextNode("")) } // Block nodes function def(cls, method) { cls.prototype.serializeDOM = method } def(BlockQuote, wrapIn("blockquote")) BlockQuote.prototype.clicked = (_, path, dom, coords) => { let childBox = dom.firstChild.getBoundingClientRect() if (coords.left < childBox.left - 2) return Pos.from(path) } def(BulletList, wrapIn("ul")) def(OrderedList, (node, options) => { let dom = wrap(node, options, "ol") if (node.attrs.order > 1) dom.setAttribute("start", node.attrs.order) return dom }) OrderedList.prototype.clicked = BulletList.prototype.clicked = (_, path, dom, coords) => { for (let i = 0; i < dom.childNodes.length; i++) { let child = dom.childNodes[i] if (!child.hasAttribute("pm-path")) continue let childBox = child.getBoundingClientRect() if (coords.left > childBox.left - 2) return null if (childBox.top <= coords.top && childBox.bottom >= coords.top) return new Pos(path, i) } } def(ListItem, wrapIn("li")) def(HorizontalRule, () => elt("hr")) def(Paragraph, wrapIn("p")) def(Heading, (node, options) => wrap(node, options, "h" + node.attrs.level)) def(CodeBlock, (node, options) => { let code = wrap(node, options, "code") if (node.attrs.params != null) code.className = "fence " + node.attrs.params.replace(/(^|\s+)/g, "$&lang-") return elt("pre", null, code) }) // Inline content def(Text, node => doc.createTextNode(node.text)) def(Image, node => elt("img", { src: node.attrs.src, alt: node.attrs.alt, title: node.attrs.title, contentEditable: false })) def(HardBreak, () => elt("br")) // Inline styles def(EmStyle, () => elt("em")) def(StrongStyle, () => elt("strong")) def(CodeStyle, () => elt("code")) def(LinkStyle, style => elt("a", {href: style.attrs.href, title: style.attrs.title}))
angular.module('AboutCtrl', []).controller('AboutController', function($scope) { if (window.location.pathname == '/about') { $('#navAbout').addClass("active"); } $scope.tagline = 'Feel free to modify and extend this project!'; });
require("./spec_helper") describe("$dom", function(){ describe("hasClass", function(){ it("whithout the class", function(){ var elm = document.createElement("div"); var hasClassHelper = stik.labs.dom({ name: "hasClass" }).run(); expect(hasClassHelper(elm, "active")).toBeFalsy(); }); it("with the class", function(){ var elm = document.createElement("div"); elm.className = "active"; var hasClassHelper = stik.labs.dom({ name: "hasClass" }).run(); expect(hasClassHelper(elm, "active")).toBeTruthy(); }); it("with a different class", function(){ var elm = document.createElement("div"); elm.className = "not-active"; var hasClassHelper = stik.labs.dom({ name: "hasClass" }).run(); expect(hasClassHelper(elm, "active")).toBeFalsy(); }); }); describe("addClass", function(){ it("whithout the class", function(){ var elm = document.createElement("div"); var addClassHelper = stik.labs.dom({ name: "addClass" }).run(); addClassHelper(elm, "active"); expect(elm.className).toEqual("active"); }); it("with the class", function(){ var elm = document.createElement("div"); elm.className = "active"; var addClassHelper = stik.labs.dom({ name: "addClass" }).run(); addClassHelper(elm, "active"); expect(elm.className).toEqual("active"); }); it("with a different class", function(){ var elm = document.createElement("div"); elm.className = "not-active"; var addClassHelper = stik.labs.dom({ name: "addClass" }).run(); addClassHelper(elm, "active"); expect(elm.className).toEqual("not-active active"); }); it("with multiple classes", function(){ var elm = document.createElement("div"); elm.className = "active"; var addClass = stik.labs.dom({ name: "addClass" }).run(); addClass(elm, "should-be-active and-functional"); expect(elm.className).toEqual("active should-be-active and-functional"); }); it("with an array of classes", function(){ var elm = document.createElement("div"); elm.className = "active"; var addClass = stik.labs.dom({ name: "addClass" }).run(); addClass(elm, ["should-be-active", "and-functional"]); expect(elm.className).toEqual("active should-be-active and-functional"); }); }); describe("removeClass", function(){ it("whithout the class", function(){ var elm = document.createElement("div"); var removeClassHelper = stik.labs.dom({ name: "removeClass" }).run(); expect(function(){ removeClassHelper(elm, "active"); }).not.toThrow(); }); it("with the class", function(){ var elm = document.createElement("div"); elm.className = "active"; var removeClassHelper = stik.labs.dom({ name: "removeClass" }).run(); removeClassHelper(elm, "active"); expect(elm.className).toEqual(""); }); it("with a different class", function(){ var elm = document.createElement("div"); elm.className = "not-active"; var removeClassHelper = stik.labs.dom({ name: "removeClass" }).run(); removeClassHelper(elm, "active"); expect(elm.className).toEqual("not-active"); }); it("with a close enough class", function(){ var elm = document.createElement("div"); elm.className = "active-by-click active"; var removeClassHelper = stik.labs.dom({ name: "removeClass" }).run(); removeClassHelper(elm, "active"); expect(elm.className).toEqual("active-by-click"); }); it("with multiple classes", function(){ var elm = document.createElement("div"); elm.className = "should-be-active active and-functional"; var removeClass = stik.labs.dom({ name: "removeClass" }).run(); removeClass(elm, "should-be-active and-functional"); expect(elm.className).toEqual("active"); }); it("with an array of classes", function(){ var elm = document.createElement("div"); elm.className = "should-be-active and-functional active"; var removeClass = stik.labs.dom({ name: "removeClass" }).run(); removeClass(elm, ["should-be-active", "and-functional"]); expect(elm.className).toEqual("active"); }); it("removing the middle class", function(){ var elm = document.createElement("div"); elm.className = "cc-number visa identified"; var removeClass = stik.labs.dom({ name: "removeClass" }).run(); removeClass(elm, "visa"); expect(elm.className).toEqual("cc-number identified"); }); }); describe("toggleClass", function(){ it("whithout the class", function(){ var elm = document.createElement("div"); var toggleClass = stik.labs.dom({ name: "toggleClass" }).run(); toggleClass(elm, "active"); expect(elm.className).toEqual("active"); }); it("with the class", function(){ var elm = document.createElement("div"); elm.className = "active"; var toggleClass = stik.labs.dom({ name: "toggleClass" }).run(); toggleClass(elm, "active"); expect(elm.className).toEqual(""); }); it("with a different class", function(){ var elm = document.createElement("div"); elm.className = "not-active"; var toggleClass = stik.labs.dom({ name: "toggleClass" }).run(); toggleClass(elm, "active"); expect(elm.className).toEqual("not-active active"); }); it("forcing addition", function(){ var elm = document.createElement("div"); elm.className = "active"; addClassMock = jasmine.createSpy("addClassMock"); var toggleClass = stik.labs.dom({ name: "toggleClass" }).run({ addClass: addClassMock }); toggleClass(elm, "active", true); expect(addClassMock).toHaveBeenCalledWith(elm, "active"); }); it("forcing removal", function(){ var elm = document.createElement("div"); elm.className = "active"; removeClassMock = jasmine.createSpy("removeClassMock"); var toggleClass = stik.labs.dom({ name: "toggleClass" }).run({ removeClass: removeClassMock }); toggleClass(elm, "active", false); expect(removeClassMock).toHaveBeenCalledWith(elm, "active"); }); }); describe("hide", function(){ it("when visible", function(){ var elm = document.createElement("div"); var hideHelper = stik.labs.dom({ name: "hide" }).run(); hideHelper(elm); expect(elm.style.display).toEqual("none"); }); }); describe("show", function(){ it("when visible", function(){ var elm = document.createElement("div"); var showHelper = stik.labs.dom({ name: "show" }).run(); showHelper(elm); expect(elm.style.display).toEqual("block"); }); it("when hidden", function(){ var elm = document.createElement("div"); elm.style.display = "none"; var showHelper = stik.labs.dom({ name: "show" }).run(); showHelper(elm); expect(elm.style.display).toEqual("block"); }); }); describe("remove", function(){ it("should remove a child from its parent", function(){ var template = document.createElement("div"); template.innerHTML = "<span></span>"; var removeHelper = stik.labs.dom({ name: "remove" }).run(); removeHelper(template.firstChild); expect(template.childNodes.length).toEqual(0); }); }); describe("parse", function(){ it("should parse a string as a node element", function(){ var template = "<span></span>"; var parse = stik.labs.dom({ name: "parse" }).run(); var parsedTemplate = parse(template); expect(parsedTemplate instanceof window.HTMLElement).toBeTruthy(); }); }); describe("append", function(){ it("with a non empty parent", function(){ var template = document.createElement("div"); template.innerHTML = "<span></span>"; var newNode = document.createElement("div"); var appendHelper = stik.labs.dom({ name: "append" }).run(); appendHelper(template, newNode); expect(template.childNodes.length).toEqual(2); expect(template.lastChild.nodeName).toEqual("DIV"); }); it("with an empty parent", function(){ var template = document.createElement("div"); var newNode = document.createElement("div"); var appendHelper = stik.labs.dom({ name: "append" }).run(); appendHelper(template, newNode); expect(template.childNodes.length).toEqual(1); expect(template.firstChild.nodeName).toEqual("DIV"); }); it("with a string child", function(){ var template = document.createElement("div"); var newNode = "<span></span>"; var appendHelper = stik.labs.dom({ name: "append" }).run(); appendHelper(template, newNode); expect(template.childNodes.length).toEqual(1); expect(template.firstChild.nodeName).toEqual("SPAN"); }); it("with multiple childs as string", function(){ var template = document.createElement("div"); var newNodes = "<span></span><br><a>"; var appendHelper = stik.labs.dom({ name: "append" }).run(); appendHelper(template, newNodes); expect(template.childNodes.length).toEqual(3); expect(template.childNodes[0].nodeName).toEqual("SPAN"); expect(template.childNodes[1].nodeName).toEqual("BR"); expect(template.childNodes[2].nodeName).toEqual("A"); }); }); describe("prepend", function(){ it("with a non empty parent", function(){ var template = document.createElement("div"); template.innerHTML = "<span></span>"; var newNode = document.createElement("div"); var prependHelper = stik.labs.dom({ name: "prepend" }).run(); prependHelper(template, newNode); expect(template.childNodes.length).toEqual(2); expect(template.firstChild.nodeName).toEqual("DIV"); }); it("with an empty parent", function(){ var template = document.createElement("div"); var newNode = document.createElement("div"); var prependHelper = stik.labs.dom({ name: "prepend" }).run(); prependHelper(template, newNode); expect(template.childNodes.length).toEqual(1); expect(template.firstChild.nodeName).toEqual("DIV"); }); it("with a string child", function(){ var template = document.createElement("div"); var newNode = "<span></span>"; var appendHelper = stik.labs.dom({ name: "prepend" }).run(); appendHelper(template, newNode); expect(template.childNodes.length).toEqual(1); expect(template.firstChild.nodeName).toEqual("SPAN"); }); it("with multiple childs as string", function(){ var template = document.createElement("div"); var newNodes = "<span></span><br><a>"; var appendHelper = stik.labs.dom({ name: "prepend" }).run(); appendHelper(template, newNodes); expect(template.childNodes.length).toEqual(3); expect(template.childNodes[0].nodeName).toEqual("SPAN"); expect(template.childNodes[1].nodeName).toEqual("BR"); expect(template.childNodes[2].nodeName).toEqual("A"); }); }); describe("insertAfter", function(){ it("with a non empty parent", function(){ var template = document.createElement("div"); template.innerHTML = "<span></span><br>"; var newNode = document.createElement("div"); var insertAfterHelper = stik.labs.dom({ name: "insertAfter" }).run(); insertAfterHelper(template.firstChild, newNode); expect(template.childNodes.length).toEqual(3); expect(template.childNodes[1].nodeName).toEqual("DIV"); }); it("with a string child", function(){ var template = document.createElement("div"); template.innerHTML = "<span></span><br>"; var newNode = "<div>/div>"; var insertAfterHelper = stik.labs.dom({ name: "insertAfter" }).run(); insertAfterHelper(template.firstChild, newNode); expect(template.childNodes.length).toEqual(3); expect(template.childNodes[1].nodeName).toEqual("DIV"); }); }); describe("insertBefore", function(){ it("with a non empty parent", function(){ var template = document.createElement("div"); template.innerHTML = "<span></span><br>"; var newNode = document.createElement("div"); var insertBeforeHelper = stik.labs.dom({ name: "insertBefore" }).run(); insertBeforeHelper(template.firstChild, newNode); expect(template.childNodes.length).toEqual(3); expect(template.firstChild.nodeName).toEqual("DIV"); }); it("with a string child", function(){ var template = document.createElement("div"); template.innerHTML = "<span></span><br>"; var newNode = "<div></div>"; var insertBeforeHelper = stik.labs.dom({ name: "insertBefore" }).run(); insertBeforeHelper(template.firstChild, newNode); expect(template.childNodes.length).toEqual(3); expect(template.firstChild.nodeName).toEqual("DIV"); }); }); describe("data", function(){ it("should retrieve one attribute from the template", function(){ var template = document.createElement("div"), result, dataHelper; template.setAttribute("data-id", "$081209j09urr123"); dataHelper = stik.labs.dom({ name: "data" }).run(); result = dataHelper(template); expect(result).toEqual( { id: "$081209j09urr123" } ); }); it("should retrieve multiple attributes from the template", function(){ var template = document.createElement("div"), result, dataHelper; template.setAttribute("data-id", "$081209j09urr123"); template.setAttribute("data-active", "false"); template.setAttribute("data-relative", "$0129740y4u2i2"); dataHelper = stik.labs.dom({ name: "data" }).run(); result = dataHelper(template); expect(result).toEqual({ id: "$081209j09urr123", active: "false", relative: "$0129740y4u2i2" }); }); it("should handle an attribute with multiple dashes", function(){ var template = document.createElement("div"), result, dataHelper; template.setAttribute("data-db-id", "$081209j09urr123"); template.setAttribute("data-is-more-active", "true"); dataHelper = stik.labs.dom({ name: "data" }).run(); result = dataHelper(template); expect(result).toEqual({ "dbId": "$081209j09urr123", "isMoreActive": "true" }); }); it("should also be accesible as a boundary", function(){ var template = "", dom = { data: jasmine.createSpy("$dom") }; var dataHelper = stik.labs.boundary({ name: "$data" }).run({ $template: template, $dom: dom }); expect(dom.data).toHaveBeenCalledWith(template); }); }); describe("find", function(){ it("a child element", function(){ var template = document.createElement("div"); template.innerHTML = "<span class=\"child\"></span>"; var find = stik.labs.dom({ name: "find" }).run(); expect(find(template, ".child").nodeName).toEqual("SPAN"); }); }); describe("findAll", function(){ it("all specified child elements", function(){ var template = document.createElement("div"); template.innerHTML = "<span class=\"child\"></span><input class=\"name\"/><br>"; var findAll = stik.labs.dom({ name: "findAll" }).run(); var result = findAll(template, ".child, .name"); expect(result.length).toEqual(2); expect(result[0].nodeName).toEqual("SPAN"); expect(result[1].nodeName).toEqual("INPUT"); }); }); describe("event", function(){ it("should delegate to addEventListener", function(){ var template = jasmine.createSpyObj("template", ["addEventListener"]); var event = stik.labs.dom({ name: "event" }).run(); event(template, "click", function(){}); expect( template.addEventListener ).toHaveBeenCalledWith("click", jasmine.any(Function), false); }); }); describe("click", function(){ it("should create a listener", function(){ var template = jasmine.createSpyObj("template", ["addEventListener"]); var click = stik.labs.dom({ name: "click" }).run(); click(template, function(){}); expect( template.addEventListener ).toHaveBeenCalledWith("click", jasmine.any(Function), false); }); }); describe("doubleClick", function(){ it("should create a listener", function(){ var template = jasmine.createSpyObj("template", ["addEventListener"]); var doubleClick = stik.labs.dom({ name: "doubleClick" }).run(); doubleClick(template, function(){}); expect( template.addEventListener ).toHaveBeenCalledWith("dblclick", jasmine.any(Function), false); }); }); describe("mouseDown", function(){ it("should create a listener", function(){ var template = jasmine.createSpyObj("template", ["addEventListener"]); var mouseDown = stik.labs.dom({ name: "mouseDown" }).run(); mouseDown(template, function(){}); expect( template.addEventListener ).toHaveBeenCalledWith("mousedown", jasmine.any(Function), false); }); }); describe("mouseUp", function(){ it("should create a listener", function(){ var template = jasmine.createSpyObj("template", ["addEventListener"]); var mouseUp = stik.labs.dom({ name: "mouseUp" }).run(); mouseUp(template, function(){}); expect( template.addEventListener ).toHaveBeenCalledWith("mouseup", jasmine.any(Function), false); }); }); describe("mouseMove", function(){ it("should create a listener", function(){ var template = jasmine.createSpyObj("template", ["addEventListener"]); var mouseMove = stik.labs.dom({ name: "mouseMove" }).run(); mouseMove(template, function(){}); expect( template.addEventListener ).toHaveBeenCalledWith("mousemove", jasmine.any(Function), false); }); }); describe("mouseOver", function(){ it("should create a listener", function(){ var template = jasmine.createSpyObj("template", ["addEventListener"]); var mouseOver = stik.labs.dom({ name: "mouseOver" }).run(); mouseOver(template, function(){}); expect( template.addEventListener ).toHaveBeenCalledWith("mouseover", jasmine.any(Function), false); }); }); describe("mouseOut", function(){ it("should create a listener", function(){ var template = jasmine.createSpyObj("template", ["addEventListener"]); var mouseOut = stik.labs.dom({ name: "mouseOut" }).run(); mouseOut(template, function(){}); expect( template.addEventListener ).toHaveBeenCalledWith("mouseout", jasmine.any(Function), false); }); }); describe("abort", function(){ it("should create a listener", function(){ var template = jasmine.createSpyObj("template", ["addEventListener"]); var abort = stik.labs.dom({ name: "abort" }).run(); abort(template, function(){}); expect( template.addEventListener ).toHaveBeenCalledWith("abort", jasmine.any(Function), false); }); }); describe("blur", function(){ it("should create a listener", function(){ var template = jasmine.createSpyObj("template", ["addEventListener"]); var blur = stik.labs.dom({ name: "blur" }).run(); blur(template, function(){}); expect( template.addEventListener ).toHaveBeenCalledWith("blur", jasmine.any(Function), false); }); }); describe("change", function(){ it("should create a listener", function(){ var template = jasmine.createSpyObj("template", ["addEventListener"]); var change = stik.labs.dom({ name: "change" }).run(); change(template, function(){}); expect( template.addEventListener ).toHaveBeenCalledWith("change", jasmine.any(Function), false); }); }); describe("error", function(){ it("should create a listener", function(){ var template = jasmine.createSpyObj("template", ["addEventListener"]); var error = stik.labs.dom({ name: "error" }).run(); error(template, function(){}); expect( template.addEventListener ).toHaveBeenCalledWith("error", jasmine.any(Function), false); }); }); describe("focus", function(){ it("should create a listener", function(){ var template = jasmine.createSpyObj("template", ["addEventListener"]); var focus = stik.labs.dom({ name: "focus" }).run(); focus(template, function(){}); expect( template.addEventListener ).toHaveBeenCalledWith("focus", jasmine.any(Function), false); }); }); describe("load", function(){ it("should create a listener", function(){ var template = jasmine.createSpyObj("template", ["addEventListener"]); var load = stik.labs.dom({ name: "load" }).run(); load(template, function(){}); expect( template.addEventListener ).toHaveBeenCalledWith("load", jasmine.any(Function), false); }); }); describe("reset", function(){ it("should create a listener", function(){ var template = jasmine.createSpyObj("template", ["addEventListener"]); var reset = stik.labs.dom({ name: "reset" }).run(); reset(template, function(){}); expect( template.addEventListener ).toHaveBeenCalledWith("reset", jasmine.any(Function), false); }); }); describe("resize", function(){ it("should create a listener", function(){ var template = jasmine.createSpyObj("template", ["addEventListener"]); var resize = stik.labs.dom({ name: "resize" }).run(); resize(template, function(){}); expect( template.addEventListener ).toHaveBeenCalledWith("resize", jasmine.any(Function), false); }); }); describe("scroll", function(){ it("should create a listener", function(){ var template = jasmine.createSpyObj("template", ["addEventListener"]); var scroll = stik.labs.dom({ name: "scroll" }).run(); scroll(template, function(){}); expect( template.addEventListener ).toHaveBeenCalledWith("scroll", jasmine.any(Function), false); }); }); describe("select", function(){ it("should create a listener", function(){ var template = jasmine.createSpyObj("template", ["addEventListener"]); var select = stik.labs.dom({ name: "select" }).run(); select(template, function(){}); expect( template.addEventListener ).toHaveBeenCalledWith("select", jasmine.any(Function), false); }); }); describe("submit", function(){ it("should create a listener", function(){ var template = jasmine.createSpyObj("template", ["addEventListener"]); var submit = stik.labs.dom({ name: "submit" }).run(); submit(template, function(){}); expect( template.addEventListener ).toHaveBeenCalledWith("submit", jasmine.any(Function), false); }); }); describe("unload", function(){ it("should create a listener", function(){ var template = jasmine.createSpyObj("template", ["addEventListener"]); var unload = stik.labs.dom({ name: "unload" }).run(); unload(template, function(){}); expect( template.addEventListener ).toHaveBeenCalledWith("unload", jasmine.any(Function), false); }); }); describe("$elm", function(){ it("should wrap the template as a stik-dom obj", function(){ var template = document.createElement("div"); var elm = stik.labs.boundary({ name: "$elm" }).run({ $template: template }); expect(elm.template).toEqual(template); elm.addClass("active"); expect(elm.hasClass("active")).toBeTruthy(); elm.removeClass("active"); expect(elm.hasClass("active")).toBeFalsy(); elm.toggleClass("active", false); expect(elm.hasClass("active")).toBeFalsy(); }); it("should return another $elm object after a dom query", function(){ var template = document.createElement("div"); template.innerHTML = "<span></span>"; var elm = stik.labs.boundary({ name: "$elm" }).run({ $template: template }); span = elm.find("span"); expect(span.hasClass).not.toBeUndefined(); }); }); });
/* * geo-tales-mobile * * Copyright (c) 2015 Maximilian Antoni <mail@maxantoni.de> * * @license MIT */ /*global document*/ 'use strict'; const fs = require('fs'); const events = require('events'); const hyperglue = require('hyperglue'); const animate = require('animatify'); const locatify = require('locatify'); const color = require('./color'); const message = require('./message'); const screen = require('./screen'); const html = fs.readFileSync(`${__dirname }/screen-navigate.html`, 'utf8'); exports.create = function (parent, shape, opts, next) { const screenElement = hyperglue(html, {}); const compassElement = screenElement.querySelector('.compass'); const arrowElement = screenElement.querySelector('.arrow'); const accuracyElement = screenElement.querySelector('.accuracy'); const distanceElement = screenElement.querySelector('.distance'); const footerElement = screenElement.querySelector('.footer'); footerElement.style.display = 'none'; if (opts.compass === false) { compassElement.style.display = 'none'; } parent.appendChild(screenElement); const sx = shape.center.latitude; const sy = shape.center.longitude; let mx, my, deg; let lastPos; let visible = false; let animating = false; let errorMessage; function destroyErrorMessage() { if (errorMessage) { errorMessage.destroy(); errorMessage = null; } } function updateArrow() { // http://www.movable-type.co.uk/scripts/latlong.html mx = lastPos.latitude; my = lastPos.longitude; const wy = sy - my; const x = Math.cos(mx) * Math.sin(sx) - Math.sin(mx) * Math.cos(sx) * Math.cos(wy); const y = Math.sin(wy) * Math.cos(sx); let d = Math.atan2(x, y) * 180 / Math.PI - deg + 180; if (d < 0) { d += 360; } const transform = `rotate(${ Math.round(d) }deg)`; arrowElement.style.transform = transform; arrowElement.style.webkitTransform = transform; if (!visible) { visible = true; animating = true; arrowElement.style.visibility = 'visible'; animate(arrowElement, 'zoomIn', () => { animating = false; updateArrow(); }); } } let tracker; let timeout; if (opts.demo) { tracker = new events.EventEmitter(); tracker.destroy = function () { tracker.removeAllListeners(); }; } else { tracker = locatify.create(); timeout = setTimeout(() => { if (!errorMessage) { destroyErrorMessage(); errorMessage = message.create(parent, 'Waiting for position data', 'info'); } }, 3000); } const makeColor = opts.colorSteps ? color(opts.colorSteps) : null; tracker.on('error', (err) => { clearTimeout(timeout); destroyErrorMessage(); errorMessage = message.create(parent, err.message, 'warning'); visible = false; arrowElement.style.visibility = 'hidden'; document.documentElement.style.backgroundColor = 'inherit'; }); function updateAccuracy() { const acc = lastPos.accuracy; const pre = acc < 20 ? '' : 'Accuracy: '; accuracyElement.innerHTML = `${pre + Math.round(acc || 10000) } m`; } tracker.on('position', (pos) => { clearTimeout(timeout); destroyErrorMessage(); lastPos = pos; if (animating) { return; } const distance = shape.distance(pos); if (opts.distance !== false) { distanceElement.innerHTML = `${distance } m`; updateAccuracy(); } if (deg !== undefined) { updateArrow(); } const goodAccuracy = pos.accuracy && pos.accuracy < 20; if (goodAccuracy) { if (accuracyElement.classList.contains('bad')) { accuracyElement.classList.remove('bad'); if (opts.distance === false) { accuracyElement.innerHTML = ''; } } } else { accuracyElement.classList.add('bad'); if (opts.distance === false) { updateAccuracy(); } } if (makeColor) { document.documentElement.style.backgroundColor = goodAccuracy ? makeColor(distance) : 'inherit'; } if (goodAccuracy && shape.within(pos)) { if (errorMessage) { errorMessage.destroy(); errorMessage = null; } tracker.destroy(); const elements = []; if (opts.compass !== false) { elements.push(compassElement); } if (opts.distance !== false) { elements.push(distanceElement, accuracyElement); } screen.hide(elements, () => { compassElement.style.display = 'none'; distanceElement.style.display = 'none'; accuracyElement.style.display = 'none'; }); footerElement.style.display = 'block'; screen.show([footerElement]); setTimeout(() => { const msg = message.create(parent, 'Location reached!', 'info', () => { footerElement.querySelector('.next').onclick = function () { screen.hide([footerElement], () => { footerElement.style.display = 'none'; }); msg.destroy(() => { document.documentElement.style.backgroundColor = 'inherit'; next(); }); }; }); }, 500); } }); if (opts.compass !== false) { tracker.on('heading', (heading) => { if (!heading) { return; } deg = heading; if (lastPos && !animating) { updateArrow(); } }); } if (opts.demo) { const l = { latitude: shape.center.latitude - 0.0005, longitude: shape.center.longitude, accuracy: 5 }; let h = 360; tracker.emit('heading', h); tracker.emit('position', l); const move = function () { setTimeout(() => { tracker.emit('heading', h); h -= 3; tracker.emit('position', l); l.latitude += 0.00002; if (l.latitude < shape.center.latitude) { move(); } }, 50); }; setTimeout(move, 1000); } };
module.exports = (function(fs){ return function(req, res){ fs.read().then(function(rules){ res.json({ success: true, rules : rules }); }, function(){ res.json({ success: false }); }); }; }(require('./fs.js')));
/*global define*/ define('Scene/ArcGisMapServerAndVworldHybridImageryProvider',[ '../Core/Cartesian2', '../Core/Credit', '../Core/defaultValue', '../Core/defined', '../Core/defineProperties', '../Core/DeveloperError', '../Core/Event', '../Core/GeographicProjection', '../Core/GeographicTilingScheme', '../Core/jsonp', '../Core/Rectangle', '../Core/TileProviderError', '../Core/WebMercatorProjection', '../Core/WebMercatorTilingScheme', '../ThirdParty/when', './DiscardMissingTileImagePolicy', './ImageryProvider' ], function( Cartesian2, Credit, defaultValue, defined, defineProperties, DeveloperError, Event, GeographicProjection, GeographicTilingScheme, jsonp, Rectangle, TileProviderError, WebMercatorProjection, WebMercatorTilingScheme, when, DiscardMissingTileImagePolicy, ImageryProvider) { "use strict"; /** * Provides tiled imagery hosted by an ArcGIS MapServer. By default, the server's pre-cached tiles are * used, if available. * * @alias ArcGisMapServerAndVworldHybridImageryProvider * @constructor * * @param {Object} options Object with the following properties: * @param {String} options.url The URL of the ArcGIS MapServer service. * @param {TileDiscardPolicy} [options.tileDiscardPolicy] The policy that determines if a tile * is invalid and should be discarded. If this value is not specified, a default * {@link DiscardMissingTileImagePolicy} is used for tiled map servers, and a * {@link NeverTileDiscardPolicy} is used for non-tiled map servers. In the former case, * we request tile 0,0 at the maximum tile level and check pixels (0,0), (200,20), (20,200), * (80,110), and (160, 130). If all of these pixels are transparent, the discard check is * disabled and no tiles are discarded. If any of them have a non-transparent color, any * tile that has the same values in these pixel locations is discarded. The end result of * these defaults should be correct tile discarding for a standard ArcGIS Server. To ensure * that no tiles are discarded, construct and pass a {@link NeverTileDiscardPolicy} for this * parameter. * @param {Proxy} [options.proxy] A proxy to use for requests. This object is * expected to have a getURL function which returns the proxied URL, if needed. * @param {Boolean} [options.usePreCachedTilesIfAvailable=true] If true, the server's pre-cached * tiles are used if they are available. If false, any pre-cached tiles are ignored and the * 'export' service is used. * * @see BingMapsImageryProvider * @see GoogleEarthImageryProvider * @see OpenStreetMapImageryProvider * @see SingleTileImageryProvider * @see TileMapServiceImageryProvider * @see WebMapServiceImageryProvider * * @see {@link http://resources.esri.com/help/9.3/arcgisserver/apis/rest/|ArcGIS Server REST API} * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing} * * @example * var esri = new Cesium.ArcGisMapServerAndVworldHybridImageryProvider({ * url: '//services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer' * }); */ var ArcGisMapServerAndVworldHybridImageryProvider = function ArcGisMapServerAndVworldHybridImageryProvider(options) { options = defaultValue(options, {}); if (!defined(options.url)) { throw new DeveloperError('options.url is required.'); } this._url = options.url; this._tileDiscardPolicy = options.tileDiscardPolicy; this._proxy = options.proxy; this._tileWidth = undefined; this._tileHeight = undefined; this._maximumLevel = undefined; this._tilingScheme = undefined; this._credit = undefined; this._useTiles = defaultValue(options.usePreCachedTilesIfAvailable, true); this._rectangle = undefined; this._errorEvent = new Event(); this._ready = false; // Grab the details of this MapServer. var that = this; var metadataError; function metadataSuccess(data) { var tileInfo = data.tileInfo; if (!that._useTiles || !defined(tileInfo)) { that._tileWidth = 256; that._tileHeight = 256; that._tilingScheme = new GeographicTilingScheme(); that._rectangle = that._tilingScheme.rectangle; that._useTiles = false; } else { that._tileWidth = tileInfo.rows; that._tileHeight = tileInfo.cols; if (tileInfo.spatialReference.wkid === 102100 || tileInfo.spatialReference.wkid === 102113) { that._tilingScheme = new WebMercatorTilingScheme(); } else if (data.tileInfo.spatialReference.wkid === 4326) { that._tilingScheme = new GeographicTilingScheme(); } else { var message = 'Tile spatial reference WKID ' + data.tileInfo.spatialReference.wkid + ' is not supported.'; metadataError = TileProviderError.handleError(metadataError, that, that._errorEvent, message, undefined, undefined, undefined, requestMetadata); return; } that._maximumLevel = data.tileInfo.lods.length - 1; if (defined(data.fullExtent)) { var projection = that._tilingScheme.projection; if (defined(data.fullExtent.spatialReference) && defined(data.fullExtent.spatialReference.wkid)) { if (data.fullExtent.spatialReference.wkid === 102100 || data.fullExtent.spatialReference.wkid === 102113) { projection = new WebMercatorProjection(); } else if (data.fullExtent.spatialReference.wkid === 4326) { projection = new GeographicProjection(); } else { var extentMessage = 'fullExtent.spatialReference WKID ' + data.fullExtent.spatialReference.wkid + ' is not supported.'; metadataError = TileProviderError.handleError(metadataError, that, that._errorEvent, extentMessage, undefined, undefined, undefined, requestMetadata); return; } } var sw = projection.unproject(new Cartesian2(data.fullExtent.xmin, data.fullExtent.ymin)); var ne = projection.unproject(new Cartesian2(data.fullExtent.xmax, data.fullExtent.ymax)); that._rectangle = new Rectangle(sw.longitude, sw.latitude, ne.longitude, ne.latitude); } else { that._rectangle = that._tilingScheme.rectangle; } // Install the default tile discard policy if none has been supplied. if (!defined(that._tileDiscardPolicy)) { that._tileDiscardPolicy = new DiscardMissingTileImagePolicy({ missingImageUrl : buildImageUrl(that, 0, 0, that._maximumLevel), pixelsToCheck : [new Cartesian2(0, 0), new Cartesian2(200, 20), new Cartesian2(20, 200), new Cartesian2(80, 110), new Cartesian2(160, 130)], disableCheckIfAllPixelsAreTransparent : true }); } that._useTiles = true; } if (defined(data.copyrightText) && data.copyrightText.length > 0) { that._credit = new Credit(data.copyrightText); } that._ready = true; TileProviderError.handleSuccess(metadataError); } function metadataFailure(e) { var message = 'An error occurred while accessing ' + that._url + '.'; metadataError = TileProviderError.handleError(metadataError, that, that._errorEvent, message, undefined, undefined, undefined, requestMetadata); } function requestMetadata() { var metadata = jsonp(that._url, { parameters : { f : 'json' }, proxy : that._proxy }); when(metadata, metadataSuccess, metadataFailure); } requestMetadata(); }; function buildImageUrl(imageryProvider, x, y, level) { var url; if (imageryProvider._useTiles) { url = imageryProvider._url + '/tile/' + level + '/' + y + '/' + x; } else { var nativeRectangle = imageryProvider._tilingScheme.tileXYToNativeRectangle(x, y, level); var bbox = nativeRectangle.west + '%2C' + nativeRectangle.south + '%2C' + nativeRectangle.east + '%2C' + nativeRectangle.north; url = imageryProvider._url + '/export?'; url += 'bbox=' + bbox; url += '&bboxSR=4326&size=256%2C256&imageSR=4326&format=png&transparent=true&f=image'; } // vworld customizing 시작 //console.log(x, y, level); if ( (level == 6 && (x >= 52 && x <= 56) && (y >= 23 && y <= 26)) || (level == 7 && (x >= 104 && x <= 112) && (y >= 47 && y <= 52)) || (level == 8 && (x >= 210 && x <= 224) && (y >= 93 && y <= 105)) || (level == 9 && (x >= 420 && x <= 448) && (y >= 184 && y <= 211)) || (level == 10 && (x >= 840 && x <= 896) && (y >= 368 && y <= 422)) || (level == 11 && (x >= 1680 && x <= 1792) && (y >= 736 && y <= 844)) || (level == 12 && (x >= 3360 && x <= 3584) && (y >= 1472 && y <= 1688)) || (level == 13 && (x >= 6720 && x <= 7168) && (y >= 2944 && y <= 3376)) || (level == 14 && (x >= 13440 && x <= 14336) && (y >= 5888 && y <= 6752)) || (level == 15 && (x >= 26880 && x <= 28672) && (y >= 11776 && y <= 13504)) || (level == 16 && (x >= 53760 && x <= 57344) && (y >= 23552 && y <= 27008)) || (level == 17 && (x >= 107520 && x <= 114688) && (y >= 47104 && y <= 54016)) || (level == 18 && (x >= 215040 && x <= 229376) && (y >= 94208 && y <= 108032)) ) { url = '//xdworld.vworld.kr:8080/2d/Hybrid/201411/' + level + '/' + x + '/' + y + '.png'; //console.log(url); } // vworld customizing 끝 var proxy = imageryProvider._proxy; if (defined(proxy)) { url = proxy.getURL(url); } return url; } defineProperties(ArcGisMapServerAndVworldHybridImageryProvider.prototype, { /** * Gets the URL of the ArcGIS MapServer. * @memberof ArcGisMapServerAndVworldHybridImageryProvider.prototype * @type {String} * @readonly */ url : { get : function() { return this._url; } }, /** * Gets the proxy used by this provider. * @memberof ArcGisMapServerAndVworldHybridImageryProvider.prototype * @type {Proxy} * @readonly */ proxy : { get : function() { return this._proxy; } }, /** * Gets the width of each tile, in pixels. This function should * not be called before {@link ArcGisMapServerAndVworldHybridImageryProvider#ready} returns true. * @memberof ArcGisMapServerAndVworldHybridImageryProvider.prototype * @type {Number} * @readonly */ tileWidth : { get : function() { if (!this._ready) { throw new DeveloperError('tileWidth must not be called before the imagery provider is ready.'); } return this._tileWidth; } }, /** * Gets the height of each tile, in pixels. This function should * not be called before {@link ArcGisMapServerAndVworldHybridImageryProvider#ready} returns true. * @memberof ArcGisMapServerAndVworldHybridImageryProvider.prototype * @type {Number} * @readonly */ tileHeight: { get : function() { if (!this._ready) { throw new DeveloperError('tileHeight must not be called before the imagery provider is ready.'); } return this._tileHeight; } }, /** * Gets the maximum level-of-detail that can be requested. This function should * not be called before {@link ArcGisMapServerAndVworldHybridImageryProvider#ready} returns true. * @memberof ArcGisMapServerAndVworldHybridImageryProvider.prototype * @type {Number} * @readonly */ maximumLevel : { get : function() { if (!this._ready) { throw new DeveloperError('maximumLevel must not be called before the imagery provider is ready.'); } return this._maximumLevel; } }, /** * Gets the minimum level-of-detail that can be requested. This function should * not be called before {@link ArcGisMapServerAndVworldHybridImageryProvider#ready} returns true. * @memberof ArcGisMapServerAndVworldHybridImageryProvider.prototype * @type {Number} * @readonly */ minimumLevel : { get : function() { if (!this._ready) { throw new DeveloperError('minimumLevel must not be called before the imagery provider is ready.'); } return 0; } }, /** * Gets the tiling scheme used by this provider. This function should * not be called before {@link ArcGisMapServerAndVworldHybridImageryProvider#ready} returns true. * @memberof ArcGisMapServerAndVworldHybridImageryProvider.prototype * @type {TilingScheme} * @readonly */ tilingScheme : { get : function() { if (!this._ready) { throw new DeveloperError('tilingScheme must not be called before the imagery provider is ready.'); } return this._tilingScheme; } }, /** * Gets the rectangle, in radians, of the imagery provided by this instance. This function should * not be called before {@link ArcGisMapServerAndVworldHybridImageryProvider#ready} returns true. * @memberof ArcGisMapServerAndVworldHybridImageryProvider.prototype * @type {Rectangle} * @readonly */ rectangle : { get : function() { if (!this._ready) { throw new DeveloperError('rectangle must not be called before the imagery provider is ready.'); } return this._rectangle; } }, /** * Gets the tile discard policy. If not undefined, the discard policy is responsible * for filtering out "missing" tiles via its shouldDiscardImage function. If this function * returns undefined, no tiles are filtered. This function should * not be called before {@link ArcGisMapServerAndVworldHybridImageryProvider#ready} returns true. * @memberof ArcGisMapServerAndVworldHybridImageryProvider.prototype * @type {TileDiscardPolicy} * @readonly */ tileDiscardPolicy : { get : function() { if (!this._ready) { throw new DeveloperError('tileDiscardPolicy must not be called before the imagery provider is ready.'); } return this._tileDiscardPolicy; } }, /** * Gets an event that is raised when the imagery provider encounters an asynchronous error. By subscribing * to the event, you will be notified of the error and can potentially recover from it. Event listeners * are passed an instance of {@link TileProviderError}. * @memberof ArcGisMapServerAndVworldHybridImageryProvider.prototype * @type {Event} * @readonly */ errorEvent : { get : function() { return this._errorEvent; } }, /** * Gets a value indicating whether or not the provider is ready for use. * @memberof ArcGisMapServerAndVworldHybridImageryProvider.prototype * @type {Boolean} * @readonly */ ready : { get : function() { return this._ready; } }, /** * Gets the credit to display when this imagery provider is active. Typically this is used to credit * the source of the imagery. This function should not be called before {@link ArcGisMapServerAndVworldHybridImageryProvider#ready} returns true. * @memberof ArcGisMapServerAndVworldHybridImageryProvider.prototype * @type {Credit} * @readonly */ credit : { get : function() { return this._credit; } }, /** * Gets a value indicating whether this imagery provider is using pre-cached tiles from the * ArcGIS MapServer. If the imagery provider is not yet ready ({@link ArcGisMapServerAndVworldHybridImageryProvider#ready}), this function * will return the value of `options.usePreCachedTilesIfAvailable`, even if the MapServer does * not have pre-cached tiles. * @memberof ArcGisMapServerAndVworldHybridImageryProvider.prototype * * @type {Boolean} * @readonly * @default true */ usingPrecachedTiles : { get : function() { return this._useTiles; } }, /** * Gets a value indicating whether or not the images provided by this imagery provider * include an alpha channel. If this property is false, an alpha channel, if present, will * be ignored. If this property is true, any images without an alpha channel will be treated * as if their alpha is 1.0 everywhere. When this property is false, memory usage * and texture upload time are reduced. * @memberof ArcGisMapServerAndVworldHybridImageryProvider.prototype * * @type {Boolean} * @readonly * @default true */ hasAlphaChannel : { get : function() { return true; } } }); /** * Gets the credits to be displayed when a given tile is displayed. * * @param {Number} x The tile X coordinate. * @param {Number} y The tile Y coordinate. * @param {Number} level The tile level; * @returns {Credit[]} The credits to be displayed when the tile is displayed. * * @exception {DeveloperError} <code>getTileCredits</code> must not be called before the imagery provider is ready. */ ArcGisMapServerAndVworldHybridImageryProvider.prototype.getTileCredits = function(x, y, level) { return undefined; }; /** * Requests the image for a given tile. This function should * not be called before {@link ArcGisMapServerAndVworldHybridImageryProvider#ready} returns true. * * @param {Number} x The tile X coordinate. * @param {Number} y The tile Y coordinate. * @param {Number} level The tile level. * @returns {Promise} A promise for the image that will resolve when the image is available, or * undefined if there are too many active requests to the server, and the request * should be retried later. The resolved image may be either an * Image or a Canvas DOM object. * * @exception {DeveloperError} <code>requestImage</code> must not be called before the imagery provider is ready. */ ArcGisMapServerAndVworldHybridImageryProvider.prototype.requestImage = function(x, y, level) { if (!this._ready) { throw new DeveloperError('requestImage must not be called before the imagery provider is ready.'); } var url = buildImageUrl(this, x, y, level); return ImageryProvider.loadImage(this, url); }; /** * Picking features is not currently supported by this imagery provider, so this function simply returns * undefined. * * @param {Number} x The tile X coordinate. * @param {Number} y The tile Y coordinate. * @param {Number} level The tile level. * @param {Number} longitude The longitude at which to pick features. * @param {Number} latitude The latitude at which to pick features. * @return {Promise} A promise for the picked features that will resolve when the asynchronous * picking completes. The resolved value is an array of {@link ImageryLayerFeatureInfo} * instances. The array may be empty if no features are found at the given location. * It may also be undefined if picking is not supported. */ ArcGisMapServerAndVworldHybridImageryProvider.prototype.pickFeatures = function() { return undefined; }; return ArcGisMapServerAndVworldHybridImageryProvider; });
var util = require('util'); var Logger = require('devnull'); var logger = new Logger({namespacing:0}); var Reservation = require('../models/Reservation'); var User = require('../models/User'); ReservationController = function(app,mongoose,config){ var Reservation = mongoose.model('Reservation'); var User = mongoose.model('User'); /* List all reservations from database */ app.post('/reservation_query',function(req,res){ var start = req.body.start; var end = req.body.end; if(req.body.user){ var user = req.body.user; Reservation.count({username:user, date : { $gte: start, $lte: end }},function(err,cnt){ if(cnt<1){ res.json({"status":"0"}); }else{ Reservation.find({username:user, date : { $gte: start, $lte: end }},function(err,data){ res.json({"status":"1",data:data}); }); } }); }else{ Reservation.count({date : { $gte: start, $lte: end }},function(err,cnt){ if(cnt<1){ res.json({"status":"0"}); }else{ Reservation.find({date : { $gte: start, $lte: end }},function(err,data){ res.json({"status":"1",data:data}); }); } }); } }); app.get('/rezervasyon-sorgula',function(req,res){ if(req.session.user.auth>0){ var data = { activeUser: req.session.user.username, auth: req.session.user.auth }; res.render('reservation-query-view',{data:data}); }else res.render('unauthorized'); }); /* check reservation by date */ app.post('/check_reservation',function(req,res){ util.log(req.method + " request to url: " + req.route.path); Reservation.count({dateStr : req.body.date, type : req.body.type, user : req.session.user.name},function(err,data){ if(err) res.json({"status":err}); else if(data>0) res.json({"status":"1"}); else{ Reservation.count({dateStr:req.body.date,type:req.body.type},function(err,cnt){ if(cnt>0) res.json({"status":"0","others":"1"}); else res.json({"status":"0","others":"0"}); }); } }); }); app.post('/check_single_reservation',function(req,res){ Reservation.count({username:req.body.user,dateStr:req.body.date},function(err,data){ if(data>0){ Reservation.find({username:req.body.user,dateStr: req.body.date},function(err,result){ res.json({"status":"1",data:result}); }); }else{ User.findOne({username:req.body.user},function(err,data){ res.json({"status":"0",fullname:data.name}); }); } }); }); app.post('/reservations',function(req,res){ Reservation.find({dateStr:req.body.date,type:req.body.type},function(err,data){ if(!err) res.json({data:data}); }); }); /* handling post request for create new reservation */ app.post('/reservation/create',function(req,res,next){ util.log(req.method + " request to url : " + req.route.path); var reservationModel = new Reservation(); reservationModel.dateStr = req.body.dateStr; reservationModel.type = req.body.type; reservationModel.date = req.body.date; if(req.body.user){ reservationModel.username = req.body.user; reservationModel.user = req.body.fullName; } else{ reservationModel.username = req.session.user.username; reservationModel.user = req.session.user.name; } reservationModel.save(function(err) { if(!err) res.json({"status":"ok"}); }); }); app.post('/reservation/delete',function(req,res,next){ util.log(req.method + " request to url : " + req.route.path); if(req.body.user){ if(req.session.user.auth>0){ util.log("yetki denetimini gecti"); Reservation.remove({username:req.body.user,dateStr:req.body.date,type:req.body.type},function(err){ util.log("sorgunun icinde"); if(!err) res.json({"status":"ok"}); }); }else res.json({"status":"error, not authorized request"}); }else{ util.log("yetki denetiminde sıçtı"); Reservation.remove({user:req.session.user.name,dateStr:req.body.date,type:req.body.type},function(err){ if(!err) res.json({"status":"ok"}); }); } }); app.get('/rezervasyon-guncelle',function(req,res){ if(req.session.user.auth>0){ var data = { activeUser: req.session.user.username, auth: req.session.user.auth }; res.render('reservation-update',{data:data}); }else res.render('unauthorized'); }); /* handling post requtest for update reservation */ app.post('/reservation/update',function(req,res,next){ util.log(req.method + " request to url : " + req.route.path); var ID = req.params('ID'); var date = req.params('date'); var type = req.params('type'); var user = req.session.user.username; var reservationModel = new Reservation(); reservationModel.date = date; reservationModel.type = type; reservationModel.user = user; reservationModel.findByIdAndUpdate(ID, { $set: { date: date, type: type }}, function (err, reservation) { if (err) return handleError(err); res.render('reservation-list',{reservation:reservation}); }); }); } module.exports = ReservationController;
$(function() { $('input,select').not('.btn').attr('disabled', 'disabled'); }); function print_request() { create_print_area(person_name); window.print(); }
/*global */ var trimString; /* Description: */ trimString = function(s) { return s.replace(/^\s\s*/, '').replace(/\s\s*$/, ''); };
import { get } from 'ember-metal/property_get'; import EmberError from 'ember-metal/error'; import run from 'ember-metal/run_loop'; import jQuery from 'ember-views/system/jquery'; import Test from 'ember-testing/test'; import RSVP from 'ember-runtime/ext/rsvp'; import isEnabled from 'ember-metal/features'; /** @module ember @submodule ember-testing */ var helper = Test.registerHelper; var asyncHelper = Test.registerAsyncHelper; var keyboardEventTypes, mouseEventTypes, buildKeyboardEvent, buildMouseEvent, buildBasicEvent, fireEvent, focus; if (isEnabled('ember-test-helpers-fire-native-events')) { let defaultEventOptions = { canBubble: true, cancelable: true }; keyboardEventTypes = ['keydown', 'keypress', 'keyup']; mouseEventTypes = ['click', 'mousedown', 'mouseup', 'dblclick', 'mouseenter', 'mouseleave', 'mousemove', 'mouseout', 'mouseover']; buildKeyboardEvent = function buildKeyboardEvent(type, options = {}) { let event; try { event = document.createEvent('KeyEvents'); let eventOpts = jQuery.extend({}, defaultEventOptions, options); event.initKeyEvent( type, eventOpts.canBubble, eventOpts.cancelable, window, eventOpts.ctrlKey, eventOpts.altKey, eventOpts.shiftKey, eventOpts.metaKey, eventOpts.keyCode, eventOpts.charCode ); } catch (e) { event = buildBasicEvent(type, options); } return event; }; buildMouseEvent = function buildMouseEvent(type, options = {}) { let event; try { event = document.createEvent('MouseEvents'); let eventOpts = jQuery.extend({}, defaultEventOptions, options); event.initMouseEvent( type, eventOpts.canBubble, eventOpts.cancelable, window, eventOpts.detail, eventOpts.screenX, eventOpts.screenY, eventOpts.clientX, eventOpts.clientY, eventOpts.ctrlKey, eventOpts.altKey, eventOpts.shiftKey, eventOpts.metaKey, eventOpts.button, eventOpts.relatedTarget); } catch (e) { event = buildBasicEvent(type, options); } return event; }; buildBasicEvent = function buildBasicEvent(type, options = {}) { let event = document.createEvent('Events'); event.initEvent(type, true, true); jQuery.extend(event, options); return event; }; fireEvent = function fireEvent(element, type, options = {}) { if (!element) { return; } let event; if (keyboardEventTypes.indexOf(type) > -1) { event = buildKeyboardEvent(type, options); } else if (mouseEventTypes.indexOf(type) > -1) { let rect = element.getBoundingClientRect(); let x = rect.left + 1; let y = rect.top + 1; let simulatedCoordinates = { screenX: x + 5, screenY: y + 95, clientX: x, clientY: y }; event = buildMouseEvent(type, jQuery.extend(simulatedCoordinates, options)); } else { event = buildBasicEvent(type, options); } element.dispatchEvent(event); }; focus = function focus(el) { if (!el) { return; } let $el = jQuery(el); if ($el.is(':input, [contenteditable=true]')) { let type = $el.prop('type'); if (type !== 'checkbox' && type !== 'radio' && type !== 'hidden') { run(null, function() { // Firefox does not trigger the `focusin` event if the window // does not have focus. If the document doesn't have focus just // use trigger('focusin') instead. if (!document.hasFocus || document.hasFocus()) { el.focus(); } else { $el.trigger('focusin'); } }); } } }; } else { focus = function focus(el) { if (el && el.is(':input, [contenteditable=true]')) { var type = el.prop('type'); if (type !== 'checkbox' && type !== 'radio' && type !== 'hidden') { run(el, function() { // Firefox does not trigger the `focusin` event if the window // does not have focus. If the document doesn't have focus just // use trigger('focusin') instead. if (!document.hasFocus || document.hasFocus()) { this.focus(); } else { this.trigger('focusin'); } }); } } }; fireEvent = function fireEvent(element, type, options) { var event = jQuery.Event(type, options); jQuery(element).trigger(event); }; } function currentRouteName(app) { var routingService = app.__container__.lookup('service:-routing'); return get(routingService, 'currentRouteName'); } function currentPath(app) { var routingService = app.__container__.lookup('service:-routing'); return get(routingService, 'currentPath'); } function currentURL(app) { var router = app.__container__.lookup('router:main'); return get(router, 'location').getURL(); } function pauseTest() { Test.adapter.asyncStart(); return new RSVP.Promise(function() { }, 'TestAdapter paused promise'); } function visit(app, url) { var router = app.__container__.lookup('router:main'); var shouldHandleURL = false; app.boot().then(function() { router.location.setURL(url); if (shouldHandleURL) { run(app.__deprecatedInstance__, 'handleURL', url); } }); if (app._readinessDeferrals > 0) { router['initialURL'] = url; run(app, 'advanceReadiness'); delete router['initialURL']; } else { shouldHandleURL = true; } return app.testHelpers.wait(); } function click(app, selector, context) { let $el = app.testHelpers.findWithAssert(selector, context); let el = $el[0]; run(null, fireEvent, el, 'mousedown'); focus(el); run(null, fireEvent, el, 'mouseup'); run(null, fireEvent, el, 'click'); return app.testHelpers.wait(); } function triggerEvent(app, selector, contextOrType, typeOrOptions, possibleOptions) { var arity = arguments.length; var context, type, options; if (arity === 3) { // context and options are optional, so this is // app, selector, type context = null; type = contextOrType; options = {}; } else if (arity === 4) { // context and options are optional, so this is if (typeof typeOrOptions === 'object') { // either // app, selector, type, options context = null; type = contextOrType; options = typeOrOptions; } else { // or // app, selector, context, type context = contextOrType; type = typeOrOptions; options = {}; } } else { context = contextOrType; type = typeOrOptions; options = possibleOptions; } var $el = app.testHelpers.findWithAssert(selector, context); var el = $el[0]; run(null, fireEvent, el, type, options); return app.testHelpers.wait(); } function keyEvent(app, selector, contextOrType, typeOrKeyCode, keyCode) { var context, type; if (typeof keyCode === 'undefined') { context = null; keyCode = typeOrKeyCode; type = contextOrType; } else { context = contextOrType; type = typeOrKeyCode; } return app.testHelpers.triggerEvent(selector, context, type, { keyCode: keyCode, which: keyCode }); } function fillIn(app, selector, contextOrText, text) { var $el, el, context; if (typeof text === 'undefined') { text = contextOrText; } else { context = contextOrText; } $el = app.testHelpers.findWithAssert(selector, context); el = $el[0]; focus(el); run(function() { $el.val(text); fireEvent(el, 'input'); fireEvent(el, 'change'); }); return app.testHelpers.wait(); } function findWithAssert(app, selector, context) { var $el = app.testHelpers.find(selector, context); if ($el.length === 0) { throw new EmberError('Element ' + selector + ' not found.'); } return $el; } function find(app, selector, context) { var $el; context = context || get(app, 'rootElement'); $el = app.$(selector, context); return $el; } function andThen(app, callback) { return app.testHelpers.wait(callback(app)); } function wait(app, value) { return new RSVP.Promise(function(resolve) { var router = app.__container__.lookup('router:main'); // Every 10ms, poll for the async thing to have finished var watcher = setInterval(function() { // 1. If the router is loading, keep polling var routerIsLoading = router.router && !!router.router.activeTransition; if (routerIsLoading) { return; } // 2. If there are pending Ajax requests, keep polling if (Test.pendingAjaxRequests) { return; } // 3. If there are scheduled timers or we are inside of a run loop, keep polling if (run.hasScheduledTimers() || run.currentRunLoop) { return; } if (Test.waiters && Test.waiters.any(function(waiter) { var context = waiter[0]; var callback = waiter[1]; return !callback.call(context); })) { return; } // Stop polling clearInterval(watcher); // Synchronously resolve the promise run(null, resolve, value); }, 10); }); } /** Loads a route, sets up any controllers, and renders any templates associated with the route as though a real user had triggered the route change while using your app. Example: ```javascript visit('posts/index').then(function() { // assert something }); ``` @method visit @param {String} url the name of the route @return {RSVP.Promise} @public */ asyncHelper('visit', visit); /** Clicks an element and triggers any actions triggered by the element's `click` event. Example: ```javascript click('.some-jQuery-selector').then(function() { // assert something }); ``` @method click @param {String} selector jQuery selector for finding element on the DOM @return {RSVP.Promise} @public */ asyncHelper('click', click); /** Simulates a key event, e.g. `keypress`, `keydown`, `keyup` with the desired keyCode Example: ```javascript keyEvent('.some-jQuery-selector', 'keypress', 13).then(function() { // assert something }); ``` @method keyEvent @param {String} selector jQuery selector for finding element on the DOM @param {String} type the type of key event, e.g. `keypress`, `keydown`, `keyup` @param {Number} keyCode the keyCode of the simulated key event @return {RSVP.Promise} @since 1.5.0 @public */ asyncHelper('keyEvent', keyEvent); /** Fills in an input element with some text. Example: ```javascript fillIn('#email', 'you@example.com').then(function() { // assert something }); ``` @method fillIn @param {String} selector jQuery selector finding an input element on the DOM to fill text with @param {String} text text to place inside the input element @return {RSVP.Promise} @public */ asyncHelper('fillIn', fillIn); /** Finds an element in the context of the app's container element. A simple alias for `app.$(selector)`. Example: ```javascript var $el = find('.my-selector'); ``` @method find @param {String} selector jQuery string selector for element lookup @return {Object} jQuery object representing the results of the query @public */ helper('find', find); /** Like `find`, but throws an error if the element selector returns no results. Example: ```javascript var $el = findWithAssert('.doesnt-exist'); // throws error ``` @method findWithAssert @param {String} selector jQuery selector string for finding an element within the DOM @return {Object} jQuery object representing the results of the query @throws {Error} throws error if jQuery object returned has a length of 0 @public */ helper('findWithAssert', findWithAssert); /** Causes the run loop to process any pending events. This is used to ensure that any async operations from other helpers (or your assertions) have been processed. This is most often used as the return value for the helper functions (see 'click', 'fillIn','visit',etc). Example: ```javascript Ember.Test.registerAsyncHelper('loginUser', function(app, username, password) { visit('secured/path/here') .fillIn('#username', username) .fillIn('#password', password) .click('.submit') return app.testHelpers.wait(); }); @method wait @param {Object} value The value to be returned. @return {RSVP.Promise} @public */ asyncHelper('wait', wait); asyncHelper('andThen', andThen); /** Returns the currently active route name. Example: ```javascript function validateRouteName() { equal(currentRouteName(), 'some.path', "correct route was transitioned into."); } visit('/some/path').then(validateRouteName) ``` @method currentRouteName @return {Object} The name of the currently active route. @since 1.5.0 @public */ helper('currentRouteName', currentRouteName); /** Returns the current path. Example: ```javascript function validateURL() { equal(currentPath(), 'some.path.index', "correct path was transitioned into."); } click('#some-link-id').then(validateURL); ``` @method currentPath @return {Object} The currently active path. @since 1.5.0 @public */ helper('currentPath', currentPath); /** Returns the current URL. Example: ```javascript function validateURL() { equal(currentURL(), '/some/path', "correct URL was transitioned into."); } click('#some-link-id').then(validateURL); ``` @method currentURL @return {Object} The currently active URL. @since 1.5.0 @public */ helper('currentURL', currentURL); /** Pauses the current test - this is useful for debugging while testing or for test-driving. It allows you to inspect the state of your application at any point. Example (The test will pause before clicking the button): ```javascript visit('/') return pauseTest(); click('.btn'); ``` @since 1.9.0 @method pauseTest @return {Object} A promise that will never resolve @public */ helper('pauseTest', pauseTest); /** Triggers the given DOM event on the element identified by the provided selector. Example: ```javascript triggerEvent('#some-elem-id', 'blur'); ``` This is actually used internally by the `keyEvent` helper like so: ```javascript triggerEvent('#some-elem-id', 'keypress', { keyCode: 13 }); ``` @method triggerEvent @param {String} selector jQuery selector for finding element on the DOM @param {String} [context] jQuery selector that will limit the selector argument to find only within the context's children @param {String} type The event type to be triggered. @param {Object} [options] The options to be passed to jQuery.Event. @return {RSVP.Promise} @since 1.5.0 @public */ asyncHelper('triggerEvent', triggerEvent);
import Rx from 'rxjs'; import createActions from './createActions'; const result = createActions(["foo", "bar"]); test('Subjects are available', () => { expect(result.actions.foo$).toBeInstanceOf(Rx.Subject); expect(result.actions.bar$).toBeInstanceOf(Rx.Subject); }); test('actions are available', () => { expect(result.foo).toBeInstanceOf(Function); expect(result.bar).toBeInstanceOf(Function); }); test('wired', () => { result.actions.foo$.subscribe(x => { expect(x.a).toBe(1); expect(x.b).toBe(2); }); result.foo({ a: 1, b: 2}); })
var loadFile = function(event) { var output = document.getElementById('preview_imagem'); output.src = URL.createObjectURL(event.target.files[0]); };
import React, { Component } from 'react'; import SearchBar from '../containers/SearchBar'; import WeatherList from '../containers/WeatherList'; export default class App extends Component { render() { return ( <div> <SearchBar/> <WeatherList/> </div> ); } }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js (function(global) { global.ng = global.ng || {}; global.ng.common = global.ng.common || {}; global.ng.common.locales = global.ng.common.locales || {}; var u = undefined; function plural(n) { var i = Math.floor(Math.abs(n)), v = n.toString().replace(/^[^.]*\.?/, '').length; if (i === 1 && v === 0) return 1; return 5; } global.ng.common.locales['en-tv'] = [ 'en-TV', [['a', 'p'], ['am', 'pm'], u], [['am', 'pm'], u, u], [ ['S', 'M', 'T', 'W', 'T', 'F', 'S'], ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'] ], u, [ ['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'], ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ] ], u, [['B', 'A'], ['BC', 'AD'], ['Before Christ', 'Anno Domini']], 1, [6, 0], ['dd/MM/y', 'd MMM y', 'd MMMM y', 'EEEE, d MMMM y'], ['HH:mm', 'HH:mm:ss', 'HH:mm:ss z', 'HH:mm:ss zzzz'], ['{1}, {0}', u, '{1} \'at\' {0}', u], ['.', ',', ';', '%', '+', '-', 'E', '×', '‰', '∞', 'NaN', ':'], ['#,##0.###', '#,##0%', '¤#,##0.00', '#E0'], 'AUD', '$', 'Australian Dollar', {'AUD': ['$'], 'JPY': ['JP¥', '¥'], 'USD': ['US$', '$']}, 'ltr', plural, [ [ ['mi', 'n', 'in the morning', 'in the afternoon', 'in the evening', 'at night'], ['midnight', 'noon', 'in the morning', 'in the afternoon', 'in the evening', 'at night'], u ], [['midnight', 'noon', 'morning', 'afternoon', 'evening', 'night'], u, u], [ '00:00', '12:00', ['06:00', '12:00'], ['12:00', '18:00'], ['18:00', '21:00'], ['21:00', '06:00'] ] ] ]; })(typeof globalThis !== 'undefined' && globalThis || typeof global !== 'undefined' && global || typeof window !== 'undefined' && window);
// NOTE: We must not cache references to membersService.api // as it is a getter and may change during runtime. const Promise = require('bluebird'); const moment = require('moment-timezone'); const errors = require('@tryghost/errors'); const models = require('../../models'); const membersService = require('../../services/members'); const settingsCache = require('../../../shared/settings-cache'); const tpl = require('@tryghost/tpl'); const messages = { memberNotFound: 'Member not found.', stripeNotConnected: { message: 'Missing Stripe connection.', context: 'Attempting to import members with Stripe data when there is no Stripe account connected.', help: 'You need to connect to Stripe to import Stripe customers. ' }, memberAlreadyExists: { message: 'Member already exists', context: 'Attempting to {action} member with existing email address.' }, stripeCustomerNotFound: { context: 'Missing Stripe customer.', help: 'Make sure you’re connected to the correct Stripe Account.' }, resourceNotFound: '{resource} not found.' }; const allowedIncludes = ['email_recipients']; module.exports = { docName: 'members', hasActiveStripeSubscriptions: { permissions: { method: 'browse' }, async query() { const hasActiveStripeSubscriptions = await membersService.api.hasActiveStripeSubscriptions(); return { hasActiveStripeSubscriptions }; } }, browse: { options: [ 'limit', 'fields', 'filter', 'order', 'debug', 'page', 'search' ], permissions: true, validation: {}, async query(frame) { frame.options.withRelated = ['labels', 'stripeSubscriptions', 'stripeSubscriptions.customer']; const page = await membersService.api.members.list(frame.options); return page; } }, read: { options: [ 'include' ], headers: {}, data: [ 'id', 'email' ], validation: { options: { include: { values: allowedIncludes } } }, permissions: true, async query(frame) { const defaultWithRelated = ['labels', 'stripeSubscriptions', 'stripeSubscriptions.customer']; if (!frame.options.withRelated) { frame.options.withRelated = defaultWithRelated; } else { frame.options.withRelated = frame.options.withRelated.concat(defaultWithRelated); } if (frame.options.withRelated.includes('email_recipients')) { frame.options.withRelated.push('email_recipients.email'); } let model = await membersService.api.members.get(frame.data, frame.options); if (!model) { throw new errors.NotFoundError({ message: tpl(messages.memberNotFound) }); } return model; } }, add: { statusCode: 201, headers: {}, options: [ 'send_email', 'email_type' ], validation: { data: { email: {required: true} }, options: { email_type: { values: ['signin', 'signup', 'subscribe'] } } }, permissions: true, async query(frame) { let member; frame.options.withRelated = ['stripeSubscriptions', 'stripeSubscriptions.customer']; try { if (!membersService.config.isStripeConnected() && (frame.data.members[0].stripe_customer_id || frame.data.members[0].comped)) { const property = frame.data.members[0].comped ? 'comped' : 'stripe_customer_id'; throw new errors.ValidationError({ message: tpl(messages.stripeNotConnected.message), context: tpl(messages.stripeNotConnected.context), help: tpl(messages.stripeNotConnected.help), property }); } member = await membersService.api.members.create(frame.data.members[0], frame.options); if (frame.data.members[0].stripe_customer_id) { await membersService.api.members.linkStripeCustomer({ customer_id: frame.data.members[0].stripe_customer_id, member_id: member.id }); } if (frame.data.members[0].comped) { await membersService.api.members.setComplimentarySubscription(member); } if (frame.options.send_email) { await membersService.api.sendEmailWithMagicLink({email: member.get('email'), requestedType: frame.options.email_type}); } return member; } catch (error) { if (error.code && error.message.toLowerCase().indexOf('unique') !== -1) { throw new errors.ValidationError({ message: tpl(messages.memberAlreadyExists.message), context: tpl(messages.memberAlreadyExists.context, { action: 'add' }) }); } // NOTE: failed to link Stripe customer/plan/subscription or have thrown custom Stripe connection error. // It's a bit ugly doing regex matching to detect errors, but it's the easiest way that works without // introducing additional logic/data format into current error handling const isStripeLinkingError = error.message && (error.message.match(/customer|plan|subscription/g)); if (member && isStripeLinkingError) { if (error.message.indexOf('customer') && error.code === 'resource_missing') { error.message = `Member not imported. ${error.message}`; error.context = tpl(messages.stripeCustomerNotFound.context); error.help = tpl(messages.stripeCustomerNotFound.help); } await membersService.api.members.destroy({ id: member.get('id') }, frame.options); } throw error; } } }, edit: { statusCode: 200, headers: {}, options: [ 'id' ], validation: { options: { id: { required: true } } }, permissions: true, async query(frame) { try { frame.options.withRelated = ['stripeSubscriptions']; const member = await membersService.api.members.update(frame.data.members[0], frame.options); const hasCompedSubscription = !!member.related('stripeSubscriptions').find(sub => sub.get('plan_nickname') === 'Complimentary' && sub.get('status') === 'active'); if (typeof frame.data.members[0].comped === 'boolean') { if (frame.data.members[0].comped && !hasCompedSubscription) { await membersService.api.members.setComplimentarySubscription(member); } else if (!(frame.data.members[0].comped) && hasCompedSubscription) { await membersService.api.members.cancelComplimentarySubscription(member); } await member.load(['stripeSubscriptions']); } await member.load(['stripeSubscriptions.customer']); return member; } catch (error) { if (error.code && error.message.toLowerCase().indexOf('unique') !== -1) { throw new errors.ValidationError({ message: tpl(messages.memberAlreadyExists.message), context: tpl(messages.memberAlreadyExists.context, { action: 'edit' }) }); } throw error; } } }, editSubscription: { statusCode: 200, headers: {}, options: [ 'id', 'subscription_id' ], data: [ 'cancel_at_period_end' ], validation: { options: { id: { required: true }, subscription_id: { required: true } }, data: { cancel_at_period_end: { required: true } } }, permissions: { method: 'edit' }, async query(frame) { await membersService.api.members.updateSubscription({ id: frame.options.id, subscription: { subscription_id: frame.options.subscription_id, cancel_at_period_end: frame.data.cancel_at_period_end } }); let model = await membersService.api.members.get({id: frame.options.id}, { withRelated: ['labels', 'stripeSubscriptions', 'stripeSubscriptions.customer'] }); if (!model) { throw new errors.NotFoundError({ message: tpl(messages.memberNotFound) }); } return model; } }, destroy: { statusCode: 204, headers: {}, options: [ 'id', 'cancel' ], validation: { options: { id: { required: true } } }, permissions: true, async query(frame) { frame.options.require = true; frame.options.cancelStripeSubscriptions = frame.options.cancel; await Promise.resolve(membersService.api.members.destroy({ id: frame.options.id }, frame.options)).catch(models.Member.NotFoundError, () => { throw new errors.NotFoundError({ message: tpl(messages.resourceNotFound, { resource: 'Member' }) }); }); return null; } }, exportCSV: { options: [ 'limit', 'filter', 'search' ], headers: { disposition: { type: 'csv', value() { const datetime = (new Date()).toJSON().substring(0, 10); return `members.${datetime}.csv`; } } }, response: { format: 'plain' }, permissions: { method: 'browse' }, validation: {}, async query(frame) { frame.options.withRelated = ['labels', 'stripeSubscriptions', 'stripeSubscriptions.customer']; const page = await membersService.api.members.list(frame.options); return page; } }, importCSV: { statusCode(result) { if (result && result.meta && result.meta.stats && result.meta.stats.imported !== null) { return 201; } else { return 202; } }, permissions: { method: 'add' }, async query(frame) { const siteTimezone = settingsCache.get('timezone'); const importLabel = { name: `Import ${moment().tz(siteTimezone).format('YYYY-MM-DD HH:mm')}` }; const globalLabels = [importLabel].concat(frame.data.labels); const pathToCSV = frame.file.path; const headerMapping = frame.data.mapping; return membersService.processImport({ pathToCSV, headerMapping, globalLabels, importLabel, LabelModel: models.Label, user: { email: frame.user.get('email') } }); } }, stats: { options: [ 'days' ], permissions: { method: 'browse' }, validation: { options: { days: { values: ['30', '90', '365', 'all-time'] } } }, async query(frame) { const days = frame.options.days === 'all-time' ? 'all-time' : Number(frame.options.days || 30); return await membersService.stats.fetch(days); } } };
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var NullCache = /** @class */ (function () { function NullCache() { } NullCache.prototype.retrieve = function (correlationId, key, callback) { callback(null, null); }; NullCache.prototype.store = function (correlationId, key, value, timeout, callback) { callback(null, value); }; NullCache.prototype.remove = function (correlationId, key, callback) { callback(null); }; return NullCache; }()); exports.NullCache = NullCache; //# sourceMappingURL=NullCache.js.map
;(function ($, Formstone, undefined) { "use strict"; /** * @method private * @name construct * @description Builds instance. * @param data [object] "Instance data" */ function construct(data) { data.mq = "(max-width:" + (data.maxWidth === Infinity ? "100000px" : data.maxWidth) + ")"; var html = ""; html += '<button type="button" class="' + [RawClasses.control, RawClasses.control_previous].join(" ") + '">' + data.labels.previous + '</button>'; html += '<button type="button" class="' + [RawClasses.control, RawClasses.control_next].join(" ") + '">' + data.labels.next + '</button>'; html += '<div class="' + RawClasses.position + '">'; html += '<span class="' + RawClasses.current + '">0</span>'; html += ' ' + data.labels.count + ' '; html += '<span class="' + RawClasses.total + '">0</span>'; html += '</div>'; html += '<select class="' + RawClasses.select + '" tab-index="-1"></select>'; this.addClass(RawClasses.base) .wrapInner('<div class="' + RawClasses.pages + '"></div>') .prepend(html); data.$controls = this.find(Classes.control); data.$pages = this.find(Classes.pages); data.$items = data.$pages.children().addClass(RawClasses.page); data.$position = this.find(Classes.position); data.$select = this.find(Classes.select); data.index = -1; data.total = data.$items.length - 1; var index = data.$items.index(data.$items.filter(Classes.active)); data.$items.eq(0) .addClass(RawClasses.first) .after('<span class="' + RawClasses.ellipsis + '">&hellip;</span>') .end() .eq(data.total) .addClass(RawClasses.last) .before('<span class="' + RawClasses.ellipsis + '">&hellip;</span>'); data.$ellipsis = data.$pages.find(Classes.ellipsis); buildMobilePages(data); this.on(Events.clickTouchStart, Classes.page, data, onPageClick) .on(Events.clickTouchStart, Classes.control, data, onControlClick) .on(Events.clickTouchStart, Classes.position, data, onPositionClick) .on(Events.change, Classes.select, onPageSelect); $.mediaquery("bind", data.rawGuid, data.mq, { enter: function() { data.$el.addClass(RawClasses.mobile); }, leave: function() { data.$el.removeClass(RawClasses.mobile); } }); updatePage(data, index); } /** * @method private * @name destruct * @description Tears down instance. * @param data [object] "Instance data" */ function destruct(data) { $.mediaquery("unbind", data.rawGuid); data.$controls.remove(); data.$ellipsis.remove(); data.$select.remove(); data.$position.remove(); data.$items.removeClass( [RawClasses.page, RawClasses.active, RawClasses.visible, RawClasses.first, RawClasses.last].join(" ") ) .unwrap(); this.removeClass(RawClasses.base) .off(Events.namespace); } /** * @method * @name jump * @description Jump instance of plugin to specific page * @example $(".target").pagination("jump", 1); */ function jump(data, index) { data.$items.eq(index).trigger(Events.raw.click); } /** * @method private * @name onControlClick * @description Traverses pages * @param e [object] "Event data" */ function onControlClick(e) { Functions.killEvent(e); var data = e.data, index = data.index + ( $(e.currentTarget).hasClass(RawClasses.control_previous) ? -1 : 1 ); if (index >= 0) { data.$items.eq(index).trigger(Events.raw.click); } } /** * @method private * @name onPageSelect * @description Jumps to a page * @param e [object] "Event data" */ function onPageSelect(e) { Functions.killEvent(e); var data = e.data, $target = $(e.currentTarget), index = parseInt($target.val(), 10); data.$items.eq(index).trigger(Events.raw.click); } /** * @method private * @name onPageClick * @description Jumps to a page * @param e [object] "Event data" */ function onPageClick(e) { Functions.killEvent(e); var data = e.data, index = data.$items.index( $(e.currentTarget) ); /* if (data.ajax) { Functions.killEvent(e); } */ updatePage(data, index); } /** * @method private * @name onPositionClick * @description Opens mobile select * @param e [object] "Event data" */ function onPositionClick(e) { Functions.killEvent(e); var data = e.data; if (Formstone.isMobile && !Formstone.isFirefoxMobile) { // Only open select on non-firefox mobile var el = data.$select[0]; if (window.document.createEvent) { // All var evt = window.document.createEvent("MouseEvents"); evt.initMouseEvent("mousedown", false, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); el.dispatchEvent(evt); } else if (el.fireEvent) { // IE el.fireEvent("onmousedown"); } } } /** * @method private * @name updatePage * @description Updates pagination state * @param data [object] "Instance data" * @param index [int] "New page index" */ function updatePage(data, index) { if (index < 0) { index = 0; } if (index > data.total) { index = data.total; } if (index !== data.index) { data.index = index; var start = data.index - data.visible, end = data.index + (data.visible + 1); if (start < 0) { start = 0; } if (end > data.total) { end = data.total; } data.$items.removeClass(RawClasses.visible) .filter(Classes.active) .removeClass(RawClasses.active) .end() .eq(data.index) .addClass(RawClasses.active) .end() .slice(start, end) .addClass(RawClasses.visible); data.$position.find(Classes.current) .text(data.index + 1) .end() .find(Classes.total) .text(data.total + 1); data.$select.val(data.index); // controls data.$controls.removeClass(Classes.disabled); if (index === 0) { data.$controls.filter(Classes.control_previous).addClass(RawClasses.disabled); } if (index === data.total) { data.$controls.filter(Classes.control_next).addClass(RawClasses.disabled); } // elipsis data.$ellipsis.removeClass(RawClasses.visible); if (index > data.visible + 1) { data.$ellipsis.eq(0).addClass(RawClasses.visible); } if (index < data.total - data.visible - 1) { data.$ellipsis.eq(1).addClass(RawClasses.visible); } // Update data.$el.trigger(Events.update, [ data.index ]); } } /** * @method private * @name buildMobilePages * @description Builds options for mobile select * @param data [object] "Instance data" */ function buildMobilePages(data) { var html = ''; for (var i = 0; i <= data.total; i++) { html += '<option value="' + i + '"'; if (i === data.index) { html += 'selected="selected"'; } html += '>Page ' + (i+1) + '</option>'; } data.$select.html(html); } /** * @plugin * @name Pagination * @description A jQuery plugin for simple pagination. * @type widget * @dependency core.js * @dependency mediaquery.js */ var Plugin = Formstone.Plugin("pagination", { widget: true, /** * @options * @param ajax [boolean] <false> "Flag to disable default click actions" * @param customClass [string] <''> "Class applied to instance" * @param labels.close [string] <'Close'> "Close button text" * @param labels.count [string] <'of'> "Gallery count separator text" * @param labels.next [string] <'Next'> "Gallery control text" * @param labels.previous [string] <'Previous'> "Gallery control text" * @param maxWidth [string] <'980px'> "Width at which to auto-disable plugin" * @param visible [int] <2> "Visible pages before and after current page" */ defaults: { ajax : false, customClass : "", labels: { count : "of", next : "Next", previous : "Previous" }, maxWidth : "740px", visible : 2 }, classes: [ "pages", "page", "active", "first", "last", "visible", "ellipsis", "control", "control_previous", "control_next", "position", "select", "mobile", "current", "total" ], /** * @events * @event update.pagination "Page updated" */ events: { update : "update" }, methods: { _construct : construct, _destruct : destruct } }), // Localize References Classes = Plugin.classes, RawClasses = Classes.raw, Events = Plugin.events, Functions = Plugin.functions; })(jQuery, Formstone);
// Include gulp var gulp = require('gulp'); var rename = require( 'gulp-rename' ); var uglify = require( 'gulp-uglify' ); var minifyCss = require('gulp-minify-css'); var usemin = require('gulp-usemin'); var del = require('del'); var runSequence = require('run-sequence'); var rm = require('gulp-rimraf'); var Q = require('q'); var concat = require('gulp-concat'); // Include plugins var plugins = require("gulp-load-plugins")({ pattern: ['gulp-*', 'gulp.*', 'main-bower-files'], replaceString: /\bgulp[\-.]/ }); gulp.task('js_minify', function() { // Define default destination folder //console.log('js start'); var deferred = Q.defer(); var dest = 'js/'; //gulp.src( dest , { buffer: false }).pipe(rm()); var files = [ 'js/*.js', '!js/*.min.js' ]; // moving the js files gulp.src( plugins.mainBowerFiles() ) .pipe( plugins.filter('*.js') ) .pipe( gulp.dest( dest ) ); // minify the js files and rename it gulp.src( files ) .pipe( rename({suffix: '.min'}) ) .pipe( uglify() ) .pipe( gulp.dest( dest ) ); gulp.src( 'js/*.min.js' ) .pipe( concat( 'main.js' ) ) .pipe( uglify() ) .pipe( gulp.dest( dest ) ); // var jsFiles = ['src/js/*']; // gulp.src(plugins.mainBowerFiles().concat(jsFiles)) // .pipe(plugins.filter('*.js')) // .pipe(plugins.concat('main.js')) // .pipe(plugins.uglify()) // .pipe(gulp.dest(dest + 'js')); //console.log('js_stop'); deferred.resolve(); return deferred.promise; }); gulp.task('clean', function() { //console.log('clean start'); var deferred = Q.defer(); var dest = 'js/'; var files = [ 'js/*.js', '!js/*.min.js' ]; gulp.src(files) .pipe(rm()); //console.log('clean stop'); //callback(err); deferred.resolve(); return deferred.promise; }); gulp.task('css', function() { var deferred = Q.defer(); //console.log('css start'); // Define default destination folder var dest = 'css/'; gulp.src(plugins.mainBowerFiles()) .pipe(plugins.filter('*.css')) .pipe(gulp.dest(dest)); var files = [ 'css/*.css', '!css/*.min.css' ]; gulp.src( files ) .pipe( rename({suffix: '.min'}) ) .pipe(minifyCss()) .pipe( gulp.dest( dest ) ); //console.log('css stop'); deferred.resolve(); return deferred.promise; }); // gulp.task('build', function() { // gulp.src('templates/layout.src.tpl') // .pipe(usemin({ // assetsDir: 'public', // css: [minifyCss(), 'concat'], // js: [uglify(), 'concat'] // })) // .pipe(gulp.dest('public')); //}); gulp.task('build', function(callback) { runSequence(['js_minify','css'], 'clean', callback); }); // Default Task gulp.task('default', ['build']);
export const hourglass3 = {"viewBox":"0 0 1536 1792","children":[{"name":"path","attribs":{"d":"M1408 128q0 261-106.5 461.5t-266.5 306.5q160 106 266.5 306.5t106.5 461.5h96q14 0 23 9t9 23v64q0 14-9 23t-23 9h-1472q-14 0-23-9t-9-23v-64q0-14 9-23t23-9h96q0-261 106.5-461.5t266.5-306.5q-160-106-266.5-306.5t-106.5-461.5h-96q-14 0-23-9t-9-23v-64q0-14 9-23t23-9h1472q14 0 23 9t9 23v64q0 14-9 23t-23 9h-96zM874 836q77-29 149-92.5t129.5-152.5 92.5-210 35-253h-1024q0 132 35 253t92.5 210 129.5 152.5 149 92.5q19 7 30.5 23.5t11.5 36.5-11.5 36.5-30.5 23.5q-137 51-244 196h700q-107-145-244-196-19-7-30.5-23.5t-11.5-36.5 11.5-36.5 30.5-23.5z"}}]};
/* =!EXPECTSTART!= A 5 SHIFTED: 5 4 0 = pig 1 = cat 2 = 99 3 = 4 4 = 3 5 = 2 6 = 1 10 = -1 11 = dog A = pig,cat,99,4,3,2,1,-1,dog IDX = 11 S = cat,99,4,3 SLICE0 = cat SLICE* = cat,99,4,3 T: pig,cat,99,4,3,2,1,-1,dog,SICK!!!,cat,99,4,3 Z: 5,4,A,B,1 ==> 3,2 Q: Aaa,aAb,AAc,Bba,bBb =!EXPECTEND!= */ var y = [ '2', '1' ]; var x = { '0': 'A', '1':'B' }; puts(x[0]); var a = new Array(5,4,3,2,1); a.dog = 9; puts(a[0]); var b = a.shift(); puts("SHIFTED: "+b); puts(a[0]); a[7] = -1; a[8] = 'dog'; a.unshift('pig', 'cat', 99); for (var i in a) { puts(i+" = "+a[i]); } puts('A = '+a.join(',')); puts("IDX = "+a.indexOf('dog')); var s = a.slice(1,4); puts('S = '+ s.join(',')); puts("SLICE0 = "+s[0]); puts("SLICE* = "+s.join(',')); var t = a.concat('SICK!!!',s); puts('T: '+t.join(',')); var z = new Array(5,4,3,2,1); var za = z.splice(2,2,'A','B'); puts('Z: '+z.join(',') + " ==> "+za.join(',')); //var q = new Array(5,4,2,3,1); var q = new Array('Aaa','aAb','AAc','Bba','bBb'); var qq = q.sort(); puts('Q: '+qq.join(','));
/* * bootstrap-filestyle * doc: http://markusslima.github.io/bootstrap-filestyle/ * github: https://github.com/markusslima/bootstrap-filestyle * * Copyright (c) 2014 Markus Vinicius da Silva Lima * Version 1.1.2 * Licensed under the MIT license. */ (function($) {"use strict"; var Filestyle = function(element, options) { this.options = options; this.$elementFilestyle = []; this.$element = $(element); }; Filestyle.prototype = { clear : function() { this.$element.val(''); this.$elementFilestyle.find(':text').val(''); this.$elementFilestyle.find('.badge').remove(); }, destroy : function() { this.$element.removeAttr('style').removeData('filestyle'); this.$elementFilestyle.remove(); }, disabled : function(value) { if (value === true) { if (!this.options.disabled) { this.$element.attr('disabled', 'true'); this.$elementFilestyle.find('label').attr('disabled', 'true'); this.options.disabled = true; } } else if (value === false) { if (this.options.disabled) { this.$element.removeAttr('disabled'); this.$elementFilestyle.find('label').removeAttr('disabled'); this.options.disabled = false; } } else { return this.options.disabled; } }, buttonBefore : function(value) { if (value === true) { if (!this.options.buttonBefore) { this.options.buttonBefore = true; if (this.options.input) { this.$elementFilestyle.remove(); this.constructor(); this.pushNameFiles(); } } } else if (value === false) { if (this.options.buttonBefore) { this.options.buttonBefore = false; if (this.options.input) { this.$elementFilestyle.remove(); this.constructor(); this.pushNameFiles(); } } } else { return this.options.buttonBefore; } }, icon : function(value) { if (value === true) { if (!this.options.icon) { this.options.icon = true; this.$elementFilestyle.find('label').prepend(this.htmlIcon()); } } else if (value === false) { if (this.options.icon) { this.options.icon = false; this.$elementFilestyle.find('.glyphicon').remove(); } } else { return this.options.icon; } }, input : function(value) { if (value === true) { if (!this.options.input) { this.options.input = true; if (this.options.buttonBefore) { this.$elementFilestyle.append(this.htmlInput()); } else { this.$elementFilestyle.prepend(this.htmlInput()); } this.$elementFilestyle.find('.badge').remove(); this.pushNameFiles(); this.$elementFilestyle.find('.group-span-filestyle').addClass('input-group-btn'); } } else if (value === false) { if (this.options.input) { this.options.input = false; this.$elementFilestyle.find(':text').remove(); var files = this.pushNameFiles(); if (files.length > 0 && this.options.badge) { this.$elementFilestyle.find('label').append(' <span class="badge">' + files.length + '</span>'); } this.$elementFilestyle.find('.group-span-filestyle').removeClass('input-group-btn'); } } else { return this.options.input; } }, size : function(value) { if (value !== undefined) { var btn = this.$elementFilestyle.find('label'), input = this.$elementFilestyle.find('input'); btn.removeClass('btn-lg btn-sm'); input.removeClass('input-lg input-sm'); if (value != 'nr') { btn.addClass('btn-' + value); input.addClass('input-' + value); } } else { return this.options.size; } }, buttonText : function(value) { if (value !== undefined) { this.options.buttonText = value; this.$elementFilestyle.find('label .buttonText').html(this.options.buttonText); } else { return this.options.buttonText; } }, buttonName : function(value) { if (value !== undefined) { this.options.buttonName = value; this.$elementFilestyle.find('label').attr({ 'class' : 'btn ' + this.options.buttonName }); } else { return this.options.buttonName; } }, iconName : function(value) { if (value !== undefined) { this.$elementFilestyle.find('.glyphicon').attr({ 'class' : '.glyphicon ' + this.options.iconName }); } else { return this.options.iconName; } }, htmlIcon : function() { if (this.options.icon) { return '<span class="glyphicon ' + this.options.iconName + '"></span> '; } else { return ''; } }, htmlInput : function() { if (this.options.input) { return '<input type="text" class="form-control ' + (this.options.size == 'nr' ? '' : 'input-' + this.options.size) + '" disabled> '; } else { return ''; } }, // puts the name of the input files // return files pushNameFiles : function() { var content = '', files = []; if (this.$element[0].files === undefined) { files[0] = { 'name' : this.$element[0] && this.$element[0].value }; } else { files = this.$element[0].files; } for (var i = 0; i < files.length; i++) { content += files[i].name.split("\\").pop() + ', '; } if (content !== '') { this.$elementFilestyle.find(':text').val(content.replace(/\, $/g, '')); } else { this.$elementFilestyle.find(':text').val(''); } return files; }, constructor : function() { var _self = this, html = '', id = _self.$element.attr('id'), files = [], btn = '', $label; if (id === '' || !id) { id = 'filestyle-' + $('.bootstrap-filestyle').length; _self.$element.attr({ 'id' : id }); } btn = '<span class="group-span-filestyle ' + (_self.options.input ? 'input-group-btn' : '') + '">' + '<label for="' + id + '" class="btn ' + _self.options.buttonName + ' ' + (_self.options.size == 'nr' ? '' : 'btn-' + _self.options.size) + '" ' + (_self.options.disabled ? 'disabled="true"' : '') + '>' + _self.htmlIcon() + '<span class="buttonText">' + _self.options.buttonText + '</span>' + '</label>' + '</span>'; html = _self.options.buttonBefore ? btn + _self.htmlInput() : _self.htmlInput() + btn; _self.$elementFilestyle = $('<div class="bootstrap-filestyle input-group">' + html + '</div>'); _self.$elementFilestyle.find('.group-span-filestyle').attr('tabindex', "0").keypress(function(e) { if (e.keyCode === 13 || e.charCode === 32) { _self.$elementFilestyle.find('label').click(); return false; } }); // hidding input file and add filestyle _self.$element.css({ 'position' : 'absolute', 'clip' : 'rect(0px 0px 0px 0px)' // using 0px for work in IE8 }).attr('tabindex', "-1").after(_self.$elementFilestyle); if (_self.options.disabled) { _self.$element.attr('disabled', 'true'); } // Getting input file value _self.$element.change(function() { var files = _self.pushNameFiles(); if (_self.options.input == false && _self.options.badge) { if (_self.$elementFilestyle.find('.badge').length == 0) { _self.$elementFilestyle.find('label').append(' <span class="badge">' + files.length + '</span>'); } else if (files.length == 0) { _self.$elementFilestyle.find('.badge').remove(); } else { _self.$elementFilestyle.find('.badge').html(files.length); } } else { _self.$elementFilestyle.find('.badge').remove(); } }); // Check if browser is Firefox if (window.navigator.userAgent.search(/firefox/i) > -1) { // Simulating choose file for firefox _self.$elementFilestyle.find('label').click(function() { _self.$element.click(); return false; }); } } }; var old = $.fn.filestyle; $.fn.filestyle = function(option, value) { var get = '', element = this.each(function() { if ($(this).attr('type') === 'file') { var $this = $(this), data = $this.data('filestyle'), options = $.extend({}, $.fn.filestyle.defaults, option, typeof option === 'object' && option); if (!data) { $this.data('filestyle', ( data = new Filestyle(this, options))); data.constructor(); } if ( typeof option === 'string') { get = data[option](value); } } }); if ( typeof get !== undefined) { return get; } else { return element; } }; $.fn.filestyle.defaults = { 'buttonText' : 'Choose file', 'iconName' : 'glyphicon-folder-open', 'buttonName' : 'btn-default', 'size' : 'nr', 'input' : true, 'badge' : true, 'icon' : true, 'buttonBefore' : false, 'disabled' : false }; $.fn.filestyle.noConflict = function() { $.fn.filestyle = old; return this; }; // Data attributes register $(function() { $('.filestyle').each(function() { var $this = $(this), options = { 'input' : $this.attr('data-input') === 'false' ? false : true, 'icon' : $this.attr('data-icon') === 'false' ? false : true, 'buttonBefore' : $this.attr('data-buttonBefore') === 'true' ? true : false, 'disabled' : $this.attr('data-disabled') === 'true' ? true : false, 'size' : $this.attr('data-size'), 'buttonText' : $this.attr('data-buttonText'), 'buttonName' : $this.attr('data-buttonName'), 'iconName' : $this.attr('data-iconName'), 'badge' : $this.attr('data-badge') === 'false' ? false : true }; $this.filestyle(options); }); }); })(window.jQuery);
(function(){ 'use strict'; angular.module('prerender-tutorial.home', ['ngRoute']); })();
/* global describe, it, expect, module, inject, beforeEach */ /* jshint es3:false, esnext:true */ (function (_) { 'use strict'; describe('drf-field-errors', function () { beforeEach(function () { module('drf-field-errors'); inject(function (drfFieldErrors) { this.drfFieldErrors = drfFieldErrors; }); }); describe('clear method', function () { it('should clear non-field errors', function () { let fields = { errors: ['Non-field error'] }; this.drfFieldErrors.clear(fields); expect(fields.errors).toEqual([]); }); it('should clear field errors', function () { let fields = { field1: { errors: 'Error 1' }, field2: { errors: 'Error 2' } }; this.drfFieldErrors.clear(fields); expect(fields.field1.errors).toBe(''); expect(fields.field2.errors).toBe(''); }); }); describe('set method', function () { beforeEach(function () { this.fields = { errors: [], field1: { errors: '' }, field2: { errors: '' } }; }); describe('non-field errors', function () { it('should be set when under __all__ property', function () { let errors = { __all__: 'Error' }; this.drfFieldErrors.set(this.fields, errors); expect(this.fields.errors[0].msg).toBe('Error'); }); it('should be set when under non_field_errors property', function () { let errors = { // jscs:disable requireCamelCaseOrUpperCaseIdentifiers // jshint camelcase: false non_field_errors: 'Error' // jscs:enable requireCamelCaseOrUpperCaseIdentifiers // jshint camelcase: true }; this.drfFieldErrors.set(this.fields, errors); expect(this.fields.errors[0].msg).toBe('Error'); }); it('should create an array of errors', function () { let errors = { // jscs:disable requireCamelCaseOrUpperCaseIdentifiers // jshint camelcase: false non_field_errors: [ 'Error1', 'Error2' ] // jscs:enable requireCamelCaseOrUpperCaseIdentifiers // jshint camelcase: true }; this.drfFieldErrors.set(this.fields, errors); expect(this.fields.errors[0].msg).toBe('Error1'); expect(this.fields.errors[1].msg).toBe('Error2'); }); }); describe('field errors', function () { it('should be set under appropriate fields', function () { let errors = { field1: ['Error1'], field2: ['Error2' ] }; this.drfFieldErrors.set(this.fields, errors); expect(this.fields.field1.errors).toBe('Error1'); expect(this.fields.field2.errors).toBe('Error2'); }); }); }); }); }(window._));
import { Map } from 'immutable'; export function clearToken() { localStorage.removeItem('id_token'); } export function getToken() { try { const idToken = localStorage.getItem('id_token'); return new Map({ idToken }); } catch (err) { clearToken(); return new Map(); } } export function timeDifference(givenTime) { givenTime = new Date(givenTime); const milliseconds = new Date().getTime() - givenTime.getTime(); const numberEnding = number => { return number > 1 ? 's' : ''; }; const number = num => (num > 9 ? '' + num : '0' + num); const getTime = () => { let temp = Math.floor(milliseconds / 1000); const years = Math.floor(temp / 31536000); if (years) { const month = number(givenTime.getUTCMonth() + 1); const day = number(givenTime.getUTCDate()); const year = givenTime.getUTCFullYear() % 100; return `${day}-${month}-${year}`; } const days = Math.floor((temp %= 31536000) / 86400); if (days) { if (days < 28) { return days + ' day' + numberEnding(days); } else { const months = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]; const month = months[givenTime.getUTCMonth()]; const day = number(givenTime.getUTCDate()); return `${day} ${month}`; } } const hours = Math.floor((temp %= 86400) / 3600); if (hours) { return `${hours} hour${numberEnding(hours)} ago`; } const minutes = Math.floor((temp %= 3600) / 60); if (minutes) { return `${minutes} minute${numberEnding(minutes)} ago`; } return 'a few seconds ago'; }; return getTime(); } export function stringToInt(value, defValue = 0) { if (!value) { return 0; } else if (!isNaN(value)) { return parseInt(value, 10); } return defValue; } export function stringToPosetiveInt(value, defValue = 0) { const val = stringToInt(value, defValue); return val > -1 ? val : defValue; }
Dagaz.Model.WIDTH = 12; Dagaz.Model.HEIGHT = 12; ZRF = { JUMP: 0, IF: 1, FORK: 2, FUNCTION: 3, IN_ZONE: 4, FLAG: 5, SET_FLAG: 6, POS_FLAG: 7, SET_POS_FLAG: 8, ATTR: 9, SET_ATTR: 10, PROMOTE: 11, MODE: 12, ON_BOARD_DIR: 13, ON_BOARD_POS: 14, PARAM: 15, LITERAL: 16, VERIFY: 20 }; Dagaz.Model.BuildDesign = function(design) { design.checkVersion("z2j", "2"); design.checkVersion("animate-captures", "false"); design.checkVersion("smart-moves", "true"); design.checkVersion("show-hints", "false"); design.checkVersion("show-blink", "true"); design.checkVersion("maximal-captures", "true"); design.checkVersion("deferred-captures", "true"); design.checkVersion("advisor-wait", "25"); design.checkVersion("international-extension", "true"); design.addDirection("se"); design.addDirection("sw"); design.addDirection("ne"); design.addDirection("nw"); design.addPlayer("White", [3, 2, 1, 0]); design.addPlayer("Black", [3, 2, 1, 0]); design.addPosition("a12", [13, 0, 0, 0]); design.addPosition("b12", [13, 11, 0, 0]); design.addPosition("c12", [13, 11, 0, 0]); design.addPosition("d12", [13, 11, 0, 0]); design.addPosition("e12", [13, 11, 0, 0]); design.addPosition("f12", [13, 11, 0, 0]); design.addPosition("g12", [13, 11, 0, 0]); design.addPosition("h12", [13, 11, 0, 0]); design.addPosition("i12", [13, 11, 0, 0]); design.addPosition("j12", [13, 11, 0, 0]); design.addPosition("k12", [13, 11, 0, 0]); design.addPosition("l12", [0, 11, 0, 0]); design.addPosition("a11", [13, 0, -11, 0]); design.addPosition("b11", [13, 11, -11, -13]); design.addPosition("c11", [13, 11, -11, -13]); design.addPosition("d11", [13, 11, -11, -13]); design.addPosition("e11", [13, 11, -11, -13]); design.addPosition("f11", [13, 11, -11, -13]); design.addPosition("g11", [13, 11, -11, -13]); design.addPosition("h11", [13, 11, -11, -13]); design.addPosition("i11", [13, 11, -11, -13]); design.addPosition("j11", [13, 11, -11, -13]); design.addPosition("k11", [13, 11, -11, -13]); design.addPosition("l11", [0, 11, 0, -13]); design.addPosition("a10", [13, 0, -11, 0]); design.addPosition("b10", [13, 11, -11, -13]); design.addPosition("c10", [13, 11, -11, -13]); design.addPosition("d10", [13, 11, -11, -13]); design.addPosition("e10", [13, 11, -11, -13]); design.addPosition("f10", [13, 11, -11, -13]); design.addPosition("g10", [13, 11, -11, -13]); design.addPosition("h10", [13, 11, -11, -13]); design.addPosition("i10", [13, 11, -11, -13]); design.addPosition("j10", [13, 11, -11, -13]); design.addPosition("k10", [13, 11, -11, -13]); design.addPosition("l10", [0, 11, 0, -13]); design.addPosition("a9", [13, 0, -11, 0]); design.addPosition("b9", [13, 11, -11, -13]); design.addPosition("c9", [13, 11, -11, -13]); design.addPosition("d9", [13, 11, -11, -13]); design.addPosition("e9", [13, 11, -11, -13]); design.addPosition("f9", [13, 11, -11, -13]); design.addPosition("g9", [13, 11, -11, -13]); design.addPosition("h9", [13, 11, -11, -13]); design.addPosition("i9", [13, 11, -11, -13]); design.addPosition("j9", [13, 11, -11, -13]); design.addPosition("k9", [13, 11, -11, -13]); design.addPosition("l9", [0, 11, 0, -13]); design.addPosition("a8", [13, 0, -11, 0]); design.addPosition("b8", [13, 11, -11, -13]); design.addPosition("c8", [13, 11, -11, -13]); design.addPosition("d8", [13, 11, -11, -13]); design.addPosition("e8", [13, 11, -11, -13]); design.addPosition("f8", [13, 11, -11, -13]); design.addPosition("g8", [13, 11, -11, -13]); design.addPosition("h8", [13, 11, -11, -13]); design.addPosition("i8", [13, 11, -11, -13]); design.addPosition("j8", [13, 11, -11, -13]); design.addPosition("k8", [13, 11, -11, -13]); design.addPosition("l8", [0, 11, 0, -13]); design.addPosition("a7", [13, 0, -11, 0]); design.addPosition("b7", [13, 11, -11, -13]); design.addPosition("c7", [13, 11, -11, -13]); design.addPosition("d7", [13, 11, -11, -13]); design.addPosition("e7", [13, 11, -11, -13]); design.addPosition("f7", [13, 11, -11, -13]); design.addPosition("g7", [13, 11, -11, -13]); design.addPosition("h7", [13, 11, -11, -13]); design.addPosition("i7", [13, 11, -11, -13]); design.addPosition("j7", [13, 11, -11, -13]); design.addPosition("k7", [13, 11, -11, -13]); design.addPosition("l7", [0, 11, 0, -13]); design.addPosition("a6", [13, 0, -11, 0]); design.addPosition("b6", [13, 11, -11, -13]); design.addPosition("c6", [13, 11, -11, -13]); design.addPosition("d6", [13, 11, -11, -13]); design.addPosition("e6", [13, 11, -11, -13]); design.addPosition("f6", [13, 11, -11, -13]); design.addPosition("g6", [13, 11, -11, -13]); design.addPosition("h6", [13, 11, -11, -13]); design.addPosition("i6", [13, 11, -11, -13]); design.addPosition("j6", [13, 11, -11, -13]); design.addPosition("k6", [13, 11, -11, -13]); design.addPosition("l6", [0, 11, 0, -13]); design.addPosition("a5", [13, 0, -11, 0]); design.addPosition("b5", [13, 11, -11, -13]); design.addPosition("c5", [13, 11, -11, -13]); design.addPosition("d5", [13, 11, -11, -13]); design.addPosition("e5", [13, 11, -11, -13]); design.addPosition("f5", [13, 11, -11, -13]); design.addPosition("g5", [13, 11, -11, -13]); design.addPosition("h5", [13, 11, -11, -13]); design.addPosition("i5", [13, 11, -11, -13]); design.addPosition("j5", [13, 11, -11, -13]); design.addPosition("k5", [13, 11, -11, -13]); design.addPosition("l5", [0, 11, 0, -13]); design.addPosition("a4", [13, 0, -11, 0]); design.addPosition("b4", [13, 11, -11, -13]); design.addPosition("c4", [13, 11, -11, -13]); design.addPosition("d4", [13, 11, -11, -13]); design.addPosition("e4", [13, 11, -11, -13]); design.addPosition("f4", [13, 11, -11, -13]); design.addPosition("g4", [13, 11, -11, -13]); design.addPosition("h4", [13, 11, -11, -13]); design.addPosition("i4", [13, 11, -11, -13]); design.addPosition("j4", [13, 11, -11, -13]); design.addPosition("k4", [13, 11, -11, -13]); design.addPosition("l4", [0, 11, 0, -13]); design.addPosition("a3", [13, 0, -11, 0]); design.addPosition("b3", [13, 11, -11, -13]); design.addPosition("c3", [13, 11, -11, -13]); design.addPosition("d3", [13, 11, -11, -13]); design.addPosition("e3", [13, 11, -11, -13]); design.addPosition("f3", [13, 11, -11, -13]); design.addPosition("g3", [13, 11, -11, -13]); design.addPosition("h3", [13, 11, -11, -13]); design.addPosition("i3", [13, 11, -11, -13]); design.addPosition("j3", [13, 11, -11, -13]); design.addPosition("k3", [13, 11, -11, -13]); design.addPosition("l3", [0, 11, 0, -13]); design.addPosition("a2", [13, 0, -11, 0]); design.addPosition("b2", [13, 11, -11, -13]); design.addPosition("c2", [13, 11, -11, -13]); design.addPosition("d2", [13, 11, -11, -13]); design.addPosition("e2", [13, 11, -11, -13]); design.addPosition("f2", [13, 11, -11, -13]); design.addPosition("g2", [13, 11, -11, -13]); design.addPosition("h2", [13, 11, -11, -13]); design.addPosition("i2", [13, 11, -11, -13]); design.addPosition("j2", [13, 11, -11, -13]); design.addPosition("k2", [13, 11, -11, -13]); design.addPosition("l2", [0, 11, 0, -13]); design.addPosition("a1", [0, 0, -11, 0]); design.addPosition("b1", [0, 0, -11, -13]); design.addPosition("c1", [0, 0, -11, -13]); design.addPosition("d1", [0, 0, -11, -13]); design.addPosition("e1", [0, 0, -11, -13]); design.addPosition("f1", [0, 0, -11, -13]); design.addPosition("g1", [0, 0, -11, -13]); design.addPosition("h1", [0, 0, -11, -13]); design.addPosition("i1", [0, 0, -11, -13]); design.addPosition("j1", [0, 0, -11, -13]); design.addPosition("k1", [0, 0, -11, -13]); design.addPosition("l1", [0, 0, 0, -13]); design.addZone("promotion", 1, [1, 3, 5, 7, 9, 11]); design.addZone("promotion", 2, [132, 134, 136, 138, 140, 142]); design.addCommand(0, ZRF.FUNCTION, 24); // from design.addCommand(0, ZRF.PARAM, 0); // $1 design.addCommand(0, ZRF.FUNCTION, 22); // navigate design.addCommand(0, ZRF.FUNCTION, 2); // enemy? design.addCommand(0, ZRF.FUNCTION, 20); // verify design.addCommand(0, ZRF.FUNCTION, 26); // capture design.addCommand(0, ZRF.PARAM, 1); // $2 design.addCommand(0, ZRF.FUNCTION, 22); // navigate design.addCommand(0, ZRF.FUNCTION, 1); // empty? design.addCommand(0, ZRF.FUNCTION, 20); // verify design.addCommand(0, ZRF.MODE, 0); // jump-type design.addCommand(0, ZRF.FUNCTION, 25); // to design.addCommand(0, ZRF.FUNCTION, 28); // end design.addCommand(1, ZRF.FUNCTION, 24); // from design.addCommand(1, ZRF.PARAM, 0); // $1 design.addCommand(1, ZRF.FUNCTION, 22); // navigate design.addCommand(1, ZRF.FUNCTION, 1); // empty? design.addCommand(1, ZRF.FUNCTION, 20); // verify design.addCommand(1, ZRF.FUNCTION, 25); // to design.addCommand(1, ZRF.FUNCTION, 28); // end design.addCommand(2, ZRF.FUNCTION, 24); // from design.addCommand(2, ZRF.PARAM, 0); // $1 design.addCommand(2, ZRF.FUNCTION, 22); // navigate design.addCommand(2, ZRF.FUNCTION, 1); // empty? design.addCommand(2, ZRF.FUNCTION, 0); // not design.addCommand(2, ZRF.IF, 4); design.addCommand(2, ZRF.PARAM, 1); // $2 design.addCommand(2, ZRF.FUNCTION, 22); // navigate design.addCommand(2, ZRF.JUMP, -5); design.addCommand(2, ZRF.FUNCTION, 2); // enemy? design.addCommand(2, ZRF.FUNCTION, 20); // verify design.addCommand(2, ZRF.PARAM, 2); // $3 design.addCommand(2, ZRF.FUNCTION, 22); // navigate design.addCommand(2, ZRF.FUNCTION, 1); // empty? design.addCommand(2, ZRF.FUNCTION, 0); // not design.addCommand(2, ZRF.IF, 18); design.addCommand(2, ZRF.FUNCTION, 6); // mark design.addCommand(2, ZRF.FUNCTION, 1); // empty? design.addCommand(2, ZRF.FUNCTION, 0); // not design.addCommand(2, ZRF.IF, 5); design.addCommand(2, ZRF.PARAM, 3); // $4 design.addCommand(2, ZRF.FUNCTION, 23); // opposite design.addCommand(2, ZRF.FUNCTION, 22); // navigate design.addCommand(2, ZRF.JUMP, -6); design.addCommand(2, ZRF.FUNCTION, 26); // capture design.addCommand(2, ZRF.FUNCTION, 7); // back design.addCommand(2, ZRF.FORK, 4); design.addCommand(2, ZRF.MODE, 2); // cont-type design.addCommand(2, ZRF.FUNCTION, 25); // to design.addCommand(2, ZRF.FUNCTION, 28); // end design.addCommand(2, ZRF.PARAM, 4); // $5 design.addCommand(2, ZRF.FUNCTION, 22); // navigate design.addCommand(2, ZRF.JUMP, -19); design.addCommand(2, ZRF.FUNCTION, 28); // end design.addCommand(3, ZRF.FUNCTION, 24); // from design.addCommand(3, ZRF.PARAM, 0); // $1 design.addCommand(3, ZRF.FUNCTION, 22); // navigate design.addCommand(3, ZRF.FUNCTION, 1); // empty? design.addCommand(3, ZRF.FUNCTION, 0); // not design.addCommand(3, ZRF.IF, 7); design.addCommand(3, ZRF.PARAM, 1); // $2 design.addCommand(3, ZRF.FUNCTION, 22); // navigate design.addCommand(3, ZRF.FUNCTION, 4); // last-from? design.addCommand(3, ZRF.FUNCTION, 0); // not design.addCommand(3, ZRF.FUNCTION, 20); // verify design.addCommand(3, ZRF.JUMP, -8); design.addCommand(3, ZRF.FUNCTION, 2); // enemy? design.addCommand(3, ZRF.FUNCTION, 20); // verify design.addCommand(3, ZRF.PARAM, 2); // $3 design.addCommand(3, ZRF.FUNCTION, 22); // navigate design.addCommand(3, ZRF.FUNCTION, 1); // empty? design.addCommand(3, ZRF.FUNCTION, 0); // not design.addCommand(3, ZRF.IF, 18); design.addCommand(3, ZRF.FUNCTION, 6); // mark design.addCommand(3, ZRF.FUNCTION, 1); // empty? design.addCommand(3, ZRF.FUNCTION, 0); // not design.addCommand(3, ZRF.IF, 5); design.addCommand(3, ZRF.PARAM, 3); // $4 design.addCommand(3, ZRF.FUNCTION, 23); // opposite design.addCommand(3, ZRF.FUNCTION, 22); // navigate design.addCommand(3, ZRF.JUMP, -6); design.addCommand(3, ZRF.FUNCTION, 26); // capture design.addCommand(3, ZRF.FUNCTION, 7); // back design.addCommand(3, ZRF.FORK, 4); design.addCommand(3, ZRF.MODE, 2); // cont-type design.addCommand(3, ZRF.FUNCTION, 25); // to design.addCommand(3, ZRF.FUNCTION, 28); // end design.addCommand(3, ZRF.PARAM, 4); // $5 design.addCommand(3, ZRF.FUNCTION, 22); // navigate design.addCommand(3, ZRF.JUMP, -19); design.addCommand(3, ZRF.FUNCTION, 28); // end design.addCommand(4, ZRF.FUNCTION, 24); // from design.addCommand(4, ZRF.PARAM, 0); // $1 design.addCommand(4, ZRF.FUNCTION, 22); // navigate design.addCommand(4, ZRF.FUNCTION, 1); // empty? design.addCommand(4, ZRF.FUNCTION, 0); // not design.addCommand(4, ZRF.IF, 7); design.addCommand(4, ZRF.FORK, 3); design.addCommand(4, ZRF.FUNCTION, 25); // to design.addCommand(4, ZRF.FUNCTION, 28); // end design.addCommand(4, ZRF.PARAM, 1); // $2 design.addCommand(4, ZRF.FUNCTION, 22); // navigate design.addCommand(4, ZRF.JUMP, -8); design.addCommand(4, ZRF.FUNCTION, 28); // end design.addPriority(0); // jump-type design.addPriority(1); // normal-type design.addPiece("Man", 0, 20); design.addMove(0, 0, [3, 3], 0); design.addMove(0, 0, [2, 2], 0); design.addMove(0, 0, [1, 1], 0); design.addMove(0, 0, [0, 0], 0); design.addMove(0, 1, [3], 1); design.addMove(0, 1, [2], 1); design.addPiece("King", 1, 100); design.addMove(1, 2, [3, 3, 3, 3, 3], 0); design.addMove(1, 2, [2, 2, 2, 2, 2], 0); design.addMove(1, 2, [1, 1, 1, 1, 1], 0); design.addMove(1, 2, [0, 0, 0, 0, 0], 0); design.addMove(1, 3, [3, 3, 3, 3, 3], 2); design.addMove(1, 3, [2, 2, 2, 2, 2], 2); design.addMove(1, 3, [1, 1, 1, 1, 1], 2); design.addMove(1, 3, [0, 0, 0, 0, 0], 2); design.addMove(1, 4, [3, 3], 1); design.addMove(1, 4, [2, 2], 1); design.addMove(1, 4, [1, 1], 1); design.addMove(1, 4, [0, 0], 1); design.setup("White", "Man", 132); design.setup("White", "Man", 134); design.setup("White", "Man", 136); design.setup("White", "Man", 138); design.setup("White", "Man", 140); design.setup("White", "Man", 142); design.setup("White", "Man", 121); design.setup("White", "Man", 123); design.setup("White", "Man", 125); design.setup("White", "Man", 127); design.setup("White", "Man", 129); design.setup("White", "Man", 131); design.setup("White", "Man", 108); design.setup("White", "Man", 110); design.setup("White", "Man", 112); design.setup("White", "Man", 114); design.setup("White", "Man", 116); design.setup("White", "Man", 118); design.setup("White", "Man", 97); design.setup("White", "Man", 99); design.setup("White", "Man", 101); design.setup("White", "Man", 103); design.setup("White", "Man", 105); design.setup("White", "Man", 107); design.setup("White", "Man", 84); design.setup("White", "Man", 86); design.setup("White", "Man", 88); design.setup("White", "Man", 90); design.setup("White", "Man", 92); design.setup("White", "Man", 94); design.setup("Black", "Man", 1); design.setup("Black", "Man", 3); design.setup("Black", "Man", 5); design.setup("Black", "Man", 7); design.setup("Black", "Man", 9); design.setup("Black", "Man", 11); design.setup("Black", "Man", 12); design.setup("Black", "Man", 14); design.setup("Black", "Man", 16); design.setup("Black", "Man", 18); design.setup("Black", "Man", 20); design.setup("Black", "Man", 22); design.setup("Black", "Man", 25); design.setup("Black", "Man", 27); design.setup("Black", "Man", 29); design.setup("Black", "Man", 31); design.setup("Black", "Man", 33); design.setup("Black", "Man", 35); design.setup("Black", "Man", 36); design.setup("Black", "Man", 38); design.setup("Black", "Man", 40); design.setup("Black", "Man", 42); design.setup("Black", "Man", 44); design.setup("Black", "Man", 46); design.setup("Black", "Man", 49); design.setup("Black", "Man", 51); design.setup("Black", "Man", 53); design.setup("Black", "Man", 55); design.setup("Black", "Man", 57); design.setup("Black", "Man", 59); } Dagaz.View.configure = function(view) { view.defBoard("Board"); view.defPiece("WhiteMan", "White Man"); view.defPiece("BlackMan", "Black Man"); view.defPiece("WhiteKing", "White King"); view.defPiece("BlackKing", "Black King"); view.defPosition("a12", 2, 2, 50, 50); view.defPosition("b12", 52, 2, 50, 50); view.defPosition("c12", 102, 2, 50, 50); view.defPosition("d12", 152, 2, 50, 50); view.defPosition("e12", 202, 2, 50, 50); view.defPosition("f12", 252, 2, 50, 50); view.defPosition("g12", 302, 2, 50, 50); view.defPosition("h12", 352, 2, 50, 50); view.defPosition("i12", 402, 2, 50, 50); view.defPosition("j12", 452, 2, 50, 50); view.defPosition("k12", 502, 2, 50, 50); view.defPosition("l12", 552, 2, 50, 50); view.defPosition("a11", 2, 52, 50, 50); view.defPosition("b11", 52, 52, 50, 50); view.defPosition("c11", 102, 52, 50, 50); view.defPosition("d11", 152, 52, 50, 50); view.defPosition("e11", 202, 52, 50, 50); view.defPosition("f11", 252, 52, 50, 50); view.defPosition("g11", 302, 52, 50, 50); view.defPosition("h11", 352, 52, 50, 50); view.defPosition("i11", 402, 52, 50, 50); view.defPosition("j11", 452, 52, 50, 50); view.defPosition("k11", 502, 52, 50, 50); view.defPosition("l11", 552, 52, 50, 50); view.defPosition("a10", 2, 102, 50, 50); view.defPosition("b10", 52, 102, 50, 50); view.defPosition("c10", 102, 102, 50, 50); view.defPosition("d10", 152, 102, 50, 50); view.defPosition("e10", 202, 102, 50, 50); view.defPosition("f10", 252, 102, 50, 50); view.defPosition("g10", 302, 102, 50, 50); view.defPosition("h10", 352, 102, 50, 50); view.defPosition("i10", 402, 102, 50, 50); view.defPosition("j10", 452, 102, 50, 50); view.defPosition("k10", 502, 102, 50, 50); view.defPosition("l10", 552, 102, 50, 50); view.defPosition("a9", 2, 152, 50, 50); view.defPosition("b9", 52, 152, 50, 50); view.defPosition("c9", 102, 152, 50, 50); view.defPosition("d9", 152, 152, 50, 50); view.defPosition("e9", 202, 152, 50, 50); view.defPosition("f9", 252, 152, 50, 50); view.defPosition("g9", 302, 152, 50, 50); view.defPosition("h9", 352, 152, 50, 50); view.defPosition("i9", 402, 152, 50, 50); view.defPosition("j9", 452, 152, 50, 50); view.defPosition("k9", 502, 152, 50, 50); view.defPosition("l9", 552, 152, 50, 50); view.defPosition("a8", 2, 202, 50, 50); view.defPosition("b8", 52, 202, 50, 50); view.defPosition("c8", 102, 202, 50, 50); view.defPosition("d8", 152, 202, 50, 50); view.defPosition("e8", 202, 202, 50, 50); view.defPosition("f8", 252, 202, 50, 50); view.defPosition("g8", 302, 202, 50, 50); view.defPosition("h8", 352, 202, 50, 50); view.defPosition("i8", 402, 202, 50, 50); view.defPosition("j8", 452, 202, 50, 50); view.defPosition("k8", 502, 202, 50, 50); view.defPosition("l8", 552, 202, 50, 50); view.defPosition("a7", 2, 252, 50, 50); view.defPosition("b7", 52, 252, 50, 50); view.defPosition("c7", 102, 252, 50, 50); view.defPosition("d7", 152, 252, 50, 50); view.defPosition("e7", 202, 252, 50, 50); view.defPosition("f7", 252, 252, 50, 50); view.defPosition("g7", 302, 252, 50, 50); view.defPosition("h7", 352, 252, 50, 50); view.defPosition("i7", 402, 252, 50, 50); view.defPosition("j7", 452, 252, 50, 50); view.defPosition("k7", 502, 252, 50, 50); view.defPosition("l7", 552, 252, 50, 50); view.defPosition("a6", 2, 302, 50, 50); view.defPosition("b6", 52, 302, 50, 50); view.defPosition("c6", 102, 302, 50, 50); view.defPosition("d6", 152, 302, 50, 50); view.defPosition("e6", 202, 302, 50, 50); view.defPosition("f6", 252, 302, 50, 50); view.defPosition("g6", 302, 302, 50, 50); view.defPosition("h6", 352, 302, 50, 50); view.defPosition("i6", 402, 302, 50, 50); view.defPosition("j6", 452, 302, 50, 50); view.defPosition("k6", 502, 302, 50, 50); view.defPosition("l6", 552, 302, 50, 50); view.defPosition("a5", 2, 352, 50, 50); view.defPosition("b5", 52, 352, 50, 50); view.defPosition("c5", 102, 352, 50, 50); view.defPosition("d5", 152, 352, 50, 50); view.defPosition("e5", 202, 352, 50, 50); view.defPosition("f5", 252, 352, 50, 50); view.defPosition("g5", 302, 352, 50, 50); view.defPosition("h5", 352, 352, 50, 50); view.defPosition("i5", 402, 352, 50, 50); view.defPosition("j5", 452, 352, 50, 50); view.defPosition("k5", 502, 352, 50, 50); view.defPosition("l5", 552, 352, 50, 50); view.defPosition("a4", 2, 402, 50, 50); view.defPosition("b4", 52, 402, 50, 50); view.defPosition("c4", 102, 402, 50, 50); view.defPosition("d4", 152, 402, 50, 50); view.defPosition("e4", 202, 402, 50, 50); view.defPosition("f4", 252, 402, 50, 50); view.defPosition("g4", 302, 402, 50, 50); view.defPosition("h4", 352, 402, 50, 50); view.defPosition("i4", 402, 402, 50, 50); view.defPosition("j4", 452, 402, 50, 50); view.defPosition("k4", 502, 402, 50, 50); view.defPosition("l4", 552, 402, 50, 50); view.defPosition("a3", 2, 452, 50, 50); view.defPosition("b3", 52, 452, 50, 50); view.defPosition("c3", 102, 452, 50, 50); view.defPosition("d3", 152, 452, 50, 50); view.defPosition("e3", 202, 452, 50, 50); view.defPosition("f3", 252, 452, 50, 50); view.defPosition("g3", 302, 452, 50, 50); view.defPosition("h3", 352, 452, 50, 50); view.defPosition("i3", 402, 452, 50, 50); view.defPosition("j3", 452, 452, 50, 50); view.defPosition("k3", 502, 452, 50, 50); view.defPosition("l3", 552, 452, 50, 50); view.defPosition("a2", 2, 502, 50, 50); view.defPosition("b2", 52, 502, 50, 50); view.defPosition("c2", 102, 502, 50, 50); view.defPosition("d2", 152, 502, 50, 50); view.defPosition("e2", 202, 502, 50, 50); view.defPosition("f2", 252, 502, 50, 50); view.defPosition("g2", 302, 502, 50, 50); view.defPosition("h2", 352, 502, 50, 50); view.defPosition("i2", 402, 502, 50, 50); view.defPosition("j2", 452, 502, 50, 50); view.defPosition("k2", 502, 502, 50, 50); view.defPosition("l2", 552, 502, 50, 50); view.defPosition("a1", 2, 552, 50, 50); view.defPosition("b1", 52, 552, 50, 50); view.defPosition("c1", 102, 552, 50, 50); view.defPosition("d1", 152, 552, 50, 50); view.defPosition("e1", 202, 552, 50, 50); view.defPosition("f1", 252, 552, 50, 50); view.defPosition("g1", 302, 552, 50, 50); view.defPosition("h1", 352, 552, 50, 50); view.defPosition("i1", 402, 552, 50, 50); view.defPosition("j1", 452, 552, 50, 50); view.defPosition("k1", 502, 552, 50, 50); view.defPosition("l1", 552, 552, 50, 50); }
/*** * Globals ***/ var eventStack = []; var graph = new Graph(); var selectedElement = null; var elementIdCounter = 0; var graphName; var width; var height; /*** * End Globals ***/ /*** * Node/Link Storage ***/ function storeLocalChanges() { var storageObject = new Object(); storageObject.elementIdCounter = elementIdCounter; storageObject.graph = JSON.stringify(graph, function(key, value){ if(key === "connection") { return value[0][0].outerHTML; } else { return value; } }); storageObject.svg = $("#main-container").html(); window.localStorage[graphName] = JSON.stringify(storageObject); } function initFromStorage() { selectedElement = null; var storageObject = JSON.parse(window.localStorage[graphName]); var tmpGraph = JSON.parse(storageObject.graph); graph = new Graph(); for(var i = 0; i < tmpGraph.nodes.length; i++) { var tmpNode = tmpGraph.nodes[i]; var node = new GraphNode(tmpNode.elementId); var connections = tmpNode.connectedElements; for(var key in connections){ var link = connections[key]; node.addConnection(key, link.connection, link.isOrigin); } graph.addNode(node); } elementIdCounter = storageObject.elementIdCounter; var mainContainer = $("#main-container"); mainContainer.empty(); var jQuerySvg = $(storageObject.svg); mainContainer.append(jQuerySvg); mainContainer.html(mainContainer.html()); $("#main-container line").each(function(k, v){ v.remove(); }); d3.selectAll(".node").call(drag).on("click", elementClickHandler); var nodes = graph.nodes; for (var i = nodes.length - 1; i >= 0; i--) { var node = nodes[i]; var conn = node.connectedElements; for(var key in conn) { var link = conn[key]; if(!link.isOrigin) { var jQueryConn = $(link.connection); var x1 = jQueryConn.attr("x1"); var y1 = jQueryConn.attr("y1"); var x2 = jQueryConn.attr("x2"); var y2 = jQueryConn.attr("y2"); node.removeConnection(key); var otherNode = graph.getNode(key); otherNode.removeConnection(node.elementId); addConnection(node, otherNode, d3.select("#" + nodes[i].elementId), d3.select("#" + key)); } } } d3.selectAll(".selected").classed("selected", false); } function Graph() { this.nodes = []; this.addNode = function(node) { this.nodes.push(node); } this.removeNode = function(elementId) { for(var i = this.nodes.length; i >= 0; i--) { if(this.nodes[i].elementId === elementId) return this.nodes.splice(i, 1); } } this.getNode = function(elementId) { for(var i = 0; i < this.nodes.length; i++) { if(this.nodes[i].elementId === elementId) return this.nodes[i]; } } } function GraphNode(elementId){ this.connectedElements = new Object(); this.elementId = elementId; this.addConnection = function(otherId, connection, isOrigin) { // origin -> if x1y1 or x2y2 this.connectedElements[otherId] = {"connection" : connection, "isOrigin" : isOrigin}; } this.removeConnection = function(otherId) { var link = this.connectedElements[otherId]; if(typeof link.connection !== "string" && link.connection !== null) { link.connection.remove(); link.connection = null; } delete this.connectedElements[otherId]; } this.getConnection = function(otherId) { return this.connectedElements[otherId]; } } function removeElement(node) { var connections = node.connectedElements; for(var key in connections) { removeConnection(node, graph.getNode(key), false); } var toRemove = d3.select("#" + node.elementId); if(toRemove.classed("selected")) selectedElement = null; toRemove.remove(); storeLocalChanges(); } function addConnection(originNode, toNode, originSelection, toSelection) { var line = d3.select("#main-container").insert("line", "#bounding-rect") .classed("connection", true) .attr("x1", originSelection.attr("x")) .attr("y1", originSelection.attr("y")) .attr("x2", toSelection.attr("x")) .attr("y2", toSelection.attr("y")) .attr("marker-end", "url(#arrowhead)"); originNode.addConnection(toSelection.attr("id"), line, false); toNode.addConnection(originSelection.attr("id"), line, true); storeLocalChanges(); } function removeConnection(originNode, toNode, store) { originNode.removeConnection(toNode.elementId); toNode.removeConnection(originNode.elementId); if(store) storeLocalChanges(); } /*** * End Node/Link Storage ***/ /*** * SVG Event Handlers ***/ var zoom = d3.behavior.zoom() .scaleExtent([.15, 10]) .on("zoom", zoomed); var drag = d3.behavior.drag() .origin(function() { var el = d3.select(this); return {"x" : el.attr("x"), "y" : el.attr("y")}; }) .on("dragstart", dragstarted) .on("drag", dragged) .on("dragend", dragended); var elementClickHandler = function() { if(d3.event.defaultPrevented) return; if(selectedElement !== null) { if(selectedElement[0][0] !== this){ selectedElement.classed("selected", false); var updatedSelection = d3.select(this).classed("selected", true); var selectedNode = graph.getNode(selectedElement.attr("id")); var updatedNode = graph.getNode(this.id); if(selectedNode.getConnection(this.id) === undefined) { addConnection(selectedNode, updatedNode, selectedElement, updatedSelection); } selectedElement = updatedSelection; } } else { $("#selected-options").css({ display: 'inline-block', opacity:0 }).animate({ opacity: 1 }); selectedElement = d3.select(this); selectedElement.classed("selected", true); } }; var internalClickHandler = function() { if(d3.event.defaultPrevented) return; if(selectedElement !== null) { if(d3.event.toElement.id === "bounding-rect"){ selectedElement.classed("selected", false); selectedElement = null; $("#selected-options").fadeOut("fast"); } } else { var location = d3.mouse(this); var x = location[0]; var y = location[1]; var element = d3.select("#main-container").append("g").call(drag).on("click", elementClickHandler) .attr("x", x).attr("y", y).attr("data-scale", 3) .attr("transform", "translate(" + x + "," + y + ") scale(3)") .attr("id", "el-" + elementIdCounter++) .classed("node", true); graph.addNode(new GraphNode(element.attr("id"))); element .append("circle") .attr("r", 30).attr("stroke", "black").attr("stroke-width", 1) .attr("fill", "#00FF00"); var textarea = element.append("text").classed("node-text", true).attr("dy", -10) textarea.append("tspan").classed("node-title", true); textarea.append("tspan").classed("node-description", true).attr("x", 0).attr("dy", 5); storeLocalChanges(); } }; function zoomed() { d3.select("#main-container").attr("transform", "translate(" + d3.event.translate + ") scale(" + d3.event.scale + ")"); } var currentlyDragged; var connections; function dragstarted(d) { d3.event.sourceEvent.stopPropagation(); currentlyDragged = graph.getNode(this.id); connections = currentlyDragged.connectedElements; d3.select(this).classed("dragging", true); } function dragged() { var el = d3.select(this); var x = d3.event.x < 0 ? 0 : (d3.event.x > width ? width : d3.event.x); var y = d3.event.y < 0 ? 0 : (d3.event.y > height ? height : d3.event.y); el.attr("x", x); el.attr("y", y); var scale = el.attr("data-scale"); el.attr("transform", "translate(" + x + "," + y + ") scale(" + scale + ")"); for(var key in connections) { var link = connections[key]; var connection = link.connection; if(link.isOrigin) { connection.attr("x2", x); connection.attr("y2", y); } else { connection.attr("x1", x); connection.attr("y1", y); } } } function dragended(d) { d3.event.sourceEvent.stopPropagation(); d3.select(this).classed("dragging", false); storeLocalChanges(); } function initSVG(width, height) { var svg = d3.select("#main-content").append("svg") .attr("id", "main-svg") .style("width", width) .style("height", height) .append("g").attr("transform", "translate(0, 0)").call(zoom); d3.select("#main-svg").append("defs").append("marker") .attr("id", "arrowhead") .attr("viewBox", "0 -5 10 10") .attr("refX", 25) .attr("refY", 0) .attr("markerWidth", 6) .attr("markerHeight", 6) .attr("orient", "auto") .append("path") .attr("d", "M0,-5L10,0L0,5"); var container = svg.append("g").attr("id", "main-container") .on("click", internalClickHandler); } /*** * End SVG Event Handlers ***/ /*** * Button Handlers ***/ function bindEvents() { $("#clear-map").click(function(){ graph = new Graph(); elementIdCounter = 0; $("#main-container g").remove(); $("#main-container line").remove(); selectedElement = null; storeLocalChanges(); }); $("#edit-node").click(function(){ if(selectedElement !== null) { $("#edit-svg").empty(); var editSvg = d3.select("#edit-svg"); var translateX = parseInt(editSvg.attr("width")) / 2; var translateY = parseInt(editSvg.attr("height")) / 2; var translate = "translate(" + translateX + "," + translateY + ") scale(5)"; var clonedNode = clone(selectedElement); clonedNode.attr("data-id", clonedNode.attr("id")); clonedNode.attr("id", "editable-node").attr("transform", translate).classed("selected", false); editSvg.append(function(d) { return clonedNode.node(); }); $("#node-title").val($("#editable-node .node-title").html()); $("#node-description").val($("#editable-node .node-description").html()); $("#node-color").val($("#editable-node > :first-child").attr("fill")); } }); $(".scale-change").click(function(){ if(selectedElement !== null) { var scale = parseInt(selectedElement.attr("data-scale")); if(this.id === "decrease-size") scale = Math.max(scale - 1, 1); else scale++; selectedElement.attr("data-scale", scale); selectedElement.attr("transform", selectedElement.attr("transform").split(" ")[0] + " scale(" + scale + ")"); storeLocalChanges(); } }); $("#remove-node").click(function(){ if(selectedElement !== null) { var node = graph.getNode(selectedElement.attr("id")); removeElement(node); $("#selected-options").fadeOut("fast"); } }); $("#node-title").on("input", function(){ var val = $(this).val(); $("#editable-node .node-title").html(val); }); $("#node-description").on("input", function(){ var val = $(this).val(); $("#editable-node .node-description").html(val); }); $("#node-color").on("input", function(){ var val = $(this).val(); $("#editable-node > :first-child").attr("fill", val); }); $("#confirm-edit").click(function(){ var replacement = $($("#editable-node").html()); replacement.attr("id", replacement.attr("data-id")); var selected = $(".selected"); selected.empty(); selected.append(replacement); selected.html(selected.html()); }); $("#initial-name-edit").on("input", function(){ var val = $(this).val(); if(!val){ $("#initial-confirm-name").attr("disabled", "disabled"); } else { $("#initial-confirm-name").removeAttr("disabled"); var found = false; for(var i = 0;i < window.localStorage.length;i++){ if(val == window.localStorage.key(i)){ found = true; $("#initial-replace-warning").fadeIn(); break; } } if(found === false) $("#initial-replace-warning").fadeOut(); } }); $("#initial-confirm-name").click(function(){ graphName = $("#initial-name-edit").val(); $("#initial-name-edit").val(""); $(this).attr("disabled", "disabled"); $("#initial-replace-warning").fadeOut(); var mainContainer = $("#main-container"); mainContainer.empty(); $("#idea-name").text(graphName); d3.select("#main-container").append("rect").attr("width", width).attr("height", height).attr("id", "bounding-rect"); $.mobile.changePage($("#svg-page"), {transition: "slide"}); graph = new Graph(); storeLocalChanges(); populateList(); }); $("#confirm-delete").click(function(){ var popup = $("#delete-map-popup"); var key = popup.attr("data-graph"); delete window.localStorage[key]; populateList(); popup.popup("close"); }); $("#idea-name-change").click(function(){ var name = $("#idea-name").text(); $("#idea-name-edit").val(name); }); $("#idea-name-edit").on("input", function(){ var val = $(this).val(); if(!val){ $("#confirm-name").attr("disabled", "disabled"); } else { $("#confirm-name").removeAttr("disabled"); var found = false; for(var i = 0;i < window.localStorage.length;i++){ if(val === window.localStorage.key(i) && val !== graphName){ found = true; $("#replace-warning").fadeIn(); break; } } if(found === false) $("#replace-warning").fadeOut(); } }); $("#confirm-name").click(function(){ var newKey = $("#idea-name-edit").val(); if(newKey !== graphName){ window.localStorage[newKey] = window.localStorage[graphName]; delete window.localStorage[graphName]; graphName = newKey; $("#idea-name").text(graphName); populateList(); } $("#replace-warning").fadeOut(); $("#idea-name-popup").popup("close"); }); } function populateList() { var list = $("#graph-list"); $(".graph-list-item").parent().remove(); for(var i = 0;i < localStorage.length;i++){ var key = localStorage.key(i); var listItem = $('<li>' + '<a class="graph-list-item">' + key + '</a>' + '<a href="#delete-map-popup" data-graph="' + key + '" class="delete-list-item" data-rel="popup" data-position-to="window" data-transition="pop"></a>' + '</li>'); list.prepend(listItem); } list.listview("refresh"); $(".graph-list-item").click(function(){ graphName = $(this).text(); var mainContainer = $("#main-container"); mainContainer.empty(); $("#idea-name").text(graphName); $.mobile.changePage($("#svg-page"), {transition: "slide"}); initFromStorage(); }); $(".delete-list-item").click(function(){ var key = $(this).attr("data-graph"); $("#delete-map-name").text(key); $("#delete-map-popup").attr("data-graph", key); }); } /*** * End Button Handlers ***/ /*** * Page Init Functions ***/ $('#list-page').live('pageinit', function(event) { var availWidth = screen.availWidth; var availHeight = screen.availHeight - $("#header").height() - $("#footer").height(); width = availWidth * 3; height = availHeight * 3; populateList(); var mainContent = $("#main-content"); mainContent.css("width", "100%"); mainContent.css("height", availHeight + "px"); initSVG(width, height); bindEvents(); }); function init() { var onDeviceReady = function() { }; var updateScreen = function() { }; window.addEventListener("orientationchange", function(e){ updateScreen(); }, false); document.addEventListener("deviceready", onDeviceReady, true); } /*** * End Page Init Functions ***/ /** * Random Functions ***/ function clone(selectedElement) { return d3.select(selectedElement.node().cloneNode(true)); }
module.exports = { env: { browser: true, jest: true, }, parser: 'babel-eslint', globals: { google: true, }, plugins: [ 'babel', ], settings: { 'import/resolver': { webpack: { config: './webpack/resolve.js', }, }, }, extends: 'airbnb', rules: { /* possible errors */ 'no-console': 'off', /* best practises */ 'accessor-pairs': 'error', curly: ['error', 'all'], 'no-alert': 'error', 'no-div-regex': 'error', 'no-new': 'off', 'no-param-reassign': 'off', 'vars-on-top': 'off', 'wrap-iife': ['error', 'inside', { functionPrototypeMethods: false }], /* stylistic issues */ 'consistent-this': ['error', '_this'], 'func-names': 'off', indent: ['error', 2, { SwitchCase: 1 }], 'max-depth': ['error', 3], 'max-len': ['error', 120, 2, { ignoreComments: true }], 'max-nested-callbacks': [2, 3], 'max-params': ['error', 5], 'no-bitwise': ['error', { int32Hint: true }], 'no-mixed-operators': 'off', 'no-plusplus': 'off', 'no-restricted-syntax': 'off', 'padded-blocks': ['error', { classes: 'always', blocks: 'never', switches: 'never' }], /* es6 */ 'arrow-parens': ['error', 'as-needed'], /* react */ 'react/jsx-filename-extension': 'off', 'react/jsx-one-expression-per-line': 'off', /* jsx-a11y */ 'jsx-a11y/anchor-is-valid': ['error', { components: ['Link'], specialLink: ['hrefLeft', 'hrefRight', 'to'], aspects: ['noHref', 'invalidHref', 'preferButton'], }], /* import */ 'import/no-extraneous-dependencies': ['error', { 'devDependencies': [ "**/*.stories.js", "**/*.test.js", "**/*.spec.js", "**/jest/setup/enzymeSetup.js", ] }], /* airbnb off, babel on */ semi: 'off', 'babel/semi': ['error', 'always'], quotes: 'off', 'babel/quotes': ['error', 'single', { avoidEscape: true }], }, };
var config; function methodConfigHelper() { beforeEach(function () { config = configurator() .children() .numberNode('property1').required().greaterThan(4).lessThan(11).end() .stringNode('property2').setDefault('defaultString').end() .objectNode('nested') .children() .booleanNode('property1').required().end() .stringNode('property2').end() .end() .end() .arrayNode('collection') .children() .objectNode('all') .children() .stringNode('property1').greaterThan(10).lessThan(20).end() .stringNode('property2').end() .end() .end() .end() .end() .arrayNode('array') .children() .booleanNode('all').end() .end() .end() .mixedNode('mixed').end() .mixedNode('mixedWithChildren') .children() .stringNode('all').end() .end() .end() .stringNode('email').regex(/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i).end() .stringNode('gender').choice(['male', 'female']).end() .stringNode('country').notEmpty().end() .numberNode('subscribe').choice([0, 1]).end() .mixedNode('mixedNodeWithAssert').greaterThan(0).lessThan(10).end() .mixedNode('mixedNode').choice([true, 'string', 5]).end() .mixedNode('mixedNodeNotEmpty').notEmpty().end() .arrayNode('arrayCount').count(1, 10).end() .functionNode('callback').end() .end(); }); afterEach(function () { config = null; }); } function argConfigHelper() { beforeEach(function () { config = configurator([ new configurator.NumberNode('property1').greaterThan(4).lessThan(11).required(), new configurator.StringNode('property2').setDefault('defaultString'), new configurator.ObjectNode('nested', [ new configurator.BooleanNode('property1').required(), new configurator.StringNode('property2') ]), new configurator.ArrayNode('collection', [ new configurator.ObjectNode('all', [ new configurator.StringNode('property1').greaterThan(10).lessThan(20), new configurator.StringNode('property2') ]) ]), new configurator.ArrayNode('array', [ new configurator.BooleanNode('all') ]), new configurator.MixedNode('mixed'), new configurator.MixedNode('mixedWithChildren', [ new configurator.StringNode('all') ]), new configurator.StringNode('email').regex(/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i), new configurator.StringNode('gender').choice(['male', 'female']), new configurator.StringNode('country').notEmpty(), new configurator.NumberNode('subscribe').choice([0, 1]), new configurator.MixedNode('mixedNodeWithAssert').greaterThan(0).lessThan(10), new configurator.MixedNode('mixedNode').choice([true, 'string', 5]), new configurator.MixedNode('mixedNodeNotEmpty').notEmpty(), new configurator.ArrayNode('arrayCount').count(1, 10), new configurator.FunctionNode('callback') ]); }); afterEach(function () { config = null; }); }
(function(angular, undefined) { 'use strict'; angular.module('voteroidApp.constants', []) .constant('appConfig', {userRoles:['guest','user','admin']}) ; })(angular);
//Dojo Configuration : var dojoConfig = { async:true, //All your sources MUST be AMD compliant ! baseUrl: "/base/src", cacheBust:new Date(), packages:[ {name:"dojo", location:"/base/node_modules/dojo"}, {name:"stubborn", location:"/base", main:"stubborn"}, {name:"testApp", location:"/base/test/app"}, {name:"testStub", location:"/base/test/stub"} ], //updated by karma-dojo-adapter: deps: null, waitSeconds:30, //custom objects for test purposes appConfig:{ foo:'bar', car:'cdr', welcomeMessage: "Hello World !" }, has:{ "dojo-undef-api":1 }, //Dojo Trace API //for debugging : trace:{ "loader-run-factory":0, "loader-define":0 }, //callback used when specified deps will be loaded: callback:null, //updated by karma-dojo-adapter loaderPatch: { undef: function(moduleId, referenceModule){ // In order to reload a module, it must be undefined (this routine) and then re-requested. // This is useful for testing frameworks (at least). delete require.modules[moduleId]; } }, locale:"en" }
define("#base/0.9.13/aspect",[],function(a,b){function d(a,b,d,g){var h=b.split(c),i,j;while(i=h.shift())j=e(this,i),j.__isAspected||f.call(this,i),this.on(a+":"+i,d,g);return this}function e(a,b){var c=a[b];if(!c)throw"Invalid method name: "+b;return c}function f(a){var b=this[a];this[a]=function(){var c=Array.prototype.slice.call(arguments),d=["before:"+a].concat(c);this.trigger.apply(this,d);var e=b.apply(this,arguments);return this.trigger("after:"+a,e),e},this[a].__isAspected=!0}b.before=function(a,b,c){return d.call(this,"before",a,b,c)},b.after=function(a,b,c){return d.call(this,"after",a,b,c)};var c=/\s+/});
"use strict" var encryption = require('./encryption.js'), sqlite3 = require('sqlite3'), db = new sqlite3.Database('./database/development.sqlite3'), query = require('./database/query'); var helper = require('./helpers/helpers'); /** * @function db.serialize * @memberof database * @description Initializes tables */ db.serialize(function() { /********** users table **********/ //salt from encryption var salt = encryption.salt(); //Drop users table if it exists db.run("DROP TABLE IF EXISTS users"); //Create the users table db.run("CREATE TABLE users (" + "id INTEGER PRIMARY KEY AUTOINCREMENT," + "first_name TEXT," + "last_name TEXT," + "username TEXT UNIQUE," + "email TEXT UNIQUE," + "is_admin BOOLEAN," + "password_digest TEXT,"+ "salt TEXT," + "temp_password TEXT," + "tempPassCreatedOn Text," + "is_verified BOOLEAN," + "secretHash TEXT," + "createdBy TEXT," + "createdOn TEXT)"); //Create a default admin db.run("INSERT INTO users (" + "first_name," + "last_name, "+ "username," + "email," + "is_admin," + "password_digest," + "salt," + "temp_password," + "tempPassCreatedOn," + "is_verified," + "secretHash," + "createdBy," + "createdOn)" + "values" + "(?,?,?,?,?,?,?,?,?,?,?,?,?)", 'Admin', //first name 'User', //last name 'admin', //username 'admin@none.com', //email true, //is admin encryption.digest('password' + salt), //digest salt, //salt null, //temp password null, true, encryption.digest('secret' + salt), 'SEED PROGRAM', helper.getTimestamp() ); //Create a default user db.run("INSERT INTO users (" + "first_name," + "last_name, "+ "username," + "email," + "is_admin," + "password_digest," + "salt," + "temp_password," + "tempPassCreatedOn," + "is_verified," + "secretHash," + "createdBy," + "createdOn)" + "values" + "(?,?,?,?,?,?,?,?,?,?,?,?,?)", 'Standard', //first name 'User', //last name 'user', //username 'user@none.com', //email false, //not admin encryption.digest('password' + salt), //digest salt, //salt null, //temp password null, true, encryption.digest('secret' + salt), 'SEED PROGRAM', helper.getTimestamp() ); //Create an unapproved std user db.run("INSERT INTO users (" + "first_name," + "last_name, "+ "username," + "email," + "is_admin," + "password_digest," + "salt," + "temp_password," + "tempPassCreatedOn," + "is_verified," + "secretHash," + "createdBy," + "createdOn)" + "values" + "(?,?,?,?,?,?,?,?,?,?,?,?,?)", 'Another', //first name 'User', //last name 'user2', //username 'user@gmail.com', //email false, //not admin null, //digest (NULL) salt, //salt 'DFRxVyumnvPg', //temp password helper.getTimestamp(), false, encryption.digest('secret' + salt), 'SEED PROGRAM', helper.getTimestamp() ); //Log contents of the user table to the console db.each("SELECT * FROM users", function(err, row){ if(err) return console.error(err); console.log(row); }); /* <Logins> ID Username PasswordHash TempPasswordHash SecretPinHash Salt Is_Verified Is_Admin */ /* <Users> ID FirstName LastName Username CreatedBy CreatedOnDate */ // db.run("DROP TABLE IF EXISTS logins"); // db.run("DROP TABLE IF EXISTS users"); // // var salt = encryption.salt(); // // db.run("CREATE TABLE logins (" + // "Id INTEGER PRIMARY KEY AUTOINCREMENT," + // "Username TEXT UNIQUE," + // "PasswordHash TEXT," + // "TempPasswordHash TEXT ," + // "SecretHash TEXT," + // "Salt TEXT," + // "Is_Verified BOOLEAN,"+ // "Is_Admin BOOLEAN)"); // // db.run("CREATE TABLE users (" + // "Id INTEGER UNIQUE," + // "FirstName TEXT UNIQUE," + // "LastName TEXT," + // "Username TEXT UNIQUE," + // "Email TEXT, " + // "CreatedOnDate TEXT," + // "CreatedBy TEXT)"); // // db.run("INSERT INTO logins (" + // "Username," + // "PasswordHash, "+ // "TempPasswordHash," + // "SecretHash," + // "Salt," + // "Is_Verified," + // "Is_Admin)" + // "values" + // "(?,?,?,?,?,?,?)", // 'admin', //Username // encryption.digest('password' + salt), //PasswordHash // encryption.digest('temp' + salt), //TempPasswordHash // encryption.digest('1234' + salt), //SecretHash // salt, //Salt // true, //Is Verified // true //Is Admin // ); // // db.run("INSERT INTO logins (" + // "Username," + // "PasswordHash, "+ // "TempPasswordHash," + // "SecretHash," + // "Salt," + // "Is_Verified," + // "Is_Admin)" + // "values" + // "(?,?,?,?,?,?,?)", // 'user', //Username // encryption.digest('password' + salt), //PasswordHash // encryption.digest('temp' + salt), //TempPasswordHash // encryption.digest('1234' + salt), //SecretHash // salt, //Salt // true, //Is Verified // false //Is Admin // ); // // db.run("INSERT INTO logins (" + // "Username," + // "PasswordHash, "+ // "TempPasswordHash," + // "SecretHash," + // "Salt," + // "Is_Verified," + // "Is_Admin)" + // "values" + // "(?,?,?,?,?,?,?)", // 'user2', //Username // encryption.digest('password' + salt), //PasswordHash // encryption.digest('temp' + salt), //TempPasswordHash // encryption.digest('1234' + salt), //SecretHash // salt, //Salt // false, //Is Verified // false //Is Admin // ); // // var id; // //insert into users table // db.get(query.selectAll('logins', 'username'), 'admin', (err, rows) => { // if(rows != null) { // id = rows.Id; // console.log(id); // // db.run('INSERT INTO users (' + // "Id," + // "FirstName," + // "LastName," + // "Username," + // "Email, " + // "CreatedOnDate," + // "CreatedBy)" + // "values" + // "(?,?,?,?,?,?,?)", // 1, // 'AdminFirst', // 'AdminLast', // 'admin', // 'adminemail@email.com', // 'DATE', // 'SYSTEM'); // // } // // // // //if we get here, user exists, insert user // // db.run(query.insert('users', 'Id, FirstName, LastName, Username, Email, CreatedOnDate, CreatedBy'), // // id, // // 'AdminFirst', // // 'AdminLast', // // 'admin', // // 'adminemail@email.com', // // //new Date().toLocaleString(), // // 'Date', // // 'System', // // (err, entry) => { // // if(err) { // // //TODO set res status // // //find specific error for logger // // logger.error("Some error 1"); // // // // // // } //end err // // // // console.log("should have worked") // // }); //end insert // // // // // // // }); //end check // db.each("SELECT * FROM users", function(err, rows){ // if(err) return console.error(err); // console.log(rows); // }); console.log("DB SEED DONE!"); });
var THREE = require('three'), DbgDraw = require('./../index')(THREE); var container, stats; var camera, scene, renderer; var mouseX = 0, mouseY = 0; var windowHalfX = window.innerWidth / 2; var windowHalfY = window.innerHeight / 2; init(); animate(); function doDrawing() { var i; // Some lines. for (i = 0; i < 10; i++) { DbgDraw.drawLine(new THREE.Vector3(-20 * i - 20, 20, 20), new THREE.Vector3(-20 * i - 20, 20, -20), 'red'); DbgDraw.drawLine(new THREE.Vector3(-20 * i - 20, 0, 20), new THREE.Vector3(-20 * i - 20, 0, -20), 'green'); DbgDraw.drawLine(new THREE.Vector3(-20 * i - 20, -20, 20), new THREE.Vector3(-20 * i - 20, -20, -20), 'blue'); } // Line strip. // Change positions every frame to show that drawn objects are dynamic. var points = []; for (i = 0; i < 10; i++) { points.push( new THREE.Vector3( Math.random() * 100 + 10, Math.random() * 100 + 10, Math.random() * 100 + 10 )); } DbgDraw.drawLineStrip(points, 'cyan'); // X, Y, Z axes. DbgDraw.drawArrow( new THREE.Vector3(0, 0, 0), new THREE.Vector3(100, 0, 0), 5, 'red' ); DbgDraw.drawArrow( new THREE.Vector3(0, 0, 0), new THREE.Vector3(0, 100, 0), 5, 'green' ); DbgDraw.drawArrow( new THREE.Vector3(0, 0, 0), new THREE.Vector3(0, 0, -100), 5, 'blue' ); // Some boxes. DbgDraw.drawBoundingBox( new THREE.Vector3(-200, 50, 0), new THREE.Vector3(-150, 100, 50), 'red'); DbgDraw.drawBoundingBox( new THREE.Vector3(-190, 60, 10), new THREE.Vector3(-160, 90, 40), 'green'); DbgDraw.drawBoundingBox( new THREE.Vector3(-180, 70, 20), new THREE.Vector3(-170, 80, 30), 'blue'); // Spheres. DbgDraw.drawSphere( new THREE.Vector3(0, 0, 0), 10, 'black'); DbgDraw.drawSphere( new THREE.Vector3(-100, 80, 0), 30, 'red'); DbgDraw.drawSphere( new THREE.Vector3(-50, 80, 0), 15, 'green'); DbgDraw.drawSphere( new THREE.Vector3(-20, 80, 0), 7.5, 'blue'); } function init() { container = document.createElement( 'div' ); document.body.appendChild( container ); camera = new THREE.PerspectiveCamera( 40, window.innerWidth / window.innerHeight, 1, 1000 ); camera.position.set( 0, 100, 400 ); scene = new THREE.Scene(); renderer = new THREE.WebGLRenderer( { antialias: true } ); renderer.setClearColor( 0xf0f0f0 ); renderer.setSize( window.innerWidth, window.innerHeight ); container.appendChild( renderer.domElement ); stats = new Stats(); stats.domElement.style.position = 'absolute'; stats.domElement.style.top = '0px'; container.appendChild( stats.domElement ); document.addEventListener( 'mousemove', onDocumentMouseMove, false ); document.addEventListener( 'touchstart', onDocumentTouchStart, false ); document.addEventListener( 'touchmove', onDocumentTouchMove, false ); window.addEventListener( 'resize', onWindowResize, false ); } function onWindowResize() { windowHalfX = window.innerWidth / 2; windowHalfY = window.innerHeight / 2; camera.aspect = window.innerWidth / window.innerHeight; camera.updateProjectionMatrix(); renderer.setSize( window.innerWidth, window.innerHeight ); } function onDocumentMouseMove( event ) { mouseX = event.clientX - windowHalfX; mouseY = event.clientY - windowHalfY; } function onDocumentTouchStart( event ) { if ( event.touches.length === 1 ) { event.preventDefault(); mouseX = event.touches[ 0 ].pageX - windowHalfX; mouseY = event.touches[ 0 ].pageY - windowHalfY; } } function onDocumentTouchMove( event ) { if ( event.touches.length === 1 ) { event.preventDefault(); mouseX = event.touches[ 0 ].pageX - windowHalfX; mouseY = event.touches[ 0 ].pageY - windowHalfY; } } function animate() { requestAnimationFrame( animate ); doDrawing(); render(); stats.update(); } function render() { camera.position.x += ( mouseX - camera.position.x ) * 0.05; camera.position.y += ( - mouseY - camera.position.y ) * 0.05; camera.lookAt( scene.position ); // Update the debug drawer every frame. DbgDraw.render(scene); renderer.render(scene, camera); }
var @_port = chrome.runtime.connect {name: "onClicked"}; @_port.sendMessage{ message: "YES" };
/* Write an expression that calculates trapezoid's area by given sides a and b and height h. */ var a = 0.222; var b = 0.333; var h = 0.555; var area = (a + b) / 2 * h; console.log (area);
"use strict"; var React = require('react'); var navigate = require('react-mini-router').navigate; var marked = require("marked"); var api = require('./api'); var PostSettings = React.createClass({ render: function() { return ( <div className="settings-menu-container ember-view" id="entry-controls"> <div id="entry-controls"> <div className="settings-menu-pane-in settings-menu settings-menu-pane"> <div className="settings-menu-header"> <h4>Post Settings</h4> <button className="close settings-menu-header-action" onClick={this.props.onClose}><i className="fa fa-close fa-2x" /><span className="sr-only">Close</span></button> </div> <div className="settings-menu-content"> <section className="image-uploader js-post-image-upload"> <span className="media"><span className="sr-only">Image Upload</span></span> <img className="js-upload-target" style={{display: 'none'}} src /> <div className="description">Add post image<strong /></div> <input name="uploadimage" className="main" type="file" /> <div className="js-fail failed" style={{display: 'none'}}>Something went wrong :(</div> <button className="js-fail btn btn-green" style={{display: 'none'}}>Try Again</button> <a title="Add image from URL" className="image-url"><i className="fa fa-link"><span className="sr-only">URL</span></i></a> </section> <form onChange={this.props.onChange}> <div className="form-group"> <label htmlFor="url">Post URL</label> <div className="input-group"> <span className="input-group-addon"><i className="fa fa-link" /></span> <input name="post-setting-slug" id="url" className="form-control" type="text" /> </div> <a href="/blah" target="_blank" className="ublog-url-preview" tabIndex="-1">ublog.io/blah/</a> </div> <div className="form-group"> <label htmlFor="post-setting-date">Publish Date</label> <div className="input-group"> <span className="input-group-addon"><i className="fa fa-calendar" /></span> <input name="post-setting-date" id="post-setting-date" className="form-control" type="text" /> </div> </div> <div className="form-group"> <label htmlFor="tag-input">Tags</label> <div className="input-group"> <span className="input-group-addon">#</span> <input name="post-setting-tags" id="tag-input" className="form-control" type="text" /> </div> </div> <div className="form-group"> <label htmlFor="author-list">Author</label> <div className="input-group"> <span className="input-group-addon"><i className="fa fa-user" /></span> <span tabIndex="0"> <div id="author-list"> <select className="form-control"> <option value={1}>Fireball</option> </select> </div> </span> </div> </div> <div className="form-group"> <div className="checkbox"> <label htmlFor="static-page"> <input name="static-page" id="static-page" type="checkbox" /> Turn this post into a static page </label> </div> <div className="checkbox"> <label htmlFor="published"> <input name="published" id="published" ref="published" type="checkbox" defaultChecked={this.props.post.published} /> Publish this post </label> </div> </div> </form> </div> </div> <div className="settings-menu-pane-out-right settings-menu settings-menu-pane"> <div></div> </div> </div> </div>); } }); var Editor = React.createClass({ getInitialState: function() { return { settings: false, updating: false, loading: false, pid: 0, value: 'Type some *markdown* on the left!', published: true }; }, componentDidMount: function() { // Do not reload same data if it's passed in via init property //if (!this.state.posts) { this.loadPost(this.props); //} }, // This is needed in case URL is changed by something else than the component itself componentWillReceiveProps: function(newProps) { if (this.props.pid != newProps.pid) { this.loadPost(newProps); } }, loadPost: function(props) { // Don't return anything if we are creating a new post if (props.pid == 0) { this.setState(this.getInitialState()); return; } this.setState({ loading: true }); var query = { pid: props.pid }; props.blog.api.getPosts(query, function(post) { if (!post) { this.setState({ loading: false }); return; } this.refs.source.value = post.content; this.refs.title.value = post.title; this.setState({ loading: false, pid: post.id, value: post.content, published: post.published }); }.bind(this)); }, onSettingsClose: function() { this.setState({settings: false}); }, onSettingsShow: function() { this.setState({settings: true}); }, onSettingsChange: function() { // Update our state regarding changes in the settings var sts = this.refs.settings; this.setState({ published: sts.refs.published.checked }); }, onUpdatePost: function() { // Start updating the post contents var title = this.refs.title.value; var text = this.refs.source.value; var post = { title: title, content: text, id: this.state.pid, published: this.state.published }; this.setState({ updating: true }); api.updatePost(post, this.onUpdatePostDone); }, onUpdatePostDone: function(res) { this.setState({ updating: false }); if (res) { // All good, we got a post body in reply, update it this.setState({ pid: res.id, published: res.published, value: res.content }); } }, onSourceTextChange: function(e) { this.setState({value: this.refs.source.value}); }, onSourceTextScroll: function(e) { var src = e.target; var preview = this.refs.previewContainer; // End of scroll: element.scrollHeight - element.scrollTop === element.clientHeight var r1 = preview.scrollHeight - preview.clientHeight; var r2 = src.scrollHeight - src.clientHeight; var perc = src.scrollTop / r2; preview.scrollTop = (preview.scrollHeight - preview.clientHeight) * perc; }, rowMarkup: function() { return { __html: marked(this.state.value, {sanitize: false}) }; }, render: function() { var st = this.state; var loading = null; if (st.loading) loading = <div className="loaddimmer"><i className="fa fa-spinner fa-spin fa-4x" /></div>; var globalClass = 'post-editor'; if (st.settings) globalClass += ' settings-menu-expanded'; var actionButtonText = null; if (st.pid == 0) { if (st.published) actionButtonText = 'Create Post'; else actionButtonText = 'Create Draft'; } else { if (st.published) actionButtonText = 'Update Post'; else actionButtonText = 'Update Draft'; } if (this.state.updating) actionButtonText = <span>Saving... &nbsp;<i className="fa fa-spinner fa-spin" /></span>; return ( <section className={globalClass}> <header className="post-editor-title"> <h2 className="view-title"> <input id="entry-title" ref="title" placeholder="Your Post Title" tabIndex="1" type="text" /> </h2> <section className="post-actions"> <button type="button" className="post-settings" title="Post Settings" onClick={this.onSettingsShow}> <i className="fa fa-cog"></i> </button> <section className="btn-group"> <button type="button" className="btn btn-sm btn-primary" onClick={this.onUpdatePost}> { actionButtonText } </button> <button role="button" className="btn btn-sm btn-primary dropdown-toggle up"> <i className="options icon-arrow2"></i> <span className="sr-only">Toggle Settings Menu</span> </button> </section> </section> </header> <section className="post-editor-container"> <section className="post-editor-pane-container"> <header className="post-editor-pane-footer"> Footer </header> <section className="post-editor-pane-body"> <textarea ref="source" onChange={this.onSourceTextChange} onScroll={this.onSourceTextScroll}/> </section> </section> <section className="post-preview-pane-container"> <header className="post-editor-pane-footer"> Footer </header> <section className="post-editor-pane-body entry-preview-content" ref="previewContainer"> <div className="rendered-markdown" ref="preview" dangerouslySetInnerHTML={this.rowMarkup()} /> </section> </section> </section> <PostSettings ref="settings" post={this.state} onClose={this.onSettingsClose} onChange={this.onSettingsChange} /> { loading } </section>); } }); module.exports = Editor;
export layout from './layout' export colors from './colors' export spacing from './spacing' export typeface from './typeface' export media from './media'
export default (env) => { const obj = Object.keys(env) .filter((key) => env[key]) .reduce((p, key) => { const [value] = env[key]; p[key] = value; return p; }, {}); return Object.assign({}, obj); };
import rollup from 'rollup' import nodeResolve from 'rollup-plugin-node-resolve' import commonjs from 'rollup-plugin-commonjs'; import uglify from 'rollup-plugin-uglify' export default { entry: 'app/main-aot.js', dest: 'aot/dist/build.js', // output a single application bundle sourceMap: false, format: 'iife', plugins: [ nodeResolve({jsnext: true, module: true}), commonjs({ include: 'node_modules/rxjs/**', }), uglify() ] }
const fs = require('fs'); const csv = require('csv-parser'); const mongoose = require('mongoose'); const { userSchema } = require('../auth/schema'); const User = mongoose.model('User', userSchema); mongoose.Promise = global.Promise; // database config const database = { name: process.env.APP_DATABASE_NAME || 'app_default_database', host: process.env.APP_DATABASE_HOST || 'localhost', seed: process.env.APP_DATABASE_SEED || false, customApiKey: process.env.APP_CUSTOM_API_KEY || 'non-secure-api-key', }; console.log('\x1b[33mConnecting to MongoDB:', database, '\x1b[0m'); const dbUri = `mongodb://${database.host}/${database.name}`; mongoose.connect(dbUri); // mongoose.set('debug', true) var dbConnection = mongoose.connection; dbConnection.on( 'error', console.error.bind(console, 'MongoDB connection error:') ); dbConnection.on('connected', () => { fs .createReadStream('Users101317.csv') .pipe(csv()) .on('data', user => { User.findOne({ username: database.customApiKey }).then(api => { User.create( { username: user.SamAccountName, firstName: user.GivenName, lastName: user.Surname, password: 'null', email: user.Mail, accessLevel: 'Basic', lastModifiedBy: api._id, }, (error, key) => { if (error) { console.log(`\x1b[31m${error}\x1b[0m`); } else { console.log( '\x1b[32mSuccessfully created ', key.username, '\x1b[0m' ); } } ); }); }); });
var questions = [ 'Given the choice of anyone in the world, whom would you want as a dinner guest?', 'Would you like to be famous? In what way?', 'Before making a telephone call, do you ever rehearse what you are going to say? Why?', 'What would constitute a “perfect” day for you?', 'When did you last sing to yourself? To someone else?', 'If you were able to live to the age of 90 and retain either the mind or body of a 30-year-old for the last 60 years of your life, which would you want?', 'Do you have a secret hunch about how you will die?', 'Name three things you and your partner appear to have in common.', 'For what in your life do you feel most grateful?', 'If you could change anything about the way you were raised, what would it be?', 'Take four minutes and tell your partner your life story in as much detail as possible.', 'If you could wake up tomorrow having gained any one quality or ability, what would it be?', 'If a crystal ball could tell you the truth about yourself, your life, the future or anything else, what would you want to know?', 'Is there something that you’ve dreamed of doing for a long time? Why haven’t you done it?', 'What is the greatest accomplishment of your life?', 'What do you value most in a friendship?', 'What is your most treasured memory?', 'What is your most terrible memory?', 'If you knew that in one year you would die suddenly, would you change anything about the way you are now living? Why?', 'What does friendship mean to you?', 'What roles do love and affection play in your life?', 'Alternate sharing something you consider a positive characteristic of your partner. Share a total of five items.', 'How close and warm is your family? Do you feel your childhood was happier than most other people’s?', 'How do you feel about your relationship with your mother?', 'Make three true “we” statements each. For instance, “We are both in this room feeling ... “', 'Complete this sentence: “I wish I had someone with whom I could share ... “', 'If you were going to become a close friend with your partner, please share what would be important for him or her to know.', 'Tell your partner what you like about them; be very honest this time, saying things that you might not say to someone you’ve just met.', 'Share with your partner an embarrassing moment in your life.', 'When did you last cry in front of another person? By yourself?', 'Tell your partner something that you like about them already.', 'What, if anything, is too serious to be joked about?', 'If you were to die this evening with no opportunity to communicate with anyone, what would you most regret not having told someone? Why haven’t you told them yet?', 'Your house, containing everything you own, catches fire. After saving your loved ones and pets, you have time to safely make a final dash to save any one item. What would it be? Why?', 'Of all the people in your family, whose death would you find most disturbing? Why?', 'Share a personal problem and ask your partner’s advice on how he or she might handle it. Also, ask your partner to reflect back to you how you seem to be feeling about the problem you have chosen.', ]; module.exports = questions;
'use strict' const reduce = require('lodash.reduce') /** * Возвращает конвертер для сущностей МойСклад * @param {Function} reducer Преобразователь объекта * @returns {convertEntity} Конвертер */ module.exports = function getEntityConverter (reducer) { let reduceEntity = value => new Promise(resolve => reducer(resolve)(value)) /** * Преобразует сущность МойСклад к формату удобному для хранения в CouchDB * @param {Entity} entity Сущность МойСклад * @returns {PromiseLike<TransformedEntity>} Преобразованная сущность МойСклад */ function convertEntity (entity) { return reduce(entity, (result, value, key) => result.then(res => (value instanceof Object ? convertEntity(value).then(reduceEntity) : reduceEntity(value)).then(reducedValue => { res[key] = reducedValue return res })), Promise.resolve(entity instanceof Array ? [] : {})) } return entity => convertEntity(JSON.parse(JSON.stringify(entity))).then(reduceEntity) }
var config = Meteor.settings; // github login if (config.Github_AK && config.Github_SK){ console.log('Config github ...'); ServiceConfiguration.configurations.upsert( { service: 'github' }, { $set: { clientId: config.Github_AK, loginStyle: 'popup', secret: config.Github_SK, } } ); } // kadira monitor if (config.Kadira_AK && config.Kadira_SK) { console.log('Config kadira ...'); Kadira.connect(config.Kadira_AK, config.Kadira_SK); }
/** * REIA - MIT license * https://github.com/cneuro/reia * client * @author Chris Nater * */ /// CREATED /// Template.configuration.onCreated( function () { this.subscribe('metrics'); }); /// HELPERS /// Template.configurationMetricsSummary.helpers({ 'columns': function () { return ['Active & inactive', 'Active', 'Inactive']; }, 'subColumns': function () { return ['Total', 'Inputs', 'Outputs']; }, 'activeSwitches': function () { return [null, true, false]; }, 'notBasic': function (type, active) { return __getMetrics( { '$ne': 'basic' }, type, _.isBoolean(active) ? { 'active': (active ? {'$ne': false} : false) } : {} ); } }) Template.configurationTabContent.helpers({ 'active': function () { return this.active !== false; }, 'tabContentData': function () { return Template.parentData(); } }); Template.configurationMetricsScoringFormRow.helpers({ 'unitType': function () { return Template.parentData().unitType || Template.parentData(2).unitType; }, 'points': function () { return Template.parentData().points[this.index]; } }); /// EXTENSIONS /// Template.configurationMetricsPanelTitle.inheritsHelpersFrom('configuration'); Template.configurationMetricsSummary.inheritsHelpersFrom('configuration');
'use strict'; angular.module('mygameApp') .factory('game', function () { var tileNames = ['8-ball', 'kronos', 'baked-potato', 'dinosaur', 'rocket', 'skinny-unicorn', 'that-guy', 'zeppelin']; return new Game(tileNames); });
// Load dependencies var Promise = require('bluebird'); var Utils = require('./utils'); var Request = Promise.promisifyAll(require("request")); var Hoek = require('hoek'); var Kilt = require('kilt'); var Events = require('events'); var _ = require('lodash'); var Modelo = require('modelo'); // Load modules var Api = require('./api'); var Discover = require('./discover'); var Bridge = require('./bridge'); var Debugger = require('./debugger'); // Declare internals var internals = { debug: new Debugger('hue') }; /** * @class Hue * @param {String} username * @param {String} ip * @constructor */ module.exports = internals.Hue = function Hue(username, ip) { Hoek.assert(this.constructor === internals.Hue, 'Hue must be instantiated using new'); Hoek.assert(username && typeof username === 'string', 'Username must be a string'); Hoek.assert(typeof ip === 'undefined' || typeof ip === 'string', 'IP Address must be a string'); this._events = new Kilt(); internals.debug('Attached a Kilt instance to the new hue instance'); this._discover = new Discover(this); internals.debug('Attached a Discover instance to the new hue instance'); Bridge.call(this); if (!ip) { internals.debug('Auto discovering bridges on the network'); this.discover().bind(this).then(function(results) { if (results[0] && results[0].internalipaddress) { internals.debug('Auto discover successful: %o', results[0]); this.init(results[0].internalipaddress, username); } else { // TODO: Handle no results internals.debug('Auto discovered failed to find a bridge'); this._events.emit('bridge.failed', 'No bridges could be found'); } }); } else { internals.debug('Manually intializing the bridge with IP: %s', ip); this.init(ip, username); } } Modelo.inherits(internals.Hue, Bridge); /** * Discovers the bridges on the network * http://www.developers.meethue.com/documentation/hue-bridge-discovery * * @method discover * @param {String|Array} method can be a string to search via one method, or an array of search methods ['upnp', 'nupnp', 'ip'] * @return {Promise} will return a promise that will resolve with the discovered bridges */ internals.Hue.prototype.discover = function discover(method) { var discover = this._discover; internals.debug('Running discover using %s method', method || 'waterfall'); return Promise.using(discover.search(method), function(search) { internals.debug('Search completed with the following results: %o', search); return Promise.resolve(search); }); }; /** * Gets the description of any bridge on the network * The bridge will return the description in XML form, by default this will * parse that into json, but can be chosen to be kept as XML * http://www.developers.meethue.com/documentation/hue-bridge-discovery * * @method description * @param {String} ip the IP address of the bridge to get description information * @param {Boolean} parse parse the xml data into json, by default this is set to `true` * @return {Promise} will return a promise that will resolve with the parsed description */ internals.Hue.prototype.description = Promise.method(function description(ip, parse) { var endpoint = Utils.getEndpoint(ip, '/description.xml'); return Request.getAsync(endpoint).spread(function(response, xml) { if (typeof parse === 'boolean' && parse === false) { return Promise.resolve(xml); } else { return Utils.parseXml(xml); } }); }); /** * Notifies when this instance is ready to be used * - Bridge is found * * @method ready * @return {Promise} will return a promise that will resolve when ready to be used */ internals.Hue.prototype.ready = function ready() { return new Promise(function(resolve, reject) { if (this._bridgeReady) { return resolve(); } else { this._events.on('bridge.initialized', resolve); this._events.on('bridge.failed', reject); } }.bind(this)).bind(this); };
$(document).ready(function(){ // === Sidebar navigation === // $('.submenu > a').click(function(e) { e.preventDefault(); var submenu = $(this).siblings('ul'); var li = $(this).parents('li'); var submenus = $('#sidebar li.submenu ul'); var submenus_parents = $('#sidebar li.submenu'); if(li.hasClass('open')) { if(($(window).width() > 768) || ($(window).width() < 479)) { submenu.slideUp(); } else { submenu.fadeOut(250); } li.removeClass('open'); } else { if(($(window).width() > 768) || ($(window).width() < 479)) { submenus.slideUp(); submenu.slideDown(); } else { submenus.fadeOut(250); submenu.fadeIn(250); } submenus_parents.removeClass('open'); li.addClass('open'); } }); var ul = $('#sidebar > ul'); $('#sidebar > a').click(function(e) { e.preventDefault(); var sidebar = $('#sidebar'); if(sidebar.hasClass('open')) { sidebar.removeClass('open'); ul.slideUp(250); } else { sidebar.addClass('open'); ul.slideDown(250); } }); // === Resize window related === // $(window).resize(function() { if($(window).width() > 479) { ul.css({'display':'block'}); $('#content-header .btn-group').css({width:'auto'}); } if($(window).width() < 479) { ul.css({'display':'none'}); fix_position(); } if($(window).width() > 768) { $('#user-nav > ul').css({width:'auto',margin:'0'}); $('#content-header .btn-group').css({width:'auto'}); } }); if($(window).width() < 468) { ul.css({'display':'none'}); fix_position(); } if($(window).width() > 479) { $('#content-header .btn-group').css({width:'auto'}); ul.css({'display':'block'}); } // === Tooltips === // $('.tip').tooltip(); $('.tip-left').tooltip({ placement: 'left' }); $('.tip-right').tooltip({ placement: 'right' }); $('.tip-top').tooltip({ placement: 'top' }); $('.tip-bottom').tooltip({ placement: 'bottom' }); // === Search input typeahead === // // $('#search input[type=text]').typeahead({ // source: ['Dashboard','Form elements','Common Elements','Validation','Wizard','Buttons','Icons','Interface elements','Support','Calendar','Gallery','Reports','Charts','Graphs','Widgets'], // items: 4 // }); // === Fixes the position of buttons group in content header and top user navigation === // function fix_position() { var uwidth = $('#user-nav > ul').width(); $('#user-nav > ul').css({width:uwidth,'margin-left':'-' + uwidth / 2 + 'px'}); var cwidth = $('#content-header .btn-group').width(); $('#content-header .btn-group').css({width:cwidth,'margin-left':'-' + uwidth / 2 + 'px'}); } // === Style switcher === // $('#style-switcher i').click(function() { if($(this).hasClass('open')) { $(this).parent().animate({marginRight:'-=190'}); $(this).removeClass('open'); } else { $(this).parent().animate({marginRight:'+=190'}); $(this).addClass('open'); } $(this).toggleClass('icon-arrow-left'); $(this).toggleClass('icon-arrow-right'); }); $('#style-switcher a').click(function() { var style = $(this).attr('href').replace('#',''); $('.skin-color').attr('href','css/maruti.'+style+'.css'); $(this).siblings('a').css({'border-color':'transparent'}); $(this).css({'border-color':'#aaaaaa'}); }); $('.lightbox_trigger').click(function(e) { e.preventDefault(); var image_href = $(this).attr("href"); if ($('#lightbox').length > 0) { $('#imgbox').html('<img src="' + image_href + '" /><p><i class="icon-remove icon-white"></i></p>'); $('#lightbox').slideDown(500); } else { var lightbox = '<div id="lightbox" style="display:none;">' + '<div id="imgbox"><img src="' + image_href +'" />' + '<p><i class="icon-remove icon-white"></i></p>' + '</div>' + '</div>'; $('body').append(lightbox); $('#lightbox').slideDown(500); } }); $('#lightbox').live('click', function() { $('#lightbox').hide(200); }); });
import createVoteUsecases from './vote'; export default (providers, present) => { const vote = createVoteUsecases(providers, present); return ({ vote, }); };
import {HttpClient} from 'aurelia-fetch-client'; export class View { static inject() { return [HttpClient]; } constructor(http) { this.http = http; this.id = "Unknown"; this.selected = null; this.messages = []; this.isAttached = false; } update() { this.http.fetch(`api/messages/from/${this.id}`) .then(response => response.json()) .then(messages => this.mergeMessages(messages)); if (this.isAttached) { setTimeout(() => this.update.call(this), 1000 * 3); } } mergeMessages(messageList) { var localIds = this.messages.map(x => x.Id); var remoteIds = messageList.map(x => x.Id); // Add for (var i = 0; i < remoteIds.length; i++) { var id = remoteIds[i]; var exists = localIds.indexOf(id); if (exists === -1) { var message = messageList[i]; console.log(`New messages ${message.Id} found.`); this.messages.push(message); } } // Remove for (var i = 0; i < localIds.length; i++) { var id = localIds[i]; var exists = remoteIds.indexOf(id); if (exists === -1) { var message = this.messages[i]; console.log(`Removed messages ${message.Id} found.`); this.messages.splice(i, 1); } } } activate(params, routeConfig, navigationInstruction) { this.id = params.id; } attached() { this.isAttached = true; this.update(); } detached() { this.isAttached = false; } }
'use strict'; import React from 'react'; import TestUtils from 'react-dom/test-utils'; import { expect } from 'chai'; import createShallowComponent from './utils/createShallowComponent'; import renderIntoDocument from './utils/renderIntoDocument'; import BurgerMenu from '../src/BurgerMenu'; const Menu = BurgerMenu.scaleDown.default; describe('scaleDown', () => { let component, menuWrap, menu, itemList, firstItem; function addWrapperElementsToDOM() { let outerContainer = document.createElement('div'); outerContainer.setAttribute('id', 'outer-container'); let pageWrap = document.createElement('div'); pageWrap.setAttribute('id', 'page-wrap'); outerContainer.appendChild(pageWrap); document.body.appendChild(outerContainer); } function removeWrapperElementsFromDOM() { let outerContainer = document.getElementById('outer-container'); document.body.removeChild(outerContainer); } beforeEach(() => { addWrapperElementsToDOM(); }); afterEach(() => { removeWrapperElementsFromDOM(); }); it('has default menuWrap styles', () => { component = createShallowComponent( <Menu pageWrapId={'page-wrap'} outerContainerId={'outer-container'}> <div>An item</div> </Menu> ); menuWrap = component.props.children[2]; expect(menuWrap.props.style.position).to.equal('fixed'); expect(menuWrap.props.style.zIndex).to.equal(1100); expect(menuWrap.props.style.width).to.equal('300px'); expect(menuWrap.props.style.height).to.equal('100%'); }); it('has correct menu styles', () => { component = renderIntoDocument( <Menu pageWrapId={'page-wrap'} outerContainerId={'outer-container'}> <div>An item</div> </Menu> ); menu = TestUtils.findRenderedDOMComponentWithClass(component, 'bm-menu'); expect(menu.style.height).to.equal('100%'); expect(menu.style.boxSizing).to.equal('border-box'); }); it('has correct itemList styles', () => { component = renderIntoDocument( <Menu pageWrapId={'page-wrap'} outerContainerId={'outer-container'}> <div>An item</div> </Menu> ); itemList = TestUtils.findRenderedDOMComponentWithClass( component, 'bm-item-list' ); expect(itemList.style.height).to.equal('100%'); }); it('has correct item styles', () => { component = renderIntoDocument( <Menu pageWrapId={'page-wrap'} outerContainerId={'outer-container'}> <div>An item</div> </Menu> ); firstItem = TestUtils.findRenderedDOMComponentWithClass( component, 'bm-item-list' ).children[0]; expect(firstItem.style.display).to.equal('block'); }); it('can be positioned on the right', () => { component = renderIntoDocument( <Menu pageWrapId={'page-wrap'} outerContainerId={'outer-container'} right> <div>An item</div> </Menu> ); menuWrap = TestUtils.findRenderedDOMComponentWithClass( component, 'bm-menu-wrap' ); expect(menuWrap.style.right).to.equal('0px'); }); });
test('New basic form', function() { expect(11); visit("/"); click('.menu-item.basic > .model-to-new'); andThen(function() { equal(currentURL(), '/basic/new', "The formular is displayed"); equal(find('.new-document-title').text(), "New Basic", "The title form is rendered"); equal(find('.field:eq(0) .field-name').text(), "title", "The first field name is 'title'"); equal(find('.field:eq(0) .field-input').attr('type'), "text", "A title is a text input"); equal(find('.field:eq(0) .field-input').attr('name'), "title", "Its name is 'title'"); equal(find('.field:eq(1) .field-name').text(), "description", "The second field name is 'description'"); equal(find('.field:eq(1) .field-input').attr('type'), "text", "A description is a text input"); equal(find('.field:eq(1) .field-input').attr('name'), "description", "Its name is 'description'"); equal(find('.field:eq(2) .field-name').text(), "thumb", "The third field name is 'thumb'"); equal(find('.field:eq(2) .field-input').attr('type'), "text", "A thumb is a text input"); equal(find('.field:eq(2) .field-input').attr('name'), "thumb", "Its name is 'thumb'"); }); }); test('Create a Basic', function() { expect(14); visit('/'); andThen(function() { equal(find('.result-item').length, 0, "No result yet"); visit('/basic/new'); fillIn('.field-input[name=title]', 'The big title'); fillIn('.field-input[name=description]', 'The best description ever'); fillIn('.field-input[name=thumb]', "http://placehold.it/40x40"); click('button.save'); andThen(function() { equal(currentURL(), '/basic', 'We go back to the basics list'); equal(find('.result-item').length, 1, "We have now 1 result"); equal(find('.result-item .item-title > a').text().trim(), 'The big title', "The result has a correct title"); equal(find('.result-item .item-description').text(), "The best description ever", "The result has a correct description"); equal(find('.result-item .item-thumb').attr('src'), "http://placehold.it/40x40", "The result has a correct thumb"); click('.result-item:eq(0) > .item-title > a'); andThen(function() { equal(currentPath(), 'generic_model.display'); equal(find('.document-title:contains("The big title")').length, 1, "The document should have the correct title"); equal(find('.document .field:eq(0) .field-name').text(), "title", "the first field name is 'title'"); equal(find('.document .field:eq(0) .field-value').text().trim(), "The big title", "title is correctly filled"); equal(find('.document .field:eq(1) .field-name').text(), "description", "the first field name is 'description'"); equal(find('.document .field:eq(1) .field-value').text().trim(), "The best description ever", "description is correctly filled"); equal(find('.document .field:eq(2) .field-name').text(), "thumb", "the first field name is 'thumb'"); equal(find('.document .field:eq(2) .field-value').text().trim(), "http://placehold.it/40x40", "thumb is correctly filled"); }); }); }); });
const sendApiError = require('../helper').sendApiError; const generateToken = require('../controllers/auth').generateToken; const getUserInfo = require('../controllers/users').getUserInfo; const canLogin = require('../controllers/users').canLogin; const apiLogin = (req, res) => { const {login, password} = req.body; canLogin(login, password) .then(user => { const _user = getUserInfo(user, false); const token = generateToken(_user); res.send({user: _user, token}) }) .catch(error => sendApiError(res, 'Can\'t login.', error)) }; module.exports = apiLogin;
'use strict'; /* Koroutine library configuration */ let _enableBreadcrumbs = false; let _errorHandler = console.log; /** * Enable/disable full stack traces for all coroutines * @param flag {Boolean} */ exports.enableBreadcrumbs = function (flag) { _enableBreadcrumbs = flag; }; /* Current executing Koroutine */ let _resume = false; /** * Set error handle function. Koroutine library passes uncaught exceptions thrown from Koroutine into this function * @param {Function} error_handler_function(errorObject) */ exports.setErrorHandler = function (errHandler) { _errorHandler = errHandler; }; function stitchBreadcrumbs (error, breadcrumbs) { if (breadcrumbs) { breadcrumbs.push(error); const filteredLines = []; for (let i = breadcrumbs.length - 1; i >= 0; i--) { const stack = breadcrumbs[i].stack; if (stack) { const lines = stack.split('\n'); for (let line of lines) { if (!line.includes('koroutine.js') && !line.includes('next (native)')) { filteredLines.push(line); } } } error.stack = filteredLines.join('\n'); } } } /** * Utility function that resumes the coroutine by throwing TimedOut exception when coroutine/callback/future does not finish before set timeout * @param {Function} either resume or future function * @param {String} 'coroutine' or 'callback' or 'future' * @param {String} Name of the callback or future involved. optional. * @param {Number} timeout in milliseconds */ function timedOut (resume, type, name, timeout) { const e = new Error((type || '') + ' ' + (name || '') + ' did not finish within ' + timeout + ' ms.'); e.cause = 'TimedOut'; e.name = name; resume(e); } /** * Used to run coroutine for the first time after it is created * @param iter {Iterator} Iterator received by calling generator function * @param options {Object} Optional options object. It can include following properties * - name: Name of the Koroutine * - timeout: Maximum time in milliseconds up to which this Koroutine is allowed to run * - enableStackTrace: Enable clean stack trace across yields * - stackDepth: Max number of lines to print in case of clean stack traces enabled exceptions */ exports.run = function (iter, options) { if (_resume) { throw new Error('Cannot spawn new koroutine from within another koroutine.'); } if (!iter || typeof iter[Symbol.iterator] !== 'function') { throw new Error('First parameter to koroutine.create() must be iterator returned by a generator function.'); } // const o = options || null; const name = (options && options.name) || ''; const errorHandlerFn = (options && options.errorHandler) || _errorHandler; let breadcrumbs = ((options && options.enableBreadcrumbs) || _enableBreadcrumbs) ? [] : null; let state = new Map(); const resume = function (error, ...rest) { if (!iter) { return; // koroutine already finished } // Callback was invoked so cancel callback timer, if any const cbTimer = resume.callbackTimer; if (cbTimer) { clearTimeout(cbTimer); } try { if (error) { error.cause = error.cause || 'Exception'; stitchBreadcrumbs(error, breadcrumbs); error.koroutine = name; } // Resume suspended koroutine resume.cbInProgress = false; resume.timer = null; exports.state = state; _resume = resume; const result = error ? iter.throw(error) : iter.next(rest); if (result.done) { iter = breadcrumbs = state = null; return result.value; } } catch (e) { e.message = 'Unhandled exception in koroutine ' + (name || '') + ' : ' + e.message; e.koroutine = name; stitchBreadcrumbs(e, breadcrumbs); iter = breadcrumbs = state = null; errorHandlerFn(e); } finally { // we are outside running coroutine, clear "current coroutine" variables exports.state = null; _resume = null; } }; // This is the global timeout that limits duration of the entire Koroutine execution const timeout = (options && options.timeout) || null; if (timeout && timeout > 0) { setTimeout(timedOut, timeout, resume, 'coroutine', name, timeout); } resume.krName = name; resume.breadcrumbs = breadcrumbs; // Start coroutine execution resume(); }; function prepareKoroutineCB (resume) { if (!resume) { throw new Error('koroutine.callback() must be invoked from within an active koroutine'); } if (resume.cbInProgress) { throw new Error('koroutine.callback() called when there is already another callback in progress'); } const breadcrumbs = resume.breadcrumbs; if (breadcrumbs) { const name = resume.krName; const errMessage = name ? name + ' suspended at' : 'suspended at'; breadcrumbs.push(new Error(errMessage)); } } /** * Returns NodeJs style callback function - callback(err, data) - which resumes suspended coroutine when called * @param timeout {Number} in milliseconds. optional. set to null or 0 for infinite time out. * @param name callback name. optional * @return {Function} callback function */ exports.callback = function (timeout, name) { const resume = _resume; prepareKoroutineCB(resume); resume.cbInProgress = true; if (timeout && timeout > 0) { resume.callbackTimer = setTimeout(timedOut, timeout, resume, 'callback', name, timeout); } return resume; }; /** * Returns a Future object that can be passed in place of normal node callback. Future * objects work with koroutine.join() to facilitate firing multiple async operations * from a single coroutine without blocking or yielding and then waiting for all of them * to finish at a single 'join' point in the code * @param timeout {Number} Number of milliseconds after which this future will timeout wih error.cause = 'timedout' * @param name {String} future name. optional. * @return {Function} future callback */ exports.future = function (timeout, name) { const resume = _resume; prepareKoroutineCB(resume); const future = function (error, ...rest) { if (future.done === true) { return; } future.done = true; if (error) { error.cause = error.cause || 'Exception'; future.error = error; } else { future.data = rest; } if (future.isJoined) { resume(null, future); } }; if ((timeout) && (timeout > 0)) { setTimeout(timedOut, timeout, future, 'future', name, timeout); } return future; }; /** * Wait till all the passed in futures are complete - i.e. done executing * @param {Array of futur objects} Futures to wait on * @return {Number} number of futures who returned error */ exports.join = function* (...futures) { let errorCount = 0; for (const future of futures) { while (future.done !== true) { future.isJoined = true; yield; } // future.isJoined = null; if (future.error) { errorCount += 1; } } return errorCount; }; function assertCalledFromKoroutine (name) { const resume = _resume; if (!resume) { throw new Error(name + ' must be called from within an active koroutine'); } return resume; } /** * Sleep for given number of milliseconds. Doesn't block the node's event loop * @param ms {Number} Number of milliseconds to sleep */ exports.sleep = function (timeout) { const resume = assertCalledFromKoroutine('sleep'); setTimeout(resume, timeout); }; /** * Akin to thread.yield() */ exports.defer = function () { const resume = assertCalledFromKoroutine('defer'); setImmediate(resume); };
var debugit = require('debugit').enable(); var debug = debugit.add('samsaara:test:groups'); var test = require('tape').test; var TapeFence = require('./tapefence'); var fences = {}; var WebSocketServer = require('ws').Server; var samsaara = require('samsaara'); var groups = require('../main'); var connectionCount = 0; var wss = new WebSocketServer({ port: 8080 }); // test setup samsaara.on('connection', function(connection) { debug('New Connection', connection.name); fences['New connections'].hit(connection); }); wss.on('connection', function(ws) { samsaara.newConnection(ws, 'connection' + connectionCount++); }); samsaara.expose({ addToGroup: function(groupName) { samsaara.group(groupName).add(this); fences['Wait till Groups Mounted'].hit(this, groupName); }, doneTest: function(cb) { cb(true); fences['Done Test'].hit(this); } }); // tests test('Samsaara Server Exists', function(t) { t.equal(typeof samsaara, 'object'); t.end(); }); test('Samsaara can load Groups middleware', function(t) { samsaara.use(groups); t.end(); }); test('Samsaara can initialize', function(t) { var initialized = samsaara.initialize(); t.equal(initialized, samsaara); t.end(); }); test('Wait for X Connections', function(t) { fences['New connections'] = new TapeFence(5, function() { t.equal(typeof samsaara.connection('connection0'), 'object'); t.equal(typeof samsaara.connection('connection1'), 'object'); t.equal(typeof samsaara.connection('connection2'), 'object'); t.equal(typeof samsaara.connection('connection3'), 'object'); t.equal(typeof samsaara.connection('connection4'), 'object'); t.equal(typeof samsaara.connection('connection0').groups, 'object'); t.equal(samsaara.connection('connection0').groups.all, true); t.end(); }); }); test('Create Groups', function(t) { samsaara.createGroup('groupA'); samsaara.createGroup('groupB'); samsaara.createGroup('groupC'); t.equal(typeof samsaara.group('groupA'), 'object'); t.equal(typeof samsaara.group('groupB'), 'object'); t.equal(typeof samsaara.group('groupC'), 'object'); t.end(); }); test('Hold Test', function(t) { setTimeout(function() { samsaara.group('all').execute('continueTest')(); t.end(); }, 500); }); test('Wait till Groups Mounted', function(t) { fences['Wait till Groups Mounted'] = new TapeFence(10, function() { t.equal(typeof samsaara.group('groupA').members, 'object'); t.equal(typeof samsaara.group('groupB').members, 'object'); t.equal(typeof samsaara.group('groupC').members, 'object'); t.equal(Object.keys(samsaara.group('groupA').members).length, 5); t.equal(Object.keys(samsaara.group('groupB').members).length, 3); t.equal(Object.keys(samsaara.group('groupC').members).length, 2); t.end(); }); }); test('Execute on Groups', function(t) { var aHit = 0; var bHit = 0; var cHit = 0; t.plan(13); samsaara.group('groupA').execute('testMethodA')(5, function(answer) { aHit++; t.equal(10, answer); fences['Execute On Groups'].hit(); }); samsaara.group('groupB').execute('testMethodB')(5, function(answer) { bHit++; t.equal(20, answer); fences['Execute On Groups'].hit(); }); samsaara.group('groupC').execute('testMethodC')(5, function(answer) { cHit++; t.equal('nugget', answer); fences['Execute On Groups'].hit(); }); fences['Execute On Groups'] = new TapeFence(10, function() { t.equal(aHit, 5); t.equal(bHit, 3); t.equal(cHit, 2); t.end(); }); }); test('Hold Test', function(t) { setTimeout(function() { samsaara.group('all').execute('continueTest')(); t.end(); }, 500); }); test('Close Test', function(t) { fences['Done Test'] = new TapeFence(5, function() { wss.close(); t.end(); }); });
/** * Hoodie plugin <%= generatorName %> * Lightweight and easy <%= generatorName %> */ /** * Dependencies */ var <%= capitalizeName %> = require('./lib'); /** * <%= capitalizeName %> worker */ module.exports = function (hoodie, callback) { var <%= generatorName %> = new <%= capitalizeName %>(hoodie); //YO[HOODIE-PLUGIN] hoodie.account.on('change', <%= generatorName %>.addProfileEachUser); callback(); };
'use strict'; const deleteReqValidator = require('../../../app/validators/deleteReqValidator'); const expect = require('chai').expect; const _ = require('lodash'); describe('test/unit/validators/deleteReqValidator check', function() { // eslint-disable-line it('should require a valid id', () => { const paramsEmpty = { params: {} }; let error = deleteReqValidator.check(paramsEmpty) || ''; expect(error.toString()).to.be.equal('VError: 400: id required'); const paramsNullId = { params: { id: '', }, }; error = deleteReqValidator.check(paramsNullId) || ''; expect(error.toString()).to.be.equal('VError: 400: id required'); let paramsId = { params: { id: '2cdc234qreq', }, }; error = deleteReqValidator.check(paramsId); expect(error.toString()).to.be.equal('VError: 400: invalid id'); paramsId = { params: { id: '57543795c5e18d4310a7db1f', }, }; error = deleteReqValidator.check(paramsId); expect(_.toString(error)).to.be.empty; }); }); describe('test/unit/validators/deleteReqValidator sanitize', function() { // eslint-disable-line const sanitizedReq = { params: { id: '57543795c5e18d4310a7db1f', }, }; it('should sanitize params', () => { const params1 = { params: { id: ' 57543795c5e18d4310a7db1f ', }, }; deleteReqValidator.sanitize(params1); expect(params1).to.be.deep.equal(sanitizedReq); }); });
var fs = require('fs'); var jsonFormat = require('json-format'); var distPackageJsonContentAsStr = fs.readFileSync('package.json'); var distPackageJsonContent = JSON.parse(distPackageJsonContentAsStr); distPackageJsonContent['main'] = 'bundles/' + distPackageJsonContent.name + '.umd.min.js'; distPackageJsonContent['module'] = 'index.js'; distPackageJsonContent['typings'] = 'index.d.ts'; Object.defineProperty(distPackageJsonContent, 'peerDependencies', Object.getOwnPropertyDescriptor(distPackageJsonContent, 'dependencies')); delete distPackageJsonContent['dependencies']; delete distPackageJsonContent['devDependencies']; delete distPackageJsonContent['scripts']; fs.writeFileSync('dist/package.json', jsonFormat(distPackageJsonContent, { type: 'space', size: 2 }));
var pg = require('pg') var named = require('node-postgres-named') module.exports = { start: function(room_id, source, dataset, raw_params, callback) { console.log("not suprisingly we have a socket") var conString = "postgres://" + source.user + ":" + source.password + "@" + source.host + "/" + source.database; var client = new pg.Client(conString) named.patch(client) client.connect() var params = {} if (raw_params) { params = _.object(raw_params.map(function (para) { return [para.name, para.value] })) } try { console.log("ok postgres query attempted") client.query(dataset.sql, params, function (err, result) { if (err) { console.log("ok postgres query returned") callback({error: [{ message: err.message }]}) } else { callback({list: result.rows }) } }) } catch (e) { console.log(e.message) callback({error: [{ message: e.message }]}) } } }
/* * Wegas * http://wegas.albasim.ch * * Copyright (c) 2013 School of Business and Engineering Vaud, Comem * Licensed under the MIT License */ /** * @fileoverview * @author Cyril Junod */ YUI.add("treeview", function(Y) { "use strict"; var HOST = "host", SELECTED = "selected", SELECTION = "selection", TREEVIEW = "treeview", TREENODE = "treenode", CONTENT = "content", //TREELEAF = "treeleaf", CONTENT_BOX = "contentBox", BOUNDING_BOX = "boundingBox", getClassName = Y.ClassNameManager.getClassName, classNames = { loading: getClassName(TREENODE, "loading"), collapsed: getClassName(TREENODE, "collapsed"), visibleRightWidget: getClassName(TREEVIEW, "visible-right"), multiSelect: getClassName(TREEVIEW, "multiselect"), emptyMSG: getClassName(TREEVIEW, "empty-msg") }; /** * TreeView main class * <p><strong>Attributes</strong></p> * <ul> * <li>visibleRightWidget {Boolean} should right widget be shown.</li> * </ul> * @name Y.TreeView * @class TreeView class * @extends Y.Widget# * @constructor * @param Object Will be used to fill attributes field */ Y.TreeView = Y.Base.create(TREEVIEW, Y.Widget, [Y.WidgetParent], { /** @lends Y.TreeView# */ CONTENT_TEMPLATE: "<ul></ul>", /** * Lifecycle method * @private * @function * @returns {undefined} */ initializer: function() { this.publish("nodeClick", { defaultFn: function(e) { this.deselectAll(); e.node.set(SELECTED, 2); } }); }, /** * Lifecycle method * @private * @function * @returns {undefined} */ bindUI: function() { //this.after("*:addChild", function(e) { // /* Selection is not updated if a child with selected attribute is added, force it. */ // e.target._set(SELECTION, e.target.get(SELECTION)); //}); this.after("addChild", function(e) { this.get(BOUNDING_BOX).all("." + classNames.emptyMSG).remove(true); }); this.after("removeChild", function(e) { if (!this.size()) { this.get(BOUNDING_BOX).append("<div class='" + classNames.emptyMSG + "'>" + this.get("emptyMsg") + "</div>"); } }); this.get(CONTENT_BOX).delegate("click", function(e) { var node = e.target, widget = Y.Widget.getByNode(e.currentTarget); e.stopPropagation(); if (node.hasClass(widget.getClassName(CONTENT, "icon"))) { this.fire("iconClick", { node: widget }); } if (node.hasClass(widget.getClassName(CONTENT, "label"))) { widget.fire("labelClick", { node: widget }); } if (node.hasClass(widget.getClassName(CONTENT, "toggle"))) { widget.fire("toggleClick", { node: widget }); } else { widget.fire("click", { node: widget, domEvent: e }); this.fire("nodeClick", {node: widget, domEvent: e}); } }, ".content-header", this); this.get(CONTENT_BOX).delegate("dblclick", function(e) { e.halt(true); Y.Widget.getByNode(e.currentTarget).toggleTree(); }, "." + getClassName(TREENODE, CONTENT, "header")); //Render child before expand this.before("treenode:collapsedChange", function(e) { var renderTo; if (!e.newVal && e.target.get("rendered")) { renderTo = e.target._childrenContainer; e.target.each(function(child) { child.render(renderTo); }); } }); }, /** * Lifecycle method * @private * @function * @returns {undefined} */ renderUI: function() { if (this.get("visibleRightWidget")) { this.get(CONTENT_BOX).addClass(classNames.visibleRightWidget); } if (!this.size()) { this.get(BOUNDING_BOX).append("<div class='" + classNames.emptyMSG + "'>" + this.get("emptyMsg") + "</div>"); } }, syncUI: function() { this.each(function(child) { var s = child.get(SELECTED); if (s) { this._updateSelection({target: child, newVal: s}); } }, this); }, /** * Expand all children * @public * @function * @returns {undefined} */ expandAll: function() { this.each(function(item) { if (item.expandAll) { item.expandAll(); } }); }, /** * Collapse all children * @public * @function * @returns {undefined} */ collapseAll: function() { this.each(function(item) { if (item.collapseAll) { item.collapseAll(); } }); }, getSelection: function() { var selection = this.get(SELECTION); if (selection) { while (selection.item(0).get(SELECTION)) { selection = selection.item(0).get(SELECTION); } } return selection; }, saveState: function() { var state = {}, getChildsState = function(o, item, index) { if (item instanceof Y.TreeNode) { o[index] = {expanded: !item.get("collapsed")}; item.each(Y.bind(getChildsState, item, o[index])); } }; this.each(Y.bind(getChildsState, this, state)); return state; }, applyState: function(state) { var setChildsState = function(o, item, index) { if (item instanceof Y.TreeNode) { if (o[index]) { if (o[index].expanded) { item.expand(false); } else if (o[index].expanded === false) { item.collapse(false); } item.each(Y.bind(setChildsState, item, o[index])); } } }; this.each(Y.bind(setChildsState, this, state)); }, /** * * @param {type} testFn * @returns {Y.TreeNode|Y.TreeLeaf} */ find: function(testFn) { var find = function(widget) { if (testFn(widget)) { return widget; } if (widget.each) { // Is a treeview or a treenode for (var i = 0; i < widget.size(); i += 1) { var test = find(widget.item(i)); if (test) { return test; } } } return null; }; return find(this); } }, { /** * @lends Y.TreeView */ NAME: TREEVIEW, ATTRS: { visibleRightWidget: { value: false, validator: Y.Lang.isBoolean }, defaultChildType: { value: "TreeLeaf" }, multiple: { value: true, readOnly: true }, emptyMsg: { value: "Empty", setter: function(v) { this.get(BOUNDING_BOX).all("." + classNames.emptyMSG).setHTML(v); return v; } } }, RIGHTWIDGETSETTERFN: function(v) { var rightWidget = this.get("rightWidget"), targetNode = this.get(BOUNDING_BOX).one(".yui3-tree-rightwidget"); if (rightWidget !== v && rightWidget) { // Remove existing child if (rightWidget instanceof Y.Node) { // Case 1: Y.Node rightWidget.remove(); } else { rightWidget.get(BOUNDING_BOX).remove(); // Case 2: Y.Widget rightWidget.removeTarget(this); this.set("parent", null); } } if (v) { // Append the new widget if (v instanceof Y.Node) { // Case 1: Y.Node v.appendTo(targetNode); } else { // Case 2: Y.Widget if (v.get("rendered")) { v.get(BOUNDING_BOX).appendTo(targetNode); } else { v.render(targetNode); } v.set("parent", this); v.addTarget(this); } } return v; } }); /** * TreeView's TreeNode * <p><strong>Attributes</strong></p> * <ul> * <li>label {String} The TreeNode's label</li> * <li>collapsed {Boolean} Define if the node is collased. <i>Default:</i> false</li> * <li>rightWidget {Widget} TreeNode's right widget</li> * <li>loading {Boolean} is the node loading, will replace left icon. <i>Default:</i> false</li> * <li>iconCSS {String} left icon's CSS class</li> * </ul> * @name Y.TreeNode * @class Base TreeNode class * @extends Y.Widget * @constructor * @param Object Will be used to fill attributes field */ Y.TreeNode = Y.Base.create("treenode", Y.Widget, [Y.WidgetParent, Y.WidgetChild], { /** @lends Y.TreeNode# */ BOUNDING_TEMPLATE: "<li>" + "<div class='content-header yui3-treenode-content-header'>" + "<span class='yui3-treenode-content-toggle'></span>" + "<span class='yui3-treenode-content-icon'></span>" + "<span class='yui3-treenode-content-label'></span>" + "<div class=\"yui3-treenode-content-rightwidget yui3-tree-rightwidget\">" + "</div></li>", CONTENT_TEMPLATE: "<ul></ul>", /** * Lifecycle method * @private * @function */ initializer: function() { this.publish("toggleClick", { bubbles: false, broadcast: false, defaultFn: this.toggleTree }); this.publish("nodeExpanded", { bubbles: true }); this.publish("nodeCollapsed", { bubbles: true }); this.publish("iconClick", { bubbles: true }); this.publish("labelClick", { bubbles: true }); this.publish("click", { bubbles: true }); }, /** * Lifecycle method * @private * @function * @returns {undefined} */ renderUI: function() { if (this.get("collapsed")) { this.get(BOUNDING_BOX).addClass(classNames.collapsed); } }, /** * Lifecycle method * @private * @function * @returns {undefined} */ bindUI: function() { this.after("collapsedChange", function(e) { if (e.target !== this) { return; } if (e.newVal) { this.get(BOUNDING_BOX).addClass(classNames.collapsed); if (e.fireEvent) { this.fire("nodeCollapsed", {node: e.target}); } } else { this.get(BOUNDING_BOX).removeClass(classNames.collapsed); if (e.fireEvent) { this.fire("nodeExpanded", {node: e.target}); } } }); }, /** * Lifecycle method, sync attributes * @public * @function * @returns {undefined} */ syncUI: function() { this.set("loading", this.get("loading")); this.set("iconCSS", this.get("iconCSS")); this.set("label", this.get("label")); this.set("tooltip", this.get("tooltip")); this.set("rightWidget", this.get("rightWidget")); this.set("collapsed", this.get("collapsed")); this.set("cssClass", this.get("cssClass")); this.each(function(child) { var s = child.get(SELECTED); if (s) { this._updateSelection({target: child, newVal: s}); } }, this); }, /** * Lifecycle method * @private * @function * @returns {undefined} */ destructor: function() { this.blur(); //remove a focused node generates some errors if (this.get("rightWidget")) { this.get("rightWidget").destroy(); } }, /** * Toggle treeNode between collapsed and expanded. Fires an event "nodeCollapsed" / "nodeExpanded" * @public * @function * @returns {undefined} */ toggleTree: function() { this.set("collapsed", !this.get("collapsed"), {fireEvent: true}); }, /** * Expand the treeNode * @public * @function * @param {Boolean} fireEvent specifies if an event should be fired. <i>Default:</i> true * @returns {undefined} */ expand: function(fireEvent) { this.set("collapsed", false, {fireEvent: fireEvent}); }, /** * Collapse the treeNode * @public * @function * @param {Boolean} fireEvent specifies if an event should be fired. <i>Default:</i> true * @returns {undefined} */ collapse: function(fireEvent) { this.set("collapsed", true, {fireEvent: fireEvent}); }, /** * Expand all subtree * @public * @function * @returns {undefined} */ expandAll: function(fireEvent) { this.expand(fireEvent); this.each(function(item) { if (item.expandAll) { item.expandAll(fireEvent); } }); }, /** * Collapse all subtree * @public * @function * @returns {undefined} */ collapseAll: function(fireEvent) { this.collapse(fireEvent); this.each(function(item) { if (item.collapseAll) { item.collapseAll(fireEvent); } }); }, /** * Only render Child on opened tree * @private * @override Y.WidgetParent.prototype._uiAddChild * @param {type} child * @param {type} parentNode */ _uiAddChild: function(child, parentNode) { if (!this.get("collapsed")) { Y.WidgetParent.prototype._uiAddChild.call(this, child, parentNode); } }, /** * Only render Children on opened tree * @private * @override Y.WidgetParent.prototype._renderChildren */ _renderChildren: function() { var renderTo = this._childrenContainer || this.get("contentBox"); this._childrenContainer = renderTo; if (!this.get("collapsed")) { this.each(function(child) { child.render(renderTo); }); } } }, { /** @lends Y.TreeNode */ NAME: "TreeNode", ATTRS: { label: { value: "", validator: Y.Lang.isString, setter: function(v) { this.get(BOUNDING_BOX).one(".yui3-treenode-content-label").setContent(v); return v; } }, selected: { setter: function(v) { if (this.get(BOUNDING_BOX)._node) { this.get(BOUNDING_BOX).removeClass(SELECTED) .removeClass("sub-partially-selected") .removeClass("sub-fully-selected"); } if (v && !this.get(SELECTION)) { this.get(BOUNDING_BOX).addClass(SELECTED); } else if (v === 2) { this.get(BOUNDING_BOX).addClass("sub-partially-selected"); } else if (v === 1) { this.get(BOUNDING_BOX).addClass("sub-fully-selected"); } return v; } }, tooltip: { value: "", validator: Y.Lang.isString, setter: function(v) { if (v) { this.get(BOUNDING_BOX).one(".content-header").setAttribute("title", v); } else { this.get(BOUNDING_BOX).one(".content-header").removeAttribute("title"); } } }, initialSelected: { writeOnce: "initOnly" }, collapsed: { value: true, validator: Y.Lang.isBoolean }, tabIndex: { value: 1 }, rightWidget: { value: null, validator: function(o) { return o instanceof Y.Widget || o instanceof Y.Node || o === null; }, setter: Y.TreeView.RIGHTWIDGETSETTERFN }, loading: { value: false, validator: Y.Lang.isBoolean, setter: function(v) { this.get(BOUNDING_BOX).toggleClass(classNames.loading, v); return v; } }, iconCSS: { value: getClassName("treenode", "default-icon"), validator: Y.Lang.isString, setter: function(v) { var iconNode = this.get(BOUNDING_BOX).one(".yui3-treenode-content-icon"); if (this.currentIconCSS) { iconNode.removeClass(this.currentIconCSS); } iconNode.addClass(v); this.currentIconCSS = v; return v; } }, cssClass: { setter: function(v) { if (v) { this.get(BOUNDING_BOX).addClass(v); } return v; } }, defaultChildType: { value: "TreeLeaf" }, data: {} } }); /** * TreeLeaf widget. Default child type for TreeView. * It extends WidgetChild, please refer to it's documentation for more info. * <p><strong>Attributes</strong></p> * <ul> * <li>label {String} The TreeNode's label</li> * <li>rightWidget {Widget} TreeNode's right widget</li> * <li>loading {Boolean} is the node loading, will replace left icon. <i>Default:</i> false</li> * <li>iconCSS {String} left icon's CSS class</li> * <li>editable {Boolean} label is editable. <i>Default:</i> false</li> * </ul> * @name Y.TreeLeaf * @class TreeView's TreeLeaf * @constructor * @uses Y.WidgetChild * @extends Y.Widget * @param {Object} config User configuration object. */ Y.TreeLeaf = Y.Base.create("treeleaf", Y.Widget, [Y.WidgetChild], { /** @lends Y.TreeLeaf# */ /** * @field * @private */ CONTENT_TEMPLATE: "<div><div class='content-header yui3-treeleaf-content-header'>" + "<span class='yui3-treeleaf-content-icon'></span>" + "<span class='yui3-treeleaf-content-label'></span>" + "<div class=\"yui3-treeleaf-content-rightwidget yui3-tree-rightwidget\"></div>" + "</div></div>", /** * @field * @private */ BOUNDING_TEMPLATE: "<li></li>", /** * Lifecycle method * @private * @function * @returns {undefined} */ initializer: function() { this.publish("iconClick", { bubbles: true }); this.publish("labelClick", { bubbles: true }); this.publish("click", { bubbles: true }); }, /** * Lifecycle method * @private * @function * @returns {undefined} */ bindUI: function() { //one line, prevent special chars this.get(CONTENT_BOX).on("blur", function(e) { e.currentTarget.setContent(e.target.getContent().replace(/&[^;]*;/gm, "").replace(/(\r\n|\n|\r|<br>|<br\/>)/gm, "").replace(/(<|>|\|\\|:|;)/gm, "").replace(/^\s+/g, '').replace(/\s+$/g, '')); }, "." + this.getClassName(CONTENT, "label"), this); }, /** * Lifecycle method, sync attributes * @public * @function * @returns {undefined} */ syncUI: function() { this.set("label", this.get("label")); this.set("tooltip", this.get("tooltip")); this.set("iconCSS", this.get("iconCSS")); this.set("editable", this.get("editable")); this.set("loading", this.get("loading")); this.set("rightWidget", this.get("rightWidget")); this.set("cssClass", this.get("cssClass")); }, /** * Lifecycle method * @private * @function * @returns {undefined} */ destructor: function() { this.blur(); //remove a focused node generates some errors this.set(SELECTED, 0); if (this.get("rightWidget") && this.get("rightWidget").destroy) { try { this.get("rightWidget").destroy(); } catch (e) { } } } }, { /** @lends Y.TreeLeaf */ NAME: "TreeLeaf", ATTRS: { label: { value: "", validator: Y.Lang.isString, setter: function(v) { this.get(BOUNDING_BOX).one(".yui3-treeleaf-content-label").setContent(v); return v; }, getter: function() { return this.get(BOUNDING_BOX).one(".yui3-treeleaf-content-label").getContent(); } }, selected: { setter: function(v) { this.get(BOUNDING_BOX).toggleClass(SELECTED, v); return v; } }, tooltip: { value: "", validator: Y.Lang.isString, setter: function(v) { if (v) { this.get(BOUNDING_BOX).one(".content-header").setAttribute("title", v); } else { this.get(BOUNDING_BOX).one(".content-header").removeAttribute("title"); } } }, cssClass: { setter: function(v) { if (v) { this.get(BOUNDING_BOX).addClass(v); } return v; } }, tabIndex: { value: -1 }, initialSelected: { writeOnce: "initOnly" }, rightWidget: { value: null, validator: function(o) { return o instanceof Y.Widget || o instanceof Y.Node || o === null; }, setter: Y.TreeView.RIGHTWIDGETSETTERFN }, editable: { value: false, validator: Y.Lang.isBoolean, setter: function(v) { this.get(BOUNDING_BOX).one(".yui3-treeleaf-content-label").setAttribute("contenteditable", v ? "true" : "false"); return v; } }, loading: { value: false, validator: Y.Lang.isBoolean, setter: function(v) { this.get(CONTENT_BOX).toggleClass(classNames.loading, v); return v; } }, iconCSS: { value: getClassName("treeleaf", "default-icon"), validator: Y.Lang.isString, setter: function(v) { var iconNode = this.get(BOUNDING_BOX).one(".yui3-treeleaf-content-icon"); if (this.currentIconCSS) { iconNode.removeClass(this.currentIconCSS); } iconNode.addClass(v); this.currentIconCSS = v; return v; } }, data: {} } }); /** * TreeView plugin, if a team select all players. * Toggle selection on click */ Y.Plugin.TeamSelection = Y.Base.create("TeamSelection", Y.Plugin.Base, [], { initializer: function() { this.get(HOST).each(function(child) { if (child.get(SELECTED)) { child.set(SELECTED, 1); } }); this.onceAfterHostEvent("render", function() { this.afterHostEvent("treeleaf:selectedChange", function(e) { if (e.newVal > 0) { e.target.get("parent").selectAll(); } else { e.target.get("parent").deselectAll(); } }); this.afterHostEvent("nodeClick", function(e) { e.node.set("selected", 1); }); }); } }, { NS: "teamselect" }); /** * TreeView plugin, nodes will react like checkboxes. * Toggle selection on click */ Y.Plugin.CheckBoxTV = Y.Base.create("CheckBoxTv", Y.Plugin.Base, [], { initializer: function() { this.onHostEvent("nodeClick", function(e) { e.preventDefault(); if (e.node && e.node !== this.get(HOST)) { e.node.set(SELECTED, e.node.get(SELECTED) ? 0 : 1); } }); this.get(HOST).get(BOUNDING_BOX).addClass(classNames.multiSelect); }, destructor: function() { this.get(HOST).get(BOUNDING_BOX).removeClass(classNames.multiSelect); } }, { NS: "treeviewselect" }); /** * Treeview plugin, hold CTRL key to select multiple nodes */ Y.Plugin.CTRLSelectTV = Y.Base.create("CTRLSelectTV", Y.Plugin.Base, [], { initializer: function() { this.onHostEvent("nodeClick", function(e) { e.preventDefault(); if (!e.domEvent.ctrlKey) { this.deselectAll(); } if (e.node && e.node !== this) { e.node.set(SELECTED, e.node.get(SELECTED) ? 0 : 1); } }, this.get(HOST)); this.get(HOST).get(BOUNDING_BOX).addClass(classNames.multiSelect); }, destructor: function() { this.get(HOST).get(BOUNDING_BOX).removeClass(classNames.multiSelect); } }, { NS: "treeviewselect" }); });
const test = require('tape') const parse = require('../../parse').element('Program') test('Multiline program I', function (t) { const res = parse([ 'name @ a ==> b', 'name2 @ b <=> c' ].join('\n')) t.equal(typeof res, 'object') t.equal(res.type, 'Program') t.equal(res.body.length, 2) t.end() }) test('Multiline program II', function (t) { const res = parse([ '', 'name @ a ==> b', 'name2 @ b <=> c' ].join('\n')) t.equal(typeof res, 'object') t.equal(res.type, 'Program') t.equal(res.body.length, 2) t.end() }) test('Multiline program III', function (t) { const res = parse([ '', 'name @ a ==> b', '', 'name2 @ b <=> c' ].join('\n')) t.equal(typeof res, 'object') t.equal(res.type, 'Program') t.equal(res.body.length, 2) t.end() }) test('Multiline program IV', function (t) { const res = parse([ '', 'name @ a ==> b', '', 'name2 @ b <=> c', '' ].join('\n')) t.equal(typeof res, 'object') t.equal(res.type, 'Program') t.equal(res.body.length, 2) t.end() }) test('Multiline program V', function (t) { const res = parse([ 'name @ a ==> b;', 'name2 @ b <=> c;' ].join('\n')) t.equal(typeof res, 'object') t.equal(res.type, 'Program') t.equal(res.body.length, 2) t.end() })
/*! * Simple & awesome JavaScript library for BROGRAMMERS B-) * https://github.com/carlosjln/epic * * Copyright 2015 * Released under MIT License * https://github.com/carlosjln/epic/blob/master/LICENSE * * Author: Carlos J. Lopez * https://github.com/carlosjln */ var epic = (function() { function epic() { return "Hello world :)" } function log(message) { if (typeof window.console !== "undefined") { console.log(epic.object.to_array(arguments)) } } function fail(message, number) { var error = new Error(message, number); if (this instanceof fail) { return error } log(error) } epic.type = (function() { var core_types = { '[object Boolean]': 'boolean', '[object Number]': 'number', '[object String]': 'string', '[object Function]': 'function', '[object Array]': 'array', '[object Date]': 'date', '[object RegExp]': 'regexp', '[object Object]': 'object', '[object Error]': 'error' }; var to_string = core_types.toString; function type(object) { var typeof_object = typeof(object); if (object === null) { return 'null' } if (typeof_object === 'object' || typeof_object === 'function') { return core_types[to_string.call(object)] || 'object' } return typeof_object } type.is_window = function(object) { return object !== null && object === object.window }; type.is_numeric = function(object) { return !isNaN(parseFloat(object)) && isFinite(object) }; type.is_undefined = function(object) { return typeof(object) === 'undefined' }; type.is_array = function(object) { return type(object) === "array" }; type.is_function = function(object) { return type(object) === "function" }; type.is_string = function(object) { return type(object) === "string" }; type.is_object = function(object) { return type(object) === "object" }; type.is_boolean = function(object) { return type(object) === 'boolean' }; type.is_regexp = function(object) { return type(object) === 'regexp' }; type.is_element = function(object) { var html_element = typeof HTMLElement === "object"; return html_element ? object instanceof HTMLElement : object && typeof object === "object" && object.nodeType === 1 && typeof object.nodeName === "string" }; return type })(); epic.parse = { currency: function(symbol, expression) { if (arguments.length === 1) { expression = symbol; symbol = null } var numbers = expression + ''; var array = numbers.split('.'); var digits = array[0]; var decimals = array.length > 1 ? '.' + array[1] : ''; var pattern = /(\d+)(\d{3})/; while (pattern.test(digits)) { digits = digits.replace(pattern, '$1' + ',' + '$2') } return (symbol ? symbol + ' ' : '') + digits + decimals }, url: function(url) { var anchor = document.createElement("a"); var query = {}; anchor.href = url; anchor.search.replace(/([^?=&]+)(=([^&]*))?/g, function($0, $1, $2, $3) { query[$1] = $3; return $0 }); var json = { href: anchor.href, protocol: anchor.protocol, host: anchor.host, hostname: anchor.hostname, port: anchor.port, path: anchor.pathname, query: query, bookmark: anchor.hash }; return json } }; epic.log = log; epic.fail = fail; epic.uid = (function() { var token = "__::UID::__"; function uid(){} function next() { return ++uid.seed } uid.seed = (new Date).getTime(); uid.token = token; uid.next = next; uid.get = function(object) { return object[token] || (object[token] = ++uid.seed) }; return uid })(); epic.start = function(callback) { this.fail("Oops! :$ The [onready] feature isn't ready yet.") }; return epic })(); (function(epic) { var get_type = epic.type; function object(obj) { return new dsl(obj, to_array(arguments)) } function dsl(obj, parameters) { this.object = obj; this.parameters = parameters } function copy(source, target, undefined_only) { var new_value; var current_value; var source_type = get_type(source); undefined_only = undefined_only === true; if (source_type === "date") { target = new Date; target.setTime(source.getTime()); return target } if (source_type === "array" && undefined_only === false) { var index = source.length; target = target === undefined ? [] : target; while (index--) { target[index] = copy(source[index], target[index], undefined_only) } return target } if (source_type === "object") { target = target === undefined ? {} : target; for (var attribute in source) { if (source.hasOwnProperty(attribute)) { new_value = source[attribute]; current_value = target[attribute]; target[attribute] = copy(new_value, current_value, undefined_only) } } return target } return undefined_only ? (target !== undefined ? target : source) : source } function merge() { var objects = arguments; var length = objects.length; var target = {}; var i = 0; for (; i < length; i++) { copy(objects[i], target) } return target } function to_array(object) { if (object === undefined || object === null) { return [] } if (object instanceof Array) { return object } if (isFinite(object.length)) { return Array.prototype.slice.call(object) } return [object] } function extend(klass, base) { if (typeof klass !== "function") { return false } var klass_prototype = klass.prototype; copy(base, klass, true); if (typeof base === "function") { copy(base.prototype, klass_prototype, true); klass_prototype.constructor = klass; klass_prototype.baseclass = base; klass_prototype.base = function() { this.baseclass.apply(this, arguments) } } else { copy(base, klass_prototype, true) } return true } object.merge = merge; object.copy = copy; object.to_array = to_array; object.extend = extend; object.dsl = dsl; epic.object = object })(epic); (function(epic) { var to_array = Array.prototype.slice; function string(input) { return new dsl(input, to_array.call(arguments)) } function dsl(input, parameters) { this.input = input; this.parameters = parameters } function replace_default_html_entities(str) { var i = str.charCodeAt(0); if ((i > 31 && i < 96) || (i > 96 && i < 127)) { return str } else { return '&#' + i + ';' } } function replace_all_html_entities(str) { var i = str.charCodeAt(0); if ((i !== 34 && i !== 39 && i !== 38 && i !== 60 && i !== 62) && ((i > 31 && i < 96) || (i > 96 && i < 127))) { return str } else { return '&#' + i + ';' } } function restore_html_entities(str) { return String.fromCharCode(str.replace(/[#&;]/g, '')) } var B64KEY = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; function encode_base64(input) { var key = B64KEY; var str = string.encode_utf8(input); var length = str.length; var index = 0; var output = ""; var chr1, chr2, chr3, enc1, enc2, enc3, enc4; while (index < length) { chr1 = str.charCodeAt(index++); chr2 = str.charCodeAt(index++); chr3 = str.charCodeAt(index++); enc1 = chr1 >> 2; enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); enc4 = chr3 & 63; if (isNaN(chr2)) { enc3 = enc4 = 64 } else if (isNaN(chr3)) { enc4 = 64 } output = output + key.charAt(enc1) + key.charAt(enc2) + key.charAt(enc3) + key.charAt(enc4) } return output } function decode_base64(input) { var key = B64KEY; var str = input.replace(/[^A-Za-z0-9\+\/\=]/g, ""); var length = str.length; var index = 0; var output = ""; var chr1, chr2, chr3; var enc1, enc2, enc3, enc4; while (index < length) { enc1 = key.indexOf(str.charAt(index++)); enc2 = key.indexOf(str.charAt(index++)); enc3 = key.indexOf(str.charAt(index++)); enc4 = key.indexOf(str.charAt(index++)); chr1 = (enc1 << 2) | (enc2 >> 4); chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); chr3 = ((enc3 & 3) << 6) | enc4; output = output + String.fromCharCode(chr1); if (enc3 !== 64) { output = output + String.fromCharCode(chr2) } if (enc4 !== 64) { output = output + String.fromCharCode(chr3) } } output = string.decode_utf8(output); return output } function encode_utf8(input) { var str = input.replace(/\r\n/g, "\n"); var length = str.length; var index = 0; var output = ""; var charcode; while (length--) { charcode = str.charCodeAt(index++); if (charcode < 128) { output += String.fromCharCode(charcode) } else if ((charcode > 127) && (charcode < 2048)) { output += String.fromCharCode((charcode >> 6) | 192); output += String.fromCharCode((charcode & 63) | 128) } else { output += String.fromCharCode((charcode >> 12) | 224); output += String.fromCharCode(((charcode >> 6) & 63) | 128); output += String.fromCharCode((charcode & 63) | 128) } } return output } function decode_utf8(input) { var length = input.length; var index = 0; var output = ""; var charcode; var c2; var c3; while (index < length) { charcode = input.charCodeAt(index); if (charcode < 128) { output += String.fromCharCode(charcode); index++ } else if ((charcode > 191) && (charcode < 224)) { c2 = input.charCodeAt(index + 1); output += String.fromCharCode(((charcode & 31) << 6) | (c2 & 63)); index += 2 } else { c2 = input.charCodeAt(index + 1); c3 = input.charCodeAt(index + 2); output += String.fromCharCode(((charcode & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); index += 3 } } return output } function encode_url(input) { return encodeURIComponent(input) } function decode_url(input) { return decodeURIComponent(input) } function encode_html_entities(input, encode_reserved_chars) { return input.replace(/./g, encode_reserved_chars ? replace_all_html_entities : replace_default_html_entities) } function decode_html_entities(input) { return input.replace(/&#(\d)+;/g, restore_html_entities) } function uppercase(str) { return str.toUpperCase() } function lowercase(str) { return str.toLowerCase() } function trim(str, collapse_spaces) { str = str.replace(/^\s+|\s+$/gm, ''); if (collapse_spaces) { str = str.replace(/\s+/g, ' ') } return str } function is_html(str) { return (/^(?:\s*(<[\w\W]+>)[^>]*)$/img).test(str) } function to_dom(str) { return epic.html.create.document_fragment(str) } function capitalize(str) { return str.charAt(0).toUpperCase() + str.slice(1) } string.encode_base64 = encode_base64; string.decode_base64 = decode_base64; string.encode_utf8 = encode_utf8; string.decode_utf8 = decode_utf8; string.encode_url = encode_url; string.decode_url = decode_url; string.encode_html_entities = encode_html_entities; string.decode_html_entities = decode_html_entities; string.uppercase = uppercase; string.lowercase = lowercase; string.capitalize = capitalize; string.trim = trim; string.is_html = is_html; string.to_dom = to_dom; string.dsl = dsl; epic.string = string })(epic); (function(epic) { function array(list) { return new dsl(list, epic.object.to_array(arguments)) } function dsl(list, parameters) { this.object = list; this.parameters = parameters } function remove(list, index, howmany) { list.splice(index, howmany) } function locate(list, element) { var length = list.length >>> 0; while (length--) { if (list[length] === element) { return length } } return -1 } array.flatten = function(items) { var a = []; return a.concat.apply(a, items) }; array.each = function(list, callback, self) { var i = 0; var length = list.length; self = self || list; for (; i < length; i++) { callback.call(self, list[i], i, list) } return list }; array.every = function(list, callback, self) { var i = 0; var length = list.length; self = self || list; for (; i < length; i++) { if (callback.call(self, list[i], i, list)) { continue } return false } return true }; array.filter = function(list, condition, self) { var length = list.length; var i = 0; var result = []; var item; self = self || list; for (; i < length; i++) { item = list[i]; if (condition.call(self, item, i, list)) { result[result.length] = item } } return result }; array.indexof = function(list, element, from_index) { var length = list.length >>> 0; from_index = +from_index || 0; if (Math.abs(from_index) === Infinity) { from_index = 0 } if (from_index < 0) { from_index += length; if (from_index < 0) { from_index = 0 } } for (; from_index < length; from_index++) { if (list[from_index] === element) { return from_index } } return -1 }; array.locate = locate; array.contains = function(list, element) { return locate(list, element) > -1 ? true : false }; array.remove = remove; array.dsl = dsl; epic.array = array })(epic); (function(epic) { function collection() { var self = this; self.collection = {}; self.list = [] } function set(key, item, override) { if (key === undefined || item === undefined) { return null } key = to_string(key); var self = this; var current = self.collection[key]; var index = current ? current.index : self.list.length; if (current && !override) { return null } self.collection[key] = { key: key, value: item, index: index }; self.list[index] = item; return item } function set_items(key_name, items, override) { if (!(items instanceof Array)) { return null } var self = this; var length = items.length; var index = 0; var item; var key; var processed = []; while (length--) { item = items[index++]; key = item[key_name]; self.set(key, item, override); processed[processed.length] = (self.collection[key] || {}).value } return processed } function get(key) { key = to_string(key); var self = this; var record = self.collection[key] || {}; var item = record.value; return item } function remove(key) { key = to_string(key); var self = this; var record = self.collection[key] || {}; var item = record.value; var index = record.index; if (item) { delete self.collection[key]; self.list.splice(index, 1); return item } return undefined } function to_string(key) { return String(key) } collection.prototype = { set: set, get: get, remove: remove, set_items: set_items }; epic.collection = collection })(epic); (function(epic, window, document, navigator) { var agent = navigator.userAgent; var vendor = navigator.vendor; var platform = navigator.platform; var browser_agent = [[agent, "Chrome"], [agent, "OmniWeb", '', "OmniWeb/"], [vendor, "Safari", "Apple", "Version"], [window.opera, "Opera"], [vendor, "iCab"], [vendor, "Konqueror", "KDE"], [agent, "Firefox"], [vendor, "Camino"], [agent, "Netscape"], [agent, "Explorer", "MSIE"], [agent, "Gecko", "Mozilla", "rv"], [agent, "Netscape", "Mozilla"]]; var browser_os = [[platform, "Windows", "Win"], [platform, "Mac"], [agent, "iPhone", "iPhone/iPod"], [platform, "Linux"]]; var browser_info = search(browser_agent); var browser = epic.browser = { webkit: agent.indexOf('AppleWebKit/') > -1, gecko: agent.indexOf('Gecko') > -1 && agent.indexOf('KHTML') === -1, name: browser_info[0], os: search(browser_os)[0], version: browser_info[1], load: function(url, type, callback) { setTimeout(function() { request(url, type, callback) }, 10) } }; var loaded_documents = []; browser.ie = (browser.name === 'explorer'); browser.get_current_url = get_current_url; if (browser.ie) { try { document.execCommand("BackgroundImageCache", false, true) } catch(er) {} } function search(array) { var len = array.length; var index = 0; var item; var user_agent; var identity; var identity_search; var version_search; while (len--) { item = array[index++]; user_agent = item[0]; identity = item[1]; identity_search = item[2]; version_search = item[3]; if (user_agent) { if (user_agent.indexOf(identity_search || identity) > -1) { new RegExp((version_search || identity_search || identity) + "[\\/\\s](\\d+\\.\\d+)").test(user_agent); return [epic.string.lowercase(identity), parseFloat(RegExp.$1)] } } } return null } function get_current_url(relative) { var anchor = document.createElement("a"); var port; var pathname = ''; anchor.href = document.location; port = parseInt(anchor.port, 10); if (relative) { pathname = anchor.pathname.replace(/^[\/]/, ''); if (pathname) { pathname = pathname.substring(0, pathname.lastIndexOf("/")) + "/" } } return anchor.protocol + '//' + anchor.hostname + (port && port !== 0 ? ':' + port : '') + '/' + pathname } function request(url, type, callback) { var tag; var src = 'src'; var rel; var typeof_script = typeof(type); if (/^http/i.test(url) === false) { url = browser.url + url } if (loaded_documents[url] !== null) { if (callback) { callback.free() } return loaded_documents[url].element } if (typeof_script === 'function') { callback = type } if (typeof_script !== 'string') { type = url.split('?')[0].file_ext() } if (type === 'js') { tag = 'script'; rel = type = 'javascript' } else { tag = 'link'; src = 'href'; rel = 'stylesheet' } var element = document.createElement(tag); element.setAttribute("type", "text/" + type); element.setAttribute('rel', rel); element.setAttribute(src, url); var data = { element: element, loaded: false, callback: callback }; if (callback) { element.onreadystatechange = function() { var state = this.readyState; if ((state === 'loaded' || state === 'complete') && data.loaded === false) { this.onreadystatechange = null; data.loaded = true; data.callback() } }; element.onload = function() { if (data.loaded === false) { data.loaded = true; data.callback() } }; if (type === 'css') { if (browser.name === "firefox") { element.textContent = '@import "' + url + '"'; var foo = setInterval(function() { try { clearInterval(foo); if (callback) { callback() } } catch(e) {} }, 50) } } } setTimeout(function() { document.getElementsByTagName('head')[0].insertBefore(element, null) }, 10); loaded_documents[url] = data; return element } })(epic, window, document, navigator); (function(epic, window, document, navigator) { var get_type = epic.type; var get_transport = window.XMLHttpRequest ? function() { return new XMLHttpRequest } : function() { return new ActiveXObject("Microsoft.XMLHTTP") }; function ajax(settings) { if ((this instanceof ajax) === false) { return new ajax(settings) } var self = this; var transport = self.transport = get_transport(); var typeof_default_property; var value; for (var property in settings) { typeof_default_property = get_type(self[property]); value = settings[property]; if (settings.hasOwnProperty(property) && (typeof_default_property === "undefined" || typeof_default_property === get_type(value))) { self[property] = value } } var method = self.method; var context = self.context || self; self.before_request.call(context, self, settings); transport.open(method, self.url, true); transport.onreadystatechange = function() { self.on_ready_state_change.call(self) }; if (method === "POST") { transport.setRequestHeader('Content-type', 'application/x-www-form-urlencoded') } transport.send(self.send) } ajax.prototype = { constructor: ajax, url: "", method: "GET", before_request: function(xhr, settings){}, on_success: function(response){}, on_complete: function(response){}, on_error: function(response){}, on_ready_state_change: function(parameters) { var self = this; var transport = self.transport; var ready_state = transport.readyState; var status; var json; var context = self.context || self; if (ready_state !== 4) { return null } try { status = transport.status } catch(e) { return null } if (status !== 200) { return null } var response_text = transport.responseText; try { json = new Function('return (' + response_text + ')')(); self.on_success.call(context, json) } catch(e) { self.on_error.call(context, e) } self.on_complete.call(context) } }; epic.request = ajax })(epic, window, document, navigator); (function(epic, widnow, document) { var is_html = epic.string.is_html; var get_epic_uid = epic.uid.get; var trim_spaces = epic.string.trim; var capitalize = epic.string.capitalize; var array = epic.array; var flatten = array.flatten; var for_each = array.each; var array_contains = array.contains; var to_array = epic.object.to_array; var get_type = epic.type; var encode_url = epic.string.encode_url; var match_id_tag_class = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/; var match_pixel_value = /^(\d*.?\d*)px$/; var match_spaces_between_css_rules = /\ *((;)|(:))+ *([\w]*)/ig; var match_css_rules = /\ *((-*\**[\w]+)+): *([\-()\w, .#%]*)/ig; var match_css_property_name = /^(\w*(-*)?)*$/i; var match_line_return = /\r/g; var match_trailing_spaces = /^\s+|\s+$/g; var match_multiple_spaces = /\s+/g; var document_element = document.documentElement; var contains = 'compareDocumentPosition' in document_element ? compare_document_position : container_contains; var get_computed_style = window.getComputedStyle ? function(element, property) { var style = element.ownerDocument.defaultView.getComputedStyle(element, null); return style ? style.getPropertyValue(property) || style[property] : undefined } : function(element, property) { return element.curentStyle[property] }; var IGNORE_NODE = { 1: false, 2: true, 3: true, 4: true, 5: true, 6: true, 7: true, 8: true, 9: false, 10: false, 11: false, 12: true }; function html(query, context) { return new selector(query, context) } function selector(query, context) { var t = this; var elements = []; if (!context) { context = document } else if (typeof context === 'string') { context = selector(context).elements[0] } else if (!context.nodeType && isFinite(context.length)) { context = context[0] } if (query) { if (typeof query === "string") { if (query === "body" && !context && document.body) { elements = [document.body] } else if (is_html(query)) { elements = to_array(create_document_fragment(query).childNodes) } else { elements = query_selector(query, context) } } if (query instanceof selector) { return query } var node_type = query.nodeType; if (node_type) { if (node_type === 11) { var child_nodes = query.cloneNode(true).childNodes; elements = to_array(child_nodes); context = to_array(child_nodes) } else { elements = [query]; context = [query] } } } t.query = query; t.context = context; t.elements = elements; t.length = elements.length } function parse_elements(element, index, list) { if (element == null) { return } if (typeof element === "string") { if (is_html(element)) { list[index] = create("fragment", element) } else { list[index] = create("textnode", element) } } else if (element instanceof selector) { list[index] = element.elements } else if (element.nodeName) { list[index] = element } } function compare_document_position(container, element) { return (container.compareDocumentPosition(element) & 16) === 16 } function container_contains(container, element) { container = container === document || container === window ? document_element : container; return container !== element && container.contains(element) } function is_node(object) { var node_type; return object && typeof object === 'object' && (node_type = object.nodeType) && (node_type === 1 || node_type === 9) } function get_uid(element) { var node_type = (element || {}).nodeType; if (node_type === 1 || node_type === 9) { return get_epic_uid(element) } return null } function query_selector(query, context) { var node_type = context.nodeType; var result = []; if (node_type != 1 && node_type != 9 && node_type != 11) { return result } var match = match_id_tag_class.exec(query) || {}; var element; var id = match[1]; var tag = match[2]; var class_name = match[3]; if (id) { if (node_type == 9) { result = context.getElementById(id) } else if (context.ownerDocument && (element = context.ownerDocument.getElementById(id)) && contains(context, element) && element.id === id) { result = element } } else if (tag) { result = context.getElementsByTagName(tag) } else if (class_name) { result = context.getElementsByClassName(class_name) } else if (context.querySelectorAll) { result = context.querySelectorAll(query) } return to_array(result) } function create(tag) { tag = trim_spaces(tag); var parameters = arguments; var param_1 = parameters[1]; var param_2 = parameters[2]; var node; if (tag === "fragment") { node = create_document_fragment(param_1) } else if (tag === 'option') { node = create_option(parameters[0], param_1, param_2) } else if (tag === "textnode") { node = document.createTextNode(param_1) } else { node = document.createElement(trim_spaces(tag)) } return node } function create_document_fragment(content, callback) { var fragment = document.createDocumentFragment(); var content_holder; var index; var nodes; if (content) { content_holder = document.createElement('div'); content_holder.innerHTML = content; if (callback) { (function() { if (content_holder.firstChild) { fragment.appendChild(content_holder.firstChild); setTimeout(arguments.callee, 0) } else { callback(fragment) } })() } else { nodes = content_holder.childNodes; index = nodes.length; while (index--) { fragment.insertBefore(nodes[index], fragment.firstChild) } } } return fragment } function create_option(caption, value, selected) { var node = document.createElement("option"); if (selected === undefined && value === true) { selected = true; value = undefined } value = typeof value === "undefined" ? caption : value; node.insertBefore(document.createTextNode(caption), null); node.setAttribute('value', value); if (selected) { node.setAttribute('selected', 'selected') } return new epic.html.selector(node) } function create_script(code) { var node = document.createElement("script"); var property = ('innerText' in node) ? 'innerText' : 'textContent'; node.setAttribute("type", "text/javascript"); setTimeout(function() { document.getElementsByTagName('head')[0].insertBefore(node, null); node[property] = code }, 10); return new epic.html.selector(node) } function create_style(css) { var node = document.createElement("style"); node.setAttribute("type", "text/css"); if (node.styleSheet) { node.styleSheet.cssText = css } else { node.insertBefore(document.createTextNode(css), null) } document.getElementsByTagName('head')[0].insertBefore(node, null); return new epic.html.selector(node) } function unique(elements, target, control) { var list = target || []; var collection = control || {}; var length = elements.length; var i = 0; var uid; var element; for (; i < length; i++) { element = elements[i]; uid = get_uid(element); if (collection[uid]) { continue } collection[uid] = true; list[list.length] = element } return list } function add_class(element, class_names) { var trim = trim_spaces; var class_list = trim(element.className, true).split(' '); var class_count; var i = 0; var name; class_names = trim(class_names, true).split(' '); for (class_count = class_names.length; i < class_count; i++) { name = class_names[i]; if (class_list.indexOf(name) === -1) { class_list[class_list.length] = name } } element.className = trim(class_list.join(' ')); return element } function toggle_class(element, class_names) { var trim = trim_spaces; var class_list = trim(element.className, true).split(' '); var class_count; var i = 0; var name; var index; class_names = trim(class_names, true).split(' '); for (class_count = class_names.length; i < class_count; i++) { name = class_names[i]; index = class_list.indexOf(name); if (index === -1) { class_list[class_list.length] = name } else { class_list.splice(index) } } element.className = trim(class_list.join(' ')); return element } function get_set_value(val) { var t = this; var elements = t.elements; var length = elements.length; var element; var getter; var result; var i = 0; if (arguments.length === 0) { if ((element = elements[0])) { getter = get_set_value[element.nodeName.toLowerCase()]; if (getter && ("get" in getter) && (result = getter.get(element)) !== undefined) { return result } result = element.value; return typeof result === "string" ? result.replace(match_line_return, "") : result === null ? "" : result } return undefined } for (; i < length; i++) { element = elements[i]; if (element.nodeType !== 1) { continue } if (val === null) { val = "" } else if (typeof val === "number") { val += "" } getter = get_set_value[element.nodeName.toLowerCase()]; if (!getter || !("set" in getter) && getter.set(element) === undefined) { element.value = val } } return t } function set_css(element, css, merge) { merge = typeof merge === "undefined" ? true : false; css = css.replace(match_spaces_between_css_rules, '$2$3$4'); var element_style = element.style; var clean_style = element_style.cssText.replace(match_spaces_between_css_rules, '$2$3$4'); if (clean_style && !/;$/.test(clean_style)) { clean_style += ';' } if (merge) { var replacer = function(a, property) { var value = a; var p = RegExp("(^|;)+(" + property + "): *([-()\\w, .#%=]*)", "ig"); css = css.replace(p, function(t, x, y, z) { if (z === '-') { value = '' } else { value = y + ':' + z } return '' }); return value }; css = clean_style.replace(match_css_rules, replacer) + css } element_style.cssText = css; return element } function get_dimension(element, property) { var offset_name = "offset" + capitalize(property); if (element) { element = element === element.window ? element.document : element; if (element.nodeType === 9) { element = element.document.documentElement; return Math.max(element.body[offset_name], element[offset_name]) } var value = get_computed_style(element, property); if (value !== null && value !== "") { value = value.replace(match_pixel_value, '$1'); return isNaN(value) ? value : parseFloat(value) } } return null } function set_css_display(context, value) { var elements = context.elements; var i = elements.length; while (i--) { elements[i].style.display = value } return context } selector.prototype = { empty: function() { var t = this; var elements = t.elements; var index = elements.length; var element; while (index--) { element = elements[index]; while (element.firstChild) { element.removeChild(element.firstChild) } } return t }, insert: function(elements, position) { elements = flatten(for_each(to_array(elements), parse_elements)); var t = this; var elements_count = elements.length; var target = t.elements[0]; var reference = null; var element; var valid_nodes = []; if (t.elements.length === 0) { return t } if (position !== undefined) { var child_nodes = target.childNodes; var j = child_nodes.length; var trim = epic.string.trim; var index = 0; var node; var node_type; while (j--) { node = child_nodes[index++]; node_type = node.nodeType; if (node_type === 1 || (node_type === 3 && trim(node.textContent) !== '')) { valid_nodes[valid_nodes.length] = node } } if (position > -1 && position < valid_nodes.length) { reference = valid_nodes[position] } } index = 0; while (elements_count--) { element = elements[index++]; if (!element) { continue } if (!element.nodeType) { element = document.createTextNode(element) } target.insertBefore(element, reference) } return t }, append: function() { return this.insert(arguments, undefined) }, html: function(content) { var self = this; var element = self.elements[0]; if (element) { if (typeof content === "undefined") { return element.innerHTML } element.innerHTML = content } return self }, remove: function() { var self = this; var elements = self.elements; var length = elements.length; var i = 0; var parent; var element; for (; i < length; i++) { element = elements[i]; parent = element.parentNode; parent.removeChild(element) } return self }, value: get_set_value, get: function(index) { var elements = this.elements; var upper_limit = elements.length - 1; if (index < 0) { index = 0 } else if (index > upper_limit) { index = upper_limit } return elements[index] }, first: function() { return new selector(this.elements[0]) }, find: function(query) { var elements = this.elements; var length = elements.length; var i = 0; var new_selector = new selector; var new_elements = new_selector.elements; var collection = {}; var element; var result; for (; i < length; i++) { element = elements[i]; result = query_selector(query, element); unique(result, new_elements, collection) } new_selector.length = new_elements.length; return new_selector }, parent: function() { return (this.elements[0] || {}).parentNode }, parents: function(query) { var parents = new selector(query); var elements = parents.elements; var element = this.elements[0] || {}; var result = []; var current = element; while ((current = current.parentNode)) { if (array_contains(elements, current)) { result[result.length] = current } } parents.elements = result; return parents }, has_class: function(name) { var t = this; var elements = t.elements; var length = elements.length; var i = 0; for (; i < length; ) { if (elements[i++].className.indexOf(name) > -1) { return true } } return false }, add_class: function(class_names) { var t = this; var elements = t.elements; var length = elements.length; var i = 0; for (; i < length; i++) { add_class(elements[i], class_names) } return t }, toggle_class: function(class_names) { var t = this; var elements = t.elements; var length = elements.length; var i = 0; for (; i < length; i++) { toggle_class(elements[i], class_names) } return t }, remove_class: function(class_name) { var t = this; var pattern = new RegExp(class_name.replace(match_trailing_spaces, '').replace(match_multiple_spaces, '|'), 'g'); var elements = t.elements; var j = elements.length; var element; while (j--) { element = elements[j]; element.className = element.className.replace(pattern, '').replace(match_multiple_spaces, ' ').replace(match_trailing_spaces, ' ') } return t }, replace_class: function(class_name, new_class_name) { var t = this; var elements = t.elements; var j = elements.length; var element; while (j--) { element = elements[j]; element.className = element.className.replace(class_name, new_class_name).replace(match_multiple_spaces, ' ').replace(match_trailing_spaces, ' ') } return t }, width: function() { return get_dimension(this.elements[0], "width") }, height: function() { return get_dimension(this.elements[0], "height") }, css: function(property) { var self = this; var element = self.elements[0]; if (!property) { return element.style.cssText } if (match_css_property_name.test(property)) { return get_computed_style(element, property) } set_css(element, property); return self }, show: function() { return set_css_display(this, '') }, hide: function() { return set_css_display(this, 'none') }, contains: function(element) { return contains(this.elements[0], element) }, prop: function(name, value) { var t = this; var elements = t.elements; var length = elements.length; var element; var i = 0; if (value === undefined) { element = elements[0]; return element ? element[name] : undefined } for (; i < length; i++) { element = elements[i]; if (element) { element[name] = value } } return t }, attr: function(name, value) { var t = this; return value === undefined ? t.get_attribute(name) : t.set_attribute(name, value) }, remove_attr: function(name) { var t = this; var elements = t.elements; var length = elements.length; var element; var i = 0; for (; i < length; i++) { element = elements[i]; if (element) { element.removeAttribute(name) } } return t }, get_attribute: function(name) { var t = this; var element = t.elements[0]; return element && typeof(element.getAttribute) == 'function' ? element.getAttribute(name) : undefined }, set_attribute: function(name, value) { var t = this; var elements = t.elements; var length = elements.length; var node_type; var element; var i = 0; for (; i < length; i++) { element = elements[i]; node_type = element.nodeType; if (element && (node_type == 1 || node_type == 9 || node_type == 11)) { element.setAttribute(name, value) } } return t }, remove_attribute: function(name) { var t = this; var elements = t.elements; var length = elements.length; var element; var i = 0; for (; i < length; i++) { element = elements[i]; if (element) { element.removeAttribute(name) } } return t }, serialize: function() { var empty = ''; var concat = empty; var query = empty; var amp = '&'; var t = this; var encrypt_method; var type; var elements = t.find('select').elements; var element; var element_id; var i = elements.length; while (i--) { element = elements[i]; if ((element_id = element.id || element.name || empty) == empty) continue; query += (query != empty ? amp : empty) + element_id + '=' + encode_url(element.value) } elements = t.find('input').elements; i = elements.length; while (i--) { element = elements[i]; if ((element_id = element.id || element.name || empty) == empty) continue; concat = query != empty ? amp : empty; type = element.type.toLowerCase(); value = encode_url(element.value); if ('checkbox,radio'.indexOf(type) > -1) { query += concat + element_id + '=' + (element.checked ? value : empty) } else { encrypt_method = window[element.getAttribute('encrypt-method')]; if (encrypt_method) { try { value = encrypt_method(value) } catch(er) {} } query += concat + element_id + '=' + value } } elements = t.find('textarea').elements; i = elements.length; while (i--) { element = elements[i]; if ((element_id = element.id || element.name || empty) == empty) continue; query += (query != empty ? amp : empty) + element_id + '=' + encode_url(element.value) } return query } }; create.document_fragment = create_document_fragment; create.option = create_option; create.script = create_script; create.style = create_style; html.contains = contains; html.selector = selector; html.create = create; html.add_class = add_class; html.toggle_class = toggle_class; html.is_node = is_node; html.get_uid = get_uid; epic.html = html })(epic, window, document); (function(epic, window, document) { var REGISTRY = {}; var REGISTRY_POLICE = {}; var HANDLERS = {}; var get_uid = epic.uid.get; var contains = epic.html.contains; var set_event_handler = document.addEventListener ? add_event_listener : attach_event; var trigger = document.createEvent ? dispatch_event : fire_event; var get_element_uid = epic.html.get_uid; var event_name_map = { mouseenter: "mouseover", mouseleave: "mouseout", DOMMouseScroll: "mousewheel" }; var keycode_map = { 8: 'BACKSPACE', 9: 'TAB', 10: 'ENTER', 13: 'ENTER', 20: 'CAPSLOCK', 27: 'ESC', 33: 'PAGEUP', 34: 'PAGEDOWN', 35: 'END', 36: 'HOME', 37: 'LEFT', 38: 'UP', 39: 'RIGHT', 40: 'DOWN', 45: 'INSERT', 46: 'DELETE' }; function event(){} function add(element, event_name, method, event_data) { if (typeof event_name !== "string") { return epic.fail("[event_name] must be a valid event name.") } var element_uid = get_element_uid(element); var element_events = REGISTRY[element_uid] || (REGISTRY[element_uid] = {}); var method_uid = get_uid(method); var police_key = element_uid + "_" + event_name + "_" + method_uid; if (REGISTRY_POLICE[police_key]) { return false } var handler = { context: element, method: method, event_data: event_data || {} }; if (event_name === "mouseover" || event_name === "mouseout") { handler.context = { element: element, method: method }; handler.method = function(e, data) { var t = this; var elem = t.element; if (!contains(elem, e.related_target)) { t.method.call(elem, e, data) } } } (element_events[event_name] || (element_events[event_name] = [])).push(handler); set_event_handler(element, event_name, element_uid); REGISTRY_POLICE[police_key] = true; return true } function remove(element, event_name, handler){} function dispatch_event(element, event_name) { var evt = document.createEvent('HTMLEvents'); evt.initEvent(event_name, true, true, window, 0, 0, 0, 80, 20, false, false, false, false, 0, null); element.dispatchEvent(evt); return element } function fire_event(element, event_name) { var evt = document.createEventObject(); element.fireEvent('on' + event_name, evt); return element } function add_event_listener(element, event_name, element_uid) { var element_event = element_uid + "_" + event_name; if (!HANDLERS[element_event]) { HANDLERS[element_event] = true; element.addEventListener(event_name, epic_event_handler, false) } } function attach_event(element, event_name, element_uid) { var element_event = element_uid + "_" + event_name; if (!HANDLERS[element_event]) { HANDLERS[element_event] = true; element.attachEvent('on' + event_name, epic_event_handler) } } function epic_event_handler(e) { var evt = e instanceof epic_event ? e : new epic_event(e); var target = evt.target; var execution_path = [target]; while ((target = target.parentNode)) { execution_path[execution_path.length] = target } process_execution_path(evt, execution_path); if (evt.propagation_stopped === false) { e.cancelBubble = true; e.stopPropagation() } return this } function process_execution_path(evt, elements) { var elements_count = elements.length; var handlers; var handler; var element; var events; var i = 0; var j; var handlers_count; var type = evt.type; for (; i < elements_count; i++) { element = elements[i]; events = REGISTRY[get_element_uid(element)]; if (events && (handlers = events[type])) { handlers_count = handlers.length; for (j = 0; j < handlers_count; j++) { handler = handlers[j]; handler.method.call(handler.context, evt, handler.event_data); if (evt.propagation_stopped === true) { return evt } } } } return evt } function epic_event(e) { var target = (e.target || e.srcElement) || document; var event_name = event_name_map[e.type] || e.type; var from_element = e.fromElement; var related_target = from_element === target ? e.toElement : e.relatedTarget || from_element; var which = e.which; var keycode = which ? which : keycode; var charcode = e.charCode; var keyvalue = ''; var meta_key; var delta = 0; var page_x; var page_y; var capslock = false; if (e.altKey) { meta_key = 'ALT' } else if (e.ctrlKey || e.metaKey) { meta_key = 'CTRL' } else if (e.shiftKey || charcode === 16) { meta_key = 'SHIFT' } else if (keycode === 20) { meta_key = 'CAPSLOCK' } if (which === undefined && charcode === undefined) { keycode = keycode } else { keycode = which !== 0 && charcode !== 0 ? which : keycode } keyvalue = keycode > 31 ? String.fromCharCode(keycode) : ''; if (keycode > 96 && keycode < 123 && meta_key === 'SHIFT' || keycode > 64 && keycode < 91 && meta_key !== 'SHIFT') { capslock = true } if (event_name === 'keydown' || event_name === 'keyup') { if (keyvalue === 'CAPSLOCK') { capslock = !capslock } if (keycode > 64 && keycode < 91 && meta_key !== 'SHIFT') { keycode = keycode + 32; keyvalue = String.fromCharCode(keycode) } } if (keycode_map[keycode]) { keyvalue = keycode_map[keycode] } if (event_name === 'mousewheel') { delta = e.detail ? e.detail * -1 : e.wheelDelta / 40; delta = delta > 0 ? 1 : -1 } if (typeof e.pageX === "undefined" && e.clientX !== null) { var document_element = document.documentElement; var body = document.body; page_x = e.clientX + (document_element && document_element.scrollLeft || body && body.scrollLeft || 0) - (document_element && document_element.clientLeft || body && body.clientLeft || 0); page_y = e.clientY + (document_element && document_element.scrollTop || body && body.scrollTop || 0) - (document_element && document_element.clientTop || body && body.clientTop || 0) } var self = this; self.original = e; self.event_phase = e.eventPhase; self.target = target.nodeType === 3 ? target.parentNode : target; self.type = event_name; self.from_element = from_element; self.to_element = e.toElement || target; self.pagex = page_x; self.pagey = page_y; self.keycode = keycode; self.keyvalue = keyvalue; self.metaKey = meta_key; self.delta = delta; self.capslock = capslock; self.button = e.button; self.related_target = related_target; self.propagation_stopped = false } epic_event.prototype = { prevent_default: function() { var foo = this; foo.original.preventDefault(); foo.original.result = false }, stop_propagation: function() { var self = this; var original = self.original; original.cancelBubble = true; original.stopPropagation(); self.propagation_stopped = true }, stop: function() { var self = this; self.prevent_default(); self.stop_propagation() } }; event.add = add; event.remove = remove; event.trigger = trigger; event.registry = REGISTRY; epic.event = event; var plugins = { on: function(event_name, event_handler, data) { var t = this; var elements = t.elements; var i = elements.length; while (i--) { add(elements[i], event_name, event_handler, data) } return t }, click: function(event_handler, data) { var t = this; if (arguments.length === 0) { t.trigger("click") } else { t.on("click", event_handler, data) } return t }, trigger: function(event_name) { var t = this; var elements = t.elements; var i = elements.length; while (i--) { trigger(elements[i], event_name) } return t } }; epic.object.copy(plugins, epic.html.selector.prototype) })(epic, window, document); (function(epic, undefined) { var object_merge = epic.object.merge; var object_copy = epic.object.copy; var default_settings = { on_start: nothing, execute: nothing, on_stop: nothing, interval: 1000 }; function nothing(){} function task(settings) { var self = this; object_copy(object_merge(default_settings, settings), self, true) } task.prototype = { construtor: task, start: function() { var self = this; self.timer = setInterval(function() { self.execute.call(self) }, self.interval); self.on_start.call(self) }, stop: function() { var self = this; clearInterval(self.timer); self.on_stop.call(self) } }; epic.task = task })(epic); (function(epic, undefined) { var object_merge = epic.object.merge; var object_copy = epic.object.copy; var epic_task = epic.task; var default_worker_settings = {tasks: {}}; function worker(settings) { var self = this; object_copy(object_merge(default_worker_settings, settings), self, true) } worker.prototype = { construtor: worker, add: function(id, task) { var self = this; var tasks = self.tasks; if (!(task instanceof epic_task)) { throw new Error("Not a valid task"); } if (tasks[id] !== undefined) { throw new Error("Task id [" + id + "] is already taken."); } tasks[id] = task; return self }, remove: function(id) { var self = this; if (typeof id === "string") { delete self.tasks[id] } return self }, start: function(id) { if (typeof id !== "string") { throw new Error("The id parameter must be a string."); } var self = this; var task = self.tasks[id]; if (self.current) { self.current.stop() } self.current = task; task.start(); return self }, stop: function(id) { var self = this; var task = self.tasks[id]; if (task instanceof epic_task) { self.current = null; task.stop() } return self } }; epic.worker = worker })(epic);
"use strict"; function _while(condition, callback) { var defer = new Promise(function (resolve, reject) { var promises = []; _whileCallback(condition, callback, resolve, reject, promises); return promises; }); return defer; } exports._while = _while; function _whileCallback(condition, callback, resolve, reject, resolutions) { if (condition()) { callback().then(function (resolution) { resolutions.push(resolution); _whileCallback(condition, callback, resolve, reject, resolutions); }).catch(function (err) { reject(err); }); } else { resolve(resolutions); } } exports._whileCallback = _whileCallback; //# sourceMappingURL=while.js.map
import React, { Component, PropTypes } from 'react'; import { connect } from 'dva'; import { Link } from 'dva/router'; import Result from '../../components/compete/Result' function ReultInfo(props) { return ( <Result {...props}/> ); } function mapStateToProps(state, ownProps) { return { ...state, }; } export default connect(mapStateToProps)(ReultInfo);
var fs = require('fs'); var path = require('path'); var ts = require('typescript'); var log = require('debuglog')(require('../package').name); var convert = require('convert-source-map'); var Compiler = require('./compiler'); function EntryCompiler(logger, compiler, opts) { opts = opts || {}; this.opts = { sourceMap: opts.sourceMap || false }; this.logger = logger; this.compiler = compiler; this.cachedResults = {}; } /** * Compiles the source for this entry file * TypeScript will do the require resolution, so this compiles the entire component * * @param {string} the entry file * @return {boolean} success * @api public */ EntryCompiler.prototype.compile = function (entry) { var results = this.compiler.compile([entry.path]); if (results) { this.outputDiagnostics(entry, results.errors); this.cachedResults[entry.path] = results; return !results.failure; } else { return true; // use the already cached output } } /** * Updates the file contents with the compiled output. * Also sorts out the source maps * * @param {object} the file * @param {string} the entry file * @return {boolean} success * @api public */ EntryCompiler.prototype.update = function (file, entry) { log('updating %s', file.path); var inputPath = ts.normalizePath(file.path); outputPath = Compiler.tsToJs(inputPath); var results = this.cachedResults[entry.path]; if (!results) throw new Error("Unexpected file: " + inputPath); if (results.failure) return false; if (!results.output[outputPath]) { this.logger.error('typescript', file.path + ' was not compiled'); return false; } file.src = this.getSource(results, outputPath); file.type = 'js'; file.mtime = new Date(); if (this.opts.sourceMap) { file.sourceMap = this.getSourceMap(results, file.path, outputPath); } return true; } /** * Write the compiler errors to console * * @param {string} the entry file * @param {array} the TypeScript compiler errors * @return {boolean} success * @api private */ EntryCompiler.prototype.outputDiagnostics = function (entry, diags) { var self = this; diags.slice(0, 10) .forEach(function(diag) { // feature: print the compiler output over 2 lines! file then message if (diag.file) { var loc = diag.file.getLineAndCharacterFromPosition(diag.start); var filename = Compiler.normalizePath(path.relative(entry.root, diag.file.filename)); var output = filename + "(" + loc.line + "," + loc.character + "): "; if (diag.category === ts.DiagnosticCategory.Error) self.logger.error('typescript', output) else self.logger.warn('typescript', output) } if (diag.category === 1) self.logger.error('typescript', diag.messageText + " (TS" + diag.code + ")"); else self.logger.warn('typescript', diag.messageText + " (TS" + diag.code + ")"); }); } /** * Retrieves the compiled output as a string * * @param {results} the compilation results * @param {string} the output file * @return {string} compiled output * @api private */ EntryCompiler.prototype.getSource = function (results, outputPath) { var output = results.output[outputPath]; // strip out source urls if (output) output = output.replace(convert.mapFileCommentRegex, ''); return output; }; /** * Retrieves the source map as a string * * @param {results} the compilation results * @param {string} the input file * @param {string} the output file * @return {string} source map json * @api private */ EntryCompiler.prototype.getSourceMap = function (results, inputPath, outputPath) { var sourcemap = convert.fromJSON(results.output[outputPath + '.map']); sourcemap.setProperty('sources', [inputPath]); return sourcemap.toJSON(); }; module.exports = EntryCompiler;
'use strict'; var fs = require('fs'), path = require('path'), docdown = require('../index.js'); var packagePath = path.resolve(__dirname, '..', 'package.json'), packageText = fs.readFileSync(packagePath, 'utf-8'), packageJSON = JSON.parse(packageText); var reExt = /\.[a-z]+$/; // The version number from the package.json. var version = packageJSON.version; // The input filename. var file = process.argv[2] + (reExt.test(process.argv[2]) ? '' : '.js'); // The output filename. var output = process.argv[3] || (path.basename(file).replace(reExt, '') + '.md') /*----------------------------------------------------------------------------*/ var markdown = docdown({ 'path': path.join(process.cwd(), file), 'title': 'docdown <sup>v' + version + '</sup>', 'url': 'https://github.com/jdalton/docdown/tree/' + version + '/index.js' }); fs.writeFileSync(output, markdown); console.log(markdown + '\n');
var require = patchRequire(require); var utils = require('utils'); var magento = require('./src/magento'); var app = function() { app.super_.apply(this, arguments); // Customize the default Magento application settings here // this.base_url = 'http://www.your-application.example.com'; }; utils.inherits(app, magento);
(function() { "use strict"; CodeMirror.showHint = function(cm, getHints, options) { // We want a single cursor position. if (cm.somethingSelected()) return; if (getHints == null) getHints = cm.getHelper(cm.getCursor(), "hint"); if (getHints == null) return; if (cm.state.completionActive) cm.state.completionActive.close(); var completion = cm.state.completionActive = new Completion(cm, getHints, options || {}); CodeMirror.signal(cm, "startCompletion", cm); if (completion.options.async) getHints(cm, function(hints) { completion.showHints(hints); }, completion.options); else return completion.showHints(getHints(cm, completion.options)); }; function Completion(cm, getHints, options) { this.cm = cm; this.getHints = getHints; this.options = options; this.widget = this.onClose = null; } Completion.prototype = { close: function() { if (!this.active()) return; this.cm.state.completionActive = null; if (this.widget) this.widget.close(); if (this.onClose) this.onClose(); CodeMirror.signal(this.cm, "endCompletion", this.cm); }, active: function() { return this.cm.state.completionActive == this; }, pick: function(data, i) { var completion = data.list[i]; if (completion.hint) completion.hint(this.cm, data, completion); else this.cm.replaceRange(getText(completion), data.from, data.to); this.close(); }, showHints: function(data) { if (!data || !data.list.length || !this.active()) return this.close(); if (this.options.completeSingle != false && data.list.length == 1) this.pick(data, 0); else this.showWidget(data); }, showWidget: function(data) { this.widget = new Widget(this, data); CodeMirror.signal(data, "shown"); var debounce = null, completion = this, finished; var closeOn = this.options.closeCharacters || /[\s()\[\]{};:>,]/; var startPos = this.cm.getCursor(), startLen = this.cm.getLine(startPos.line).length; function done() { if (finished) return; finished = true; completion.close(); completion.cm.off("cursorActivity", activity); CodeMirror.signal(data, "close"); } function isDone() { if (finished) return true; if (!completion.widget) { done(); return true; } } function update() { if (isDone()) return; CodeMirror.signal(data, "update"); if (completion.options.async) completion.getHints(completion.cm, finishUpdate, completion.options); else finishUpdate(completion.getHints(completion.cm, completion.options)); } function finishUpdate(data_) { data = data_; if (isDone()) return; if (!data || !data.list.length) return done(); completion.widget = new Widget(completion, data); } function activity() { clearTimeout(debounce); var pos = completion.cm.getCursor(), line = completion.cm.getLine(pos.line); if (pos.line != startPos.line || line.length - pos.ch != startLen - startPos.ch || pos.ch < startPos.ch || completion.cm.somethingSelected() || (pos.ch && closeOn.test(line.charAt(pos.ch - 1)))) { completion.close(); } else { debounce = setTimeout(update, 170); completion.widget.close(); } } this.cm.on("cursorActivity", activity); this.onClose = done; } }; function getText(completion) { if (typeof completion == "string") return completion; else return completion.text; } function buildKeyMap(options, handle) { var baseMap = { Up: function() {handle.moveFocus(-1);}, Down: function() {handle.moveFocus(1);}, PageUp: function() {handle.moveFocus(-handle.menuSize());}, PageDown: function() {handle.moveFocus(handle.menuSize());}, Home: function() {handle.setFocus(0);}, End: function() {handle.setFocus(handle.length);}, Enter: handle.pick, Tab: handle.pick, Esc: handle.close }; var ourMap = options.customKeys ? {} : baseMap; function addBinding(key, val) { var bound; if (typeof val != "string") bound = function(cm) { return val(cm, handle); }; // This mechanism is deprecated else if (baseMap.hasOwnProperty(val)) bound = baseMap[val]; else bound = val; ourMap[key] = bound; } if (options.customKeys) for (var key in options.customKeys) if (options.customKeys.hasOwnProperty(key)) addBinding(key, options.customKeys[key]); if (options.extraKeys) for (var key in options.extraKeys) if (options.extraKeys.hasOwnProperty(key)) addBinding(key, options.extraKeys[key]); return ourMap; } function Widget(completion, data) { this.completion = completion; this.data = data; var widget = this, cm = completion.cm, options = completion.options; var hints = this.hints = document.createElement("ul"); hints.className = "CodeMirror-hints"; this.selectedHint = 0; var completions = data.list; for (var i = 0; i < completions.length; ++i) { var elt = hints.appendChild(document.createElement("li")), cur = completions[i]; var className = "CodeMirror-hint" + (i ? "" : " CodeMirror-hint-active"); if (cur.className != null) className = cur.className + " " + className; elt.className = className; if (cur.render) cur.render(elt, data, cur); else elt.appendChild(document.createTextNode(cur.displayText || getText(cur))); elt.hintId = i; } var pos = cm.cursorCoords(options.alignWithWord !== false ? data.from : null); var left = pos.left, top = pos.bottom, below = true; hints.style.left = left + "px"; hints.style.top = top + "px"; // If we're at the edge of the screen, then we want the menu to appear on the left of the cursor. var winW = window.innerWidth || Math.max(document.body.offsetWidth, document.documentElement.offsetWidth); var winH = window.innerHeight || Math.max(document.body.offsetHeight, document.documentElement.offsetHeight); var box = hints.getBoundingClientRect(); var overlapX = box.right - winW, overlapY = box.bottom - winH; if (overlapX > 0) { if (box.right - box.left > winW) { hints.style.width = (winW - 5) + "px"; overlapX -= (box.right - box.left) - winW; } hints.style.left = (left = pos.left - overlapX) + "px"; } if (overlapY > 0) { var height = box.bottom - box.top; if (box.top - (pos.bottom - pos.top) - height > 0) { overlapY = height + (pos.bottom - pos.top); below = false; } else if (height > winH) { hints.style.height = (winH - 5) + "px"; overlapY -= height - winH; } hints.style.top = (top = pos.bottom - overlapY) + "px"; } (options.container || document.body).appendChild(hints); cm.addKeyMap(this.keyMap = buildKeyMap(options, { moveFocus: function(n) { widget.changeActive(widget.selectedHint + n); }, setFocus: function(n) { widget.changeActive(n); }, menuSize: function() { return widget.screenAmount(); }, length: completions.length, close: function() { completion.close(); }, pick: function() { widget.pick(); } })); if (options.closeOnUnfocus !== false) { var closingOnBlur; cm.on("blur", this.onBlur = function() { closingOnBlur = setTimeout(function() { completion.close(); }, 100); }); cm.on("focus", this.onFocus = function() { clearTimeout(closingOnBlur); }); } var startScroll = cm.getScrollInfo(); cm.on("scroll", this.onScroll = function() { var curScroll = cm.getScrollInfo(), editor = cm.getWrapperElement().getBoundingClientRect(); var newTop = top + startScroll.top - curScroll.top; var point = newTop - (window.pageYOffset || (document.documentElement || document.body).scrollTop); if (!below) point += hints.offsetHeight; if (point <= editor.top || point >= editor.bottom) return completion.close(); hints.style.top = newTop + "px"; hints.style.left = (left + startScroll.left - curScroll.left) + "px"; }); CodeMirror.on(hints, "dblclick", function(e) { var t = e.target || e.srcElement; if (t.hintId != null) {widget.changeActive(t.hintId); widget.pick();} }); CodeMirror.on(hints, "click", function(e) { var t = e.target || e.srcElement; if (t.hintId != null) widget.changeActive(t.hintId); }); CodeMirror.on(hints, "mousedown", function() { setTimeout(function(){cm.focus();}, 20); }); CodeMirror.signal(data, "select", completions[0], hints.firstChild); return true; } Widget.prototype = { close: function() { if (this.completion.widget != this) return; this.completion.widget = null; this.hints.parentNode.removeChild(this.hints); this.completion.cm.removeKeyMap(this.keyMap); var cm = this.completion.cm; if (this.completion.options.closeOnUnfocus !== false) { cm.off("blur", this.onBlur); cm.off("focus", this.onFocus); } cm.off("scroll", this.onScroll); }, pick: function() { this.completion.pick(this.data, this.selectedHint); }, changeActive: function(i) { i = Math.max(0, Math.min(i, this.data.list.length - 1)); if (this.selectedHint == i) return; var node = this.hints.childNodes[this.selectedHint]; node.className = node.className.replace(" CodeMirror-hint-active", ""); node = this.hints.childNodes[this.selectedHint = i]; node.className += " CodeMirror-hint-active"; if (node.offsetTop < this.hints.scrollTop) this.hints.scrollTop = node.offsetTop - 3; else if (node.offsetTop + node.offsetHeight > this.hints.scrollTop + this.hints.clientHeight) this.hints.scrollTop = node.offsetTop + node.offsetHeight - this.hints.clientHeight + 3; CodeMirror.signal(this.data, "select", this.data.list[this.selectedHint], node); }, screenAmount: function() { return Math.floor(this.hints.clientHeight / this.hints.firstChild.offsetHeight) || 1; } }; })();
/** * This constraint is used to ensure that a credit card number passes the Luhn algorithm. * It is useful as a first step to validating a credit card: before communicating with a payment gateway * * @author Alexey Bob <alexey.bob@gmail.com> */ 'use strict'; //import Validator from './AbstractValidator'; var Validator = require('./AbstractValidator'); class LuhnValidator extends Validator { constructor() { super(arguments); var message = arguments[0]['message']; this.configuring(); this.setMessage('message', message); } configuring() { this.setDefaultMessages({ 'message': 'Invalid card number.' }); } validate(data, errorType) { errorType = (errorType == null) ? 'array' : errorType; this.setErrorType(errorType); this.resetErrors(); var message = this.getMessage('message'); if (null === data || '' === data) { return ; } if (!this.ctype_digit(data)) { // INVALID_CHARACTERS_ERROR this.addError(message.format({value: data})); return; } var checkSum = 0; var length = data.length; // Starting with the last digit and walking left, add every second // digit to the check sum // e.g. 7 9 9 2 7 3 9 8 7 1 3 // ^ ^ ^ ^ ^ ^ // = 7 + 9 + 7 + 9 + 7 + 3 for (var i = length - 1; i >= 0; i -= 2) { checkSum += (data[i] * 1); } // Starting with the second last digit and walking left, double every // second digit and add it to the check sum // For doubles greater than 9, sum the individual digits // e.g. 7 9 9 2 7 3 9 8 7 1 3 // ^ ^ ^ ^ ^ // = 1+8 + 4 + 6 + 1+6 + 2 for (var i = length - 2; i >= 0; i -= 2) { checkSum += this.array_sum(this.str_split(data[i] * 2)); } if (0 === checkSum || 0 !== checkSum % 10) { // CHECKSUM_FAILED_ERROR this.addError(message.format({value: data})); } } } module.exports = LuhnValidator;
import { flatMap, keyBy } from "lodash"; import determineBlackOrWhiteTextColor from "./determineBlackOrWhiteTextColor"; export function getTagsAndTagOptions(allTags) { return flatMap(allTags, tag => { if (tag.tagOptions && tag.tagOptions.length) { return tag.tagOptions.map(tagO => { const fullname = `${tag.name}: ${tagO.name}`; const value = `${tag.id}:${tagO.id}`; return { ...tagO, label: fullname, value, id: tagO.id }; }); } return { ...tag, label: tag.name, value: tag.id }; }); } export function getKeyedTagsAndTagOptions(tags) { return keyBy(getTagsAndTagOptions(tags), "value"); } export function getTagColorStyle(color) { return color ? { style: { backgroundColor: color, color: determineBlackOrWhiteTextColor(color) } } : {}; } export function getTagProps(vals) { return { ...getTagColorStyle(vals.color), children: vals.label || vals.name }; }
jQuery(document).ready(function($) { /* Initiate Light filters */ LightFilter.init() /* Add jQuery table sorter parser */ $.tablesorter.addParser({ // set a unique id id: 'ranks', is: function(s) { // return false so this parser is not auto detected return false; }, format: function(s) { var s_trimmed = s.trim() if (s_trimmed) { return s_trimmed; } return Number.MAX_VALUE.toString(); }, // set type, either numeric or text type: 'numeric' }); // Intialize the table sorter of table-results-athletes var column_count = $("#table-results-athletes").find("tr:first th").length; var last_column_index = column_count - 1; var headers = {} for (i = 2; i < column_count; i += 1) { headers[i] = (i % 2 == 1) ? { sorter: 'ranks' } : { sorter: false } } $("#table-results-athletes").tablesorter({ // sort on the first column and third column, order asc sortList: [[last_column_index, 0], [0, 0]], headers: headers }); // intialize the table sorter of table-results-teams var column_count = $("#table-results-teams").find("tr:first th").length; var last_column_index = column_count - 1; var headers = {} for (i = 2; i < column_count; i += 1) { headers[i] = (i % 2 == 1) ? { sorter: 'ranks' } : { sorter: false } } $("#table-results-teams").tablesorter({ // sort on the first column and third column, order asc sortList: [[last_column_index,0],[0,0]], headers: headers }); /* Initiate jquery.dragsort */ function saveOrder() { var data = $("#chosen-list li").map(function() { return $(this).data('itemidx'); }).get(); $("input[name=chosen_list_order]").val(data.join(" ")); }; $("#chosen-list, #available-list").dragsort({ dragSelector: "li", dragBetween: true, dragEnd: saveOrder, placeHolderTemplate: "<li class='list-group-item'></li>" }); /* Add jquery.dragsort extending click handlers */ $('#available-list').on('click', 'li', function() { $('#chosen-list').append($(this)); saveOrder(); }); $('#chosen-list').on('click', 'li', function() { $('#available-list').append($(this)); saveOrder(); }); // Initial saving of the saveOrder. saveOrder(); /* Vertical scroll handling */ $(window).scroll(function() { var scroll_limit = 150; var scroll_top = $(this).scrollTop(); scrollResponsePageHeader(scroll_top, scroll_limit); scrollResponseHorizontalFormButtons(scroll_top, scroll_limit); }); function scrollResponsePageHeader(scroll_top, scroll_limit) { var page_header_div = $(".page-header:first"); var is_locked = page_header_div.hasClass("fixed"); var page_header_bg_img = page_header_div.find(".page-header-bg-img:first"); if (scroll_top == 0) { scrollResponseTransform(page_header_bg_img, null); } else if (scroll_top < scroll_limit) { if (is_locked) { page_header_div.removeClass("fixed"); } scrollResponseTransform(page_header_bg_img, scroll_top / 5); } else if (scroll_top >= scroll_limit && !is_locked) { page_header_div.addClass("fixed"); scrollResponseTransform(page_header_bg_img, scroll_limit / 5); } } function scrollResponseTransform(element, transform_value) { if (transform_value) { element.css("transform", "translate3d(0px, " + transform_value + "px, 0px)"); } else { element.css("transform", "none"); } } function scrollResponseHorizontalFormButtons(scroll_top, scroll_limit) { var default_margin_top = 100 var button_group = $('.btn-group-vertical.vertical-align-center') var is_locked = button_group.hasClass("fixed"); if (button_group) { if (!is_locked && scroll_top > scroll_limit) { button_group.addClass("fixed"); } else if (is_locked && scroll_top <= scroll_limit) { button_group.removeClass("fixed"); } } } // media query handling with enquire.js var vertically_centered_buttons = $("#btn-group-vertical-align") enquire.register("screen and (min-width: 992px)", { // OPTIONAL // If supplied, triggered when a media query matches. match : function() { vertically_centered_buttons.removeClass('btn-group btn-group-justified') vertically_centered_buttons.addClass('btn-group-vertical') }, // OPTIONAL // If supplied, triggered when the media query transitions // *from a matched state to an unmatched state*. unmatch : function() { vertically_centered_buttons.removeClass('btn-group-vertical') vertically_centered_buttons.addClass('btn-group btn-group-justified') }, // OPTIONAL // If supplied, triggered once, when the handler is registered. setup : function() {}, // OPTIONAL, defaults to false // If set to true, defers execution of the setup function // until the first time the media query is matched deferSetup : true, // OPTIONAL // If supplied, triggered when handler is unregistered. // Place cleanup code here destroy : function() {} }); });
/*! @license MIT ©2015-2016 Ruben Verborgh, Ghent University - imec */ var ViewCollection = require('../../lib/views/ViewCollection'); var View = require('../../lib/views/View'); describe('ViewCollection', function () { describe('The ViewCollection module', function () { it('should be a function', function () { ViewCollection.should.be.a('function'); }); it('should be a ViewCollection constructor', function () { new ViewCollection().should.be.an.instanceof(ViewCollection); }); it('should create new ViewCollection objects', function () { ViewCollection().should.be.an.instanceof(ViewCollection); }); }); describe('A ViewCollection instance without views', function () { var viewCollection; before(function () { viewCollection = new ViewCollection(); }); it('should throw an error when matching a view', function () { (function () { viewCollection.matchView('Foo'); }) .should.throw('No view named Foo found.'); }); }); describe('A ViewCollection instance with one view', function () { var viewCollection, viewA; before(function () { viewA = new View('MyView1', 'text/html,application/trig;q=0.7'); viewCollection = new ViewCollection([viewA]); }); it('should throw an error when matching a view with a non-existing type', function () { (function () { viewCollection.matchView('Bar'); }) .should.throw('No view named Bar found.'); }); describe('when a client requests HTML', function () { var viewDetails, request, response; before(function () { request = { headers: { accept: 'text/html' } }; response = {}; viewDetails = viewCollection.matchView('MyView1', request, response); }); it('should return a match for the view', function () { viewDetails.should.have.property('view', viewA); viewDetails.should.have.property('type', 'text/html'); viewDetails.should.have.property('responseType', 'text/html;charset=utf-8'); }); }); describe('when a client requests TriG', function () { var viewDetails, request, response; before(function () { request = { headers: { accept: 'application/trig' } }; response = {}; viewDetails = viewCollection.matchView('MyView1', request, response); }); it('should return a match for the view', function () { viewDetails.should.have.property('view', viewA); viewDetails.should.have.property('type', 'application/trig'); viewDetails.should.have.property('responseType', 'application/trig;charset=utf-8'); }); }); }); describe('A ViewCollection instance with three views of two types', function () { var viewCollection, viewA, viewB, viewC; before(function () { viewA = new View('MyView1', 'text/html,application/trig;q=0.5'); viewB = new View('MyView1', 'text/html;q=1.0,application/trig'); viewC = new View('MyView2', 'text/html'); viewCollection = new ViewCollection([viewA, viewB, viewC]); }); it('should throw an error when matching a view with a non-existing type', function () { (function () { viewCollection.matchView('Bar'); }) .should.throw('No view named Bar found.'); }); describe('when matching a request of one view type as HTML', function () { var viewDetails, request, response; before(function () { request = { headers: { accept: 'text/html' } }; response = {}; viewDetails = viewCollection.matchView('MyView1', request, response); }); it('should return a description of the best fitting view', function () { viewDetails.should.have.property('view', viewA); viewDetails.should.have.property('type', 'text/html'); viewDetails.should.have.property('responseType', 'text/html;charset=utf-8'); }); }); describe('when matching a request of one view type as TriG', function () { var viewDetails, request, response; before(function () { request = { headers: { accept: 'application/trig' } }; response = {}; viewDetails = viewCollection.matchView('MyView1', request, response); }); it('should return a description of the best fitting view', function () { viewDetails.should.have.property('view', viewB); viewDetails.should.have.property('type', 'application/trig'); viewDetails.should.have.property('responseType', 'application/trig;charset=utf-8'); }); }); describe('when matching a request of another view type as HTML', function () { var viewDetails, request, response; before(function () { request = { headers: { accept: 'text/html' } }; response = {}; viewDetails = viewCollection.matchView('MyView2', request, response); }); it('should return a description of the other view', function () { viewDetails.should.have.property('view', viewC); viewDetails.should.have.property('type', 'text/html'); viewDetails.should.have.property('responseType', 'text/html;charset=utf-8'); }); }); }); });
(function() { 'use strict'; angular.module('app.charts') .directive('barChart', chartDirective); chartDirective.$inject = ['d3']; function chartDirective(d3) { return { template: '<svg></svg>', link: link }; function link(scope, elem) { var data, dataField, barSizes, marks; var space = 20; var barSpace = 5; var chartWidth = 300; var chartHeight = 320; var svgElem = d3.select(elem[0]).select('svg'); var group = svgElem.append('g'); var chart = group.selectAll('rect'); var marksText = group.selectAll('text'); var colors = ['#9E0041', '#C32F4B', '#E1514B', '#F47245', '#eeb763', '#e5cf73', '#d0c865', '#a4c57b', '#9CD6A4', '#6CC4A4', '#4D9DB4', '#4776B4', '#5E4EA1', '#7E4E81']; function updateChart() { if (!data) return; marks = []; barSizes = []; chart = chart.data([]); marksText = marksText.data([]); marksText.exit().remove(); chart.exit().remove(); for (var i = 0; i < data.length; i++) { var markIndex = marks.indexOf(data[i][dataField].toString()); if (markIndex === -1) { marks.push(data[i][dataField].toString()); barSizes.push(1); } else { barSizes[markIndex]++; } } var barWidth = (chartWidth + barSpace) / barSizes.length - barSpace; var barScale = d3.scale.linear().domain([0, d3.max(barSizes)]).range([0, chartHeight]); chart = chart.data(barSizes); chart.exit().remove(); chart.enter().append('rect').attr({ width: barWidth, height: function(d) { return barScale(d); }, x: function(d, i) { return i * (barWidth + barSpace); }, y: function(d) { return chartHeight - barScale(d); }, fill: function(d, i) { return colors[i]; } }); marksText = marksText.data(barSizes); marksText.exit().remove(); marksText.enter().append('text').attr({ x: function (d, i) { return ((chartWidth + barSpace) / barSizes.length) * i + (chartWidth - barSpace * (barSizes.length - 1)) / barSizes.length / 2; }, 'font-size': (barWidth / 2 > 24 ? 24 : barWidth / 3) + 'px', 'font-weight': 400 }).text(function(d, i) { return marks[i]; }); marksText.attr({ y: function (d, i) { if (this.clientWidth + (barWidth / 2 > 24 ? 24 : barWidth / 3) > barScale(barSizes[i])) return chartHeight - barScale(barSizes[i]); else return chartHeight - 2; }, transform: function(d, i) { return 'rotate(-90, ' + (((chartWidth + barSpace) / barSizes.length) * i + (chartWidth - barSpace * (barSizes.length - 1)) / barSizes.length / 2) + ', ' + (this.clientWidth + (barWidth / 2 > 24 ? 24 : barWidth / 3) > barScale(barSizes[i]) ? chartHeight - barScale(barSizes[i]) - 5 : chartHeight - 5) + ')'; }, fill: function (d, i) { if (this.clientWidth + (barWidth / 2 > 24 ? 24 : barWidth / 3) > barScale(barSizes[i])) return colors[i]; else return '#fff'; } }); updateSize(); } function updateSize() { var svgRect = svgElem[0][0].getBoundingClientRect(); var svgWidth = svgRect.width; var svgHeight = svgRect.height; var groupScale = group[0][0].getBBox(); var k = Math.min((svgWidth - 2 * space) / groupScale.width, (svgHeight - 2 * space) / groupScale.height); var newX = ((svgWidth - 2 * space) / k - groupScale.width) / 2 - groupScale.x + space / k; var newY = ((svgHeight - 2 * space) / k - groupScale.height) / 2 - groupScale.y + space / k; if (k !== Infinity) { group.attr('transform', 'scale(' + k + ') translate(' + newX + ' ' + newY + ')'); } } scope.$on(scope.board, function() { updateSize(); }); scope.$on('gridster-item-transition-end', function() { updateSize(); }); scope.$watch('data', function(newVal) { if (newVal) { data = newVal; dataField = 'author'; updateChart(); } }); scope.$watch('field', function(newVal) { if (newVal) { data = scope.source; dataField = newVal; updateChart(); } }); } } })();
/*globals define, _, WebGMEGlobal*/ /*jshint browser: true*/ define([ // Add the css for this button 'js/Constants', 'js/RegistryKeys', 'js/PanelBase/PanelBase', './FloatingActionButton.Plugins', 'js/Utils/ComponentSettings', 'text!./templates/PluginButton.html.ejs', 'text!./templates/PluginAnchor.html.ejs', 'text!./templates/NoPlugins.html', // Extra js and css for the button 'css!./styles/css/floating-action-btn.css', 'css!./styles/css/icons.css' ], function ( CONSTANTS, REGISTRY_KEYS, PanelBase, ActionBtnPlugins, ComponentSettings, PluginBtnTemplateText, PluginTemplateText, NoPluginHtml ) { 'use strict'; var PluginButton, PluginTemplate = _.template(PluginTemplateText), PluginBtnTemplate = _.template(PluginBtnTemplateText), DEFAULT_ICON = 'play_arrow', DEFAULT_STYLE = { priority: 0 }; // I need to extend this so I can support custom actions that do not // use a plugin. // TODO // // The button needs to have an action name and function. Plugins will have // a stock function to use (results will also be refactored). // // TODO: // + Refactor the actions to lookup and call a function // + Where should I put the actions? PluginButton = function (layoutManager, params) { var options = {}; //initialize UI PanelBase.call(this); this.client = params.client; this.currentPlugins = []; this._validPlugins = []; this.buttons = {}; // name -> function this._currentButtons = []; this._config = { hideOnEmpty: true, pluginUIConfigs: {} }; ComponentSettings.resolveWithWebGMEGlobal(this._config, PluginButton.getComponentId()); ActionBtnPlugins.call(this); this._initialize(); this.logger.debug('ctor finished'); }; _.extend(PluginButton.prototype, PanelBase.prototype); PluginButton.getComponentId = function () { return 'FloatingActionButton'; }; PluginButton.prototype._needsUpdate = function () { // Check if the buttons have changed var actionNames = Object.keys(this.buttons); return !this._currentButtons.length || // No actions actionNames.length !== this._currentButtons.length || _.difference(actionNames, this._currentButtons).length; }; PluginButton.prototype.update = function () { if (this._needsUpdate()) { this._updateButton(); } }; PluginButton.prototype._clearHtml = function () { this.$el.find('.tooltipped').tooltip('remove'); this.$el.empty(); }; PluginButton.prototype._updateButton = function () { // Create the html elements var html; // Update the html this._clearHtml(); html = this._createButtonHtml(); if (html) { this.$el.append(html); // Set the onclick for the action buttons var anchors = [], child, container = html[0], listElement; for (var i = container.children.length; i--;) { child = container.children[i]; if (child.tagName.toLowerCase() === 'a') { anchors.push(child); } else { // ul element for (var k = child.children.length; k--;) { listElement = child.children[k].children[0]; if (listElement) { anchors.push(listElement); } } } } // Add onclick listener anchors .forEach(anchor => { var name = anchor.getAttribute('data-tooltip'); anchor.onclick = this._onButtonClicked.bind(this, name); }); this.$el.find('.tooltipped').tooltip({delay: 50}); } }; PluginButton.prototype._initialize = function () { // Add listener for object changed and update the button WebGMEGlobal.State.on('change:' + CONSTANTS.STATE_ACTIVE_OBJECT, (model, nodeId) => this.selectedObjectChanged(nodeId)); // TODO: Do I need a destructor for this? // TODO: I should check to see how this updates when the validPlugins // gets updated. It may require a refresh of the active node currently }; PluginButton.prototype.TERRITORY_RULE = {children: 0}; PluginButton.prototype.selectedObjectChanged = function(nodeId) { if (this._territoryId) { this.client.removeUI(this._territoryId); } if (typeof nodeId === 'string') { this._territoryId = this.client.addUI(this, events => { this._eventCallback(events); }); this._currentNodeId = nodeId; this._selfPatterns = {}; this._selfPatterns[nodeId] = this.TERRITORY_RULE; this.client.updateTerritory(this._territoryId, this._selfPatterns); } }; PluginButton.prototype._eventCallback = function(events) { var event = events.find(e => e.eid === this._currentNodeId); if (event && (event.etype === CONSTANTS.TERRITORY_EVENT_LOAD || event.etype === CONSTANTS.TERRITORY_EVENT_UPDATE)) { this.onNodeLoad(event.eid); } }; PluginButton.prototype._createButtonHtml = function () { var actions = [], colors = ['red', 'blue', 'yellow darken-1', 'green'], actionNames, html, names, action; // Get the actions actionNames = Object.keys(this.buttons); names = actionNames // Remove all buttons that don't have an action or href .filter(name => this.buttons[name].action || typeof this.buttons[name].href === 'string'|| this.buttons[name].href.call(this) ) // Sort by priority .map(name => { return { name, priority: this.buttons[name].priority || 0 }; }) .sort((a, b) => a.priority > b.priority ? 1 : -1) .map(obj => obj.name); if (names.length) { names.unshift(names.pop()); } // Create the html for each for (var i = 0; i < names.length; i++) { action = this.buttons[names[i]]; actions.push(PluginTemplate({ name: names[i], icon: action.icon || DEFAULT_ICON, color: action.color || (i === 0 ? colors[i] : colors[(names.length-i) % colors.length]), // Add href if appropriate href: action.href ? action.href.call(this) : null })); } if (actions.length > 0) { html = PluginBtnTemplate({plugins: actions}); return $(html); } else if (this._config.hideOnEmpty) { return null; } else { return $(NoPluginHtml); } this._currentButtons = names; }; PluginButton.prototype._onButtonClicked = function (name, event) { // Look up the function and invoke it if (this.buttons[name].action) { this.buttons[name].action.call(this, event); } }; _.extend(PluginButton.prototype, ActionBtnPlugins.prototype); return PluginButton; });
(function() { "use strict"; describe("scormAPI", function() { var api, constants, listener, result; beforeEach(function() { api = new window.simplifyScorm.ScormAPI(); api.apiLog = sinon.stub(); sinon.spy(api, "throwSCORMError"); constants = window.simplifyScorm.constants; listener = sinon.stub(); }); context("initially", function() { it("should create a global instance of itself", function() { expect(window.API).to.be.an.instanceof(window.simplifyScorm.ScormAPI); }); }); describe("#LMSCommit", function() { beforeEach(function() { api.on("LMSCommit", listener); }); context("when not initialized", function() { beforeEach(function() { result = api.LMSCommit(); }); it("should throw a SCORM error", function() { expect(api.throwSCORMError).to.have.been.calledOnce; expect(api.throwSCORMError).to.have.been.calledWith(301); expect(api.LMSGetLastError()).to.equal("301"); }); it("should not notify event listeners", function() { expect(listener).to.not.have.been.called; }); it("should log at INFO level", function() { expect(api.apiLog).to.have.been.calledWith("LMSCommit", null, sinon.match.string, constants.LOG_LEVEL_INFO); }); it("should return false", function() { expect(result).to.equal(constants.SCORM_FALSE); }); }); context("when initialized", function() { beforeEach(function() { api.LMSInitialize(); api.apiLog.reset(); api.lastErrorCode = "301"; result = api.LMSCommit(); }); it("should notify event listeners", function() { expect(listener).to.have.been.calledOnce; }); it("should log at INFO level", function() { expect(api.apiLog).to.have.been.calledOnce; expect(api.apiLog).to.have.been.calledWith("LMSCommit", null, sinon.match.string, constants.LOG_LEVEL_INFO); }); it("should clear the error state", function() { expect(api.LMSGetLastError()).to.equal("0"); }); it("should return true", function() { expect(result).to.equal(constants.SCORM_TRUE); }); }); }); describe("#LMSFinish", function() { beforeEach(function() { api.on("LMSFinish", listener); }); context("when not initialized", function() { beforeEach(function() { result = api.LMSFinish(); }); it("should throw a SCORM error", function() { expect(api.throwSCORMError).to.have.been.calledOnce; expect(api.throwSCORMError).to.have.been.calledWith(301); expect(api.LMSGetLastError()).to.equal("301"); }); it("should not terminate the API", function() { expect(api.currentState).to.equal(constants.STATE_NOT_INITIALIZED); }); it("should not notify event listeners", function() { expect(listener).to.not.have.been.called; }); it("should log at INFO level", function() { expect(api.apiLog).to.have.been.calledWith("LMSFinish", null, sinon.match.string, constants.LOG_LEVEL_INFO); }); it("should return false", function() { expect(result).to.equal(constants.SCORM_FALSE); }); }); context("when initialized", function() { beforeEach(function() { api.LMSInitialize(); api.apiLog.reset(); api.lastErrorCode = "301"; result = api.LMSFinish(); }); it("should terminate the API", function() { expect(api.currentState).to.equal(constants.STATE_TERMINATED); }); it("should notify event listeners", function() { expect(listener).to.have.been.calledOnce; }); it("should log at INFO level", function() { expect(api.apiLog).to.have.been.calledOnce; expect(api.apiLog).to.have.been.calledWith("LMSFinish", null, sinon.match.string, constants.LOG_LEVEL_INFO); }); it("should clear the error state", function() { expect(api.LMSGetLastError()).to.equal("0"); }); it("should return true", function() { expect(result).to.equal(constants.SCORM_TRUE); }); }); }); describe("#LMSInitialize", function() { beforeEach(function() { api.lastErrorCode = "301"; api.on("LMSInitialize", listener); result = api.LMSInitialize(); }); it("should initialize the API", function() { expect(api.currentState).to.equal(constants.STATE_INITIALIZED); }); it("should notify event listeners", function() { expect(listener).to.have.been.calledOnce; }); it("should log at INFO level", function() { expect(api.apiLog).to.have.been.calledOnce; expect(api.apiLog).to.have.been.calledWith("LMSInitialize", null, sinon.match.string, constants.LOG_LEVEL_INFO); }); it("should clear the error state", function() { expect(api.LMSGetLastError()).to.equal("0"); }); it("should return true", function() { expect(result).to.equal(constants.SCORM_TRUE); }); context("when already initialized", function() { beforeEach(function() { api.apiLog.reset(); listener.reset(); result = api.LMSInitialize(); }); it("should throw a SCORM error", function() { expect(api.throwSCORMError).to.have.been.calledOnce; expect(api.throwSCORMError).to.have.been.calledWith(101, sinon.match.string); expect(api.LMSGetLastError()).to.equal("101"); }); it("should not notify event listeners", function() { expect(listener).to.not.have.been.called; }); it("should log at INFO level", function() { expect(api.apiLog).to.have.been.calledWith("LMSInitialize", null, sinon.match.string, constants.LOG_LEVEL_INFO); }); it("should return false", function() { expect(result).to.equal(constants.SCORM_FALSE); }); }); context("when finished", function() { beforeEach(function() { result = api.LMSFinish(); api.apiLog.reset(); listener.reset(); result = api.LMSInitialize(); }); it("should throw a SCORM error", function() { expect(api.throwSCORMError).to.have.been.calledOnce; expect(api.throwSCORMError).to.have.been.calledWith(101, sinon.match.string); expect(api.LMSGetLastError()).to.equal("101"); }); it("should not initialize the API", function() { expect(api.currentState).to.equal(constants.STATE_TERMINATED); }); it("should not notify event listeners", function() { expect(listener).to.not.have.been.called; }); it("should log at INFO level", function() { expect(api.apiLog).to.have.been.calledWith("LMSInitialize", null, sinon.match.string, constants.LOG_LEVEL_INFO); }); it("should return false", function() { expect(result).to.equal(constants.SCORM_FALSE); }); }); }); }); })();
var Icon = require('../icon'); var element = require('magic-virtual-element'); var clone = require('../clone'); exports.render = function render(component) { var props = clone(component.props); delete props.children; return element( Icon, props, element('path', { d: 'M20 5h-3.2L15 3H9L7.2 5H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 14h-8v-1c-2.8 0-5-2.2-5-5s2.2-5 5-5V7h8v12zm-3-6c0-2.8-2.2-5-5-5v1.8c1.8 0 3.2 1.4 3.2 3.2s-1.4 3.2-3.2 3.2V18c2.8 0 5-2.2 5-5zm-8.2 0c0 1.8 1.4 3.2 3.2 3.2V9.8c-1.8 0-3.2 1.4-3.2 3.2z' }) ); };
version https://git-lfs.github.com/spec/v1 oid sha256:0e1fce284bd80c690fe10a3b9f810be68e39d63f05779c68f0b9d14886c85611 size 64192
version https://git-lfs.github.com/spec/v1 oid sha256:8addb65159ec852f00c4fdc34d0b89c78d9d8c32f3fdb1ea0b1a591b28765fa6 size 4330
import React from 'react'; import ReactDOM from 'react-dom'; import { shallow } from 'enzyme'; import TabsetsItemNotifs from '../TabsetsItemNotifs'; it('renders without crashing', () => { const props = {}; shallow( <TabsetsItemNotifs {...props} />, {context: {}} ); });
'use strict'; var gutil = require('gulp-util'); var faker = require('faker'); var through = require('through2'); module.exports = function() { return through.obj(function(file, enc, cb) { if (file.isNull()) { cb(null, file); return; } if (file.isStream()) { cb(new gutil.PluginError('gulp-faker', 'Streaming not supported')); return; } try { var c = file.contents.toString(); c = c.replace(/<faker-([^"]+?)-([^"]+?)\/>/g, function(match, cat, name) { if ((!faker[cat]) || (!faker[cat][name])) return match; return faker[cat][name](); }); file.contents = new Buffer(c); this.push(file); } catch (err) { this.emit('error', new gutil.PluginError('gulp-faker', err)); } cb(); }); };
import React from 'react'; import PropTypes from 'prop-types'; import BaseView from '../../utils/rnw-compat/BaseView'; const propTypes = { children: PropTypes.node.isRequired, titleId: PropTypes.string, }; const OffcanvasHeader = React.forwardRef((props, ref) => ( <BaseView {...props} ref={ref} essentials={{ className: 'offcanvas-header' }} /> )); OffcanvasHeader.displayName = 'OffcanvasHeader'; OffcanvasHeader.propTypes = propTypes; export default OffcanvasHeader;
/* @flow */ import resolveToCwd from "./../utils/resolve-to-cwd"; import { resolveModuleToCwd } from "./../utils/npm"; type Aliases = { [string]: string }; const aliases: Aliases = {}; export default function createAliases({ framework, filename }: AikParams): Aliases { if (framework === "react") { return Object.assign({}, aliases, { aikReactEntryPoint: resolveToCwd(filename), react: resolveModuleToCwd("react"), "react-dom": resolveModuleToCwd("react-dom") }); } return aliases; }
(function () { 'use strict'; angular .module('sampleApp', [ 'route-provider', 'state-provider', 'services', 'models' ]) .constant("CONFIG", { url: "http://dev.example", domain: "http://dev.example", port: "80" }) ; angular.module('route-provider', ['ngRoute']); angular.module('state-provider', ['ui.router']); angular.module('services', []); angular.module('models', []); })();
const _path = require('path'), _fs = require('fs'), _tjs = require('typescript-json-schema'), stringify = require('json-stringify-pretty-compact'); const program = _tjs.programFromConfig( _path.resolve('tsconfig.json')); const schema = _tjs.generateSchema(program, '*', { id: 'https://json-rql.org/schema.json' }); schema.anyOf = [ { $ref: "#/definitions/Subject" }, { $ref: "#/definitions/Group" }, { $ref: "#/definitions/Update" }, { $ref: "#/definitions/Describe" }, { $ref: "#/definitions/Construct" }, { $ref: "#/definitions/Distinct" }, { $ref: "#/definitions/Select" } ]; _fs.writeFileSync(_path.resolve('spec/schema.json'), stringify(schema), 'utf-8');
var curry = require('./curry'); var call = function (fn, val) { return fn(val); }; module.exports = curry(call);
// displayedNotes.srv.spec.js 'use strict'; describe('Service: displayedNotes', function () { var displayedNotes; beforeEach(function () { module('simpleNote'); inject(function ($injector) { displayedNotes = $injector.get('displayedNotes'); }); }); it('should be an array', function () { expect(displayedNotes.notes).to.be.instanceof(Array); }); it('should set displayedNotes.notes', function () { var testNotes = [1,2,3,4,5]; displayedNotes.setDisplayedNotes(testNotes); expect(displayedNotes.notes).to.deep.equal(testNotes); }); });
/* Write a script that prints all the numbers from 1 to N, that are not divisible by 3 and 7 at the same time */ var jsConsole; var button = document.getElementById('print'); button.onclick = printNumbers; function printNumbers() { var n = jsConsole.readInteger('#input'); for (var i = 1; i <= n; i++) { if (i % 3 === 0 && i % 7 === 0 ) { continue; } if (i === n) { jsConsole.write(i); console.log(i); break; } jsConsole.write(i + ', '); console.log(i + ', '); } }
/** * Created by leon on 15/11/5. */ angular.module("treeSelectDemo", ["ui.neptune"]) .factory("OrgListBySelectTree", function (nptRepository) { function builderOrgTreeNode(nodes, data) { if (data) { nodes.nodes = []; for (var i = 0; i < data.length; i++) { var node = { id: data[i]["id"], title: data[i]["name"] }; builderOrgTreeNode(node, data[i].children); nodes.nodes.push(node); } } } return nptRepository("queryOrgTree").params({ "instid": "10000001468002", "dimtype": "hr" }).addResponseInterceptor(function (response) { var orgNodes = [{ id: response.data.id, title: response.data.simplename }]; builderOrgTreeNode(orgNodes[0], response.data.children); return orgNodes; }); }) .factory("UserListBySelectTree", function (nptRepository) { return nptRepository("queryUsersByOrgid").addRequestInterceptor(function (request) { if (request.params.id) { request.params = { orgid: request.params.id }; } return request; }); }) .controller("treeSelectDemoController", function ($scope, UserListBySelectTree, OrgListBySelectTree) { var vm = this; this.selectTreeSetting = { onRegisterApi: function (selectTreeApi) { vm.selectTreeApi = selectTreeApi; }, treeRepository: OrgListBySelectTree, listRepository: UserListBySelectTree }; this.show = function () { vm.selectTreeApi.open().then(function (data) { $scope.item = data; }, function () { $scope.item = { msg: "用户取消选择" } }) }; });
'use strict'; /** * DESIGN NOTES * * The design decisions behind the scope are heavily favored for speed and memory consumption. * * The typical use of scope is to watch the expressions, which most of the time return the same * value as last time so we optimize the operation. * * Closures construction is expensive in terms of speed as well as memory: * - No closures, instead use prototypical inheritance for API * - Internal state needs to be stored on scope directly, which means that private state is * exposed as $$____ properties * * Loop operations are optimized by using while(count--) { ... } * - This means that in order to keep the same order of execution as addition we have to add * items to the array at the beginning (unshift) instead of at the end (push) * * Child scopes are created and removed often * - Using an array would be slow since inserts in the middle are expensive; so we use linked lists * * There are fewer watches than observers. This is why you don't want the observer to be implemented * in the same way as watch. Watch requires return of the initialization function which is expensive * to construct. */ /** * @ngdoc provider * @name $rootScopeProvider * @description * * Provider for the $rootScope service. */ /** * @ngdoc method * @name $rootScopeProvider#digestTtl * @description * * Sets the number of `$digest` iterations the scope should attempt to execute before giving up and * assuming that the model is unstable. * * The current default is 10 iterations. * * In complex applications it's possible that the dependencies between `$watch`s will result in * several digest iterations. However if an application needs more than the default 10 digest * iterations for its model to stabilize then you should investigate what is causing the model to * continuously change during the digest. * * Increasing the TTL could have performance implications, so you should not change it without * proper justification. * * @param {number} limit The number of digest iterations. */ /** * @ngdoc service * @name $rootScope * @this * * @description * * Every application has a single root {@link ng.$rootScope.Scope scope}. * All other scopes are descendant scopes of the root scope. Scopes provide separation * between the model and the view, via a mechanism for watching the model for changes. * They also provide event emission/broadcast and subscription facility. See the * {@link guide/scope developer guide on scopes}. */ function $RootScopeProvider() { var TTL = 10; var $rootScopeMinErr = minErr('$rootScope'); var lastDirtyWatch = null; var applyAsyncId = null; this.digestTtl = function(value) { if (arguments.length) { TTL = value; } return TTL; }; function createChildScopeClass(parent) { function ChildScope() { this.$$watchers = this.$$nextSibling = this.$$childHead = this.$$childTail = null; this.$$listeners = {}; this.$$listenerCount = {}; this.$$watchersCount = 0; this.$id = nextUid(); this.$$ChildScope = null; } ChildScope.prototype = parent; return ChildScope; } this.$get = ['$exceptionHandler', '$parse', '$browser', function($exceptionHandler, $parse, $browser) { function destroyChildScope($event) { $event.currentScope.$$destroyed = true; } function cleanUpScope($scope) { // Support: IE 9 only if (msie === 9) { // There is a memory leak in IE9 if all child scopes are not disconnected // completely when a scope is destroyed. So this code will recurse up through // all this scopes children // // See issue https://github.com/angular/angular.js/issues/10706 if ($scope.$$childHead) { cleanUpScope($scope.$$childHead); } if ($scope.$$nextSibling) { cleanUpScope($scope.$$nextSibling); } } // The code below works around IE9 and V8's memory leaks // // See: // - https://code.google.com/p/v8/issues/detail?id=2073#c26 // - https://github.com/angular/angular.js/issues/6794#issuecomment-38648909 // - https://github.com/angular/angular.js/issues/1313#issuecomment-10378451 $scope.$parent = $scope.$$nextSibling = $scope.$$prevSibling = $scope.$$childHead = $scope.$$childTail = $scope.$root = $scope.$$watchers = null; } /** * @ngdoc type * @name $rootScope.Scope * * @description * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the * {@link auto.$injector $injector}. Child scopes are created using the * {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when * compiled HTML template is executed.) See also the {@link guide/scope Scopes guide} for * an in-depth introduction and usage examples. * * * # Inheritance * A scope can inherit from a parent scope, as in this example: * ```js var parent = $rootScope; var child = parent.$new(); parent.salutation = "Hello"; expect(child.salutation).toEqual('Hello'); child.salutation = "Welcome"; expect(child.salutation).toEqual('Welcome'); expect(parent.salutation).toEqual('Hello'); * ``` * * When interacting with `Scope` in tests, additional helper methods are available on the * instances of `Scope` type. See {@link ngMock.$rootScope.Scope ngMock Scope} for additional * details. * * * @param {Object.<string, function()>=} providers Map of service factory which need to be * provided for the current scope. Defaults to {@link ng}. * @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should * append/override services provided by `providers`. This is handy * when unit-testing and having the need to override a default * service. * @returns {Object} Newly created scope. * */ function Scope() { this.$id = nextUid(); this.$$phase = this.$parent = this.$$watchers = this.$$nextSibling = this.$$prevSibling = this.$$childHead = this.$$childTail = null; this.$root = this; this.$$destroyed = false; this.$$listeners = {}; this.$$listenerCount = {}; this.$$watchersCount = 0; this.$$isolateBindings = null; } /** * @ngdoc property * @name $rootScope.Scope#$id * * @description * Unique scope ID (monotonically increasing) useful for debugging. */ /** * @ngdoc property * @name $rootScope.Scope#$parent * * @description * Reference to the parent scope. */ /** * @ngdoc property * @name $rootScope.Scope#$root * * @description * Reference to the root scope. */ Scope.prototype = { constructor: Scope, /** * @ngdoc method * @name $rootScope.Scope#$new * @kind function * * @description * Creates a new child {@link ng.$rootScope.Scope scope}. * * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} event. * The scope can be removed from the scope hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}. * * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is * desired for the scope and its child scopes to be permanently detached from the parent and * thus stop participating in model change detection and listener notification by invoking. * * @param {boolean} isolate If true, then the scope does not prototypically inherit from the * parent scope. The scope is isolated, as it can not see parent scope properties. * When creating widgets, it is useful for the widget to not accidentally read parent * state. * * @param {Scope} [parent=this] The {@link ng.$rootScope.Scope `Scope`} that will be the `$parent` * of the newly created scope. Defaults to `this` scope if not provided. * This is used when creating a transclude scope to correctly place it * in the scope hierarchy while maintaining the correct prototypical * inheritance. * * @returns {Object} The newly created child scope. * */ $new: function(isolate, parent) { var child; parent = parent || this; if (isolate) { child = new Scope(); child.$root = this.$root; } else { // Only create a child scope class if somebody asks for one, // but cache it to allow the VM to optimize lookups. if (!this.$$ChildScope) { this.$$ChildScope = createChildScopeClass(this); } child = new this.$$ChildScope(); } child.$parent = parent; child.$$prevSibling = parent.$$childTail; if (parent.$$childHead) { parent.$$childTail.$$nextSibling = child; parent.$$childTail = child; } else { parent.$$childHead = parent.$$childTail = child; } // When the new scope is not isolated or we inherit from `this`, and // the parent scope is destroyed, the property `$$destroyed` is inherited // prototypically. In all other cases, this property needs to be set // when the parent scope is destroyed. // The listener needs to be added after the parent is set if (isolate || parent !== this) child.$on('$destroy', destroyChildScope); return child; }, /** * @ngdoc method * @name $rootScope.Scope#$watch * @kind function * * @description * Registers a `listener` callback to be executed whenever the `watchExpression` changes. * * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest * $digest()} and should return the value that will be watched. (`watchExpression` should not change * its value when executed multiple times with the same input because it may be executed multiple * times by {@link ng.$rootScope.Scope#$digest $digest()}. That is, `watchExpression` should be * [idempotent](http://en.wikipedia.org/wiki/Idempotence).) * - The `listener` is called only when the value from the current `watchExpression` and the * previous call to `watchExpression` are not equal (with the exception of the initial run, * see below). Inequality is determined according to reference inequality, * [strict comparison](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators) * via the `!==` Javascript operator, unless `objectEquality == true` * (see next point) * - When `objectEquality == true`, inequality of the `watchExpression` is determined * according to the {@link angular.equals} function. To save the value of the object for * later comparison, the {@link angular.copy} function is used. This therefore means that * watching complex objects will have adverse memory and performance implications. * - The watch `listener` may change the model, which may trigger other `listener`s to fire. * This is achieved by rerunning the watchers until no changes are detected. The rerun * iteration limit is 10 to prevent an infinite loop deadlock. * * * If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called, * you can register a `watchExpression` function with no `listener`. (Be prepared for * multiple calls to your `watchExpression` because it will execute multiple times in a * single {@link ng.$rootScope.Scope#$digest $digest} cycle if a change is detected.) * * After a watcher is registered with the scope, the `listener` fn is called asynchronously * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the * watcher. In rare cases, this is undesirable because the listener is called when the result * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the * listener was called due to initialization. * * * * # Example * ```js // let's assume that scope was dependency injected as the $rootScope var scope = $rootScope; scope.name = 'misko'; scope.counter = 0; expect(scope.counter).toEqual(0); scope.$watch('name', function(newValue, oldValue) { scope.counter = scope.counter + 1; }); expect(scope.counter).toEqual(0); scope.$digest(); // the listener is always called during the first $digest loop after it was registered expect(scope.counter).toEqual(1); scope.$digest(); // but now it will not be called unless the value changes expect(scope.counter).toEqual(1); scope.name = 'adam'; scope.$digest(); expect(scope.counter).toEqual(2); // Using a function as a watchExpression var food; scope.foodCounter = 0; expect(scope.foodCounter).toEqual(0); scope.$watch( // This function returns the value being watched. It is called for each turn of the $digest loop function() { return food; }, // This is the change listener, called when the value returned from the above function changes function(newValue, oldValue) { if ( newValue !== oldValue ) { // Only increment the counter if the value changed scope.foodCounter = scope.foodCounter + 1; } } ); // No digest has been run so the counter will be zero expect(scope.foodCounter).toEqual(0); // Run the digest but since food has not changed count will still be zero scope.$digest(); expect(scope.foodCounter).toEqual(0); // Update food and run digest. Now the counter will increment food = 'cheeseburger'; scope.$digest(); expect(scope.foodCounter).toEqual(1); * ``` * * * * @param {(function()|string)} watchExpression Expression that is evaluated on each * {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers * a call to the `listener`. * * - `string`: Evaluated as {@link guide/expression expression} * - `function(scope)`: called with current `scope` as a parameter. * @param {function(newVal, oldVal, scope)} listener Callback called whenever the value * of `watchExpression` changes. * * - `newVal` contains the current value of the `watchExpression` * - `oldVal` contains the previous value of the `watchExpression` * - `scope` refers to the current scope * @param {boolean=} [objectEquality=false] Compare for object equality using {@link angular.equals} instead of * comparing for reference equality. * @returns {function()} Returns a deregistration function for this listener. */ $watch: function(watchExp, listener, objectEquality, prettyPrintExpression) { var get = $parse(watchExp); if (get.$$watchDelegate) { return get.$$watchDelegate(this, listener, objectEquality, get, watchExp); } var scope = this, array = scope.$$watchers, watcher = { fn: listener, last: initWatchVal, get: get, exp: prettyPrintExpression || watchExp, eq: !!objectEquality }; lastDirtyWatch = null; if (!isFunction(listener)) { watcher.fn = noop; } if (!array) { array = scope.$$watchers = []; } // we use unshift since we use a while loop in $digest for speed. // the while loop reads in reverse order. array.unshift(watcher); incrementWatchersCount(this, 1); return function deregisterWatch() { if (arrayRemove(array, watcher) >= 0) { incrementWatchersCount(scope, -1); } lastDirtyWatch = null; }; }, /** * @ngdoc method * @name $rootScope.Scope#$watchGroup * @kind function * * @description * A variant of {@link ng.$rootScope.Scope#$watch $watch()} where it watches an array of `watchExpressions`. * If any one expression in the collection changes the `listener` is executed. * * - The items in the `watchExpressions` array are observed via the standard `$watch` operation. Their return * values are examined for changes on every call to `$digest`. * - The `listener` is called whenever any expression in the `watchExpressions` array changes. * * @param {Array.<string|Function(scope)>} watchExpressions Array of expressions that will be individually * watched using {@link ng.$rootScope.Scope#$watch $watch()} * * @param {function(newValues, oldValues, scope)} listener Callback called whenever the return value of any * expression in `watchExpressions` changes * The `newValues` array contains the current values of the `watchExpressions`, with the indexes matching * those of `watchExpression` * and the `oldValues` array contains the previous values of the `watchExpressions`, with the indexes matching * those of `watchExpression` * The `scope` refers to the current scope. * @returns {function()} Returns a de-registration function for all listeners. */ $watchGroup: function(watchExpressions, listener) { var oldValues = new Array(watchExpressions.length); var newValues = new Array(watchExpressions.length); var deregisterFns = []; var self = this; var changeReactionScheduled = false; var firstRun = true; if (!watchExpressions.length) { // No expressions means we call the listener ASAP var shouldCall = true; self.$evalAsync(function() { if (shouldCall) listener(newValues, newValues, self); }); return function deregisterWatchGroup() { shouldCall = false; }; } if (watchExpressions.length === 1) { // Special case size of one return this.$watch(watchExpressions[0], function watchGroupAction(value, oldValue, scope) { newValues[0] = value; oldValues[0] = oldValue; listener(newValues, (value === oldValue) ? newValues : oldValues, scope); }); } forEach(watchExpressions, function(expr, i) { var unwatchFn = self.$watch(expr, function watchGroupSubAction(value, oldValue) { newValues[i] = value; oldValues[i] = oldValue; if (!changeReactionScheduled) { changeReactionScheduled = true; self.$evalAsync(watchGroupAction); } }); deregisterFns.push(unwatchFn); }); function watchGroupAction() { changeReactionScheduled = false; if (firstRun) { firstRun = false; listener(newValues, newValues, self); } else { listener(newValues, oldValues, self); } } return function deregisterWatchGroup() { while (deregisterFns.length) { deregisterFns.shift()(); } }; }, /** * @ngdoc method * @name $rootScope.Scope#$watchCollection * @kind function * * @description * Shallow watches the properties of an object and fires whenever any of the properties change * (for arrays, this implies watching the array items; for object maps, this implies watching * the properties). If a change is detected, the `listener` callback is fired. * * - The `obj` collection is observed via standard $watch operation and is examined on every * call to $digest() to see if any items have been added, removed, or moved. * - The `listener` is called whenever anything within the `obj` has changed. Examples include * adding, removing, and moving items belonging to an object or array. * * * # Example * ```js $scope.names = ['igor', 'matias', 'misko', 'james']; $scope.dataCount = 4; $scope.$watchCollection('names', function(newNames, oldNames) { $scope.dataCount = newNames.length; }); expect($scope.dataCount).toEqual(4); $scope.$digest(); //still at 4 ... no changes expect($scope.dataCount).toEqual(4); $scope.names.pop(); $scope.$digest(); //now there's been a change expect($scope.dataCount).toEqual(3); * ``` * * * @param {string|function(scope)} obj Evaluated as {@link guide/expression expression}. The * expression value should evaluate to an object or an array which is observed on each * {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the * collection will trigger a call to the `listener`. * * @param {function(newCollection, oldCollection, scope)} listener a callback function called * when a change is detected. * - The `newCollection` object is the newly modified data obtained from the `obj` expression * - The `oldCollection` object is a copy of the former collection data. * Due to performance considerations, the`oldCollection` value is computed only if the * `listener` function declares two or more arguments. * - The `scope` argument refers to the current scope. * * @returns {function()} Returns a de-registration function for this listener. When the * de-registration function is executed, the internal watch operation is terminated. */ $watchCollection: function(obj, listener) { $watchCollectionInterceptor.$stateful = true; var self = this; // the current value, updated on each dirty-check run var newValue; // a shallow copy of the newValue from the last dirty-check run, // updated to match newValue during dirty-check run var oldValue; // a shallow copy of the newValue from when the last change happened var veryOldValue; // only track veryOldValue if the listener is asking for it var trackVeryOldValue = (listener.length > 1); var changeDetected = 0; var changeDetector = $parse(obj, $watchCollectionInterceptor); var internalArray = []; var internalObject = {}; var initRun = true; var oldLength = 0; function $watchCollectionInterceptor(_value) { newValue = _value; var newLength, key, bothNaN, newItem, oldItem; // If the new value is undefined, then return undefined as the watch may be a one-time watch if (isUndefined(newValue)) return; if (!isObject(newValue)) { // if primitive if (oldValue !== newValue) { oldValue = newValue; changeDetected++; } } else if (isArrayLike(newValue)) { if (oldValue !== internalArray) { // we are transitioning from something which was not an array into array. oldValue = internalArray; oldLength = oldValue.length = 0; changeDetected++; } newLength = newValue.length; if (oldLength !== newLength) { // if lengths do not match we need to trigger change notification changeDetected++; oldValue.length = oldLength = newLength; } // copy the items to oldValue and look for changes. for (var i = 0; i < newLength; i++) { oldItem = oldValue[i]; newItem = newValue[i]; // eslint-disable-next-line no-self-compare bothNaN = (oldItem !== oldItem) && (newItem !== newItem); if (!bothNaN && (oldItem !== newItem)) { changeDetected++; oldValue[i] = newItem; } } } else { if (oldValue !== internalObject) { // we are transitioning from something which was not an object into object. oldValue = internalObject = {}; oldLength = 0; changeDetected++; } // copy the items to oldValue and look for changes. newLength = 0; for (key in newValue) { if (hasOwnProperty.call(newValue, key)) { newLength++; newItem = newValue[key]; oldItem = oldValue[key]; if (key in oldValue) { // eslint-disable-next-line no-self-compare bothNaN = (oldItem !== oldItem) && (newItem !== newItem); if (!bothNaN && (oldItem !== newItem)) { changeDetected++; oldValue[key] = newItem; } } else { oldLength++; oldValue[key] = newItem; changeDetected++; } } } if (oldLength > newLength) { // we used to have more keys, need to find them and destroy them. changeDetected++; for (key in oldValue) { if (!hasOwnProperty.call(newValue, key)) { oldLength--; delete oldValue[key]; } } } } return changeDetected; } function $watchCollectionAction() { if (initRun) { initRun = false; listener(newValue, newValue, self); } else { listener(newValue, veryOldValue, self); } // make a copy for the next time a collection is changed if (trackVeryOldValue) { if (!isObject(newValue)) { //primitive veryOldValue = newValue; } else if (isArrayLike(newValue)) { veryOldValue = new Array(newValue.length); for (var i = 0; i < newValue.length; i++) { veryOldValue[i] = newValue[i]; } } else { // if object veryOldValue = {}; for (var key in newValue) { if (hasOwnProperty.call(newValue, key)) { veryOldValue[key] = newValue[key]; } } } } } return this.$watch(changeDetector, $watchCollectionAction); }, /** * @ngdoc method * @name $rootScope.Scope#$digest * @kind function * * @description * Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and * its children. Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change * the model, the `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers} * until no more listeners are firing. This means that it is possible to get into an infinite * loop. This function will throw `'Maximum iteration limit exceeded.'` if the number of * iterations exceeds 10. * * Usually, you don't call `$digest()` directly in * {@link ng.directive:ngController controllers} or in * {@link ng.$compileProvider#directive directives}. * Instead, you should call {@link ng.$rootScope.Scope#$apply $apply()} (typically from within * a {@link ng.$compileProvider#directive directive}), which will force a `$digest()`. * * If you want to be notified whenever `$digest()` is called, * you can register a `watchExpression` function with * {@link ng.$rootScope.Scope#$watch $watch()} with no `listener`. * * In unit tests, you may need to call `$digest()` to simulate the scope life cycle. * * # Example * ```js var scope = ...; scope.name = 'misko'; scope.counter = 0; expect(scope.counter).toEqual(0); scope.$watch('name', function(newValue, oldValue) { scope.counter = scope.counter + 1; }); expect(scope.counter).toEqual(0); scope.$digest(); // the listener is always called during the first $digest loop after it was registered expect(scope.counter).toEqual(1); scope.$digest(); // but now it will not be called unless the value changes expect(scope.counter).toEqual(1); scope.name = 'adam'; scope.$digest(); expect(scope.counter).toEqual(2); * ``` * */ $digest: function() { var watch, value, last, fn, get, watchers, length, dirty, ttl = TTL, next, current, target = this, watchLog = [], logIdx, asyncTask; beginPhase('$digest'); // Check for changes to browser url that happened in sync before the call to $digest $browser.$$checkUrlChange(); if (this === $rootScope && applyAsyncId !== null) { // If this is the root scope, and $applyAsync has scheduled a deferred $apply(), then // cancel the scheduled $apply and flush the queue of expressions to be evaluated. $browser.defer.cancel(applyAsyncId); flushApplyAsync(); } lastDirtyWatch = null; do { // "while dirty" loop dirty = false; current = target; // It's safe for asyncQueuePosition to be a local variable here because this loop can't // be reentered recursively. Calling $digest from a function passed to $applyAsync would // lead to a '$digest already in progress' error. for (var asyncQueuePosition = 0; asyncQueuePosition < asyncQueue.length; asyncQueuePosition++) { try { asyncTask = asyncQueue[asyncQueuePosition]; asyncTask.scope.$eval(asyncTask.expression, asyncTask.locals); } catch (e) { $exceptionHandler(e); } lastDirtyWatch = null; } asyncQueue.length = 0; traverseScopesLoop: do { // "traverse the scopes" loop if ((watchers = current.$$watchers)) { // process our watches length = watchers.length; while (length--) { try { watch = watchers[length]; // Most common watches are on primitives, in which case we can short // circuit it with === operator, only when === fails do we use .equals if (watch) { get = watch.get; if ((value = get(current)) !== (last = watch.last) && !(watch.eq ? equals(value, last) : (isNumberNaN(value) && isNumberNaN(last)))) { dirty = true; lastDirtyWatch = watch; watch.last = watch.eq ? copy(value, null) : value; fn = watch.fn; fn(value, ((last === initWatchVal) ? value : last), current); if (ttl < 5) { logIdx = 4 - ttl; if (!watchLog[logIdx]) watchLog[logIdx] = []; watchLog[logIdx].push({ msg: isFunction(watch.exp) ? 'fn: ' + (watch.exp.name || watch.exp.toString()) : watch.exp, newVal: value, oldVal: last }); } } else if (watch === lastDirtyWatch) { // If the most recently dirty watcher is now clean, short circuit since the remaining watchers // have already been tested. dirty = false; break traverseScopesLoop; } } } catch (e) { $exceptionHandler(e); } } } // Insanity Warning: scope depth-first traversal // yes, this code is a bit crazy, but it works and we have tests to prove it! // this piece should be kept in sync with the traversal in $broadcast if (!(next = ((current.$$watchersCount && current.$$childHead) || (current !== target && current.$$nextSibling)))) { while (current !== target && !(next = current.$$nextSibling)) { current = current.$parent; } } } while ((current = next)); // `break traverseScopesLoop;` takes us to here if ((dirty || asyncQueue.length) && !(ttl--)) { clearPhase(); throw $rootScopeMinErr('infdig', '{0} $digest() iterations reached. Aborting!\n' + 'Watchers fired in the last 5 iterations: {1}', TTL, watchLog); } } while (dirty || asyncQueue.length); clearPhase(); // postDigestQueuePosition isn't local here because this loop can be reentered recursively. while (postDigestQueuePosition < postDigestQueue.length) { try { postDigestQueue[postDigestQueuePosition++](); } catch (e) { $exceptionHandler(e); } } postDigestQueue.length = postDigestQueuePosition = 0; }, /** * @ngdoc event * @name $rootScope.Scope#$destroy * @eventType broadcast on scope being destroyed * * @description * Broadcasted when a scope and its children are being destroyed. * * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to * clean up DOM bindings before an element is removed from the DOM. */ /** * @ngdoc method * @name $rootScope.Scope#$destroy * @kind function * * @description * Removes the current scope (and all of its children) from the parent scope. Removal implies * that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer * propagate to the current scope and its children. Removal also implies that the current * scope is eligible for garbage collection. * * The `$destroy()` is usually used by directives such as * {@link ng.directive:ngRepeat ngRepeat} for managing the * unrolling of the loop. * * Just before a scope is destroyed, a `$destroy` event is broadcasted on this scope. * Application code can register a `$destroy` event handler that will give it a chance to * perform any necessary cleanup. * * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to * clean up DOM bindings before an element is removed from the DOM. */ $destroy: function() { // We can't destroy a scope that has been already destroyed. if (this.$$destroyed) return; var parent = this.$parent; this.$broadcast('$destroy'); this.$$destroyed = true; if (this === $rootScope) { //Remove handlers attached to window when $rootScope is removed $browser.$$applicationDestroyed(); } incrementWatchersCount(this, -this.$$watchersCount); for (var eventName in this.$$listenerCount) { decrementListenerCount(this, this.$$listenerCount[eventName], eventName); } // sever all the references to parent scopes (after this cleanup, the current scope should // not be retained by any of our references and should be eligible for garbage collection) if (parent && parent.$$childHead === this) parent.$$childHead = this.$$nextSibling; if (parent && parent.$$childTail === this) parent.$$childTail = this.$$prevSibling; if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling; if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling; // Disable listeners, watchers and apply/digest methods this.$destroy = this.$digest = this.$apply = this.$evalAsync = this.$applyAsync = noop; this.$on = this.$watch = this.$watchGroup = function() { return noop; }; this.$$listeners = {}; // Disconnect the next sibling to prevent `cleanUpScope` destroying those too this.$$nextSibling = null; cleanUpScope(this); }, /** * @ngdoc method * @name $rootScope.Scope#$eval * @kind function * * @description * Executes the `expression` on the current scope and returns the result. Any exceptions in * the expression are propagated (uncaught). This is useful when evaluating Angular * expressions. * * # Example * ```js var scope = ng.$rootScope.Scope(); scope.a = 1; scope.b = 2; expect(scope.$eval('a+b')).toEqual(3); expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3); * ``` * * @param {(string|function())=} expression An angular expression to be executed. * * - `string`: execute using the rules as defined in {@link guide/expression expression}. * - `function(scope)`: execute the function with the current `scope` parameter. * * @param {(object)=} locals Local variables object, useful for overriding values in scope. * @returns {*} The result of evaluating the expression. */ $eval: function(expr, locals) { return $parse(expr)(this, locals); }, /** * @ngdoc method * @name $rootScope.Scope#$evalAsync * @kind function * * @description * Executes the expression on the current scope at a later point in time. * * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only * that: * * - it will execute after the function that scheduled the evaluation (preferably before DOM * rendering). * - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after * `expression` execution. * * Any exceptions from the execution of the expression are forwarded to the * {@link ng.$exceptionHandler $exceptionHandler} service. * * __Note:__ if this function is called outside of a `$digest` cycle, a new `$digest` cycle * will be scheduled. However, it is encouraged to always call code that changes the model * from within an `$apply` call. That includes code evaluated via `$evalAsync`. * * @param {(string|function())=} expression An angular expression to be executed. * * - `string`: execute using the rules as defined in {@link guide/expression expression}. * - `function(scope)`: execute the function with the current `scope` parameter. * * @param {(object)=} locals Local variables object, useful for overriding values in scope. */ $evalAsync: function(expr, locals) { // if we are outside of an $digest loop and this is the first time we are scheduling async // task also schedule async auto-flush if (!$rootScope.$$phase && !asyncQueue.length) { $browser.defer(function() { if (asyncQueue.length) { $rootScope.$digest(); } }); } asyncQueue.push({scope: this, expression: $parse(expr), locals: locals}); }, $$postDigest: function(fn) { postDigestQueue.push(fn); }, /** * @ngdoc method * @name $rootScope.Scope#$apply * @kind function * * @description * `$apply()` is used to execute an expression in angular from outside of the angular * framework. (For example from browser DOM events, setTimeout, XHR or third party libraries). * Because we are calling into the angular framework we need to perform proper scope life * cycle of {@link ng.$exceptionHandler exception handling}, * {@link ng.$rootScope.Scope#$digest executing watches}. * * ## Life cycle * * # Pseudo-Code of `$apply()` * ```js function $apply(expr) { try { return $eval(expr); } catch (e) { $exceptionHandler(e); } finally { $root.$digest(); } } * ``` * * * Scope's `$apply()` method transitions through the following stages: * * 1. The {@link guide/expression expression} is executed using the * {@link ng.$rootScope.Scope#$eval $eval()} method. * 2. Any exceptions from the execution of the expression are forwarded to the * {@link ng.$exceptionHandler $exceptionHandler} service. * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the * expression was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method. * * * @param {(string|function())=} exp An angular expression to be executed. * * - `string`: execute using the rules as defined in {@link guide/expression expression}. * - `function(scope)`: execute the function with current `scope` parameter. * * @returns {*} The result of evaluating the expression. */ $apply: function(expr) { try { beginPhase('$apply'); try { return this.$eval(expr); } finally { clearPhase(); } } catch (e) { $exceptionHandler(e); } finally { try { $rootScope.$digest(); } catch (e) { $exceptionHandler(e); // eslint-disable-next-line no-unsafe-finally throw e; } } }, /** * @ngdoc method * @name $rootScope.Scope#$applyAsync * @kind function * * @description * Schedule the invocation of $apply to occur at a later time. The actual time difference * varies across browsers, but is typically around ~10 milliseconds. * * This can be used to queue up multiple expressions which need to be evaluated in the same * digest. * * @param {(string|function())=} exp An angular expression to be executed. * * - `string`: execute using the rules as defined in {@link guide/expression expression}. * - `function(scope)`: execute the function with current `scope` parameter. */ $applyAsync: function(expr) { var scope = this; if (expr) { applyAsyncQueue.push($applyAsyncExpression); } expr = $parse(expr); scheduleApplyAsync(); function $applyAsyncExpression() { scope.$eval(expr); } }, /** * @ngdoc method * @name $rootScope.Scope#$on * @kind function * * @description * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for * discussion of event life cycle. * * The event listener function format is: `function(event, args...)`. The `event` object * passed into the listener has the following attributes: * * - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or * `$broadcast`-ed. * - `currentScope` - `{Scope}`: the scope that is currently handling the event. Once the * event propagates through the scope hierarchy, this property is set to null. * - `name` - `{string}`: name of the event. * - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel * further event propagation (available only for events that were `$emit`-ed). * - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag * to true. * - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called. * * @param {string} name Event name to listen on. * @param {function(event, ...args)} listener Function to call when the event is emitted. * @returns {function()} Returns a deregistration function for this listener. */ $on: function(name, listener) { var namedListeners = this.$$listeners[name]; if (!namedListeners) { this.$$listeners[name] = namedListeners = []; } namedListeners.push(listener); var current = this; do { if (!current.$$listenerCount[name]) { current.$$listenerCount[name] = 0; } current.$$listenerCount[name]++; } while ((current = current.$parent)); var self = this; return function() { var indexOfListener = namedListeners.indexOf(listener); if (indexOfListener !== -1) { namedListeners[indexOfListener] = null; decrementListenerCount(self, 1, name); } }; }, /** * @ngdoc method * @name $rootScope.Scope#$emit * @kind function * * @description * Dispatches an event `name` upwards through the scope hierarchy notifying the * registered {@link ng.$rootScope.Scope#$on} listeners. * * The event life cycle starts at the scope on which `$emit` was called. All * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get * notified. Afterwards, the event traverses upwards toward the root scope and calls all * registered listeners along the way. The event will stop propagating if one of the listeners * cancels it. * * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed * onto the {@link ng.$exceptionHandler $exceptionHandler} service. * * @param {string} name Event name to emit. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners. * @return {Object} Event object (see {@link ng.$rootScope.Scope#$on}). */ $emit: function(name, args) { var empty = [], namedListeners, scope = this, stopPropagation = false, event = { name: name, targetScope: scope, stopPropagation: function() {stopPropagation = true;}, preventDefault: function() { event.defaultPrevented = true; }, defaultPrevented: false }, listenerArgs = concat([event], arguments, 1), i, length; do { namedListeners = scope.$$listeners[name] || empty; event.currentScope = scope; for (i = 0, length = namedListeners.length; i < length; i++) { // if listeners were deregistered, defragment the array if (!namedListeners[i]) { namedListeners.splice(i, 1); i--; length--; continue; } try { //allow all listeners attached to the current scope to run namedListeners[i].apply(null, listenerArgs); } catch (e) { $exceptionHandler(e); } } //if any listener on the current scope stops propagation, prevent bubbling if (stopPropagation) { event.currentScope = null; return event; } //traverse upwards scope = scope.$parent; } while (scope); event.currentScope = null; return event; }, /** * @ngdoc method * @name $rootScope.Scope#$broadcast * @kind function * * @description * Dispatches an event `name` downwards to all child scopes (and their children) notifying the * registered {@link ng.$rootScope.Scope#$on} listeners. * * The event life cycle starts at the scope on which `$broadcast` was called. All * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get * notified. Afterwards, the event propagates to all direct and indirect scopes of the current * scope and calls all registered listeners along the way. The event cannot be canceled. * * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed * onto the {@link ng.$exceptionHandler $exceptionHandler} service. * * @param {string} name Event name to broadcast. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners. * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on} */ $broadcast: function(name, args) { var target = this, current = target, next = target, event = { name: name, targetScope: target, preventDefault: function() { event.defaultPrevented = true; }, defaultPrevented: false }; if (!target.$$listenerCount[name]) return event; var listenerArgs = concat([event], arguments, 1), listeners, i, length; //down while you can, then up and next sibling or up and next sibling until back at root while ((current = next)) { event.currentScope = current; listeners = current.$$listeners[name] || []; for (i = 0, length = listeners.length; i < length; i++) { // if listeners were deregistered, defragment the array if (!listeners[i]) { listeners.splice(i, 1); i--; length--; continue; } try { listeners[i].apply(null, listenerArgs); } catch (e) { $exceptionHandler(e); } } // Insanity Warning: scope depth-first traversal // yes, this code is a bit crazy, but it works and we have tests to prove it! // this piece should be kept in sync with the traversal in $digest // (though it differs due to having the extra check for $$listenerCount) if (!(next = ((current.$$listenerCount[name] && current.$$childHead) || (current !== target && current.$$nextSibling)))) { while (current !== target && !(next = current.$$nextSibling)) { current = current.$parent; } } } event.currentScope = null; return event; } }; var $rootScope = new Scope(); //The internal queues. Expose them on the $rootScope for debugging/testing purposes. var asyncQueue = $rootScope.$$asyncQueue = []; var postDigestQueue = $rootScope.$$postDigestQueue = []; var applyAsyncQueue = $rootScope.$$applyAsyncQueue = []; var postDigestQueuePosition = 0; return $rootScope; function beginPhase(phase) { if ($rootScope.$$phase) { throw $rootScopeMinErr('inprog', '{0} already in progress', $rootScope.$$phase); } $rootScope.$$phase = phase; } function clearPhase() { $rootScope.$$phase = null; } function incrementWatchersCount(current, count) { do { current.$$watchersCount += count; } while ((current = current.$parent)); } function decrementListenerCount(current, count, name) { do { current.$$listenerCount[name] -= count; if (current.$$listenerCount[name] === 0) { delete current.$$listenerCount[name]; } } while ((current = current.$parent)); } /** * function used as an initial value for watchers. * because it's unique we can easily tell it apart from other values */ function initWatchVal() {} function flushApplyAsync() { while (applyAsyncQueue.length) { try { applyAsyncQueue.shift()(); } catch (e) { $exceptionHandler(e); } } applyAsyncId = null; } function scheduleApplyAsync() { if (applyAsyncId === null) { applyAsyncId = $browser.defer(function() { $rootScope.$apply(flushApplyAsync); }); } } }]; }
import React from 'react' const BaseMapList = ({baseMaps, onChangeActiveBaseMap}) => { function handleChangeActiveBaseMap(baseMap) { return onChangeActiveBaseMap(baseMap) } return ( <ul className="basemap-list"> { // Checks if baseMaps already exists in state baseMaps ? baseMaps.map((baseMap, index) => { return ( <li className="basemap-list--item" key={index}> <a role="button" onClick={()=>handleChangeActiveBaseMap(baseMap)}> <img src={baseMap.image} className="basemap-list--image" alt={`${baseMap.name} base map`}/> </a> <span className="tooltip top">{baseMap.subtitle}</span> </li> ) }) : '' } </ul> ) } export default BaseMapList
/* General GridModel which generate whole slickGrid instance and can be extend with custom parameters. Using this library you avoid unnecessary work when constructing normal use-case slickGrid instance... */ var DataModel = function(options) { var _defaults = { columnStaticFilter: columnStaticFilter, columnFilters: {}, dataView: true, data: [], date: false, grid: false, refreshPeriod: 1000, refreshField: 'date', dataUrl: false, images: { group: '/js/vendor/SlickGrid/images/arrow_right_peppermint.png', }, dataComparer: comparer, getData: getData, useDataFlatter: true, useDataSorting: true, useDataGrouping: true, dataIdField: 'id', gridOptions: { //enableColumnReorder: false, //enableCellNavigation: true, }, gridId: '#myGrid', pagerId: false, slickPlugins: { groupItemMetadataProvider: { obj: newGroupItemMetadataProvider }, distinctMenu: { obj: true, options: { onAfterFilter: onAfterFilter, //getDistinct: getStaticDistinct, //doFilter: doStaticFilter, } }, headerMenu: { obj: true, options: {} }, headerButtons: { obj: true, options: {} } } } function Init(){ options = $.extend(true, {}, _defaults, options); if( options.dataUrl ){ //this.getStaticDistinct = getStaticDistinct; //this.doStaticFilter = doStaticFilter; options.slickPlugins.distinctMenu.options.doFilter = doRemoteFilter; } else { options.slickPlugins.distinctMenu.options.doFilter = doStaticFilter; } if( options.dataView === true ){ var dataViewArgs = {} generateDataGroupMenus(); if( options.useDataGrouping ){ var groupItemMetadataProvider = options.slickPlugins.groupItemMetadataProvider.obj(); options.slickPlugins.groupItemMetadataProvider.obj = groupItemMetadataProvider dataViewArgs = { groupItemMetadataProvider: groupItemMetadataProvider, inlineFilters: true } } options.dataView = newDataView(dataViewArgs); } //set data to dataView options.dataView.setItems(options.data); //set column filter //options.dataView.setFilter(columnStaticFilter); //if grid is not yet created, create grid instance if(!options.grid) options.grid = new Slick.Grid( options.gridId, options.dataView, options.columns, options.gridOptions); // Make the grid respond to DataView change events. options.dataView.onRowCountChanged.subscribe(function (e, args) { options.grid.updateRowCount(); options.grid.render(); }); options.dataView.onRowsChanged.subscribe(function (e, args) { options.grid.invalidateRows(args.rows); options.grid.render(); }); if( options.useDataGrouping){ options.grid.registerPlugin(groupItemMetadataProvider); } if( options.useDataSorting ){ options.grid.onSort.subscribe(function(e, args) { var comparer = function(a, b) { return a[args.sortCol.field] > b[args.sortCol.field]; } options.dataView.sort(comparer, args.sortAsc); }); } //add sort event handler options.grid.onSort.subscribe(function (e, args) { sortdir = args.sortAsc ? 1 : -1; sortcol = args.sortCol.field; options.dataView.sort(options.dataComparer, args.sortAsc); }); //if headerMenu is purpose to use, create it if( options.slickPlugins.headerMenu.obj === true ) { options.slickPlugins.headerMenu.obj = new Slick.Plugins.HeaderMenu( options.slickPlugins.headerMenu.options ); options.grid.registerPlugin(options.slickPlugins.headerMenu.obj); } //if headerButtons is purpose to use, create it if( options.slickPlugins.headerButtons.obj === true ) { options.slickPlugins.headerButtons.obj = new Slick.Plugins.HeaderButtons( options.slickPlugins.headerButtons.options); options.grid.registerPlugin(options.slickPlugins.headerButtons.obj); options.slickPlugins.headerButtons.obj.onCommand.subscribe(onCommand); } //if distinct menu is purpose to use create it if( options.slickPlugins.headerMenu.obj && options.slickPlugins.distinctMenu.obj === true ) // init distinctMenu { //Create distinctMenu instance options.slickPlugins.distinctMenu.obj = new Slick.Plugins.DistinctMenu( $.extend(true, {}, options.slickPlugins.distinctMenu.options, { headerMenu: options.slickPlugins.headerMenu.obj, columns: options.columns, })); //register distinctMenu options.grid.registerPlugin(options.slickPlugins.distinctMenu.obj); //and update menu items options.slickPlugins.distinctMenu.obj.update(); } if( options.pagerId ){ $.extend(true, options, {slickPlugins: { Pager: {obj: new Slick.Controls.Pager(options.dataView, options.grid, $(options.pagerId))} }}); } options.getData( options.dataUrl, options.slickPlugins.distinctMenu.obj.condition(), onAfterFilter); options.date = new Date(); if( options.refreshPeriod >= 0 && options.refreshField) { //setInterval( refresh, options.refreshPeriod ); } } function refresh() { var condition = {} condition[options.refreshField] = {$gte: options.date} options.slickPlugins.distinctMenu.obj.condition(options.refreshField, condition); Atari.getJSON( options.dataUrl+ '?q='+JSON.stringify(options.slickPlugins.distinctMenu.obj.condition() ), function(err, data){ if( data && data.length > 0 ){ console.log("New logs "+data.length); options.date = new Date(); options.dataView.beginUpdate(); data.forEach( function(row){ row.id = row._id|row.uuid; //options.data.push(row); options.dataView.addItem(row); }); options.dataView.endUpdate(); options.dataView.refresh(); //options.grid.refresh(); } }); } function onCommand(e, args) { if( args.command == 'group' ){ onGroup(e, args); // Stop propagation so that it doesn't register as a header click event. e.preventDefault(); e.stopPropagation(); } } function onGroup(e, args){ console.log('onGrouping..'); var grouping = options.dataView.getGrouping(); if( grouping.length == 0 || e.ctrlKey || e.altKey ){ grouping.push({ getter: args.column.id, formatter: function (g, a, b, c) { console.log(g); return args.column.name+": " + g.value + " <span style='color:green'>(" + g.count + " items)</span>"; }, collapsed: true, /*aggregators: [ //new Slick.Data.Aggregators.Avg("percentComplete"), //new Slick.Data.Aggregators.Sum("cost") ], aggregateCollapsed: true */ }); } else { grouping = []; } options.dataView.setGrouping( grouping ); } function generateDataGroupMenus(){ for(var i in options.columns){ var column = options.columns[i]; $.extend(true, column, {header: {buttons: [ { cssClass: 'slick-header-distinctbutton', image: options.images.group, command: 'group'} ]}}); } } function columnStaticFilter(item) { for(var field in options.columnFilters) { if( item!==undefined && item[field]!== options.columnFilters[field] ) { return false; } } return true; } function getData(url, urlParameters, callback){ $.getJSON( url, urlParameters ).done(function( json ) { if( typeof(json) == 'object' ){ callback(null, json); } else { callback('invalid response format'); } }).fail( function(jqxhr, textStatus, error) { callback( textStatus + ", " + error ); }); } function newGroupItemMetadataProvider(){ return new Slick.Data.GroupItemMetadataProvider() } function newDataView(args){return new Slick.Data.DataView(args);} function getStaticDistinct(field, url, urlParameters, callback){ function getDist(field){ var i=0,list = []; options.data.forEach( function(row){ if( row[field] && list.indexOf( row[field] )== -1 ){ list.push( row[field] ); } }); return list; } callback(null, getDist(field)); } function doStaticFilter(field, condition, callback){ console.log('doStaticFilter'); options.columnFilters = {}; for(var i=0;condition['$and'] && i<condition['$and'].length;i++){ for(var key in condition['$and'][i] ){ options.columnFilters[key] = condition['$and'][i][key]; }; } callback(); } function doRemoteFilter(field, condition, callback){ getData( options.dataUrl, {q: JSON.stringify(condition)}, callback); } function onAfterFilter(error, list){ if( list ){ if( list.length > 0 ){ var i, len=list.length; for(i=0;i<len;i++){ if( options.useDataFlatter) list[i] = flatten(list[i]); if(options.dataIdField!='id') list[i].id = list[i][options.dataIdField]; } } } options.data = list; options.dataView.beginUpdate(); options.dataView.setItems(options.data); options.dataView.endUpdate(); options.dataView.refresh(); options.slickPlugins.distinctMenu.obj.update(); } function comparer(a, b) { var x = a[sortcol], y = b[sortcol]; return (x == y ? 0 : (x > y ? 1 : -1)); } this.updateDistinct = function(){ options.slickPlugins.distinctMenu.obj.update(); } this.Grid = function(){ return options.grid; } this.DataView = function(){ return options.dataView; } this.Data = function(){ return options.data; } Init(); return this; }