text
stringlengths 2
6.14k
|
|---|
/* eslint-env mocha */
const { expect } = chai;
import React from './React';
import TestUtils from './TestUtils';
describe('React components', () => {
it('should find valid xpath in react component', () => {
const component = TestUtils.renderIntoDocument(<blink>hi</blink>);
expect(component).to.have.xpath('//blink');
});
it('should find valid xpath in react component twice', () => {
const component = TestUtils.renderIntoDocument(<blink>hi</blink>);
expect(component).to.have.xpath('//blink');
expect(component).to.have.xpath('//blink');
});
describe('when it does not find valid xpath in react component', () => {
it('should throw', () => {
const component = TestUtils.renderIntoDocument(<blink>hi</blink>);
expect(() => {
expect(component).to.have.xpath('//h1');
}).to.throw('to have xpath \'//h1\'');
});
it('should throw with outerHTML of the component', () => {
const component = TestUtils.renderIntoDocument(<blink>hi</blink>);
expect(() => {
expect(component).to.have.xpath('//h1');
}).to.throw('hi</blink>');
});
});
});
|
const getAllMatchers = require("./getAllMatchers");
describe("unit: getAllMatchers", () => {
let handler;
let matcherStore;
beforeEach(() => {
matcherStore = [{}, {}, {}];
handler = getAllMatchers(matcherStore);
});
test("it should return all matchers", () => {
expect(handler()).toHaveProperty("body", matcherStore);
});
test("it should return a status of 200", () => {
expect(handler()).toHaveProperty("status", 200);
});
});
|
black = '#202427';
red = '#EB6A58'; // red
green = '#49A61D'; // green
yellow = '#959721'; // yellow
blue = '#798FB7'; // blue
magenta = '#CD7B7E'; // pink
cyan = '#4FA090'; // cyan
white = '#909294'; // light gray
lightBlack = '#292B35'; // medium gray
lightRed = '#DB7824'; // red
lightGreen = '#09A854'; // green
lightYellow = '#AD8E4B'; // yellow
lightBlue = '#309DC1'; // blue
lightMagenta= '#C874C2'; // pink
lightCyan = '#1BA2A0'; // cyan
lightWhite = '#8DA3B8'; // white
t.prefs_.set('color-palette-overrides',
[ black , red , green , yellow,
blue , magenta , cyan , white,
lightBlack , lightRed , lightGreen , lightYellow,
lightBlue , lightMagenta , lightCyan , lightWhite ]);
t.prefs_.set('cursor-color', lightWhite);
t.prefs_.set('foreground-color', lightWhite);
t.prefs_.set('background-color', black);
|
var createSubmit = function(name, primus, keyDict) {
return function(event) {
var message = $('#message').val();
if (message.length === 0) {
event.preventDefault();
return;
}
$('#message').val('');
$('#message').focus();
var BigInteger = forge.jsbn.BigInteger;
var data = JSON.parse(sessionStorage[name]);
var pem = data.pem;
var privateKey = forge.pki.privateKeyFromPem(pem);
var ownPublicKey = forge.pki.setRsaPublicKey(new BigInteger(data.n), new BigInteger(data.e));
var keys = [];
var iv = forge.random.getBytesSync(16);
var key = forge.random.getBytesSync(16);
var cipher = forge.cipher.createCipher('AES-CBC', key);
cipher.start({iv: iv});
cipher.update(forge.util.createBuffer(message, 'utf8'));
cipher.finish();
var encryptedMessage = cipher.output.getBytes();
var encryptedKey = ownPublicKey.encrypt(key, 'RSA-OAEP');
keys.push({
'name': name,
'key': encryptedKey
});
var md = forge.md.sha1.create();
md.update(message, 'utf8');
var signature = privateKey.sign(md);
var recipients = $.map($("#recipients").tokenfield("getTokens"), function(o) {return o.value;});
var deferredRequests = [];
for (var i = 0; i < recipients.length; i++) {
(function (index) {
var retrieveKey = function(pk) {
if (pk === false) {
return;
}
if (keyDict[recipients[i]] === undefined) {
keyDict[recipients[i]] = pk;
}
var publicKey = forge.pki.setRsaPublicKey(new BigInteger(pk.n), new BigInteger(pk.e));
var encryptedKey = publicKey.encrypt(key, 'RSA-OAEP');
keys.push({
'name': recipients[index],
'key': encryptedKey
});
}
if (keyDict[recipients[i]] === undefined) {
deferredRequests.push($.post('/user/getpublickey', {'name' : recipients[i]}, retrieveKey));
} else {
retrieveKey(keyDict[recipients[i]]);
}
})(i);
}
$.when.apply(null, deferredRequests).done(function() {
primus.substream('messageStream').write({'message': encryptedMessage, 'keys': keys, 'iv': iv,
'signature': signature, 'recipients': recipients});
});
event.preventDefault();
};
};
|
// Copyright (c) 2012 Ecma International. All rights reserved.
// Ecma International makes this code available under the terms and conditions set
// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
// "Use Terms"). Any redistribution of this code must retain the above
// copyright and this notice and otherwise comply with the Use Terms.
/*---
es5id: 15.4.4.21-2-15
description: Array.prototype.reduce - 'length' is property of the global object
includes:
- runTestCase.js
- fnGlobalObject.js
---*/
function testcase() {
function callbackfn(prevVal, curVal, idx, obj) {
return (obj.length === 2);
}
try {
var oldLen = fnGlobalObject().length;
fnGlobalObject()[0] = 12;
fnGlobalObject()[1] = 11;
fnGlobalObject()[2] = 9;
fnGlobalObject().length = 2;
return Array.prototype.reduce.call(fnGlobalObject(), callbackfn, 1) === true;
} finally {
delete fnGlobalObject()[0];
delete fnGlobalObject()[1];
delete fnGlobalObject()[2];
fnGlobalObject().length = oldLen;
}
}
runTestCase(testcase);
|
$(function () {
var $container = $('#container');
var certificatesInfo = $container.data('certinfo');
var runDate = $container.data('rundate');
$('#created_date').html(runDate);
var sorted_certificates = Object.keys(certificatesInfo)
.sort(function( a, b ) {
return certificatesInfo[a].info.days_left - certificatesInfo[b].info.days_left;
}).map(function(sortedKey) {
return certificatesInfo[sortedKey];
});
var card_html = String()
+'<div class="col-xs-12 col-md-6 col-xl-4">'
+' <div class="card text-xs-center" style="border-color:#333;">'
+' <div class="card-header" style="overflow:hidden;">'
+' <h4 class="text-muted" style="margin-bottom:0;">{{server}}</h4>'
+' </div>'
+' <div class="card-block {{background}}">'
+' <h1 class="card-text display-4" style="margin-top:0;margin-bottom:-1rem;">{{days_left}}</h1>'
+' <p class="card-text" style="margin-bottom:.75rem;"><small>days left</small></p>'
+' </div>'
+' <div class="card-footer">'
+' <h6 class="text-muted" style="margin-bottom:.5rem;">Issued by: {{issuer}}</h6>'
+' <h6 class="text-muted" style=""><small>{{issuer_cn}}</small></h6>'
+' <h6 class="text-muted" style="margin-bottom:0;"><small>{{common_name}}</small></h6>'
+' </div>'
+' </div>'
+'</div>';
function insert_card(json) {
var card_template = Handlebars.compile(card_html),
html = card_template(json);
$('#panel').append(html);
};
sorted_certificates.forEach(function(element, index, array){
var json = {
'server': element.server,
'days_left': element.info.days_left,
'issuer': element.issuer.org,
'common_name': element.subject.common_name,
'issuer_cn': element.issuer.common_name
}
if (element.info.days_left <= 30 ){
json.background = 'card-inverse card-danger';
} else if (element.info.days_left > 30 && element.info.days_left <= 60 ) {
json.background = 'card-inverse card-warning';
} else if (element.info.days_left === "??") {
json.background = 'card-inverse card-info';
} else {
json.background = 'card-inverse card-success';
}
insert_card(json);
});
});
|
'use strict';
//Setting up route
angular.module('socketio-area').config(['$stateProvider',
function($stateProvider) {
// Socketio area state routing
$stateProvider.
state('socketio-area', {
url: '/socketio',
templateUrl: 'modules/socketio-area/views/socketio-area.client.view.html'
});
}
]);
|
/**
* configuration for grunt tasks
* @module Gruntfile
*/
module.exports = function(grunt) {
/** load tasks */
require('load-grunt-tasks')(grunt);
/** config for build paths */
var config = {
dist: {
dir: 'dist/',
StoreFactory: 'dist/StoreFactory.js',
ngStoreFactory: 'dist/ngStore.js'
},
src: {
dir: 'src/'
},
tmp: {
dir: 'tmp/'
}
};
/** paths to files */
var files = {
/** src files */
Factory: [
'StoreFactory.js'
],
/** src files */
Store: [
'Store.js'
],
};
/* # # # # # # # # # # # # # # # # # # # # */
/* # # # # # # # # # # # # # # # # # # # # */
/* # # # # # # # # # # # # # # # # # # # # */
/* # # # # # # # # # # # # # # # # # # # # */
/** config for grunt tasks */
var taskConfig = {
/** concatentation tasks for building the source files */
concat: {
StoreFactory: {
options: {
// stripBanners: true
banner: '',
footer: '',
},
src: (function() {
var
cwd = config.src.dir,
queue = [].concat(files.Factory, files.Store);
return queue.map(function(path) {
return cwd + path;
});
})(),
dest: config.dist.StoreFactory,
},
ngSession: {
options: {
banner: 'angular.module("ngStore", [])\n' +
'.service("ngStore", [\n' +
'function() {\n\n',
footer: '\n\n' +
'return new StoreFactory();\n\n}' +
'\n]);'
},
src: (function() {
return [
config.dist.StoreFactory,
];
})(),
dest: config.dist.ngStoreFactory
}
},
/** uglify (javascript minification) config */
uglify: {
StoreFactory: {
options: {},
files: [
{
src: config.dist.StoreFactory,
dest: (function() {
var split = config.dist.StoreFactory.split('.');
split.pop(); // removes `js` extension
split.push('min'); // adds `min` extension
split.push('js'); // adds `js` extension
return split.join('.');
})()
}
]
},
ngStoreFactory: {
options: {},
files: [
{
src: config.dist.ngStoreFactory,
dest: (function() {
var split = config.dist.ngStoreFactory.split('.');
split.pop(); // removes `js` extension
split.push('min'); // adds `min` extension
split.push('js'); // adds `js` extension
return split.join('.');
})()
}
]
}
}
};
/* # # # # # # # # # # # # # # # # # # # # */
/* # # # # # # # # # # # # # # # # # # # # */
/* # # # # # # # # # # # # # # # # # # # # */
/* # # # # # # # # # # # # # # # # # # # # */
// register default & custom tasks
grunt.initConfig(taskConfig);
grunt.registerTask('default', [
'build'
]);
grunt.registerTask('build', [
'concat',
'uglify'
]);
};
|
/**
* Module dependencies.
*/
var express = require('express');
var path = require('path');
var api = require('./lib/api');
var seo = require('./lib/seo');
var app = module.exports = express();
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser('change this value to something unique'));
app.use(express.cookieSession());
app.use(express.compress());
app.use(api);
app.use(seo);
app.use(express.static(path.join(__dirname, '../build')));
app.use(app.router);
app.get('/loaderio-995e64d5aae415e1f10d60c9391e37ac/', function(req, res, next) {
res.send('loaderio-995e64d5aae415e1f10d60c9391e37ac');
});
if ('development' === app.get('env')) {
app.use(express.errorHandler());
}
var cacheBuster = function(req, res, next){
res.header("Cache-Control", "no-cache, no-store, must-revalidate");
res.header("Pragma", "no-cache");
res.header("Expires", 0);
next();
};
// @todo isolate to api routes...
app.use(cacheBuster);
// catch all which sends all urls to index page, thus starting our app
// @note that because Express routes are registered in order, and we already defined our api routes
// this catch all will not effect prior routes.
app.use(function(req, res, next) {
app.get('*', function(req, res, next) {
//return res.ok('catch all');
res.redirect('/#!' + req.url);
});
});
|
var score = 0;
var scoreText;
var map_x = 14;
var map_y = 10;
var game = new Phaser.Game(map_x * 16, map_y * 16, Phaser.AUTO, '', { preload: preload, create: create, update: update });
function preload() {
// game.scale.maxWidth = 600;
// game.scale.maxHeight = 600;
game.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
game.scale.setScreenSize();
game.load.image('cat', 'assets/cat.png', 16, 16);
game.load.image('ground', 'assets/darkfloor.png', 16, 16);
game.load.image('l_wall', 'assets/l_wall.png', 16, 16);
game.load.image('r_wall', 'assets/r_wall.png', 16, 16);
game.load.image('t_wall', 'assets/t_wall.png', 16, 16);
game.load.image('tr_wall', 'assets/tr_wall_iso.png', 16, 16);
game.load.image('tl_wall', 'assets/tl_wall_iso.png', 16, 16);
game.load.image('bl_wall', 'assets/bl_wall.png', 16, 16);
game.load.image('br_wall', 'assets/br_wall.png', 16, 16);
game.load.image('stone_door', 'assets/door_stone.png', 16, 16);
game.load.image('star', 'assets/star.png');
}
function create() {
game.physics.startSystem(Phaser.Physics.ARCADE);
// the game world
gmap = game.add.tilemap();
gmap.addTilesetImage('ground', 'ground', 16, 16, null, null, 0);
gmap.addTilesetImage('l_wall', 'l_wall', 16, 16, null, null, 1);
gmap.addTilesetImage('r_wall', 'r_wall', 16, 16, null, null, 2);
gmap.addTilesetImage('tr_wall', 'tr_wall', 16, 16, null, null, 3);
gmap.addTilesetImage('tl_wall', 'tl_wall', 16, 16, null, null, 4);
gmap.addTilesetImage('br_wall', 'br_wall', 16, 16, null, null, 5);
gmap.addTilesetImage('bl_wall', 'bl_wall', 16, 16, null, null, 6);
gmap.addTilesetImage('t_wall', 't_wall', 16, 16, null, null, 7);
gmap.addTilesetImage('stone_door', 'stone_door', 16, 16, null, null, 8);
ground_layer = gmap.create('ground_layer', map_x, map_y, 16, 16);
wall_layer = gmap.create('wall_layer', map_x, map_y, 16, 16);
for (var i=0; i<map_x; i++) {
for(var j=0; j<map_y; j++) {
if (i==0 && j==0) {
gmap.putTile(4, i, j, wall_layer);
} else if (i==map_x/2 && j==0) {
gmap.putTile(8, i, j, wall_layer);
} else if (i==map_x-1 && j == map_y-1) {
gmap.putTile(5, i, j, wall_layer);
} else if (i==0 && j == map_y-1) {
gmap.putTile(6, i, j, wall_layer);
} else if (i==map_x-1 && j == 0) {
gmap.putTile(3, i, j, wall_layer);
} else if (i==map_x-1 && j == map_y-1) {
gmap.putTile(6, i, j, wall_layer);
} else if (i==0) {
gmap.putTile(1, i, j, wall_layer);
} else if(i==map_x-1) {
gmap.putTile(2, i, j, wall_layer);
} else if(j==map_y-1) {
gmap.putTile(7, i, j, wall_layer);
} else if(j==0) {
gmap.putTile(7, i, j, wall_layer);
} else {
gmap.putTile(0, i, j, ground_layer);
}
}
}
wall_layer.resizeWorld();
game.physics.arcade.enable(wall_layer);
gmap.setCollision(wall_layer);
// the player
player = game.add.sprite(32, 32, 'cat');
game.physics.arcade.enable(player);
player.body.collideWorldBounds = true;
// gmap.setCollisionBetween(0, 100, true, wall_layer);
cursors = game.input.keyboard.createCursorKeys();
}
function update() {
game.physics.arcade.collide(player, wall_layer);
player.body.velocity.x = 0;
player.body.velocity.y = 0;
if (cursors.left.isDown) {
player.body.velocity.x = -150;
} else if (cursors.right.isDown) {
player.body.velocity.x = 150;
} else if (cursors.down.isDown) {
player.body.velocity.y = 150;
} else if (cursors.up.isDown) {
player.body.velocity.y = -150;
} else {
}
}
|
export { default } from 'ember-flexberry-gis/services/map-store';
|
angular.module('booksAR')
.directive('userNavbar', function(){
return{
restrict: 'E',
templateUrl: './app/components/directives/user/user-navbar.html'
};
})
.directive('userBooksTable', function(){
return{
restrict: 'E',
templateUrl: './app/components/directives/user/user-books-table.html'
};
})
.directive('userTable', function(){
return{
restrict: 'E',
templateUrl: './app/components/directives/user/user-table.html'
};
})
.directive('userProfileInfo', function(){
return{
restrict: 'E',
templateUrl: './app/components/directives/user/user-profile-info.html'
};
})
.directive('ngConfirmClick', [
function(){
return {
link: function (scope, element, attr) {
var msg = attr.ngConfirmClick || "Are you sure?";
var clickAction = attr.confirmedClick;
element.bind('click',function (event) {
if ( window.confirm(msg) ) {
scope.$eval(clickAction)
}
});
}
};
}]);
|
const test = require('tap').test
const GF = require('core/galois-field')
test('Galois Field', function (t) {
t.throw(function () { GF.log(0) }, 'Should throw for log(n) with n < 1')
for (let i = 1; i < 255; i++) {
t.equal(GF.log(GF.exp(i)), i, 'log and exp should be one the inverse of the other')
t.equal(GF.exp(GF.log(i)), i, 'exp and log should be one the inverse of the other')
}
t.equal(GF.mul(0, 1), 0, 'Should return 0 if first param is 0')
t.equal(GF.mul(1, 0), 0, 'Should return 0 if second param is 0')
t.equal(GF.mul(0, 0), 0, 'Should return 0 if both params are 0')
for (let j = 1; j < 255; j++) {
t.equal(GF.mul(j, 255 - j), GF.mul(255 - j, j), 'Multiplication should be commutative')
}
t.end()
})
|
import test from 'ava';
import escapeStringRegexp from './index.js';
test('main', t => {
t.is(
escapeStringRegexp('\\ ^ $ * + ? . ( ) | { } [ ]'),
'\\\\ \\^ \\$ \\* \\+ \\? \\. \\( \\) \\| \\{ \\} \\[ \\]'
);
});
test('escapes `-` in a way compatible with PCRE', t => {
t.is(
escapeStringRegexp('foo - bar'),
'foo \\x2d bar'
);
});
test('escapes `-` in a way compatible with the Unicode flag', t => {
t.regex(
'-',
new RegExp(escapeStringRegexp('-'), 'u')
);
});
|
const { InventoryError,
NotFoundError } = require('../../errors')
const checkExists = (data) => {
return (entity) => {
if (!entity) throw new NotFoundError(`${data} not found`)
return entity
}
}
module.exports = (sequelize, DataTypes) => {
const Pokemon = sequelize.define('Pokemon', {
name: DataTypes.STRING,
price: DataTypes.FLOAT,
stock: DataTypes.INTEGER
}, { tableName: 'pokemons' })
Pokemon.getByIdWithLock = function (pokemonId, transaction) {
return Pokemon.findOne({
where: {
id: pokemonId
},
lock: {
level: transaction.LOCK.UPDATE
}
})
}
Pokemon.getByName = function (name) {
return Pokemon.findOne({
where: {
name
}
}).then(checkExists(name))
}
Pokemon.prototype.decreaseStock = function (quantity) {
if (this.stock < quantity) {
return Promise.reject(new InventoryError(this.name, this.stock))
}
this.stock -= quantity
return this.save()
}
Pokemon.prototype.increaseStock = function (quantity) {
this.stock += quantity
return this.save()
}
return Pokemon
}
|
import hbs from 'htmlbars-inline-precompile';
import { moduleForComponent, test } from 'ember-qunit';
moduleForComponent('advanced-form/integer', {
integration: true
});
test('Render component with attributes', function(assert) {
this.render(
hbs`{{advanced-form/integer min=10 max=20 value=5}}`
);
var $componentInput = this.$('.integer input');
assert.equal($componentInput.val(), '10');
});
|
import React from 'react'
import { Hero } from '../../components'
const HeroContainer = () => (
<Hero />
)
export default HeroContainer
|
'use strict';
let sounds = new Map();
let playSound = path => {
let sound = sounds.get(path);
if (sound) {
sound.play();
} else {
sound = new Audio(path);
sound.play();
}
};
export default playSound;
|
var mongoose = require('mongoose');
var statuses = ['open', 'closed', 'as_expected'];
var priorities = ['major','regular','minor','enhancement'];
var Comment = new mongoose.Schema(
{
comment: String,
username: String,
name: String,
dca: {type: Date, default: Date.now}
}
);
var Bug = new mongoose.Schema(
{
id: {type: String},
name: {type: String, required: true},
desc: String,
status: {type: String, default: 'open'},
priority: {type: String, default: 'regular'},
username: { type: String, required: true},
reported_by: {type: String},
company: {type: String, required: true},
comments: [Comment],
dca: {type: Date, default: Date.now},
dua: Date
}
);
Bug.pre('save', function(next) {
if (this.id === undefined) {
this.id = (new Date()).getTime().toString();
}
now = new Date();
this.dua = now;
next();
});
module.exports = mongoose.model('Bug', Bug);
|
/*** AppView ***/
define(function(require, exports, module) {
var View = require('famous/core/View');
var Surface = require('famous/core/Surface');
var Transform = require('famous/core/Transform');
var StateModifier = require('famous/modifiers/StateModifier');
var SlideshowView = require('views/SlideshowView');
function ProjectView() {
View.apply(this, arguments);
}
ProjectView.prototype = Object.create(View.prototype);
ProjectView.prototype.constructor = ProjectView;
ProjectView.DEFAULT_OPTIONS = {};
module.exports = ProjectView;
});
|
"use strict";
var ArrayCollection_1 = require('./ArrayCollection');
exports.ArrayCollection = ArrayCollection_1.ArrayCollection;
var ArrayList_1 = require('./ArrayList');
exports.ArrayList = ArrayList_1.ArrayList;
var SequenceBase_1 = require('./SequenceBase');
exports.SequenceBase = SequenceBase_1.SequenceBase;
var Buckets_1 = require('./Buckets');
exports.Buckets = Buckets_1.Buckets;
var Collection_1 = require('./Collection');
exports.Collection = Collection_1.Collection;
var Dictionary_1 = require('./Dictionary');
exports.Dictionary = Dictionary_1.Dictionary;
exports.Pair = Dictionary_1.Pair;
var Hash_1 = require('./Hash');
exports.HashFunc = Hash_1.HashFunc;
exports.DefaultHashFunc = Hash_1.DefaultHashFunc;
var HashSet_1 = require('./HashSet');
exports.HashSet = HashSet_1.HashSet;
var Iterable_1 = require('./Iterable');
exports.Iterable = Iterable_1.Iterable;
var LinkedList_1 = require('./LinkedList');
exports.LinkedList = LinkedList_1.LinkedList;
var Native_1 = require('./Native');
exports.NativeIndex = Native_1.NativeIndex;
exports.NativeMap = Native_1.NativeMap;
var Sequence_1 = require('./Sequence');
exports.Sequence = Sequence_1.Sequence;
var Stack_1 = require('./Stack');
exports.Stack = Stack_1.Stack;
var Util_1 = require('./Util');
exports.Util = Util_1.Util;
//# sourceMappingURL=index.js.map
|
'use strict'
var solc = require('solc/wrapper')
var compileJSON = function () { return '' }
var missingInputs = []
module.exports = function (self) {
self.addEventListener('message', function (e) {
var data = e.data
switch (data.cmd) {
case 'loadVersion':
delete self.Module
// NOTE: workaround some browsers?
self.Module = undefined
compileJSON = null
self.importScripts(data.data)
var compiler = solc(self.Module)
compileJSON = function (input) {
try {
return compiler.compileStandardWrapper(input, function (path) {
missingInputs.push(path)
return { 'error': 'Deferred import' }
})
} catch (exception) {
return JSON.stringify({ error: 'Uncaught JavaScript exception:\n' + exception })
}
}
self.postMessage({
cmd: 'versionLoaded',
data: compiler.version()
})
break
case 'compile':
missingInputs.length = 0
self.postMessage({cmd: 'compiled', job: data.job, data: compileJSON(data.input), missingInputs: missingInputs})
break
}
}, false)
}
|
//Express, Mongo & Environment specific imports
var express = require('express');
var morgan = require('morgan');
var serveStatic = require('serve-static');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var compression = require('compression');
var errorHandler = require('errorhandler');
var mongo = require('./api/config/db');
var env = require('./api/config/env');
// Controllers/Routes import
var BookController = require('./api/controller/BookController');
//MongoDB setup
mongo.createConnection(env.mongoUrl);
//Express setup
var app = express();
//Express middleware
app.use(morgan('short'));
app.use(serveStatic(__dirname + '/app'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(compression());
var environment = process.env.NODE_ENV || 'development';
if ('development' == environment) {
app.use(errorHandler({ dumpExceptions: true, showStack: true }));
var ImportController = require('./api/controller/ImportController');
app.get('/import', ImportController.import);
app.get('/import/reset', ImportController.reset);
}
// Route definitions
app.get('/api/books', BookController.list);
app.get('/api/books/:id', BookController.show);
app.post('api/books', BookController.create);
app.put('/api/books/:id', BookController.update);
app.delete('/api/books/:id', BookController.remove);
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Books app listening at http://%s:%s', host, port);
console.log("Configured MongoDB URL: " + env.mongoUrl);
});
|
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var core_1 = require("@angular/core");
var ConversationHeaderComponent = (function () {
function ConversationHeaderComponent() {
}
ConversationHeaderComponent.prototype.ngOnInit = function () {
};
__decorate([
core_1.Input(),
__metadata('design:type', Object)
], ConversationHeaderComponent.prototype, "conversationDetailItem", void 0);
ConversationHeaderComponent = __decorate([
core_1.Component({
selector: 'ngm-conversation-header',
styleUrls: ['./conversation-header.component.scss'],
templateUrl: './conversation-header.component.html'
}),
__metadata('design:paramtypes', [])
], ConversationHeaderComponent);
return ConversationHeaderComponent;
}());
exports.ConversationHeaderComponent = ConversationHeaderComponent;
//# sourceMappingURL=conversation-header.component.js.map
|
const describe = require("mocha").describe;
const it = require("mocha").it;
const assert = require("chai").assert;
const HttpError = require("./HttpError");
describe("HttpError", function () {
it("should be instance of Error", function () {
const testSubject = new HttpError();
assert.isOk(testSubject instanceof Error);
});
});
|
const test = require('tape')
const nlp = require('../_lib')
test('match min-max', function(t) {
let doc = nlp('hello1 one hello2').match('#Value{7,9}')
t.equal(doc.out(), '', 'match was too short')
doc = nlp('hello1 one two three four five hello2').match('#Value{3}')
t.equal(doc.out(), 'one two three', 'exactly three')
doc = nlp('hello1 one two three four five hello2').match('#Value{3,3}')
t.equal(doc.out(), 'one two three', 'still exactly three')
doc = nlp('hello1 one two three four five hello2').match('#Value{3,}')
t.equal(doc.out(), 'one two three four five', 'minimum three')
doc = nlp('hello1 one two three four five hello2').match('hello1 .{3}')
t.equal(doc.out(), 'hello1 one two three', 'unspecific greedy exact length')
doc = nlp('hello1 one two').match('hello1 .{3}')
t.equal(doc.out(), '', 'unspecific greedy not long enough')
t.end()
})
|
function ones(rows, columns) {
columns = columns || rows;
if (typeof rows === 'number' && typeof columns === 'number') {
const matrix = [];
for (let i = 0; i < rows; i++) {
matrix.push([]);
for (let j = 0; j < columns; j++) {
matrix[i].push(1);
}
}
return matrix;
}
throw new TypeError('Matrix dimensions should be integers.');
}
module.exports = ones;
|
// http://www.w3.org/2010/05/video/mediaevents.html
var poppy = popcorn( [ vid_elem_ref | 'id_string' ] );
poppy
// pass-through video control methods
.load()
.play()
.pause()
// property setters
.currentTime( time ) // skip forward or backwards `time` seconds
.playbackRate( rate )
.volume( delta )
.mute( [ state ] )
// sugar?
.rewind() // to beginning + stop??
.loop( [ state ] ) // toggle looping
// queuing (maybe unnecessary):
// enqueue method w/ optional args
.queue( 'method', args )
// enqueue arbitrary callback
.queue(function(next){ /* do stuff */ next(); })
// clear the queue
.clearQueue()
// execute arbitrary code @ time
poppy.exec( 1.23, function(){
// exec code
});
// plugin factory sample
popcorn.plugin( 'myPlugin' [, super_plugin ], init_options );
// call plugin (defined above)
poppy.myPlugin( time, options );
// define subtitle plugin
popcorn.plugin( 'subtitle', {
});
poppy
.subtitle( 1.5, {
html: '<p>SUPER AWESOME MEANING</p>',
duration: 5
})
.subtitle({
start: 1.5,
end: 6.5,
html: '<p>SUPER AWESOME MEANING</p>'
})
.subtitle([
{
start: 1.5,
html: '<p>SUPER AWESOME MEANING</p>'
},
{
start: 2.5,
end: 3.5,
html: '<p>OTHER NEAT TEXT</p>'
}
])
.data([
{
subtitle: [
{
start: 1.5,
html: '<p>SUPER AWESOME MEANING</p>'
},
{
start: 2.5,
end: 3.5,
html: '<p>OTHER NEAT TEXT</p>'
}
]
}
]);
// jQuery-dependent plugin, using $.ajax - extend popcorn.data
popcorn.plugin( 'data', popcorn.data, {
_setup: function( options ) {
// called when plugin is first registered (?)
},
_add: function( options ) {
// called when popcorn.data is called
// this == plugin (?)
if ( typeof options === 'string' ) {
$.ajax({
url: options
// stuff
});
} else {
return this.super.data.apply( this, arguments );
}
}
});
poppy.data( '/data.php' ) // data.php returns JSON?
/*
poppy.twitter( dom_elem | 'id_of_dom_elem', options ); // multiple twitters?? FAIL
poppy.twitter( 'load', options );
*/
var widget1 = $(dom_elem).twitter( options ); // ui widget factory initializes twitter widget
poppy.jQuery( 5.9, {
elem: widget1,
method: 'twitter',
args: [ 'search', '@cowboy' ]
})
poppy.jQuery( time, selector, methodname [, args... ] );
poppy.jQuery( 5.9, widget1, 'twitter', 'search', '@cowboy' );
poppy.jQuery( 5.9, '.div', 'css', 'color', 'red' );
poppy.jQuery( 5.9, '#form', 'submit' );
// sugar methods for jQuery
$(selector).popcorn( time, methodname [, args... ] );
$(selector).popcorn( time, fn );
// another idea, using jQuery special events api
$(selector).bind( 'popcorn', { time: 5.9 }, function(e){
$(this).css( 'color', 'red' );
});
// does $.fn[ methodname ].apply( $(selector), args );
|
define(['myweb/jquery'], function ($) {
'use strict';
var error = function (message) {
$('.form-feedback').removeClass('form-success').addClass('form-error').text(message).fadeIn(200);
};
var success = function (message) {
$('.form-feedback').removeClass('form-error').addClass('form-success').text(message).fadeIn(200);
};
var clear = function () {
$('.form-feedback').hide().removeClass('form-success form-error').empty();
};
return {
error: error,
success: success,
clear: clear
};
});
|
const gulp = require('gulp'),
zip = require('gulp-zip');
/**
* Metadata about the plugin.
*
* @var object
*/
const plugin = {
name: 'example-plugin',
directory: '.'
}
gulp.task('distribute', function () {
let paths = [
'vendor/twig/**/*',
'vendor/composer/**/*',
'vendor/autoload.php',
'src/**/*'
]
let src = gulp.src(paths, {
base: './'
})
let archive = src.pipe(zip(`${plugin.name}.zip`))
return archive.pipe(gulp.dest(plugin.directory))
});
|
/*
* This code it's help you to check JS plugin function (e.g. jQuery) exist.
* When function not exist, the code will auto reload JS plugin from your setting.
*
* plugin_name: It's your plugin function name (e.g. jQuery). The type is string.
* reload_url: It's your reload plugin function URL. The type is string.
*
* Copyright 2015, opoepev (Matt, Paul.Lu, Yi-Chun Lu)
* Free to use and abuse under the MIT license.
* http://www.opensource.org/licenses/mit-license.php
*/
//Main code
var checkJSPluginExist = function (plugin_name, reload_url, depend_plugin_name) {
//window[plugin_name] || document.write('<script src="' + reload_url + '">\x3C/script>');
if (typeof depend_plugin_name !== 'undefined') {
if (typeof window[depend_plugin_name][plugin_name] !== "function") {
var tag = document.createElement('script');
tag.src = reload_url;
var headerElementTag = document.getElementsByTagName('head')[0];
headerElementTag.appendChild(tag);
return false;
}
} else {
if (typeof window[plugin_name] !== "function") {
var tag = document.createElement('script');
tag.src = reload_url;
var headerElementTag = document.getElementsByTagName('head')[0];
headerElementTag.appendChild(tag);
return false;
}
}
return true;
};
|
const ASSERT = require('assert');
describe('SSL Specs', function () {
const PATH = require('path');
let Acts = require('./../index');
let testcert = PATH.join(__dirname, 'certs', 'test.cert');
let testkey = PATH.join(__dirname, 'certs', 'test.key');
it('boot with testcertificate without chain', function() {
return new Promise((resolve, reject) => {
try {
Acts.createServer(__dirname, {
server: {
address: 'localhost',
port: 8086,
ssl: {
usessl: true,
redirectnonsslrequests: true,
privatekey: testkey,
certificate: testcert,
certificationauthority: []
}
}
});
Acts.start(function () {
Acts.shutdown();
resolve();
});
} catch (e) {
reject(e);
}
});
});
it('boot with testcertificate with chain', function() {
return new Promise((resolve, reject) => {
try {
Acts.createServer(__dirname, {
server: {
address: 'localhost',
port: 8086,
ssl: {
usessl: true,
redirectnonsslrequests: true,
privatekey: testkey,
certificate: testcert,
certificationauthority: [testcert]
}
}
});
Acts.start(function () {
Acts.shutdown();
resolve();
});
} catch (e) {
reject(e);
}
});
});
});
|
import React from 'react'
import { useSelector } from 'react-redux'
import Container from 'react-bootstrap/Container'
import Row from 'react-bootstrap/Row'
import Col from 'react-bootstrap/Col'
import MoveSelector from '../containers/move-selector'
import Footer from '../containers/footer'
import Player from '../containers/player'
import WelcomeDlg from '../containers/welcome-dlg'
import History from '../features/history'
import { GlobalState } from '../reducers/consts'
const Game = () => {
const showWelcome = useSelector(state => state.globalState === GlobalState.New)
return (
<>
<WelcomeDlg show={showWelcome} />
<Container>
<Row>
<Col>
<Player color='white' />
</Col>
<Col>
<Player color='black' right />
</Col>
</Row>
<Row>
<Col className='px-0'>
<MoveSelector />
</Col>
<Col sm='3' className='pr-0 pl-1'>
<History />
</Col>
</Row>
<Row>
<Col className='px-0'>
<Footer />
</Col>
</Row>
</Container>
</>
)
}
export default Game
|
const fs = require('fs');
const path = require('path');
class Service {
constructor() {
this.getFileRecursevly = this.getFileRecursevly.bind(this);
this.getFiles = this.getFiles.bind(this);
}
getFileRecursevly(folderPath, shortPath = '') {
var files = [];
var folder = fs.readdirSync(path.resolve(__dirname, folderPath));
var x = folder.forEach(file => {
var filePath = path.resolve(folderPath, file);
if (fs.lstatSync(filePath).isDirectory()) {
files.push({
folder: file,
files: this.getFileRecursevly(filePath, file)
})
} else {
files.push({ file: file, folder: shortPath });
}
})
return files;
}
getFiles(path) {
return new Promise((resolve, reject) => {
var files = this.getFileRecursevly(path)
resolve(files)
})
}
}
module.exports = Service;
|
import DateParser from '../date-parser.js';
import ParsedInfo from '../../parsed-info';
import moment from 'moment';
Date.now = jest.fn(() => 1527130897000)
test('Parses 12 Jan', () => {
const dateParser = new DateParser();
dateParser.parse('12 Jan', ParsedInfo);
const { value, startIndex, endIndex } = ParsedInfo.dateParser;
expect({ value: value.unix(), startIndex, endIndex })
.toEqual({ value: 1515695400, startIndex: 0, endIndex: 6 });
});
test('Parses 22 May', () => {
const dateParser = new DateParser();
dateParser.parse('22 May', ParsedInfo);
const { value, startIndex, endIndex } = ParsedInfo.dateParser;
expect({ value: value.unix(), startIndex, endIndex })
.toEqual({ value: 1526927400, startIndex: 0, endIndex: 6 });
});
|
exports.LOADING = "LOADING";
exports.ERROR = "ERROR";
exports.SUCCESS = "SUCCESS";
exports.FETCH = "FETCH";
exports.CREATE = "CREATE";
exports.UPDATE = "UPDATE";
exports.DELETE = "DELETE";
exports.SET_EDIT_MODE = "SET_EDIT_MODE";
exports.SET_ADD_MODE = "SET_ADD_MODE";
exports.CLOSE_FORM = "CLOSE_FORM";
exports.SET_PAGE = "SET_PAGE"
|
'use strict';
exports.ContainerBuilder = require('./CqrsContainerBuilder');
exports.EventStream = require('./EventStream');
exports.CommandBus = require('./CommandBus');
exports.EventStore = require('./EventStore');
exports.AbstractAggregate = require('./AbstractAggregate');
exports.AggregateCommandHandler = require('./AggregateCommandHandler');
exports.AbstractSaga = require('./AbstractSaga');
exports.SagaEventHandler = require('./SagaEventHandler');
exports.AbstractProjection = require('./AbstractProjection');
exports.InMemoryMessageBus = require('./infrastructure/InMemoryMessageBus');
exports.InMemoryEventStorage = require('./infrastructure/InMemoryEventStorage');
exports.InMemorySnapshotStorage = require('./infrastructure/InMemorySnapshotStorage');
exports.InMemoryView = require('./infrastructure/InMemoryView');
exports.getMessageHandlerNames = require('./utils/getMessageHandlerNames');
exports.subscribe = require('./subscribe');
|
import { connect } from 'react-redux';
import Main from './Main';
import * as userActions from '../../state/user/userActions';
const mapStateToProps = (state, ownProps) => {
return {
activeTab: ownProps.location.pathname.split('/')[2]
};
};
const mapDispatchToProps = (dispatch) => {
return {
getUserData: () => dispatch(userActions.authRequest())
};
};
export default connect(mapStateToProps, mapDispatchToProps)(Main);
|
(function(angular) {
'use strict';
angular
.module('jstube.chromeExtensionCleaner.popup')
.directive('jstubeNavbar', jstubeNavbar);
function jstubeNavbar() {
return {
restrict: 'E',
templateUrl: 'nav/_navbar.html',
controller: 'NavbarController',
controllerAs: 'nav'
};
}
} (window.angular));
|
require('babel-polyfill');
/* eslint-disable */
// Webpack config for creating the production bundle.
var path = require('path');
var webpack = require('webpack');
var CleanPlugin = require('clean-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var strip = require('strip-loader');
var projectRootPath = path.resolve(__dirname, '../');
var assetsPath = path.resolve(projectRootPath, './static/dist');
// https://github.com/halt-hammerzeit/webpack-isomorphic-tools
var WebpackIsomorphicToolsPlugin = require('webpack-isomorphic-tools/plugin');
var webpackIsomorphicToolsPlugin = new WebpackIsomorphicToolsPlugin(require('./webpack-isomorphic-tools'));
module.exports = {
devtool: 'source-map',
context: path.resolve(__dirname, '..'),
entry: {
'main': [
'bootstrap-sass!./src/theme/bootstrap.config.prod.js',
'font-awesome-webpack!./src/theme/font-awesome.config.prod.js',
'./src/client.js'
]
},
output: {
path: assetsPath,
filename: '[name]-[chunkhash].js',
chunkFilename: '[name]-[chunkhash].js',
publicPath: '/dist/'
},
module: {
loaders: [
{ test: /\.jsx?$/, exclude: /node_modules/, loaders: [strip.loader('debug'), 'babel']},
{ test: /\.json$/, loader: 'json-loader' },
{ test: /\.less$/, loader: ExtractTextPlugin.extract('style', 'css?modules&importLoaders=2&sourceMap!autoprefixer?browsers=last 2 version!less?outputStyle=expanded&sourceMap=true&sourceMapContents=true') },
{ test: /\.scss$/, loader: ExtractTextPlugin.extract('style', 'css?modules&importLoaders=2&sourceMap!autoprefixer?browsers=last 2 version!sass?outputStyle=expanded&sourceMap=true&sourceMapContents=true') },
{ test: /\.woff(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=application/font-woff" },
{ test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=application/font-woff" },
{ test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=application/octet-stream" },
{ test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: "file" },
{ test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=image/svg+xml" },
{ test: webpackIsomorphicToolsPlugin.regular_expression('images'), loader: 'url-loader?limit=10240' }
]
},
progress: true,
resolve: {
modulesDirectories: [
'src',
'node_modules'
],
extensions: ['', '.json', '.js', '.jsx']
},
plugins: [
new CleanPlugin([assetsPath], { root: projectRootPath }),
// css files from the extract-text-plugin loader
new ExtractTextPlugin('[name]-[chunkhash].css', {allChunks: true}),
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"production"'
},
__CLIENT__: true,
__SERVER__: false,
__DEVELOPMENT__: false,
__DEVTOOLS__: false
}),
// ignore dev config
new webpack.IgnorePlugin(/\.\/dev/, /\/config$/),
// optimizations
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
}
}),
webpackIsomorphicToolsPlugin
]
};
|
App.SubPhotoInstance = DS.Model.extend({
width: DS.attr('number'),
height: DS.attr('number'),
url: DS.attr('string'),
type: 'sub_photo_instance'
});
|
finApp.directive('brief', function () {
return {
restrict: 'E',
templateUrl: 'views/directives/brief.html',
controller: 'BriefController',
controllerAs: 'bfc'
};
});
|
import {keccak256, bufferToHex} from "ethereumjs-util"
export default class MerkleTree {
constructor(elements) {
// Filter empty strings and hash elements
this.elements = elements.filter(el => el).map(el => keccak256(el))
// Deduplicate elements
this.elements = this.bufDedup(this.elements)
// Sort elements
this.elements.sort(Buffer.compare)
// Create layers
this.layers = this.getLayers(this.elements)
}
getLayers(elements) {
if (elements.length === 0) {
return [[""]]
}
const layers = []
layers.push(elements)
// Get next layer until we reach the root
while (layers[layers.length - 1].length > 1) {
layers.push(this.getNextLayer(layers[layers.length - 1]))
}
return layers
}
getNextLayer(elements) {
return elements.reduce((layer, el, idx, arr) => {
if (idx % 2 === 0) {
// Hash the current element with its pair element
layer.push(this.combinedHash(el, arr[idx + 1]))
}
return layer
}, [])
}
combinedHash(first, second) {
if (!first) {
return second
}
if (!second) {
return first
}
return keccak256(this.sortAndConcat(first, second))
}
getRoot() {
return this.layers[this.layers.length - 1][0]
}
getHexRoot() {
return bufferToHex(this.getRoot())
}
getProof(el) {
let idx = this.bufIndexOf(el, this.elements)
if (idx === -1) {
throw new Error("Element does not exist in Merkle tree")
}
return this.layers.reduce((proof, layer) => {
const pairElement = this.getPairElement(idx, layer)
if (pairElement) {
proof.push(pairElement)
}
idx = Math.floor(idx / 2)
return proof
}, [])
}
getHexProof(el) {
const proof = this.getProof(el)
return this.bufArrToHexArr(proof)
}
getPairElement(idx, layer) {
const pairIdx = idx % 2 === 0 ? idx + 1 : idx - 1
if (pairIdx < layer.length) {
return layer[pairIdx]
} else {
return null
}
}
bufIndexOf(el, arr) {
let hash
// Convert element to 32 byte hash if it is not one already
if (el.length !== 32 || !Buffer.isBuffer(el)) {
hash = keccak256(el)
} else {
hash = el
}
for (let i = 0; i < arr.length; i++) {
if (hash.equals(arr[i])) {
return i
}
}
return -1
}
bufDedup(elements) {
return elements.filter((el, idx) => {
return this.bufIndexOf(el, elements) === idx
})
}
bufArrToHexArr(arr) {
if (arr.some(el => !Buffer.isBuffer(el))) {
throw new Error("Array is not an array of buffers")
}
return arr.map(el => "0x" + el.toString("hex"))
}
sortAndConcat(...args) {
return Buffer.concat([...args].sort(Buffer.compare))
}
}
|
//
// peas.js
//
// tree data structure in javascript
//
//////////////////////////
var peas = function() {
// "sub" here is used as an object container for
// operations related to sub nodes.
// Each pea node will have a "sub" property
// with an instance of "sub"
var sub = function() {}
// the current node is accesable as "this.pea", from
// methods in the "sub" object
sub.prototype.pea = null
// first and last sub
sub.prototype.first = null
sub.prototype.last = null
// number of sub nodes
sub.prototype.n = 0
// get subnode at index position (0 index)
sub.prototype.at = function( index ) {
var pik,i
if( index > this.pea.sub.n - 1 )
return null
pik = this.pea.sub.first
for( i=0; i<index; i++ )
pik = pik.next
return pik
}
// add spare node at last position
// returns the added node
sub.prototype.add = function( spare ) {
if( this.pea.sub.last ) {
spare.prev = this.pea.sub.last
this.pea.sub.last.next = spare
this.pea.sub.last = spare
} else {
spare.prev = null
this.pea.sub.first = spare
this.pea.sub.last = spare
}
spare.top = this.pea
spare.next = null
this.pea.sub.n++
return spare
}
// insert sub node at index position
// returns the inserted node
sub.prototype.insertAt = function( spare, index ) {
var pik
// validate index given
if( index < 0 )
throw "node insert failed, invalid index"
if( index > this.pea.sub.n )
throw "node insert failed, given index exceeds valid places"
// if insert at last+1, then just add
if( index == this.pea.sub.n ) {
this.pea.add( spare )
return
}
pik = this.pea.sub.at( index )
spare.prev = pik.prev
spare.next = pik
// if not inserting at first
if( pik.prev ) {
pik.prev.next = spare
} else {
// inserting as first
pik.top.sub.first = spare
}
pik.prev = spare
spare.top = this.pea
this.pea.sub.n++
return spare
}
// executes function "action" on each direct
// sub node (not recursive)
sub.prototype.each = function( action ) {
var node = this.pea.sub.first
while( node ) {
action( node )
node = node.next
}
}
///////////////////////////
// constructor function for pea nodes
peas = function( item ) {
this.sub = new sub()
this.sub.pea = this
this.item = item
}
peas.prototype.item = null
// top node
peas.prototype.top = null
// prev
peas.prototype.prev = null
// next
peas.prototype.next = null
// namespace for sub nodes
peas.prototype.sub = {}
// find the root node, of the tree
// of this node
peas.prototype.root = function() {
var node = this
while ( node.top ) node = node.top
}
// executes function func on all the tree
// nodes below (recursively)
peas.prototype.onAllBelow = function( action ) {
var node = this.sub.first
while( node ) {
action( node )
if( node.sub.n > 0 )
nodeMethods.each( action )
node = node.next
}
}
// removes this node from tree, leaving
// other tree nodes in consistent state
peas.prototype.rip = function() {
if( ! this.top ) return this
if( this.next )
this.next.prev = this.prev
if( this.prev )
this.prev.next = this.next
if( this.top.sub.last == this )
this.top.sub.last = this.prev
if( this.top.sub.first == this )
this.top.sub.first = this.next
this.top.sub.n--
this.top = null
this.next = null
this.prev = null
return this
}
// returns an array containing all nodes below this, in the tree
peas.prototype.flat = function() {
var flat = []
var grab = function( node ) {
flat.push( node )
}
root.onAllBelow( grab )
return flat
}
// puts spare node in the tree,
// before of this node.
// returns the inserted node
peas.prototype.putBefore = function( spare ) {
if( ! this.top )
throw "not in a tree"
if ( this.prev )
this.prev.next = spare
if( this.top.sub.first == this )
this.top.sub.first = spare
spare.next = this
spare.prev = this.prev
this.prev = spare
spare.top = this.top
this.top.sub.n++
return spare
}
return peas
}()
|
import formatPhoneNumber, { formatPhoneNumberIntl } from './formatPhoneNumberDefaultMetadata'
describe('formatPhoneNumberDefaultMetadata', () => {
it('should format phone numbers', () => {
formatPhoneNumber('+12133734253', 'NATIONAL').should.equal('(213) 373-4253')
formatPhoneNumber('+12133734253', 'INTERNATIONAL').should.equal('+1 213 373 4253')
formatPhoneNumberIntl('+12133734253').should.equal('+1 213 373 4253')
})
})
|
var final_transcript = '';
var recognizing = false;
//var socket = io.connect('http://collab.di.uniba.it:48922');//"http://collab.di.uniba.it/~iaffaldano:48922"
//socket.emit('client_type', {text: "Speaker"});
if ('webkitSpeechRecognition' in window) {
var recognition = new webkitSpeechRecognition();
recognition.continuous = true;
recognition.interimResults = true;
console.log("MAX ALTERNATIVES = "+ recognition.maxAlternatives);
recognition.onstart = function () {
recognizing = true;
console.log("RECOGNITION STARTED");
};
recognition.onerror = function (event) {
console.log("RECOGNITION ERROR: " + event.error);
recognition.start();
};
recognition.onend = function () {
console.log("RECOGNITION STOPPED");
if(recognizing){
recognition.start();
console.log("RECOGNITION RESTARTED");
}
};
recognition.onresult = function (event) {
var interim_transcript = '';
for (var i = event.resultIndex; i < event.results.length; ++i) {
if (event.results[i].isFinal) {
final_transcript += event.results[i][0].transcript;
console.log("CONFIDENCE (" + event.results[i][0].transcript + ") = " + event.results[i][0].confidence);
//recognition.stop();
//recognition.start();
socket.emit('client_message', {text: event.results[i][0].transcript});
} else {
interim_transcript += event.results[i][0].transcript;
}
}
final_transcript = capitalize(final_transcript);
final_span.innerHTML = linebreak(final_transcript);
interim_span.innerHTML = linebreak(interim_transcript);
};
recognition.onaudiostart= function (event) {
console.log("AUDIO START");
};
recognition.onsoundstart= function (event) {
console.log("SOUND START");
};
recognition.onspeechstart= function (event) {
console.log("SPEECH START");
};
recognition.onspeechend= function (event) {
console.log("SPEECH END");
};
recognition.onsoundend= function (event) {
console.log("SOUND END");
};
recognition.onnomatch= function (event) {
console.log("NO MATCH");
};
}
var two_line = /\n\n/g;
var one_line = /\n/g;
function linebreak(s) {
return s.replace(two_line, '<p></p>').replace(one_line, '<br>');
}
function capitalize(s) {
return s.replace(s.substr(0, 1), function (m) {
return m.toUpperCase();
});
}
function startDictation(event) {
if (recognizing) {
recognition.stop();
recognizing=false;
start_button.innerHTML = "START"
return;
}
final_transcript = '';
recognition.lang = 'it-IT';
recognition.start();
start_button.innerHTML = "STOP"
final_span.innerHTML = '';
interim_span.innerHTML = '';
}
|
/* eslint-disable promise/always-return */
import { runAuthenticatedQuery, runQuery } from "schema/v1/test/utils"
describe("UpdateCollectorProfile", () => {
it("updates and returns a collector profile", () => {
/* eslint-disable max-len */
const mutation = `
mutation {
updateCollectorProfile(input: { professional_buyer: true, loyalty_applicant: true, self_reported_purchases: "trust me i buy art", intents: [BUY_ART_AND_DESIGN] }) {
id
name
email
self_reported_purchases
intents
}
}
`
/* eslint-enable max-len */
const context = {
updateCollectorProfileLoader: () =>
Promise.resolve({
id: "3",
name: "Percy",
email: "percy@cat.com",
self_reported_purchases: "treats",
intents: ["buy art & design"],
}),
}
const expectedProfileData = {
id: "3",
name: "Percy",
email: "percy@cat.com",
self_reported_purchases: "treats",
intents: ["buy art & design"],
}
expect.assertions(1)
return runAuthenticatedQuery(mutation, context).then(
({ updateCollectorProfile }) => {
expect(updateCollectorProfile).toEqual(expectedProfileData)
}
)
})
it("throws error when data loader is missing", () => {
/* eslint-disable max-len */
const mutation = `
mutation {
updateCollectorProfile(input: { professional_buyer: true, loyalty_applicant: true, self_reported_purchases: "trust me i buy art" }) {
id
name
email
self_reported_purchases
intents
}
}
`
/* eslint-enable max-len */
const errorResponse =
"Missing Update Collector Profile Loader. Check your access token."
expect.assertions(1)
return runQuery(mutation)
.then(() => {
throw new Error("An error was not thrown but was expected.")
})
.catch(error => {
expect(error.message).toEqual(errorResponse)
})
})
})
|
module.exports = require('./src/tracking');
|
/*
Configures webpack to build only assets required
for integration environments.
*/
const webpack = require('webpack');
const merge = require('webpack-merge');
const { source, sourceAll } = require('../lib/path-helpers');
const ciBuildWorkflow = require('./workflow/build.ci');
const { entries } = require(source('fc-config')); // eslint-disable-line
// remove the styleguide dll references
const modify = (config) => {
config.plugins = config.plugins.slice(1);
return config;
};
module.exports = modify(merge(ciBuildWorkflow, {
entry: sourceAll(entries.ci),
plugins: [
new webpack.DefinePlugin({
'process.env.CI_MODE': true
})
]
}));
|
/**
* A null-safe function to repeat the source string the desired amount of times.
* @private
* @param {String} source
* @param {Number} times
* @returns {String}
*/
function _repeat (source, times) {
var result = "";
for (var i = 0; i < times; i++) {
result += source;
}
return result;
}
export default _repeat;
|
/* eslint-disable func-names */
const {
sampleUrls,
shortSampleUrls,
E2E_WAIT_TIME: WAIT_TIME,
E2E_PRESENT_WAIT_TIME: PRESENT_WAIT_TIME
} = require('../e2e_helper');
module.exports = {
after(browser) {
browser.end();
},
'Go to top page': browser => {
browser.page.index().navigate().waitForElementVisible('body', PRESENT_WAIT_TIME);
},
'Add musics': browser => {
browser.page
.index()
.log('add musics')
.setValue('@trackUrlField', sampleUrls.join(','))
.submitForm('@trackSubmitButton')
.waitForElementPresent('a.playlist-content:nth-child(5)', PRESENT_WAIT_TIME)
.assert.elementPresent('@playButton')
.assert.hasPlaylistLength(5)
.api.pause(WAIT_TIME);
},
'Play music': browser => {
browser.page
.index()
.moveToElement('@playerBlock', 10, 10)
.click('@playButton')
.waitForElementPresent('@pauseButton', PRESENT_WAIT_TIME)
.assert.elementPresent('@pauseButton')
.assert.hasPlaylistLength(5)
.assert.currentTrackNumEquals(1)
.assert.currentTitleEquals(1)
.api.pause(WAIT_TIME);
},
'Play next music': browser => {
browser.page
.index()
.click('@nextButton')
.waitForElementNotPresent('a.playlist-content:nth-child(5)', PRESENT_WAIT_TIME) // dequeue
.assert.elementPresent('@pauseButton')
.assert.hasPlaylistLength(4)
.assert.currentTrackNumEquals(1)
.assert.currentTitleEquals(1)
.api.pause(WAIT_TIME);
},
'Has play prev music button?': browser => {
browser.page.index().assert.cssClassPresent('@prevButton', 'deactivate');
},
'Stop music': browser => {
browser.page
.index()
.click('@pauseButton')
.waitForElementPresent('@playButton', PRESENT_WAIT_TIME)
.assert.elementPresent('@playButton')
.assert.hasPlaylistLength(4)
.assert.currentTrackNumEquals(1)
.assert.title('jukebox')
.api.pause(WAIT_TIME);
},
'Play specified music': browser => {
browser.page
.index()
.click('a.playlist-content:nth-child(3)')
.waitForElementPresent('@pauseButton', PRESENT_WAIT_TIME)
.assert.elementPresent('@pauseButton')
.assert.hasPlaylistLength(4)
.assert.currentTrackNumEquals(3)
.assert.currentTitleEquals(3)
.api.pause(WAIT_TIME);
},
'Delete current music': browser => {
browser.page
.index()
.click('a.playlist-content:nth-child(3) i[title=Delete]')
.waitForElementPresent('@playButton', PRESENT_WAIT_TIME)
.assert.elementPresent('@playButton')
.assert.hasPlaylistLength(3)
.assert.currentTrackNumEquals(3)
.assert.title('jukebox')
.api.pause(WAIT_TIME);
},
'Add short music': browser => {
browser.page
.index()
.setValue('@trackUrlField', shortSampleUrls[0])
.submitForm('@trackSubmitButton')
.waitForElementPresent('a.playlist-content:nth-child(4)', PRESENT_WAIT_TIME)
.assert.hasPlaylistLength(4);
},
'Play short music': browser => {
browser.page
.index()
.click('a.playlist-content:nth-child(4)')
.waitForElementPresent('@pauseButton', PRESENT_WAIT_TIME);
},
'Wait till end': browser => {
browser.page
.index()
.waitForElementNotPresent(
'.playlist-content:nth-child(4) .thumbnail-wrapper i',
PRESENT_WAIT_TIME
)
.assert.elementPresent('@playButton')
.assert.hasPlaylistLength(3);
},
'Clear playlist': browser => {
browser.page
.index()
.click('@openClearModalButton')
.waitForElementPresent('@clearModal', PRESENT_WAIT_TIME)
.click('@clearButton')
.waitForElementNotPresent('a.playlist-content', PRESENT_WAIT_TIME)
.assert.hasPlaylistLength(0)
.api.pause(WAIT_TIME);
}
};
|
#! /usr/bin/env node
import minimist from 'minimist'
import Avifors from './Avifors'
import YamlModelBuilder from './model/YamlModelBuilder'
import Configuration from './Configuration'
import {helpMessage} from './help'
import YamlHelper from './tools/YamlHelper'
const avifors = new Avifors()
const corePlugins = ['./model/plugin', './template/plugin', './commands/plugin']
corePlugins.forEach(plugin => require(plugin).default(avifors))
const argv = minimist(process.argv.slice(2))
const userCommand = argv._[0]
if (userCommand === undefined || userCommand === 'help') {
console.log(helpMessage)
} else {
const yamlHelper = new YamlHelper()
const config = new Configuration(argv.config, yamlHelper)
avifors.loadPlugins(config.plugins)
const modelBuilder = new YamlModelBuilder(avifors, yamlHelper)
const model = modelBuilder.build(config.modelFiles)
avifors.setModel(model)
avifors.getCommand(userCommand)({
avifors: avifors,
model: model,
argv: argv
})
}
|
import express from 'express'
import cors from 'cors'
import bodyParser from 'body-parser'
import helmet from 'helmet'
import httpStatus from 'http-status'
import path from 'path'
import routes from './routes'
import logger from './helpers/logger.js'
const app = express()
// Pug
app.set('view engine', 'pug')
app.set('views', path.join(__dirname, 'views'))
// Helmet helps you secure your Express apps by setting various HTTP headers.
app.use(helmet())
// Enable CORS
app.use(cors())
// To use with Nginx
// app.enable('trust proxy')
// Parse incoming request bodies in a middleware before your handlers, available under the req.body property.
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())
// API Routes
app.use('/', routes)
// Catch 404
app.get('*', (req, res) => {
res.status(404).send({ message: 'Not found' })
})
// Error log
app.use((err, req, res, next) => {
logger.log(err.level || 'error', err.message)
next(err)
})
// Error handler
app.use((err, req, res, next) => {
res.status(err.status || 500).send({
status: err.status || 500,
message: err.status ? err.message : httpStatus[500],
})
})
export default app
|
import Lab from 'lab';
import server from '../../server';
import data from '../data';
const expect = Lab.assertions.expect;
export const lab = Lab.script();
lab.experiment('ProfileCtrl', function() {
lab.before(done => {
data.sync().then(done, done);
});
lab.test('[getAuthenticated] returns the current profile', function(done) {
const options = {
method: 'GET',
url: '/profile',
headers: {
'Authorization': `Bearer ${data.fp.token.value}`
}
};
server.inject(options, function(response) {
const result = response.result;
expect(response.statusCode).to.equal(200);
expect(result.email).to.equal(data.fp.account.profile.email);
done();
});
});
lab.test('[getAuthenticated] returns 401 without a token', function(done) {
const options = {
method: 'GET',
url: '/profile'
};
server.inject(options, function(response) {
expect(response.statusCode).to.equal(401);
done();
});
});
lab.test('[get] returns the correct profile by id', function(done) {
const options = {
method: 'GET',
url: `/profile/${data.tp.account.profile.id}`,
headers: {
'Authorization': `Bearer ${data.fp.token.value}`
}
};
server.inject(options, function(response) {
const result = response.result;
expect(response.statusCode).to.equal(200);
expect(result.id).to.equal(data.tp.account.profile.id);
done();
});
});
lab.test('[get] returns the correct profile by email', function(done) {
const options = {
method: 'GET',
url: `/profile/${encodeURIComponent(data.tp.account.profile.email)}`,
headers: {
'Authorization': `Bearer ${data.fp.token.value}`
}
};
server.inject(options, function(response) {
const result = response.result;
expect(response.statusCode).to.equal(200);
expect(result.email).to.equal(data.tp.account.profile.email);
done();
});
});
lab.test('[get] returns 404 if not found by id', function(done) {
const options = {
method: 'GET',
url: `/profile/123-456`,
headers: {
'Authorization': `Bearer ${data.fp.token.value}`
}
};
server.inject(options, function(response) {
expect(response.statusCode).to.equal(404);
done();
});
});
lab.test('[get] returns 404 if not found by email', function(done) {
const options = {
method: 'GET',
url: `/profile/${encodeURIComponent('not@found.com')}`,
headers: {
'Authorization': `Bearer ${data.fp.token.value}`
}
};
server.inject(options, function(response) {
expect(response.statusCode).to.equal(404);
done();
});
});
lab.test('[update] returns the profile with a new first name (by id)', function(done) {
const options = {
method: 'PUT',
url: `/profile/${data.tp.account.profile.id}`,
headers: {
'Authorization': `Bearer ${data.tp.token.value}`
},
payload: {
firstName: 'Gargantua'
}
};
server.inject(options, function(response) {
const result = response.result;
expect(response.statusCode).to.equal(200);
expect(result.name.first).to.equal('Gargantua');
done();
});
});
lab.test('[update] returns the profile with a new last name (by email)', function(done) {
const options = {
method: 'PUT',
url: `/profile/${data.tp.account.profile.email}`,
headers: {
'Authorization': `Bearer ${data.tp.token.value}`
},
payload: {
lastName: 'Batman'
}
};
server.inject(options, function(response) {
const result = response.result;
expect(response.statusCode).to.equal(200);
expect(result.name.last).to.equal('Batman');
done();
});
});
lab.test('[update] returns 401 if trying to update someone else\'s profile', function(done) {
const options = {
method: 'PUT',
url: `/profile/${data.tp.account.profile.email}`,
headers: {
'Authorization': `Bearer ${data.fp.token.value}`
},
payload: {
lastName: 'Batman'
}
};
server.inject(options, function(response) {
expect(response.statusCode).to.equal(401);
done();
});
});
});
|
const fs = require('fs')
const path = require('path')
const LRU = require('lru-cache')
const express = require('express')
const favicon = require('serve-favicon')
const compression = require('compression')
const resolve = file => path.resolve(__dirname, file)
const { createBundleRenderer } = require('vue-server-renderer')
const isProd = process.env.NODE_ENV === 'production'
const useMicroCache = process.env.MICRO_CACHE !== 'false'
const serverInfo =
`express/${require('express/package.json').version} ` +
`vue-server-renderer/${require('vue-server-renderer/package.json').version}`
const app = express()
const template = fs.readFileSync(resolve('./src/index.html'), 'utf-8');
function createRenderer (bundle, options) {
// https://github.com/vuejs/vue/blob/dev/packages/vue-server-renderer/README.md#why-use-bundlerenderer
return createBundleRenderer(bundle, Object.assign(options, {
template,
// for component caching
cache: LRU({
max: 1000,
maxAge: 1000 * 60 * 15
}),
// this is only needed when vue-server-renderer is npm-linked
basedir: resolve('./dist'),
// recommended for performance
runInNewContext: false
}))
}
let renderer
let readyPromise
if (isProd) {
// In production: create server renderer using built server bundle.
// The server bundle is generated by vue-ssr-webpack-plugin.
const bundle = require('./dist/vue-ssr-server-bundle.json')
// The client manifests are optional, but it allows the renderer
// to automatically infer preload/prefetch links and directly add <script>
// tags for any async chunks used during render, avoiding waterfall requests.
const clientManifest = require('./dist/vue-ssr-client-manifest.json')
renderer = createRenderer(bundle, {
clientManifest
})
} else {
// In development: setup the dev server with watch and hot-reload,
// and create a new renderer on bundle / index template update.
readyPromise = require('./build/setup-dev-server')(app, (bundle, options) => {
renderer = createRenderer(bundle, options)
})
}
const serve = (path, cache) => express.static(resolve(path), {
maxAge: cache && isProd ? 1000 * 60 * 60 * 24 * 30 : 0
})
app.use(compression({ threshold: 0 }))
//app.use(favicon('./public/logo-48.png'))
app.use('/dist', serve('./dist', true))
app.use('/public', serve('./public', true))
app.use('/manifest.json', serve('./manifest.json', true))
app.use('/service-worker.js', serve('./dist/service-worker.js'))
// 1-second microcache.
// https://www.nginx.com/blog/benefits-of-microcaching-nginx/
const microCache = LRU({
max: 100,
maxAge: 1000
})
// since this app has no user-specific content, every page is micro-cacheable.
// if your app involves user-specific content, you need to implement custom
// logic to determine whether a request is cacheable based on its url and
// headers.
const isCacheable = req => useMicroCache
function render (req, res) {
const s = Date.now()
res.setHeader("Content-Type", "text/html")
res.setHeader("Server", serverInfo)
const handleError = err => {
if (err.url) {
res.redirect(err.url)
} else if(err.code === 404) {
res.status(404).end('404 | Page Not Found')
} else {
// Render Error Page or Redirect
res.status(500).end('500 | Internal Server Error')
console.error(`error during render : ${req.url}`)
console.error(err.stack)
}
}
const cacheable = isCacheable(req)
if (cacheable) {
const hit = microCache.get(req.url)
if (hit) {
if (!isProd) {
console.log(`cache hit!`)
}
return res.end(hit)
}
}
const context = {
title: '交易虎_手机游戏交易平台_手游交易_帐号交易_游戏币交易_装备交易_道具交易_jiaoyihu', // default title
url: req.url
}
renderer.renderToString(context, (err, html) => {
debugger;
if (err) {
return handleError(err)
}
res.end(html)
if (cacheable) {
microCache.set(req.url, html)
}
if (!isProd) {
console.log(`whole request: ${Date.now() - s}ms`)
}
})
}
app.get('*', isProd ? render : (req, res) => {
readyPromise.then(() => render(req, res))
})
const port = process.env.PORT || 80;
app.listen(port, () => {
console.log(`server started at localhost:${port}`)
})
|
$(function(){
$("#addCompanyForm").validate({
rules: {
name : {
required : true
},
email: {
required: true,
email: true
},
url : {
required : true,
url : true
}
},
messages: {
name : {
required : "Please enter your company name"
},
url : {
required : "Please enter your company website",
url : "Please enter a valid url"
},
email: {
required: "Enter your Company email address",
email: "Please enter a valid email address",
}
}
});
$('#addCompanyDialog').on('hide.bs.modal', function (e) {
refresh();
});
$('#addCompanyDialog').on('shown.bs.modal', function (e) {
$('#name').focus();
$('#id').val('');
var id = $(e.relatedTarget).attr('id');
var isEdit = $(e.relatedTarget).hasClass('fa-edit');
console.log(isEdit);
if(isEdit){
$('#id').val(id);
$.getJSON('/account/companies/' + id, function(data){
if(data.result){
$('#name').val(data.result.name);
$('#email').val(data.result.email);
$('#url').val(data.result.url);
}
});
}
var validator = $( "#addCompanyForm" ).validate();
validator.resetForm();
});
$('#confirm-delete').on('show.bs.modal', function(e) {
var id = $(e.relatedTarget).attr('id');
$(this).find('.btn-ok').on('click', function(){
$.ajax({
url: '/account/companies/' + id,
type: 'delete',
dataType: 'json',
success: function(data) {
$('#message ').html('<div class="error" style="text-align:center;padding:5px;">' + data.message + '</div>')
$('#confirm-delete').modal('hide');
if(data.result)
getCompanies();
}
});
});
});
$("#addCompanyForm").submit(function(e) {
e.preventDefault();
if($( "#addCompanyForm" ).valid()){
var actionurl = '/account/companies';
var type = 'post';
console.log($('#id').val() != '');
if($('#id').val() != ''){
type = 'put';
actionurl = '/account/companies/' + $('#id').val();
}
//var actionurl = e.currentTarget.action;
$.ajax({
url: actionurl,
type: type,
dataType: 'json',
data: $("#addCompanyForm").serialize(),
success: function(data) {
$('#message ').html('<div class="error" style="text-align:center;padding:5px;">' + data.message + '</div>')
$('#addCompanyDialog').modal('hide');
if(data.result)
getCompanies();
}
});
}
});
var getCompanies= function(){
$('#companylist').html('<div class="loader"><i class="fa fa-spinner fa-pulse"></i></div>');
$.get('/account/companies/list', function(data){
$('#companylist').html(data);
$('#message ').html('');
});
};
$('#refresh').on('click', function () {
$('#message ').html('');
getCompanies();
});
var refresh = function () {
$('#id').val('');
$('#name').val('');
$('#url').val('');
$('#email').val('');
};
getCompanies();
});
|
module.exports = {
entry: {
'public/js/bundle.js': ['./index.js'],
},
output: {
filename: '[name]',
},
devtool: 'eval',
module: {
loaders: [
{
test: /.js$/,
exclude: /node_modules/,
loaders: ['babel'],
}
]
}
}
|
import { expect } from 'chai'
import {List, Map} from 'immutable'
import categories from '../src/reducer.js'
describe("Category Test", () => {
it("should add a category", () => {
let initialState = Map({
user: 'Skye'
})
let expectedState = Map({
user: 'Skye',
categories: Map({
'Love': 0
})
})
let result = categories(initialState, {type:'ADD_CATEGORY', value:'Love'})
expect(result).to.eql(expectedState)
})
it("adding a category does not modify previous state", () => {
let initialState = Map({
user: 'Skye',
categories: Map({
'Love': 90
})
})
let expectedState = Map({
user: 'Skye',
categories: Map({
'Love': 90,
'Communication': 0
})
})
let result = categories(initialState, {type:'ADD_CATEGORY', value:'Communication'})
expect(result).to.eql(expectedState)
expect(initialState).to.eql(Map({
user: 'Skye',
categories: Map({
'Love': 90
})
}))
})
it("should rate a category", () => {
let initialState = Map({
user: 'Skye',
categories: Map({
'Love': 0
})
})
let expectedState = Map({
user: 'Skye',
categories: Map({
'Love': 90
})
})
let result = categories(initialState, { type:'RATE_CATEGORY', name:'Love', value:90 })
expect(result).to.eql(Map({
user: 'Skye',
categories: Map({
'Love': 90
})
}))
})
it("should stop adding categories", () => {
let initialState = Map({
user: 'Skye',
categories: Map({
'Love': 90,
'Communication': 80,
'Fun' : 100
})
})
let expectedState = Map({
user: 'Skye',
categories: Map({
'Love': 90,
'Communication': 80,
'Fun' : 100
}),
categories_finished: true
})
let result = categories(initialState, {type:'FINISH_CATEGORIES', value: true})
expect(result).to.eql(expectedState)
})
})
|
/**
* DevExtreme (core/component_registrator.js)
* Version: 16.2.5
* Build date: Mon Feb 27 2017
*
* Copyright (c) 2012 - 2017 Developer Express Inc. ALL RIGHTS RESERVED
* EULA: https://www.devexpress.com/Support/EULAs/DevExtreme.xml
*/
"use strict";
var $ = require("jquery"),
errors = require("./errors"),
MemorizedCallbacks = require("./memorized_callbacks"),
publicComponentUtils = require("./utils/public_component");
var callbacks = new MemorizedCallbacks;
var registerComponent = function(name, namespace, componentClass) {
if (!componentClass) {
componentClass = namespace
} else {
namespace[name] = componentClass
}
publicComponentUtils.name(componentClass, name);
callbacks.fire(name, componentClass)
};
registerComponent.callbacks = callbacks;
var registerJQueryComponent = function(name, componentClass) {
$.fn[name] = function(options) {
var result, isMemberInvoke = "string" === typeof options;
if (isMemberInvoke) {
var memberName = options,
memberArgs = $.makeArray(arguments).slice(1);
this.each(function() {
var instance = componentClass.getInstance(this);
if (!instance) {
throw errors.Error("E0009", name)
}
var member = instance[memberName],
memberValue = member.apply(instance, memberArgs);
if (void 0 === result) {
result = memberValue
}
})
} else {
this.each(function() {
var instance = componentClass.getInstance(this);
if (instance) {
instance.option(options)
} else {
new componentClass(this, options)
}
});
result = this
}
return result
}
};
callbacks.add(registerJQueryComponent);
module.exports = registerComponent;
|
'use strict';
angular.module('mgcrea.ngStrap.dropdown', ['mgcrea.ngStrap.tooltip'])
.provider('$dropdown', function() {
var defaults = this.defaults = {
animation: 'am-fade',
prefixClass: 'dropdown',
prefixEvent: 'dropdown',
placement: 'bottom-left',
template: 'dropdown/dropdown.tpl.html',
trigger: 'click',
container: false,
keyboard: true,
html: false,
delay: 0
};
this.$get = function($window, $rootScope, $tooltip, $timeout) {
var bodyEl = angular.element($window.document.body);
var matchesSelector = Element.prototype.matchesSelector || Element.prototype.webkitMatchesSelector || Element.prototype.mozMatchesSelector || Element.prototype.msMatchesSelector || Element.prototype.oMatchesSelector;
function DropdownFactory(element, config) {
var $dropdown = {};
// Common vars
var options = angular.extend({}, defaults, config);
var scope = $dropdown.$scope = options.scope && options.scope.$new() || $rootScope.$new();
$dropdown = $tooltip(element, options);
var parentEl = element.parent();
// Protected methods
$dropdown.$onKeyDown = function(evt) {
if (!/(38|40)/.test(evt.keyCode)) return;
evt.preventDefault();
evt.stopPropagation();
// Retrieve focused index
var items = angular.element($dropdown.$element[0].querySelectorAll('li:not(.divider) a'));
if(!items.length) return;
var index;
angular.forEach(items, function(el, i) {
if(matchesSelector && matchesSelector.call(el, ':focus')) index = i;
});
// Navigate with keyboard
if(evt.keyCode === 38 && index > 0) index--;
else if(evt.keyCode === 40 && index < items.length - 1) index++;
else if(angular.isUndefined(index)) index = 0;
items.eq(index)[0].focus();
};
// Overrides
var show = $dropdown.show;
$dropdown.show = function() {
show();
// use timeout to hookup the events to prevent
// event bubbling from being processed imediately.
$timeout(function() {
options.keyboard && $dropdown.$element.on('keydown', $dropdown.$onKeyDown);
bodyEl.on('click', onBodyClick);
}, 0, false);
parentEl.hasClass('dropdown') && parentEl.addClass('open');
};
var hide = $dropdown.hide;
$dropdown.hide = function() {
if(!$dropdown.$isShown) return;
options.keyboard && $dropdown.$element.off('keydown', $dropdown.$onKeyDown);
bodyEl.off('click', onBodyClick);
parentEl.hasClass('dropdown') && parentEl.removeClass('open');
hide();
};
var destroy = $dropdown.destroy;
$dropdown.destroy = function() {
bodyEl.off('click', onBodyClick);
destroy();
};
// Private functions
function onBodyClick(evt) {
if(evt.target === element[0]) return;
return evt.target !== element[0] && $dropdown.hide();
}
return $dropdown;
}
return DropdownFactory;
};
})
.directive('bsDropdown', function($window, $sce, $dropdown) {
return {
restrict: 'EAC',
scope: true,
link: function postLink(scope, element, attr, transclusion) {
// Directive options
var options = {scope: scope};
angular.forEach(['placement', 'container', 'delay', 'trigger', 'keyboard', 'html', 'animation', 'template', 'id'], function(key) {
if(angular.isDefined(attr[key])) options[key] = attr[key];
});
// use string regex match boolean attr falsy values, leave truthy values be
var falseValueRegExp = /^(false|0|)$/i;
angular.forEach(['html', 'container'], function(key) {
if(angular.isDefined(attr[key]) && falseValueRegExp.test(attr[key]))
options[key] = false;
});
// Support scope as an object
attr.bsDropdown && scope.$watch(attr.bsDropdown, function(newValue, oldValue) {
scope.content = newValue;
}, true);
// Visibility binding support
attr.bsShow && scope.$watch(attr.bsShow, function(newValue, oldValue) {
if(!dropdown || !angular.isDefined(newValue)) return;
if(angular.isString(newValue)) newValue = !!newValue.match(/true|,?(dropdown),?/i);
newValue === true ? dropdown.show() : dropdown.hide();
});
// Initialize dropdown
var dropdown = $dropdown(element, options);
// Garbage collection
scope.$on('$destroy', function() {
if (dropdown) dropdown.destroy();
options = null;
dropdown = null;
});
}
};
});
|
/*
*
* hocNotification
*
*/
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { compose, setPropTypes } from 'recompose';
import { createStructuredSelector } from 'reselect';
import { selectNotifications } from 'features/common_ui/selectors';
const mapStateToProps = createStructuredSelector({
notifications: selectNotifications(),
});
const sliderPropsType = setPropTypes({
notifications: PropTypes.oneOfType([PropTypes.array, PropTypes.object]).isRequired,
});
const hocNotification = compose(connect(mapStateToProps), sliderPropsType);
export default hocNotification;
|
#!/usr/bin/env node
let layouts = [
`# French
&é"'(-è_çà)=
azertyuiop^$*
qsdfghjklmù
wxcvbn,;:!
`,
`# German (German (IBM) is the same)
1234567890ß
qwertzuiopü+#
asdfghjklöä
yxcvbnm,.-
`,
`# Spanish
1234567890'¡
qwertyuiop+ç
asdfghjklñ
zxcvbnm,.-
## ESV
1234567890-
qwertyuiop÷
asdfghjklñç
zxcvbnm,.=
`,
`# Português
1234567890'«
qwertyuiop+´~
asdfghjklçº
zxcvbnm,.-
## PTB
1234567890-=
qwertyuiop´[]
asdfghjklç~~
zxcvbnm,.;
`,
`# Russian
1234567890-=
йцукенгшщзхъ\
фывапролджэ
ячсмитьбю.
`,
`# Cyrillic
1234567890'+
љњертзуиопшђж
асдфгхјклчћ
ѕџцвбнм,.-
`,
`# Arabic
1234567890-=
ضصثقفغعهخحجد\
شسيبلاتنمكط
ئءؤرلاىةوزظ
`,
`# Korean
1234567890-=
qwertyuiop[]\
asdfghjkl;'
zxcvbnm,./
# Turkish
1234567890*-
qwertyuıopğü,
asdfghjklşi
zxcvbnmöç.
!'^+%&/()=?_
QWERTYUIOPĞÜ;
ASDFGHJKLŞİ
ZXCVBNMÖÇ:
`
].join("\n").split("\n").filter(
line => !(line[0] === "#" || line[0] === "(" && line.slice(-1) === ")")
).join("");
const getRe = name => name instanceof RegExp ? name : new RegExp(`[\\p{${name}}]`, "ug");
const filter = (text, re) => [...new Set(text.match(re, ""))].sort();
const parse = arr => [
arr,
arr.map(i=>i.codePointAt()).filter(i => i >= 128),
arr.length
];
const print = (category, text) => console.log(`${category}:`, ...parse(filter(text, getRe(category))));
print("Ll", layouts);
print("Lo", layouts);
print("Lu", layouts);
print("Lt", layouts);
print("Lm", layouts);
const range = (start, end, conv=String.fromCharCode) => {
const arr = [];
for (let i = start, end2 = end || start + 1; i < end2; i++) { arr.push(i); }
return conv ? conv(...arr) : arr;
};
const hex = (start, end) => range(start, end, null).map(i => i.toString(16));
print("Ll", range(1070, 1120));
print("Lo", range(1569, 1614));
var hasConsole = 1;
// hasConsole = 0;
if (typeof require === "function" && hasConsole) {
Object.assign(require('repl').start("node> ").context, {
hex, range, print, filter, parse, getRe, layouts
});
}
|
import Ember from 'ember';
export default Ember.Component.extend({
tagName : '',
item : null,
isFollowing : false,
isLoggedIn : false,
init() {
this.set('isLoggedIn', !!this.get('application.user.login'));
if (this.get('application.places.length') > 0) {
this.set('isFollowing', !!this.get('application.places').findBy('id', this.get('item.id')));
}
}
});
|
const ircFramework = require('irc-framework')
const store = require('../store')
const attachEvents = require('./attachEvents')
const connect = connection => {
const state = store.getState()
let ircClient = state.ircClients[connection.id]
if (!ircClient) {
ircClient = new ircFramework.Client({
nick: connection.nick,
host: connection.host,
port: connection.port,
tls: connection.tls,
username: connection.username || connection.nick,
password: connection.password,
// "Not enough parameters" with empty gecos so a space is used.
gecos: connection.gecos || ' ',
// Custom auto reconnect mechanism is implemented, see events/connection.js.
auto_reconnect: false,
})
attachEvents(ircClient, connection.id)
store.dispatch({
type: 'SET_IRC_CLIENT',
payload: {
connectionId: connection.id,
ircClient,
},
})
}
ircClient.connect()
}
module.exports = connect
|
const assert = require('assert')
const { unparse } = require('uuid-parse')
const supertest = require('supertest')
const createApp = require('../app')
const { createSetup, getAuthPassword } = require('./lib')
const { createPlayer, createKick } = require('./fixtures')
describe('Query player kick', () => {
let setup
let request
beforeAll(async () => {
setup = await createSetup()
const app = await createApp({ ...setup, disableUI: true })
request = supertest(app.callback())
}, 20000)
afterAll(async () => {
await setup.teardown()
}, 20000)
test('should resolve all fields', async () => {
const { config: server, pool } = setup.serversPool.values().next().value
const cookie = await getAuthPassword(request, 'admin@banmanagement.com')
const player = createPlayer()
const actor = createPlayer()
const kick = createKick(player, actor)
await pool('bm_players').insert([player, actor])
await pool('bm_player_kicks').insert(kick)
const { body, statusCode } = await request
.post('/graphql')
.set('Cookie', cookie)
.set('Accept', 'application/json')
.send({
query: `query playerKick {
playerKick(id:"1", serverId: "${server.id}") {
id
reason
created
actor {
id
name
}
acl {
update
delete
yours
}
}
}`
})
assert.strictEqual(statusCode, 200)
assert(body)
assert(body.data)
assert.deepStrictEqual(body.data.playerKick,
{
id: '1',
reason: kick.reason,
created: kick.created,
actor: { id: unparse(actor.id), name: actor.name },
acl: { delete: true, update: true, yours: false }
})
})
})
|
// All code points in the Khmer Symbols block as per Unicode v5.0.0:
[
0x19E0,
0x19E1,
0x19E2,
0x19E3,
0x19E4,
0x19E5,
0x19E6,
0x19E7,
0x19E8,
0x19E9,
0x19EA,
0x19EB,
0x19EC,
0x19ED,
0x19EE,
0x19EF,
0x19F0,
0x19F1,
0x19F2,
0x19F3,
0x19F4,
0x19F5,
0x19F6,
0x19F7,
0x19F8,
0x19F9,
0x19FA,
0x19FB,
0x19FC,
0x19FD,
0x19FE,
0x19FF
];
|
jQuery(document).ready(function() {
$('.alert-close').bind('click', function() {
$(this).parent().fadeOut(100);
});
function createAutoClosingAlert(selector, delay) {
var alert = $(selector).alert();
window.setTimeout(function() { alert.alert('close') }, delay);
}
createAutoClosingAlert(".alert", 20000);
});
|
CucumberJsBrowserRunner.StepDefinitions.test3(function () {
var And = Given = When = Then = this.defineStep,
runner;
Given(/^test3$/, function(callback) {
callback();
});
When(/^test3$/, function(callback) {
callback();
});
Then(/^test3$/, function(callback) {
callback();
});
});
|
'use strict';
var run = require('./helpers').runMochaJSON;
var assert = require('assert');
describe('.only()', function() {
describe('bdd', function() {
it('should run only tests that marked as `only`', function(done) {
run('options/only/bdd.fixture.js', ['--ui', 'bdd'], function(err, res) {
if (err) {
done(err);
return;
}
assert.equal(res.stats.pending, 0);
assert.equal(res.stats.passes, 11);
assert.equal(res.stats.failures, 0);
assert.equal(res.code, 0);
done();
});
});
});
describe('tdd', function() {
it('should run only tests that marked as `only`', function(done) {
run('options/only/tdd.fixture.js', ['--ui', 'tdd'], function(err, res) {
if (err) {
done(err);
return;
}
assert.equal(res.stats.pending, 0);
assert.equal(res.stats.passes, 8);
assert.equal(res.stats.failures, 0);
assert.equal(res.code, 0);
done();
});
});
});
describe('qunit', function() {
it('should run only tests that marked as `only`', function(done) {
run('options/only/qunit.fixture.js', ['--ui', 'qunit'], function(
err,
res
) {
if (err) {
done(err);
return;
}
assert.equal(res.stats.pending, 0);
assert.equal(res.stats.passes, 5);
assert.equal(res.stats.failures, 0);
assert.equal(res.code, 0);
done();
});
});
});
});
|
module.exports = require('eden-class').extend(function() {
/* Require
-------------------------------*/
/* Constants
-------------------------------*/
/* Public.Properties
-------------------------------*/
/* Protected Properties
-------------------------------*/
this._table = null;
this._where = [];
/* Private Properties
-------------------------------*/
/* Magic
-------------------------------*/
this.___construct = function(table) {
this.argument().test(1, 'string', 'undef');
if(typeof table === 'string') {
this.setTable(table);
}
};
/* Public.Methods
-------------------------------*/
/**
* Set the table name in which you want to delete from
*
* @param string name
* @return this
*/
this.setTable = function(table) {
//argument test
this.argument().test(1, 'string');
this._table = table;
return this;
};
/**
* Returns the string version of the query
*
* @param bool
* @return string
* @notes returns the query based on the registry
*/
this.getQuery = function() {
return 'DELETE FROM {TABLE} WHERE {WHERE};'
.replace('{TABLE}' , this._table)
.replace('{WHERE}' , this._where.join(' AND '));
};
/**
* Where clause
*
* @param array|string where
* @return this
* @notes loads a where phrase into registry
*/
this.where = function(where) {
//Argument 1 must be a string or array
this.argument().test(1, 'string', 'array');
if(typeof where === 'string') {
where = [where];
}
this._where = this._where.concat(where);
return this;
};
/* Protected Methods
-------------------------------*/
/* Private Methods
-------------------------------*/
}).register('eden/mysql/delete');
|
const path = require('path');
const { expect } = require('chai');
const delay = require('../../../../lib/utils/delay');
describe('Compiler service', () => {
it('Should execute a basic test', async () => {
await runTests('testcafe-fixtures/basic-test.js', 'Basic test');
});
it('Should handle an error', async () => {
try {
await runTests('testcafe-fixtures/error-test.js', 'Throw an error', { shouldFail: true });
}
catch (err) {
expect(err[0].startsWith([
`The specified selector does not match any element in the DOM tree. ` +
` > | Selector('#not-exists') ` +
` [[user-agent]] ` +
` 1 |fixture \`Compiler service\`;` +
` 2 |` +
` 3 |test(\`Throw an error\`, async t => {` +
` > 4 | await t.click('#not-exists');` +
` 5 |});` +
` 6 | at <anonymous> (${path.join(__dirname, 'testcafe-fixtures/error-test.js')}:4:13)`
])).to.be.true;
}
});
it('Should allow using ClientFunction in assertions', async () => {
await runTests('testcafe-fixtures/client-function-in-assertions.js', 'ClientFunction in assertions');
});
it('Should execute Selectors in sync mode', async () => {
await runTests('testcafe-fixtures/synchronous-selectors.js');
});
it('debug', async () => {
let resolver = null;
const result = new Promise(resolve => {
resolver = resolve;
});
runTests('testcafe-fixtures/debug.js')
.then(() => resolver());
setTimeout(async () => {
const client = global.testCafe.runner.compilerService.cdp;
await client.Debugger.resume();
await delay(1000);
await client.Debugger.resume();
}, 10000);
return result;
});
});
|
var fans=require('../../modules/blog/fans');
var User=require('../../modules/resume/user');
var async = require('asyncawait/async');
var await = require('asyncawait/await');
module.exports=(async(function(method,req,res){
var result;
if(method==='get'){
}
else if(method==='post'){
var userId=req.session.uid;
var targetId=req.body.targetId;
if(userId){
if(userId==targetId){
result={
status:-1,
msg:"你咋可以自己关注自己呢?自恋!"
}
}else{
//已登录才能关注,查询是否已关注过
var isFansDate=await(fans.findOne({
where:{
userId:userId,
targetId:targetId
}
}))
if(isFansDate){
result={
status:-1,
msg:"已关注"
}
}
else{
var fansDate=await(fans.create({
userId:userId,
targetId:targetId
}))
if(fansDate){
result={
status:0,
msg:"关注成功"
}
}else{
result={
status:-1,
msg:"关注失败"
}
}
}
}
}else{
result={
status:-1,
msg:"未登录"
}
}
}
else if(method==='delete'){
var targetId=req.query.targetId;
var userId=req.session.uid;
if(userId){
//已登录才能取消关注,查询是否已关注过
var isFansDate=await(fans.findOne({
where:{
userId:userId,
targetId:targetId
}
}))
if(isFansDate){
var fansDate=await(fans.destroy({
where:{
userId:userId,
targetId:targetId
}
}))
if(fansDate){
result={
status:0,
msg:"取消关注成功"
}
}else{
result={
status:-1,
msg:"取消关注失败"
}
}
}
else{
result={
status:-1,
msg:"未关注"
}
}
}else{
result={
status:-1,
msg:"未登录"
}
}
}
res.writeHead(200,{"Content-Type":"text/html;charset=utf-8"});
res.end(JSON.stringify(result))
}))
|
// @flow
import React, { Component } from 'react'
import { Helmet } from 'react-helmet'
import AlternativeMedia from './AlternativeMedia'
import ImageViewer from './ImageViewer'
import { Code, CodeBlock, Title } from '../components'
const propFn = k => {
const style = { display: 'inline-block', marginBottom: 4, marginRight: 4 }
return (
<span key={k} style={style}>
<Code>{k}</Code>
</span>
)
}
const commonProps = [
'carouselProps',
'currentIndex',
'currentView',
'frameProps',
'getStyles',
'isFullscreen',
'isModal',
'modalProps',
'interactionIsIdle',
'trackProps',
'views',
]
export default class CustomComponents extends Component<*> {
render() {
return (
<div>
<Helmet>
<title>Components - React Images</title>
<meta
name="description"
content="React Images allows you to augment layout and functionality by
replacing the default components with your own."
/>
</Helmet>
<Title>Components</Title>
<p>
The main feature of this library is providing consumers with the building blocks necessary to create <em>their</em> component.
</p>
<h3>Replacing Components</h3>
<p>
React-Images allows you to augment layout and functionality by replacing the default components with your own, using the <Code>components</Code>{' '}
property. These components are given all the current props and state letting you achieve anything you dream up.
</p>
<h3>Inner Props</h3>
<p>
All functional properties that the component needs are provided in <Code>innerProps</Code> which you must spread.
</p>
<h3>Common Props</h3>
<p>
Every component receives <Code>commonProps</Code> which are spread onto the component. These include:
</p>
<p>{commonProps.map(propFn)}</p>
<CodeBlock>
{`import React from 'react';
import Carousel from 'react-images';
const CustomHeader = ({ innerProps, isModal }) => isModal ? (
<div {...innerProps}>
// your component internals
</div>
) : null;
class Component extends React.Component {
render() {
return <Carousel components={{ Header: CustomHeader }} />;
}
}`}
</CodeBlock>
<h2>Component API</h2>
<h3>{'<Container />'}</h3>
<p>Wrapper for the carousel. Attachment point for mouse and touch event listeners.</p>
<h3>{'<Footer />'}</h3>
<p>
Element displayed beneath the views. Renders <Code>FooterCaption</Code> and <Code>FooterCount</Code> by default.
</p>
<h3>{'<FooterCaption />'}</h3>
<p>
Text associated with the current view. Renders <Code>{'{viewData.caption}'}</Code> by default.
</p>
<h3>{'<FooterCount />'}</h3>
<p>
How far through the carousel the user is. Renders{' '}
<Code>
{'{currentIndex}'} of {'{totalViews}'}
</Code>{' '}
by default
</p>
<h3>{'<Header />'}</h3>
<p>
Element displayed above the views. Renders <Code>FullscreenButton</Code> and <Code>CloseButton</Code> by default.
</p>
<h3>{'<HeaderClose />'}</h3>
<p>
The button to close the modal. Accepts the <Code>onClose</Code> function.
</p>
<h3>{'<HeaderFullscreen />'}</h3>
<p>
The button to fullscreen the modal. Accepts the <Code>toggleFullscreen</Code> function.
</p>
<h3>{'<Navigation />'}</h3>
<p>
Wrapper for the <Code>{'<NavigationNext />'}</Code> and <Code>{'<NavigationPrev />'}</Code> buttons.
</p>
<h3>{'<NavigationPrev />'}</h3>
<p>
Button allowing the user to navigate to the previous view. Accepts an <Code>onClick</Code> function.
</p>
<h3>{'<NavigationNext />'}</h3>
<p>
Button allowing the user to navigate to the next view. Accepts an <Code>onClick</Code> function.
</p>
<h3>{'<View />'}</h3>
<p>
The view component renders your media to the user. Receives the current view object as the <Code>data</Code> property.
</p>
<h2>Examples</h2>
<ImageViewer {...this.props} />
<AlternativeMedia />
</div>
)
}
}
|
var gulp = require('gulp');
var browserify = require('browserify');
//transform jsx to js
var reactify = require('reactify');
//convert to stream
var source = require('vinyl-source-stream');
var nodemon = require('gulp-nodemon');
gulp.task('browserify', function() {
//source
browserify('./src/js/main.js')
//convert jsx to js
.transform('reactify')
//creates a bundle
.bundle()
.pipe(source('main.js'))
.pipe(gulp.dest('dist/js'))
});
gulp.task('copy', function() {
gulp.src('src/index.html')
.pipe(gulp.dest('dist'));
gulp.src('src/assets/**/*.*')
.pipe(gulp.dest('dist/assets'));
});
gulp.task('nodemon', function(cb) {
var called = false;
return nodemon({
script: 'server.js'
}).on('start', function() {
if (!called) {
called = true;
cb();
}
});
});
gulp.task('default', ['browserify', 'copy', 'nodemon'], function() {
return gulp.watch('src/**/*.*', ['browserify', 'copy']);
});
|
module.exports = function(config) {
config.set({
basePath: '../../',
frameworks: ['jasmine', 'requirejs'],
files: [
{pattern: 'test/unit/require.conf.js', included: true},
{pattern: 'test/unit/tests/global.js', included: true},
{pattern: 'src/client/**/*.*', included: false},
{pattern: 'test/unit/tests/**/*.*', included: false},
],
plugins: [
'karma-jasmine',
'karma-requirejs',
'karma-coverage',
'karma-html-reporter',
'karma-phantomjs-launcher',
'karma-chrome-launcher',
'karma-firefox-launcher',
'karma-safari-launcher',
'karma-ie-launcher'
],
reporters: ['coverage', 'html', 'progress'],
preprocessors: {
'src/client/component/**/*.js': ['coverage'],
'src/client/service/**/*.js': ['coverage']
},
coverageReporter: {
type: 'html',
dir: 'test/unit/coverage/',
includeAllSources: true
},
htmlReporter: {
outputDir: 'results' //it is annoying that this file path isn't from basePath :(
},
colors: true,
logLevel: config.LOG_INFO,
autoWatch: false,
browsers: ['Chrome'/*, 'PhantomJS', 'Firefox', 'IE', 'Safari'*/],
captureTimeout: 5000,
singleRun: true
});
};
|
/**
* @namespace http
*
* The C<http> namespace groups functions and classes used while making
* HTTP Requests.
*
*/
ECMAScript.Extend('http', function (ecma) {
// Intentionally private
var _documentLocation = null
function _getDocumentLocation () {
if (!_documentLocation) _documentLocation = new ecma.http.Location();
return _documentLocation;
}
/**
* @constant HTTP_STATUS_NAMES
* HTTP/1.1 Status Code Definitions
*
* Taken from, RFC 2616 Section 10:
* L<http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html>
*
* These names are used in conjuction with L<ecma.http.Request> for
* indicating callback functions. The name is prepended with C<on> such
* that
* onMethodNotAllowed
* corresponds to the callback triggered when a 405 status is received.
*
# Names
*
* 100 Continue
* 101 SwitchingProtocols
* 200 Ok
* 201 Created
* 202 Accepted
* 203 NonAuthoritativeInformation
* 204 NoContent
* 205 ResetContent
* 206 PartialContent
* 300 MultipleChoices
* 301 MovedPermanently
* 302 Found
* 303 SeeOther
* 304 NotModified
* 305 UseProxy
* 306 Unused
* 307 TemporaryRedirect
* 400 BadRequest
* 401 Unauthorized
* 402 PaymentRequired
* 403 Forbidden
* 404 NotFound
* 405 MethodNotAllowed
* 406 NotAcceptable
* 407 ProxyAuthenticationRequired
* 408 RequestTimeout
* 409 Conflict
* 410 Gone
* 411 LengthRequired
* 412 PreconditionFailed
* 413 RequestEntityTooLarge
* 414 RequestURITooLong
* 415 UnsupportedMediaType
* 416 RequestedRangeNotSatisfiable
* 417 ExpectationFailed
* 500 InternalServerError
* 501 NotImplemented
* 502 BadGateway
* 503 ServiceUnavailable
* 504 GatewayTimeout
* 505 HTTPVersionNotSupported
*/
this.HTTP_STATUS_NAMES = {
100: 'Continue',
101: 'SwitchingProtocols',
200: 'Ok',
201: 'Created',
202: 'Accepted',
203: 'NonAuthoritativeInformation',
204: 'NoContent',
205: 'ResetContent',
206: 'PartialContent',
300: 'MultipleChoices',
301: 'MovedPermanently',
302: 'Found',
303: 'SeeOther',
304: 'NotModified',
305: 'UseProxy',
306: 'Unused',
307: 'TemporaryRedirect',
400: 'BadRequest',
401: 'Unauthorized',
402: 'PaymentRequired',
403: 'Forbidden',
404: 'NotFound',
405: 'MethodNotAllowed',
406: 'NotAcceptable',
407: 'ProxyAuthenticationRequired',
408: 'RequestTimeout',
409: 'Conflict',
410: 'Gone',
411: 'LengthRequired',
412: 'PreconditionFailed',
413: 'RequestEntityTooLarge',
414: 'RequestURITooLong',
415: 'UnsupportedMediaType',
416: 'RequestedRangeNotSatisfiable',
417: 'ExpectationFailed',
500: 'InternalServerError',
501: 'NotImplemented',
502: 'BadGateway',
503: 'ServiceUnavailable',
504: 'GatewayTimeout',
505: 'HTTPVersionNotSupported'
};
/**
* @function isSameOrigin
*
* Compare originating servers.
*
* var bool = ecma.http.isSameOrigin(uri);
* var bool = ecma.http.isSameOrigin(uri, uri);
*
* Is the resource located on the server at the port using the same protocol
* which served the document.
*
* var bool = ecma.http.isSameOrigin('http://www.example.com');
*
* Are the two URI's served from the same origin
*
* var bool = ecma.http.isSameOrigin('http://www.example.com', 'https://www.example.com');
*
*/
this.isSameOrigin = function(uri1, uri2) {
if (!(uri1)) return false;
var loc1 = uri1 instanceof ecma.http.Location
? uri1 : new ecma.http.Location(uri1);
var loc2 = uri2 || _getDocumentLocation();
return loc1.isSameOrigin(loc2);
};
});
|
import debounce from 'debounce';
import $ from 'jquery';
const groupElementsByTop = (groups, element) => {
const top = $(element).offset().top;
groups[top] = groups[top] || [];
groups[top].push(element);
return groups;
};
const groupElementsByZero = (groups, element) => {
groups[0] = groups[0] || [];
groups[0].push(element);
return groups;
};
const clearHeight = elements => $(elements).css('height', 'auto');
const getHeight = element => $(element).height();
const applyMaxHeight = (elements) => {
const heights = elements.map(getHeight);
const maxHeight = Math.max.apply(null, heights);
$(elements).height(maxHeight);
};
const equalizeHeights = (elements, groupByTop) => {
// Sort into groups.
const groups = groupByTop ?
elements.reduce(groupElementsByTop, {}) :
elements.reduce(groupElementsByZero, {});
// Convert to arrays.
const groupsAsArray = Object.keys(groups).map((key) => {
return groups[key];
});
// Apply max height.
groupsAsArray.forEach(clearHeight);
groupsAsArray.forEach(applyMaxHeight);
};
$.fn.equalHeight = function ({
groupByTop = false,
resizeTimeout = 20,
updateOnDOMReady = true,
updateOnDOMLoad = false
} = {}) {
// Convert to native array.
const elements = this.toArray();
// Handle resize event.
$(window).on('resize', debounce(() => {
equalizeHeights(elements, groupByTop);
}, resizeTimeout));
// Handle load event.
$(window).on('load', () => {
if (updateOnDOMLoad) {
equalizeHeights(elements, groupByTop);
}
});
// Handle ready event.
$(document).on('ready', () => {
if (updateOnDOMReady) {
equalizeHeights(elements, groupByTop);
}
});
return this;
};
|
// Structure to represent a proof
class ProofTree {
constructor({equation, rule, newScope=false }) {
this.equation = equation;
this.rule = rule;
this.newScope = newScope;
this.parent = null;
this.children = [];
this.isSound = !newScope;
}
isAssumption() {
return this.newScope;
}
isEmpty() {
return this.parent === null && this.children === [];
}
size() {
if (this.isEmpty()) return 0;
if (this.children.length)
return 1 + this.children.map(c=>c.size()).reduce((acc, c)=>acc+c);
return 1;
}
lastNumber() {
return this.size();
}
walk(fn) {
fn(this);
this.children.forEach(child => {
child.walk(fn);
});
}
last() {
if (this.children.length === 0) return this;
var last = this;
this.children.forEach(child => {
if (!child.isAssumption()) {
last = child.last();
}
});
return last;
}
setLines() {
var count = 1;
this.walk((child) => {
child.lineNumber = count;
count ++;
});
}
root() {
if (this.parent === null) return this;
return this.parent.root();
}
inScope(target) {
if (this.lineNumber === target) {
return true;
} else {
if (this.parent === null) return false;
var child = null;
var anySiblings = this.parent.children.some(child => {
return !child.isAssumption() && (child.lineNumber === target)
})
if (anySiblings) {
return true;
}
return this.parent.inScope(target);
}
}
// inScope(line1, line2, context=this.root()) {
//
// if (line1 === line2) return true;
// if (line1 > line2) return false;
// var line1Obj = context.line(line1);
// var line2Obj = context.line(line2);
// return this.inScope(line1Obj.lineNumber, line2Obj.parent.lineNumber, context);
// }
line(lineNumber) {
var line = null;
var count = 1;
this.walk(child => {
if (lineNumber === count) line = child;
count ++;
});
return line;
}
addLine(line) {
line.parent = this.last();
line.parent.children.push(line);
this.root().setLines();
}
closeBox() {
this.isSound = true;
}
addLineTo(line, lineNumber) {
// line.parent = this.line()
}
addLineNewScope({equation, rule}) {
var line = new ProofTree({
equation,
rule,
newScope: true
});
line.parent = this.last();
this.children.push(line);
line.root().setLines();
}
}
// Synonym as it reads better sometimes
ProofTree.prototype.scope = ProofTree.prototype.line;
export default ProofTree;
|
version https://git-lfs.github.com/spec/v1
oid sha256:20e35c5c96301564881e3f892b8c5e38c98b131ea58889ed9889b15874e39cbe
size 8394
|
/**
* Javascript file for Category Show.
* It requires jQuery.
*/
function wpcs_gen_tag() {
// Category Show searches for term_id since 0.4.1 and not term slug.
// There is a need to add the id%% tag to be compatible with other versions
$("#wpcs_gen_tag").val("%%wpcs-"+$("#wpcs_term_dropdown").val()+"%%"+$("#wpcs_order_type").val()+$("#wpcs_order_by").val()+"%%id%%");
$("#wpcs_gen_tag").select();
$("#wpcs_gen_tag").focus();
}
|
function mathGame(){
var game = new Phaser.Game(window.innerWidth, window.innerHeight, Phaser.auto, 'math', {
preload: onPreload,
create: onCreate,
// resize:onResize
});
WebFontConfig = {
active: function() { game.time.events.add(Phaser.Timer.SECOND, createText, this); },
google: {
families: ['Fredericka the Great']
}
};
var sumsArray = [];
var questionText;
var randomSum;
var timeTween;
var numberTimer;
var buttonMask;
var replay;
var score=0;
var scoreText;
var isGameOver = false;
var topScore;
var numbersArray = [-3,-2,-1,1,2,3];
function buildThrees(initialNummber,currentIndex,limit,currentString){
for(var i=0;i<numbersArray.length;i++){
var sum = initialNummber+numbersArray[i];
var outputString = currentString+(numbersArray[i]<0?"":"+")+numbersArray[i];
if(sum>0 && sum<4 && currentIndex==limit){
sumsArray[limit][sum-1].push(outputString);
}
if(currentIndex<limit){
buildThrees(sum,currentIndex+1,limit,outputString);
}
}
}
function onPreload() {
// responsiveScale();
game.load.script('webfont', '//ajax.googleapis.com/ajax/libs/webfont/1.4.7/webfont.js');
game.load.image("timebar", "/images/math/timebar.png");
game.load.image("buttonmask", "/images/math/buttonmask.png");
game.load.spritesheet("buttons", "/images/math/buttons.png",400,50);
game.load.spritesheet('myguy', '/images/math/dance.png', 70, 120);
game.load.image("background", "/images/math/board2.png");
game.load.image("replay", "images/math/replay.png");
game.load.image("home", "images/home.png");
}
function onCreate() {
topScore = localStorage.getItem("topScore")==null?0:localStorage.getItem("topScore");
// game.stage.backgroundColor = "#cccccc";
chalkBoard = game.add.sprite(1100, 850,"background");
chalkBoard.x = 0;
chalkBoard.y = 0;
chalkBoard.height = game.height;
chalkBoard.width = game.width;
game.stage.disableVisibilityChange = true;
gameOverSprite = this.game.add.sprite(600, 300, 'myguy');
gameOverSprite.visible = false;
gameOverSprite.frame = 0;
gameOverSprite.animations.add('left', [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13], 10, true);
replay = game.add.button(game.width*.6, game.height*.1,"replay",replay,this);
replay.visable = false;
home = game.add.button(game.width*.75, game.height*.1, 'home', function onClick(){window.location.href ="/home"});
home.scale.setTo(0.2,0.2);
for(var i=1;i<5;i++){
sumsArray[i]=[[],[],[]];
for(var j=1;j<=3;j++){
buildThrees(j,1,i,j);
}
}
questionText = game.add.text(game.width*.5,game.height*.3,"-");
questionText.anchor.set(0.5);
scoreText = game.add.text(game.width*.1,game.height*.10,"-");
for(var i=0;i<3;i++){
var numberButton = game.add.button(game.width*.3,game.height*.4+i*75,"buttons",checkAnswer,this).frame=i;
}
numberTimer = game.add.sprite(game.width*.3,game.height*.4,"timebar");
nextNumber();
}
function createText() {
questionText.font = 'Fredericka the Great';
questionText.fontSize = 37;
questionText.addColor('#edf0f3',0);
scoreText.font = 'Fredericka the Great';
scoreText.fontSize = 37;
scoreText.addColor('#edf0f3',0);
};
function gameOver(gameOverString){
// game.stage.backgroundColor = "#ff0000";
console.log(gameOverString)
questionText.text = "Wrong Answer!";
questionText.addColor('#ff471a',0);
isGameOver = true;
localStorage.setItem("topScore",Math.max(score,topScore));
numberTimer.destroy();
buttonMask.destroy();
replay.visible = true;
// gameOverSprite.visible = true;
// gameOverSprite.animations.play('left');
}
function checkAnswer(button){
var correctAnswer;
if(!isGameOver){
if(button.frame==randomSum){
score+=Math.floor((buttonMask.x+350)/4);
nextNumber();
}
else{
if(score>0) {
timeTween.stop();
}
correctAnswer = randomSum;
gameOver(correctAnswer);
}
}
}
function replay(){
$("#math").html("");
mathGame();
}
function nextNumber(){
scoreText.text = "Score: "+score.toString()+"\nBest Score: "+topScore.toString();
if(buttonMask){
buttonMask.destroy();
game.tweens.removeAll();
}
buttonMask = game.add.graphics(game.width*.3,game.height*.4);
buttonMask.beginFill(0xffffff);
buttonMask.drawRect(0, 0, 400, 200);
buttonMask.endFill();
numberTimer.mask = buttonMask;
if(score>0){
timeTween=game.add.tween(buttonMask);
timeTween.to({
x: -350
}, 9000, "Linear",true);
timeTween.onComplete.addOnce(function(){
gameOver("?");
}, this);
}
randomSum = game.rnd.between(0,2);
questionText.text = sumsArray[Math.min(Math.round((score-100)/400)+1,4)][randomSum][game.rnd.between(0,sumsArray[Math.min(Math.round((score-100)/400)+1,4)][randomSum].length-1)];
}
}
// }
|
'use strict';exports.__esModule = true;var _stringify = require('babel-runtime/core-js/json/stringify');var _stringify2 = _interopRequireDefault(_stringify);var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);var _inherits2 = require('babel-runtime/helpers/inherits');var _inherits3 = _interopRequireDefault(_inherits2);function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { default: obj };}var _class = function (_think$controller$bas) {(0, _inherits3.default)(_class, _think$controller$bas);function _class() {(0, _classCallCheck3.default)(this, _class);return (0, _possibleConstructorReturn3.default)(this, _think$controller$bas.apply(this, arguments));}
/**
* some base method in here
*/_class.prototype.
get = function get(key) {
if (key == undefined) {
return this.http._get;
}
return this.http._get[key];
};_class.prototype.
post = function post(key) {
if (key == undefined) {
return this.http._post;
}
return this.http._post[key];
};_class.prototype.
getCookie = function getCookie(key) {
if (key == undefined) {
return '';
}
return this.http._cookie;
};_class.prototype.
setCookie = function setCookie(key, val) {
if (typeof val !== 'string') {
val = (0, _stringify2.default)(val);
}
return this.http._cookie[key] = val;
};_class.prototype.
apiErrorHandle = function apiErrorHandle(errno) {
var API_ERROR_MSG_TABLE = {
// user
'101': '用户未登录',
'102': '用户密码错误',
'111': '密码不一致',
// category
'3000': 'Category name is empty' };
var msg = API_ERROR_MSG_TABLE[errno] || 'system error';
console.log(msg);
this.fail(errno, msg);
};return _class;}(think.controller.base);exports.default = _class;
|
// Generated by CoffeeScript 1.8.0
(function() {
var TaskSchema, mongoose;
mongoose = require('./mongoose');
TaskSchema = mongoose.Schema({
id: {
type: Number,
unique: true
},
title: {
type: String
},
url: {
type: String,
unique: true
},
status: {
type: Number,
"default": 1
}
});
module.exports = mongoose.model('Task', TaskSchema);
}).call(this);
//# sourceMappingURL=tasks.js.map
|
var mongoose = require('mongoose'),
_ = require('underscore'),
roomTokenizer = function(msg) {
var tokens = [];
tokens = tokens.concat(msg.content.split(' '));
tokens.push(msg.author);
return tokens;
};
exports.init = function(db) {
var EntitySchemaDefinition,
EntitySchema,
EntityModel;
//create schema
EntitySchemaDefinition = {
content : { type: String, required: true },
author: {
email: String,
username: String,
avatar: String
},
room: { type: mongoose.Schema.ObjectId, required: true },
status: { type: Number, required: true },
date : { type: Date },
keywords: [String]
};
EntitySchema = new mongoose.Schema(EntitySchemaDefinition, {autoIndex: false} );
EntitySchema.index({keywords: 1});
//during save update all keywords
EntitySchema.pre('save', function(next) {
//set dates
if ( !this.date ) {
this.date = new Date();
}
//clearing keywords
this.keywords.length = 0;
//adding keywords
this.keywords = this.keywords.concat(roomTokenizer(this));
next();
});
EntityModel = db.model('Message', EntitySchema);
return EntityModel;
};
|
import React, { PropTypes } from 'react'
import { Grid, Row, Col } from 'react-bootstrap'
import Sort from '../../components/Sort'
import ProjectFilterForm from '../../components/ProjectFilterForm'
import Search from '../../containers/Search'
import ProjectsDashboardStatContainer from '../../containers/ProjectsDashboardStatContainer';
import { PROJECTS_SORT } from '../../resources/options'
const ProjectsDashboard = (props) => {
return (
<Grid fluid>
<Row>
<Col xs={12} md={4}>
<ProjectsDashboardStatContainer />
</Col>
<Col xs={12} md={8}>
Latest Updates
</Col>
</Row>
<Row>
<Col md={12}>
<Search
types={['projects']}
searchId='projectsDashboardSearch'
filterElement={<ProjectFilterForm />}
sortElement={<Sort options={PROJECTS_SORT} />}
/>
</Col>
</Row>
</Grid>
)
}
export default ProjectsDashboard
|
export default function mapNodesToColumns({
children = [],
columns = 1,
dimensions = [],
} = {}) {
let nodes = []
let heights = []
if (columns === 1) {
return children
}
// use dimensions to calculate the best column for each child
if (dimensions.length && dimensions.length === children.length) {
for(let i=0; i<columns; i++) {
nodes[i] = []
heights[i] = 0
}
children.forEach((child, i) => {
let { width, height } = dimensions[i]
let index = heights.indexOf(Math.min(...heights))
nodes[index].push(child)
heights[index] += height / width
})
}
// equally spread the children across the columns
else {
for(let i=0; i<columns; i++) {
nodes[i] = children.filter((child, j) => j % columns === i)
}
}
return nodes
}
|
module.exports = {
FIREBASE_URL: 'https://amber-heat-<your-app>.firebaseio.com/',
TWITTER_KEY: '',
TWITTER_SECRET: '',
TWITTER_CALLBACK: process.env.TWITTER_CALLBACK || 'Twitter Callback Url'
};
|
'use strict'
const _ = require('lodash')
module.exports = {
getQueryString(url) {
const qs = {}
_.forEach(url.split('?').pop().split('&'), s => {
if (!s) return
const kv = s.split('=')
if (kv[0]) {
qs[kv[0]] = decodeURIComponent(kv[1])
}
})
return qs
},
toQueryString(o) {
return _.keys(o).map(k => k + '=' + encodeURIComponent(o[k])).join('&')
},
isMobile(v) {
return /^1[358]\d{9}$/.test(v)
},
getRandomStr() {
return (1e32 * Math.random()).toString(36).slice(0, 16)
}
}
|
'use strict';
var eachAsync = require('each-async');
var onetime = require('onetime');
var arrify = require('arrify');
module.exports = function (hostnames, cb) {
cb = onetime(cb);
eachAsync(arrify(hostnames), function (hostname, i, next) {
var img = new Image();
img.onload = function () {
cb(true);
// skip to end
next(new Error());
};
img.onerror = function () {
next();
};
img.src = '//' + hostname + '/favicon.ico?' + Date.now();
}, function () {
cb(false);
});
};
|
/* @flow */
import {
InputTypeComposer,
type ObjectTypeComposerFieldConfigAsObjectDefinition,
} from 'graphql-compose';
import { getTypeName, type CommonOpts, desc } from '../../../utils';
import { getAllAsFieldConfigMap } from '../../Commons/FieldNames';
export function getRangeITC<TContext>(
opts: CommonOpts<TContext>
): InputTypeComposer<TContext> | ObjectTypeComposerFieldConfigAsObjectDefinition<any, any> {
const name = getTypeName('QueryRange', opts);
const description = desc(
`
Matches documents with fields that have terms within a certain range.
[Documentation](https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-range-query.html)
`
);
const subName = getTypeName('QueryRangeSettings', opts);
const fields = getAllAsFieldConfigMap(
opts,
opts.getOrCreateITC(subName, () => ({
name: subName,
fields: {
gt: 'JSON',
gte: 'JSON',
lt: 'JSON',
lte: 'JSON',
boost: 'Float',
relation: 'String',
},
}))
);
if (typeof fields === 'object') {
return opts.getOrCreateITC(name, () => ({
name,
description,
fields,
}));
}
return {
type: 'JSON',
description,
};
}
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
// Split the input into chunks.
exports.default = (function (input, fail) {
var len = input.length;
var level = 0;
var parenLevel = 0;
var lastOpening;
var lastOpeningParen;
var lastMultiComment;
var lastMultiCommentEndBrace;
var chunks = [];
var emitFrom = 0;
var chunkerCurrentIndex;
var currentChunkStartIndex;
var cc;
var cc2;
var matched;
function emitChunk(force) {
var len = chunkerCurrentIndex - emitFrom;
if (((len < 512) && !force) || !len) {
return;
}
chunks.push(input.slice(emitFrom, chunkerCurrentIndex + 1));
emitFrom = chunkerCurrentIndex + 1;
}
for (chunkerCurrentIndex = 0; chunkerCurrentIndex < len; chunkerCurrentIndex++) {
cc = input.charCodeAt(chunkerCurrentIndex);
if (((cc >= 97) && (cc <= 122)) || (cc < 34)) {
// a-z or whitespace
continue;
}
switch (cc) {
case 40: // (
parenLevel++;
lastOpeningParen = chunkerCurrentIndex;
continue;
case 41: // )
if (--parenLevel < 0) {
return fail('missing opening `(`', chunkerCurrentIndex);
}
continue;
case 59: // ;
if (!parenLevel) {
emitChunk();
}
continue;
case 123: // {
level++;
lastOpening = chunkerCurrentIndex;
continue;
case 125: // }
if (--level < 0) {
return fail('missing opening `{`', chunkerCurrentIndex);
}
if (!level && !parenLevel) {
emitChunk();
}
continue;
case 92: // \
if (chunkerCurrentIndex < len - 1) {
chunkerCurrentIndex++;
continue;
}
return fail('unescaped `\\`', chunkerCurrentIndex);
case 34:
case 39:
case 96: // ", ' and `
matched = 0;
currentChunkStartIndex = chunkerCurrentIndex;
for (chunkerCurrentIndex = chunkerCurrentIndex + 1; chunkerCurrentIndex < len; chunkerCurrentIndex++) {
cc2 = input.charCodeAt(chunkerCurrentIndex);
if (cc2 > 96) {
continue;
}
if (cc2 == cc) {
matched = 1;
break;
}
if (cc2 == 92) { // \
if (chunkerCurrentIndex == len - 1) {
return fail('unescaped `\\`', chunkerCurrentIndex);
}
chunkerCurrentIndex++;
}
}
if (matched) {
continue;
}
return fail("unmatched `" + String.fromCharCode(cc) + "`", currentChunkStartIndex);
case 47: // /, check for comment
if (parenLevel || (chunkerCurrentIndex == len - 1)) {
continue;
}
cc2 = input.charCodeAt(chunkerCurrentIndex + 1);
if (cc2 == 47) {
// //, find lnfeed
for (chunkerCurrentIndex = chunkerCurrentIndex + 2; chunkerCurrentIndex < len; chunkerCurrentIndex++) {
cc2 = input.charCodeAt(chunkerCurrentIndex);
if ((cc2 <= 13) && ((cc2 == 10) || (cc2 == 13))) {
break;
}
}
}
else if (cc2 == 42) {
// /*, find */
lastMultiComment = currentChunkStartIndex = chunkerCurrentIndex;
for (chunkerCurrentIndex = chunkerCurrentIndex + 2; chunkerCurrentIndex < len - 1; chunkerCurrentIndex++) {
cc2 = input.charCodeAt(chunkerCurrentIndex);
if (cc2 == 125) {
lastMultiCommentEndBrace = chunkerCurrentIndex;
}
if (cc2 != 42) {
continue;
}
if (input.charCodeAt(chunkerCurrentIndex + 1) == 47) {
break;
}
}
if (chunkerCurrentIndex == len - 1) {
return fail('missing closing `*/`', currentChunkStartIndex);
}
chunkerCurrentIndex++;
}
continue;
case 42: // *, check for unmatched */
if ((chunkerCurrentIndex < len - 1) && (input.charCodeAt(chunkerCurrentIndex + 1) == 47)) {
return fail('unmatched `/*`', chunkerCurrentIndex);
}
continue;
}
}
if (level !== 0) {
if ((lastMultiComment > lastOpening) && (lastMultiCommentEndBrace > lastMultiComment)) {
return fail('missing closing `}` or `*/`', lastOpening);
}
else {
return fail('missing closing `}`', lastOpening);
}
}
else if (parenLevel !== 0) {
return fail('missing closing `)`', lastOpeningParen);
}
emitChunk(true);
return chunks;
});
//# sourceMappingURL=chunker.js.map
|
'use strict';
var isA = require("Espresso/oop").isA;
var oop = require("Espresso/oop").oop;
var init = require("Espresso/oop").init;
var trim = require("Espresso/trim").trim;
var isA = require("Espresso/oop").isA;
var oop = require("Espresso/oop").oop;
function RequestInterface(){
oop(this,"Espresso/Http/RequestInterface");
}
module.exports = RequestInterface;
|
module.exports = function(dataUri, maxDimension, callback){
var source = new Image();
source.addEventListener('load', function(){
var canvas = document.createElement('canvas'),
ratio = Math.max(source.width, source.height) / maxDimension;
canvas.width = source.width / ratio;
canvas.height = source.height / ratio;
var context = canvas.getContext('2d');
context.drawImage(
source,
0,
0,
source.width,
source.height,
0,
0,
canvas.width,
canvas.height
);
callback(null, canvas.toDataURL());
});
source.src = dataUri;
};
|
// @flow
import React from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import Middleware from './Middleware';
type Base = {
href?: string,
target?: string,
};
type Link = {
crossOrigin?: string,
href?: string,
hrefLang?: string,
integrity?: string,
media?: string,
preload?: boolean,
prefetch?: boolean,
rel?: string,
sizes?: string,
title?: string,
type?: string,
};
type Meta = { content?: string, httpEquiv?: string, charSet?: string, name?: string };
type Script = {
async?: boolean,
crossOrigin?: string,
defer?: boolean,
integrity?: string,
script?: string,
src?: string,
type?: string,
};
type Stylesheet = { href?: string, media?: string, rel?: string };
type Head = {
base?: Base,
meta?: Array<Meta>,
links?: Array<Link>,
scripts?: Array<Script>,
stylesheets?: Array<Stylesheet>,
title?: string,
};
type Result = {
body?: string,
containerId?: string,
head?: Head,
lang?: string,
scripts?: Array<Script>,
status?: number,
stylesheets?: Array<Stylesheet>,
};
export type Props = {
render: (context: *) => Promise<Result> | Result,
};
export function renderHead(head: Head, additionalStylesheets?: Array<Stylesheet> = []): string {
const metaTags = head.meta || [];
const links = head.links || [];
const scripts = head.scripts || [];
const stylesheets = [...(head.stylesheets || []), ...additionalStylesheets];
return renderToStaticMarkup(
<head>
{head.base && <base {...head.base} />}
{metaTags.map((tag, i) => <meta key={i} {...tag} />)}
<title>
{head.title}
</title>
{links.map((linkAttrs, i) => <link key={i} {...linkAttrs} />)}
{stylesheets.map((stylesheetAttrs, i) =>
<link key={`s-${i}`} {...stylesheetAttrs} rel={stylesheetAttrs.rel || 'stylesheet'} />,
)}
{scripts.map((scriptAttrs, i) =>
<script
key={`scr-${i}`}
{...scriptAttrs}
dangerouslySetInnerHTML={{ __html: scriptAttrs.script }}
/>,
)}
</head>,
);
}
export function renderFooter(scripts?: Array<Script> = []): string {
return renderToStaticMarkup(
<footer>
{scripts.map((scriptAttrs, i) =>
<script
key={`fscr-${i}`}
{...scriptAttrs}
dangerouslySetInnerHTML={{ __html: scriptAttrs.script }}
/>,
)}
</footer>,
).replace(/<(\/)?footer>/g, '');
}
export default function RenderApp({ render }: Props) {
return (
<Middleware
use={async ctx => {
const {
body = '',
containerId = 'app',
lang = 'en',
head = {},
scripts = [],
status,
stylesheets = [],
} = await render(ctx);
ctx.status = status || 200;
ctx.body = `
<html lang="${lang}">
${renderHead(head, stylesheets)}
<body>
<div id="${containerId}">${body}</div>
${renderFooter(scripts)}
</body>
</html>
`.trim();
}}
/>
);
}
|
import {
RESOURCE,
SERVER_ERRORS,
INITIAL_STATE_WITH_CACHED_LIST,
INITIAL_STATE_WITH_LIST_BEING_FETCHED,
INITIAL_STATE_WITH_CACHED_AND_SELECTED_LIST,
} from '../mocks'
import { generateListResourceActions } from './mocks'
const request = () => Promise.resolve([RESOURCE])
const errorRequest = () => Promise.reject(SERVER_ERRORS)
it('will dispatch two actions on success', async () => {
const actions = await generateListResourceActions({ request })
expect(actions.length).toBe(2)
})
it('will dispatch two actions on error', async () => {
const actions = await generateListResourceActions({ request: errorRequest })
expect(actions.length).toBe(2)
})
it('will dispatch one action if the list is cached but not selected', async () => {
const actions = await generateListResourceActions({
request: errorRequest,
initialState: INITIAL_STATE_WITH_CACHED_LIST,
})
expect(actions.length).toBe(1)
})
it('will dispatch two action if the list is cached but shouldIgnoreCache is passed', async () => {
const actions = await generateListResourceActions({
request: errorRequest,
shouldIgnoreCache: true,
initialState: INITIAL_STATE_WITH_CACHED_LIST,
})
expect(actions.length).toBe(2)
})
it('will dispatch no actions if the list is cached and selected', async () => {
const actions = await generateListResourceActions({
request: errorRequest,
initialState: INITIAL_STATE_WITH_CACHED_AND_SELECTED_LIST,
})
expect(actions.length).toBe(0)
})
it('will dispatch no actions if the list is being fetched', async () => {
const actions = await generateListResourceActions({
request: errorRequest,
initialState: INITIAL_STATE_WITH_LIST_BEING_FETCHED,
})
expect(actions.length).toBe(0)
})
it('will have a update selectedResourceList action', async () => {
const [inititalAction] = await generateListResourceActions({
request: errorRequest,
initialState: INITIAL_STATE_WITH_CACHED_LIST,
})
expect(inititalAction).toMatchSnapshot()
})
it('will have an initial action', async () => {
const [inititalAction] = await generateListResourceActions({ request })
expect(inititalAction).toMatchSnapshot()
})
it('will have a success action', async () => {
const [_, successAction] = await generateListResourceActions({ request })
expect(successAction).toMatchSnapshot()
})
it('will have a error action', async () => {
const [_, errorAction] = await generateListResourceActions({ request: errorRequest })
expect(errorAction).toMatchSnapshot()
})
|
import React, {Component} from 'react';
import MiniInfoBar from '../components/MiniInfoBar';
export default class About extends Component {
state = {
showKitten: false
}
handleToggleKitten() {
this.setState({showKitten: !this.state.showKitten});
}
render() {
const {showKitten} = this.state;
const kitten = require('./kitten.jpg');
return (
<div>
<div className="container">
<h1>About Us</h1>
<p>This project was orginally created by Erik Rasmussen
(<a href="https://twitter.com/erikras" target="_blank">@erikras</a>), but has since seen many contributions
from the open source community. Thank you to <a
href="https://github.com/erikras/react-redux-universal-hot-example/graphs/contributors"
target="_blank">all the contributors</a>.
</p>
<h3>Mini Bar <span style={{color: '#aaa'}}>(not that kind)</span></h3>
<p>Hey! You found the mini info bar! The following component is display-only. Note that it shows the same
time as the info bar.</p>
<MiniInfoBar/>
<h3>Images</h3>
<p>
Psst! Would you like to see a kitten?
<button className={'btn btn-' + (showKitten ? 'danger' : 'success')}
style={{marginLeft: 50}}
onClick={::this.handleToggleKitten}>
{showKitten ? 'No! Take it away!' : 'Yes! Please!'}</button>
</p>
{showKitten && <div><img src={kitten}/></div>}
</div>
</div>
);
}
}
|
/** @jsx jsx */
import { Editor } from 'slate'
import { jsx } from '../..'
export const input = (
<editor>
<block>
<mark key="a">
<anchor />o
</mark>
n
<mark key="b">
e<focus />
</mark>
</block>
</editor>
)
export const run = editor => {
return Array.from(Editor.activeMarks(editor, { union: true }))
}
export const output = [{ key: 'a' }, { key: 'b' }]
|
/*
* Popular Repositories
* Copyright (c) 2014 Alberto Congiu (@4lbertoC)
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
'use strict';
var React = require('react');
/**
* Like Array.map(), but on an object's own properties.
* Returns an array.
*
* @param {object} obj The object to call the function on.
* @param {function(*, string)} func The function to call on each
* of the object's properties. It takes as input parameters the
* value and the key of the current property.
* @returns {Array} The result.
*/
function mapObject(obj, func) {
var results = [];
if (obj) {
for(var key in obj) {
if (obj.hasOwnProperty(key)) {
results.push(func(obj[key], key));
}
}
}
return results;
}
/**
* A component that displays a GitHub repo's languages.
*
* @prop {GitHubRepoLanguages} gitHubRepoLanguages.
*/
var LanguageList = React.createClass({
propTypes: {
gitHubRepoLanguages: React.PropTypes.object.isRequired
},
render() {
var gitHubRepoLanguages = this.props.gitHubRepoLanguages;
/* jshint ignore:start */
return (
<div className="text-center language-list">
{mapObject(gitHubRepoLanguages, (percentage, languageName) => {
return (
<div className="language" key={languageName}>
<h3 className="language-name">{languageName}</h3>
<h5 className="language-percentage">{percentage}</h5>
</div>
);
})}
</div>
);
/* jshint ignore:end */
}
});
module.exports = LanguageList;
|
import assert from 'assert'
import {fixCase} from '../../src/lib/words/case'
import Locale from '../../src/locale/locale'
describe('Corrects accidental uPPERCASE\n', () => {
let testCase = {
'Hey, JEnnifer!': 'Hey, Jennifer!',
'CMSko': 'CMSko',
'FPs': 'FPs',
'ČSNka': 'ČSNka',
'BigONE': 'BigONE', // specific brand names
'two Panzer IVs': 'two Panzer IVs',
'How about ABC?': 'How about ABC?',
'cAPSLOCK': 'capslock',
'(cAPSLOCK)': '(capslock)',
'iPhone': 'iPhone',
'iT': 'it',
'Central Europe and Cyrillic tests: aĎIÉUБUГ': 'Central Europe and Cyrillic tests: aďiéuбuг',
}
Object.keys(testCase).forEach((key) => {
it('', () => {
assert.equal(fixCase(key, new Locale('en-us')), testCase[key])
})
})
})
|
/**
* Reparse the Grunt command line options flags.
*
* Using the arguments parsing logic from Grunt:
* https://github.com/gruntjs/grunt/blob/master/lib/grunt/cli.js
*/
module.exports = function(grunt){
// Get the current Grunt CLI instance.
var nopt = require('nopt'),
parsedOptions = parseOptions(nopt, grunt.cli.optlist);
grunt.log.debug('(nopt-grunt-fix) old flags: ', grunt.option.flags());
// Reassign the options.
resetOptions(grunt, parsedOptions);
grunt.log.debug('(nopt-grunt-fix) new flags: ', grunt.option.flags());
return grunt;
};
// Normalise the parameters and then parse them.
function parseOptions(nopt, optlist){
var params = getParams(optlist);
var parsedOptions = nopt(params.known, params.aliases, process.argv, 2);
initArrays(optlist, parsedOptions);
return parsedOptions;
}
// Reassign the options on the Grunt instance.
function resetOptions(grunt, parsedOptions){
for (var i in parsedOptions){
if (parsedOptions.hasOwnProperty(i) && i != 'argv'){
grunt.option(i, parsedOptions[i]);
}
}
}
// Parse `optlist` into a form that nopt can handle.
function getParams(optlist){
var aliases = {};
var known = {};
Object.keys(optlist).forEach(function(key) {
var short = optlist[key].short;
if (short) {
aliases[short] = '--' + key;
}
known[key] = optlist[key].type;
});
return {
known: known,
aliases: aliases
}
}
// Initialize any Array options that weren't initialized.
function initArrays(optlist, parsedOptions){
Object.keys(optlist).forEach(function(key) {
if (optlist[key].type === Array && !(key in parsedOptions)) {
parsedOptions[key] = [];
}
});
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.