code stringlengths 2 1.05M |
|---|
'use strict';
var fs = require('fs');
var _ = require('lodash');
var acorn = require('acorn');
var walk = require('acorn/dist/walk');
module.exports = {
parseBundle: parseBundle
};
function parseBundle(bundlePath) {
var contentBuffer = fs.readFileSync(bundlePath);
var contentStr = contentBuffer.toString('utf8');
var ast = acorn.parse(contentStr, { sourceType: 'script' });
var walkState = {
locations: null
};
walk.recursive(ast, walkState, {
CallExpression: function CallExpression(node, state, c) {
if (state.sizes) return;
var args = node.arguments;
// Additional bundle without webpack loader.
// Modules are stored in second argument, after chunk ids:
// webpackJsonp([<chunks>], <modules>, ...)
// As function name may be changed with `output.jsonpFunction` option we can't rely on it's default name.
if (node.callee.type === 'Identifier' && args.length >= 2 && isArgumentContainsChunkIds(args[0]) && isArgumentContainsModulesList(args[1])) {
state.locations = getModulesLocationFromFunctionArgument(args[1]);
return;
}
// Main bundle with webpack loader
// Modules are stored in first argument:
// (function (...) {...})(<modules>)
if (node.callee.type === 'FunctionExpression' && !node.callee.id && args.length === 1 && isArgumentContainsModulesList(args[0])) {
state.locations = getModulesLocationFromFunctionArgument(args[0]);
return;
}
// Walking into arguments because some of plugins (e.g. `DedupePlugin`) or some Webpack
// features (e.g. `umd` library output) can wrap modules list into additional IIFE.
_.each(args, function (arg) {
return c(arg, state);
});
}
});
if (!walkState.locations) {
return null;
}
return {
src: contentStr,
modules: _.mapValues(walkState.locations, function (loc) {
return contentBuffer.toString('utf8', loc.start, loc.end);
})
};
}
function isArgumentContainsChunkIds(arg) {
// Array of numeric ids
return arg.type === 'ArrayExpression' && _.every(arg.elements, isNumericId);
}
function isArgumentContainsModulesList(arg) {
if (arg.type === 'ObjectExpression') {
return _(arg.properties).map('value').every(isModuleWrapper);
}
if (arg.type === 'ArrayExpression') {
// Modules are contained in array.
// Array indexes are module ids
return _.every(arg.elements, function (elem) {
return (
// Some of array items may be skipped because there is no module with such id
!elem || isModuleWrapper(elem)
);
});
}
return false;
}
function isModuleWrapper(node) {
return (
// It's an anonymous function expression that wraps module
node.type === 'FunctionExpression' && !node.id ||
// If `DedupePlugin` is used it can be an ID of duplicated module...
isModuleId(node) ||
// or an array of shape [<module_id>, ...args]
node.type === 'ArrayExpression' && node.elements.length > 1 && isModuleId(node.elements[0])
);
}
function isModuleId(node) {
return node.type === 'Literal' && (isNumericId(node) || typeof node.value === 'string');
}
function isNumericId(node) {
return node.type === 'Literal' && Number.isInteger(node.value) && node.value >= 0;
}
function getModulesLocationFromFunctionArgument(arg) {
if (arg.type === 'ObjectExpression') {
var modulesNodes = arg.properties;
return _.transform(modulesNodes, function (result, moduleNode) {
var moduleId = moduleNode.key.name || moduleNode.key.value;
result[moduleId] = getModuleLocation(moduleNode.value);
}, {});
}
if (arg.type === 'ArrayExpression') {
var _modulesNodes = arg.elements;
return _.transform(_modulesNodes, function (result, moduleNode, i) {
if (!moduleNode) return;
result[i] = getModuleLocation(moduleNode);
}, {});
}
return {};
}
function getModuleLocation(node) {
if (node.type === 'FunctionExpression') {
node = node.body;
}
return _.pick(node, 'start', 'end');
} |
export function reportError(ctx) {
return (err) => {
const result = {};
const status = err && err.status ? err.status : 500;
if ('internalQuery' in err) {
// looks like postgres err
ctx.logger.error(err);
Reflect.deleteProperty(err, 'message'); // do not expose DB internals
}
if (err && 'message' in err && err.message) {
result.err = err.message
} else {
result.err = 'Internal Server Error';
}
ctx.status = status;
ctx.body = result;
}
}
export class BadRequestException {
constructor(message) {
this.message = message || 'Bad Request'
this.status = 400
}
}
export class NotAuthorizedException {
constructor(message) {
this.message = message || 'Unauthorized';
this.status = 401;
}
}
export class ForbiddenException {
constructor(message) {
this.message = message || 'Forbidden'
this.status = 403
}
}
export class NotFoundException {
constructor(message) {
this.message = message || 'Not found'
this.status = 404
}
}
export class ValidationException {
constructor(message) {
this.message = message || 'Invalid'
this.status = 422
}
}
|
//--------------------------------------------------------------------------------------------------//
//--------------------------------------------- Filters --------------------------------------------//
//--------------------------------------------------------------------------------------------------//
Router._filters = {
isReady: function() {
if (!this.ready()) {
// console.log('not ready')
this.render(getTemplate('loading'));
}else{
this.next();
// console.log('ready')
}
},
clearSeenErrors: function () {
clearSeenErrors();
this.next();
},
resetScroll: function () {
var scrollTo = window.currentScroll || 0;
var $body = $('body');
$body.scrollTop(scrollTo);
$body.css("min-height", 0);
},
isLoggedIn: function() {
if (!(Meteor.loggingIn() || Meteor.user())) {
throwError(i18n.t('please_sign_in_first'));
var current = getCurrentRoute();
if (current){
Session.set('fromWhere', current);
}
this.render('entrySignIn');
} else {
this.next();
}
},
isLoggedIn: AccountsTemplates.ensureSignedIn,
isLoggedOut: function() {
if(Meteor.user()){
this.render('already_logged_in');
} else {
this.next();
}
},
isAdmin: function() {
if(!this.ready()) return;
if(!isAdmin()){
this.render(getTemplate('no_rights'));
} else {
this.next();
}
},
canView: function() {
if(!this.ready() || Meteor.loggingIn()){
this.render(getTemplate('loading'));
} else if (!canView()) {
this.render(getTemplate('no_rights'));
} else {
this.next();
}
},
canPost: function () {
if(!this.ready() || Meteor.loggingIn()){
this.render(getTemplate('loading'));
} else if(!canPost()) {
throwError(i18n.t("sorry_you_dont_have_permissions_to_add_new_items"));
this.render(getTemplate('no_rights'));
} else {
this.next();
}
},
canEditPost: function() {
if(!this.ready()) return;
// Already subscribed to this post by route({waitOn: ...})
var post = Posts.findOne(this.params._id);
if(!currentUserCanEdit(post)){
throwError(i18n.t("sorry_you_cannot_edit_this_post"));
this.render(getTemplate('no_rights'));
} else {
this.next();
}
},
canEditComment: function() {
if(!this.ready()) return;
// Already subscribed to this comment by CommentPageController
var comment = Comments.findOne(this.params._id);
if(!currentUserCanEdit(comment)){
throwError(i18n.t("sorry_you_cannot_edit_this_comment"));
this.render(getTemplate('no_rights'));
} else {
this.next();
}
},
/*
hasCompletedProfile: function() {
if(!this.ready()) return;
var user = Meteor.user();
if (user && ! userProfileComplete(user)){
this.render(getTemplate('user_email'));
} else {
this.next();
}
},
*/
setTitle: function() {
// set title
var title = getSetting("title");
var tagline = getSetting("tagline");
document.title = (tagline ? title+': '+tagline : title) || "";
}
};
filters = Router._filters;
coreSubscriptions = new SubsManager({
// cache recent 50 subscriptions
cacheLimit: 50,
// expire any subscription after 30 minutes
expireIn: 30
});
Meteor.startup( function (){
if(Meteor.isClient){
// Load Hooks
Router.onRun( function () {
Session.set('categorySlug', null);
// if we're not on the search page itself, clear search query and field
if(getCurrentRoute().indexOf('search') == -1){
Session.set('searchQuery', '');
$('.search-field').val('').blur();
}
this.next();
});
// Before Hooks
Router.onBeforeAction(filters.isReady);
Router.onBeforeAction(filters.clearSeenErrors);
Router.onBeforeAction(filters.canView, {except: ['atSignIn', 'atSignUp', 'atForgotPwd', 'atResetPwd', 'signOut']});
// Router.onBeforeAction(filters.hasCompletedProfile);
Router.onBeforeAction(filters.isLoggedIn, {only: ['post_submit']});
Router.onBeforeAction(filters.isLoggedOut, {only: []});
Router.onBeforeAction(filters.canPost, {only: ['posts_pending', 'post_submit']});
Router.onBeforeAction(filters.canEditPost, {only: ['post_edit']});
Router.onBeforeAction(filters.canEditComment, {only: ['comment_edit']});
Router.onBeforeAction(filters.isAdmin, {only: ['posts_pending', 'all-users', 'settings', 'toolbox', 'logs']});
// After Hooks
// Router.onAfterAction(filters.resetScroll, {except:['posts_top', 'posts_new', 'posts_best', 'posts_pending', 'posts_category', 'all-users']});
Router.onAfterAction(analyticsInit); // will only run once thanks to _.once()
Router.onAfterAction(analyticsRequest); // log this request with mixpanel, etc
Router.onAfterAction(filters.setTitle);
// Unload Hooks
//
}
});
|
'use strict';
var express = require('express'),
router = express.Router(),
authenticateOverseerToken = require('../middlewares/authenticateOverseerToken'),
prepareUpdateObject = require('../middlewares/prepareUpdateObject'),
getCreditCatId = require('../middlewares/getCreditCatId'),
CreditCategory = require('models').CreditCategory,
CreditType = require('models').CreditType,
Sequelize = require('models').Sequelize,
HttpApiError = require('error').HttpApiError;
router.get('/', function(req, res, next) {
var offset = +req.query.offset || 0,
limit = +req.query.limit || 50;
CreditCategory
.findAll({ offset: offset, limit: limit })
.then(function(creditCats) {
res.json({
count: creditCats.length,
offset: offset,
limit: limit,
creditCats: creditCats
});
})
.catch(function(error) {
next(error);
});
});
router.get('/:creditCatId/credit/types', getCreditCatId, function(req, res, next) {
var offset = +req.query.offset || 0,
limit = +req.query.limit || 50;
CreditType
.findAll({
offset: offset,
limit: limit,
where: { credit_category_id: req.creditCatId }
})
.then(function(creditTypes) {
res.json({
count: creditTypes.length,
offset: offset,
limit: limit,
creditTypes: creditTypes
});
})
.catch(function(error) {
next(error);
});
});
router.get('/:creditCatId', getCreditCatId, function(req, res, next) {
CreditCategory
.findById(req.creditCatId)
.then(function(creditCat) {
if (!creditCat) {
return res.json({
message: 'No credit category has been found with given id'
});
}
res.json(creditCat);
})
.catch(function(error) {
next(error);
});
});
router.post('/', authenticateOverseerToken, function(req, res, next) {
CreditCategory
.create({
title: req.body.title
})
.then(function(creditCat) {
res.json({
creditCatId: creditCat.id
});
})
.catch(Sequelize.ValidationError, function(error) {
next(new HttpApiError(400, error.message));
})
.catch(function(error) {
next(error);
});
});
router.patch('/:creditCatId', authenticateOverseerToken,
getCreditCatId,
prepareUpdateObject, function(req, res, next) {
CreditCategory
.update(req.updateObj, {
where: {
id: req.creditCatId
}
})
.then(function() {
res.json({
updated: req.creditCatId
});
})
.catch(Sequelize.ValidationError, function(error) {
next(new HttpApiError(400, error.message));
})
.catch(function(error) {
next(error);
});
});
router.delete('/:creditCatId', authenticateOverseerToken,
getCreditCatId, function(req, res, next) {
CreditCategory
.destroy({
where: { id: req.creditCatId }
})
.then(function() {
res.json({
creditCatId: req.creditCatId
});
})
.catch(function(error) {
next(error);
});
});
module.exports = router;
|
var test = require('tap').test;
var distributions = require('../../distributions.js');
var equals = require('../equal.js');
var reference = require('../assets/studentt.json');
test('testing student t density function', function (t) {
equals.absoluteEqual({
test: t,
map: reference.pdf,
fn: (t, df) => distributions.Studentt(df).pdf(t),
limit: 0.0000005
});
t.end();
});
test('testing student t cumulative function', function (t) {
equals.absoluteEqual({
test: t,
map: reference.cdf,
fn: (t, df) => distributions.Studentt(df).cdf(t),
limit: 0.0000005
});
t.end();
});
test('testing student t inverse function', function (t) {
equals.absoluteEqual({
test: t,
map: reference.ppf,
fn: (p, df) => distributions.Studentt(df).inv(p),
limit: 0.0000005
});
equals.absoluteEqual({
test: t,
map: [
[0.0, 15, -Infinity],
[1.0, 15, +Infinity]
],
fn: (p, df) => distributions.Studentt(df).inv(p),
limit: 0.0000005
});
t.end();
});
test('testing student t key values', function (t) {
var studentt = distributions.Studentt(15);
t.equal(studentt.median(), 0);
t.equal(studentt.mean(), 0);
t.equal(studentt.variance(), 15/13);
t.end();
});
|
import { Vue } from '../../../vue'
import {
PROP_TYPE_ARRAY_OBJECT_STRING,
PROP_TYPE_BOOLEAN,
PROP_TYPE_BOOLEAN_STRING,
PROP_TYPE_STRING
} from '../../../constants/props'
import { identity } from '../../../utils/identity'
import { isBoolean } from '../../../utils/inspect'
import { makeProp } from '../../../utils/props'
import { toString } from '../../../utils/string'
import { attrsMixin } from '../../../mixins/attrs'
// Main `<table>` render mixin
// Includes all main table styling options
// --- Props ---
export const props = {
bordered: makeProp(PROP_TYPE_BOOLEAN, false),
borderless: makeProp(PROP_TYPE_BOOLEAN, false),
captionTop: makeProp(PROP_TYPE_BOOLEAN, false),
dark: makeProp(PROP_TYPE_BOOLEAN, false),
fixed: makeProp(PROP_TYPE_BOOLEAN, false),
hover: makeProp(PROP_TYPE_BOOLEAN, false),
noBorderCollapse: makeProp(PROP_TYPE_BOOLEAN, false),
outlined: makeProp(PROP_TYPE_BOOLEAN, false),
responsive: makeProp(PROP_TYPE_BOOLEAN_STRING, false),
small: makeProp(PROP_TYPE_BOOLEAN, false),
// If a string, it is assumed to be the table `max-height` value
stickyHeader: makeProp(PROP_TYPE_BOOLEAN_STRING, false),
striped: makeProp(PROP_TYPE_BOOLEAN, false),
tableClass: makeProp(PROP_TYPE_ARRAY_OBJECT_STRING),
tableVariant: makeProp(PROP_TYPE_STRING)
}
// --- Mixin ---
// @vue/component
export const tableRendererMixin = Vue.extend({
mixins: [attrsMixin],
provide() {
return {
bvTable: this
}
},
// Don't place attributes on root element automatically,
// as table could be wrapped in responsive `<div>`
inheritAttrs: false,
props,
computed: {
// Layout related computed props
isResponsive() {
const { responsive } = this
return responsive === '' ? true : responsive
},
isStickyHeader() {
let { stickyHeader } = this
stickyHeader = stickyHeader === '' ? true : stickyHeader
return this.isStacked ? false : stickyHeader
},
wrapperClasses() {
const { isResponsive } = this
return [
this.isStickyHeader ? 'b-table-sticky-header' : '',
isResponsive === true
? 'table-responsive'
: isResponsive
? `table-responsive-${this.responsive}`
: ''
].filter(identity)
},
wrapperStyles() {
const { isStickyHeader } = this
return isStickyHeader && !isBoolean(isStickyHeader) ? { maxHeight: isStickyHeader } : {}
},
tableClasses() {
let { hover, tableVariant } = this
hover = this.isTableSimple
? hover
: hover && this.computedItems.length > 0 && !this.computedBusy
return [
// User supplied classes
this.tableClass,
// Styling classes
{
'table-striped': this.striped,
'table-hover': hover,
'table-dark': this.dark,
'table-bordered': this.bordered,
'table-borderless': this.borderless,
'table-sm': this.small,
// The following are b-table custom styles
border: this.outlined,
'b-table-fixed': this.fixed,
'b-table-caption-top': this.captionTop,
'b-table-no-border-collapse': this.noBorderCollapse
},
tableVariant ? `${this.dark ? 'bg' : 'table'}-${tableVariant}` : '',
// Stacked table classes
this.stackedTableClasses,
// Selectable classes
this.selectableTableClasses
]
},
tableAttrs() {
const {
computedItems: items,
filteredItems,
computedFields: fields,
selectableTableAttrs
} = this
const ariaAttrs = this.isTableSimple
? {}
: {
'aria-busy': toString(this.computedBusy),
'aria-colcount': toString(fields.length),
// Preserve user supplied `aria-describedby`, if provided
'aria-describedby':
this.bvAttrs['aria-describedby'] || this.$refs.caption ? this.captionId : null
}
const rowCount =
items && filteredItems && filteredItems.length > items.length
? toString(filteredItems.length)
: null
return {
// We set `aria-rowcount` before merging in `$attrs`,
// in case user has supplied their own
'aria-rowcount': rowCount,
// Merge in user supplied `$attrs` if any
...this.bvAttrs,
// Now we can override any `$attrs` here
id: this.safeId(),
role: this.bvAttrs.role || 'table',
...ariaAttrs,
...selectableTableAttrs
}
}
},
render(h) {
const {
wrapperClasses,
renderCaption,
renderColgroup,
renderThead,
renderTbody,
renderTfoot
} = this
const $content = []
if (this.isTableSimple) {
$content.push(this.normalizeSlot())
} else {
// Build the `<caption>` (from caption mixin)
$content.push(renderCaption ? renderCaption() : null)
// Build the `<colgroup>`
$content.push(renderColgroup ? renderColgroup() : null)
// Build the `<thead>`
$content.push(renderThead ? renderThead() : null)
// Build the `<tbody>`
$content.push(renderTbody ? renderTbody() : null)
// Build the `<tfoot>`
$content.push(renderTfoot ? renderTfoot() : null)
}
// Assemble `<table>`
const $table = h(
'table',
{
staticClass: 'table b-table',
class: this.tableClasses,
attrs: this.tableAttrs,
key: 'b-table'
},
$content.filter(identity)
)
// Add responsive/sticky wrapper if needed and return table
return wrapperClasses.length > 0
? h(
'div',
{
class: wrapperClasses,
style: this.wrapperStyles,
key: 'wrap'
},
[$table]
)
: $table
}
})
|
import http from 'http';
import React from 'react';
import { renderToString } from 'react-dom/server';
import { match, RouterContext } from 'react-router';
import fs from 'fs';
import { createPage, write, writeError, writeNotFound, redirect } from './utils/server-utils';
import routes from './routes/RootRoute';
const webpack = require('webpack');
const config = require('../webpack.config');
var express = require('express');
var app = express();
const compiler = webpack(config[1]);
function renderApp(props, res) {
const markup = renderToString(<RouterContext {...props}/>);
const html = createPage(markup);
write(html, 'text/html', res);
}
app.use(require('webpack-dev-middleware')(compiler, {
publicPath: '__build__',
stats: {
colors: true
}
}));
app.use(require('webpack-hot-middleware')(compiler));
// Do anything you like with the rest of your express application.
app.get('*', function(req, res) {
if (req.url === '/favicon.ico') {
write('haha', 'text/plain', res);
}
// serve JavaScript assets
else if (/__build__/.test(req.url)) {
fs.readFile(`.${req.url}`, (err, data) => {
var ext = req.url.split('.').pop();
var contentTypeMap = {
'js': 'text/javascript',
'css': 'text/css'
};
write(data, contentTypeMap[ext] || '', res);
});
}
// handle all other urls with React Router
else {
match({ routes, location: req.url }, (error, redirectLocation, renderProps) => {
if(error){
writeError('ERROR!', res);
}
else if(redirectLocation){
redirect(redirectLocation, res);
}
else if(renderProps){
renderApp(renderProps, res);
}
else{
writeNotFound(res);
}
});
}
});
var server = http.createServer(app);
server.listen(process.env.PORT || 3000, function() {
console.log('Listening on %j', server.address());
});
|
/**
* This script is for ajax search
*/
$(document).ready(function() {
$("#search_form_text").keyup(function(){
if($("#search_form_text").val().length < 3) return;
$.post('/tneexrc/web/app_dev.php/ajax/search/'+$("#search_form_text").val(),function(data){
var result = '<table class="table table-striped table-hover well"><tbody>';
$.each(data, function(index, value) {
result= result+ '<tr ';
var cl = "row-fluid even";
if(index % 2 == 0)
cl = "row-fluid odd";
result= result+ '>';
result= result+ '<td>'+value.location+'</td>';
result= result+ '<td><a href="/tneexrc/web/app_dev.php/job/'+value.comapny_s+'/'+value.location_s+'/'+value.ref+'/'+value.position+'">'+value.position +'</a> </td>';
result= result+ '<td>'+value.company +'</td></tr>';
});
result= result+ '</tbody></table>';
$('#output').html(result);
}
);
});
}); |
/*global define*/
define({
"_widgetLabel": "Umkreissuche",
"searchHeaderText": "Eine Adresse suchen oder auf der Karte verorten",
"invalidSearchLayerMsg": "Such-Layer sind nicht ordnungsgemäß konfiguriert",
"bufferSliderText": "Ergebnisse in ${BufferDistance} ${BufferUnit} anzeigen",
"bufferSliderValueString": "Geben Sie eine Entfernung größer als null (0) an",
"unableToCreateBuffer": "Ergebnis(se) kann/konnten nicht gefunden werden",
"selectLocationToolTip": "Position festlegen",
"noFeatureFoundText": "Keine Ergebnisse gefunden ",
"unableToFetchResults": "Ergebnisse können nicht aus dem/den Layer(n) abgerufen werden:",
"informationTabTitle": "Informationen",
"directionTabTitle": "Wegbeschreibung",
"failedToGenerateRouteMsg": "Route konnte nicht erstellt werden.",
"geometryServicesNotFound": "Geometrieservice ist nicht verfügbar.",
"allPopupsDisabledMsg": "Pop-ups sind nicht konfiguriert, Ergebnisse können nicht angezeigt werden.",
"worldGeocoderName": "Adresse",
"searchLocationTitle": "Gesuchte Position",
"unknownAttachmentExt": "DATEI",
"proximityButtonTooltip": "Nächstgelegene/n durchsuchen",
"approximateDistanceTitle": "Ungefähre Entfernung: ${DistanceToLocation}",
"toggleTip": "Zum Ein-/Ausblenden von Filtereinstellungen klicken",
"filterTitle": "Anzuwendende Filter auswählen",
"clearFilterButton": "Alle Filter löschen",
"units": {
"miles": {
"displayText": "Meilen",
"acronym": "mi"
},
"kilometers": {
"displayText": "Kilometer",
"acronym": "km"
},
"feet": {
"displayText": "Fuß",
"acronym": "ft"
},
"meters": {
"displayText": "Meter",
"acronym": "m"
}
}
}); |
var searchData=
[
['unary_5fbit_5fnot',['unary_bit_not',['../d3/d4d/namespacebbb_1_1function_1_1direct__lambda.html#ac0e6ddec93a461b94a38fce232feee40ad77634e1730e985ce0114c3beb2cf8ca',1,'bbb::function::direct_lambda']]],
['unary_5ffunc_5fapply',['unary_func_apply',['../d3/d4d/namespacebbb_1_1function_1_1direct__lambda.html#ac0e6ddec93a461b94a38fce232feee40ad0e613c5cc5a5b9543e5b3becf3d2053',1,'bbb::function::direct_lambda']]],
['unary_5ffunction_2ehpp',['unary_function.hpp',['../db/d11/unary__function_8hpp.html',1,'']]],
['unary_5fminus',['unary_minus',['../d3/d4d/namespacebbb_1_1function_1_1direct__lambda.html#ac0e6ddec93a461b94a38fce232feee40a4087f1ffc05f4eab1b923856a05c6d12',1,'bbb::function::direct_lambda']]],
['unary_5fnot',['unary_not',['../d3/d4d/namespacebbb_1_1function_1_1direct__lambda.html#ac0e6ddec93a461b94a38fce232feee40ae07c277eeaeb49ff52e18fa89a2c4f3d',1,'bbb::function::direct_lambda']]],
['unary_5fplus',['unary_plus',['../d3/d4d/namespacebbb_1_1function_1_1direct__lambda.html#ac0e6ddec93a461b94a38fce232feee40ac4bb485390e425b490b0706d4f408467',1,'bbb::function::direct_lambda']]],
['unknown',['unknown',['../d8/db2/namespacebbb_1_1container__info.html#ab556caddfc8f1f1a78e0b02dcc921309aad921d60486366258809553a3db49a4a',1,'bbb::container_info']]],
['unlock',['unlock',['../de/dc1/classbbb_1_1multithread_1_1manager.html#af63c02b83a58e1d0f1b14eda94e3f74e',1,'bbb::multithread::manager']]],
['unordered_5fmap',['unordered_map',['../d8/db2/namespacebbb_1_1container__info.html#ab556caddfc8f1f1a78e0b02dcc921309a2d3c955815e43f44f7f2d51529545915',1,'bbb::container_info']]],
['unordered_5fmultimap',['unordered_multimap',['../d8/db2/namespacebbb_1_1container__info.html#ab556caddfc8f1f1a78e0b02dcc921309a77ea4cf3305cad392df07644ce487f04',1,'bbb::container_info']]],
['unordered_5fmultiset',['unordered_multiset',['../d8/db2/namespacebbb_1_1container__info.html#ab556caddfc8f1f1a78e0b02dcc921309a98fb5bd6a841cb36a662a4fbe5031202',1,'bbb::container_info']]],
['unordered_5fset',['unordered_set',['../d8/db2/namespacebbb_1_1container__info.html#ab556caddfc8f1f1a78e0b02dcc921309a25da9a081f4768825080ee2466f99d81',1,'bbb::container_info']]],
['unshift',['unshift',['../d9/d12/structbbb_1_1container_1_1array.html#a695c37165cbb84eac1713349627188b4',1,'bbb::container::array']]],
['update',['update',['../da/d8a/classbbb_1_1reusable__array.html#afab04bbca6a1d5ae80c858280d91f22b',1,'bbb::reusable_array']]],
['update_5fvalue',['update_value',['../d2/d64/classbbb_1_1enumeratable_1_1enumeratable__iterator.html#adbc4c08504ae40f31530fdbd505cd320',1,'bbb::enumeratable::enumeratable_iterator']]],
['utility_2ehpp',['utility.hpp',['../d8/da0/container_2utility_8hpp.html',1,'(Global Namespace)'],['../d0/d42/function_2direct__lambda_2utility_8hpp.html',1,'(Global Namespace)'],['../d6/d15/function_2utility_8hpp.html',1,'(Global Namespace)'],['../d4/dc0/tmp_2utility_8hpp.html',1,'(Global Namespace)']]]
];
|
var gulp = require('gulp');
// Build everything else
gulp.task('build', ['images', 'fonts', 'sass', 'root', 'compile', 'vendor', 'templates']);
|
import TableTile from "../support/elements/TableTile";
import CodapObject from "../support/elements/CodapObject";
import CaseCardObject from "../support/elements/CaseCardObject";
import CfmObject from "../support/elements/CfmObject";
const table = new TableTile;
const codap = new CodapObject;
const casecard = new CaseCardObject;
const cfm = new CfmObject;
const baseUrl = `${Cypress.config("baseUrl")}`;
const ext = '.codap';
context('attribute types', () => {
before(() => {
var filename = 'attribute-types-test-document',
dir = '../fixtures/';
cy.visit(baseUrl)
cy.wait(3000)
cfm.openDocFromModal();
cy.wait(500)
cfm.openLocalDoc(dir + filename + ext)
codap.getTableTileTitle().click() //bring the table into focus
})
describe('attribute types are rendered correctly', () => {
it('verify string', () => {
table.getCell("1", "1", 0).should('contain', 'Arizona');
})
it('verify numerical', () => {
table.getCell("2", "2", 0).should('contain', '48');
})
it('verify date', () => {
table.getCell("3", "3", 0).should('contain', '8/7/2017, 12:01 PM');
})
it('verify boolean', () => {
table.getCell("4", "4", 0).should('contain', 'false');
})
it('verify qualitative', () => {
table.getCell("5", "5", 0).find('span span').should('have.class', 'dg-qualitative-bar');
})
it('verify color', () => {
table.getCell("6", "6", 0).find('span').should('have.class', 'dg-color-table-cell');
})
it('verify bounds', () => {
cy.wait(1500);
table.getCell("8", "8", 0).find('span').should('have.class', 'dg-boundary-thumb');
})
it('verify invalid type', () => {
table.getCell("9", "9", 0).should('contain',"❌: invalid type(s) for '*'");
})
it('verify unrecognized', () => {
table.getCell("10", "10", 0).should('contain', "❌: 'Bool|color' is unrecognized");
})
})
}) |
var merge = require('yields-merge')
var own = Object.hasOwnProperty
var call = Function.call
module.exports = Emitter
/**
* Emitter constructor. Can optionally also act as a mixin
*
* @param {Object} [obj]
* @return {Object}
*/
function Emitter(obj){
if (obj) return merge(obj, Emitter.prototype)
}
/**
* Process `event`. All arguments after `topic` will
* be passed to all listeners
*
* emitter.emit('event', new Date)
*
* @param {String} topic
* @param {Any} [...args]
* @return {this}
*/
Emitter.prototype.emit = function(topic){
var sub = this._events
if (!(sub && (sub = sub[topic]))) return this
// single subsription case
if (typeof sub == 'function') {
// avoid using .apply() for speed
switch (arguments.length) {
case 1: sub.call(this);break
case 2: sub.call(this, arguments[1]);break
case 3: sub.call(this, arguments[1], arguments[2]);break
case 4: sub.call(this, arguments[1], arguments[2], arguments[3]);break
default:
// `arguments` is magic :)
topic = this
call.apply(sub, arguments)
}
} else {
var fn
var i = 0
var l = sub.length
switch (arguments.length) {
case 1: while (i < l) sub[i++].call(this);break
case 2: while (i < l) sub[i++].call(this, arguments[1]);break
case 3: while (i < l) sub[i++].call(this, arguments[1], arguments[2]);break
case 4: while (i < l) sub[i++].call(this, arguments[1], arguments[2], arguments[3]);break
default:
topic = this
while (i < l) call.apply(sub[i++], arguments)
}
}
return this
}
/**
* Add a subscription under a topic name
*
* emitter.on('event', function(data){})
*
* @param {String} topic
* @param {Function} fn
* @return {this}
*/
Emitter.prototype.on = function(topic, fn){
if (!own.call(this, '_events')) this._events = clone(this._events)
var events = this._events
if (typeof events[topic] == 'function') {
events[topic] = [events[topic], fn]
} else if (events[topic]) {
events[topic] = events[topic].concat(fn)
} else {
events[topic] = fn
}
return this
}
/**
* Remove subscriptions
*
* emitter.off() // clears all listeners
* emitter.off('topic') // clears all `topic` listeners
* emitter.off('topic', fn) // as above but only where `listener == fn`
*
* @param {String} [topic]
* @param {Function} [fn]
* @return {this}
*/
Emitter.prototype.off = function(topic, fn){
if (!this._events) return this
if (!own.call(this, '_events')) this._events = clone(this._events)
var events = this._events
if (topic == null) {
for (var i in events) delete events[i]
} else if (fn == null) {
delete events[topic]
} else {
var subs = events[topic]
if (!subs) return this
if (typeof subs == 'function') {
if (subs === fn) delete events[topic]
} else {
subs = events[topic] = subs.filter(function(listener){
return listener !== fn
})
// tidy
if (subs.length == 1) events[topic] = subs[0]
else if (!subs.length) delete events[topic]
}
}
return this
}
/**
* subscribe `fn` but remove if after its first invocation
*
* @param {String} topic
* @param {Function} fn
* @return {this}
*/
Emitter.prototype.once = function(topic, fn){
var self = this
return this.on(topic, function once(){
self.off(topic, once)
fn.apply(this, arguments)
})
}
/**
* see if `emitter` has any subscriptions matching
* `topic` and optionally also `fn`
*
* @param {Emitter} emitter
* @param {String} topic
* @param {Function} [fn]
* @return {Boolean}
*/
Emitter.hasSubscription = function(emitter, topic, fn){
var fns = Emitter.subscriptions(emitter, topic)
if (fn == null) return Boolean(fns.length)
return fns.indexOf(fn) >= 0
}
/**
* get an Array of subscriptions for `topic`
*
* @param {Emitter} emitter
* @param {String} topic
* @return {Array}
*/
Emitter.subscriptions = function(emitter, topic){
var fns = emitter._events
if (!fns || !(fns = fns[topic])) return []
if (typeof fns == 'function') return [fns]
return fns.slice()
}
function clone(obj){
return merge({}, obj)
}
|
RPH = {};
RPH.math = {
getDistance: function(x1, y1, x2, y2) {
return Math.pow(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2), 0.5);
},
getAngle: function(x1, y1, x2, y2) {
var angle;
if (Math.abs(x1 - x2) < RPH.W / 100 && y2 > y1) return 1 * Math.PI / 2;
if (Math.abs(x1 - x2) < RPH.W / 100 && y2 < y1) return 3 * Math.PI / 2;
angle = Math.atan((y2 - y1) / (x2 - x1));
if (x1 < x2) {
if (angle < 0) return angle + 2 * Math.PI;
return angle;
}
return angle + Math.PI;
}
};
RPH.mouse = {
x: 0,
y: 0,
xDrag: 0,
yDrag: 0,
isDragging: false,
get: function(e) {
var rect = RPH.canvas.getBoundingClientRect();
this.x = e.clientX - rect.left;
this.y = e.clientY - rect.top;
},
down: function(e) {
this.get(e);
this.xDrag = this.x;
this.yDrag = this.y;
this.isDragging = true;
},
up: function(e) {
this.get(e);
this.isDragging = false;
},
move: function(e) {
this.get(e);
},
draw: function(e) {
RPH.pen.circle(this.x, this.y, 5);
}
};
RPH.pen = {
clear: function() {
RPH.ctx.clearRect(0, 0, RPH.W, RPH.H);
},
rect: function(x, y, w, h) {
RPH.ctx.beginPath();
RPH.ctx.rect(x, y, w, h);
RPH.ctx.closePath();
RPH.ctx.fill();
},
circle: function(x, y, r) {
RPH.ctx.beginPath();
RPH.ctx.arc(x, y, r, 0, Math.PI * 2, true);
RPH.ctx.fill();
}
};
RPH.phone = {
alpha: 0,
alphaPrev: 0,
oBeta: Math.PI * 4 / 9,
dBeta: Math.PI / 7,
rBeta: Math.PI / 24,
r0: 0.35,
r2: 0.23,
r1: 0.29,
r3: 0.04,
fontString: "",
activeDigit: -1,
setDrag: function() {
var xc = this.centroid.x,
yc = this.centroid.y;
this.alpha = RPH.math.getAngle(RPH.W * xc, RPH.H * yc, RPH.mouse.x, RPH.mouse.y) - RPH.math.getAngle(RPH.W * xc, RPH.H * yc, RPH.mouse.xDrag, RPH.mouse.yDrag);
// dialing only works forward
this.alpha = (this.alpha < 0) ? 0 : this.alpha;
if (this.alpha > ((10 - this.activeDigit) * this.dBeta + this.rBeta)) {
RPH.mouse.isDragging = false;
var phoneField = document.getElementById("phone");
if (phoneField.value.length < 11) phoneField.value += this.activeDigit;
if (RPH.dialer.number.length < 11) RPH.dialer.number += this.activeDigit;
this.activeDigit = -1;
}
},
setActiveDigit: function() {
var angle;
this.activeDigit = -1;
for (i = 0; i < 10; i += 1) {
angle = this.oBeta + this.dBeta * i + this.alpha;
xt = RPH.W * this.centroid.x + RPH.minWH * this.r1 * Math.cos(angle);
yt = RPH.H * this.centroid.y + RPH.minWH * this.r1 * Math.sin(angle);
if (RPH.math.getDistance(RPH.mouse.x, RPH.mouse.y, xt, yt) < RPH.minWH * this.r3) {
this.activeDigit = i;
}
}
},
drawRing: function() {
var xc = this.centroid.x,
yc = this.centroid.y;
RPH.ctx.fillStyle = "#444444";
RPH.pen.circle(RPH.W * xc, RPH.H * yc, RPH.minWH * this.r0);
RPH.ctx.fillStyle = "rgb(240,245,240)";
RPH.pen.circle(RPH.W * xc, RPH.H * yc, RPH.minWH * this.r2);
},
drawLine: function() {
var angle = this.oBeta + 10 * this.dBeta + this.rBeta,
xc = this.centroid.x,
yc = this.centroid.y;
RPH.ctx.strokeStyle = "rgb(240,245,240)";
RPH.ctx.beginPath();
RPH.ctx.moveTo(RPH.W * xc + this.r0 * RPH.minWH * Math.cos(angle), RPH.H * yc + this.r0 * RPH.minWH * Math.sin(angle));
RPH.ctx.lineTo(RPH.W * xc + this.r1 * RPH.minWH * Math.cos(angle), RPH.H * yc + this.r1 * RPH.minWH * Math.sin(angle));
RPH.ctx.lineWidth = RPH.minWH / 150;
RPH.ctx.stroke();
},
drawNumber: function() {
RPH.ctx.font = RPH.minWH / 25 + "px " + this.fontString;
RPH.ctx.fillStyle = "#444444";
RPH.ctx.fillText(RPH.dialer.number, RPH.W * this.text.x, RPH.H * this.text.y);
},
drawDigits: function() {
var i, angle;
RPH.ctx.font = RPH.minWH / 18 + "px Courier";
for (i = 0; i < 10; i += 1) {
RPH.ctx.fillStyle = (this.activeDigit === i) ? "rgb(180,205,200)" : "rgb(240,245,240)";
angle = RPH.phone.oBeta + RPH.phone.dBeta * i + RPH.phone.alpha;
RPH.pen.circle(
RPH.W * this.centroid.x + RPH.minWH * this.r1 * Math.cos(angle),
RPH.H * this.centroid.y + RPH.minWH * this.r1 * Math.sin(angle),
RPH.minWH * this.r3
);
RPH.ctx.fillStyle = "#444444";
angle = RPH.phone.oBeta + RPH.phone.dBeta * i;
RPH.ctx.fillText(
i,
RPH.W * this.centroid.x + RPH.minWH * this.r1 * Math.cos(angle),
RPH.H * this.centroid.y + RPH.minWH * this.r1 * Math.sin(angle)
);
}
},
centroid: {
x: 0.5,
y: 0.55
},
text: {
x: 0.5,
y: 0.1,
isHovered: function() {
return (RPH.mouse.y / RPH.minWH < this.y + 0.02) && (RPH.mouse.y / RPH.minWH > this.y - 0.02);
}
}
};
RPH.dialer = {
number: "",
dial: function() {
console.log(this.number);
window.location = "tel:" + this.number;
}
};
RPH.mouseUp = function(e) {
RPH.mouse.up(e);
};
RPH.mouseDown = function(e) {
RPH.mouse.down(e);
RPH.mouse.isDragging = (RPH.phone.alpha < 0.03 && RPH.phone.activeDigit !== -1);
if (RPH.phone.text.isHovered()) {
RPH.dialer.dial();
}
};
RPH.mouseMove = function(e) {
RPH.mouse.move(e);
if (RPH.mouse.isDragging) {
RPH.phone.setDrag();
} else if (RPH.phone.alpha < 0.03) {
RPH.phone.setActiveDigit();
}
RPH.fontString = (RPH.phone.text.isHovered()) ? "bold " : "";
RPH.fontString += RPH.minWH / 30 + "px Courier";
};
// !main
RPH.draw = function() {
RPH.pen.clear();
RPH.ctx.textAlign = "center";
RPH.ctx.textBaseline = "middle";
RPH.phone.drawRing();
RPH.phone.drawLine();
RPH.phone.drawNumber();
RPH.phone.drawDigits();
if (RPH.phone.alpha > 0 && !RPH.mouse.isDragging) {
RPH.phone.alpha -= 0.02;
}
RPH.canvas.addEventListener('mousedown', RPH.mouseDown);
RPH.canvas.addEventListener('mousemove', RPH.mouseMove);
RPH.canvas.addEventListener('mouseup', RPH.mouseUp);
};
function touchHandler(event) {
var touch = event.changedTouches[0],
simulatedEvent = document.createEvent("MouseEvent");
simulatedEvent.initMouseEvent({
touchstart: "mousedown",
touchmove: "mousemove",
touchend: "mouseup"
}[event.type], true, true, window, 1,
touch.screenX, touch.screenY,
touch.clientX, touch.clientY, false,
false, false, false, 0, null);
touch.target.dispatchEvent(simulatedEvent);
event.preventDefault();
}
RPH.init = function() {
document.addEventListener("touchstart", touchHandler, true);
document.addEventListener("touchmove", touchHandler, true);
document.addEventListener("touchend", touchHandler, true);
document.addEventListener("touchcancel", touchHandler, true);
RPH.canvas = document.getElementById("retrophone");
RPH.ctx = RPH.canvas.getContext("2d");
this.resizeCanvas();
return setInterval(RPH.draw, 10);
};
RPH.resizeCanvas = function() {
//RPH.canvas.width = window.innerWidth;
RPH.canvas.height = 400;
RPH.W = RPH.canvas.width;
RPH.H = RPH.canvas.height;
RPH.minWH = Math.min(RPH.W, RPH.H);
};
RPH.init();
window.addEventListener('resize', RPH.resizeCanvas, false);
|
'use strict';
/**
* Module dependencies
*/
import * as mongo from 'mongodb';
import User from '../../../models/user';
import Post from '../../../models/post';
/**
* Aggregate post of a user
*
* @param {Object} params
* @return {Promise<object>}
*/
module.exports = (params) =>
new Promise(async (res, rej) =>
{
// Get 'user_id' parameter
const userId = params.user_id;
if (userId === undefined || userId === null) {
return rej('user_id is required');
}
// Lookup user
const user = await User.findOne({
_id: new mongo.ObjectID(userId)
});
if (user === null) {
return rej('user not found');
}
const datas = await Post
.aggregate([
{ $match: { user_id: user._id } },
{ $project: {
repost_id: '$repost_id',
reply_to_id: '$reply_to_id',
created_at: { $add: ['$created_at', 9 * 60 * 60 * 1000] } // Convert into JST
}},
{ $project: {
date: {
year: { $year: '$created_at' },
month: { $month: '$created_at' },
day: { $dayOfMonth: '$created_at' }
},
type: {
$cond: {
if: { $ne: ['$repost_id', null] },
then: 'repost',
else: {
$cond: {
if: { $ne: ['$reply_to_id', null] },
then: 'reply',
else: 'post'
}
}
}
}}
},
{ $group: { _id: {
date: '$date',
type: '$type'
}, count: { $sum: 1 } } },
{ $group: {
_id: '$_id.date',
data: { $addToSet: {
type: '$_id.type',
count: '$count'
}}
} }
])
.toArray();
datas.forEach(data => {
data.date = data._id;
delete data._id;
data.posts = (data.data.filter(x => x.type == 'post')[0] || { count: 0 }).count;
data.reposts = (data.data.filter(x => x.type == 'repost')[0] || { count: 0 }).count;
data.replies = (data.data.filter(x => x.type == 'reply')[0] || { count: 0 }).count;
delete data.data;
});
const graph = [];
for (let i = 0; i < 30; i++) {
let day = new Date(new Date().setDate(new Date().getDate() - i));
const data = datas.filter(d =>
d.date.year == day.getFullYear() && d.date.month == day.getMonth() + 1 && d.date.day == day.getDate()
)[0];
if (data) {
graph.push(data)
} else {
graph.push({
date: {
year: day.getFullYear(),
month: day.getMonth() + 1, // In JavaScript, month is zero-based.
day: day.getDate()
},
posts: 0,
reposts: 0,
replies: 0
})
};
}
res(graph);
});
|
var searchData=
[
['keycode',['KeyCode',['../classthewizardplusplus_1_1anna_1_1graphics_1_1_key_code.html',1,'thewizardplusplus::anna::graphics']]]
];
|
var path = require("path");
var webpack = require("webpack");
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var basePath = __dirname;
module.exports = {
context: path.join(basePath, "src"),
resolve: {
// .js is required for react imports.
// .tsx is for our app entry point.
// .ts is optional, in case you will be importing any regular ts files.
extensions: ['.js', '.ts', '.tsx']
},
entry: {
app: './index.tsx',
styles: [
'./css/site.css',
],
vendor: [
"core-js",
"lc-form-validation",
"react",
"react-dom",
"react-redux",
"redux",
"redux-thunk",
"toastr",
],
vendorStyles: [
'../node_modules/bootstrap/dist/css/bootstrap.css',
'../node_modules/toastr/build/toastr.css',
]
},
output: {
path: path.join(basePath, "dist"),
filename: '[name].js'
},
//https://webpack.github.io/docs/webpack-dev-server.html#webpack-dev-server-cli
devServer: {
contentBase: './dist', //Content base
inline: true, //Enable watch and live reload
host: 'localhost',
stats: 'errors-only',
port: 8080
},
// http://webpack.github.io/docs/configuration.html#devtool
devtool: 'source-map',
module: {
rules: [
{
test: /\.tsx?$/,
exclude: /node_modules/,
use: {
loader: 'awesome-typescript-loader',
options: {
useBabel: true
}
}
},
//Note: Doesn't exclude node_modules to load bootstrap
{
test: /\.css$/,
loader: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: 'css-loader'
})
},
//Loading glyphicons => https://github.com/gowravshekar/bootstrap-webpack
//Using here url-loader and file-loader
{ test: /\.(woff|woff2)(\?v=\d+\.\d+\.\d+)?$/, loader: "url-loader?limit=10000&mimetype=application/font-woff" },
{ test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: "url-loader?limit=10000&mimetype=application/octet-stream" },
{ test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: "file-loader" },
{ test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: "url-loader?limit=10000&mimetype=image/svg+xml" }
]
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
}),
//Generate index.html in /dist => https://github.com/ampedandwired/html-webpack-plugin
new HtmlWebpackPlugin({
filename: 'index.html', //Name of file in ./dist/
template: 'index.html' //Name of template in ./src
}),
//Generate bundle.css => https://github.com/webpack/extract-text-webpack-plugin
new ExtractTextPlugin('[name].css'),
]
}
|
module.exports = {
name: "dns",
ns: "pkgcloud",
title: "Dns",
description: "The pkgcloud.dns service is designed to make it easy to manage DNS zones and records on various infrastructure providers.",
phrases: {
active: "Creating DNS service"
},
ports: {
input: {
credentials: {
title: "Credentials",
type: "object",
required: true
}
},
output: {
client: {
type: "object"
}
}
},
dependencies: {
npm: {
pkgcloud: require('pkgcloud')
}
},
fn: function dns(input, $, output, state, done, cb, on, pkgcloud) {
var r = function() {
output = {
client: $.create(pkgcloud.dns.createClient($.credentials))
}
}.call(this);
return {
output: output,
state: state,
on: on,
return: r
};
}
} |
function UserGenderBlock(options) {
this.graph = options.graph;
this.tab = options.tab;
this.list = options.list;
this.init();
}
UserGenderBlock.prototype = {
init: function() {
if(jQuery(this.graph.id).length > 0) {
this.generateChart();
}
if(jQuery(this.list.id).length > 0) {
this.generateSparklink(this);
}
},
generateSparklink: function(obj) {
var sparkline_user_gender = null;
jQuery('.'+this.tab.id).on('shown.bs.tab', function(e){
if(sparkline_user_gender === null) {
sparkline_user_gender = jQuery(obj.list.id).sparkline('html', {type: 'pie', height: '20px', width: '20px', sliceColors: [obj.list.dataGender.color, obj.list.dataTotal.color]});
}
});
},
generateChart: function() {
var user_gender_chart = c3.generate({
bindto: this.graph.id,
data: {
json: this.graph.data,
type : 'pie',
colors: {
'unknown': this.graph.colors.unknown,
'male': this.graph.colors.male,
'female': this.graph.colors.female
},
},
});
}
}
|
CT.map.Shape = CT.Class({
CLASSNAME: "CT.map.Shape",
_gclass: function() {
var cname = this.CLASSNAME.split(".")[2];
return {
Shape: "Polygon",
Line: "Polyline"
}[cname] || cname;
},
add: function(map) {
this.opts.map = map;
this.shape.setMap(map);
},
remove: function() {
this.opts.map = null;
this.shape.setMap(null);
},
init: function(opts) {
this.opts = opts;
this.shape = new google.maps[this._gclass()](opts);
if (opts.map)
this.add(opts.map);
}
});
CT.map.Circle = CT.Class({
CLASSNAME: "CT.map.Circle"
}, CT.map.Shape);
CT.map.Rectangle = CT.Class({
CLASSNAME: "CT.map.Rectangle"
}, CT.map.Shape);
CT.map.Line = CT.Class({
CLASSNAME: "CT.map.Line"
}, CT.map.Shape); |
import { SepCon } from '../../src/index';
export default SepCon.createComponent({
id: 'described-button',
}, {
state: {
props: {
local: {label: 'Button', description: 'Button\'s Description', isActive: false}
},
methods: {
local: {
onclick(next, num) {
num += 5;
console.log('described-button clicked');
next(num);
},
}
},
routes: [
{
match: /^\s*$/,
handler: function () {
console.log('THIS IS HOME PAGE');
}
}
]
},
view: {
events: [
{event: 'click', selector: '.clickable', callback: 'handleClick'}
],
lifecycle: {
render() {
let classes = ['button', 'raised', 'clickable'];
if (this.props.isActive) {
classes.push('is-active');
}
return `<div class="sepcon sepcon-element">
<div class="${classes.join(' ')}">
<h5>${this.props.label}</h5>
</div>
${this.children.length ? this.children.map(el => el.outerHTML).join('') : ''}
</div>`;
}
},
handleClick(e) {
e.preventDefault();
e.stopPropagation();
this.methods.onclick(123);
}
}
}); |
var path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var CopyWebpackPlugin = require('copy-webpack-plugin');
module.exports = {
entry: {
app: './src/app/index.ts'
},
output: {
filename: '[hash:6].bundle.js',
path: path.resolve(__dirname, 'dist')
},
module: {
rules: [
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: 'css-loader'
})
},
{
test: /\.ts?$/,
loader: 'ts-loader',
exclude: /node_modules/,
},
{
test: /\.(jpe?g|png|gif|svg)$/i,
use: [
'url-loader?limit=10000',
'img-loader'
]
}
]
},
resolve: {
extensions: [".ts", ".js"]
},
plugins: [
new CopyWebpackPlugin([
{ from: 'src/tips/tips.json' },
{ from: 'src/templates/index.html', to: 'index.html' },
{ from: 'src/img/favicon.ico', to: 'img/favicon.ico' }
]),
new ExtractTextPlugin('[hash:6].main.css'),
new HtmlWebpackPlugin({
title: 'webview1',
template: 'src/templates/webview1.html',
filename: 'webview1.html'
}),
new HtmlWebpackPlugin({
title: 'webview2',
template: 'src/templates/webview2.html',
filename: 'webview2.html'
}),
],
devtool: 'source-map',
devServer: {
inline: true,
contentBase: path.join(__dirname, 'dist'),
compress: true,
port: 9000
}
}; |
(function () {
'use strict';
var module = angular.module('fim.base');
module.controller('InspectorPluginInspectModalController', function (items, $modalInstance, $scope, $sce, $timeout, $state) {
$scope.items = items;
var order = items.order ? items.order.split(',') : [];
$scope.close = function () {
$modalInstance.close($scope.items);
}
$scope.goToAccount = function (id_rs) {
$timeout(function () {
$state.transitionTo('accounts', {id_rs:id_rs, action:'show'}, {reload:true});
});
$scope.close();
}
function renderTable(object) {
var s = ['<table class="table table-striped table-condensed table-hover"><tbody>'];
var sorted = []
angular.forEach(object, function (value, key) {
sorted.push({key: key, value: value});
});
if (order.length > 0) {
sorted.sort(function (a, b) {
a = order.indexOf(a.key);
b = order.indexOf(b.key);
a = a == -1 ? Number.MAX_VALUE : a;
b = b == -1 ? Number.MAX_VALUE : b;
if (a < b) { return -1; }
if (a > b) { return 1; }
return 0;
});
}
angular.forEach(sorted, function (tuple) {
renderObject(s, 0, tuple.key, tuple.value, items.translator||{});
});
s.push('</tbody></table>');
console.log(s.join(''));
return s.join('');
}
/* @returns Array [label, value] */
function translate(_translator, key, value) {
return _translator && _translator[key] ? _translator[key].call(null, value) : [key, value];
}
function capitalize(s) {
return (typeof s == 'string') ? (s[0].toUpperCase() + s.slice(1)) : s;
}
function renderRow(s, indent, name, value, translator) {
var tuple = translate(translator, name, value);
s.push('<tr>');
s.push('<td style="padding-left:',indent,'px;"><strong>',capitalize(tuple[0]),'</strong></td>');
s.push('<td>',tuple[1],'</td>');
s.push('</tr>');
}
function renderObject(s, indent, name, object, translator) {
var t = typeof object;
if (t=='number'||t=='string'||t=='function'||t=='boolean'||object==null||object==undefined) {
renderRow(s, indent, name, object, translator);
}
else {
renderRow(s, indent, name, '');
angular.forEach(object, function (value, key) {
renderObject(s, indent+10, key, value, translator[name]||{});
});
}
}
$scope.tableHTML = $sce.trustAsHtml(renderTable(items.object));
});
})();
|
function components(input) {
let system = new Map();
for (let line of input) {
let [name, comp, subcomp] = line.split(' | ');
if (!system.get(name)) {
system.set(name, new Map());
}
if (!system.get(name).get(comp)) {
system.get(name).set(comp, []);
}
system.get(name).get(comp).push(subcomp);
}
let systemSorted = Array.from(system.keys())
.sort((s1, s2) => sortSystem(s1, s2));
for (let name of systemSorted) {
console.log(name);
let componentSorted = Array.from(system.get(name).keys())
.sort((c1, c2) => sortComponents(name, c1, c2));
for (let component of componentSorted) {
console.log(`|||${component}`);
system.get(name).get(component)
.forEach(sc => console.log(`||||||${sc}`));
}
}
function sortSystem(s1, s2) {
if(system.get(s1).size !== system.get(s2).size) {
return system.get(s2).size - system.get(s1).size;
} else {
return s1.toLowerCase().localeCompare(s2.toLowerCase());
}
}
function sortComponents(name, c1, c2) {
return system.get(name).get(c2).length -
system.get(name).get(c1).length;
}
}
components([
'SULS | Main Site | Home Page',
'SULS | Main Site | Login Page',
'SULS | Main Site | Register Page',
'SULS | Judge Site | Login Page',
'SULS | Judge Site | Submittion Page',
'Lambda | CoreA | A23',
'SULS | Digital Site | Login Page',
'Lambda | CoreB | B24',
'Lambda | CoreA | A24',
'Lambda | CoreA | A25',
'Lambda | CoreC | C4',
'Indice | Session | Default Storage',
'Indice | Session | Default Security'
]); |
import React from "react";
import { connect } from "react-redux";
import { addUser } from "../actions";
let AddUser = ({dispatch}) => {
let input;
return (
<div>
<form
onSubmit={e => {
e.preventDefault();
if (!input.value.trim) {
return;
}
dispatch(addUser(input.value));
input.value = "";
}} >
<input ref={node => {
input = node;
}} />
<button type="submit">
Add User
</button>
</form>
</div>
)
};
AddUser = connect()(AddUser);
export default AddUser;
|
'use strict';
module.exports = [
// parses unwrapped keys, containing backslashes
'{"a?":"\\""}',
'{"a?":"\'"}',
'{"a?":","}',
'{"a?":":"}',
// parses unwrapped keys, containing minus signs
'{"b-c":"b:"}',
'{"b-c":":c"}',
'{"b-c":"b,"}',
'{"b-c":",c"}',
// parses multiple unwrapped keys, containing backslashes and minus signs, with different amounts of spacing
'{"a?":"a\\"","b-c":"b:c"}',
'{"a?":"a\'","b-c":"b:c"}',
'{"a?":"\\"a","b-c":"b,c"}',
'{"a?":",:","b-c":":,"}',
// parses unwrapped keys, containing tildes, with different amounts of spacing
'{"d~e":"d\\"~\\""}',
'{"d~e":"d\'~\'"}',
'{"d~e":"\\"~\\"e"}',
'{"d~e":"d\\"~\\"e"}',
// parses multiple unwrapped keys, containing backslashes, minus signs and tildes, with different amounts of spacing
'{"a?":"\\",","b-c":",\\"","d~e":",\\":"}',
'{"a?":"\',","b-c":",\'","d~e":",\':"}',
'{"a?":"\\":","b-c":":\\"","d~e":":\\","}',
'{"a?":"\':","b-c":":\'","d~e":":\',"}',
// parses unwrapped keys, containing plus signs, with unwrapped values
'{"f+g":true}',
'{"f+g":0}',
'{"f+g":66}',
'{"f+g":0.66}',
// parses multiple wrapped and unwrapped keys, containing colons, backslashes and minus signs, with unwrapped values
// 1st in the list
'{"f:g":true,"a?":"\\",","b-c":",\\""}',
'{"f:g":0,"a?":"\',","b-c":",\'"}',
'{"f:g":66,"a?":"\\":","b-c":":\\""}',
'{"f:g":0.66,"a?":"\':","b-c":":\'"}',
// parses multiple wrapped and unwrapped keys, containing backslashes, colons and minus signs, with unwrapped values
// midway in the list
'{"a?":"\\",","f:g":true,"b-c":",\\""}',
'{"a?":"\',","f:g":0,"b-c":",\'"}',
'{"a?":"\\":","f:g":66,"b-c":":\\""}',
'{"a?":"\':","f:g":0.66,"b-c":":\'"}',
// parses multiple wrapped and unwrapped keys, containing backslashes, colons and minus signs, with unwrapped values
// last in the list
'{"a?":"\\",","b-c":",\\"","f:g":true}',
'{"a?":"\',","b-c":",\'","f:g":0}',
'{"a?":"\\":","b-c":":\\"","f:g":66}',
'{"a?":"\':","b-c":":\'","f:g":0.66}'
];
|
import request from 'superagent';
function extract(error) {
if (error.response && error.response.body) {
return error.response.body;
} else if (error.response) {
return error.response;
} else { // eslint-disable-line no-else-return
return error;
}
}
export default function postWebReport({
token,
baseUrl,
url,
branch,
report,
result,
}) {
return new Promise((resolve, reject) =>
request
.post(`${baseUrl.replace(/\/+$/, '')}${url}`)
.accept('json')
.send({
token,
branch,
report,
result,
})
.end(error => error
? reject(extract(error))
: resolve(result)));
}
|
import React from 'react';
import { Row , Col , Breadcrumb , Icon , Pagination } from 'antd';
import blogService from '../../service/blogService';
import moment from 'moment';
import '../../../../style/markdown.less'
var content=React.createClass({
getInitialState:function(){
return {
typeName:"",
list:null,
typeId:this.props.params.typeId,
userId:this.props.params.userId,
pageSize:10,
pageNum:1,
total:0
}
},
componentWillMount:function(){
let typeId=this.state.typeId;
let userId=this.state.userId;
this.getList(this,userId,typeId);
},
componentWillReceiveProps:function(object ,nextProps){
let typeId=object.params.typeId;
let userId=object.params.userId;
this.setState({
userId:userId,
typeId:typeId
})
this.getList(this,userId,typeId);
},
changePage(page){
var ctx=this;
this.setState({
pageNum:page
},function(){
ctx.getList(ctx,ctx.state.userId,ctx.state.typeId)
})
},
getList:(ctx,userId,typeId)=>{
//ctx:需要把作用域传过来设置state
var menuId=-1;
blogService.getList({
userId:userId,
categoryId:typeId,
menuId:menuId,
pageNum:ctx.state.pageNum,
pageSize:ctx.state.pageSize
}).then((res)=>{
if(res.status===0){
ctx.setState({
typeName:res.data.categoryName,
list:res.data.articalList,
total:res.data.total
})
}else{
ctx.setState({
typeName:res.data.categoryName,
list:[],
total:0
})
}
})
},
render:function(){
let blogList;
if(this.state.list===null){
blogList=<div className="blogList">loading</div>
}
else if(this.state.list.length===0){
blogList= <div className="blogList">暂无文章</div>
}
else{
blogList=(<div className="blogList">
{
this.state.list.map((item)=>{
return <div className="blogItem clearfix" key={"artical"+item.id}>
<h2>{item.articalName}</h2>
<p>更新时间:{moment(item.updataAt).format("YYYY-MM-DD HH:mm:ss")}</p>
<div dangerouslySetInnerHTML={{__html:item.articalContent}}></div>
<a href={`#/blog/${this.state.userId}/${this.state.typeId}/${item.id}`}>
<Icon type="eye-o" />
({item.reading})</a>
</div>
})
}
<Pagination total={this.state.total} onChange={this.changePage}/>
</div>)
}
return <section className="">
<div className="blogBreadcrumb">
<Breadcrumb>
<Breadcrumb.Item>
{this.state.typeName}
</Breadcrumb.Item>
</Breadcrumb>
</div>
{blogList}
</section>
}
})
export default content; |
/**
* Enables filtration delay for keeping the browser more responsive while
* searching for a longer keyword.
*
* This can be particularly useful when working with server-side processing,
* where you wouldn't typically want an Ajax request to be made with every key
* press the user makes when searching the table.
*
* @name fnSetFilteringDelay
* @summary Add a key debouce delay to the global filtering input of a table
* @author [Zygimantas Berziunas](http://www.zygimantas.com/),
* [Allan Jardine](http://www.sprymedia.co.uk/) and _vex_
*
* @example
* $(document).ready(function() {
* $('.dataTable').dataTable().fnSetFilteringDelay();
* } );
*/
jQuery.fn.dataTableExt.oApi.fnSetFilteringDelay = function (oSettings, iDelay) {
var _that = this;
if (iDelay === undefined) {
iDelay = 250;
}
this.each(function (i) {
$.fn.dataTableExt.iApiIndex = i;
var
$this = this,
oTimerId = null,
sPreviousSearch = null,
anControl = $('input', _that.fnSettings().aanFeatures.f);
anControl.unbind('keyup search input').bind('keyup search input', function () {
var $$this = $this;
if (sPreviousSearch === null || sPreviousSearch != anControl.val()) {
window.clearTimeout(oTimerId);
sPreviousSearch = anControl.val();
oTimerId = window.setTimeout(function () {
$.fn.dataTableExt.iApiIndex = i;
_that.fnFilter(anControl.val());
}, iDelay);
}
});
return this;
});
return this;
};
|
/*
* `config` module
* ===============
*
* The game instance settings.
*/
// Import created game scenes.
import * as scenes from '@/scenes';
// HINT: Import plugins, custom or trusted third-party ones, here.
// import ExamplePlugin from 'example-plugin';
// import ExampleScenePlugin from '@/plugins/example-scene-plugin';
/**
* Game canvas width.
*/
export const width = 640;
/**
* Game canvas height.
*/
export const height = 360;
/**
* Adjust zoom factor.
*/
export const zoom = 1;
/**
* Adjust pixel density of game graphics.
*/
export const resolution = 1;
/**
* Choose a rendering method.
*
* Available options are:
*
* - `WEBGL`: Use WebGL rendering;
* - `CANVAS`: Use 'context2D' API rendering method;
* - `AUTO`: Phaser will choose, based on device capabilities, the best
* rendering method to be used.
*/
export const type = Phaser.AUTO;
/**
* Whether to disable antialiasing or not. Great for pixel art.
*/
export const pixelArt = false;
/**
* Whether to enable canvas transparency or not.
*/
export const transparent = false;
/**
* Apply some style to the canvas element.
*/
export const canvasStyle = 'display: block; margin: 0 auto;';
/**
* Define a default a background color.
*/
export const backgroundColor = '#bfcc00';
/**
* Configure physics engines global parameters.
*
* Available systems are:
*
* - `arcade`: Phaser Arcade Physics 2;
* - `matter`: Liam Brummitt's (@liabru) Matter.js;
* - `impact`: ImpactJS Physics Engine.
*/
export const physics = {
/**
* Phaser Arcade Physics 2 parameters.
*
* This engine becomes available under a `physics` property on game scenes.
*/
// arcade: {
// },
/**
* Matter.js parameters.
*
* This engine becomes available under a `matter` property on game scenes.
*/
// matter: {
// },
/**
* Impact Physics Engine parameters.
*
* This engine becomes available under a `impact` property on game scenes.
*/
// impact: {
// },
/**
* Enable a physics engine by default on all game scenes.
*/
default: false
};
/**
* Global parameters of the asset manager.
*/
export const loader = {
// HINT: Put all your game assets in the `app/static/assets/` directory.
path: 'assets/'
};
/**
* Declare custom Phaser plugins.
*
* There are two kinds of plugins: Global Plugins and Scene Plugins.
*
* Global plugins are instantiated once per game and persist throughout the
* whole session.
*
* Scene plugins are instantiated with each scene and are stored in the
* `Systems` class, rather than the global plugin manager. Scene plugins are
* tied to the scene life cycle.
*/
export const plugins = {
global: [
// {
// // An identifier to associate this plugin instance within Phaser's
// // plugin manager cache. It must be unique to avoid naming clashes
// // with other plugins.
// key: 'ExamplePlugin',
//
// // The imported plugin class.
// plugin: ExamplePlugin,
//
// // The property name your plugin will be aliased to. This plugin
// // will be exposed as a property of your scene context, for example,
// // `this.myPlugin`.
// mapping: 'myPlugin',
//
// // Whether to start up or not this plugin on game's initialization.
// // If omitted or set to `false`, you must request the plugin manager
// // to start up the plugin on a game scene using the method
// // `this.plugins.start('<key>')`.
// start: true
// },
],
scene: [
// {
// // An identifier for reference in the scene `Systems` class. It must
// // be unique to avoid naming clashes with other plugins.
// key: 'ExampleScenePlugin',
//
// // The imported plugin class.
// plugin: ExampleScenePlugin,
//
// // The property name your plugin will be aliased to. This plugin
// // will be exposed as a property of your scene context, for example,
// // `this.myPlugin`.
// mapping: 'myPlugin'
// }
]
};
/**
* Export the game title, version and Web address, as defined in the
* project package metadata file (`package.json`).
*
* These properties can be accessed in the game configuration object
* (`scene.sys.game.config`), under the keys `gameTitle`, `gameVersion` and
* `gameURL`, respectively.
*/
export {title, version, url} from '@/../../package.json';
/**
* Export created game scenes.
*/
export const scene = Object.values(scenes);
|
//>>excludeStart("exclude", pragmas.exclude);
define([ "shoestring" ], function(){
//>>excludeEnd("exclude");
shoestring.enUS = {
errors: {
"prefix": "Shoestring does not support",
"ajax-url-query": "data with urls that have existing query params",
"click": "the click method. Try using trigger( 'click' ) instead.",
"css-get" : "getting computed attributes from the DOM.",
"data-attr-alias": "the data method aliased to `data-` DOM attributes.",
"has-class" : "the hasClass method. Try using .is( '.klassname' ) instead.",
"html-function" : "passing a function into .html. Try generating the html you're passing in an outside function",
"live-delegate" : "the .live or .delegate methods. Use .bind or .on instead.",
"map": "the map method. Try using .each to make a new object.",
"next-selector" : "passing selectors into .next, try .next().filter( selector )",
"off-delegate" : ".off( events, selector, handler ) or .off( events, selector ). Use .off( eventName, callback ) instead.",
"next-until" : "the .nextUntil method. Use .next in a loop until you reach the selector, don't include the selector",
"on-delegate" : "the .on method with three or more arguments. Using .on( eventName, callback ) instead.",
"outer-width": "the outerWidth method. Try combining .width() with .css for padding-left, padding-right, and the border of the left and right side.",
"prev-selector" : "passing selectors into .prev, try .prev().filter( selector )",
"prevall-selector" : "passing selectors into .prevAll, try .prevAll().filter( selector )",
"queryselector": "all CSS selectors on querySelector (varies per browser support). Specifically, this failed: ",
"siblings-selector": "passing selector into siblings not supported, try .siblings().find( ... )",
"show-hide": "the show or hide methods. Use display: block (or whatever you'd like it to be) or none instead",
"text-setter": "setting text via the .text method.",
"toggle-class" : "the toggleClass method. Try using addClass or removeClass instead.",
"trim": "the trim method. Try using replace(/^\\s+|\\s+$/g, ''), or just String.prototype.trim if you don't need to support IE8"
}
};
shoestring.error = function( id, str ) {
var errors = shoestring.enUS.errors;
throw new Error( errors.prefix + " " + errors[id] + ( str ? " " + str : "" ) );
};
//>>excludeStart("exclude", pragmas.exclude);
});
//>>excludeEnd("exclude");
|
/**
* # authActions-test.js
*
* This test is for authActions
*
*/
'use strict';
jest.autoMockOff();
/**
* ## Mocks
*
* We don't want to use the devices storage, nor actually call Parse.com
*/
jest.mock('../../../lib/AppAuthToken');
jest.mock('../../../lib/BackendFactory');
/**
* ## Mock Store
*
* The ```mockStore``` confirms the all the actions are dispatched and
* in the correct order
*
*/
var mockStore = require('../../mocks/Store').default;
/**
* ## Class under test
*
*/
var actions = require('../authActions');
/**
* ## Imports
*
* actions under test
*/
const {
SESSION_TOKEN_REQUEST,
SESSION_TOKEN_SUCCESS,
SESSION_TOKEN_FAILURE,
LOGIN_STATE_LOGOUT,
LOGIN_STATE_REGISTER,
LOGIN_STATE_LOGIN,
LOGIN_STATE_FORGOT_PASSWORD,
LOGOUT_REQUEST,
LOGOUT_SUCCESS,
LOGOUT_FAILURE,
LOGIN_REQUEST,
LOGIN_SUCCESS,
LOGIN_FAILURE,
ON_AUTH_FORM_FIELD_CHANGE,
SIGNUP_REQUEST,
SIGNUP_SUCCESS,
SIGNUP_FAILURE,
RESET_PASSWORD_REQUEST,
RESET_PASSWORD_SUCCESS,
RESET_PASSWORD_FAILURE
} = require('../../../lib/constants').default;
/**
* ## Tests
*
* authActions
*/
describe('authActions', () => {
/**
* ### simple tests that prove the actions have the specific type
*/
it('should set logoutState', () => {
expect(actions.logoutState()).toEqual({type: LOGIN_STATE_LOGOUT });
});
it('should set registerState', () => {
expect(actions.registerState()).toEqual({type: LOGIN_STATE_REGISTER });
});
it('should set loginState', () => {
expect(actions.loginState()).toEqual({type: LOGIN_STATE_LOGIN});
});
it('should set forgotPasswordState', () => {
expect(actions.forgotPasswordState()).toEqual({type: LOGIN_STATE_FORGOT_PASSWORD});
});
it('should set logoutRequest', () => {
expect(actions.logoutRequest()).toEqual({type: LOGOUT_REQUEST});
});
it('should set logoutSuccess', () => {
expect(actions.logoutSuccess()).toEqual({type: LOGOUT_SUCCESS});
});
it('should set logoutFailure', () => {
let error = {error: 'test error'};
expect(actions.logoutFailure(error)).toEqual({type:
LOGOUT_FAILURE,
payload: error});
});
it('should set signupRequest', () => {
expect(actions.signupRequest()).toEqual({type: SIGNUP_REQUEST});
});
it('should set signupSuccess', () => {
expect(actions.signupSuccess()).toEqual({type: SIGNUP_SUCCESS});
});
it('should set sessionTokenRequest', () => {
expect(actions.sessionTokenRequest()).toEqual({type: SESSION_TOKEN_REQUEST});
});
it('should set sessionTokenRequestSuccess', () => {
let token = {token: 'thisisthetoken'};
expect(actions.sessionTokenRequestSuccess(token)).toEqual({
type:SESSION_TOKEN_SUCCESS,payload:token});
});
it('should set sessionTokenRequestFailure', () => {
let error = {error: 'thisistheerror'};
expect(actions.sessionTokenRequestFailure(error)).toEqual({
type: SESSION_TOKEN_FAILURE,payload: error });
});
it('should set signupFailure', () => {
let error = {error: 'thisistheerror'};
expect(actions.signupFailure(error)).toEqual({type:
SIGNUP_FAILURE, payload:error});
});
it('should set loginRequest', () => {
expect(actions.loginRequest()).toEqual({type: LOGIN_REQUEST});
});
it('should set loginSuccess', () => {
expect(actions.loginSuccess()).toEqual({type: LOGIN_SUCCESS});
});
it('should set loginFailure', () => {
let error = {error: 'thisistheerror'};
expect(actions.loginFailure(error)).toEqual({type: LOGIN_FAILURE,
payload: error});
});
it('should set resetPasswordRequest', () => {
expect(actions.resetPasswordRequest()).toEqual({type: RESET_PASSWORD_REQUEST});
});
it('should set resetPasswordSuccess', () => {
expect(actions.resetPasswordSuccess()).toEqual({type: RESET_PASSWORD_SUCCESS});
});
it('should set resetPasswordFailure', () => {
let error = {error: 'thisistheerror'};
expect(actions.resetPasswordFailure(error)).toEqual({type:
RESET_PASSWORD_FAILURE,
payload: error});
});
it('should set onAuthFormFieldChange', () => {
let field = 'field';
let value = 'value';
expect(actions.onAuthFormFieldChange(field, value)).toEqual({
type: ON_AUTH_FORM_FIELD_CHANGE,
payload: {field: field, value: value}
});
});
/**
* ### async tests
*
* the following tests describe the actions that should be
* dispatched the function is invoked
*
* *Note*: these tests are run with ```pit``` because they are async
*
*/
pit('should logout', () => {
const expectedActions = [
{type: LOGOUT_REQUEST},
{type: LOGIN_STATE_REGISTER},
{type: LOGOUT_SUCCESS},
{type: SESSION_TOKEN_REQUEST},
{type: SESSION_TOKEN_SUCCESS}
];
const store = mockStore({}, expectedActions);
return store.dispatch(actions.logout());
});
pit('should login', () => {
const expectedActions = [
{type: LOGIN_REQUEST},
{type: LOGIN_STATE_LOGOUT},
{type: LOGIN_SUCCESS}
];
const store = mockStore({}, expectedActions);
return store.dispatch(actions.login('foo','bar'));
});
pit('should getSessionToken', () => {
const expectedActions = [
{type: SESSION_TOKEN_REQUEST},
{type: LOGIN_STATE_LOGOUT},
{type: SESSION_TOKEN_SUCCESS}
];
const store = mockStore({}, expectedActions);
return store.dispatch(actions.getSessionToken());
});
pit('should signup', () => {
const expectedActions = [
{type: SIGNUP_REQUEST},
{type: LOGIN_STATE_LOGOUT},
{type: SIGNUP_SUCCESS}
];
const store = mockStore({}, expectedActions);
return store.dispatch(actions.signup('user','email','password'));
});
pit('should resetPassword', () => {
const expectedActions = [
{type: RESET_PASSWORD_REQUEST},
{type: LOGIN_STATE_LOGIN},
{type: RESET_PASSWORD_SUCCESS}
];
const store = mockStore({}, expectedActions);
return store.dispatch(actions.resetPassword('email'));
});
pit('should deleteSessionToken', () => {
const expectedActions = [
{type: SESSION_TOKEN_REQUEST},
{type: SESSION_TOKEN_SUCCESS}
];
const store = mockStore({}, expectedActions);
return store.dispatch(actions.deleteSessionToken());
});
});
|
import React from 'react'
import { TweenMax } from 'gsap'
const MetroHoc = Component =>
class MetroContainer extends React.Component {
static defaultProps = {
wrapperType: 'div'
}
// longest animation in sequence
getLongestAnimationInSequence(io) {
return Math.max(
...this.props.sequence.map(
obj => obj.animation[io].time + obj.animation[io].delay
)
)
}
isThisTheLongestAnimation(animation, io) {
const highestDuration = this.getLongestAnimationInSequence(io)
const duration = animation[io].time + animation[io].delay
return duration >= highestDuration
}
applySequenceEndIfLastInSequence(animationIndex, sequence, io) {
const highestDuration = this.getLongestAnimationInSequence(io)
let isLastInSequence = true
sequence.forEach((animationInSequence, i) => {
const duration =
animationInSequence.animation[io].time +
animationInSequence.animation[io].delay
if (duration === highestDuration) {
if (i > animationIndex) {
isLastInSequence = false
}
}
})
return isLastInSequence
}
// on will enter
componentWillEnter(callback) {
const el = this.container
this.props.sequence[this.props.itemIndex].animating = true
TweenMax.fromTo(
el,
this.props.animation.in.time,
this.props.animation.willEnter.from,
{
...this.props.animation.willEnter.to,
delay: this.props.animation.in.delay,
onComplete: () => {
if (
this.isThisTheLongestAnimation(this.props.animation, 'in') &&
this.applySequenceEndIfLastInSequence(
this.props.index,
this.props.sequence,
'in'
)
) {
this.props.onMount && this.props.onMount()
}
this.props.sequence[this.props.itemIndex].animating = false
callback()
}
}
)
}
// on will leave
componentWillLeave(callback) {
const el = this.container
const fullSequenceDuration = this.getLongestAnimationInSequence('out')
const leftOver =
fullSequenceDuration -
(this.props.animation.out.time + this.props.animation.out.delay)
this.props.sequence[this.props.itemIndex].animating = true
TweenMax.fromTo(
el,
this.props.animation.out.time,
this.props.animation.willLeave.from,
{
...this.props.animation.willLeave.to,
delay: this.props.animation.out.delay,
onComplete: () => {
setTimeout(() => {
if (
this.isThisTheLongestAnimation(this.props.animation, 'out') &&
this.applySequenceEndIfLastInSequence(
this.props.index,
this.props.sequence,
'out'
)
) {
this.props.onUnmount && this.props.onUnmount()
}
this.props.sequence[this.props.itemIndex].animating = false
callback()
}, leftOver * 1000)
}
}
)
}
/* eslint-disable */
render() {
return (
<this.props.wrapperType ref={c => (this.container = c)}>
<Component {...this.props} />
</this.props.wrapperType>
)
}
}
export default MetroHoc
|
(function() {
'use strict';
angular
.module('scientificweekApp')
.controller('PersonDetailController', PersonDetailController);
PersonDetailController.$inject = ['$scope', '$rootScope', '$stateParams', 'previousState', 'entity', 'Person', 'User'];
function PersonDetailController($scope, $rootScope, $stateParams, previousState, entity, Person, User) {
var vm = this;
vm.person = entity;
vm.previousState = previousState.name;
var unsubscribe = $rootScope.$on('scientificweekApp:personUpdate', function(event, result) {
vm.person = result;
});
$scope.$on('$destroy', unsubscribe);
}
})();
|
version https://git-lfs.github.com/spec/v1
oid sha256:395885129d8af1e87cd16e921d840ab8d11ec632c46d15a0144192bb27062cde
size 8317
|
version https://git-lfs.github.com/spec/v1
oid sha256:7d71635b7ede773ce81bee8e11204d8ed5d124dc2e208d8a2c175804744acfce
size 29197
|
import React, {PureComponent} from "react";
export class CompositionSlide extends PureComponent {
render() {
return (
<div>
<h1>
React<br />
Component<br />
Composition
</h1>
</div>
)
}
}
|
/**
* VLANG linter worker.
*
* @copyright 2011, Ajax.org B.V.
* @license GPLv3 <http://www.gnu.org/licenses/gpl.txt>
*/
define("ext/cloud9-vlang/cloud9-vlang-worker", ["require", "exports", "module"], function(require, exports, module) {
var baseLanguageHandler = require("ext/linereport/linereport_base");
var handler = module.exports = Object.create(baseLanguageHandler);
handler.disabled = false;
handler.handlesLanguage = function(language) {
return language === 'd';
};
handler.init = function(callback) {
handler.initReporter("rdmd --version", "exit 1 # can't really install vlang", function(err, output) {
if (err) {
console.log("Unable to lint VLANG\n" + output);
handler.disabled = true;
}
callback();
});
};
handler.analyze = function(doc, fullAst, callback) {
if (handler.disabled)
return callback();
handler.invokeReporter("time rdmd -I/home/vlang/work/vlang/src " + handler.path.replace(/.*\/workspace/, handler.workspaceDir),
this.$postProcess, callback);
};
/**
* Postprocess VLANG output to match the expected format of
* line:column: error message.
*/
handler.$postProcess = function(line) {
return line.replace(/(.*) (in .*? )?on line ([0-9]+)$/, "$3:1: $1/");
};
});
|
define(['joga/bindings/ElementBinding', 'joga/computedProperty'], function (ElementBinding, computedProperty) {
function HTMLImageElementBinding(element, model) {
ElementBinding.call(this, element, model);
}
HTMLImageElementBinding.prototype = new ElementBinding();
HTMLImageElementBinding.prototype.src = function (dataExpression) {
var computed = computedProperty(dataExpression);
this.src.update = function () {
this.element.src = computed.apply(this.model);
}.bind(this);
this.src.update();
computed.subscribe(this.src.update);
};
HTMLImageElementBinding.prototype.alt = function (dataExpression) {
var computed = computedProperty(dataExpression);
this.alt.update = function () {
this.element.alt = computed.apply(this.model);
}.bind(this);
this.alt.update();
computed.subscribe(this.alt.update);
};
return HTMLImageElementBinding;
});
|
/*!
* @author Felix Heck <hi@whoTheHeck.de>
* @version 0.1.2
* @copyright Felix Heck 2016
* @license MIT
*/
;(function() {
'use strict';
angular.module('uxs', [
'ngAnimate'
]);
})();
|
// Generated by CoffeeScript 1.6.3
var define;
if (typeof define !== 'function') {
define = require('amdefine')(module);
}
define(function() {
var Actor;
return Actor = (function() {
function Actor(globals, ui, config) {
var key;
this.ui = ui;
this.actor = true;
for (key in config) {
this[key] = config[key];
}
}
return Actor;
})();
});
|
/**
* Router Reducer
*
* React Native Starter App
* https://github.com/mcnamee/react-native-starter-app
*/
import { ActionConst } from 'react-native-router-flux'
// Set initial state
const initialState = {
scene: {},
}
export default function routerReducer(state = initialState, action) {
switch (action.type) {
// focus action is dispatched when a new screen comes into focus
case ActionConst.FOCUS :
return {
...state,
scene: action.scene,
}
// ...other actions
default :
return state
}
}
|
var compassToDegrees = {
"N": 0, "NNE": 23, "NE": 45, "ENE": 68,
"E": 90, "ESE":113, "SE":135, "SSE":158,
"S":180, "SSW":203, "SW":225, "WSW":248,
"W":270, "WNW":293, "NW":315, "NNW":338
};
function JSWindView(canvasId, imageId, compassDirection) {
this.canvas = document.getElementById(canvasId);
this.context = this.canvas.getContext("2d");
this.img = document.getElementById(imageId);
var direction = this.convertDirection(compassDirection)
if (!direction)
direction = 0;
this.field = new PointField(-10, -10, 530, 530, 1.0, direction);
}
JSWindView.prototype.convertDirection = function(compassDirection) {
var degrees = compassToDegrees[compassDirection];
// change so that the wind blows from the
// specified direction (invert degrees)
if (degrees >= 180) {
degrees = degrees - 180
} else {
degrees = degrees + 180
}
return degrees;
}
JSWindView.prototype.setDirection = function(compassDirection) {
var newDirection = this.convertDirection(compassDirection);
this.field.direction = newDirection
}
JSWindView.prototype.setSpeed = function(speed) {
this.field.setSpeed(speed)
}
JSWindView.prototype.draw = function() {
var c = this.context;
c.save();
c.drawImage(this.img, 0, 0, this.canvas.width, this.canvas.height);
this.field.update();
this.field.draw(c);
c.restore();
}
JSWindView.prototype.start = function() {
window.setInterval(
function(jsww) {
jsww.draw();
}
, 50, this);
}
function Point(x, y) {
this.x = x;
this.y = y;
}
Point.prototype.move = function(speed, angle) {
var quad = Math.floor(angle / 90);
var quadAngle = angle - (quad*90);
var radians = quadAngle * (Math.PI / 180);
var hypotenuse = speed;
var opposite = Math.abs(Math.sin(radians) * hypotenuse)
var adjacent = Math.abs(Math.cos(radians) * hypotenuse)
var dx = 0
var dy = 0
if (quad == 0) {
dy = dy - adjacent
dx = dx + opposite
} else if (quad == 1) {
dy = dy + opposite
dx = dx + adjacent
} else if (quad == 2) {
dy = dy + adjacent
dx = dx - opposite
} else if (quad == 3) {
dy = dy - opposite
dx = dx - adjacent
}
this.x = this.x + dx;
this.y = this.y + dy;
}
function PointField(x, y, width, height, speed, direction) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.direction = direction;
this.speed = (speed/200.0);
this.points = [];
var index = 0;
for (x=0;x<10;x++) {
for (y=0;y<10;y++) {
if (Math.random() > 0.6)
this.points[index++] = new Point(x/10.0,y/10.0)
}
}
}
PointField.prototype.setSpeed = function(speed) {
this.speed = (speed/200.0)
}
PointField.prototype.update = function() {
for (var i in this.points) {
var p = this.points[i]
p.move(this.speed, this.direction);
if (p.x < 0) p.x = 1
if (p.x > 1) p.x = 0
if (p.y < 0) p.y = 1
if (p.y > 1) p.y = 0
}
}
PointField.prototype.draw = function(ctx) {
ctx.save();
for (var i in this.points) {
var p = this.toPixel(this.points[i])
ctx.strokeStyle = "white";
ctx.beginPath();
ctx.moveTo(p.x, p.y);
ctx.lineTo(p.x+1, p.y+1);
ctx.closePath();
ctx.stroke();
ctx.strokeRect(this.x, this.y, this.width, this.height);
}
ctx.restore();
}
PointField.prototype.toPixel = function(p) {
return new Point(p.x * this.width + this.x,
p.y * this.height + this.y)
}
|
import React from 'react';
import PropTypes from 'prop-types';
import Link from 'gatsby-link';
import Helmet from 'react-helmet';
import './index.css';
const Header = () =>
<div
style={{
background: 'rebeccapurple',
marginBottom: '1.45rem'
}}
>
<div
style={{
margin: '0 auto',
maxWidth: 960,
padding: '1.45rem 1.0875rem'
}}
>
<h1 style={{ margin: 0 }}>
<Link
to="/"
style={{
color: 'white',
textDecoration: 'none'
}}
>
Biserica Creștină după Evanghelie
</Link>
</h1>
</div>
</div>;
const TemplateWrapper = ({ children }) =>
<div>
<Helmet
title="Biserica Cluj - Biserica Creștină după Evanghelie"
meta={[
{
name: 'description',
content: 'Situl Bisericii Creștine după Evanghelie, Cluj-Napoca'
},
{
name: 'keywords',
content: 'cluj-napoca, biserica, creștină, evanghelie'
}
]}
/>
<Header />
<div
style={{
margin: '0 auto',
maxWidth: 960,
padding: '0px 1.0875rem 1.45rem',
paddingTop: 0
}}
>
{children()}
</div>
</div>;
TemplateWrapper.propTypes = {
children: PropTypes.func
};
export default TemplateWrapper;
|
var __M; (function(a) { var list = Array(a.length / 2); __M = function(i, es) { var m = list[i], f, e; if (typeof m === "function") { f = m; m = i ? { exports: {} } : module; f(list[i] = m, m.exports); e = m.exports; m.__es = Object(e) !== e || e.constructor === Object ? e : Object.create(e, { "default": { value: e } }); } return es ? m.__es : m.exports; }; for (var i = 0; i < a.length; i += 2) { var j = Math.abs(a[i]); list[j] = a[i + 1]; if (a[i] >= 0) __M(j); } })([
1, function(m) { m.exports = require("fs") },
-6, function(module, exports) {
module.exports = {
"value": 1
}
;
},
2, function(module, exports) {
// pkg2/main.js
exports.data = __M(6, 0);
},
-7, function(module, exports) {
// b.js
module.exports = { b: "b" };
},
-3, function(module, exports) {
// a.js (legacy)
console.log("before b");
var b = __M(7, 0);
exports.a = "a";
console.log(b.b);
},
-4, function(module, exports) {
// pkg1/index.js
},
-5, function(module, exports) {
// deep.js
return;
// comment at end
},
0, function(module, exports) {
'use strict'; // root.js
var FS = __M(1, 1);
var pkg2 = __M(2, 1);
console.log(pkg2.data);
console.log("before a");
var a = __M(3, 0);
console.log(a.a);
require("fs");
__M(4, 0);
__M(5, 0);
}]);
|
// Simple trace advice (params and result) for functions.
// The error handler will be called when advice throws.
export const after =
(f, advice) => {
const callAdvice = squelched(advice)
return (...x) => {
const result = f(...x)
callAdvice(...x, result)
return result
}
}
export const before =
(advice, f) => {
const callAdvice = squelched(advice)
return (...x) => {
callAdvice(...x)
return f(...x)
}
}
export const full =
(before, f, after) => {
const callBefore = squelched(before)
const callAfter = squelched(after)
return (...x) => {
callBefore(x)
const result = f(...x)
callAfter(x, result)
return result
}
}
export const errorHandler =
handle => f => (...x) => {
try {
return f(...x)
}
catch (err) {
handle(err)
}
}
const squelched =
advice => (...x) => {
try { advice(...x) }
catch (err) {}
}
|
module.exports = function (app, pageModel, websiteModel) {
app.post("/api/website/:websiteId/page", createPage);
app.get("/api/website/:websiteId/page", findPagesByWebsite);
app.get("/api/page/:pageId", findPageById);
app.put("/api/page/:pageId", updatePage);
app.delete("/api/page/:pageId", deletePage)
var pages = [
{ "_id": "321", "name": "Post 1", "websiteId": "456", "description": "Lorem" },
{ "_id": "432", "name": "Post 2", "websiteId": "456", "description": "Lorem" },
{ "_id": "543", "name": "Post 3", "websiteId": "456", "description": "Lorem" }
];
function createPage(req, res) {
var websiteId = req.params.websiteId;
var newPage = req.body;
pageModel
.createPageForWebsite(websiteId, newPage)
.then(function(page) {
return websiteModel.addPageToWebsite(page)
})
.then(function(page) {
res.json(page.toObject())
});
}
function findPagesByWebsite(req, res) {
var websiteId = req.params.websiteId;
pageModel
.findAllPagesForWebsite(websiteId)
.then(function(pages) {
res.json(pages);
}, function (error) {
res.sendStatus(500).send(error);
});
}
function findPageById(req, res) {
var pageId = req.params.pageId;
pageModel
.findPageById(pageId)
.then(function(page) {
res.json(page);
}, function (error) {
res.sendStatus(500).send(error);
});
}
function updatePage(req, res) {
var pageId = req.params.pageId;
var page = req.body;
pageModel
.updatePage(pageId, page)
.then(function(page) {
res.json(page);
}, function (error) {
res.sendStatus(500).send(error);
});
}
function deletePage(req, res) {
var pageId = req.params.pageId;
pageModel
.deletePage(pageId)
.then(function (status) {
res.send(status);
}, function (err) {
res.sendStatus(500).send(err);
});
}
};
|
/** Created on May 6, 2014
* author: MrPoxipol
*/
var util = require('util');
// Templates module
var Mustache = require('mustache');
var S = require('string');
// Bot utiles
var ut = require('../nibo/ut');
var debug = require('../nibo/debug');
const COMMAND_NAME = 'ud';
// pattern for util.format()
const TERM_API_URL_PATTERN = 'http://api.urbandictionary.com/v0/define?term=%s';
const RANDOM_API_URL = 'http://api.urbandictionary.com/v0/random';
const DESCRIPTION_MAX_LEN = 250;
exports.meta = {
name: 'urban-dictionary',
commandName: COMMAND_NAME,
description: "Polls UrbanDictionary for given phrase and " +
"returns random definition when the term is not specified. " +
"Usage: ud (<phrase>) -- phrase is optional"
};
function getDefFromJson(data) {
var parsedJson;
try {
parsedJson = JSON.parse(data);
} catch (e) {
debug.debug('JSON parsing error');
return;
}
if (parsedJson.list.length < 1) {
return;
}
var first = parsedJson.list[0];
var term = {};
term.id = first.defid;
term.link = first.permalink;
term.word = first.word;
term.definition = ut.short(first.definition, DESCRIPTION_MAX_LEN);
term.example = ut.short(first.example, DESCRIPTION_MAX_LEN);
term.upvotes = first.thumbs_up;
term.downvotes = first.thumbs_down;
var pattern = '[#{{&id}}|{{&word}}] {{&upvotes}}/{{&downvotes}}' +
' - {{&definition}}|Example: {{&example}} ({{&link}})';
var output = Mustache.render(pattern, term);
// Remove \r\n
output = S(output).collapseWhitespace().s;
return output;
}
function sendResponse(bot, args, message) {
bot.sayToUser(args.channel, args.user.nick, message);
}
function fetchTerm(bot, args, random) {
args.term = encodeURIComponent(args.term);
var url = util.format(TERM_API_URL_PATTERN, args.term);
if (random) {
url = RANDOM_API_URL;
}
try {
ut.http.get(url, function (data) {
var message = getDefFromJson(data);
if (message) {
sendResponse(bot, args, message);
} else {
sendResponse(bot,
args,
util.format(
'[%s] Could not find definition for given phrase.',
decodeURIComponent(args.term)
)
);
}
});
}
catch (e) {
debug.error('HTTP ' + e.message);
sendResponse(bot, args, '[] UrbanDictionary is not available at the moment.');
}
}
exports.onCommand = function (bot, user, channel, command) {
if (command.name !== COMMAND_NAME)
return;
var random = false;
if (command.args.length < 1) {
// Random switch!
random = true;
}
var args = {
user: user,
channel: channel,
term: command.args.join(' '),
};
fetchTerm(bot, args, random);
}; |
var express = require('express');
var app = express();
var path = require('path');
var bodyParser = require('body-parser')
var server = app.listen(3001, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
const jsonAPI = function (req, res) {
res.set('Content-Type', 'application/json');
let accountNumber = req.params.accountNumber || req.body.accountNumber;
let users = {
6759370: {
firstName: "Abhinav",
lastName: "Juneja",
},
6759371: {
firstName: "Neha",
lastName: "Saini",
}
}
let response = `{
"firstName":"${users[accountNumber]?.firstName}",
"lastName":"${users[accountNumber]?.lastName}",
"lastDate":"10102020",
"amountDue":10
}`
if (accountNumber == 6759370 || accountNumber == 6759371) {
res.send(response);
} else {
res.status(404).send('');
}
}
const xmlAPI = function (req, res) {
console.log(req.body, req.body.accountNumber)
res.set('Content-Type', 'text/xml');
let accountNumber = req.params.accountNumber || req.body.accountNumber;
let users = {
6759370: {
firstName: "Abhinav",
lastName: "Juneja",
},
6759371: {
firstName: "Neha",
lastName: "Saini",
}
}
let response = `<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Body>
<setPaymentResponse xmlns="http://soapserver.commsoft.net">
<setPaymentReturn>
<first_name>${users[accountNumber]?.firstName}</first_name>
<last_name>${users[accountNumber]?.lastName}</last_name>
<payment_due>10</payment_due>
</setPaymentReturn>
</setPaymentResponse>
</soapenv:Body>
</soapenv:Envelope>`
if (accountNumber == 6759370 || accountNumber == 6759371) {
res.send(response);
} else {
res.status(404).send('');
}
}
app.use(bodyParser.json({ extended: false }))
app.post('/json-api/:accountNumber', jsonAPI);
app.post('/json-api', jsonAPI);
app.post('/xml-api/:accountNumber', xmlAPI);
app.post('/xml-api', xmlAPI);
|
/*******************************************
file: hello4.js
project: backbone.js tutorial
*******************************************/
(function($){
var Item = Backbone.Model.extend({
defaults: {
part1: 'hello',
part2: 'world'
}
});
var List = Backbone.Collection.extend({
model: Item
});
var ItemView = Backbone.View.extend({
tagName: 'li',
initialize: function(){
_.bindAll(this, 'render');
},
render: function(){
$(this.el).html('<span>'+this.model.get('part1')+' '+this.model.get('part2')+'</span>');
return this;
}
});
var ListView = Backbone.View.extend({
el: $('body'),
events: {
'click button#add': 'addItem'
},
initialize: function(){
_.bindAll(this, 'render', 'addItem', 'appendItem');
this.collection = new List();
this.collection.bind('add', this.appendItem);
this.counter = 0;
this.render();
},
render: function(){
var self = this;
$(this.el).append("<button id='add'>Add list item</button>");
$(this.el).append("<ul></ul>");
_(this.collection.models).each(function(item){
self.appendItem(item);
}, this);
},
addItem: function(){
console.log("click!");
this.counter++;
var item = new Item();
item.set({
part2: item.get('part2') + this.counter
});
this.collection.add(item);
//console.log(item);
},
appendItem: function(item){
console.log("append!");
var itemView = new ItemView({
model: item
});
$('ul', this.el).append(itemView.render().el);
}
});
var ListView = new ListView();
})(jQuery);
|
var WeMo = require('./lib/WeMo');
exports.discover = require('./lib/Discoverer');
exports.createClient = function(config) {
return new WeMo(config);
}; |
class ControlPrinter
{
sendVariable = (name, value) => {
console.log("<ctrl>:" + name + "=" + value);
}
}
export default ControlPrinter; |
common.ready(function(){
/*******************读取配置文件显示任务列表**********************/
var id; //当前操作的任务编号
var configDir = 'configs/qun_config.json';
var config = _.read(configDir); //读取配置文件内容
if(config.result == '' || config.result == 'undefined'){
config = {};
}else{
config = JSON.parse(config.result);
}
//显示列表
list();
/*******************读取配置文件显示任务列表**********************/
/***********************mui初始化*****************************/
mui.init();
//动态加载的数字框初始化
mui('.mui-numbox').numbox();
//初始化单页view
var viewApi = mui('#app').view({
defaultPage: '#setting'
});
mui('.mui-scroll-wrapper').scroll();
var view = viewApi.view;
(function($) {
//处理view的后退与webview后退
var oldBack = $.back;
$.back = function() {
if (viewApi.canBack()) { //如果view可以后退,则执行view的后退
viewApi.back();
} else { //执行webview后退
oldBack();
}
};
//监听页面切换事件方案1,通过view元素监听所有页面切换事件,目前提供pageBeforeShow|pageShow|pageBeforeBack|pageBack四种事件(before事件为动画开始前触发)
//第一个参数为事件名称,第二个参数为事件回调,其中e.detail.page为当前页面的html对象
view.addEventListener('pageBeforeShow', function(e) {
//$.swipeoutClose(elem);
//list();
//页面滚动到顶部
mui.each(mui('.mui-scroll-wrapper'), function(){
mui(this).scroll().scrollTo(0,0);
});
});
view.addEventListener('pageShow', function(e) {
// console.log(e.detail.page.id + ' show');
});
view.addEventListener('pageBeforeBack', function(e) {
// console.log(e.detail.page.id + ' beforeBack');
});
view.addEventListener('pageBack', function(e) {
// console.log(e.detail.page.id + ' back');
});
})(mui);
/***********************mui初始化*****************************/
/***************************jquery的一些操作******************************/
$(function(){
//点击执行任务
$(document).on('click', '.mui-slider-handle', function(){
id = $(this).attr('data');
mui.confirm('您确定要执行这条任务吗?', 'Hi', ['确定', '取消'], function(e) {
if (e.index == 0) { //确认后
task(id);
} else { //否定后
return;
}
});
});
//点击保存任务
$('#qun-save').click(function(){
if(!checkForm( $('#form_edit')[0] ))
return;
var fields = $('#form_edit').serializeArray();
var task = {};
$.each(fields, function(index, field){
task[field.name] = field.value;
});
var l = getConfigNo();
if(id == null)
config[++l] = task;
else
config[id] = task;
var str = JSON.stringify(config);
_.write(configDir, str);
viewApi.back();
});
//点击删除任务
$(document).on('click', '.task_del', function(){
var _this = $(this);
id = _this.attr('data');
mui.confirm('您确定删除任务吗?', 'Hi', ['确定', '取消'], function(e) {
if (e.index == 0) { //确认后
//修改系统配置文件
delete config[id];
_.write(configDir, JSON.stringify(config));
//删除dom节点
_this.parent().parent().remove();
} else { //否定后
mui.swipeoutClose( _this.parent().parent()[0] );
}
});
});
//点击编辑任务
$(document).on('click', '.task_edit', function(){
var _this = $(this);
id = _this.attr('data');
//填充值
$('#task_name').val(config[id]['task_name']);
$('#task_msg').val(config[id]['task_msg']);
$(".task_anick:radio[value='"+config[id]['task_anick']+"']").prop('checked', true);
$(".task_msgtype:radio[value='"+config[id]['task_msgtype']+"']").prop('checked', true);
$(".task_quntype:radio[value='"+config[id]['task_quntype']+"']").prop('checked', true);
$('#task_keyword').val(config[id]['task_keyword']);
$('#task_mfsl').val(config[id]['task_mfsl']);
$('#task_mlsl').val(config[id]['task_mlsl']);
$('#task_mtsl').val(config[id]['task_mtsl']);
if( config[id]['task_qunfilter'] != undefined){
$('#task_qunfilter').prop('checked', true);
}
//群筛选功能
if($('#task_qunfilter').prop('checked') == true){
$('.qun-type').show();
}
viewApi.go("#account");
});
//点击添加新任务
$(document).on('click', '#add_task', function(){
$('#task_qunfilter').prop('checked', false);
$('.qun-type').hide();
id=null;
document.getElementById('form_edit').reset();
viewApi.go('#account');
});
//点击群筛选功能
$(document).on('click', '#task_qunfilter', function(){
if($(this).prop('checked') == true){
$('.qun-type').show();
}else{
$('.qun-type').hide();
}
});
});
/***************************jquery的一些操作******************************/
/***************************操作微信*******************************/
var task = function(id){
//给数组增加原型方法,指定数组只能存8个元素
Array.prototype.list = function(ele){
if( this.length >= 8 ){
this.shift();
}
return this.push(ele);
}
_.set('task_id', id);
_.set('task_config', config[id]);
_.start("com.tencent.mm", "com.tencent.mm.ui.LauncherUI");
_.when("com.tencent.mm.ui.LauncherUI", function(){
var config = _.isset('task_config') ? _.get('task_config') : {};
if(_.isEmptyObject(config))
return _.error('无法获取配置文件');
_.wait(function(){
_.debug("查找[通讯录]");
var rtn = _.findViewByText("^通讯录$");
return !_.isEmptyObject(rtn.result);
}, function(){
_.debug('点击[通讯录]');
_.clickByText("^通讯录$");
setTimeout(function(){
_.debug('点击[群聊]');
_.clickById('com.tencent.mm:id/dp');
}, 500);
}, function(){
return _.error('找不到按钮[通讯录]');
}, 10000);
}).when('com.tencent.mm.ui.contact.ChatroomContactUI', function(){
_.debug('获取群聊列表');
var config = _.get('task_config');
var keyword = config['task_keyword'];
var obj = _.findViewById('com.tencent.mm:id/iz');
if( _.isEmptyObject(obj.result) )
return _.error("无法获取群聊列表!");
var count = obj.result.childCount;
var index = _.isset('index') ? _.get('index') : 0;
var num = _.isset('num') ? _.get('num') : 0;
var nickList = _.isset('nick_list') ? _.get('nick_list') : [];
if( index >= count ){
var ob = _.scroll("com.tencent.mm:id/iz");
if( !ob.result ){
return _.halt("所有群已加完");
}
index = 0;
}
_.set('index', index+1);
_.debug("开始添加", index, "/", count);
var filter = _.findViewById('com.tencent.mm:id/ej', index);
_.debug(nickList);
//筛选群
if( config['task_qunfilter'] ){
//关键词模式
if( config['task_quntype'] == 1 ){
if( !_.isEmptyObject(filter.result) && !filter.result.text.match(eval("/"+ keyword.replace(new RegExp(' ', 'gm'), '|') +"/")) )
return _.sysAct(1);
}
//顺序号模式
if( config['task_quntype'] == 2 ){
if( !_.isEmptyObject(filter.result) ){
//查找群名称是否存在
var exist = false;
for(var i in nickList){
if( nickList[i] == filter.result.text ){
exist = true;
break;
}
}
if(!exist){
_.set('num', num+1);
nickList.list(filter.result.text);
_.set('nick_list', nickList);
}
var cur = _.get('num');
var state = false;
_.debug(cur);
var line = keyword.split(' ');
_.debug(line);
for(var j in line){
var s = line[j].toString();
if(s.indexOf('-') > -1){
var arr = s.split('-');
_.debug(arr);
if(cur >= arr[0] && cur <= arr[1]){
state = true;
}
}else{
if(cur == s){
state = true;
}
}
}
if(!state)
return _.sysAct(1);
}
}
}
var rtn = _.clickChildById('com.tencent.mm:id/iz', 0, index);
if( !rtn.result )
return _.sysAct(1);
}).when('com.tencent.mm.ui.chatting.ChattingUI', function(){
//return _.back(1);
_.debug('选择群成员');
/*var t = _.findParentViewById('com.tencent.mm:id/ce9');
_.debug(t);*/
/*var obj = _.findViewById('com.tencent.mm:id/ce9');
_.debug(obj);*/
_.clickChildById('android:id/action_bar', 0, 2);
}).when('com.tencent.mm.plugin.chatroom.ui.ChatroomInfoUI', function(){
_.debug('查找[全部群成员]按钮');
_.scroll('android:id/list');
var scrollDirect = 0; //向前滚动
var timer = setInterval(function(){
var obj = _.findViewByText('^全部群成员([0-9]{1,})$');
if( !_.isEmptyObject(obj.result) ){
clearInterval(timer);
_.clickByText('^全部群成员([0-9]{1,})$');
return;
}
var ob = _.scroll('android:id/list', scrollDirect);
if(!ob.result){
scrollDirect = 1;
}
}, 3000);
}).when('com.tencent.mm.plugin.chatroom.ui.SeeRoomMemberUI', function(){
_.debug('获取群聊成员列表');
var obj = _.findViewById('com.tencent.mm:id/j5');
if( _.isEmptyObject(obj.result) )
return _.error("无法获取列表控件!");
var count = obj.result.childCount;
var index = _.isset('index2') ? _.get('index2') : 0;
if( index >= count ){
var ob = _.scroll("com.tencent.mm:id/j5");
if( !ob.result ){
return _.back(3);
//return _.halt("完成加好友");
}
index = 0;
}
_.set('index2', index+1);
_.debug("开始添加", index, "/", count);
var config = _.get('task_config');
var second = Math.floor(60 / config['task_mfsl']);
setTimeout(function(){
var rtn = _.clickChildById('com.tencent.mm:id/j5', 0, index);
}, second * 1000);
}).when('com.tencent.mm.plugin.profile.ui.ContactInfoUI', function(){
var lock = _.isset("lock") ? _.get("lock") : false;
if (lock) {
_.debug("已经添加过,直接返回");
_.set("lock", false);
return _.sysAct(1);
}
_.debug('点击[添加到通讯录]');
var nick = _.findViewById('com.tencent.mm:id/ah0');
var preNick = _.isset('friend_nick') ? _.get('friend_nick') : '';
if( _.isEmptyObject(nick.result) ){
return _.error('无法获取好友昵称');
}
if(nick.result.text == preNick){
_.debug('重复添加,返回');
return _.sysAct(1);
}
_.set('friend_nick', nick.result.text);
var rtn = _.clickByText('^添加到通讯录$');
if(!rtn.result){
_.debug('无法找到按钮[添加到通讯录],返回');
return _.sysAct(1);
}
}).when('com.tencent.mm.plugin.profile.ui.SayHiWithSnsPermissionUI', function(){
_.debug("准备发送[验证申请]");
_.wait(1000, function(){
var nick = _.get('friend_nick');
var config = _.get('task_config');
var msg = config['task_msg'].split("\r\n");
var index = Math.floor( Math.random() * msg.length );
nick = config['task_anick'] == 1 ? nick + ',' : '';
var rtn = _.inputText("android.widget.EditText", nick + msg[index]);
return rtn.result;
});
_.wait(500, function(){
var rtn = _.clickByText("^发送$");
if (rtn.result == false)
return _.error("点击[发送]出错:", rtn);
_.set("lock", true);
_.debug("完成[验证申请]");
});
});
_.loop(function(activity){
if( !/^com\.tencent\.mm/.test(activity) && !/android\.widget\.FrameLayout/.test(activity) )
return true;
if( /^com\.tencent\.mm\.ui\.base\.p/.test(activity) )
return true;
return false;
}, function(activity, times){
/*if( times > 5000 )
return true;*/
return false;
}, function(activity){
_.error("Not found function for", activity, "!");
//_.sysAct(1);
});
}
/***************************操作微信*******************************/
/*******************************公共方法**********************************/
//得到配置长度
function getConfigLength(){
var l = 0;
for(var i in config){
l++;
}
return l;
}
//得到配置最后编号
function getConfigNo(){
var l = 0;
for(var i in config){
l = i;
}
return l;
}
//根据配置循环出任务列表
function list(){
var tlHtml = '';
if(!common.isEmptyObject(config)){
for(var i in config){
tlHtml += '<li class="mui-table-view-cell"><div class="mui-slider-right mui-disabled"><a class="mui-btn mui-btn-blue task_edit" data="'+i+'">编辑</a><a class="mui-btn mui-btn-red task_del" data="'+i+'">删除</a></div><div class="mui-slider-handle" data="'+i+'"><div class="mui-table-cell">'+config[i]['task_name']+'</div></div></li>';
}
}else{
tlHtml += '<li class="mui-table-view-cell mui-text-center">暂无任务</li>';
}
//创建任务dom
$('#OA_task_2').html(tlHtml);
}
//检测表单
function checkForm(frm){
var name = frm.task_name,
msg = frm.task_msg,
state = true;
if(name.value == ''){
$(name).addClass('error');
state = false;
}else{
$(name).removeClass('error');
}
if(msg.value == ''){
$(msg).addClass('error');
state = false;
}else{
$(msg).removeClass('error');
}
return state;
}
/*******************************公共方法**********************************/
}); |
(function() {
'use strict';
angular
.module('ionicTopTabs', [])
.directive('topTabs', topTabs);
/** @ngInject */
function topTabs($timeout) {
var directive = {
restrict: 'E',
scope: {
tabs: '=',
activated: '='
},
required: 'type',
replace: true,
template: '<section class="tabs-top tabs-background-light cs-top-tabs">' +
'<div class="tab-nav tabs">' +
'<a class="tab-item" ng-repeat="item in tabs" ng-class="{\'tab-item-active\': item.id==activated}" ng-click="active(item.id)">' +
'<span class="tab-title">{{item.title}}</span>' +
'</a>' +
'</div>' +
'</section>',
link: function(scope, element, attr) {
$timeout(function() {
var type = attr.type;
element.find('a').addClass('tab-item-' + type);
}, 100);
scope.active = function(id) {
scope.activated = id;
};
}
};
return directive;
}
})();
|
const pgp = require('pg-promise')(/*options*/);
const db = pgp(process.env.DATABASE_URL || 'postgres://postgres:postgres@localhost:8000/postgres');
db.connect()
.then(function (obj) {
console.log('DB connection established.')
obj.done(); // success, release the connection;
})
.catch(function (error) {
console.log("ERROR:", error.message || error);
});
module.exports = db;
|
'use strict';
var PrimusError = require('./errors').PrimusError
, EventEmitter = require('eventemitter3')
, Transformer = require('./transformer')
, log = require('diagnostics')('primus')
, Spark = require('./spark')
, fuse = require('fusing')
, fs = require('fs')
, vm = require('vm');
/**
* Primus is a universal wrapper for real-time frameworks that provides a common
* interface for server and client interaction.
*
* @constructor
* @param {HTTP.Server} server HTTP or HTTPS server instance.
* @param {Object} options Configuration
* @api public
*/
function Primus(server, options) {
if (!(this instanceof Primus)) return new Primus(server, options);
this.fuse();
if ('object' !== typeof server) {
var message = 'The first argument of the constructor must be ' +
'an HTTP or HTTPS server instance';
throw new PrimusError(message, this);
}
options = options || {};
options.maxLength = options.maxLength || 10485760; // Maximum allowed packet size.
options.transport = options.transport || {}; // Transformer specific options.
options.pingInterval = 'pingInterval' in options // Heartbeat interval.
? options.pingInterval
: 30000;
if ('timeout' in options) {
throw new PrimusError('The `timeout` option has been removed', this);
}
var primus = this
, key;
this.auth = options.authorization || null; // Do we have an authorization handler.
this.connections = Object.create(null); // Connection storage.
this.ark = Object.create(null); // Plugin storage.
this.layers = []; // Middleware layers.
this.heartbeatInterval = null; // The heartbeat interval.
this.transformer = null; // Reference to the real-time engine instance.
this.encoder = null; // Shorthand to the parser's encoder.
this.decoder = null; // Shorthand to the parser's decoder.
this.connected = 0; // Connection counter.
this.whitelist = []; // Forwarded-for white listing.
this.options = options; // The configuration.
this.transformers = { // Message transformers.
outgoing: [],
incoming: []
};
this.server = server;
this.pathname = 'string' === typeof options.pathname
? options.pathname.charAt(0) !== '/'
? '/'+ options.pathname
: options.pathname
: '/primus';
//
// Create a specification file with the information that people might need to
// connect to the server.
//
this.spec = {
pingInterval: options.pingInterval,
pathname: this.pathname,
version: this.version
};
//
// Create a pre-bound Spark constructor. Doing a Spark.bind(Spark, this) doesn't
// work as we cannot extend the constructor of it anymore. The added benefit of
// approach listed below is that the prototype extensions are only applied to
// the Spark of this Primus instance.
//
this.Spark = function Sparky(headers, address, query, id, request, socket) {
Spark.call(this, primus, headers, address, query, id, request, socket);
};
this.Spark.prototype = Object.create(Spark.prototype, {
constructor: {
configurable: true,
value: this.Spark,
writable: true
},
__initialise: {
value: Spark.prototype.__initialise.slice(),
configurable: true,
writable: true
}
});
//
// Copy over the original Spark static properties and methods so readable and
// writable can also be used.
//
for (key in Spark) {
this.Spark[key] = Spark[key];
}
this.parsers(options.parser);
this.initialise(options.transformer, options);
//
// If the plugins are supplied through the options, also initialise them.
// This also allows us to use plugins when creating a client constructor
// with the `Primus.createSocket({})` method.
//
if ('string' === typeof options.plugin) {
options.plugin.split(/[, ]+/).forEach(function register(name) {
primus.plugin(name, name);
});
} else if ('object' === typeof options.plugin) {
for (key in options.plugin) {
this.plugin(key, options.plugin[key]);
}
}
//
// - Cluster node 0.10 lets the Operating System decide to which worker a request
// goes. This can result in a not even distribution where some workers are
// used at 10% while others at 90%. In addition to that the load balancing
// isn't sticky.
//
// - Cluster node 0.12 implements a custom round robin algorithm. This solves the
// not even distribution of work but it does not address our sticky session
// requirement.
//
// Projects like `sticky-session` attempt to implement sticky sessions but they
// are using `net` server instead of a HTTP server in combination with the
// remoteAddress of the connection to load balance. This does not work when you
// address your servers behind a load balancer as the IP is set to the load
// balancer, not the connecting clients. All in all, it only causes more
// scalability problems. So we've opted-in to warn users about the
// risks of using Primus in a cluster.
//
if (!options.iknowclusterwillbreakconnections && require('cluster').isWorker) [
'',
'The `cluster` module does not implement sticky sessions. Learn more about',
'this issue at:',
'',
'http://github.com/primus/primus#can-i-use-cluster',
''
].forEach(function warn(line) {
console.error('Primus: '+ line);
});
}
//
// Fuse and spice-up the Primus prototype with EventEmitter and predefine
// awesomeness.
//
fuse(Primus, EventEmitter);
//
// Lazy read the primus.js JavaScript client.
//
Object.defineProperty(Primus.prototype, 'client', {
get: function read() {
if (!read.primus) {
read.primus = fs.readFileSync(__dirname + '/dist/primus.js', 'utf-8');
}
return read.primus;
}
});
//
// Lazy compile the primus.js JavaScript client for Node.js
//
Object.defineProperty(Primus.prototype, 'Socket', {
get: function () {
const sandbox = Object.keys(global).reduce((acc, key) => {
if (key !== 'global' && key !== 'require') acc[key] = global[key];
return acc;
}, {
__dirname: process.cwd(),
__filename: 'primus.js',
require: require,
//
// The following globals are introduced so libraries that use `instanceof`
// checks for type checking do not fail as the code is run in a new
// context.
//
Uint8Array: Uint8Array,
Object: Object,
RegExp: RegExp,
Array: Array,
Error: Error,
Date: Date
});
vm.runInNewContext(this.library(true), sandbox, { filename: 'primus.js' });
return sandbox[this.options.global || 'Primus'];
}
});
//
// Expose the current version number.
//
Primus.prototype.version = require('./package.json').version;
//
// A list of supported transformers and the required Node.js modules.
//
Primus.transformers = require('./transformers.json');
Primus.parsers = require('./parsers.json');
/**
* Simple function to output common errors.
*
* @param {String} what What is missing.
* @param {Object} where Either Primus.parsers or Primus.transformers.
* @returns {Object}
* @api private
*/
Primus.readable('is', function is(what, where) {
var missing = Primus.parsers !== where
? 'transformer'
: 'parser'
, dependency = where[what];
return {
missing: function write() {
console.error('Primus:');
console.error('Primus: Missing required npm dependency for '+ what);
console.error('Primus: Please run the following command and try again:');
console.error('Primus:');
console.error('Primus: npm install --save %s', dependency.server);
console.error('Primus:');
return 'Missing dependencies for '+ missing +': "'+ what + '"';
},
unknown: function write() {
console.error('Primus:');
console.error('Primus: Unsupported %s: "%s"', missing, what);
console.error('Primus: We only support the following %ss:', missing);
console.error('Primus:');
console.error('Primus: %s', Object.keys(where).join(', '));
console.error('Primus:');
return 'Unsupported '+ missing +': "'+ what +'"';
}
};
});
/**
* Initialise the real-time engine that was chosen.
*
* @param {Mixed} Transformer The name of the transformer or a constructor;
* @param {Object} options Options.
* @api private
*/
Primus.readable('initialise', function initialise(Transformer, options) {
Transformer = Transformer || 'websockets';
var primus = this
, transformer;
if ('string' === typeof Transformer) {
log('transformer `%s` is a string, attempting to resolve location', Transformer);
Transformer = transformer = Transformer.toLowerCase();
this.spec.transformer = transformer;
//
// This is a unknown transformer, it could be people made a typo.
//
if (!(Transformer in Primus.transformers)) {
log('the supplied transformer %s is not supported, please use %s', transformer, Primus.transformers);
throw new PrimusError(this.is(Transformer, Primus.transformers).unknown(), this);
}
try {
Transformer = require('./transformers/'+ transformer);
this.transformer = new Transformer(this);
} catch (e) {
if (e.code === 'MODULE_NOT_FOUND') {
log('the supplied transformer `%s` is missing', transformer);
throw new PrimusError(this.is(transformer, Primus.transformers).missing(), this);
} else {
log(e);
throw e;
}
}
} else {
log('received a custom transformer');
this.spec.transformer = 'custom';
}
if ('function' !== typeof Transformer) {
throw new PrimusError('The given transformer is not a constructor', this);
}
this.transformer = this.transformer || new Transformer(this);
this.on('connection', function connection(stream) {
this.connected++;
this.connections[stream.id] = stream;
log('connection: %s currently serving %d concurrent', stream.id, this.connected);
});
this.on('disconnection', function disconnected(stream) {
this.connected--;
delete this.connections[stream.id];
log('disconnection: %s currently serving %d concurrent', stream.id, this.connected);
});
//
// Add our default middleware layers.
//
this.use('forwarded', require('./middleware/forwarded'));
this.use('cors', require('./middleware/access-control'));
this.use('primus.js', require('./middleware/primus'));
this.use('spec', require('./middleware/spec'));
this.use('x-xss', require('./middleware/xss'));
this.use('no-cache', require('./middleware/no-cache'));
this.use('authorization', require('./middleware/authorization'));
//
// Set the heartbeat interval.
//
if (options.pingInterval) {
this.heartbeatInterval = setInterval(
this.heartbeat.bind(this),
options.pingInterval
);
}
//
// Emit the initialised event after the next tick so we have some time to
// attach listeners.
//
process.nextTick(function tock() {
primus.emit('initialised', primus.transformer, primus.parser, options);
});
});
/**
* Add a new authorization handler.
*
* @param {Function} auth The authorization handler.
* @returns {Primus}
* @api public
*/
Primus.readable('authorize', function authorize(auth) {
if ('function' !== typeof auth) {
throw new PrimusError('Authorize only accepts functions', this);
}
if (auth.length < 2) {
throw new PrimusError('Authorize function requires more arguments', this);
}
log('setting an authorization function');
this.auth = auth;
return this;
});
/**
* Iterate over the connections.
*
* @param {Function} fn The function that is called every iteration.
* @param {Function} done Optional callback, if you want to iterate asynchronously.
* @returns {Primus}
* @api public
*/
Primus.readable('forEach', function forEach(fn, done) {
if (!done) {
for (var id in this.connections) {
if (fn(this.spark(id), id, this.connections) === false) break;
}
return this;
}
var ids = Object.keys(this.connections)
, primus = this;
log('iterating over %d connections', ids.length);
function pushId(spark) {
ids.push(spark.id);
}
//
// We are going to iterate through the connections asynchronously so
// we should handle new connections as they come in.
//
primus.on('connection', pushId);
(function iterate() {
var id = ids.shift()
, spark;
if (!id) {
primus.removeListener('connection', pushId);
return done();
}
spark = primus.spark(id);
//
// The connection may have already been closed.
//
if (!spark) return iterate();
fn(spark, function next(err, forward) {
if (err || forward === false) {
primus.removeListener('connection', pushId);
return done(err);
}
iterate();
});
}());
return this;
});
/**
* Send a ping packet to all clients to ensure that they are still connected.
*
* @returns {Primus}
* @api private
*/
Primus.readable('heartbeat', function heartbeat() {
this.forEach(function forEach(spark) {
spark.heartbeat();
});
return this;
});
/**
* Broadcast the message to all connections.
*
* @param {Mixed} data The data you want to send.
* @returns {Primus}
* @api public
*/
Primus.readable('write', function write(data) {
this.forEach(function forEach(spark) {
spark.write(data);
});
return this;
});
/**
* Install message parsers.
*
* @param {Mixed} parser Parse name or parser Object.
* @returns {Primus}
* @api private
*/
Primus.readable('parsers', function parsers(parser) {
parser = parser || 'json';
if ('string' === typeof parser) {
log('transformer `%s` is a string, attempting to resolve location', parser);
parser = parser.toLowerCase();
this.spec.parser = parser;
//
// This is a unknown parser, it could be people made a typo.
//
if (!(parser in Primus.parsers)) {
log('the supplied parser `%s` is not supported please use %s', parser, Primus.parsers);
throw new PrimusError(this.is(parser, Primus.parsers).unknown(), this);
}
try { parser = require('./parsers/'+ parser); }
catch (e) {
if (e.code === 'MODULE_NOT_FOUND') {
log('the supplied parser `%s` is missing', parser);
throw new PrimusError(this.is(parser, Primus.parsers).missing(), this);
} else {
log(e);
throw e;
}
}
} else {
this.spec.parser = 'custom';
}
if ('object' !== typeof parser) {
throw new PrimusError('The given parser is not an Object', this);
}
this.encoder = parser.encoder;
this.decoder = parser.decoder;
this.parser = parser;
return this;
});
/**
* Register a new message transformer. This allows you to easily manipulate incoming
* and outgoing data which is particularity handy for plugins that want to send
* meta data together with the messages.
*
* @param {String} type Incoming or outgoing
* @param {Function} fn A new message transformer.
* @returns {Primus}
* @api public
*/
Primus.readable('transform', function transform(type, fn) {
if (!(type in this.transformers)) {
throw new PrimusError('Invalid transformer type', this);
}
if (~this.transformers[type].indexOf(fn)) {
log('the %s message transformer already exists, not adding it', type);
return this;
}
this.transformers[type].push(fn);
return this;
});
/**
* Gets a spark by its id.
*
* @param {String} id The spark's id.
* @returns {Spark}
* @api private
*/
Primus.readable('spark', function spark(id) {
return this.connections[id];
});
/**
* Generate a client library.
*
* @param {Boolean} nodejs Don't include the library, as we're running on Node.js.
* @returns {String} The client library.
* @api public
*/
Primus.readable('library', function compile(nodejs) {
var library = [ !nodejs ? this.transformer.library : null ]
, global = this.options.global || 'Primus'
, parser = this.parser.library || ''
, client = this.client;
//
// Add a simple export wrapper so it can be used as Node.js, AMD or browser
// client.
//
client = [
'(function UMDish(name, context, definition, plugins) {',
' context[name] = definition.call(context);',
' for (var i = 0; i < plugins.length; i++) {',
' plugins[i](context[name])',
' }',
' if (typeof module !== "undefined" && module.exports) {',
' module.exports = context[name];',
' } else if (typeof define === "function" && define.amd) {',
' define(function reference() { return context[name]; });',
' }',
'})("'+ global +'", this || {}, function wrapper() {',
' var define, module, exports',
' , Primus = '+ client.slice(client.indexOf('return ') + 7, -4) +';',
''
].join('\n');
//
// Replace some basic content.
//
client = client
.replace('null; // @import {primus::pathname}', '"'+ this.pathname.toString() +'"')
.replace('null; // @import {primus::version}', '"'+ this.version +'"')
.replace('null; // @import {primus::client}', this.transformer.client.toString())
.replace('null; // @import {primus::auth}', (!!this.auth).toString())
.replace('null; // @import {primus::encoder}', this.encoder.toString())
.replace('null; // @import {primus::decoder}', this.decoder.toString());
//
// As we're given a `pingInterval` value on the server side, we need to update
// the `pingTimeout` on the client.
//
if (this.options.pingInterval) {
const value = this.options.pingInterval + Math.round(this.options.pingInterval / 2);
log('updating the default value of the client `pingTimeout` option');
client = client.replace(
'options.pingTimeout : 45e3;',
`options.pingTimeout : ${value};`
);
} else {
log('setting the default value of the client `pingTimeout` option to `false`');
client = client.replace(
'options.pingTimeout : 45e3;',
'options.pingTimeout : false;'
);
}
//
// Add the parser inside the closure, to prevent global leaking.
//
if (parser && parser.length) {
log('adding parser to the client file');
client += parser;
}
//
// Iterate over the parsers, and register the client side plugins. If there's
// a library bundled, add it the library array as there were some issues with
// frameworks that get included in module wrapper as it forces strict mode.
//
var name, plugin;
for (name in this.ark) {
plugin = this.ark[name];
name = JSON.stringify(name);
if (plugin.library) {
log('adding the library of the %s plugin to the client file', name);
library.push(plugin.library);
}
if (!plugin.client) continue;
log('adding the client code of the %s plugin to the client file', name);
client += 'Primus.prototype.ark['+ name +'] = '+ plugin.client.toString() +';\n';
}
//
// Close the export wrapper and return the client. If we need to add
// a library, we should add them after we've created our closure and module
// exports. Some libraries seem to fail hard once they are wrapped in our
// closure so I'll rather expose a global variable instead of having to monkey
// patch too much code.
//
return client + [
' return Primus;',
'},',
'['
].concat(library.filter(Boolean).map(function expose(library) {
return [
'function (Primus) {',
library,
'}'
].join('\n');
}).join(',\n'))
.concat(']);')
.join('\n');
});
/**
* Save the library to disk.
*
* @param {String} dir The location that we need to save the library.
* @param {function} fn Optional callback, if you want an async save.
* @returns {Primus}
* @api public
*/
Primus.readable('save', function save(path, fn) {
if (!fn) fs.writeFileSync(path, this.library(), 'utf-8');
else fs.writeFile(path, this.library(), 'utf-8', fn);
return this;
});
/**
* Register a new Primus plugin.
*
* ```js
* primus.plugin('ack', {
* //
* // Only ran on the server.
* //
* server: function (primus, options) {
* // do stuff
* },
*
* //
* // Runs on the client, it's automatically bundled.
* //
* client: function (primus, options) {
* // do client stuff
* },
*
* //
* // Optional library that needs to be bundled on the client (should be a string)
* //
* library: ''
* });
* ```
*
* @param {String} name The name of the plugin.
* @param {Object} energon The plugin that contains client and server extensions.
* @returns {Mixed}
* @api public
*/
Primus.readable('plugin', function plugin(name, energon) {
if (!name) return this.ark;
if (!energon) {
if ('string' === typeof name) return this.ark[name];
if ('object' === typeof name) {
energon = name;
name = energon.name;
}
}
if ('string' !== typeof name || !name) {
throw new PrimusError('Plugin name must be a non empty string', this);
}
if ('string' === typeof energon) {
log('plugin was passed as a string, attempting to require %s', energon);
energon = require(energon);
}
//
// Plugin accepts an object or a function only.
//
if (!/^(object|function)$/.test(typeof energon)) {
throw new PrimusError('Plugin should be an object or function', this);
}
//
// Plugin require a client, server or both to be specified in the object.
//
if (!energon.server && !energon.client) {
throw new PrimusError('Plugin is missing a client or server function', this);
}
//
// Don't allow duplicate plugins or plugin override as this is most likely
// unintentional.
//
if (name in this.ark) {
throw new PrimusError('Plugin name already defined', this);
}
log('adding %s as new plugin', name);
this.ark[name] = energon;
this.emit('plugin', name, energon);
if (!energon.server) return this;
log('calling the %s plugin\'s server code', name);
energon.server.call(this, this, this.options);
return this;
});
/**
* Remove plugin from the ark.
*
* @param {String} name Name of the plugin we need to remove from the ark.
* @returns {Boolean} Successful removal of the plugin.
* @api public
*/
Primus.readable('plugout', function plugout(name) {
if (!(name in this.ark)) return false;
this.emit('plugout', name, this.ark[name]);
delete this.ark[name];
return true;
});
/**
* Add a new middleware layer. If no middleware name has been provided we will
* attempt to take the name of the supplied function. If that fails, well fuck,
* just random id it.
*
* @param {String} name The name of the middleware.
* @param {Function} fn The middleware that's called each time.
* @param {Object} options Middleware configuration.
* @param {Number} level 0 based optional index for the middleware.
* @returns {Primus}
* @api public
*/
Primus.readable('use', function use(name, fn, options, level) {
if ('function' === typeof name) {
level = options;
options = fn;
fn = name;
name = fn.name || 'pid_'+ Date.now();
}
if (!level && 'number' === typeof options) {
level = options;
options = {};
}
options = options || {};
//
// No or only 1 argument means that we need to initialise the middleware, this
// is a special initialisation process where we pass in a reference to the
// initialised Primus instance so a pre-compiling process can be done.
//
if (fn.length < 2) {
log('automatically configuring middleware `%s`', name);
fn = fn.call(this, options);
}
//
// Make sure that we have a function that takes at least 2 arguments.
//
if ('function' !== typeof fn || fn.length < 2) {
throw new PrimusError('Middleware should be a function that accepts at least 2 args');
}
var layer = {
length: fn.length, // Amount of arguments indicates if it's async.
enabled: true, // Middleware is enabled by default.
name: name, // Used for lookups.
fn: fn // The actual middleware.
}, index = this.indexOfLayer(name);
//
// Override middleware layer if we already have a middleware layer with
// exactly the same name.
//
if (!~index) {
if (level >= 0 && level < this.layers.length) {
log('adding middleware `%s` to the supplied index at %d', name, level);
this.layers.splice(level, 0, layer);
} else {
this.layers.push(layer);
}
} else {
this.layers[index] = layer;
}
return this;
});
/**
* Remove a middleware layer from the stack.
*
* @param {String} name The name of the middleware.
* @returns {Primus}
* @api public
*/
Primus.readable('remove', function remove(name) {
var index = this.indexOfLayer(name);
if (~index) {
log('removing middleware `%s`', name);
this.layers.splice(index, 1);
}
return this;
});
/**
* Enable a given middleware layer.
*
* @param {String} name The name of the middleware.
* @returns {Primus}
* @api public
*/
Primus.readable('enable', function enable(name) {
var index = this.indexOfLayer(name);
if (~index) {
log('enabling middleware `%s`', name);
this.layers[index].enabled = true;
}
return this;
});
/**
* Disable a given middleware layer.
*
* @param {String} name The name of the middleware.
* @returns {Primus}
* @api public
*/
Primus.readable('disable', function disable(name) {
var index = this.indexOfLayer(name);
if (~index) {
log('disabling middleware `%s`', name);
this.layers[index].enabled = false;
}
return this;
});
/**
* Find the index of a given middleware layer by name.
*
* @param {String} name The name of the layer.
* @returns {Number}
* @api private
*/
Primus.readable('indexOfLayer', function indexOfLayer(name) {
for (var i = 0, length = this.layers.length; i < length; i++) {
if (this.layers[i].name === name) return i;
}
return -1;
});
/**
* Destroy the created Primus instance.
*
* Options:
* - close (boolean) Close the given server.
* - reconnect (boolean) Trigger a client-side reconnect.
* - timeout (number) Close all active connections after x milliseconds.
*
* @param {Object} options Destruction instructions.
* @param {Function} fn Callback.
* @returns {Primus}
* @api public
*/
Primus.readable('destroy', function destroy(options, fn) {
if ('function' === typeof options) {
fn = options;
options = null;
}
options = options || {};
if (options.reconnect) options.close = true;
var primus = this;
clearInterval(primus.heartbeatInterval);
setTimeout(function close() {
var transformer = primus.transformer;
//
// Ensure that the transformer receives the `close` event only once.
//
if (transformer) transformer.ultron.destroy();
//
// Close the connections that are left open.
//
primus.forEach(function shutdown(spark) {
spark.end(undefined, { reconnect: options.reconnect });
});
if (options.close !== false) {
//
// Closing a server that isn't started yet would throw an error.
//
try {
primus.server.close(function closed() {
primus.close(options, fn);
});
return;
}
catch (e) {}
}
primus.close(options, fn);
}, +options.timeout || 0);
return this;
});
/**
* Free resources after emitting a final `close` event.
*
* @param {Object} options Destruction instructions.
* @param {Function} fn Callback.
* @returns {Primus}
* @api private
*/
Primus.readable('close', function close(options, fn) {
var primus = this;
//
// Emit a final `close` event before removing all the listeners
// from all the event emitters.
//
primus.asyncemit('close', options, function done(err) {
if (err) {
if (fn) return fn(err);
throw err;
}
var transformer = primus.transformer
, server = primus.server;
//
// If we don't have a server we are most likely destroying an already
// destroyed Primus instance.
//
if (!server) return fn && fn();
server.removeAllListeners('request');
server.removeAllListeners('upgrade');
//
// Re-add the original listeners so that the server can be used again.
//
transformer.listeners('previous::request').forEach(function add(listener) {
server.on('request', listener);
});
transformer.listeners('previous::upgrade').forEach(function add(listener) {
server.on('upgrade', listener);
});
transformer.emit('close', options);
transformer.removeAllListeners();
primus.removeAllListeners();
//
// Null some potentially heavy objects to free some more memory instantly.
//
primus.transformers.outgoing.length = primus.transformers.incoming.length = 0;
primus.transformer = primus.encoder = primus.decoder = primus.server = null;
primus.connected = 0;
primus.connections = Object.create(null);
primus.ark = Object.create(null);
if (fn) fn();
});
return this;
});
/**
* Async emit an event. We make a really broad assumption here and that is they
* have the same amount of arguments as the supplied arguments (excluding the
* event name).
*
* @returns {Primus}
* @api private
*/
Primus.readable('asyncemit', require('asyncemit'));
//
// Alias for destroy.
//
Primus.readable('end', Primus.prototype.destroy);
/**
* Checks if the given event is an emitted event by Primus.
*
* @param {String} evt The event name.
* @returns {Boolean}
* @api public
*/
Primus.readable('reserved', function reserved(evt) {
return (/^(incoming|outgoing)::/).test(evt)
|| evt in reserved.events;
});
/**
* The actual events that are used by Primus.
*
* @type {Object}
* @api public
*/
Primus.prototype.reserved.events = {
'disconnection': 1,
'initialised': 1,
'connection': 1,
'plugout': 1,
'plugin': 1,
'close': 1,
'log': 1
};
/**
* Add a createSocket interface so we can create a Server client with the
* specified `transformer` and `parser`.
*
* ```js
* var Socket = Primus.createSocket({ transformer: transformer, parser: parser })
* , socket = new Socket(url);
* ```
*
* @param {Object} options The transformer / parser we need.
* @returns {Socket}
* @api public
*/
Primus.createSocket = function createSocket(options) {
// Make sure the temporary Primus we create below doesn't start a heartbeat
options = Object.assign({}, options, { pingInterval: false });
var primus = new Primus(new EventEmitter(), options);
return primus.Socket;
};
/**
* Create a new Primus server.
*
* @param {Function} fn Request listener.
* @param {Object} options Configuration.
* @returns {Pipe}
* @api public
*/
Primus.createServer = function createServer(fn, options) {
if ('object' === typeof fn) {
options = fn;
fn = null;
}
options = options || {};
var server = require('create-server')(Primus.prototype.merge.call(Primus, {
http: function warn() {
if (!options.iknowhttpsisbetter) [
'',
'We\'ve detected that you\'re using a HTTP instead of a HTTPS server.',
'Please be aware that real-time connections have less chance of being blocked',
'by firewalls and anti-virus scanners if they are encrypted (using SSL). If',
'you run your server behind a reverse and HTTPS terminating proxy ignore',
'this message, if not, you\'ve been warned.',
''
].forEach(function each(line) {
console.log('primus: '+ line);
});
}
}, options));
//
// Now that we've got a server, we can setup the Primus and start listening.
//
var application = new Primus(server, options);
if (fn) application.on('connection', fn);
return application;
};
//
// Expose the constructors of our Spark and Transformer so it can be extended by
// a third party if needed.
//
Primus.Transformer = Transformer;
Primus.Spark = Spark;
//
// Expose the module.
//
module.exports = Primus;
|
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
var React = require("react");
var Label_1 = require("office-ui-fabric-react/lib/Label");
var Pivot_1 = require("office-ui-fabric-react/lib/Pivot");
var PivotTabsExample = (function (_super) {
__extends(PivotTabsExample, _super);
function PivotTabsExample() {
return _super !== null && _super.apply(this, arguments) || this;
}
PivotTabsExample.prototype.render = function () {
return (React.createElement("div", null,
React.createElement(Pivot_1.Pivot, { linkFormat: Pivot_1.PivotLinkFormat.tabs },
React.createElement(Pivot_1.PivotItem, { linkText: 'Foo' },
React.createElement(Label_1.Label, null, "Pivot #1")),
React.createElement(Pivot_1.PivotItem, { linkText: 'Bar' },
React.createElement(Label_1.Label, null, "Pivot #2")),
React.createElement(Pivot_1.PivotItem, { linkText: 'Bas' },
React.createElement(Label_1.Label, null, "Pivot #3")),
React.createElement(Pivot_1.PivotItem, { linkText: 'Biz' },
React.createElement(Label_1.Label, null, "Pivot #4")))));
};
return PivotTabsExample;
}(React.Component));
exports.PivotTabsExample = PivotTabsExample;
//# sourceMappingURL=Pivot.Tabs.Example.js.map
|
/*
* A list item representing a resource in the API.
*
* This item will be backed by a resource model, which will be used for
* all synchronization with the API. It will work as a proxy for requests
* and events, and synchronize attributes between the resource and the list
* item. This allows callers to work directly with the list item instead of
* digging down into the resource.
*/
RB.Config.ResourceListItem = Djblets.Config.ListItem.extend({
defaults: _.defaults({
resource: null
}, Djblets.Config.ListItem.prototype.defaults),
/* A list of attributes synced between the ListItem and the Resource. */
syncAttrs: [],
/*
* Initializes the list item.
*
* This will begin listening for events on the resource, updating
* the state of the icon based on changes.
*/
initialize: function(options) {
var resource = this.get('resource');
if (resource) {
this.set(_.pick(resource.attributes, this.syncAttrs));
} else {
/*
* Create a resource using the attributes provided to this list
* item.
*/
resource = this.createResource(_.extend(
{
id: this.get('id')
},
_.pick(this.attributes, this.syncAttrs)));
this.set('resource', resource);
}
this.resource = resource;
Djblets.Config.ListItem.prototype.initialize.call(this, options);
/* Forward on a couple events we want the caller to see. */
this.listenTo(resource, 'request', function() {
this.trigger('request');
});
this.listenTo(resource, 'sync', function() {
this.trigger('sync');
});
/* Destroy this item when the resource is destroyed. */
this.listenTo(resource, 'destroy', this.destroy);
/*
* Listen for each synced attribute change so we can update this
* list item.
*/
_.each(this.syncAttrs, function(attr) {
this.listenTo(resource, 'change:' + attr, function(model, value) {
this.set(attr, value);
});
}, this);
},
/*
* Creates the Resource for this list item, with the given attributes.
*/
createResource: function(attrs) {
console.assert(false, 'createResource must be implemented');
},
/*
* Destroys the list item.
*
* This will just emit the 'destroy' signal. It is typically called when
* the resource itself is destroyed.
*/
destroy: function(options) {
this.stopListening(this.resource);
this.trigger('destroy', this, this.collection, options);
if (options && options.success) {
options.success(this, null, options);
}
}
});
|
// Karma configuration
let isPhantomJSInstalled = false;
const webpackConfig = require('./webpack.config.test');
try {
require.resolve('karma-phantomjs-launcher');
isPhantomJSInstalled = true;
} catch (e) {
}
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'spec.config.js',
],
// list of files to exclude
exclude: [],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'spec.config.js': ['webpack', 'sourcemap'],
},
webpack: webpackConfig,
webpackMiddleware: {
stats: 'true',
},
webpackServer: {
noInfo: true, //please don’t spam the console when running in karma!
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['nyan', 'coverage-istanbul'],
coverageIstanbulReporter: {
reports: ['html', 'text'],
dir: './test/coverage',
fixWebpackSourcePaths: true,
check: {
global: {
statements: 95,
branches: 95,
functions: 95,
lines: 95,
},
},
watermarks: {
statements: [80, 95],
functions: [80, 95],
branches: [80, 95],
lines: [80, 95],
},
},
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: false,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: [isPhantomJSInstalled ? 'PhantomJS' : 'Chrome'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: true,
// Concurrency level
// how many browser should be started simultaneous
concurrency: Infinity,
plugins: [
'karma-webpack',
'karma-sourcemap-loader',
'karma-coverage-istanbul-reporter',
'karma-nyan-reporter',
'karma-jasmine',
'karma-chrome-launcher',
'karma-phantomjs-launcher',
],
});
};
|
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
passport = require('passport'),
User = mongoose.model('User'),
Applicant = mongoose.model('Applicant'),
Bootcamp = mongoose.model('Bootcamp'),
Placement = mongoose.model('Placement'),
Test = mongoose.model('Test'),
_ = require('lodash');
var admin = require('../../app/controllers/admin');
var uuid = require('node-uuid'),
multiparty = require('multiparty'),
async = require('async');
var path = require('path'),
fs = require('fs');
/**
* Get the error message from error object
*/
var getErrorMessage = function(err) {
var message = '';
if (err.code) {
switch (err.code) {
case 11000:
case 11001:
message = 'Username already exists';
break;
default:
message = 'Something went wrong';
}
} else {
for (var errName in err.errors) {
if (err.errors[errName].message) message = err.errors[errName].message;
}
}
return message;
};
/**
* CV Upload
*
*/
var uploadCV = function(req, res, contentType, tmpPath, destPath, user) {
// Server side file type checker.
if (contentType !== 'application/msword' && contentType !== 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' && contentType !== 'application/pdf') {
fs.unlink(tmpPath);
res.send(415, {
message: 'Unsupported file type. Only support .pdf and .docx'
});
} else
async.waterfall([
function(callback) {
fs.readFile(tmpPath, function(err, data) {
if (err) {
var message = 'tmpPath doesn\'t exist.';
return callback(message);
}
callback(null, data);
});
},
function(data, callback) {
fs.writeFile(destPath, data, function(err) {
if (err) {
var message = 'Destination path doesn\'t exists';
return callback(message);
}
callback();
});
},
function(callback) {
fs.unlink(tmpPath);
}
],
function(err, results) {
if (err) {
res.send(500, {
message: err
});
}
}
);
};
var userSignup = function(req, res, user, destPath) {
if (user.role === 'applicant') {
user = new Applicant(user);
user.campId = req.camp._id;
user.cvPath = destPath;
var message = null;
user.provider = 'local';
req.camp.applicants.push(user);
user.status.name = 'pending';
user.status.reason = '';
return user;
}
return false;
};
exports.signup = function(req, res) {
//Parse Form
var form = new multiparty.Form();
form.parse(req, function(err, fields, files) {
if (err) {
res.send(500, {
message: err
});
}
if (files.file[0]) {
//if there is a file do upload
var file = files.file[0];
var contentType = file.headers['content-type'];
var tmpPath = file.path;
var extIndex = tmpPath.lastIndexOf('.');
var extension = (extIndex < 0) ? '' : tmpPath.substr(extIndex);
// uuid is for generating unique filenames.
var fileName = uuid.v4() + extension,
destPath = 'public/modules/core/img/server/Temp/' + fileName;
}
var user = {
firstName: fields.firstName[0],
lastName: fields.lastName[0],
password: fields.password[0],
email: fields.email[0],
username: fields.username[0],
testScore: fields.testScore[0],
role: fields.type[0]
};
user = userSignup(req, res, user, destPath);
if (!user)
return;
req.camp.save(function(err) {
if (err) {
res.send(500, {
message: err
});
} else {
user.save(function(err) {
if (err) {
res.send(500, {
message: err
});
} else {
uploadCV(req, res, contentType, tmpPath, destPath, user);
req.login(user, function(err) {
if (err) {
res.send(500, err);
} else {
user.password = undefined;
user.salt = undefined;
res.jsonp(user);
}
});
}
});
}
});
});
};
/**
* Signin after passport authentication
*/
exports.signin = function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err || !user) {
res.send(400, info);
} else {
// Remove sensitive data before login
user.password = undefined;
user.salt = undefined;
req.login(user, function(err) {
if (err) {
res.send(400, err);
} else {
res.jsonp(user);
}
});
}
})(req, res, next);
};
/**
* Check unique username
*/
exports.uniqueUsername = function(req, res) {
User.find().where({
username: req.body.username
}).exec(function(err, user) {
if (err) {
res.send(500, {
message: err
});
} else if (!user) {
res.send(401, {
message: 'unknown user'
});
} else {
res.jsonp(user);
}
});
};
/**
* Update user details
*/
exports.update = function(req, res) {
// Init Variables
var user = req.user;
var message = null;
// For security measurement we remove the roles from the req.body object
delete req.body.roles;
if (user) {
// Merge existing user
user = _.extend(user, req.body);
user.updated = Date.now();
user.displayName = user.firstName + ' ' + user.lastName;
user.save(function(err) {
if (err) {
return res.send(500, {
message: getErrorMessage(err)
});
} else {
req.login(user, function(err) {
if (err) {
res.send(500, err);
} else {
res.jsonp(user);
}
});
}
});
} else {
res.send(401, {
message: 'Unknown user'
});
}
};
exports.adminUpdate = function(req, res) {
// Init Variables
var user = req.profile;
var message = null;
// For security measurement we remove the roles from the req.body object
delete req.body.roles;
if (user) {
// Merge existing user
user = _.extend(user, req.body);
user.updated = Date.now();
user.displayName = user.firstName + ' ' + user.lastName;
user.save(function(err) {
if (err) {
res.send(500, {
message: getErrorMessage(err)
});
} else {
res.jsonp(user);
}
});
} else {
res.send(500, {
message: 'User update failed'
});
}
};
exports.getCamp = function(req, res) {
res.jsonp(req.camp);
};
exports.getCamps = function(req, res) {
Bootcamp.find().sort('-start_date').exec(function(err, bootcamps) {
if (err) {
res.send(500, {
message: getErrorMessage(err)
});
} else {
res.jsonp(bootcamps);
}
});
};
exports.list = function(req, res) {
Applicant.find().where({
role: 'fellow'
}).populate('user', 'displayName').exec(function(err, fellows) {
if (err) {
res.send(500, {
message: getErrorMessage(err)
});
} else {
res.jsonp(fellows);
}
});
};
// viewing Applicants data page
exports.applicantView = function(req, res, id) {
var user = req.user;
var message = null;
id = req.user._id;
if (user) {
User.findById(id).populate('user', 'displayName').exec(function(err, users) {
if (err) {
res.send(500, {
message: getErrorMessage(err)
});
} else {
req.login(user, function(err) {
if (err) {
res.send(500, err);
} else {
res.jsonp(users);
}
});
}
});
} else {
res.send(400, {
message: 'You need to Sign in to view your application progress'
});
}
};
/**
* Change Password
*/
exports.changePassword = function(req, res, next) {
// Init Variables
var passwordDetails = req.body;
var message = null;
if (req.user) {
User.findById(req.user.id, function(err, user) {
if (!err && user) {
if (user.authenticate(passwordDetails.currentPassword)) {
if (passwordDetails.newPassword === passwordDetails.verifyPassword) {
user.password = passwordDetails.newPassword;
user.save(function(err) {
if (err) {
return res.send(400, {
message: getErrorMessage(err)
});
} else {
req.login(user, function(err) {
if (err) {
res.send(400, err);
} else {
res.send({
message: 'Password changed successfully'
});
}
});
}
});
} else {
res.send(400, {
message: 'Passwords do not match'
});
}
} else {
res.send(400, {
message: 'Current password is incorrect'
});
}
} else {
res.send(400, {
message: 'User is not found'
});
}
});
} else {
res.send(400, {
message: 'User is not signed in'
});
}
};
/**
* Signout
*/
exports.signout = function(req, res) {
req.logout();
res.redirect('/');
};
/**
* Send User
*/
exports.me = function(req, res) {
res.jsonp(req.user || null);
};
/**
* OAuth callback
*/
exports.oauthCallback = function(strategy) {
return function(req, res, next) {
passport.authenticate(strategy, function(err, user, redirectURL) {
if (err || !user) {
return res.redirect('/#!/signin');
}
req.login(user, function(err) {
if (err) {
return res.redirect('/#!/signin');
}
return res.redirect(redirectURL || '/');
});
})(req, res, next);
};
};
/**
* User middleware
*/
exports.userByID = function(req, res, next, id) {
Applicant.findById(id).populate('placements').sort('-placements.end_date').exec(function(err, user) {
if (err) return next(err);
if (!user) return next(new Error('Failed to load User ' + id));
Placement.populate(user.placements, {
path: 'placement'
},
function(err, data) {
req.profile = user;
next();
}
);
});
};
exports.read = function(req, res) {
res.jsonp(req.profile);
};
exports.requiresLogin = function(req, res, next) {
if (!req.isAuthenticated()) {
return res.send(401, {
message: 'User is not logged in'
});
}
next();
};
/**
* User authorizations routing middleware
*/
exports.hasAuthorization = function(roles) {
var _this = this;
return function(req, res, next) {
_this.requiresLogin(req, res, function() {
if (_.intersection(req.user.roles, roles).length) {
return next();
} else {
return res.send(403, {
message: 'User is not authorized'
});
}
});
};
};
/**
* Helper function to save or update a OAuth user profile
*/
exports.saveOAuthUserProfile = function(req, providerUserProfile, done) {
if (!req.user) {
// Define a search query fields
var searchMainProviderIdentifierField = 'providerData.' + providerUserProfile.providerIdentifierField;
var searchAdditionalProviderIdentifierField = 'additionalProvidersData.' + providerUserProfile.provider + '.' + providerUserProfile.providerIdentifierField;
// Define main provider search query
var mainProviderSearchQuery = {};
mainProviderSearchQuery.provider = providerUserProfile.provider;
mainProviderSearchQuery[searchMainProviderIdentifierField] = providerUserProfile.providerData[providerUserProfile.providerIdentifierField];
// Define additional provider search query
var additionalProviderSearchQuery = {};
additionalProviderSearchQuery[searchAdditionalProviderIdentifierField] = providerUserProfile.providerData[providerUserProfile.providerIdentifierField];
// Define a search query to find existing user with current provider profile
var searchQuery = {
$or: [mainProviderSearchQuery, additionalProviderSearchQuery]
};
User.findOne(searchQuery, function(err, user) {
if (err) {
return done(err);
} else {
if (!user) {
var possibleUsername = providerUserProfile.username || ((providerUserProfile.email) ? providerUserProfile.email.split('@')[0] : '');
User.findUniqueUsername(possibleUsername, null, function(availableUsername) {
user = new User({
firstName: providerUserProfile.firstName,
lastName: providerUserProfile.lastName,
username: availableUsername,
displayName: providerUserProfile.displayName,
email: providerUserProfile.email,
provider: providerUserProfile.provider,
providerData: providerUserProfile.providerData
});
// And save the user
user.save(function(err) {
return done(err, user);
});
});
} else {
return done(err, user);
}
}
});
} else {
// User is already logged in, join the provider data to the existing user
var user = req.user;
// Check if user exists, is not signed in using this provider, and doesn't have that provider data already configured
if (user.provider !== providerUserProfile.provider && (!user.additionalProvidersData || !user.additionalProvidersData[providerUserProfile.provider])) {
// Add the provider data to the additional provider data field
if (!user.additionalProvidersData) user.additionalProvidersData = {};
user.additionalProvidersData[providerUserProfile.provider] = providerUserProfile.providerData;
// Then tell mongoose that we've updated the additionalProvidersData field
user.markModified('additionalProvidersData');
// And save the user
user.save(function(err) {
return done(err, user, '/#!/settings/accounts');
});
} else {
return done(new Error('User is already connected using this provider'), user);
}
}
};
/**
* Remove OAuth provider
*/
exports.removeOAuthProvider = function(req, res, next) {
var user = req.user;
var provider = req.param('provider');
if (user && provider) {
// Delete the additional provider
if (user.additionalProvidersData[provider]) {
delete user.additionalProvidersData[provider];
// Then tell mongoose that we've updated the additionalProvidersData field
user.markModified('additionalProvidersData');
}
user.save(function(err) {
if (err) {
return res.send(400, {
message: getErrorMessage(err)
});
} else {
req.login(user, function(err) {
if (err) {
res.send(400, err);
} else {
res.jsonp(user);
}
});
}
});
}
};
|
var searchData=
[
['kernelradius',['KernelRadius',['../class_cubby_flow_1_1_s_p_h_system_data.html#a9675f75fb92eddeccb69797d47dab79d',1,'CubbyFlow::SPHSystemData']]],
['keys',['Keys',['../class_cubby_flow_1_1_point_parallel_hash_grid_searcher.html#adf5e8674df562e3c89fc65e999dd038e',1,'CubbyFlow::PointParallelHashGridSearcher']]]
];
|
// Generated by CoffeeScript 1.3.3
(function() {
var AngelNode;
AngelNode = module.exports = {
auth: require('./angelnode/auth'),
client: require('./angelnode/client')
};
}).call(this);
|
const pg = require('pg');
const fs = require('fs');
// For loading evaluation data from the playtest into the same store.
// First, dump the playtest database to disk.
// Then use this to load it into another database.
// This assumes evidence ids are consistent across databases.
// read db config from disk
const databaseConfig = JSON.parse(fs.readFileSync('./tmp/threeflows_database_config.json'));
// helper for db connection pooling
function queryDatabase(text, values, cb) {
pg.connect(databaseConfig, function(err, client, done) {
if (err) console.log({err});
client.query(text, values, function(err, result) {
done();
cb(err, result);
});
});
}
// read dump from disk
function readAllEvaluations(callback) {
const results = JSON.parse(fs.readFileSync('./tmp/playtest_evaluations.json'));
callback(null, results);
}
// throws away the database-local evaluation id, but relies on the evidence ids
// being consistent across DBs
function insertEvaluation(evaluationRow, callback) {
console.log('inserting...');
console.log(evaluationRow);
const {app, type, version, timestamp, json} = evaluationRow;
const values = [app, type, version, timestamp, json];
const sql = `INSERT INTO evaluations (app, type, version, timestamp, json) VALUES ($1,$2,$3,$4,$5);`;
console.log('sql:', sql);
console.log('values:', values);
queryDatabase(sql, values, callback);
}
function insertEach(rows, callback) {
rows.forEach((evaluationRow) => {
insertEvaluation(evaluationRow, (err, result) => {
if (err) return callback(err);
console.log('Inserted.');
callback(null, result);
});
});
}
function main() {
readAllEvaluations((err, result) => {
if (err) return console.log({err});
const rows = result.rows;
var remaining = rows.length;
console.log(`Read ${rows.length} rows.`);
insertEach(rows, (err, result) => {
remaining--;
console.log('.');
if (err) return console.log({err});
if (remaining === 0) {
console.log('Done.');
process.exit(0); // eslint-disable-line no-process-exit
}
});
});
}
main(); |
const visibilityFilter = (state = 'SHOW_ACTIVE', action) => {
switch (action.type) {
case 'SET_VISIBILITY_FILTER':
return action.filter
default:
return state
}
}
export default visibilityFilter
|
var Unhyphenator = (function () {
"use strict";
var shy = /(?:\u00AD|\­|\­)/g;
var zws = /(?:\u200B|\​)/g;
var shyFilter = function (text) {
return text.replace(shy, '');
};
var zwsFilter = function (text) {
return text.replace(zws, '');
};
function Unhyphenator(filters) {
if (!filters) filters = [shyFilter, zwsFilter];
var self = this;
this.shy = shy;
this.boundHandler = function (ev) {
self.handler(ev, filters);
};
}
// Active the handler.
Unhyphenator.prototype.start = function (el) {
el = el || document.body;
if (window.addEventListener) {
el.addEventListener("copy", this.boundHandler, true);
} else {
el.attachEvent("oncopy", this.boundHandler);
}
};
// Deactivate the handler.
Unhyphenator.prototype.stop = function (el) {
el = el || document.body;
if (window.removeEventListener) {
el.removeEventListener("copy", this.boundHandler, true);
} else {
el.detachEvent("oncopy", this.boundHandler);
}
};
// Build the handler.
Unhyphenator.prototype.handler = function (e, filters) {
var i;
var target = e.target || e.srcElement,
document = target.ownerDocument,
body = document.body,
window = document.defaultView || document.parentWindow;
var shadow = document.createElement("div");
// Make the shadow invisible.
var shadowColor = window.getComputedStyle ?
window.getComputedStyle(body, null) :
"#FFFFFF";
shadow.style.color = shadowColor;
shadow.style.fontsize = '0px';
body.appendChild(shadow);
var sel, range;
if (window.getSelection !== undefined) {
e.stopPropagation();
sel = window.getSelection();
range = sel.getRangeAt(0);
shadow.appendChild(range.cloneContents());
for (i = 0; i<filters.length; i++)
shadow.innerHTML = filters[i](shadow.innerHTML);
sel.selectAllChildren(shadow);
window.setTimeout(function () {
shadow.parentNode.removeChild(shadow);
//sel.removeAllRanges(); // IE
sel.addRange(range);
}, 0);
} else { // IE
sel = document.selection;
range = sel.createRange();
for (i = 0; i<filters.length; i++)
shadow.innerHTML = filters[i](range.htmlText);
var range2 = body.createTextRange();
range2.moveToElementText(shadow);
range2.select();
window.setTimeout (function () {
shadow.parentNode.removeChild(shadow);
if (range.text) {
range.select();
}
}, 0);
}
};
return Unhyphenator;
})();
|
var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create });
function preload () {
game.load.script('webcam', '../plugins/WebCam.js');
}
var webcam;
var bmd;
var sprite;
function create () {
webcam = game.plugins.add(Phaser.Plugin.Webcam);
bmd = game.make.bitmapData(800, 600);
sprite = bmd.addToWorld();
webcam.start(800, 600, bmd.context);
game.input.onDown.addOnce(takePicture, this);
}
function takePicture () {
webcam.stop();
// bmd.context now contains your webcam image
sprite.tint = Math.random() * 0xff0000;
}
|
//Write a function that flattens an Array of Array objects into a flat Array. Your function must only do one level of flattening.
//
//flatten([1,2,3]) // => [1,2,3]
//flatten([[1,2,3],["a","b","c"],[1,2,3]]) // => [1,2,3,"a","b","c",1,2,3]
//flatten([[[1,2,3]]]) // => [[1,2,3]]
//solution 1
function flatten(array) {
var flattened = [];
for(var i = 0, len = array.length; i < len; i++){
if(array[i] instanceof Array) {
for(var j = 0, innerLen = array[i].length; j < innerLen; j++) {
flattened.push(array[i][j]);
}
} else {
flattened.push(array[i]);
}
}
return flattened;
}
function flatten(arr) {
var flat = [];
for(var key in arr) {
flat = flat.concat(arr[key]);
}
return flat;
} |
function Pen(canvasID, radius, posX, posY, speed, color) {
var self = this;
var positionAngle = -Math.PI / 2;
var increment = 0.005;
var canvas = document.getElementById(canvasID);
var context = canvas.getContext("2d");
var distance = Math.sqrt(Math.pow(posX, 2) + Math.pow(posY, 2));
var angle = Math.atan2(posY, posX);
var stop = false;
context.clearRect(0, 0, canvas.clientWidth, canvas.clientHeight);
self.Draw = function () {
for (var i = 0; i < speed; i++) {
positionAngle = rotate(positionAngle, increment);
angle = rotate(angle, -increment * 250 / radius);
self.center = polar({ x: 250, y: 250 }, positionAngle, 250 - radius);
var point = polar(self.center, angle, distance);
if (color != undefined) { context.fillStyle = color; } else { context.fillStyle = "black"; }
if (!stop) {
context.fillRect(point.x, point.y, 1, 1);
}
}
if (!stop) {
requestAnimationFrame(self.Draw);
}
};
self.Stop = function () {
stop = true;
};
requestAnimationFrame(self.Draw);
} |
const each = require('lodash/each');
const upperFirst = require('lodash/upperFirst');
const toArray = require('lodash/toArray');
const isObject = require('lodash/isObject');
const isEmpty = require('lodash/isEmpty');
const includes = require('lodash/includes');
const bunyan = require('bunyan');
const fs = require('fs-extra');
const jsonStringifySafe = require('json-stringify-safe');
const GhostPrettyStream = require('./PrettyStream');
/**
* @description Ghost's logger class.
*
* The logger handles any stdout/stderr logs and streams it into the configured transports.
*/
class GhostLogger {
constructor(options) {
options = options || {};
this.name = options.name || 'Log';
this.env = options.env || 'development';
this.domain = options.domain || 'localhost';
this.transports = options.transports || ['stdout'];
this.level = process.env.LEVEL || options.level || 'info';
this.logBody = options.logBody || false;
this.mode = process.env.MODE || options.mode || 'short';
this.path = options.path || process.cwd();
this.loggly = options.loggly || {};
this.elasticsearch = options.elasticsearch || {};
this.gelf = options.gelf || {};
// CASE: stdout has to be on the first position in the transport, because if the GhostLogger itself logs, you won't see the stdout print
if (this.transports.indexOf('stdout') !== -1 && this.transports.indexOf('stdout') !== 0) {
this.transports.splice(this.transports.indexOf('stdout'), 1);
this.transports = ['stdout'].concat(this.transports);
}
// CASE: special env variable to enable long mode and level info
if (process.env.LOIN) {
this.level = 'info';
this.mode = 'long';
}
// CASE: ensure we have a trailing slash
if (!this.path.match(/\/$|\\$/)) {
this.path = this.path + '/';
}
this.rotation = options.rotation || {
enabled: false,
period: '1w',
count: 100
};
this.streams = {};
this.setSerializers();
if (includes(this.transports, 'stderr') && !includes(this.transports, 'stdout')) {
this.transports.push('stdout');
}
this.transports.forEach((transport) => {
let transportFn = `set${upperFirst(transport)}Stream`;
if (!this[transportFn]) {
throw new Error(`${upperFirst(transport)} is an invalid transport`);
}
this[transportFn]();
});
}
/**
* @description Setup stdout stream.
*/
setStdoutStream() {
let prettyStdOut = new GhostPrettyStream({
mode: this.mode
});
prettyStdOut.pipe(process.stdout);
this.streams.stdout = {
name: 'stdout',
log: bunyan.createLogger({
name: this.name,
streams: [{
type: 'raw',
stream: prettyStdOut,
level: this.level
}],
serializers: this.serializers
})
};
}
/**
* @description Setup stderr stream.
*/
setStderrStream() {
let prettyStdErr = new GhostPrettyStream({
mode: this.mode
});
prettyStdErr.pipe(process.stderr);
this.streams.stderr = {
name: 'stderr',
log: bunyan.createLogger({
name: this.name,
streams: [{
type: 'raw',
stream: prettyStdErr,
level: 'error'
}],
serializers: this.serializers
})
}
}
/**
* @description Setup loggly.
*/
setLogglyStream() {
const Bunyan2Loggly = require('bunyan-loggly');
let logglyStream = new Bunyan2Loggly({
token: this.loggly.token,
subdomain: this.loggly.subdomain,
tags: this.loggly.tags
});
this.streams.loggly = {
name: 'loggly',
match: this.loggly.match,
log: bunyan.createLogger({
name: this.name,
streams: [{
type: 'raw',
stream: logglyStream,
level: 'error'
}],
serializers: this.serializers
})
};
}
/**
* @description Setup ElasticSearch.
*/
setElasticsearchStream() {
const ElasticSearch = require('@tryghost/elasticsearch-bunyan');
const elasticStream = new ElasticSearch({
node: this.elasticsearch.host,
auth: {
username: this.elasticsearch.username,
password: this.elasticsearch.password
}
}, {
index: this.elasticsearch.index,
pipeline: this.elasticsearch.pipeline
});
this.streams.elasticsearch = {
name: 'elasticsearch',
log: bunyan.createLogger({
name: this.name,
streams: [{
type: 'raw',
stream: elasticStream,
level: this.elasticsearch.level
}],
serializers: this.serializers
})
};
}
/**
* @description Setup gelf.
*/
setGelfStream() {
const gelfStream = require('gelf-stream');
let stream = gelfStream.forBunyan(
this.gelf.host || 'localhost',
this.gelf.port || 12201,
this.gelf.options || {}
);
this.streams.gelf = {
name: 'gelf',
log: bunyan.createLogger({
name: this.name,
streams: [{
type: 'raw',
stream: stream,
level: this.level
}],
serializers: this.serializers
})
};
}
/**
* @description Setup file stream.
*
* By default we log into two files
* 1. file-errors: all errors only
* 2. file-all: everything
*/
setFileStream() {
// e.g. http://my-domain.com --> http___my_domain_com
let sanitizedDomain = this.domain.replace(/[^\w]/gi, '_');
// CASE: target log folder does not exist, show warning
if (!fs.pathExistsSync(this.path)) {
this.error('Target log folder does not exist: ' + this.path);
return;
}
if (this.rotation.enabled) {
if (this.rotation.useLibrary) {
const RotatingFileStream = require('@tryghost/bunyan-rotating-filestream');
const rotationConfig = {
path: `${this.path}${sanitizedDomain}_${this.env}.log`,
period: this.rotation.period,
threshold: this.rotation.threshold,
totalFiles: this.rotation.count,
gzip: this.rotation.gzip,
rotateExisting: (typeof this.rotation.rotateExisting === 'undefined') ? this.rotation.rotateExisting : true
};
this.streams['rotation-errors'] = {
name: 'rotation-errors',
log: bunyan.createLogger({
name: this.name,
streams: [{
stream: new RotatingFileStream(Object.assign({}, rotationConfig, {
path: `${this.path}${sanitizedDomain}_${this.env}.error.log`
})),
level: 'error'
}],
serializers: this.serializers
})
};
this.streams['rotation-all'] = {
name: 'rotation-all',
log: bunyan.createLogger({
name: this.name,
streams: [{
stream: new RotatingFileStream(rotationConfig),
level: this.level
}],
serializers: this.serializers
})
};
} else {
// TODO: Remove this when confidence is high in the external library for rotation
this.streams['rotation-errors'] = {
name: 'rotation-errors',
log: bunyan.createLogger({
name: this.name,
streams: [{
type: 'rotating-file',
path: `${this.path}${sanitizedDomain}_${this.env}.error.log`,
period: this.rotation.period,
count: this.rotation.count,
level: "error"
}],
serializers: this.serializers
})
};
this.streams['rotation-all'] = {
name: 'rotation-all',
log: bunyan.createLogger({
name: this.name,
streams: [{
type: 'rotating-file',
path: `${this.path}${sanitizedDomain}_${this.env}.log`,
period: this.rotation.period,
count: this.rotation.count,
level: this.level
}],
serializers: this.serializers
})
};
}
} else {
this.streams['file-errors'] = {
name: 'file',
log: bunyan.createLogger({
name: this.name,
streams: [{
path: `${this.path}${sanitizedDomain}_${this.env}.error.log`,
level: 'error'
}],
serializers: this.serializers
})
};
this.streams['file-all'] = {
name: 'file',
log: bunyan.createLogger({
name: this.name,
streams: [{
path: `${this.path}${sanitizedDomain}_${this.env}.log`,
level: this.level
}],
serializers: this.serializers
})
};
}
}
// @TODO: res.on('finish') has no access to the response body
/**
* @description Serialize the log input.
*
* The goals are:
* - avoiding to log to much (pick useful information from request/response
* - removing/replacing sensitive data from logging to a stream/transport
*/
setSerializers() {
this.serializers = {
req: (req) => {
const requestLog = {
meta: {
requestId: req.requestId,
userId: req.userId
},
url: req.url,
method: req.method,
originalUrl: req.originalUrl,
params: req.params,
headers: this.removeSensitiveData(req.headers),
query: this.removeSensitiveData(req.query)
};
if (req.extra) {
requestLog.extra = req.extra;
}
if (this.logBody) {
requestLog.body = this.removeSensitiveData(req.body);
}
return requestLog;
},
res: (res) => {
return {
_headers: this.removeSensitiveData(res.getHeaders()),
statusCode: res.statusCode,
responseTime: res.responseTime
};
},
err: (err) => {
return {
id: err.id,
domain: this.domain,
code: err.code,
name: err.errorType,
statusCode: err.statusCode,
level: err.level,
message: err.message,
context: jsonStringifySafe(err.context),
help: jsonStringifySafe(err.help),
stack: err.stack,
hideStack: err.hideStack,
errorDetails: jsonStringifySafe(err.errorDetails)
};
}
};
}
/**
* @description Remove sensitive data.
* @param {Object} obj
*/
removeSensitiveData(obj) {
let newObj = {};
each(obj, (value, key) => {
try {
if (isObject(value)) {
value = this.removeSensitiveData(value);
}
if (key.match(/pin|password|pass|key|authorization|bearer|cookie/gi)) {
newObj[key] = '**REDACTED**'
}
else {
newObj[key] = value;
}
} catch (err) {
newObj[key] = value;
}
});
return newObj;
}
/**
* @description Centralised log function.
*
* Arguments can contain lot's of different things, we prepare the arguments here.
* This function allows us to use logging very flexible!
*
* logging.info('HEY', 'DU') --> is one string
* logging.info({}, {}) --> is one object
* logging.error(new Error()) --> is {err: new Error()}
*/
log(type, args) {
let modifiedMessages = [];
let modifiedObject = {};
let modifiedArguments = [];
each(args, function (value) {
if (value instanceof Error) {
modifiedObject.err = value;
} else if (isObject(value)) {
each(Object.keys(value), function (key) {
modifiedObject[key] = value[key];
});
} else {
modifiedMessages.push(value);
}
});
if (!isEmpty(modifiedObject)) {
if (modifiedObject.err) {
modifiedMessages.push(modifiedObject.err.message);
}
modifiedArguments.push(modifiedObject);
}
modifiedArguments.push(...modifiedMessages);
each(this.streams, (logger) => {
// If we have both a stdout and a stderr stream, don't log errors to stdout
// because it would result in duplicate logs
if (type === 'error' && logger.name === 'stdout' && includes(this.transports, 'stderr')) {
return;
}
/**
* @NOTE
* Only `loggly` offers the `match` option.
* And currently `loggly` is by default configured to only send errors (not configureable).
* e.g. level info would get ignored.
*
* @NOTE
* The `match` feature is not completed. We hardcode checking if the level/type is `error` for now.
* Otherwise each `level:info` would has to run through the matching logic.
*
* @NOTE
* Matching a string in the whole req/res object massively slows down the process, because it's a sync
* operation.
*
* If we want to extend the feature, we can only offer matching certain keys e.g. status code, headers.
* If we want to extend the feature, we have to do proper performance testing.
*
* `jsonStringifySafe` can match a string in an object, which has circular dependencies.
* https://github.com/moll/json-stringify-safe
*/
if (logger.match && type === 'error') {
if (new RegExp(logger.match).test(jsonStringifySafe(modifiedArguments[0].err || null).replace(/"/g, ''))) {
logger.log[type](...modifiedArguments);
}
} else {
logger.log[type](...modifiedArguments);
}
});
}
trace() {
this.log('trace', toArray(arguments));
}
debug() {
this.log('debug', toArray(arguments));
}
info() {
this.log('info', toArray(arguments));
}
warn() {
this.log('warn', toArray(arguments));
}
error() {
this.log('error', toArray(arguments));
}
fatal() {
this.log('fatal', toArray(arguments));
}
/**
* @description Creates a child of the logger with some properties bound for every log message
*/
child(boundProperties) {
const result = new GhostLogger({
name: this.name,
env: this.env,
domain: this.domain,
transports: [],
level: this.level,
logBody: this.logBody,
mode: this.mode,
});
result.streams = Object.keys(this.streams).reduce((acc, id) => {
acc[id] = {
name: this.streams[id].name,
log: this.streams[id].log.child(boundProperties)
};
return acc
}, {});
return result;
}
}
module.exports = GhostLogger;
|
import C from './constant';
export default class Pomodoro {
constructor(config) {
this.config = config;
this.nPomodoro = 1;
this.stage = undefined;
this.second = undefined;
this.intervalID = undefined;
}
isRunning() {
return !!this.intervalID;
}
start() {
this._start(C.Stage.Pomodoro, this.config.pomodoroMin);
}
pause() {
if (!!this.intervalID) {
clearInterval(this.intervalID);
}
this.intervalID = undefined;
}
resume() {
if (!this.intervalID) {
this.intervalID = setInterval(this._tick.bind(this), 1000);
}
}
reset() {
if (!!this.intervalID) {
clearInterval(this.intervalID);
}
this.nPomodoro = 1;
this.stage = undefined;
this.intervalID = undefined;
this.second = undefined;
this._updateBadge();
}
_start(stage, min) {
if (stage === C.Stage.Pomodoro) {
this.nPomodoro++;
}
this.stage = stage;
this.second = min * 60;
if (!!this.intervalID) {
clearInterval(this.intervalID);
}
this._updateBadge();
this.intervalID = setInterval(this._tick.bind(this), 1000);
}
_updateBadge() {
const color = this.stage === C.Stage.Pomodoro ? '#ff0000' : '#00cc00';
chrome.browserAction.setBadgeBackgroundColor({ color });
if (this.second > 60) {
const min = Math.floor(this.second / 60);
chrome.browserAction.setBadgeText({ text: min + 'm' });
} else if (0 < this.second && this.second <= 60) {
chrome.browserAction.setBadgeText({ text: this.second + 's' });
} else {
chrome.browserAction.setBadgeText({ text: '' });
}
}
_tick() {
this.second -= 1;
this._updateBadge();
if (this.second <= 0) {
this._doNext();
}
}
_doNext() {
if (this.stage === C.Stage.Pomodoro) {
if (this.nPomodoro % this.config.longBreakEvery === 0) {
this._postNotification("starting long break...");
this._start(C.Stage.LongBreak, this.config.longBreakMin);
} else {
this._postNotification("starting short break...");
this._start(C.Stage.ShortBreak, this.config.shortBreakMin);
}
} else if (this.stage === C.Stage.ShortBreak
|| this.stage === C.Stage.LongBreak) {
this._postNotification("starting pomodoro: " + this.nPomodoro + "...");
this._start(C.Stage.Pomodoro, this.config.pomodoroMin);
}
}
_postNotification(message) {
if (this.config.notificationType === C.NotificationType.None) {
// nothing to do.
} else if (this.config.notificationType === C.NotificationType.NotificationDissappear) {
// TODO
} else if (this.config.notificationType === C.NotificationType.NotificationDissappear) {
// TODO
} else if (this.config.notificationType === C.NotificationType.Alert) {
chrome.windows.getCurrent((window) => {
chrome.windows.update(window.id, { focused: true }, (window) => {
alert(message);
});
});
}
}
}
|
const bodyParser = require('body-parser');
const express = require('express');
const { graphqlExpress, graphiqlExpress } = require('apollo-server-express');
const PORT = process.env.PORT || 3001;
const app = express();
const graphQLSchema = require('./graphql/executableSchema');
app.use('/graphql', bodyParser.json(), graphqlExpress({ schema: graphQLSchema }));
app.use('/graphiql', graphiqlExpress({ endpointURL: '/graphql' }));
app.listen(PORT);
|
/**
* Middleware to support `type` property in an action's inputs definition
*
* @Author: Guan Gui <guiguan>
* @Date: 2016-08-29T13:41:40+10:00
* @Email: root@guiguan.net
* @Last modified by: guiguan
* @Last modified time: 2016-08-30T16:59:18+10:00
*/
module.exports = {
initialize: function(api, next) {
// set action middleware
var middleware = {
name: 'ah-swagger-material-ui',
global: true,
preProcessor: function(data, next) {
var inputs = data.actionTemplate.inputs;
for (var p of Object.keys(inputs)) {
var input = inputs[p];
if (!input.hasOwnProperty('formatter') && input.hasOwnProperty('type') && data.params.hasOwnProperty(p) && (typeof data.params[p] !== input.type)) {
console.log(input.type);
switch (input.type) {
case 'string':
{
data.params[p] = String(data.params[p]);
return next();
}
case 'boolean':
{
var param = data.params[p];
if (typeof param === 'string') {
data.params[p] = param === 'true';
} else {
data.params[p] = Boolean(param);
}
return next();
}
case 'number':
{
data.params[p] = Number(data.params[p]);
return next();
}
case 'object':
{
data.params[p] = Object(data.params[p]);
return next();
}
default:
return next(new Error('Unsupported param type: ' + input.type));
}
}
}
next();
}
}
api.actions.addMiddleware(middleware);
next();
}
};
|
// this is necessary because node doesn't has await and async keywords included
const async = require('asyncawait/async');
const await = require('asyncawait/await');
const url = require('./modules/url');
const Parser = require('./modules/parser');
const downloader = require('./modules/downloader');
const getMenuForCurrentWeek = async(() => {
const menuUrl = url.getMenuURLForCurrentWeek();
const file = await(downloader.getFile(menuUrl));
const parser = new Parser(file);
const menu = await(parser.getMenu());
return menu;
});
module.exports = {
getMenuForCurrentWeek
}
|
'use strict'
module.exports = (babel, options, dirname) => {
const value = babel.types.objectExpression([
babel.types.objectProperty(babel.types.identifier('pluginDefaultOpts'), babel.types.stringLiteral(JSON.stringify(options))),
babel.types.objectProperty(babel.types.identifier('dirname'), babel.types.stringLiteral(dirname))
])
return {
visitor: {
ArrayExpression (path) {
path.node.elements.push(value)
}
}
}
}
|
'use strict';
var config = require('../../config/environment');
var MenuSchema = {
title: {type: String, required: true},
icon: {clazz:String, beforeTitle:{type:Boolean, default:false}}, //AD:only supports css icons
// preLogin: {type:Boolean, default:false},//redundant due to permission
postLogin: {type:Boolean, default:true}, //whether should be shown after login
showIf: String,
hideIf: String,
permission: [{type: String, enum: config.userRoles, default: config.userRoles[0]}], //guest means available preLogin, user or admin means only postLogin
onClick: String,
link: String, //you can have link/api/sub menu.
state: String,
submenu:[MenuSchema], //submenu inherits parent's artibutes on permissions unless overridden
api: String//API call that will be used to populate submenu dynamically by angular
};
module.exports = MenuSchema; |
import React from 'react';
import TextInput from '../Common/TextInput.js';
import * as map from './fieldMap';
const StepForm = ({item, field, onChange, errors}) => {
let fields = [];
for (const col in item) {
fields.push(<TextInput
name={col}
key={col}
label={map[field][col]}
value={item[col]}
onChange={onChange}
error={errors[col]} />);
}
return (
<div>
{fields}
</div>
);
};
StepForm.propTypes = {
item: React.PropTypes.object.isRequired,
field: React.PropTypes.string,
onChange: React.PropTypes.func.isRequired,
errors: React.PropTypes.object
};
export default StepForm;
|
$(function() {
var cover = '';
$('input[name=cover]').change(function(e) {
var file = e.target.files[0];
var key = 'book/' + file.name;
var token = $('input[name=token]').val();
var formData = new FormData($('#qiniu-upload'));
formData.append('file', file);
formData.append('key', key);
formData.append('token', token);
$.ajax({
url: 'https://up.qbox.me/',
//url: 'https://upload.qiniu.com/',
type: 'POST',
cache: false,
data: formData,
processData: false,
contentType: false
}).done(function(res) {
cover = key;
}).fail(function(res) {});
});
$("button[type=submit]").click(function () {
var title = $.trim($("input[name=title]").val()); // 书名
var author = $.trim($("input[name=author]").val()); // 作者
var country = $.trim($("input[name=country]").val()); // 国籍
var press = $.trim($("input[name=press]").val()); // 出版社
var douban_href = $.trim($("input[name=douban_href]").val()); // 豆瓣链接
var abstract = $.trim($("input[name=abstract]").val()); // 摘要
if (cover.length <= 0) {
toastr['error']('请上传书籍封面');
return;
} else if (title.length <= 0) {
toastr['error']('请输入书籍名称');
return;
} else if (author.length <= 0) {
toastr['error']('请输入书籍作者');
return;
} else if (country.length <= 0) {
toastr['error']('请输入作者国籍');
return;
} else if (press.length <= 0) {
toastr['error']('请输入书籍出版社');
return;
} else if (douban_href.length <= 0) {
toastr['error']('请输入书籍的豆瓣链接');
return;
} else if (abstract.length <= 0) {
toastr['error']('请大概描述一下书籍把');
return;
}
$.post('/admin/book/add', {
cover: cover,
title: title,
author: author,
country: country,
press: press,
douban_href: douban_href,
abstract: abstract
}, function (result) {
if (result.code === 1) {
window.location.href = '/admin/book';
} else {
toastr['error']('添加失败');
}
})
});
});
|
import cx from 'classnames'
import _ from 'lodash'
import PropTypes from 'prop-types'
import React from 'react'
import {
childrenUtils,
customPropTypes,
getElementType,
getUnhandledProps,
META,
SUI,
useKeyOnly,
useTextAlignProp,
useWidthProp,
} from '../../lib'
import Card from './Card'
/**
* A group of cards.
*/
function CardGroup(props) {
const {
children,
className,
content,
doubling,
items,
itemsPerRow,
stackable,
textAlign,
} = props
const classes = cx(
'ui',
useKeyOnly(doubling, 'doubling'),
useKeyOnly(stackable, 'stackable'),
useTextAlignProp(textAlign),
useWidthProp(itemsPerRow),
'cards',
className,
)
const rest = getUnhandledProps(CardGroup, props)
const ElementType = getElementType(CardGroup, props)
if (!childrenUtils.isNil(children)) return <ElementType {...rest} className={classes}>{children}</ElementType>
if (!childrenUtils.isNil(content)) return <ElementType {...rest} className={classes}>{content}</ElementType>
const itemsJSX = _.map(items, (item) => {
const key = item.key || [item.header, item.description].join('-')
return <Card key={key} {...item} />
})
return <ElementType {...rest} className={classes}>{itemsJSX}</ElementType>
}
CardGroup._meta = {
name: 'CardGroup',
parent: 'Card',
type: META.TYPES.VIEW,
}
CardGroup.propTypes = {
/** An element type to render as (string or function). */
as: customPropTypes.as,
/** Primary content. */
children: PropTypes.node,
/** Additional classes. */
className: PropTypes.string,
/** Shorthand for primary content. */
content: customPropTypes.contentShorthand,
/** A group of cards can double its column width for mobile. */
doubling: PropTypes.bool,
/** Shorthand array of props for Card. */
items: customPropTypes.collectionShorthand,
/** A group of cards can set how many cards should exist in a row. */
itemsPerRow: PropTypes.oneOf(SUI.WIDTHS),
/** A group of cards can automatically stack rows to a single columns on mobile devices. */
stackable: PropTypes.bool,
/** A card group can adjust its text alignment. */
textAlign: PropTypes.oneOf(_.without(SUI.TEXT_ALIGNMENTS, 'justified')),
}
export default CardGroup
|
;(function ($, Formstone, undefined) {
"use strict";
/**
* @method private
* @name setup
* @description Setup plugin.
*/
function setup() {
$Body = Formstone.$body;
$Locks = $("html, body");
}
/**
* @method private
* @name resize
* @description Handles window resize
*/
function resize() {
if (Instance) {
resizeLightbox();
}
}
/**
* @method private
* @name construct
* @description Builds instance.
* @param data [object] "Instance data"
*/
function construct(data) {
this.on(Events.click, data, buildLightbox);
}
/**
* @method private
* @name destruct
* @description Tears down instance.
* @param data [object] "Instance data"
*/
function destruct(data) {
closeLightbox();
this.off(Events.namespace);
}
/**
* @method private
* @name initialize
* @description Builds instance from $target.
* @param $target [jQuery] "Target jQuery object"
*/
function initialize($target, options) {
if ($target instanceof $) {
// Emulate event
buildLightbox.apply(Window, [{ data: $.extend(true, {}, {
$object: $target
}, Defaults, options || {}) }]);
}
}
/**
* @method private
* @name buildLightbox
* @description Builds new lightbox.
* @param e [object] "Event data"
*/
function buildLightbox(e) {
if (!Instance) {
// Check target type
var data = e.data,
$el = data.$el,
$object = data.$object,
source = ($el && $el[0].href) ? $el[0].href || "" : "",
hash = ($el && $el[0].hash) ? $el[0].hash || "" : "",
sourceParts = source.toLowerCase().split(".").pop().split(/\#|\?/),
extension = sourceParts[0],
type = ($el) ? $el.data(Namespace + "-type") : "",
isImage = ( (type === "image") || ($.inArray(extension, data.extensions) > -1 || source.substr(0, 10) === "data:image") ),
isVideo = checkVideo(source),
isUrl = ( (type === "url") || (!isImage && !isVideo && source.substr(0, 4) === "http" && !hash) ),
isElement = ( (type === "element") || (!isImage && !isVideo && !isUrl && (hash.substr(0, 1) === "#")) ),
isObject = ( (typeof $object !== "undefined") );
if (isElement) {
source = hash;
}
// Retain default click
if ( !(isImage || isVideo || isUrl || isElement || isObject) ) {
return;
}
// Kill event
Functions.killEvent(e);
// Cache internal data
Instance = $.extend({}, {
visible : false,
gallery: {
active : false
},
isMobile : (Formstone.isMobile || data.mobile),
isTouch : Formstone.support.touch,
isAnimating : true,
oldContentHeight : 0,
oldContentWidth : 0
}, data);
// Double the margin
Instance.margin *= 2;
if (isImage) {
Instance.type = "image";
} else if (isVideo) {
Instance.type = "video";
} else {
Instance.type = "element";
}
if (isImage || isVideo) {
// Check for gallery
var id = $el.data(Namespace + "-gallery");
if (id) {
Instance.gallery.active = true;
Instance.gallery.id = id;
Instance.gallery.$items = $("a[data-lightbox-gallery= " + Instance.gallery.id + "], a[rel= " + Instance.gallery.id + "]"); // backwards compatibility
Instance.gallery.index = Instance.gallery.$items.index(Instance.$el);
Instance.gallery.total = Instance.gallery.$items.length - 1;
}
}
// Assemble HTML
var html = '';
if (!Instance.isMobile) {
html += '<div class="' + [Classes.raw.overlay, Instance.customClass].join(" ") + '"></div>';
}
var lightboxClasses = [
Classes.raw.base,
Classes.raw.loading,
Classes.raw.animating,
Instance.customClass
];
if (Instance.fixed) {
lightboxClasses.push(Classes.raw.fixed);
}
if (Instance.isMobile) {
lightboxClasses.push(Classes.raw.mobile);
}
if (Instance.isTouch) {
lightboxClasses.push(Classes.raw.touch);
}
if (isUrl) {
lightboxClasses.push(Classes.raw.iframed);
}
if (isElement || isObject) {
lightboxClasses.push(Classes.raw.inline);
}
html += '<div class="' + lightboxClasses.join(" ") + '">';
html += '<button type="button" class="' + Classes.raw.close + '">' + Instance.labels.close + '</button>';
html += '<span class="' + Classes.raw.loading_icon + '"></span>';
html += '<div class="' + Classes.raw.container + '">';
html += '<div class="' + Classes.raw.content + '">';
if (isImage || isVideo) {
html += '<div class="' + Classes.raw.tools + '">';
html += '<div class="' + Classes.raw.controls + '">';
if (Instance.gallery.active) {
html += '<button type="button" class="' + [Classes.raw.control, Classes.raw.control_previous].join(" ") + '">' + Instance.labels.previous + '</button>';
html += '<button type="button" class="' + [Classes.raw.control, Classes.raw.control_next].join(" ") + '">' + Instance.labels.next + '</button>';
}
if (Instance.isMobile && Instance.isTouch) {
html += '<button type="button" class="' + [Classes.raw.caption_toggle].join(" ") + '">' + Instance.labels.captionClosed + '</button>';
}
html += '</div>'; // controls
html += '<div class="' + Classes.raw.meta + '">';
if (Instance.gallery.active) {
html += '<p class="' + Classes.raw.position + '"';
if (Instance.gallery.total < 1) {
html += ' style="display: none;"';
}
html += '>';
html += '<span class="' + Classes.raw.position_current + '">' + (Instance.gallery.index + 1) + '</span> ';
html += Instance.labels.count;
html += ' <span class="' + Classes.raw.position_total + '">' + (Instance.gallery.total + 1) + '</span>';
html += '</p>';
}
html += '<div class="' + Classes.raw.caption + '">';
html += Instance.formatter.call($el, data);
html += '</div></div>'; // caption, meta
html += '</div>'; // tools
}
html += '</div></div></div>'; //container, content, lightbox
// Modify Dom
$Body.append(html);
// Cache jquery objects
Instance.$overlay = $(Classes.overlay);
Instance.$lightbox = $(Classes.base);
Instance.$close = $(Classes.close);
Instance.$container = $(Classes.container);
Instance.$content = $(Classes.content);
Instance.$tools = $(Classes.tools);
Instance.$meta = $(Classes.meta);
Instance.$position = $(Classes.position);
Instance.$caption = $(Classes.caption);
Instance.$controlBox = $(Classes.controls);
Instance.$controls = $(Classes.control);
if (Instance.isMobile) {
Instance.paddingVertical = Instance.$close.outerHeight();
Instance.paddingHorizontal = 0;
Instance.mobilePaddingVertical = parseInt(Instance.$content.css("paddingTop"), 10) + parseInt(Instance.$content.css("paddingBottom"), 10);
Instance.mobilePaddingHorizontal = parseInt(Instance.$content.css("paddingLeft"), 10) + parseInt(Instance.$content.css("paddingRight"), 10);
} else {
Instance.paddingVertical = parseInt(Instance.$lightbox.css("paddingTop"), 10) + parseInt(Instance.$lightbox.css("paddingBottom"), 10);
Instance.paddingHorizontal = parseInt(Instance.$lightbox.css("paddingLeft"), 10) + parseInt(Instance.$lightbox.css("paddingRight"), 10);
Instance.mobilePaddingVertical = 0;
Instance.mobilePaddingHorizontal = 0;
}
Instance.contentHeight = Instance.$lightbox.outerHeight() - Instance.paddingVertical;
Instance.contentWidth = Instance.$lightbox.outerWidth() - Instance.paddingHorizontal;
Instance.controlHeight = Instance.$controls.outerHeight();
// Center
centerLightbox();
// Update gallery
if (Instance.gallery.active) {
updateGalleryControls();
}
// Bind events
$Window.on(Events.keyDown, onKeyDown);
$Body.on(Events.clickTouchStart, [Classes.overlay, Classes.close].join(", "), closeLightbox);
if (Instance.gallery.active) {
Instance.$lightbox.on(Events.clickTouchStart, Classes.control, advanceGallery);
}
if (Instance.isMobile && Instance.isTouch) {
Instance.$lightbox.on(Events.clickTouchStart, Classes.caption_toggle, toggleCaption);
}
Instance.$lightbox.transition({
property: "opacity"
},
function() {
if (isImage) {
loadImage(source);
} else if (isVideo) {
loadVideo(source);
} else if (isUrl) {
loadURL(source);
} else if (isElement) {
cloneElement(source);
} else if (isObject) {
appendObject(Instance.$object);
}
}).addClass(Classes.raw.open);
Instance.$overlay.addClass(Classes.raw.open);
}
}
/**
* @method
* @name resize
* @description Resizes lightbox.
* @example $.lightbox("resize");
* @param height [int | false] "Target height or false to auto size"
* @param width [int | false] "Target width or false to auto size"
*/
/**
* @method private
* @name resizeLightbox
* @description Triggers resize of instance.
*/
function resizeLightbox(e) {
if (typeof e !== "object") {
Instance.targetHeight = arguments[0];
Instance.targetWidth = arguments[1];
}
if (Instance.type === "element") {
sizeContent(Instance.$content.find("> :first-child"));
} else if (Instance.type === "image") {
sizeImage();
} else if (Instance.type === "video") {
sizeVideo();
}
sizeLightbox();
}
/**
* @method
* @name close
* @description Closes active instance.
* @example $.lightbox("close");
*/
/**
* @method private
* @name closeLightbox
* @description Closes active instance.
* @param e [object] "Event data"
*/
function closeLightbox(e) {
Functions.killEvent(e);
if (Instance) {
Instance.$lightbox.transition("destroy");
Instance.$container.transition("destroy");
Instance.$lightbox.addClass(Classes.raw.animating).transition({
property: "opacity"
},
function(e) {
// Clean up
Instance.$lightbox.off(Events.namespace);
Instance.$container.off(Events.namespace);
$Window.off(Events.namespace);
$Body.off(Events.namespace);
Instance.$overlay.remove();
Instance.$lightbox.remove();
// Reset Instance
Instance = null;
$Window.trigger(Events.close);
});
Instance.$lightbox.removeClass(Classes.raw.open);
Instance.$overlay.removeClass(Classes.raw.open);
if (Instance.isMobile) {
$Locks.removeClass(RawClasses.lock);
}
}
}
/**
* @method private
* @name openLightbox
* @description Opens active instance.
*/
function openLightbox() {
var position = calculatePosition(),
durration = Instance.isMobile ? 0 : Instance.duration;
if (!Instance.isMobile) {
Instance.$controls.css({
marginTop: ((Instance.contentHeight - Instance.controlHeight - Instance.metaHeight) / 2)
});
}
if (!Instance.visible && Instance.isMobile && Instance.gallery.active) {
Instance.$content.touch({
axis: "x",
swipe: true
}).on(Events.swipe, onSwipe);
}
Instance.$lightbox.transition({
property: (Instance.contentHeight !== Instance.oldContentHeight) ? "height" : "width"
},
function() {
Instance.$container.transition({
property: "opacity"
},
function() {
Instance.$lightbox.removeClass(Classes.raw.animating);
Instance.isAnimating = false;
});
Instance.$lightbox.removeClass(Classes.raw.loading);
Instance.visible = true;
// Fire open event
$Window.trigger(Events.open);
// Start preloading
if (Instance.gallery.active) {
preloadGallery();
}
});
if (!Instance.isMobile) {
Instance.$lightbox.css({
height: Instance.contentHeight + Instance.paddingVertical,
width: Instance.contentWidth + Instance.paddingHorizontal,
top: (!Instance.fixed) ? position.top : 0
});
}
// Trigger event in case the content size hasn't changed
var contentHasChanged = (Instance.oldContentHeight !== Instance.contentHeight || Instance.oldContentWidth !== Instance.contentWidth);
if (Instance.isMobile || !contentHasChanged) {
Instance.$lightbox.transition("resolve");
}
// Track content size changes
Instance.oldContentHeight = Instance.contentHeight;
Instance.oldContentWidth = Instance.contentWidth;
if (Instance.isMobile) {
$Locks.addClass(RawClasses.lock);
}
}
/**
* @method private
* @name sizeLightbox
* @description Sizes active instance.
*/
function sizeLightbox() {
if (Instance.visible && !Instance.isMobile) {
var position = calculatePosition();
Instance.$controls.css({
marginTop: ((Instance.contentHeight - Instance.controlHeight - Instance.metaHeight) / 2)
});
Instance.$lightbox.css({
height: Instance.contentHeight + Instance.paddingVertical,
width: Instance.contentWidth + Instance.paddingHorizontal,
top: (!Instance.fixed) ? position.top : 0
});
}
}
/**
* @method private
* @name centerLightbox
* @description Centers instance.
*/
function centerLightbox() {
var position = calculatePosition();
Instance.$lightbox.css({
top: (!Instance.fixed) ? position.top : 0
});
}
/**
* @method private
* @name calculatePosition
* @description Calculates positions.
* @return [object] "Object containing top and left positions"
*/
function calculatePosition() {
if (Instance.isMobile) {
return {
left: 0,
top: 0
};
}
var pos = {
left: (Formstone.windowWidth - Instance.contentWidth - Instance.paddingHorizontal) / 2,
top: (Instance.top <= 0) ? ((Formstone.windowHeight - Instance.contentHeight - Instance.paddingVertical) / 2) : Instance.top
};
if (Instance.fixed !== true) {
pos.top += $Window.scrollTop();
}
return pos;
}
/**
* @method private
* @name toggleCaption
* @description Toggle caption.
*/
function toggleCaption(e) {
Functions.killEvent(e);
if (Instance.captionOpen) {
closeCaption();
} else {
Instance.$lightbox.addClass(Classes.raw.caption_open)
.find(Classes.caption_toggle).text(Instance.labels.captionOpen);
Instance.captionOpen = true;
}
}
/**
* @method private
* @name closeCaption
* @description Close caption.
*/
function closeCaption() {
Instance.$lightbox.removeClass(Classes.raw.caption_open)
.find(Classes.caption_toggle).text(Instance.labels.captionClosed);
Instance.captionOpen = false;
}
/**
* @method private
* @name formatCaption
* @description Formats caption.
* @param $target [jQuery object] "Target element"
*/
function formatCaption() {
var title = this.attr("title"),
t = (title !== undefined && title) ? title.replace(/^\s+|\s+$/g,'') : false;
return t ? '<p class="caption">' + t + '</p>' : "";
}
/**
* @method private
* @name loadImage
* @description Loads source image.
* @param source [string] "Source image URL"
*/
function loadImage(source) {
// Cache current image
Instance.$image = $("<img>");
Instance.$image.one(Events.load, function() {
var naturalSize = calculateNaturalSize(Instance.$image);
Instance.naturalHeight = naturalSize.naturalHeight;
Instance.naturalWidth = naturalSize.naturalWidth;
if (Instance.retina) {
Instance.naturalHeight /= 2;
Instance.naturalWidth /= 2;
}
Instance.$content.prepend(Instance.$image);
if (Instance.$caption.html() === "") {
Instance.$caption.hide();
} else {
Instance.$caption.show();
}
// Size content to be sure it fits the viewport
sizeImage();
openLightbox();
}).error(loadError)
.attr("src", source)
.addClass(Classes.raw.image);
// If image has already loaded into cache, trigger load event
if (Instance.$image[0].complete || Instance.$image[0].readyState === 4) {
Instance.$image.trigger(Events.load);
}
}
/**
* @method private
* @name sizeImage
* @description Sizes image to fit in viewport.
* @param count [int] "Number of resize attempts"
*/
function sizeImage() {
var count = 0;
Instance.windowHeight = Instance.viewportHeight = Formstone.windowHeight - Instance.mobilePaddingVertical - Instance.paddingVertical;
Instance.windowWidth = Instance.viewportWidth = Formstone.windowWidth - Instance.mobilePaddingHorizontal - Instance.paddingHorizontal;
Instance.contentHeight = Infinity;
Instance.contentWidth = Infinity;
Instance.imageMarginTop = 0;
Instance.imageMarginLeft = 0;
while (Instance.contentHeight > Instance.viewportHeight && count < 2) {
Instance.imageHeight = (count === 0) ? Instance.naturalHeight : Instance.$image.outerHeight();
Instance.imageWidth = (count === 0) ? Instance.naturalWidth : Instance.$image.outerWidth();
Instance.metaHeight = (count === 0) ? 0 : Instance.metaHeight;
Instance.spacerHeight = (count === 0) ? 0 : Instance.spacerHeight;
if (count === 0) {
Instance.ratioHorizontal = Instance.imageHeight / Instance.imageWidth;
Instance.ratioVertical = Instance.imageWidth / Instance.imageHeight;
Instance.isWide = (Instance.imageWidth > Instance.imageHeight);
}
// Double check min and max
if (Instance.imageHeight < Instance.minHeight) {
Instance.minHeight = Instance.imageHeight;
}
if (Instance.imageWidth < Instance.minWidth) {
Instance.minWidth = Instance.imageWidth;
}
if (Instance.isMobile) {
if (Instance.isTouch) {
Instance.$controlBox.css({
width: Formstone.windowWidth
});
Instance.spacerHeight = Instance.$controls.outerHeight(true);
} else {
Instance.$tools.css({
width: Formstone.windowWidth
});
Instance.spacerHeight = Instance.$tools.outerHeight(true);
}
// Content match viewport
Instance.contentHeight = Instance.viewportHeight;
Instance.contentWidth = Instance.viewportWidth;
fitImage();
Instance.imageMarginTop = (Instance.contentHeight - Instance.targetImageHeight - Instance.spacerHeight) / 2;
Instance.imageMarginLeft = (Instance.contentWidth - Instance.targetImageWidth) / 2;
} else {
// Viewport should match window, less margin, padding and meta
if (count === 0) {
Instance.viewportHeight -= (Instance.margin + Instance.paddingVertical);
Instance.viewportWidth -= (Instance.margin + Instance.paddingHorizontal);
}
Instance.viewportHeight -= Instance.metaHeight;
fitImage();
Instance.contentHeight = Instance.targetImageHeight;
Instance.contentWidth = Instance.targetImageWidth;
}
// Modify DOM
if (!Instance.isMobile && !Instance.isTouch) {
Instance.$meta.css({
width: Instance.contentWidth
});
}
Instance.$image.css({
height: Instance.targetImageHeight,
width: Instance.targetImageWidth,
marginTop: Instance.imageMarginTop,
marginLeft: Instance.imageMarginLeft
});
if (!Instance.isMobile) {
Instance.metaHeight = Instance.$meta.outerHeight(true);
Instance.contentHeight += Instance.metaHeight;
}
count ++;
}
}
/**
* @method private
* @name fitImage
* @description Calculates target image size.
*/
function fitImage() {
var height = (!Instance.isMobile) ? Instance.viewportHeight : Instance.contentHeight - Instance.spacerHeight,
width = (!Instance.isMobile) ? Instance.viewportWidth : Instance.contentWidth;
if (Instance.isWide) {
//WIDE
Instance.targetImageWidth = width;
Instance.targetImageHeight = Instance.targetImageWidth * Instance.ratioHorizontal;
if (Instance.targetImageHeight > height) {
Instance.targetImageHeight = height;
Instance.targetImageWidth = Instance.targetImageHeight * Instance.ratioVertical;
}
} else {
//TALL
Instance.targetImageHeight = height;
Instance.targetImageWidth = Instance.targetImageHeight * Instance.ratioVertical;
if (Instance.targetImageWidth > width) {
Instance.targetImageWidth = width;
Instance.targetImageHeight = Instance.targetImageWidth * Instance.ratioHorizontal;
}
}
// MAX
if (Instance.targetImageWidth > Instance.imageWidth || Instance.targetImageHeight > Instance.imageHeight) {
Instance.targetImageHeight = Instance.imageHeight;
Instance.targetImageWidth = Instance.imageWidth;
}
// MIN
if (Instance.targetImageWidth < Instance.minWidth || Instance.targetImageHeight < Instance.minHeight) {
if (Instance.targetImageWidth < Instance.minWidth) {
Instance.targetImageWidth = Instance.minWidth;
Instance.targetImageHeight = Instance.targetImageWidth * Instance.ratioHorizontal;
} else {
Instance.targetImageHeight = Instance.minHeight;
Instance.targetImageWidth = Instance.targetImageHeight * Instance.ratioVertical;
}
}
}
/**
* @method private
* @name loadVideo
* @description Loads source video.
* @param source [string] "Source video URL"
*/
function loadVideo(source) {
var youtubeParts = source.match( /(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([^"&?\/ ]{11})/i ), // 1
vimeoParts = source.match( /(?:www\.|player\.)?vimeo.com\/(?:channels\/(?:\w+\/)?|groups\/([^\/]*)\/videos\/|album\/(\d+)\/video\/|video\/|)(\d+)(?:$|\/|\?)/ ), // 3
url = (youtubeParts !== null) ? "//www.youtube.com/embed/" + youtubeParts[1] : "//player.vimeo.com/video/" + vimeoParts[3];
Instance.$videoWrapper = $('<div class="' + Classes.raw.videoWrapper + '"></div>');
Instance.$video = $('<iframe class="' + Classes.raw.video + '" seamless="seamless"></iframe>');
Instance.$video.attr("src", url)
.addClass(Classes.raw.video)
.prependTo(Instance.$videoWrapper);
Instance.$content.prepend(Instance.$videoWrapper);
sizeVideo();
openLightbox();
}
/**
* @method private
* @name sizeVideo
* @description Sizes video to fit in viewport.
*/
function sizeVideo() {
// Set initial vars
Instance.windowHeight = Instance.viewportHeight = Formstone.windowHeight - Instance.mobilePaddingVertical - Instance.paddingVertical;
Instance.windowWidth = Instance.viewportWidth = Formstone.windowWidth - Instance.mobilePaddingHorizontal - Instance.paddingHorizontal;
Instance.videoMarginTop = 0;
Instance.videoMarginLeft = 0;
if (Instance.isMobile) {
if (Instance.isTouch) {
Instance.$controlBox.css({
width: Formstone.windowWidth
});
Instance.spacerHeight = Instance.$controls.outerHeight(true);
} else {
Instance.$tools.css({
width: Formstone.windowWidth
});
Instance.spacerHeight = Instance.$tools.outerHeight(true);
}
Instance.viewportHeight -= Instance.spacerHeight;
Instance.targetVideoWidth = Instance.viewportWidth;
Instance.targetVideoHeight = Instance.targetVideoWidth * Instance.videoRatio;
if (Instance.targetVideoHeight > Instance.viewportHeight) {
Instance.targetVideoHeight = Instance.viewportHeight;
Instance.targetVideoWidth = Instance.targetVideoHeight / Instance.videoRatio;
}
Instance.videoMarginTop = (Instance.viewportHeight - Instance.targetVideoHeight) / 2;
Instance.videoMarginLeft = (Instance.viewportWidth - Instance.targetVideoWidth) / 2;
} else {
Instance.viewportHeight = Instance.windowHeight - Instance.margin;
Instance.viewportWidth = Instance.windowWidth - Instance.margin;
Instance.targetVideoWidth = (Instance.videoWidth > Instance.viewportWidth) ? Instance.viewportWidth : Instance.videoWidth;
if (Instance.targetVideoWidth < Instance.minWidth) {
Instance.targetVideoWidth = Instance.minWidth;
}
Instance.targetVideoHeight = Instance.targetVideoWidth * Instance.videoRatio;
Instance.contentHeight = Instance.targetVideoHeight;
Instance.contentWidth = Instance.targetVideoWidth;
}
// Update dom
if (!Instance.isMobile && !Instance.isTouch) {
Instance.$meta.css({
width: Instance.contentWidth
});
}
Instance.$videoWrapper.css({
height: Instance.targetVideoHeight,
width: Instance.targetVideoWidth,
marginTop: Instance.videoMarginTop,
marginLeft: Instance.videoMarginLeft
});
if (!Instance.isMobile) {
Instance.metaHeight = Instance.$meta.outerHeight(true);
Instance.contentHeight = Instance.targetVideoHeight + Instance.metaHeight;
}
}
/**
* @method private
* @name preloadGallery
* @description Preloads previous and next images in gallery for faster rendering.
* @param e [object] "Event Data"
*/
function preloadGallery(e) {
var source = '';
if (Instance.gallery.index > 0) {
source = Instance.gallery.$items.eq(Instance.gallery.index - 1).attr("href");
if (!checkVideo(source)) {
$('<img src="' + source + '">');
}
}
if (Instance.gallery.index < Instance.gallery.total) {
source = Instance.gallery.$items.eq(Instance.gallery.index + 1).attr("href");
if (!checkVideo(source)) {
$('<img src="' + source + '">');
}
}
}
/**
* @method private
* @name advanceGallery
* @description Advances gallery base on direction.
* @param e [object] "Event Data"
*/
function advanceGallery(e) {
Functions.killEvent(e);
var $control = $(e.currentTarget);
if (!Instance.isAnimating && !$control.hasClass(Classes.raw.control_disabled)) {
Instance.isAnimating = true;
closeCaption();
Instance.gallery.index += ($control.hasClass(Classes.raw.control_next)) ? 1 : -1;
if (Instance.gallery.index > Instance.gallery.total) {
Instance.gallery.index = (Instance.infinite) ? 0 : Instance.gallery.total;
}
if (Instance.gallery.index < 0) {
Instance.gallery.index = (Instance.infinite) ? Instance.gallery.total : 0;
}
Instance.$lightbox.addClass(Classes.raw.animating);
Instance.$container.transition({
property: "opacity"
},
function() {
if (typeof Instance.$image !== 'undefined') {
Instance.$image.remove();
}
if (typeof Instance.$videoWrapper !== 'undefined') {
Instance.$videoWrapper.remove();
}
Instance.$el = Instance.gallery.$items.eq(Instance.gallery.index);
Instance.$caption.html(Instance.formatter.call(Instance.$el, Instance));
Instance.$position.find(Classes.position_current).html(Instance.gallery.index + 1);
var source = Instance.$el.attr("href"),
isVideo = checkVideo(source);
if (isVideo) {
loadVideo(source);
} else {
loadImage(source);
}
updateGalleryControls();
});
Instance.$lightbox.addClass(Classes.raw.loading);
}
}
/**
* @method private
* @name updateGalleryControls
* @description Updates gallery control states.
*/
function updateGalleryControls() {
Instance.$controls.removeClass(Classes.raw.control_disabled);
if (!Instance.infinite) {
if (Instance.gallery.index === 0) {
Instance.$controls.filter(Classes.control_previous).addClass(RawClasses.control_disabled);
}
if (Instance.gallery.index === Instance.gallery.total) {
Instance.$controls.filter(Classes.control_next).addClass(RawClasses.control_disabled);
}
}
}
/**
* @method private
* @name onKeyDown
* @description Handles keypress in gallery.
* @param e [object] "Event data"
*/
function onKeyDown(e) {
if (Instance.gallery.active && (e.keyCode === 37 || e.keyCode === 39)) {
Functions.killEvent(e);
Instance.$controls.filter((e.keyCode === 37) ? Classes.control_previous : Classes.control_next).trigger(Events.click);
} else if (e.keyCode === 27) {
Instance.$close.trigger(Events.click);
}
}
/**
* @method private
* @name cloneElement
* @description Clones target inline element.
* @param id [string] "Target element id"
*/
function cloneElement(id) {
var $clone = $(id).find("> :first-child").clone();
appendObject($clone);
}
/**
* @method private
* @name loadURL
* @description Load URL into iframe.
* @param source [string] "Target URL"
*/
function loadURL(source) {
source = source + ((source.indexOf("?") > -1) ? "&" + Instance.requestKey + "=true" : "?" + Instance.requestKey + "=true");
var $iframe = $('<iframe class="' + Classes.raw.iframe + '" src="' + source + '"></iframe>');
appendObject($iframe);
}
/**
* @method private
* @name appendObject
* @description Appends and sizes object.
* @param $object [jQuery Object] "Object to append"
*/
function appendObject($object) {
Instance.$content.append($object);
sizeContent($object);
openLightbox();
}
/**
* @method private
* @name sizeContent
* @description Sizes jQuery object to fir in viewport.
* @param $object [jQuery Object] "Object to size"
*/
function sizeContent($object) {
Instance.windowHeight = Formstone.windowHeight - Instance.mobilePaddingVertical - Instance.paddingVertical;
Instance.windowWidth = Formstone.windowWidth - Instance.mobilePaddingHorizontal - Instance.paddingHorizontal;
Instance.objectHeight = $object.outerHeight(true);
Instance.objectWidth = $object.outerWidth(true);
Instance.targetHeight = Instance.targetHeight || (Instance.$el ? Instance.$el.data(Namespace + "-height") : null);
Instance.targetWidth = Instance.targetWidth || (Instance.$el ? Instance.$el.data(Namespace + "-width") : null);
Instance.maxHeight = (Instance.windowHeight < 0) ? Instance.minHeight : Instance.windowHeight;
Instance.isIframe = $object.is("iframe");
Instance.objectMarginTop = 0;
Instance.objectMarginLeft = 0;
if (!Instance.isMobile) {
Instance.windowHeight -= Instance.margin;
Instance.windowWidth -= Instance.margin;
}
Instance.contentHeight = (Instance.targetHeight) ? Instance.targetHeight : (Instance.isIframe || Instance.isMobile) ? Instance.windowHeight : Instance.objectHeight;
Instance.contentWidth = (Instance.targetWidth) ? Instance.targetWidth : (Instance.isIframe || Instance.isMobile) ? Instance.windowWidth : Instance.objectWidth;
if ((Instance.isIframe || Instance.isObject) && Instance.isMobile) {
Instance.contentHeight = Instance.windowHeight;
Instance.contentWidth = Instance.windowWidth;
} else if (Instance.isObject) {
Instance.contentHeight = (Instance.contentHeight > Instance.windowHeight) ? Instance.windowHeight : Instance.contentHeight;
Instance.contentWidth = (Instance.contentWidth > Instance.windowWidth) ? Instance.windowWidth : Instance.contentWidth;
}
}
/**
* @method private
* @name loadError
* @description Error when resource fails to load.
* @param e [object] "Event data"
*/
function loadError(e) {
var $error = $('<div class="' + Classes.raw.error + '"><p>Error Loading Resource</p></div>');
// Clean up
Instance.type = "element";
Instance.$tools.remove();
Instance.$image.off(Events.namespace);
appendObject($error);
}
/**
* @method private
* @name onSwipe
* @description Handles swipe event
* @param e [object] "Event data"
*/
function onSwipe(e) {
if (!Instance.captionOpen) {
Instance.$controls.filter((e.directionX === "left") ? Classes.control_next : Classes.control_previous).trigger(Events.click);
}
}
/**
* @method private
* @name calculateNaturalSize
* @description Determines natural size of target image.
* @param $img [jQuery object] "Source image object"
* @return [object | boolean] "Object containing natural height and width values or false"
*/
function calculateNaturalSize($img) {
var node = $img[0],
img = new Image();
if (typeof node.naturalHeight !== "undefined") {
return {
naturalHeight: node.naturalHeight,
naturalWidth: node.naturalWidth
};
} else {
if (node.tagName.toLowerCase() === 'img') {
img.src = node.src;
return {
naturalHeight: img.height,
naturalWidth: img.width
};
}
}
return false;
}
/**
* @method private
* @name checkVideo
* @description Determines if url is a YouTube or Vimeo url.
* @param source [string] "Source url"
* @return [boolean] "True if YouTube or Vimeo url"
*/
function checkVideo(source) {
return ( source.indexOf("youtube.com") > -1 || source.indexOf("youtu.be") > -1 || source.indexOf("vimeo.com") > -1 );
}
/**
* @plugin
* @name Lightbox
* @description A jQuery plugin for simple modals.
* @type widget
* @dependency core.js
* @dependency touch.js
* @dependency transition.js
*/
var Plugin = Formstone.Plugin("lightbox", {
widget: true,
/**
* @options
* @param customClass [string] <''> "Class applied to instance"
* @param extensions [array] <"jpg", "sjpg", "jpeg", "png", "gif"> "Image type extensions"
* @param fixed [boolean] <false> "Flag for fixed positioning"
* @param formatter [function] <$.noop> "Caption format function"
* @param infinite [boolean] <false> "Flag for infinite galleries"
* @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 labels.captionClosed [string] <'View Caption'> "Mobile caption toggle text, closed state"
* @param labels.captionOpen [string] <'View Caption'> "Mobile caption toggle text, open state"
* @param margin [int] <50> "Margin used when sizing (single side)"
* @param minHeight [int] <100> "Minimum height of modal"
* @param minWidth [int] <100> "Minimum width of modal"
* @param mobile [boolean] <false> "Flag to force 'mobile' rendering"
* @param retina [boolean] <false> "Flag to use 'retina' sizing (halves natural sizes)"
* @param requestKey [string] <'fs-lightbox'> "GET variable for ajax / iframe requests"
* @param top [int] <0> "Target top position; over-rides centering"
* @param videoRadio [number] <0.5625> "Video height / width ratio (9 / 16 = 0.5625)"
* @param videoWidth [int] <800> "Video max width"
*/
defaults: {
customClass : "",
extensions : [ "jpg", "sjpg", "jpeg", "png", "gif" ],
fixed : false,
formatter : formatCaption,
infinite : false,
labels: {
close : "Close",
count : "of",
next : "Next",
previous : "Previous",
captionClosed : "View Caption",
captionOpen : "Close Caption"
},
margin : 50,
minHeight : 100,
minWidth : 100,
mobile : false,
retina : false,
requestKey : "fs-lightbox",
top : 0,
videoRatio : 0.5625,
videoWidth : 800
},
classes: [
"loading",
"animating",
"fixed",
"mobile",
"touch",
"inline",
"iframed",
"open",
"overlay",
"close",
"loading_icon",
"container",
"content",
"image",
"video",
"video_wrapper",
"tools",
"meta",
"controls",
"control",
"control_previous",
"control_next",
"control_disabled",
"position",
"position_current",
"position_total",
"caption_toggle",
"caption",
"caption_open",
"iframe",
"error",
"lock"
],
/**
* @events
* @event open.lightbox "Lightbox opened; Triggered on window"
* @event close.lightbox "Lightbox closed; Triggered on window"
*/
events: {
open : "open",
close : "close",
swipe : "swipe"
},
methods: {
_setup : setup,
_construct : construct,
_destruct : destruct,
_resize : resize,
resize : resizeLightbox
},
utilities: {
_initialize : initialize,
close : closeLightbox
}
}),
// Localize References
Namespace = Plugin.namespace,
Defaults = Plugin.defaults,
Classes = Plugin.classes,
RawClasses = Classes.raw,
Events = Plugin.events,
Functions = Plugin.functions,
Window = Formstone.window,
$Window = Formstone.$window,
$Body = null,
// Internal
$Locks = null,
// Singleton
Instance = null;
})(jQuery, Formstone); |
// Wrap everything in a function to avoid polluting the global namespace.
(function() {
TypeJig.WordSets.LearnPlover = {};
TypeJig.WordSets.LearnPloverOrder = [
"One Syllable Words",
"Consonant Clusters",
"Where's the TRUFT?",
"Dropping Unstressed Vowels",
"Inversion",
"The Fifth Vowel Key",
"Long Vowel Chords",
"Diphthong Chords",
"Vowel Disambiguator Chords",
"The Missing Keys",
"The Remaining Missing Letters",
"Review Through Missing Letters",
"Digraphs",
"Review Through Digraphs",
"Common Compound Clusters",
"Review Through Common Compound Clusters",
"Common Briefs 1-20",
"Common Briefs 21-40",
"Common Briefs 41-60",
"Common Briefs 61-80",
"Common Briefs 81-100",
];
var Plover = TypeJig.WordSets.LearnPlover;
Plover["One Syllable Words"] = [
'sap', 'sag', 'sat', 'sass', 'sad',
'sop', 'sob', 'sell', 'set', 'says',
'tar', 'tap', 'tab', 'tag', 'tad', 'tour',
'top', 'toll', 'tell', 'tough', 'tub', 'tug',
'car', 'cap', 'cab', 'cat', 'cad', 'core',
'cop', 'cog', 'cot', 'cod', 'keg', 'cuff',
'cur', 'cup', 'cub', 'cull', 'cut', 'cuss',
'pal', 'pat', 'pass', 'pad', 'pour', 'poll',
'pot', 'pod', 'pep', 'peg', 'pet', 'puff',
'pup', 'pub', 'pull', 'pug', 'put', 'pus',
'war', 'wag', 'wad', 'was', 'wore',
'web', 'well', 'wet', 'wed',
'half', 'hag', 'hat', 'had', 'has', 'hop',
'hog', 'hot', 'her', 'hell', 'head',
'huff', 'hub', 'hull', 'hug', 'hut',
'rap', 'rag', 'rat', 'roar', 'rob', 'roll', 'rot',
'rod', 'red', 'rough', 'rub', 'rug', 'rut'
];
Plover["Consonant Clusters"] = [
'course', 'cover', 'hover', 'rabble', 'refer',
'rebel', 'robbed', 'rubbed', 'rubble', 'straps',
'strapped', 'trouble', 'troubles', 'waft', 'webbed'
];
Plover["Where's the TRUFT?"] = [
'past', 'castle', 'stressed', 'pressed',
'passed', 'test', 'tussle', 'crossed'
];
Plover["Dropping Unstressed Vowels"] = [
'several', 'suppress', 'averages', 'tablet',
'tepid', 'superb', 'scaffold', 'scarlet',
'starlet', 'started', 'ruffled', 'scuffled',
'corrupted', 'spotted', 'horrible', 'effort'
];
Plover["Inversion"] = [
'edit', 'elves', 'twelve', 'credit', 'portal'
];
Plover["The Fifth Vowel Key"] = [
'still', 'rig', 'hit', 'sip',
'sir', 'skirt',
'crypt', 'syrup',
'pig', 'rift', 'scribble', 'rid', 'river',
'hid', 'wilt', 'wig', 'wit', 'spill'
];
Plover["Long Vowel Chords"] = [
'aids', 'ace', 'ate', 'able', 'ape',
'raid', 'raise', 'rail', 'rate', 'race', 'pay',
'paid', 'pace', 'tape', 'spray', 'praise',
'weaver', 'trees', 'eel', 'eat', 'evil',
'ear', 'heat', 'heap', 'wield', 'weird',
'peer', 'priest', 'tree', 'tweeze', 'tweed',
'seat', 'cease', 'seed', 'seize', 'secrete',
'ire', "I'll", 'ice', 'rife', 'ripe',
'right', 'height', 'wild', 'pipe', 'pride',
'prize', 'kite', 'type', 'spite',
'hope', 'spore', 'post', 'sold', 'prose',
'ode', 'oat', 'over', 'robe', 'rope',
'roar', 'rove', 'host', 'wove', 'wrote', 'pole',
'pose', 'cope', 'coat', 'code', 'crow', 'told',
'cube', 'use', 'rude', 'rule', 'pure',
'prude', 'Proust', 'cure', 'cruel', 'crude',
'cruise', 'truce', 'truth', 'spew', 'skew',
];
Plover["Diphthong Chords"] = [
'all', 'awful', 'raw', 'call', 'caught', 'crawl',
'sprawl', 'scald', 'straw', 'halt', 'hall', 'wall',
'out', 'how', 'howl', 'house', 'pout', 'power',
'prowl', 'tower', 'spouse', 'sprout', 'scour',
'soy', 'oil', 'coil', 'toil', 'soil'
];
Plover["Vowel Disambiguator Chords"] = [
'wheel', 'wheal', 'read', 'reed', 'reel',
'real', 'heel', 'heal', 'hear', 'here',
'ware', 'wear', 'pea', 'pee', 'peace',
'piece', 'tee', 'tea', 'sea', 'see',
'tail', 'tale', 'sale', 'sail',
'stare', 'stair', 'waist', 'waste',
'hood', 'rude', 'pool', 'crew',
'soot', 'truce', 'school', 'ruse',
'road', 'rode', 'roar', 'toad', 'soar', 'sore'
];
Plover["The Missing Keys"] = [
'due', 'duffer', 'deferral', 'devil', 'double',
'drug', 'depress', 'desire', 'dessert', 'destroyed',
'feral', 'ford', 'for', 'phrase', 'fierce',
'fable', 'feeble', 'sphere', 'fries',
'leader', 'lace', 'letter', 'lust', 'lovers',
'glad', 'glare', 'glides', 'give', 'get', 'group',
'guest', 'guide', 'gravel', 'cigarette', 'goblet',
'bored', 'board', 'bruise', 'buyer', 'bobble', 'brutal',
'zest', 'zap', 'zag',
'vile', 'vase', 'virus',
'eke', 'rockets', 'correct', 'quake', 'task'
];
Plover["The Remaining Missing Letters"] = [
'nag', 'nap', 'nab', 'nut', 'never',
'nestle', 'nod', 'nest', 'nerd',
'pent', 'parent', 'went', 'earns', 'rant',
'hunt', 'hand', 'panel', 'stun',
'must', 'muffle', 'maggot', 'mallet', 'smuggle', 'morals',
'arm', 'rum', 'harm', 'tempt', 'term',
'calmed', 'palm', 'qualms',
'jut', 'jug', 'just', 'jest', 'jets',
'job', 'jostle', 'jazz', 'jagged',
'urge', 'edge', 'average', 'purge', 'trudge', 'storage',
'yard', 'yet', 'yurt'
];
Plover["Review Through Missing Letters"] = [
'noun', 'inhibit', 'nudge', 'notes', 'knack',
'enacts', 'neck', 'known', 'knock', 'gnome',
'noise', 'novice', 'named', 'neural', 'snide', 'announce',
'loin', 'donor', 'winner', 'dinner', 'learned', 'lend',
'allowance', 'flaunt', 'deference', 'different', 'dance', 'diner',
'demand', 'grunt', 'grant', 'gleans', 'severance', 'cement', 'design',
'mound', 'mourn', 'maim', 'matter', 'commit',
'commend', 'smudge', 'smuggle', 'semester',
'forms', 'primed', 'serum', 'time', 'hermit',
'maim', 'plumb', 'dream', 'gym', 'germ',
'jam', 'blame', 'bottom', 'grammar',
'balm', 'psalm',
'judge', 'journal', 'join', 'joyful', 'jam', 'genders',
'forge', 'budgets', 'average', 'leverage', 'merge',
'beige', 'carriage', 'fidget', 'frigid', 'digit',
'gadget', 'garage', 'grudge', 'turgid',
'year', 'yearn', 'yolk'
];
Plover["Digraphs"] = [
'thefts', 'thud', 'thus', 'thug',
'hath', 'earth', 'oath', 'health',
'wealth', 'worth', 'path', 'troth',
'chess', 'chest', 'chart', 'chat',
'chop', 'chore', 'chaff',
'touch', 'etch', 'ratchet', 'hutch',
'hatch', 'watch', 'patch', 'catch', 'crutch',
'such', 'sketch', 'stretch', 'retch',
'shell', 'shuffled', 'shall',
'ash', 'rush', 'rash', 'hush', 'hash',
'wash', 'push', 'posh', 'crush', 'crash',
'trash', 'squash', 'stash',
'anger', 'storing', 'rung', 'rang', 'prong',
'tongue', 'twang', 'song', 'stung', 'strong',
'sponge', 'orange'
];
Plover["Review Through Digraphs"] = [
'thing', 'thence', 'them', 'thumb',
'thrill', 'throng', 'thrash',
'seethe', 'method', 'math', 'birth', 'breath',
'fifth', 'death', 'sleuth', 'blithe', 'growth',
'choose', 'chasm', 'chuck', 'check',
'churn', 'cherub', 'chin', 'channel',
'chant', 'chance', 'chive', 'charm',
'bleach', 'much', 'latch', 'leech', 'match',
'botch', 'fetch', 'ditch', 'glitch', 'vouch',
'slouch', 'smooch', 'splotch',
'shim', 'slime', 'shrewd', 'shrine', 'shuck',
'shark', 'shock', 'sheesh', 'shrivel', 'sugar',
'lash', 'mesh', 'mash', 'plush', 'bush',
'brush', 'fish', 'fresh', 'flush', 'flesh',
'flash', 'dash', 'delish', 'gosh', 'gash',
'shush', 'slash', 'smush', 'slosh', 'splash',
'squish', 'Irish',
'anger', 'finger', 'dung', 'lung', 'ping',
'pong', 'among', 'bring', 'young', 'fang',
'flung', 'gang', 'belong',
'change', 'range', 'hinge', 'lounge', 'plunge',
'cringe', 'tinge', 'fringe', 'derange', 'grunge', 'syringe'
];
Plover["Common Compound Clusters"] = [
'hemp', 'trump', 'rump', 'romp', 'ramp',
'pump', 'camp', 'cramp', 'tamp', 'pomp',
'curve', 'carve', 'serve', 'swerve', 'starve',
'squelch',
'hulk', 'calc', 'sulk', 'talc',
'rank', 'honk', 'wonk', 'prank', 'crank', 'tank',
'session', 'option', 'ration', 'portion',
'passion', 'cushion', 'caption', 'suppression',
'section', 'correction', 'suction',
'arch', 'ranch', 'hunch', 'porch', 'crunch',
'quench', 'torch', 'trench', 'stench', 'starch',
];
Plover["Review Through Common Compound Clusters"] = [
'limp', 'blimp', 'chomp', 'clamp',
'damp', 'slump', 'shrimp', 'jump',
'nerve', 'verve', 'marvel',
'village', 'mulch', 'bulge', 'belch',
'bilge', 'gulch', 'pillage',
'ilk', 'milk', 'bulk', 'silk', 'bilk',
'wink', 'mink', 'plank', 'brink', 'blink',
'blank', 'flank', 'flunk', 'dank', 'drink',
'gunk', 'junk', 'link', 'chunk',
'lesion', 'provision', 'fusion', 'lotion',
'operation', 'mission', 'motion', 'pollution',
'election', 'auction', 'correction', 'collection',
'fraction', 'friction', 'depiction', 'selection', 'seduction',
'finch', 'clench', 'branch', 'march', 'lurch',
'lynch', 'birch', 'brunch', 'church', 'drench'
];
Plover["Common Briefs 1-20"] = [
"the", "of", "to", "in", "a",
"is", "that", "with", "be", "by",
"he", "I", "this", "are", "which",
"have", "they", "you", "you'd", "you'll"
];
Plover["Common Briefs 21-40"] = [
"you're", "you've", "were", "can", "there",
"been", "if", "would", "who", "other",
"what", "only", "do", "new", "about",
"two", "any", "could", "after", "said"
];
Plover["Common Briefs 41-60"] = [
"very", "many", "even", "where", "through",
"being", "because", "before", "upon", "without",
"another", "against", "every", "within", "example",
"others", "therefore", "having", "become", "whether"
];
Plover["Common Briefs 61-80"] = [
"somebody", "somehow", "someone", "someplace", "something",
"sometimes", "somewhere", "question", "almost", "interest",
"ever", "became", "probably", "include", "includes",
"included", "including", "amount", "receive", "received"
];
Plover["Common Briefs 81-100"] = [
"describe", "described", "anything", "continue", "continued",
"beginning", "understand", "understanding", "today", "opinion",
"becomes", "yes", "idea", "ideas", "actually",
"move", "ask", "unless", "easy", "otherwise"
];
})(); // Execute the code in the wrapper function.
|
"use strict";
// ControlBar plugin
var bufferingDirectives = angular.module("com.2fdevs.videogular.plugins.buffering", []);
bufferingDirectives.directive("vgBuffering", function(VG_EVENTS, VG_THEMES){
return {
restrict: "E",
template:
"<div class='bufferingContainer'>" +
"<div class='loadingSpinner stop'></div>" +
"</div>",
link: function(scope, elem, attrs) {
function onPlayerReady(target, params) {
spinner.addClass("stop");
elem.css("display", "none");
}
function onBuffering(target, params) {
spinner.removeClass("stop");
elem.css("display", "block");
}
function onStartPlaying(target, params) {
spinner.addClass("stop");
elem.css("display", "none");
}
var spinner = angular.element(elem[0].getElementsByClassName("loadingSpinner"));
spinner.removeClass("stop");
scope.$on(VG_EVENTS.ON_BUFFERING, onBuffering);
scope.$on(VG_EVENTS.ON_START_PLAYING, onStartPlaying);
scope.$on(VG_EVENTS.ON_PLAYER_READY, onPlayerReady);
}
}
}
);
|
import {
AyzekPlugin,
command,
middleware
}
from '../../';
import XPress from '@meteor-it/xpress';
import AJSON from '@meteor-it/ajson';
import {
addSupport as wsSupport
}
from '@meteor-it/xpress/support/ws';
import {
hashCode,
djb2Code,
sdbmCode,
loseCode
}
from '@meteor-it/utils';
let chatClients = {};
let tokenChatMap = new Map();
function hashToken(text) {
// body...
return `${hashCode(text).toString(36)}:${djb2Code(text).toString(36)}:${sdbmCode(text).toString(36)}:${loseCode(text).toString(36)}`;
}
export default class YourOwnPlugin extends AyzekPlugin {
static description = 'Плагин для создания ваших плагинов';
@middleware({
event: 'pre'
})
async pre(msg) {
let chatToken = msg.chat ? hashToken(msg.chat.cid) : hashToken(msg.user.uid);
if (!tokenChatMap.has(chatToken)) {
tokenChatMap.set(chatToken, msg.chat ? msg.chat : msg.user);
}
if (chatClients[chatToken])
chatClients[chatToken].forEach(client => {
client.send(AJSON.stringify({
text: msg.text,
chatToken,
sender: {
firstName: msg.user.firstName,
lastName: msg.user.lastName,
uid: msg.user.uid
},
chat: msg.chat ? {
title: msg.chat.title,
cid: msg.chat.cid
} : null,
replyTo: msg.replyTo ? {
text: msg.replyTo.text,
sender: {
firstName: msg.replyTo.sender.firstName,
lastName: msg.replyTo.sender.lastName,
uid: msg.replyTo.sender.uid
}
} : null
}));
});
return true;
}
server;
async init() {
let app = new XPress('ayzeksdk');
app.onListen(wsSupport);
app.on('WS /:code', (req, socket) => {
let code = (req.params.code);
if (!chatClients[code])
chatClients[code] = [socket];
else
chatClients[code].push(socket);
console.log(code);
socket.on('message', msg => {
console.log(msg);
if (!tokenChatMap.has(code))
return;
console.log(msg);
try {
console.log(msg);
msg = JSON.parse(msg);
tokenChatMap.get(code).sendText(false, msg.text);
}
catch (e) {
console.log(msg);
socket.close();
}
});
socket.on('close', () => {
chatClients[code] = chatClients[code].filter(client => client !== socket);
});
});
this.server = await app.listenHttp('0.0.0.0', 1488);
}
async deinit() {
this.server.close();
}
@command({
names: ['yoplugintoken'],
helpMessage: 'Получить токен для подключения своего плагина'
})
async yop(msg, args) {
let code = msg.chat ? hashToken(msg.chat.cid) : hashToken(msg.user.uid);
await msg.sendText(true, `Инструментарий AyzekSDK готов к подключению!\nТокен для подключения: ${code}\nНе знаете что с ним делать? Прочитайте инструкцию на сайте бота: http://ayzek.f6cf.pw/sdk`);
}
}
|
'use strict'
exports.handler = (event, context, callback) => {
if (typeof(event.ramuda_action) !== "undefined" && event.ramuda_action === "ping") {
context.done(null, "alive")
return true
}
if (typeof(event.ramuda_action) !== "undefined" && event.ramuda_action === "getenv") {
context.done(null, process.env)
return true
}
console.log('process.env value:')
console.log(process.env)
}
|
/* eslint-disable no-param-reassign */
import { DokkaError, DokkaGenericError } from '../config/errors'
export default module.exports = (app) => {
const Users = app.db.models.Users
const Tokens = app.db.models.Tokens
return {
checkToken: (req, res) =>
Tokens.findOne({ where: { token: req.params.token } })
.then((token) => {
if (!token) throw new Error('Verification token not found')
if (token.expired) throw new Error('Email already confirmed')
return Users.findById(token.user_id)
})
.then((user) => {
if (!user) throw new Error('Invalid token, server error')
user.emailVerified = true
return user.save()
})
.then((token) => {
token.expired = true
return token.save()
})
.then(() => res.sendStatus(200))
.catch((error) => {
if (error instanceof DokkaError) {
throw error
} else {
throw new DokkaGenericError(error)
}
}),
}
}
|
var Animation = require('./Animation/Animation.js')
var Circle = require('./Canvas/Shape/Circle.js')
var extend = require('./extend.js')
var Layer = require('./Canvas/Layer.js')
var Stage = require('./Canvas/Stage.js')
var Juggler = (function () {
var abc = "abcdefghijklmnopqrstuvwxyz"
var nums = {}
for (var i = 0; i < 10; ++i) {
nums[i] = i
}
for (var i = 0; i < abc.length; ++i) {
nums[abc[i]] = i + 10
}
function recalculate (attrs, maximum) {
var juggling = attrs.juggling
var stage = attrs.stage
var K = (maximum - juggling.waiting.time) * juggling.interval
var width
if (stage.width) {
var k = (juggling.integer_height - juggling.waiting.time) * juggling.interval
var r = k / K //(k * k) / (K * K)
width = r * stage.width
console.log('uu', r)
} else {
var k = (3 - juggling.waiting.time) * juggling.interval
var r = k / K // (k * k) / (K * K)
width = 1.5 * juggling.height * r
}
return {
width: 0.5 * width,
gravity: 8 * juggling.height / (K * K),
shift: juggling.waiting.shift * r,
radius: juggling.balls.radius * r
}
}
function Juggler(attrs) {
console.log(attrs.stage)
this.attrs = {}
this.attrs = extend(true, this.attrs, {
stage: {
width: 500,
height: 650
},
juggling: {
interval: 500,
waiting: {
time: 0.5,
shift: 50,
},
integer_height: 5,
balls: {
radius: 10,
colors: ['red', 'blue', 'green', 'yellow', 'black', 'orange', 'purple']
},
height: 0.8 * attrs.stage.height,
center: {
x: 0.5 * attrs.stage.width,
y: 0.9 * attrs.stage.height
}
},
layer: new Layer()
}, attrs)
this.attrs.stage = new Stage(this.attrs.stage)
this.attrs.stage.add(this.attrs.layer)
var juggling = this.attrs.juggling
var target = recalculate(this.attrs, this.attrs.juggling.integer_height)
juggling.width = target.width
juggling.gravity = target.gravity
}
Juggler.toPattern = function (string) {
return string.split('').map(function(e) {
return nums[e]
})
}
Juggler.prototype.setPattern = function (pattern) {
if (typeof pattern === 'string') {
pattern = Juggler.toPattern(pattern)
}
var attrs = this.attrs
var stage = attrs.stage
var juggling = attrs.juggling
var radius, shift, gravity, width
var maximum = Math.max.apply(null, pattern)
if (maximum > juggling.integer_height) {
var target = recalculate(attrs, maximum)
width = target.width
gravity = target.gravity
shift = target.shift
radius = target.radius
} else {
shift = juggling.waiting.shift
width = juggling.width
gravity = juggling.gravity
radius = juggling.balls.radius
}
//console.log(width, gravity, radius, shift)
var num_balls = pattern.reduce(function (a, b) {
return a + b
}, 0)
if (num_balls % pattern.length != 0) {
throw new Error('El patró es irrealitzable. Es necessita un nombre enter de boles. Actualment: ' + num_balls / pattern.length)
}
num_balls /= pattern.length
var numbers = [] // throws
for (var i = 0; i < pattern.length; ++i) {
var number = {}
number.value = pattern[i]
number.next = (i + number.value) % pattern.length
number.period = (number.value - juggling.waiting.time) * juggling.interval
number.velocity = 0.5 * gravity * number.period
numbers.push(number)
}
for (var i = 0; i < pattern.length; ++i) {
if (!numbers[i].cycle) {
var cycle_flags = {}
var index = i
var cycle = 0
while (!cycle_flags[index]) {
cycle_flags[index] = true
index = numbers[index].next
cycle += numbers[index].value
}
for (var index in cycle_flags) {
numbers[index].cycle = cycle
}
}
}
var y0 = juggling.center.y
shift /= 2
var left = juggling.center.x - (width / 2)
var right = juggling.center.x + (width / 2)
var j = 0
var jmod = 0
var i = 0
var k = 0
var begin = {}
this.balls = []
while (i < num_balls) {
if (numbers[jmod].value !== 0) {
if (begin[j] === undefined) {
begin[j] = i
begin[j + numbers[jmod].value] = i
++i
var ball = {
figure: new Circle({
x: j % 2 === 0 ? left + 15 : right -15,
y: y0,
radius: radius || 10,
fill: juggling.balls.colors[k% juggling.balls.colors.length],
}),
start: j,
cycle: numbers[jmod].cycle
}
this.balls.push(ball)
attrs.layer.add(ball.figure)
++k
} else {
begin[j + numbers[jmod].value] = numbers[jmod].value
}
}
++j
jmod = j % numbers.length
}
var self = this
//attrs.stage.add(attrs.layer)
attrs.animation = new Animation(function(frame) {
var steps = Math.floor(frame.time / juggling.interval)
//console.log(steps)
self.balls.forEach(function (ball) {
var t = frame.time - juggling.interval * ball.start
if (t >= 0) {
t %= ball.cycle * juggling.interval
var i = ball.start % numbers.length
var pattern
while (true) {
pattern = numbers[i].value
var time = pattern * juggling.interval
if (time > t) {
break
} else {
t -= time
}
i = numbers[i].next
}
var step = steps - Math.floor(t / juggling.interval)
var position = {}
if (step % 2 === 0) {
position.start = {
x: left + shift,
y: y0
}
} else {
position.start = {
x: right - shift,
y: y0
}
}
if ((step + numbers[i].value) % 2 === 0) {
position.middle = {
x: left - shift,
y: y0
}
position.end = {
x: left + shift,
y: y0
}
} else {
position.middle = {
x: right + shift,
y: y0
}
position.end = {
x: right - shift,
y: y0
}
}
var f = {
value: numbers[i].value,
time: {
total: juggling.interval,
thrown: numbers[i].period,
caught: juggling.interval * numbers[i].value - numbers[i].period,
now: t
},
left: step % 2 === 0,
gravity: gravity,
position: position
}
behaviour(ball.figure, f)
}
})
attrs.layer.draw()
})
}
Juggler.prototype.removePattern = function () {
var self = this
self.attrs.animation.stop()
self.attrs.layer.remove()
//self.attrs.layer = new Kinetic.Layer()
}
Juggler.prototype.play = function () {
this.attrs.animation.play()
}
Juggler.prototype.pause = function () {
this.attrs.animation.pause()
}
Juggler.prototype.stop = function () {
this.attrs.animation.stop()
this.attrs.layer.remove()
}
Juggler.prototype.speed = function (speed) {
this.attrs.animation.speed(speed)
}
Juggler.prototype.colors = function (colors) {
this.stop()
this.attrs.juggling.balls.colors = [].concat(colors)
}
return Juggler
})()
function behaviour(figure, frame) {
var time = frame.time
var position = frame.position
var width
var now = time.now
if (now < time.thrown) {
// thrown
width = position.middle.x - position.start.x
figure.setX(position.start.x + width * now / time.thrown)
var velocity = 0.5 * frame.gravity * time.thrown
figure.setY(position.start.y - velocity * now + 0.5 * frame.gravity * now * now)
} else {
// caught
width = position.end.x - position.middle.x
figure.setX(position.middle.x + width * (now - time.thrown) / time.caught)
figure.setY(position.middle.y)
}
}
module.exports = Juggler |
#!/usr/bin/env node
'use strict';
const fs = require('fs');
const path = require('path');
const package_json = path.resolve('./package.json');
const tsconfig_json = path.resolve('./tsconfig.json');
const webpack_config_js = path.resolve('./webpack.config.js');
const git_ignore_file = path.resolve('./.gitignore');
const eslint_file = path.resolve('./.eslintrc.js');
const index_html = path.resolve('./index.html');
const main_tsx = path.resolve('./src/main.tsx');
const spa_index = path.resolve('./index.html');
const spa_main_tsx = path.resolve('./src/main.tsx');
const spa_layout_tsx = path.resolve('./src/Layout.tsx');
const readme_md = path.resolve('./README.md');
const build_js = path.resolve('./_build.js');
const execSync = require('child_process').execSync;
const program = require('commander');
const dir_src = './src';
const dir_tests = './tests';
const dir_stories = './src/stories'
let show_start = false;
let show_test = false;
let es5 = false;
let esbuild = false;
function read(name) {
return fs.readFileSync(path.resolve(__dirname + '/cli-templates', name), 'utf8');
}
function write(file_name, text, title = ' * Creating', overwrite = false) {
const file = path.resolve(file_name);
if (!fs.existsSync(file) || overwrite) {
process.stdout.write(`${title}: ${file} ... `);
fs.writeFileSync(
file,
text
);
process.stdout.write('Done\n');
} else {
process.stdout.write(` * No change made. File exists: ${file}\n`);
}
}
function init() {
RegExp.prototype.toJSON = RegExp.prototype.toString;
if (!fs.existsSync(package_json)) {
console.log(' * Initializing package.json');
execSync('npm init -y');
}
if (!fs.existsSync(dir_src)) fs.mkdirSync(dir_src);
const packages_es5 = 'npm install -D apprun@es5 typescript webpack webpack-cli webpack-dev-server ts-loader source-map-loader';
const packages_es6 = 'npm install -D apprun typescript webpack webpack-cli webpack-dev-server ts-loader source-map-loader';
console.log(' * Installing packages. This might take a few minutes.');
if (!esbuild) {
es5
? execSync(packages_es5)
: execSync(packages_es6);
} else {
es5
? execSync('npm install -D apprun@es5 apprun-dev-server esbuild')
: execSync('npm install -D apprun apprun-dev-server esbuild');
}
es5
? write(tsconfig_json, read('tsconfig.es5.json'), ' * Configuring typescript - es5', true)
: write(tsconfig_json, read('tsconfig.es6.json'), ' * Configuring typescript - es2015', true);
write(index_html, read('index.html'));
write(main_tsx, read('main.ts_'));
write(readme_md, read('readme.md'));
console.log(' * Adding npm scripts');
const package_info = require(package_json);
if (!package_info.scripts) package_info["scripts"] = {}
if (!esbuild) {
if (!package_info.scripts['start']) {
package_info["scripts"]["start"] = 'webpack serve --mode development';
}
if (!package_info.scripts['build']) {
package_info["scripts"]["build"] = 'webpack --mode production';
}
write(webpack_config_js, read('webpack.config.js'))
} else {
write(build_js, read('_build.js'));
if (!package_info.scripts['start']) {
package_info["scripts"]["start"] = 'node _build start';
}
if (!package_info.scripts['build']) {
package_info["scripts"]["build"] = 'node _build';
}
}
if (!package_info.scripts['tsc:watch']) {
package_info['scripts']['tsc:watch'] = 'tsc -w';
}
save_package_json(package_info);
git_init();
// jest_init();
show_start = true;
}
function save_package_json(package_info) {
fs.writeFileSync(
package_json,
JSON.stringify(package_info, null, 2)
);
}
function git_init() {
if (!fs.existsSync('.git')) {
console.log(' * Initializing git');
execSync('git init');
} else {
console.log(' * Skip git init. .git exsits');
}
write(git_ignore_file, read('_gitignore'));
}
function component(name) {
if (!fs.existsSync(dir_src)) fs.mkdirSync(dir_src);
const fn = path.resolve(dir_src + '/' + name + '.tsx');
const component_template = read('component.ts_');
write(fn, component_template.replace(/\#name/g, name),
`Creating component ${name}`);
show_start = true;
}
function jest_init() {
console.log(' * Installing jest');
execSync('npm i @types/jest jest ts-jest --save-dev');
const jest_config = {
"preset": "ts-jest",
}
const package_info = require(package_json) || {};
package_info["jest"] = jest_config
package_info["scripts"]["test"] = 'jest --watch';
save_package_json(package_info);
show_test = true;
}
function lint_init() {
console.log(' * Installing ESLint');
execSync('npm install --save-dev eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin');
const package_info = require(package_json) || {};
package_info["scripts"]["lint"] = 'eslint src';
package_info["scripts"]["lint:fix"] = 'eslint src --fix';
save_package_json(package_info);
write(eslint_file, read('_eslintrc.js'));
}
function component_spec(name) {
if (!fs.existsSync(dir_tests)) fs.mkdirSync(dir_tests);
const fn = path.resolve(dir_tests + '/' + name + '.spec.ts');
const test_template = read('spec.ts_');
write(fn, test_template.replace(/\#name/g, name),
`Creating component spec ${name}`);
show_test = true;
}
function component_story(name) {
if (!fs.existsSync(dir_stories)) fs.mkdirSync(dir_stories);
const fn = path.resolve(dir_stories + '/' + name + '.stories.tsx');
const story_template = read('stories.js_');
write(fn, story_template.replace(/\#name/g, name),
`Creating component stories ${name}`);
}
function spa() {
if (!fs.existsSync(dir_src)) fs.mkdirSync(dir_src);
write(spa_index, read('spa_index.html'), 'Creating', true);
write(spa_main_tsx, read('spa_main.ts_'), 'Creating', true);
write(spa_layout_tsx, read('Layout.ts_'), 'Creating', true);
component('Home');
component('About');
component('Contact');
show_start = true;
}
program
.name('apprun')
.version('2.27')
.option('-i, --init', 'Initialize AppRun Project')
.option('-c, --component <file>', 'Generate AppRun component')
.option('-g, --git', 'Initialize git repository')
.option('-j, --jest', 'Install jest')
.option('-l, --lint', 'Install ESLint')
.option('-t, --test <file>', 'Generate component spec')
.option('-o, --story <file>', 'Generate component stories')
.option('-s, --spa', 'Generate SPA app')
.option('-5, --es5', 'Use apprun@es5')
.option('-e, --esbuild', 'Use esbuild')
.parse(process.argv);
program._name = 'apprun';
const options = program.opts();
if (!options.init && !options.component && !options.git && !options.jest &&
!options.test && !options.spa && !options.lint && !options.story) {
program.outputHelp();
process.exit()
}
if (options.es5) es5 = true;
if (options.esbuild) esbuild = true;
if (options.init) init();
if (options.component) component(program.component);
if (options.git) git_init();
if (options.jest) jest_init();
if (options.lint) lint_init();
if (options.test) component_spec(program.test);
if (options.story) component_story(program.story);
if (options.spa) spa();
console.log('\r');
if (show_start) console.log('All done. You can run `npm start` and then navigate to http://localhost:8080 in a browser.');
//if (show_test) console.log('All done. You can run `npm test`.');
|
'use strict';
module.exports = function(sequelize, DataTypes){
const Audit = sequelize.define("Audit", {
entityType: {
type: DataTypes.STRING,
allowNull: false,
comment: 'Type of the entity which change is tracked. E.g. USER, LEAVE etc',
},
entityId: {
type: DataTypes.INTEGER,
allowNull: false,
comment: 'ID of the entity defined by entityType',
},
attribute: {
type: DataTypes.STRING,
allowNull: false,
comment: 'Attribute of the entity which chnage is to be recorded',
},
oldValue: {
type: DataTypes.STRING,
allowNull: true,
comment: 'Old value converted to STRING',
},
newValue: {
type: DataTypes.STRING,
allowNull: true,
comment: 'New value converted to STRING',
},
}, {
underscored : true,
freezeTableName : true,
timestamps : true,
createdAt : 'at',
updatedAt : false,
tableName : 'audit',
classMethods : {
associate : (models) => {
Audit.belongsTo(models.Company, {
as : 'company',
foreignKey : 'companyId',
});
Audit.belongsTo(models.User, {
as: 'byUser',
foreignKey: 'byUserId',
});
},
},
});
return Audit;
};
|
/* */
var Code = require("code");
var Hawk = require("../lib/index");
var Lab = require("lab");
var Package = require("../package.json!systemjs-json");
var internals = {};
var lab = exports.lab = Lab.script();
var describe = lab.experiment;
var it = lab.test;
var expect = Code.expect;
describe('Hawk', function() {
describe('Utils', function() {
describe('#parseHost', function() {
it('returns port 80 for non tls node request', function(done) {
var req = {
method: 'POST',
url: '/resource/4?filter=a',
headers: {
host: 'example.com',
'content-type': 'text/plain;x=y'
}
};
expect(Hawk.utils.parseHost(req, 'Host').port).to.equal(80);
done();
});
it('returns port 443 for non tls node request', function(done) {
var req = {
method: 'POST',
url: '/resource/4?filter=a',
headers: {
host: 'example.com',
'content-type': 'text/plain;x=y'
},
connection: {encrypted: true}
};
expect(Hawk.utils.parseHost(req, 'Host').port).to.equal(443);
done();
});
it('returns port 443 for non tls node request (IPv6)', function(done) {
var req = {
method: 'POST',
url: '/resource/4?filter=a',
headers: {
host: '[123:123:123]',
'content-type': 'text/plain;x=y'
},
connection: {encrypted: true}
};
expect(Hawk.utils.parseHost(req, 'Host').port).to.equal(443);
done();
});
it('parses IPv6 headers', function(done) {
var req = {
method: 'POST',
url: '/resource/4?filter=a',
headers: {
host: '[123:123:123]:8000',
'content-type': 'text/plain;x=y'
},
connection: {encrypted: true}
};
var host = Hawk.utils.parseHost(req, 'Host');
expect(host.port).to.equal('8000');
expect(host.name).to.equal('[123:123:123]');
done();
});
});
describe('#version', function() {
it('returns the correct package version number', function(done) {
expect(Hawk.utils.version()).to.equal(Package.version);
done();
});
});
describe('#unauthorized', function() {
it('returns a hawk 401', function(done) {
expect(Hawk.utils.unauthorized('kaboom').output.headers['WWW-Authenticate']).to.equal('Hawk error="kaboom"');
done();
});
});
});
});
|
'use strict';
angular.module('core').controller('HomeController', ['$scope', '$http', 'Authentication', 'Beneficiaries',
function ($scope, $http, Authentication, Beneficiaries) {
// This provides Authentication context.
$scope.authentication = Authentication;
// Gender Stats
$scope.genderStats = function () {
// Chart.js Data
$scope.data = {
labels: ['Black', 'White', 'Coloured', 'Indian/Asian'],
datasets: []
};
// Chart.js Options
$scope.options = {
// Sets the chart to be responsive
responsive: true,
//Boolean - Whether the scale should start at zero, or an order of magnitude down from the lowest value
scaleBeginAtZero: true,
//Boolean - Whether grid lines are shown across the chart
scaleShowGridLines: true,
//String - Colour of the grid lines
scaleGridLineColor: "rgba(0,0,0,.05)",
//Number - Width of the grid lines
scaleGridLineWidth: 1,
//Boolean - If there is a stroke on each bar
barShowStroke: true,
//Number - Pixel width of the bar stroke
barStrokeWidth: 2,
//Number - Spacing between each of the X value sets
barValueSpacing: 5,
//Number - Spacing between data sets within X values
barDatasetSpacing: 1
};
$http({method: 'GET', url: '/beneficiaries/males'}).
success(function (maleBeneficiaries, status, headers, config) {
var blackMale = 0;
var whiteMale = 0;
var colouredMale = 0;
var indianAsianMale = 0;
for (var i in maleBeneficiaries) {
console.log(maleBeneficiaries[i].race);
switch (maleBeneficiaries[i].race) {
case "Black":
blackMale = blackMale + 1;
break;
case "White":
whiteMale = blackMale + 1;
break;
case "Coloured":
colouredMale = colouredMale + 1;
break;
case "Indian/Asian":
indianAsianMale = indianAsianMale + 1;
break;
}
}
var maleData = {
label: 'Male',
fillColor: '#1abc9c',
strokeColor: '#16a085',
highlightFill: 'rgba(220,220,220,0.75)',
highlightStroke: 'rgba(220,220,220,1)',
data: [blackMale, whiteMale, colouredMale, indianAsianMale]
};
$scope.data.datasets.push(maleData);
}).
error(function (data, status, headers, config) {
});
$http({method: 'GET', url: '/beneficiaries/females'}).
success(function (femaleBeneficiaries, status, headers, config) {
var blackFemale = 0;
var whiteFemale = 0;
var colouredFemale = 0;
var indianAsianFemale = 0;
for (var i in femaleBeneficiaries) {
console.log(femaleBeneficiaries[i].race);
switch (femaleBeneficiaries[i].race) {
case "Black":
blackFemale = blackFemale + 1;
break;
case "White":
whiteFemale = whiteFemale + 1;
break;
case "Coloured":
colouredFemale = colouredFemale + 1;
break;
case "Indian/Asian":
indianAsianFemale = indianAsianFemale + 1;
break;
}
}
var femaleData = {
label: 'Female',
fillColor: '#2980b9',
strokeColor: '#3498db',
highlightFill: 'rgba(220,220,220,0.75)',
highlightStroke: 'rgba(220,220,220,1)',
data: [blackFemale, whiteFemale, colouredFemale, indianAsianFemale]
};
$scope.data.datasets.push(femaleData);
}).
error(function (data, status, headers, config) {
});
};
}
]); |
export { default as GoogleLayer } from "./GoogleLayer";
|
import React from 'react';
import PropTypes from 'prop-types';
/**
* This portion leads to underlying translation
* 4. msgid "one more"
* msgid_plural "__num__ more"
*/
const More = ({ngettext, num, onClick}) => (
<a href="" onClick={onClick}>{ngettext(num)`one more|${{num}} more`}</a>
);
More.propTypes = {
ngettext: PropTypes.func.isRequired,
num: PropTypes.number.isRequired,
onClick: PropTypes.func.isRequired
};
/**
* This portion leads to underlying translation
* 5. msgid "one less"
* msgid_plural "__num__ less"
*/
const Less = ({ngettext, num, onClick}) => (
<a href="" onClick={onClick}>{ngettext(num)`one less|${{num}} less`}</a>
);
Less.propTypes = {
ngettext: PropTypes.func.isRequired,
num: PropTypes.number.isRequired,
onClick: PropTypes.func.isRequired
};
/**
* Pagination control for progressively expanding to more items or then contract to fewer.
*
* This example has 5 underlying translations
* 1. msgid "Show __numMoreItems__ or __numLessItems__"
* 2. msgid "Show __numMoreItems__"
* 3. msgid "Show __numLessItems__"
* 4. msgid "one more"
* msgid_plural "__num__ more"
* 5. msgid "one less"
* msgid_plural "__num__ less"
*/
export const PaginationControl = ({
gettext, ngettext, currentSize, totalSize, pageSize, minSize, onMore, onLess
}) => {
const numMore = Math.min(totalSize - currentSize, pageSize);
const numLess = Math.max(0, Math.min(currentSize - (minSize || pageSize), pageSize));
switch (true) {
case (numMore > 0) && (numLess > 0):
return (<div>{
gettext`Show ${{
numMoreItems: <More num={numMore} onClick={onMore} {...{ngettext}} />
}} or ${{
numLessItems: <Less num={numLess} onClick={onLess} {...{ngettext}} />
}}`
}</div>);
case (numMore > 0):
return (<div>{
gettext`Show ${{
numMoreItems: <More num={numMore} onClick={onMore} {...{ngettext}} />
}}`
}</div>);
case (numLess > 0):
return (<div>{
gettext`Show ${{
numLessItems: <Less num={numLess} onClick={onLess} {...{ngettext}} />
}}`
}</div>);
default:
return null;
}
};
PaginationControl.propTypes = {
gettext: PropTypes.func.isRequired,
ngettext: PropTypes.func.isRequired,
currentSize: PropTypes.number,
totalSize: PropTypes.number,
pageSize: PropTypes.number.isRequired,
minSize: PropTypes.number,
onMore: PropTypes.func,
onLess: PropTypes.func
};
PaginationControl.defaultProps = {
currentSize: NaN,
totalSize: NaN,
minSize: NaN,
onMore: () => {},
onLess: () => {}
};
|
define({
"_widgetLabel": "Ringkasan",
"filter": "Filter",
"all": "Semua",
"missingLayerInWebMap": "Tidak Ada Layer Operasional dalam Web Map.",
"missingSummaryLayerInConfig": "Layer ringkasan hilang."
}); |
import cal from "highlight.js/lib/languages/cal";
export default cal;
|
// Object to store properties of a data row.
function TabularVizDataRow(rowHash, columns) {
this.data = {};
this.cells = [];
this.shown = true;
// We store the entire data hash, not just the columns for this particular viz.
// This is important because we may use non-column fields to evaluate a
// dataShowfor.
var hashKeys = Object.keys(rowHash);
for(var i = 0; i < hashKeys.length; i++) {
var key = hashKeys[i];
this.data[key] = {
'label': rowHash[key].label,
'value': rowHash[key].value,
};
}
// Then we construct the cells separately.
for(var col = 0; col < columns.length; col++) {
var column = columns[col];
// If there's a column missing from the data, provide a helpful error message.
if(typeof this.data[column.source] === 'undefined') {
throw new Error('Worksheet is missing a field: "' + column.source + '"');
}
this.cells.push({
'label': this.data[column.source].label,
'value': this.data[column.source].value,
});
}
}
|
'use strict';
// FileMaker JDBC Table Builder & Compiler
// Because of the limited abilities of FileMaker's JDBC Driver I've omited even
// the few parts that would work (create table, add/drop columns, create indexes)
// Because those would be altered in FileMaker realistically.
// -------
module.exports = function(client) {
var _ = require('lodash');
var inherits = require('inherits');
var Schema = require('../../../schema');
// Table
// ------
function TableBuilder_FILEMAKER_JDBC() {
this.client = client;
Schema.TableBuilder.apply(this, arguments);
}
inherits(TableBuilder_FILEMAKER_JDBC, Schema.TableBuilder);
function TableCompiler_FILEMAKER_JDBC() {
this.client = client;
this.Formatter = client.Formatter;
Schema.TableCompiler.apply(this, arguments);
}
inherits(TableCompiler_FILEMAKER_JDBC, Schema.TableCompiler);
client.TableBuilder = TableBuilder_FILEMAKER_JDBC;
client.TableCompiler = TableCompiler_FILEMAKER_JDBC;
};
|
/* eslint-disable no-await-in-loop */
const { strict: assert } = require('assert');
const { createWriteStream } = require('fs');
const stream = require('stream');
const { promisify } = require('util');
const Got = require('got');
const ms = require('ms');
const pipeline = promisify(stream.pipeline);
const debug = require('./debug');
const FINISHED = new Set(['FINISHED']);
const RESULTS = new Set(['REVIEW', 'PASSED', 'SKIPPED']);
class API {
constructor({ baseUrl, bearerToken } = {}) {
assert(baseUrl, 'argument property "baseUrl" missing');
const { get, post } = Got.extend({
prefixUrl: baseUrl,
throwHttpErrors: false,
followRedirect: false,
headers: {
...(bearerToken ? { authorization: `bearer ${bearerToken}` } : undefined),
'content-type': 'application/json',
},
responseType: 'json',
retry: 0,
timeout: 10000,
});
this.get = get;
this.post = post;
this.stream = Got.extend({
prefixUrl: baseUrl,
throwHttpErrors: false,
followRedirect: false,
headers: {
...(bearerToken ? { authorization: `bearer ${bearerToken}` } : undefined),
'content-type': 'application/json',
},
retry: 0,
}).stream;
}
async getAllTestModules() {
const { statusCode, body: response } = await this.get('api/runner/available');
assert.equal(statusCode, 200);
return response;
}
async createTestPlan({ planName, configuration, variant } = {}) {
assert(planName, 'argument property "planName" missing');
assert(configuration, 'argument property "configuration" missing');
const { statusCode, body: response } = await this.post('api/plan', {
searchParams: {
planName,
...(variant ? { variant } : undefined),
},
json: configuration,
});
assert.equal(statusCode, 201);
return response;
}
async createTestFromPlan({ plan, test, variant } = {}) {
assert(plan, 'argument property "plan" missing');
assert(test, 'argument property "test" missing');
const searchParams = { test, plan };
if (variant) {
Object.assign(searchParams, { variant: JSON.stringify(variant) });
}
const { statusCode, body: response } = await this.post('api/runner', {
searchParams,
});
assert.equal(statusCode, 201);
return response;
}
async getModuleInfo({ moduleId } = {}) {
assert(moduleId, 'argument property "moduleId" missing');
const { statusCode, body: response } = await this.get(`api/info/${moduleId}`);
assert.equal(statusCode, 200);
return response;
}
async getTestLog({ moduleId } = {}) {
assert(moduleId, 'argument property "moduleId" missing');
const { statusCode, body: response } = await this.get(`api/log/${moduleId}`);
assert.equal(statusCode, 200);
return response;
}
async downloadArtifact({ planId } = {}) {
assert(planId, 'argument property "planId" missing');
const filename = `export-${planId}.zip`;
return pipeline(
this.stream(`api/plan/exporthtml/${planId}`, {
headers: { accept: 'application/zip' },
responseType: 'buffer',
}),
createWriteStream(filename),
);
}
async waitForState({ moduleId, timeout = ms('4m') } = {}) {
assert(moduleId, 'argument property "moduleId" missing');
assert(moduleId, 'argument property "states" missing');
assert(moduleId, 'argument property "timeout" missing');
const timeoutAt = Date.now() + timeout;
while (Date.now() < timeoutAt) {
const { status, result } = await this.getModuleInfo({ moduleId });
if (!['WAITING', 'FINISHED', 'RUNNING', 'CREATED'].includes(status)) {
debug('module id %s status is %s', moduleId, status);
}
if (FINISHED.has(status)) {
if (!status || !result) continue; // eslint-disable-line no-continue
if (!RESULTS.has(result)) {
throw new Error(`module id ${moduleId} is ${status} but ${result}`);
}
return [status, result];
}
if (status === 'INTERRUPTED') {
debug(await this.getTestLog({ moduleId }));
throw new Error(`module id ${moduleId} is ${status}`);
}
await new Promise((resolve) => setTimeout(resolve, ms('2s')));
}
debug(`module id ${moduleId} expected state timeout`);
throw new Error(`Timed out waiting for test module ${moduleId} to be in one of states: ${[...FINISHED].join(', ')}`);
}
}
module.exports = API;
|
(function () {
'use strict';
var express = require('express');
var load = require('express-load');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
module.exports = function () {
var app = express();
// Configurações de ambiente
app.set('port', 3000);
// middlewares
app.use(express.static('./public')); // directory - html and css
app.set('view engine', 'ejs');
app.set('views', './app/views');
// middleware - parser of methods put and delete
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(methodOverride());
// routes
load('models', { cwd: 'app' })
.then('controllers')
.then('routes')
.into(app)
// 404 route configuration
app.get('*', function (req, res) {
res.status(404).render('404');
});
return app;
};
})();
|
function fn(phone) {
phone = phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
return phone;
}
(function($){
$.fn.extend({
insertAtCaret: function(myValue){
var $t=$(this)[0];
if (document.selection) {
this.focus();
sel = document.selection.createRange();
sel.text = myValue;
this.focus();
}
else
if ($t.selectionStart || $t.selectionStart == '0') {
var startPos = $t.selectionStart;
var endPos = $t.selectionEnd;
var scrollTop = $t.scrollTop;
$t.value = $t.value.substring(0, startPos) + myValue + $t.value.substring(endPos, $t.value.length);
this.focus();
$t.selectionStart = startPos + myValue.length;
$t.selectionEnd = startPos + myValue.length;
$t.scrollTop = scrollTop;
}
else {
this.value += myValue;
this.focus();
}
}
})
})(jQuery);
//获取光标位置函数
function getCursortPosition (ctrl) {
var CaretPos = 0; // IE Support
if (document.selection) {
ctrl.focus ();
var Sel = document.selection.createRange ();
Sel.moveStart ('character', -ctrl.value.length);
CaretPos = Sel.text.length;
}
// Firefox support
else if (ctrl.selectionStart || ctrl.selectionStart == '0')
CaretPos = ctrl.selectionStart;
return (CaretPos);
}
(function (e, jQuery) {
var n = e.document,
u = n.getElementsByTagName("head")[0] || n.getElementsByTagName("body")[0],
//初始化方法
init = {
version: 20131120,
DEBUG: false,
DOMAIN: GV.DIMAUB,
EMBED_STYLESHEET: "statics/js/comment/css/embed.css?version=" + this.version,
GET_JSONP: "index.php?g=Comments&m=Index&a=json",
POST_JSONP: "index.php?g=Comments&m=Index&a=add",
VERIFYURL: "index.php?g=Api&m=Checkcode&font_size=15&width=100&height=25&type=comment",
LOAD: 0,
LOCK: false,
//分页信息
cursor: {
'total': 0, //总信息数
'pagetotal': 0, //总分页数
'page': 1, //当前分页
'size': 20 //每页显示数量
},
catid: commentsQuery.catid,
id: commentsQuery.id,
//评论设置
config: {
'guest': 1, //是否运行游客评论
'code': 0, //验证码
'strlength': 300, //评论长度
'expire': 60, //评论间隔
'noallow': true //是否允许评论
},
//当前登陆用户基本信息
users: {
'user_id': 0,
'name': '',
'avatar': '',
'email': ''
},
//评论数据
response: {},
getComment: function () {
jQuery.ajax({
type: "GET",
url: this.DOMAIN + this.GET_JSONP,
dataType: "jsonp",
jsonp: 'callback',
data: {
'catid': this.catid,
'id': this.id,
'page': this.cursor.page,
'size': commentsQuery.size //每页显示评论数
},
success: function (data) {
if (data.status) {
init.response = data.data.response;
init.cursor = data.data.cursor;
init.config = data.data.config;
//当前登陆用户信息
init.users = data.data.users;
var username = '游客';
var avatar = '';
if (init.users.user_id > 0) {
username = init.users.name;
}
if (init.users.avatar == '') {
avatar = tool.getAvatar(init.users.user_id, LS.item('coment_author_email'));
} else {
avatar = init.users.avatar;
}
init.users.avatar = avatar;
init.users.username = username;
var thread = jQuery('#ds-reset');
if (init.LOAD == 0) {
jQuery('#ds-waiting').remove();
addModel.commentsInfo(thread);
} else {
addModel.comments(thread);
}
init.LOAD += 1;
init.binds();
if (init.DEBUG) {
console.log('LOAD次数', init.LOAD);
console.log('评论设置', init.config);
console.log('评论数据:', init.response);
console.log('分页数据:', init.cursor);
console.log('登录用户:', init.users);
}
}
}
});
},
//加载样式
injectStylesheet: function (e) {
var t = n.createElement("link");
t.type = "text/css", t.rel = "stylesheet", t.href = e, u.appendChild(t)
},
//加载js
loadJS:function(id,url){
var xmlHttp = null;
if(window.ActiveXObject)//IE
{
try {
//IE6以及以后版本中可以使用
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
//IE5.5以及以后版本可以使用
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
else if(window.XMLHttpRequest)//Firefox,Opera 8.0+,Safari,Chrome
{
xmlHttp = new XMLHttpRequest();
}
//采用同步加载
xmlHttp.open("GET",url,false);
//发送同步请求,如果浏览器为Chrome或Opera,必须发布后才能运行,不然会报错
xmlHttp.send(null);
//4代表数据发送完毕
if ( xmlHttp.readyState == 4 )
{
//0为访问的本地,200到300代表访问服务器成功,304代表没做修改访问的是缓存
if((xmlHttp.status >= 200 && xmlHttp.status <300) || xmlHttp.status == 0 || xmlHttp.status == 304)
{
var myHead = document.getElementsByTagName("HEAD").item(0);
var myScript = document.createElement( "script" );
myScript.language = "javascript";
myScript.type = "text/javascript";
myScript.id = id;
try{
//IE8以及以下不支持这种方式,需要通过text属性来设置
myScript.appendChild(document.createTextNode(xmlHttp.responseText));
}
catch (ex){
myScript.text = xmlHttp.responseText;
}
myHead.appendChild( myScript );
return true;
}
else
{
return false;
}
}
else
{
return false;
}
},
//加载分页
goPage: function () {
var totalPage = this.cursor.pagetotal; //总页数
var pageSize = this.cursor.size; //每页显示行数
var currentPage = this.cursor.page; //当前页数
var str = '';
var strHighlight = 'class="ds-current"';
if (currentPage > totalPage) {
currentPage = totalPage;
}
if (currentPage < 1) {
currentPage = 1;
}
//默认显示当前分页前两个
var cPage = currentPage - 2;
if (cPage > 1) {
//if(cPage > 2){
str = '<a data-page="1" href="javascript:void(0);">1</a> ';
//}
if (cPage > 2) {
str += '<span class="page-break">...</span>';
}
for (var i = cPage; i < currentPage; i++) {
str += '<a data-page="' + i + '" href="javascript:void(0);" >' + i + '</a> ';
}
} else {
for (var i = 1; i < currentPage; i++) {
str += '<a data-page="' + i + '" href="javascript:void(0);">' + i + '</a> ';
}
}
//当前页
str += '<a data-page="' + currentPage + '" href="javascript:void(0);" ' + strHighlight + '>' + currentPage + '</a> ';
//显示后两个
var hPage = currentPage + 2;
if (totalPage >= hPage) {
for (var i = currentPage + 1; i <= hPage; i++) {
str += '<a data-page="' + i + '" href="javascript:void(0);">' + i + '</a> ';
}
if (totalPage > currentPage + 2) {
if (totalPage - hPage >= 2) {
str += '<span class="page-break">...</span>';
}
str += '<a data-page="' + totalPage + '" href="javascript:void(0);">' + totalPage + '</a> ';
}
} else {
for (var i = currentPage + 1; i <= totalPage; i++) {
str += '<a data-page="' + i + '" href="javascript:void(0);">' + i + '</a> ';
}
}
return str;
},
//绑定各种事件
binds: function () {
//允许评论
if (init.config.noallow) {
//对回复按钮绑定点击事件
jQuery('a.ds-post-reply').bind('click', function () {
var reply = jQuery(this);
var replyparent = reply.parent();
var replyactive = replyparent.next();
var comentid = reply.data('comentid');
jQuery('.ds-post .ds-replybox').hide();
jQuery('.ds-post .ds-comment-footer').removeClass('ds-reply-active');
//回复 高亮
replyparent.addClass('ds-reply-active');
//载入回复评论框
if (replyactive.html() == '') {
replyactive.html(addModel.replybox());
}
replyactive.show();
//加载登陆信息
addModel.getUser();
init.ajaxButton();
//设置回复id
replyactive.children("form").find('input[name="parent"]').attr('value', comentid);
tool.localStorages();
//表情
emote.init();
});
jQuery('a.ds-ReplyHide').bind('click', function () {
addModel.commetnReplyHide(jQuery(this).data("comentid"));
});
//表情
emote.init();
//加载登陆信息
addModel.getUser();
init.ajaxButton();
} else {
jQuery('a.ds-post-reply').hide();
}
//记录用户输入
tool.localStorages();
},
//ajax 提交
ajaxButton: function () {
var ajaxForm_list = jQuery('form.ds_form_post');
if (ajaxForm_list.length) {
jQuery('button.ds-post-button').on('click', function (es) {
es.preventDefault();
var btn = jQuery(this),
form = btn.parents('form.ds_form_post');
//ie处理placeholder提交问题
if (jQuery.browser.msie) {
form.find('[placeholder]').each(function () {
var input = jQuery(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
}
});
}
LS.item('coment_author_url', form.find('input[name="author_url"]').val());
LS.item('coment_author', form.find('input[name="author"]').val());
LS.item('coment_author_email', form.find('input[name="author_email"]').val());
if (init.DEBUG) {
console.log('提交信息', form);
}
//没有预约成功过的就不能评论
if(init.users.isyuyue == false){
alert('您没有预约过此经纪人,暂时不能评论!');
return;
}
if (init.LOCK) {
return;
}
init.LOCK = true;
form.ajaxSubmit({
url: init.DOMAIN + init.POST_JSONP, //按钮上是否自定义提交地址(多按钮情况)
dataType: 'json',
beforeSubmit: function (arr, $form, options) {
var text = btn.text();
//按钮文案、状态修改
btn.text(text + '中...').prop('disabled', true).addClass('disabled');
},
success: function (data, statusText, xhr, $form) {
if(init.DEBUG){
console.log('提交后服务器返回',data);
}
var text = btn.text();
init.LOCK = false;
//按钮文案、状态修改
btn.removeClass('disabled').text(text.replace('中...', '')).parent().find('span').remove();
if (data.status > 0) {
btn.removeProp('disabled').removeClass('disabled');
jQuery('textarea[name="content"]').val('')
//重新加载数据
init.getComment();
} else if (data.status == -1) {
btn.removeProp('disabled').removeClass('disabled');
jQuery('textarea[name="content"]').val('');
alert(data.info);
}else{
btn.removeProp('disabled').removeClass('disabled');
alert(data.info);
}
//焦点
if(data.focus){
form.find('input[name="'+data.focus+'"]').focus();
}
jQuery('#star').raty({starOff:"/statics/js/comment/raty-2.5.2/lib/img/star-off.png",
starOn:"/statics/js/comment/raty-2.5.2/lib/img/star-on.png",
target:"#score",
targetKeep:true,
score:0,
targetType: 'number'});
}
});
});
}
},
htmls: function () {
var thread = jQuery('#ds-reset');
thread.append('<div id="ds-waiting"></div>');
this.getComment();
}
},
//表情处理
emote = {
init:function(){
//点击表情后隐藏
jQuery("#ds-smilies-tooltip").hide();
var ts = this;
//表情
jQuery('a.ds-add-emote').bind('click',function(event){
ts.unbindclick();
//加载表情
ts.htmls();
//显示表情
jQuery("#ds-smilies-tooltip").show();
jQuery(document).one("click", function () {//对document绑定一个影藏Div方法
ts.unbindclick();
jQuery("#ds-smilies-tooltip").hide();
});
jQuery("#ds-smilies-tooltip").click(function (ev) {
ev.stopPropagation();
});
var emote = jQuery(this);
var winheight = jQuery(e).height();
var top = emote.offset().top - 236;
var left = emote.offset().left - 10;//按钮的位置左边距离
//表单对象
var form = emote.parents('.ds_form_post');
jQuery('#ds-reset #ds-smilies-tooltip').offset({ top: top, left: left });
jQuery(".ds-smilies-container img").bind('click',function(es){
var title = jQuery(this).attr('title');
form.find('textarea[name="content"]').insertAtCaret(title);
//点击表情后隐藏
jQuery("#ds-smilies-tooltip").hide();
ts.unbindclick();
});
event.stopPropagation();
});
},
//去除原来绑定的click事件
unbindclick:function(){
jQuery(".ds-smilies-container img").unbind('click');
},
htmls:function(){
if(jQuery('#ds-reset #ds-smilies-tooltip').length){
return;
}
var reset = jQuery("#ds-reset");
var emote = '';
var strhtml = '<div id="ds-smilies-tooltip" style="width: 600px;">\
<h2>选择表情</h2>\
<div class="ds-smilies-container">\
<ul>Loading...</ul>\
</div>\
<div id="ds-foot5"> </div>\
</div>';
reset.append(strhtml);
jQuery.ajax({
type: "GET",
async:false,
url: init.DOMAIN + 'index.php?g=Comments&m=Index&a=json_emote',
dataType: "jsonp",
jsonp: 'callback',
success: function (json) {
if(json.data){
jQuery.each(json.data, function (lab, img) {
emote += '<li>'+img+'</li>';
})
jQuery('.ds-smilies-container ul').html(emote);
}
}
});
}
},
addModel = {
//加载导航
commentsInfo: function (thread) {
//显示评论框
this.newsCommentBox(thread);
//显示评论数,和 最新,最早,最热排序导航
thread.append('<div class="ds-comments-info">\
<div class="ds-sort" style="display:none;"><a class="ds-order-desc ds-current">最新</a><a class="ds-order-asc">最早</a><a class="ds-order-hot">最热</a></div>\
<span class="ds-comment-count"><a class="ds-comments-tab-duoshuo ds-current" href="javascript:void(0);"><span class="ds-highlight">0</span>条评论</a></span> \
</div>');
//显示评论数
jQuery('.ds-highlight').html(init.cursor.total);
//加载评论
this.comments(thread);
},
//加载评论
comments: function (thread) {
var post;
//如果非第一次加载,不append插入元素
if (init.LOAD) {
jQuery('.ds-comments').empty();
} else {
thread.append('<ul class="ds-comments" style="opacity: 1; "></ul>');
}
post = jQuery('.ds-comments');
//判断是否为空
if (init.response == null || init.response == '') {
post.append('<li class="ds-post ds-post-placeholder">还没有评论,沙发等你来抢</li>');
//加载分页
this.paginator(thread);
return;
}
jQuery.each(init.response, function (i, rs) {
var comentId = rs.id;
if (rs.content) {
post.append('<li class="ds-post">\
<div class="ds-post-self">\
<div class="ds-avatar">\
<a rel="nofollow author" href="javascript:;;" title="' + rs.author + '"><img src="/d/file/avatar/000/00/00/' + rs.user_id + '_180x180.jpg" alt="' + rs.author + '" onerror="this.src=\'' + init.DOMAIN + 'statics/images/member/nophoto.gif\'"></a>\
</div>\
<div class="ds-comment-body">\
<div class="ds-comment-header"><a class="ds-user-name ds-highlight" href="javascript:;;" rel="nofollow" data-userid="' + rs.user_id + '">' + fn(rs.author) + '</a></div>\
<div id="star_' + rs.id + '"></div>\
<p>' + rs.content + '</p>\
<div class="ds-comment-footer ds-comment-actions"> \
<span class="ds-time" title="' + tool.getYearsMonthDay(rs.date * 1000,"yyyy-MM-dd hh:mm:ss") + '">' + tool.getTimeBefore(rs.date * 1000) + '</span> \
<a class="ds-post-reply" href="javascript:void(0);" data-comentid="' + comentId + '"><span class="ds-ui-icon"></span>回复</a> \
<a class="ds-post-likes" style="display:none;" href="javascript:void(0);" data-comentid="' + comentId + '"><span class="ds-ui-icon"></span>顶</a> \
</div>\
<div class="ds-replybox ds-inline-replybox replybox_' + comentId + '" style="display:none;"></div>\
</div>\
</div>\
</li>');
var id="#star_"+rs.id;
//加载回复列表
if (rs.child) {
addModel.commetnReply(rs);
}
jQuery(id).raty({starOff:"/statics/js/comment/raty-2.5.2/lib/img/star-off.png",
starOn:"/statics/js/comment/raty-2.5.2/lib/img/star-on.png",
readOnly:true,
score:rs.score});
}
});
//加载分页
this.paginator(thread);
return true;
},
//加载评论回复
commetnReply: function (json) {
var post = jQuery('.ds-comments');
var strHtml = '';
//加载回复
if (json.child) {
jQuery.each(json.child, function (i, rs) {
var comentId = rs.id;
if (rs.display == 'none') {
strHtml += '<li class="ds-post">\
<div class="ds-post-self">\
<div class="ds-comment-body">\
<p>已经省略一部分评论...<a href="javascript:;;" class="ds-ReplyHide" data-comentid="' + json.id + '">全部加载</a></p>\
</div>\
</div>\
</li>';
} else {
strHtml += '\
<li class="ds-post">\
<div class="ds-post-self">\
<div class="ds-avatar"><a rel="nofollow author" href="javascript:;" title="' + rs.author + '"><img src="/d/file/avatar/000/00/00/' + rs.user_id + '_180x180.jpg" alt="' + init.users.username + '"></a></div>\
<div class="ds-comment-body">\
<div class="ds-comment-header">\
<a class="ds-user-name ds-highlight" data-qqt-account="" href="javascript:;;" rel="nofollow" data-userid="' + rs.user_id + '">' + rs.author + '</a>\
</div>\
<p>' + rs.content + '</p>\
<div class="ds-comment-footer ds-comment-actions"> \
<span class="ds-time" title="' + tool.getYearsMonthDay(rs.date * 1000,"yyyy-MM-dd hh:mm:ss") + '">' + tool.getTimeBefore(rs.date * 1000) + '</span> \
<a class="ds-post-reply" href="javascript:void(0);" data-comentid="' + json.id + '"><span class="ds-ui-icon"></span>回复</a> \
<a class="ds-post-likes" style="display:none;" href="javascript:void(0);" data-comentid="' + comentId + '"><span class="ds-ui-icon"></span>顶</a> \
</div>\
<div class="ds-replybox ds-inline-replybox replybox_' + comentId + '"></div>\
</div>\
</div>\
</li>';
}
});
post.append('<ul class="ds-children" id="commetnReply_' + json.id + '">' + strHtml + '</ul>');
}
},
//加载隐藏部分的评论
commetnReplyHide: function (comentid) {
if (comentid == '' || comentid == null) {
return;
}
var commetnReply = jQuery("#commetnReply_" + comentid);
var strHtml = '';
commetnReply.empty();
jQuery.ajax({
type: "GET",
url: init.DOMAIN + 'index.php?g=Comments&m=Index&a=json_reply&parent=103',
dataType: "jsonp",
jsonp: 'callback',
data: {
'parent': comentid
},
success: function (data) {
if (data.status) {
//加载回复
if (data.data.response) {
jQuery.each(data.data.response, function (i, rs) {
var comentId = rs.id;
strHtml += '<li class="ds-post">\
<div class="ds-post-self">\
<div class="ds-avatar"><a rel="nofollow author" href="javascript:;;" title="' + rs.username + '"><img src="/d/file/avatar/000/00/00/' + rs.user_id + '_180x180.jpg" alt="' + rs.username + '"></a></div>\
<div class="ds-comment-body">\
<div class="ds-comment-header">\
<a class="ds-user-name ds-highlight" data-qqt-account="" href="javascript:;;" rel="nofollow" data-userid="' + rs.user_id + '">' + rs.username + '--XX</a>\
</div>\
<p>' + rs.content + '--PP</p>\
<div class="ds-comment-footer ds-comment-actions"> \
<span class="ds-time" title="' + tool.getYearsMonthDay(rs.date * 1000,"yyyy-MM-dd hh:mm:ss") + '">' + tool.getTimeBefore(rs.date * 1000) + '</span> \
<a class="ds-post-reply" href="javascript:void(0);" data-comentid="' + comentid + '"><span class="ds-ui-icon"></span>回复</a> \
<a class="ds-post-likes" style="display:none;" href="javascript:void(0);" data-comentid="' + rs.id + '"><span class="ds-ui-icon"></span>顶</a> \
</div>\
<div class="ds-replybox ds-inline-replybox replybox_' + rs.id + '"></div>\
</div>\
</div>\
</li>';
});
commetnReply.append(strHtml);
}
}
}
});
},
//分页处理
paginator: function (thread) {
//如果有存在分页才载入
if (init.cursor.pagetotal > 1) {
if (init.LOAD) {
jQuery('.ds-paginator').empty();
jQuery('.ds-paginator').append('<div class="ds-border"></div>' + init.goPage());
} else {
thread.append('<div class="ds-paginator" style="">\
<div class="ds-border"></div>\
</div>\
<a name="respond"></a>');
jQuery('.ds-paginator').append(init.goPage());
}
//对分页加点击事件
jQuery('.ds-paginator a').click(function () {
init.cursor.page = jQuery(this).html();
jQuery(this).die("click");
init.getComment();
});
}
},
//回复评论框
replybox: function () {
return '<form class="ds_form_post" method="post">\
<div class="ds-user"></div>\
<a class="ds-avatar" href="javascript:;;"><img src="/d/file/avatar/000/00/00/' + init.users.user_id + '_180x180.jpg" alt="' + init.users.username + '" onerror="this.src=\'' + init.DOMAIN + 'statics/images/member/nophoto.gif\'"></a>\
<input type="hidden" name="comment_catid" value="' + init.catid + '" />\
<input type="hidden" name="comment_id" value="' + init.id + '" />\
<input type="hidden" name="author" value="' + init.users.username + '" />\
<input type="hidden" name="parent" value="" />\
<div class="ds-textarea-wrapper ds-rounded-top">\
<textarea name="content" placeholder="说点什么吧…"></textarea>\
</div>\
<div class="ds-post-toolbar">\
<div class="ds-post-options ds-gradient-bg"></div>\
<button class="ds-post-button" type="submit">发布</button>\
<div class="ds-toolbar-buttons"><a class="ds-toolbar-button ds-add-emote" title="插入表情"></a></div>\
</div>\
</form>';
},
//发表评论框
newsCommentBox: function (thread) {
if (init.LOAD) {
return true;
}
//关闭评论
if (init.config.noallow == false) {
return true;
}
thread.append('<div class="ds-replybox" style="zoom:1;">\
<form class="ds_form_post" method="post">\
<div class="ds-user"></div>\
<a class="ds-avatar" href="javascript:;;"><img src="/d/file/avatar/000/00/00/' + init.users.user_id + '_180x180.jpg" alt="' + init.users.username + '" onerror="this.src=\'' + init.DOMAIN + 'statics/images/member/nophoto.gif\'"></a>\
<input type="hidden" name="comment_catid" value="' + init.catid + '" />\
<input type="hidden" name="author" value="' + init.users.username + '" />\
<input type="hidden" name="comment_id" value="' + init.id + '" />\
<input type="hidden" id="score" name="score" value="0"/>\
<div id="star"></div>\
<div class="ds-textarea-wrapper ds-rounded-top">\
<textarea class="J_CmFormField" name="content" placeholder="说点什么吧…"></textarea>\
</div>\
<div class="ds-post-toolbar">\
<div class="ds-post-options ds-gradient-bg"></div>\
<button class="ds-post-button" type="submit">发布</button>\
<div class="ds-toolbar-buttons"><a class="ds-toolbar-button ds-add-emote" title="插入表情"></a></div>\
</div>\
</form>\
</div>');
jQuery('#star').raty({starOff:"/statics/js/comment/raty-2.5.2/lib/img/star-off.png",
starOn:"/statics/js/comment/raty-2.5.2/lib/img/star-on.png",
target:"#score",
targetKeep:true,
targetType: 'number'});
},
//获取用户登陆信息或者显示输入框
getUser: function () {
var strHtml = '';
var nichengHtml = '<input name="author" placeholder="用户名" value="' + init.users.username + '"/>';
var emailHtml = '<input name="author_email" placeholder="请输入邮箱" value="' + init.users.email + '"/>';
var tis = '';
if (init.users.user_id) {
nichengHtml = init.users.username;
emailHtml = init.users.email;
tis = '尊敬的 ' + init.users.username + ',欢迎你评论!';
}
var userHtml = '';
var qtHtml = '<tr>\
<td></td>\
<td></td>\
<td></td>\
<td>' + tis + '</td>\
</tr>';
if (init.users.user_id) {
userHtml = '';
}
if (init.config.code == '1') {
qtHtml = '<tr>\
<td></td>\
<td></td>\
<td>验证码:</td>\
<td style="vertical-align:middle"><input name="verify" placeholder="验证码"/><img id="code_img" src="' + init.DOMAIN + init.VERIFYURL + '" alt="验证码" onClick="this.src = \'' + init.DOMAIN + init.VERIFYURL + '&refresh=1&time=' + Math.random() + '\'" style="vertical-align: middle ;"></td>\
</tr>';
}
strHtml = '<table>' + userHtml + qtHtml + '</table>';
//检查是否游客允许评论
if(init.config.guest == 0 && init.users.user_id < 1){
strHtml = '游客不允许评论,请登陆后操作!o(∩_∩)o ';
}
jQuery('.ds-user').empty().append(strHtml);
}
},
//工具
tool = {
//友好时间
getTimeBefore: function (time) {
var ret = "";
var nowd = new Date();
var now = nowd.getTime();
var delay = now - time;
var t = new Date(time);
var getHours = t.getHours();
var getMinutes = t.getMinutes();
if (delay > (10 * 24 * 60 * 60 * 1000)) {
ret = tool.getYearsMonthDay(time, "yyyy-MM-dd hh:mm:ss");
} else if (delay >= (24 * 60 * 60 * 1000)) {
delay = (delay / (24 * 60 * 60 * 1000));
var num = Math.floor(delay);
if (num == 1) {
ret = "昨天" + getHours + ":" + getMinutes;
} else if (num == 2) {
ret = "前天" + getHours + ":" + getMinutes;
} else {
ret = num + "天前";
}
} else if (delay >= (60 * 60 * 1000)) {
delay = (delay / (60 * 60 * 1000))
ret = Math.floor(delay) + "小时前";
} else if (delay >= (60 * 1000)) {
delay = (delay / (60 * 1000))
ret = Math.floor(delay) + "分钟前";
} else if (delay >= (1000)) {
delay = (delay / (1000))
ret = Math.floor(delay) + "秒前";
} else {
ret = "刚刚";
}
return ret;
},
//获取 年月日的时间格式
getYearsMonthDay: function (time, format) {
var dt = new Date(time);
/*
* eg:format="yyyy-MM-dd hh:mm:ss";
*/
var o = {
"M+": dt.getMonth() + 1, // month
"d+": dt.getDate(), // day
"h+": dt.getHours(), // hour
"m+": dt.getMinutes(), // minute
"s+": dt.getSeconds(), // second
"q+": Math.floor((dt.getMonth() + 3) / 3), // quarter
"S": dt.getMilliseconds()// millisecond
}
if (/(y+)/.test(format)) {
format = format.replace(RegExp.$1, (dt.getFullYear() + "").substr(4 - RegExp.$1.length));
}
for (var k in o) {
if (new RegExp("(" + k + ")").test(format)) {
format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
}
}
return format;
},
//获取头像地址
getAvatar: function (uid, email) {
if (Math.floor(uid) > 0) {
return init.DOMAIN + 'api.php?m=avatar&uid=' + uid;
} else {
return init.DOMAIN + 'api.php?m=avatar&a=gravatar&email=' + email;
}
},
//保存用户输入
localStorages: function () {
//记录用户输入
jQuery('input[name="author_url"]').attr('value', LS.item('coment_author_url'));
//jQuery('input[name="author"]').attr('value', LS.item('coment_author'));
jQuery('input[name="author_email"]').attr('value', LS.item('coment_author_email'));
if (init.DEBUG) {
console.log('本地存储:', localStorage);
}
}
},
LS = {
/**
* 获取/设置存储字段
* @param {String} name 字段名称
* @param {String} value 值
* @return {String}
*/
item: function (name, value) {
var val = null;
if (LS.isSupportLocalStorage()) {
if (value) {
localStorage.setItem(name, value);
val = value;
} else {
val = localStorage.getItem(name);
}
} else {
//不支持HTML5
return;
}
return val;
},
/**
* 移除指定name的存储
* @param {String} name 字段名称
* @return {Boolean}
*/
removeItem: function (name) {
if (LS.isSupportLocalStorage()) {
localStorage.removeItem(name);
} else {
//不支持HTML5
return false;
}
return true;
},
/**
* 判断浏览器是否直接html5本地存储
*/
isSupportLocalStorage: function () {
var ls = LS,
is = ls.IS_HAS_LOCAL_STORAGE;
if (is == null) {
if (window.localStorage) {
is = ls.IS_HAS_LOCAL_STORAGE = true;
}
}
return is;
},
IS_HAS_LOCAL_STORAGE: null
};
//判断ajaxForm是否加载
if($.fn.ajaxSubmit == undefined){
init.loadJS('ajaxForm',init.DOMAIN +'statics/js/ajaxForm.js');
}
//加载样式
init.injectStylesheet(init.DOMAIN + init.EMBED_STYLESHEET);
//加载html结构
init.htmls();
})(window, jQuery); |
import { expect } from 'chai';
import rawContract from 'binary-test-data/contractsForR50';
import changeDurationUnit from '../changeDurationUnit';
import { tradingOptionsForOneSymbol } from '../../../trade-params/TradeParamsSelector';
import areAllTimeFieldsValid from '../../validation/areAllTimeFieldsValid';
const mockTickTrade = {
showAssetPicker: false,
tradeCategory: 'risefall',
symbolName: 'Volatility 100 Index',
duration: 5,
amount: 50,
durationUnit: 't',
symbol: 'R_100',
pipSize: 2,
type: 'CALL',
disabled: false,
basis: 'stake',
};
const mockEndsInTrade = {
showAssetPicker: false,
tradeCategory: 'endsinout',
symbolName: 'Volatility 100 Index',
barrierType: 'relative',
duration: 2,
barrier: 49.87,
amount: 50,
durationUnit: 'm',
symbol: 'R_100',
pipSize: 2,
type: 'EXPIRYMISS',
barrier2: -49.67,
disabled: false,
basis: 'stake',
};
const mockedContract = tradingOptionsForOneSymbol(rawContract);
describe('changeDurationUnit', () => {
it('should update durationUnit ', () => {
const updateDurationUnit = changeDurationUnit('m', mockedContract, mockTickTrade);
expect(updateDurationUnit.durationUnit).to.be.equal('m');
});
it('should update barrier for trade with barrier(s)', () => {
const updateDurationUnit = changeDurationUnit('m', mockedContract, mockEndsInTrade);
expect(updateDurationUnit.barrier).to.not.equal(mockEndsInTrade.barrier);
});
it('should pick a valid duration unit when passed duration unit is not allowed', () => {
const { duration, durationUnit, dateStart, tradeCategory, type } =
changeDurationUnit('ss', mockedContract, mockTickTrade);
expect(durationUnit).to.not.equal('ss');
expect(areAllTimeFieldsValid(dateStart, duration, durationUnit, mockedContract[tradeCategory][type])).to.be.true;
});
it('should keep old duration if it is allowed', () => {
const updated = changeDurationUnit('m', mockedContract, mockTickTrade);
expect(updated.duration).to.be.equal(mockTickTrade.duration);
});
it('should change duration if old one is not allowed', () => {
const updated = changeDurationUnit('s', mockedContract, mockTickTrade);
expect(updated.duration).to.not.be.equal(mockTickTrade.duration);
});
});
|
var home = require('../controllers/home'),
unearthed = require('../controllers/unearthed'),
triplej = require('../controllers/triplej'),
doublej = require('../controllers/doublej');
module.exports.initialize = function(app) {
app.get('/', home.index);
app.get('/triplej', home.index);
app.get('/unearthed', home.index);
app.get('/doublej', home.index);
// unearthed
app.get('/api/unearthed', unearthed.tracks);
app.get('/api/unearthed/new', unearthed.new);
app.get('/api/unearthed/artist', unearthed.artist);
app.get('/api/unearthed/track', unearthed.track);
app.get('/api/unearthed/featured', unearthed.featured);
app.get('/api/unearthed/recent', unearthed.recent);
// triple j
app.get('/api/triplej', triplej.tracks);
app.get('/api/triplej/recent', triplej.recent);
// double j
app.get('/api/doublej', doublej.tracks);
app.get('/api/doublej/track', doublej.track);
app.get('/api/doublej/recent', doublej.recent);
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.