text
stringlengths 2
6.14k
|
|---|
document.addEventListener('DOMContentLoaded', function() {
photoKeys = Object.keys(TRAVEL_PHOTOS);
function injectRandomPhotos() {
figures = document.getElementsByClassName('figure-placeholder');
[].forEach.call(figures, function(fig) {
var randomPhotoKey = photoKeys[Math.floor(Math.random() * photoKeys.length)];
var randomPhoto = TRAVEL_PHOTOS[randomPhotoKey];
var page = TRAVEL_PAGES[randomPhoto.pageKey];
fig.innerHTML = (
'<a href="' + page + '#' + randomPhoto.hash + '">' +
'<i style="background-image:url(\'/img/res/400/' + randomPhotoKey + '\')"></i>' +
'</a>');
});
}
shuffleButton = document.getElementById('shuffle-button');
shuffleButton.addEventListener('click', injectRandomPhotos);
injectRandomPhotos();
});
|
var WorldClocks = {};
(function(w) {
function empty() {};
function msg(key, args) {
if (typeof(chrome) != "undefined" && typeof(chrome.i18n) != "undefined") {
return chrome.i18n.getMessage(key, args);
}
return key;
}
function setPref(key, value) {
try {
if (window.localStorage) {
localStorage[key] = value;
}
} catch (e) {
}
}
function getPref(key, defaultValue) {
var value = defaultValue;
try {
if (window.localStorage) {
value = localStorage[key] || defaultValue;
}
} catch (e) {
}
return value;
}
function log() {
console.log.apply(console, arguments);
}
w.msg = msg;
w.pref = {get:getPref, set:setPref};
w.log = (typeof(console) != "undefined" && typeof(console.log) != "undefined") ? log : empty;
})(WorldClocks);
|
Cypress.Commands.add('fetchQuery', (query, variables) => {
cy.request({
url: '/graphql',
method: 'POST',
body: JSON.stringify({ query, variables }),
headers: {
'Content-Type': 'application/json'
}
});
});
|
// This is the wrapper for custom tests, called upon web components ready state
function runCustomTests() {
// Place any setup steps like variable declaration and initialization here
// This is the placeholder suite to place custom tests in
// Use testCase(options) for a more convenient setup of the test cases
suite('Custom Automation Tests for px-validation', function() {
var px_validation = document.getElementById('px_validation_1');
suiteSetup(function(done){
flush(function(){
done();
});
});
test('Check there is a single px-validator child defined on test fixture', function(){
assert.lengthOf(Polymer.dom(px_validation).children, 1);
});
test('Integer isNumber validation returns true', function() {
assert.isTrue(px_validation.validate(2).passedValidation);
});
test('String representation of number via isNumber validation returns true', function() {
assert.isTrue(px_validation.validate('2').passedValidation);
});
});
}
|
import React from 'react';
class MyPropertiesExample extends React.Component {
render() {
return (
<div>
<h1>Properties</h1>
My favourite dish is {this.props.dish}.
</div>
);
}
}
MyPropertiesExample.defaultProps = {
dish: 'shrimp with pasta'
};
MyPropertiesExample.propTypes = {
dish: React.PropTypes.string.isRequired
};
class MyVodooComponent extends React.Component {
render() {
return (
<MyPropertiesExample dish="chicken"/>
);
}
}
export default MyPropertiesExample;
|
export App from './App'
export Home from './Home'
export List from './List'
export Login from './Login'
export Chats from './Chats'
|
//Form JS File
function frmHome_stopWatch_onClick_seq0() {
alert("You clicked on stop watch");
};
function frmHome_button214149106640_onClick_seq0(eventobject) {
var a = frmHome.stopWatch.stopWatch();
alert(a);
};
function frmHome_button214149106641_onClick_seq0(eventobject) {
frmHome.stopWatch.startWatch();
};
function addWidgetsfrmHome() {
var stopWatch = new CustomStopWatch.StopWatch({
"id": "stopWatch",
"image": null,
"isVisible": true,
"hExpand": true,
"vExpand": false,
"textSize": 35,
"bgTransparancy": 0,
"onClick": frmHome_stopWatch_onClick_seq0
}, {
"widgetAlign": 5,
"containerWeight": 6,
"margin": [5, 5, 5, 5],
"marginInPixel": false,
"padding": [15, 15, 15, 15],
"paddingInPixel": false
}, {
"widgetName": "StopWatch"
});
var button214149106640 = new kony.ui.Button({
"id": "button214149106640",
"isVisible": true,
"text": "Stop Watch",
"skin": "sknBtnKonyThemeNormal",
"focusSkin": "sknBtnKonyThemeFocus",
"onClick": frmHome_button214149106640_onClick_seq0
}, {
"widgetAlignment": constants.WIDGET_ALIGN_CENTER,
"vExpand": false,
"hExpand": true,
"margin": [3, 2, 3, 2],
"padding": [2, 3, 2, 3],
"contentAlignment": constants.CONTENT_ALIGN_CENTER,
"displayText": true,
"marginInPixel": false,
"paddingInPixel": false,
"containerWeight": 6
}, {
"glowEffect": false,
"showProgressIndicator": true
});
var button214149106641 = new kony.ui.Button({
"id": "button214149106641",
"isVisible": true,
"text": "Start Watch",
"skin": "sknBtnKonyThemeNormal",
"focusSkin": "sknBtnKonyThemeFocus",
"onClick": frmHome_button214149106641_onClick_seq0
}, {
"widgetAlignment": constants.WIDGET_ALIGN_CENTER,
"vExpand": false,
"hExpand": true,
"margin": [3, 2, 3, 2],
"padding": [2, 3, 2, 3],
"contentAlignment": constants.CONTENT_ALIGN_CENTER,
"displayText": true,
"marginInPixel": false,
"paddingInPixel": false,
"containerWeight": 6
}, {
"glowEffect": false,
"showProgressIndicator": true
});
frmHome.add(
stopWatch, button214149106640, button214149106641);
};
function frmHomeGlobals() {
var MenuId = [];
frmHome = new kony.ui.Form2({
"id": "frmHome",
"needAppMenu": true,
"title": "StopWatch",
"enabledForIdleTimeout": false,
"skin": "frm",
"addWidgets": addWidgetsfrmHome
}, {
"padding": [0, 0, 0, 0],
"displayOrientation": constants.FORM_DISPLAY_ORIENTATION_PORTRAIT,
"paddingInPixel": false,
"layoutType": constants.CONTAINER_LAYOUT_BOX
}, {
"retainScrollPosition": false,
"needsIndicatorDuringPostShow": true,
"formTransparencyDuringPostShow": "100",
"inputAccessoryViewType": constants.FORM_INPUTACCESSORYVIEW_DEFAULT,
"bounces": true,
"configureExtendTop": false,
"configureExtendBottom": false,
"configureStatusBarStyle": false,
"titleBar": true,
"titleBarSkin": "titleBar",
"titleBarConfig": {
"renderTitleText": true,
"titleBarRightSideView": "title",
"titleBarLeftSideView": "none",
"closureRightSideView": navigateToSettings,
"labelRightSideView": "Settings"
},
"footerOverlap": false,
"headerOverlap": false,
"inTransitionConfig": {
"transitionDirection": "none",
"transitionEffect": "none"
},
"outTransitionConfig": {
"transitionDirection": "none",
"transitionEffect": "none"
},
"deprecated": {
"titleBarBackGroundImage": "blue_pixel.png"
}
});
};
|
// Generated by CoffeeScript 1.4.0
/* 2D Vector
*/
var Vector;
Vector = (function() {
/* Adds two vectors and returns the product.
*/
Vector.add = function(v1, v2) {
return new Vector(v1.x + v2.x, v1.y + v2.y);
};
/* Subtracts v2 from v1 and returns the product.
*/
Vector.sub = function(v1, v2) {
return new Vector(v1.x - v2.x, v1.y - v2.y);
};
/* Projects one vector (v1) onto another (v2)
*/
Vector.project = function(v1, v2) {
return v1.clone().scale((v1.dot(v2)) / v1.magSq());
};
/* Creates a new Vector instance.
*/
function Vector(x, y) {
this.x = x != null ? x : 0.0;
this.y = y != null ? y : 0.0;
}
/* Sets the components of this vector.
*/
Vector.prototype.set = function(x, y) {
this.x = x;
this.y = y;
return this;
};
/* Add a vector to this one.
*/
Vector.prototype.add = function(v) {
this.x += v.x;
this.y += v.y;
return this;
};
/* Subtracts a vector from this one.
*/
Vector.prototype.sub = function(v) {
this.x -= v.x;
this.y -= v.y;
return this;
};
/* Scales this vector by a value.
*/
Vector.prototype.scale = function(f) {
this.x *= f;
this.y *= f;
return this;
};
/* Computes the dot product between vectors.
*/
Vector.prototype.dot = function(v) {
return this.x * v.x + this.y * v.y;
};
/* Computes the cross product between vectors.
*/
Vector.prototype.cross = function(v) {
return (this.x * v.y) - (this.y * v.x);
};
/* Computes the magnitude (length).
*/
Vector.prototype.mag = function() {
return Math.sqrt(this.x * this.x + this.y * this.y);
};
/* Computes the squared magnitude (length).
*/
Vector.prototype.magSq = function() {
return this.x * this.x + this.y * this.y;
};
/* Computes the distance to another vector.
*/
Vector.prototype.dist = function(v) {
var dx, dy;
dx = v.x - this.x;
dy = v.y - this.y;
return Math.sqrt(dx * dx + dy * dy);
};
/* Computes the squared distance to another vector.
*/
Vector.prototype.distSq = function(v) {
var dx, dy;
dx = v.x - this.x;
dy = v.y - this.y;
return dx * dx + dy * dy;
};
/* Normalises the vector, making it a unit vector (of length 1).
*/
Vector.prototype.norm = function() {
var m;
m = Math.sqrt(this.x * this.x + this.y * this.y);
this.x /= m;
this.y /= m;
return this;
};
/* Limits the vector length to a given amount.
*/
Vector.prototype.limit = function(l) {
var m, mSq;
mSq = this.x * this.x + this.y * this.y;
if (mSq > l * l) {
m = Math.sqrt(mSq);
this.x /= m;
this.y /= m;
this.x *= l;
this.y *= l;
return this;
}
};
/* Copies components from another vector.
*/
Vector.prototype.copy = function(v) {
this.x = v.x;
this.y = v.y;
return this;
};
/* Clones this vector to a new itentical one.
*/
Vector.prototype.clone = function() {
return new Vector(this.x, this.y);
};
/* Resets the vector to zero.
*/
Vector.prototype.clear = function() {
this.x = 0.0;
this.y = 0.0;
return this;
};
return Vector;
})();
|
'use strict'
const t = require('tcomb')
const fetch = require('node-fetch')
const { requestProperties, validateResponse, parseJSON } = require('../utils')
const PATH = '/designs'
module.exports = function getDesign(id) {
t.String(id)
return new Promise((resolve, reject) => {
const { href, headers } = requestProperties(
this.token, this.version, [PATH, id].join('/')
)
fetch(href, { headers })
.then(validateResponse)
.then(parseJSON)
.then(resolve)
.catch(reject)
})
}
|
'use strict';
const appErrorsFactory = require('../../app-errors/app-errors-factory');
/**
*
*/
function setup(req, res, next) {
if (!req.currentUser) {
next(appErrorsFactory.createAppError({ statusCode: 401 }));
}
else {
next();
}
}
module.exports = setup;
|
version https://git-lfs.github.com/spec/v1
oid sha256:2c648d581addc08fbd0fe28ad0d26ba08942ebfe6be59756e11ff9abcd9d3bbd
size 23184
|
describe('minTime', function() {
beforeEach(function() {
affix('#cal');
});
var numToStringConverter = function(timeIn, mins) {
var time = (timeIn % 12) || 12;
var amPm = 'am';
if ((timeIn % 24) > 11) {
amPm = 'pm';
}
return time + (mins != null ? ':' + mins : '') + amPm;
};
describe('when using the default settings', function() {
describe('in agendaWeek', function() {
it('should start at 12am', function() {
var options = {
defaultView: 'agendaWeek'
};
$('#cal').njCalendar(options);
var firstSlotText = $('.fc-slats tr:eq(0) .fc-time').text();
expect(firstSlotText).toEqual('12am');
});
});
describe('in agendaDay', function() {
it('should start at 12am', function() {
var options = {
defaultView: 'agendaDay'
};
$('#cal').njCalendar(options);
var firstSlotText = $('.fc-slats tr:eq(0) .fc-time').text();
expect(firstSlotText).toEqual('12am');
});
});
});
describe('when using a whole number', function() {
var hourNumbers = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ];
describe('in agendaWeek', function() {
beforeEach(function() {
affix('#cal2');
});
hourNumbers.forEach(function(hourNumber) {
it('should start at ' + hourNumber, function() {
var options = {
defaultView: 'agendaWeek',
minTime: { hours: hourNumber }
};
$('#cal2').njCalendar(options);
var firstSlotText = $('.fc-slats tr:eq(0) .fc-time').text();
var expected = numToStringConverter(hourNumber);
expect(firstSlotText).toEqual(expected);
});
});
});
describe('in agendaDay', function() {
beforeEach(function() {
affix('#cal2');
});
hourNumbers.forEach(function(hourNumber) {
it('should start at ' + hourNumber, function() {
var options = {
defaultView: 'agendaDay',
minTime: hourNumber + ':00' // in addition, test string duration input
};
$('#cal2').njCalendar(options);
var firstSlotText = $('.fc-slats tr:eq(0) .fc-time').text();
var expected = numToStringConverter(hourNumber);
expect(firstSlotText).toEqual(expected);
});
});
});
});
describe('when using default slotInterval and \'uneven\' minTime', function() {
var hourNumbers = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ];
describe('in agendaWeek', function() {
beforeEach(function() {
affix('#cal2');
});
hourNumbers.forEach(function(hourNumber) {
it('should start at ' + hourNumber + ':20', function() {
var options = {
defaultView: 'agendaWeek',
minTime: { hours: hourNumber, minutes: 20 }
};
$('#cal2').njCalendar(options);
var slatRows = $('.fc-slats tr');
expect(slatRows.eq(0)).toHaveClass('fc-minor');
expect(slatRows.eq(1)).toHaveClass('fc-minor');
expect(slatRows.eq(2)).toHaveClass('fc-minor');
// TODO: fix bad behavior in src where no slots have text
});
});
});
describe('in agendaDay', function() {
beforeEach(function() {
affix('#cal2');
});
hourNumbers.forEach(function(hourNumber) {
it('should start at ' + hourNumber + ':20', function() {
var options = {
defaultView: 'agendaDay',
minTime: { hours: hourNumber, minutes: 20 }
};
$('#cal2').njCalendar(options);
var slatRows = $('.fc-slats tr');
expect(slatRows.eq(0)).toHaveClass('fc-minor');
expect(slatRows.eq(1)).toHaveClass('fc-minor');
expect(slatRows.eq(2)).toHaveClass('fc-minor');
// TODO: fix bad behavior in src where no slots have text
});
});
});
});
});
|
'use strict';
/*
* Regex
*/
var regex = {
facebookPattern: /(?:https?:\/\/)?(?:[\w\-]+\.)?facebook\.com\/(?:(?:\w)*#!\/)?(?:pages\/)?(?:[\w\-]*\/)*([\w\-\.]*)/, // jshint ignore:line
facebookPluginPattern: /.*%2F(\w+?)&/
};
module.exports = {
/**
* Returns the page id for a given URL
* e.g. : https://www.facebook.com/my_page_id => my_page_id
* http://www.facebook.com/pages/foo/Bar/123456 => 123456
*
* @param String URL FacebookURL
* @return Page ID
*/
getPageId: function (url) {
if (typeof url !== 'string') {
return null;
}
var match = url.replace(/\/$/, '').match(regex.facebookPattern);
if (match) {
var short_url = match[0],
id = match[1];
if (/plugins/.test(short_url)) {
var likeMatch = regex.facebookPluginPattern.exec(match.input);
if (likeMatch) { return likeMatch[1]; }
} else {
return id;
}
}
return null;
}
};
|
"use strict";
exports.hmrReducer = function (appReducer) { return function (state, _a) {
var type = _a.type, payload = _a.payload;
switch (type) {
case 'HMR_SET_STATE': return payload;
default: return appReducer(state, { type: type, payload: payload });
}
}; };
//# sourceMappingURL=hmr-reducer.js.map
|
import React, { PropTypes } from 'react';
import EventImage from '../components/EventImage';
const Event = ({ eventUrl, images, ingress, startDate, title }) => (
<div>
<div className="col-sm-8 col-md-4">
<div className="hero-title">
<a href={eventUrl}>
<p>{ title }</p>
</a>
</div>
<div className="hero-ingress hidden-xs">
<p>{ ingress }</p>
</div>
</div>
<EventImage
date={startDate}
images={images}
eventUrl={eventUrl}
/>
</div>
);
Event.propTypes = {
eventUrl: PropTypes.string.isRequired,
images: EventImage.propTypes.images,
ingress: PropTypes.string.isRequired,
startDate: PropTypes.string.isRequired,
title: PropTypes.string.isRequired,
};
export default Event;
|
'use strict';
function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }
/**
*
* saluki api 查看
*
* Created by joe on 16/12/26.
*/
var services = require('../grpc/index').services();
var consul = require('../grpc/consul');
module.exports = function () {
var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
return function () {
var _ref = _asyncToGenerator(function* (ctx, next) {
var url = ctx.url;
ctx.services = services;
if (url.endsWith('/saluki')) {
ctx.body = JSON.stringify(consul.getALL());
return;
}
yield next();
});
function saluki(_x2, _x3) {
return _ref.apply(this, arguments);
}
return saluki;
}();
};
|
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} t
* @return {string}
*/
const tree2str = (t) => {
let ret = '';
if (t) {
ret += t.val;
if (t.left || t.right) {
ret += '(';
ret += tree2str(t.left);
ret += ')';
}
if (t.right) {
ret += `(${tree2str(t.right)})`;
}
}
return ret;
};
|
export const IIcon = {
name: 'i-icon',
};
export default IIcon;
|
import Objects from './'
import Character from './Character'
import Actions from '../actions'
import Attacks from '../actions/Attacks'
import Dash from '../actions/Dash'
const addMoveAnimations = function () {
Object.keys(this.directions).map(
(direction) => this.atlasAnimations.add({
action: Actions.move,
direction,
speed: 8
})
)
}
const addAtkAnimations = function () {
Object.keys(this.directions).map(
(direction) => this.atlasAnimations.add({
action: Actions.atk,
direction,
speed: 13
})
)
}
export default class extends Character {
constructor ({
game, x, y, name
}) {
super({
game,
x,
y,
name,
type: Objects.npc,
firstSprite: `${name}-move-down-1`
})
this.setActions([
new Attacks({
character: this,
attacks: [{id: 0, type: 'normal', time: 24, speed: 13, cooldown: 15}]
}),
new Dash({
character: this,
dash: {time: 15, speed: 300, cooldown: 15}
})
])
this.speed = 140
addMoveAnimations.call(this)
addAtkAnimations.call(this)
}
update () {
super.update()
}
}
|
var passport = require('passport');
var Auth0Strategy = require('passport-auth0');
var credentials = require('../config/credentials.js');
var strategy = new Auth0Strategy({
domain: credentials.domain,
clientID: credentials.clientID,
clientSecret: credentials.clientSecret,
callbackURL: '/callback'
}, function(accessToken, refreshToken, profile, done) {
//Some tracing info
console.log('profile is', profile);
return done(null, profile);
});
passport.use(strategy);
// This is not a best practice, but we want to keep things simple for now
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(function(user, done) {
done(null, user);
});
module.exports = strategy;
|
module.exports = require('../crud/list')({
view: 'users/manage',
model: require('../../models/user'),
sort: {
name: 1
}
});
|
module.exports = NotImplementedError => {
const throwNotImplemented = function () {
throw new NotImplementedError()
};
/**
* Controller control interface
*
* @interface
* @memberof module:client.synth
*/
var Controller = throwNotImplemented;
/**
* Asks the controller to start capturing control events
*
* @memberof module:client.synth.Controller
*
* @return {Promise}
*/
Controller.prototype.attach = throwNotImplemented;
/**
* Asks the controller to stop capturing control events
*
* @memberof module:client.synth.Controller
*
* @return {Promise}
*/
Controller.prototype.detach = throwNotImplemented;
return Controller;
};
|
import Ember from 'ember';
import { stack } from 'd3-shape';
import addOptionsToStack from '../utils/add-options-to-stack';
export function d3Stack( [ data, args ], hash={}) {
return addOptionsToStack(stack(data, args), hash);
}
export default Ember.Helper.helper(d3Stack);
|
var PROPS = injectProps;
var hookOnReload = injectOnReload;
const io = require('socket.io-client');
const socket = io(`http://127.0.0.1:${PROPS.port}`);
const { id: ext_id } = chrome.runtime;
const onReload = (query = {}, cb) => {
query = Object.assign({
url: [`chrome-extension://${ext_id}/*`]
}, query);
chrome.tabs.query(query, (tabs) => {
cb(tabs);
hookOnReload();
chrome.runtime.reload();
});
};
const onReopen = (tabs = [], cb) => {
tabs.forEach((tab) => {
var { windowId, index, url, active, pinned, openerTabId } = tab;
var new_tab = { windowId, index, url, active, pinned, openerTabId };
chrome.tabs.create(new_tab);
});
cb(tabs);
}
socket.on('reload', onReload);
socket.on('reopen', onReopen);
|
define(['views/Index','views/Cart','views/CategoryEdit','views/Categories','views/Product','views/Products','views/ProductEdit','views/ProductDetail','views/admin/Index','models/Product','models/Category','models/CartCollection','models/ProductCollection','models/CategoryCollection'], function(IndexView,CartView,CategoryEditView,CategoriesView,ProductView,ProductsView,ProductEditView,ProductDetailView,AdminIndexView,Product,Category,CartCollection,ProductCollection,CategoryCollection){
var BizRouter = Backbone.Router.extend({
currentView : null,
routes: {
'': 'index',
'index': 'index',
'cart': 'myCart',
'products(/:id)': 'products',
'product/add(/:cid)': 'productAdd',
'product/edit/:id': 'productEdit',
'product/view/:id': 'productView',
'categories(/:id)': 'categories',
'category/add(/:pid)': 'categoryAdd',
'category/edit/:id': 'categoryEdit',
'admin/index': 'adminIndex',
},
changeView: function(view){
if(null != this.currentView){
this.currentView.undelegateEvents();
}
this.currentView = view;
this.currentView.render();
},
index: function(){
this.changeView(new IndexView());
},
myCart: function(){
var cartCollection = new CartCollection();
cartCollection.url = '/cart';
this.changeView(new CartView({collection:cartCollection}));
cartCollection.fetch();
},
/** product related */
products: function(id){
var cid = id || '';
var productCollection = new ProductCollection();
productCollection.url = '/products?cid=' + cid;;
this.changeView(new ProductsView({collection: productCollection}));
productCollection.fetch();
},
productAdd: function(categoryId){
var cid = categoryId || '';
var productModel = new Product({
main_cat_id: cid,
});
this.changeView(new ProductEditView({model: productModel}));
},
productEdit: function(id){
var product = new Product();
product.url = '/products/' + id;
this.changeView(new ProductEditView({model: product}));
product.fetch();
},
productView: function(id){
var product = new Product();
product.url = '/products/' + id;
this.changeView(new ProductDetailView({model: product}));
product.fetch();
},
/** category related */
categories: function(id){
var pid = id || '';
var categoryCollection = new CategoryCollection();
categoryCollection.url = '/categories?pid=' + pid;
this.changeView(new CategoriesView({collection: categoryCollection}));
categoryCollection.fetch();
},
categoryAdd: function(parentId){
var pid = parentId || '';
var categoryModel = new Category({
parent: pid
});
this.changeView(new CategoryEditView({model: categoryModel}));
},
categoryEdit: function(id){
var category = new Category();
category.url = '/categories/' + id;
this.changeView(new CategoryEditView({model: category}));
category.fetch();
},
adminIndex: function(){
this.changeView(new AdminIndexView());
}
});
return new BizRouter();
});
|
import authorAPI from '../api/mock/mockAuthorAPI';
import * as types from './actionTypes';
import { beginAjaxCall } from './ajaxStatusActions';
const loadAuthorSuccess = (courses) => {
return {type : types.LOAD_AUTHOR_SUCCESS, courses };
};
const loadAuthors = () => {
return (dispatch) => {
dispatch(beginAjaxCall());
return authorAPI.getAllAuthors().then(authors => {
dispatch(loadAuthorSuccess(authors));
}).catch(error => {
throw(error);
});
};
};
export {
loadAuthors,
loadAuthorSuccess
};
|
function extensibleObject() {
let obj = {
extend: function(template){
for(let parentProp of Object.keys(template)){
if(typeof(template[parentProp]) == 'function'){
Object.getPrototypeOf(obj)[parentProp] = template[parentProp];
} else {
obj[parentProp] = template[parentProp];
}
}
}
};
return obj;
}
|
'use strict';
const migrate = require('../scripts/migrate-sql');
exports.up = db => migrate.migrate(db, '20180515155000-app-features.sql');
|
const path = require('path');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const resolve = (dir) => {
return path.join(__dirname, '..', dir)
};
const isProduction = process.env.NODE_ENV === 'production';
const config = {
output: {
path: path.join(__dirname, '..', 'dist', 'assets'),
filename: '[name].[hash].js',
publicPath: '/assets/',
},
resolve: {
extensions: ['.js', '.vue', '.json'],
alias: {
'~': resolve('src'),
'vue$': 'vue/dist/vue.runtime.esm.js',
'vuex$': 'vuex/dist/vuex.esm.js',
},
},
module: {
rules: [
{
test: /\.js$/,
include: [
resolve('src'),
resolve('node_modules/@material'),
],
use: ['babel-loader'],
},
{
test: /\.vue$/,
loader: 'vue-loader',
options: {
extractCSS: isProduction,
postcss: [
require('autoprefixer')({
browsers: ['IE 9', 'IE 10', 'IE 11', 'last 2 versions'],
}),
],
},
},
],
},
plugins: [
new CopyWebpackPlugin([
{
from: resolve('src/static'),
to: resolve('dist'),
},
]),
],
};
module.exports = config;
|
import { expect } from 'chai';
import Urlsparser from '../src/app.js';
describe('wrong', () => {
it('...', () => {
const caps = () => {new Urlsparser('...')};
expect(caps).to.throw();
});
it('+++abs+', () => {
const caps = () => {new Urlsparser('+++abs+')};
expect(caps).to.throw();
});
it('0:5:92', () => {
const caps = () => {new Urlsparser('0:5:92')};
expect(caps).to.throw();
});
});
|
var keypress = require("keypress");
// var Spark = require("spark-io");
var Spark = require("../");
var five = require("johnny-five");
var Sumobot = require("sumobot")(five);
keypress(process.stdin);
var board = new five.Board({
io: new Spark({
token: process.env.SPARK_TOKEN,
deviceId: process.env.SPARK_DEVICE_2
})
});
board.on("ready", function() {
console.log("Welcome to Sumobot Jr: Light Bot!");
var bot = new Sumobot({
left: "D0",
right: "D1",
speed: 0.50
});
var light = new five.Sensor("A0");
var isQuitting = false;
light.on("change", function() {
if (isQuitting || this.value === null) {
return;
}
if (this.value < 512) {
bot.fwd();
} else {
bot.rev();
}
});
// Ensure the bot is stopped
bot.stop();
});
|
require([
'app/LoginRegisterCloudRequestPane',
'dojo/dom-construct',
'dojo/query'
], function(
WidgetUnderTest,
domConstruct,
query
) {
describe('app/LoginRegisterCloudRequestPane', function() {
var widget;
var destroy = function(widget) {
widget.destroyRecursive();
widget = null;
};
beforeEach(function() {
widget = new WidgetUnderTest(null, domConstruct.create('div', null, document.body));
query(
'input[type="text"], input[type="password"], input[type="email"]',
widget.domNode
).forEach(function(node) {
node.value = 'anything';
});
});
afterEach(function() {
if (widget) {
destroy(widget);
}
});
describe('Sanity', function() {
it('should create a LoginRegisterCloudRequestPane', function() {
expect(widget).toEqual(jasmine.any(WidgetUnderTest));
});
});
describe('Password Restrictions', function() {
it('should be 8 characters in length', function() {
expect(widget.validate('aB1234$&').result).toEqual(true);
expect(widget.validate('aB1&').result).toEqual(false);
});
it('should have one uppercase letter', function() {
expect(widget.validate('aB1234$&').result).toEqual(true);
expect(widget.validate('ab1234$&').result).toEqual(false);
});
it('should have one lowercase letter', function() {
expect(widget.validate('aB1234$&').result).toEqual(true);
expect(widget.validate('AB1234$&').result).toEqual(false);
});
it('should have one special character', function() {
expect(widget.validate('aB1234$&').result).toEqual(true);
expect(widget.validate('aB123456').result).toEqual(false);
});
it('should have one number', function() {
expect(widget.validate('aB1234$&').result).toEqual(true);
expect(widget.validate('aB!@#$%^').result).toEqual(false);
});
});
});
});
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var makeCommandAbsolute = exports.makeCommandAbsolute = function makeCommandAbsolute(p, c) {
switch (c.c) {
case 'm':
return { c: 'M', x: p.x + c.dx, y: p.y + c.dy };
case 'z':
return { c: 'Z' };
case 'l':
return { c: 'L', x: p.x + c.dx, y: p.y + c.dy };
case 'h':
return { c: 'L', x: p.x + c.dx, y: p.y };
case 'v':
return { c: 'L', y: p.y + c.dy, x: p.x };
case 'H':
return { c: 'L', x: c.x, y: p.y };
case 'V':
return { c: 'L', y: c.y, x: p.x };
case 'c':
return { c: 'C', x1: p.x + c.dx1, y1: p.y + c.dy1, x2: p.x + c.dx2, y2: p.y + c.dy2, x: p.x + c.dx, y: p.y + c.dy };
case 's':
return { c: 'S', x2: p.x + c.dx2, y2: p.y + c.dy2, x: p.x + c.dx, y: p.y + c.dy };
case 'q':
return { c: 'Q', x1: p.x + c.dx1, y1: p.y + c.dy1, x: p.x + c.dx, y: p.y + c.dy };
case 't':
return { c: 'T', x: p.x + c.dx, y: p.y + c.dy };
case 'a':
return { c: 'A', rx: c.rx, ry: c.ry, xAxisRotation: c.xAxisRotation, largeArcFlag: c.largeArcFlag, sweepFlag: c.sweepFlag, x: p.x + c.dx, y: p.y + c.dy };
default:
return c;
}
};
var applyCommand = exports.applyCommand = function applyCommand(position, begin, c) {
var dif = { dx: 0, dy: 0 };
if (c.c === 'm') dif = c;else if (c.c === 'l') dif = c;else if (c.c === 'c') dif = c;else if (c.c === 's') dif = c;else if (c.c === 'q') dif = c;else if (c.c === 't') dif = c;else if (c.c === 'a') dif = c;else if (c.c === 'h') dif = { dx: c.dx, dy: 0 };else if (c.c === 'v') dif = { dx: 0, dy: c.dy };else if (c.c === 'z') dif = { dx: begin.x - position.x, dy: begin.y - position.y };else if (c.c === 'V') return { x: position.x, y: c.y };else if (c.c === 'H') return { x: c.x, y: position.y };else if (c.c === 'Z') return begin;else {
return c;
}
return { x: position.x + dif.dx, y: position.y + dif.dy };
};
var normalizeData = exports.normalizeData = function normalizeData(d) {
var begin = { x: 0, y: 0 };
var position = { x: 0, y: 0 };
var result = [];
for (var i = 0; i < d.length; i++) {
var command = d[i];
var absoluteCommand = makeCommandAbsolute(position, command);
var newPosition = applyCommand(position, begin, absoluteCommand);
// Filter line commands which doesn't change position
var isLineCommand = absoluteCommand.c === 'L' || absoluteCommand.c === 'Z';
if (!isLineCommand || !pointEquals(newPosition, position)) {
result.push(absoluteCommand);
position = newPosition;
}
if (absoluteCommand.c === 'M') {
begin = absoluteCommand;
} else if (absoluteCommand.c === 'm') {
begin = applyCommand(position, begin, absoluteCommand);
}
}
return result;
};
var getSubPaths = exports.getSubPaths = function getSubPaths(d) {
if (d.length === 0) {
return [];
} else if (d[0].c !== 'M' && d[0].c !== 'm') {
throw new Error('Path must start with an "M" or "m" command, not "' + d[0].c + '" ');
}
var result = [];
var nextSubPath = [];
var lastM = { c: 'M', x: 0, y: 0 };
d.forEach(function (command) {
if (command.c === 'M') {
if (nextSubPath.length > 0) {
result.push(nextSubPath);
}
nextSubPath = [command];
lastM = command;
} else if (command.c === 'Z') {
nextSubPath.push(command);
result.push(nextSubPath);
nextSubPath = [];
} else {
if (nextSubPath.length === 0) {
nextSubPath.push(lastM);
}
nextSubPath.push(command);
}
});
if (nextSubPath.length > 0) {
result.push(nextSubPath);
}
return result;
};
var isSubPathClosed = exports.isSubPathClosed = function isSubPathClosed(begin, d) {
if (d.length < 2) {
return true;
}
var lastCommand = d[d.length - 1];
if (lastCommand.c === 'Z') {
return true;
}
return lastCommand.x === begin.x && lastCommand.y === begin.y;
};
var pointEquals = exports.pointEquals = function pointEquals(p1, p2) {
return p1.x === p2.x && p1.y === p2.y;
};
|
"use strict"
/**
* `format` constructor.
*
* @api public
*/
const checkStatusCode = require('./helpers');
module.exports = {
create : (statusCode, error, message, data) => {
if(!statusCode) throw new Error('Status code is required')
if( isNaN( Number( statusCode))) throw new Error('Status code not a number')
this.statusCode = statusCode
this.error = error || null
this.data = data || null
this.message = checkStatusCode(this.statusCode, message)
return this
},
success: (message, data) => {
this.statusCode = 200
this.error = false
this.data = data || null
this.message = message || 'OK'
return this
},
badRequest: (message, data) => {
this.statusCode = 400
this.error = true
this.data = data || null
this.message = message || 'Bad Request'
return this
},
unAuthorized: (message, data) => {
this.statusCode = 401
this.error = true
this.data = data || null
this.message = message || 'Unauthorized'
return this
},
forbidden: (message, data) => {
this.statusCode = 403
this.error = true
this.data = data || null
this.message = message || 'Forbidden'
return this
},
notFound: (message, data) => {
this.statusCode = 404
this.error = true
this.data = data || null
this.message = message || 'Not Found'
return this
},
notAllowed: (message, data) => {
this.statusCode = 405
this.error = true
this.data = data || null
this.message = message || 'Method Not Allowed'
return this
},
requestTimeout: (message, data) => {
this.statusCode = 408
this.error = true
this.data = data || null
this.message = message || 'Request Timeout'
return this
},
internalError: (message, data) => {
this.statusCode = 500
this.error = true
this.data = data || null
this.message = message || 'Internal Server Error'
return this
},
badGateway: (message, data) => {
this.statusCode = 502
this.error = true
this.data = data || null
this.message = message || 'Bad Gateway'
return this
},
unavailable: (message, data) => {
this.statusCode = 503
this.error = true
this.data = data || null
this.message = message || 'Service Unavailable'
return this
},
gatewayTimeout: (message, data) => {
this.statusCode = 504
this.error = true
this.data = data || null
this.message = message || 'Gateway Timeout'
return this
}
}
|
'use strict';
var async = require('async');
var _ = require('lodash');
var yamlReader = require('./yaml-reader/yaml-reader');
var fliprValidation = require('flipr-validation');
module.exports = validateConfig;
function validateConfig(options, cb) {
var validateOptions = {
rules: options.rules,
};
async.auto({
config: _.partial(yamlReader, options),
validate: ['config', function(callback, results){
validateOptions.config = results.config;
callback(null, fliprValidation(validateOptions));
}]
}, function(err, results){
if(err)
return void cb(err);
return void cb(null, results.validate);
});
}
|
const { Device, UdpServer } = require('tplink-smarthome-simulator');
function startSimulator() {
const port = null;
const emeter = {
realtime: {
current: 1.1256,
voltage: 122.049119,
power: 3.14,
total: 51.493,
},
};
const devices = [];
devices.push(
new Device({
port,
model: 'hs100',
data: { alias: 'Mock HS100', mac: 'aa:aa:aa:8f:58:18', deviceId: 'A100' },
})
);
devices.push(
new Device({
port,
model: 'hs105',
data: { alias: 'Mock HS105', mac: 'aa:aa:aa:d8:bf:d4', deviceId: 'A105' },
})
);
devices.push(
new Device({
port,
model: 'hs110',
data: {
alias: 'Mock HS110',
mac: 'aa:aa:aa:0d:91:8c',
deviceId: 'A110',
emeter,
},
})
);
devices.push(
new Device({
port,
model: 'hs110v2',
data: {
alias: 'Mock HS110v2',
mac: 'aa:aa:aa:B7:F3:50',
deviceId: 'A110F2',
emeter,
},
})
);
devices.push(
new Device({
port,
model: 'hs200',
data: { alias: 'Mock HS200', mac: 'aa:aa:aa:46:b4:24', deviceId: 'A200' },
})
);
devices.push(
new Device({
port,
model: 'hs220',
data: { alias: 'Mock HS220', mac: 'aa:aa:aa:46:b5:34', deviceId: 'A220' },
})
);
devices.push(
new Device({
port,
model: 'hs300',
data: {
alias: 'Mock HS300',
mac: 'aa:aa:aa:EE:0C:9D',
deviceId: 'A300',
emeter,
},
})
);
devices.push(
new Device({
port,
model: 'lb100',
data: {
alias: 'Mock LB100',
mac: 'aa:aa:aa:49:ca:42',
deviceId: 'BB100',
},
})
);
devices.push(
new Device({
port,
model: 'lb120',
data: {
alias: 'Mock LB120',
mac: 'aa:aa:aa:90:9b:da',
deviceId: 'BB120',
},
})
);
devices.push(
new Device({
port,
model: 'lb130',
data: {
alias: 'Mock LB130',
mac: 'aa:aa:aa:b1:04:d3',
deviceId: 'BB130',
},
})
);
devices.forEach((d) => {
d.start();
});
UdpServer.start();
}
module.exports = { startSimulator };
|
function foo() {
var x = 2;
var xxx = 1;
if (xxx) {
console.log(xxx + x);
}
}
|
const Room = ({routeParams}) => <h1>{routeParams.name} Room</h1>
module.exports = Room
|
'use strict';
var storageKey = 'VN_TRANSLATE';
// ReSharper disable once InconsistentNaming
function Translate($translate, $translatePartialLoader, storage, options, disableTranslations) {
this.$translate = $translate;
this.$translatePartialLoader = $translatePartialLoader;
this.storage = storage;
this.disableTranslations = disableTranslations;
this.configure(angular.extend(options, this.getConfig()));
this.addPart = $translatePartialLoader.addPart;
}
Translate.prototype.getConfig = function() {
var storage = this.storage;
var config = JSON.parse(storage.get(storageKey)) || {};
var lang = storage.get('NG_TRANSLATE_LANG_KEY');
if (!this.disableTranslations && lang && lang !== 'undefined') {
config.lang = lang;
}
return config;
};
Translate.prototype.configure = function(config) {
config = angular.extend(this.getConfig(), config);
this.storage.set(storageKey, JSON.stringify(config));
this.$translate.use(config.lang);
};
Translate.prototype.addParts = function() {
if (this.disableTranslations) {
return true;
}
var loader = this.$translatePartialLoader;
angular.forEach(arguments, function(part) {
loader.addPart(part);
});
return this.$translate.refresh();
};
function TranslateProvider($translateProvider) {
this.$translateProvider = $translateProvider;
this.setPreferredLanguage = $translateProvider.preferredLanguage;
}
TranslateProvider.prototype.$get = [
'$translate', '$translatePartialLoader', 'storage',
function($translate, $translatePartialLoader, storage) {
var options = this.options;
return new Translate($translate, $translatePartialLoader, storage, {
region: options.region,
lang: options.lang,
country: options.country
}, options.disableTranslations);
}
];
TranslateProvider.prototype.configure = function(options) {
options = angular.extend({ region: 'us', lang: 'en', country: 'us' }, options);
if (options.lang) {
this.setPreferredLanguage(options.lang);
}
this.options = options;
if (!options.disableTranslations) {
this.initTranslateProvider(options.lang);
}
};
TranslateProvider.prototype.initTranslateProvider = function(lang) {
var $translateProvider = this.$translateProvider;
$translateProvider.useLoader('$translatePartialLoader', {
urlTemplate: '/translations/{part}/{lang}.json'
});
if (lang === 'en') {
$translateProvider.useMessageFormatInterpolation();
}
$translateProvider.useMissingTranslationHandlerLog();
$translateProvider.useLocalStorage();
};
angular.module('Volusion.toolboxCommon')
.provider('translate', ['$translateProvider', TranslateProvider]);
|
import Database from "almaden";
import Collection from "../../lib/collection.js";
import Model from "../../../";
import {ModelQuery} from "../../lib/modelFinder.js";
import {User} from "../testClasses.js";
import databaseConfig from "../databaseConfig.json";
let userFixtures = require("../fixtures/users.json");
describe("Model.find", () => {
let users,
userCollection;
before(() => {
Model.database = new Database(databaseConfig);
Model.database.mock({}); // Catch-all for database
});
after(() => {
// Remove database from model to prevent
// polluting another file via the prototype
Model.database = undefined;
});
beforeEach(done => {
userCollection = new Collection(User);
userFixtures.forEach((userFiture) => {
userCollection.push(new User(userFiture));
});
Model.database.mock({
"select * from `users` where `mom_id` = 1":
userFixtures
});
User
.find
.where("momId", "=", 1)
.results((error, fetchedUsers) => {
users = fetchedUsers;
done();
});
});
it("should return a ModelQuery instance", () => {
User.find.should.be.instanceOf(ModelQuery);
});
it("should return a collection", () => {
users.should.be.instanceOf(Collection);
});
it("should return the right collection", () => {
users.should.eql(userCollection);
});
it("should allow to search all models that matchs a certain condition", () => {
users.length.should.equal(5);
});
describe(".all", () => {
beforeEach(done => {
User.find
.all
.where("momId", 1)
.results((error, fetchedUsers) => {
users = fetchedUsers;
done();
});
});
it("should return just all users matching the condition", () => {
users.length.should.equal(5);
});
});
describe(".deleted", () => {
class SoftUser extends Model {
initialize() {
this.softDelete;
}
}
beforeEach(done => {
Model.database.mock({
"select * from `soft_users` where `mom_id` = 1 and `deleted_at` is not null":
userFixtures
});
SoftUser.find
.all
.where("momId", 1)
.deleted
.results((error, fetchedUsers) => {
users = fetchedUsers;
done();
});
});
it("should return just all users matching the condition", () => {
users.length.should.equal(5);
});
});
describe("(with a different database for a model)", () => {
class Car extends Model {}
let car,
database,
query;
describe("(static way)", () => {
beforeEach(() => {
database = new Database(databaseConfig);
Car.database = database;
query = database.spy("select * from `cars`", []);
car = new Car();
});
it("should use the specific model class database", (done) => {
Car.find.all.results(() => {
query.callCount.should.equal(1);
done();
});
});
});
describe("(instance way)", () => {
beforeEach(() => {
database = new Database(databaseConfig);
Car.database = null;
car = new Car({id: 2}, {database: database});
query = database.spy("select * from `cars` where `id` = 2 limit 1", []);
});
it("should use the specific model instance database", (done) => {
car.fetch(() => {
query.callCount.should.equal(1);
done();
});
});
});
});
});
|
var fs = require('fs');
/*var mulu = fs.readFileSync('./mulu.html','utf8');
var sutra = mulu.replace(/<sutra>/g,'#<sutra>').split(/#/);
var vol = function(sutra){
for (var i in sutra){
var vol = sutra[i].match(/<vol>(.+)<\/vol>/);
var sutraid = sutra[i].match(/<sutraid n="(.+)"\/>/);
if (vol == null || sutraid == null) {
console.log('');
} else {
console.log(sutraid[1],vol[0]);
}
}
}
var cname = function(sutra){
for (var i in sutra){
var cname = sutra[i].match(/<taisho.+chi="(.+)\/">/g);
var sutraid = sutra[i].match(/<sutraid n="(.+)"\/>/);
if (cname == null || sutraid == null) {
console.log('');
} else {
console.log(sutraid[1],cname.map(function(cname){
var chiname = cname.replace(/<taisho.+chi="(.+)\/>/g,"$1");
return chiname;
}));
}
}
}*/
///////////////////////////////////////////////////////////
fs.readdir('input',function(err,files){
if (files[0] == ".DS_Store") files.splice(0,1);
//console.log(files,files.length);
files.map(persutra);
})
var persutra = function(fn){
var text = fs.readFileSync('./input/'+fn,'utf8');
var sutra = JSON.parse(text);
console.log(sutraid(fn));
console.log(findeachtag(sutra));
//var sutra = arr[3]['མདོ་མིང་།'];
//console.log(sutra);
}
var sutraid = function(id){
var sutraid = id.match(/J\d+((\([a-z]\))|(\,\d+))*/)[0];
return ('<sutra>' + breakline + '<sutraid n="' + sutraid + '"/>');
}
var findeachtag = function(arr){
var trans = 'translator';
var tname = arr[3]['མདོ་མིང་།'];
var aname = arr[3]['མདོ་མིང་གཞན།'];
var sname = arr[3]['རྒྱ་གར་མདོ་མིང་།'];
var homage = arr[3]['བསྒྱུར་ཕྱག'];
var subject = arr[3]['བརྗོད་བྱ།'];
var yana = arr[3]['ཐེག་པ།'];
var charka = arr[3]['དཀའ། འཁོར་ལོ།'];
var location = arr[3]['གནས་ཕུན་སུམ་ཚོགས་པ།'];
var audience = arr[3]['འཁོར་ཕུན་སུམ་ཚོགས་པ།'];
var aurthor = arr[3]['སྟོན་པ་ཕུན་སུམ་ཚོགས་པ།'];
var requester = arr[3]['ཞུ་བ་པོ་ཕུན་སུམ་ཚོགས་པ།'];
var dharma = arr[3]['ཆོས་ཕུན་སུམ་ཚོགས་པ།'];
var purpose = arr[3]['ཆོས་ཀྱི་དགོས་དོན།'];
var collect = arr[3]['བསྡུས་པའི་དོན། ལེའུ།'];
var bampo = arr[3]['བམ་པོ། ཤོ་ལོ་ཀ'];
var relation = arr[3]['མཚམས་སྦྱར་བའི་གོ་རིམ།'];
var debate = arr[3]['རྒལ་ལན།'];
var translator = arr[3]['ལོ་ཙཱ་བ།'];
var reviser = arr[3]['ཞུ་དག་པ།'];
//var cname = arr[3]['རྒྱ་ནག་མདོ་མིང་།'];
if (arr[1]['ལོ་ཙཱ་བ།'] == 'translator_revisor' || arr[2]['ལོ་ཙཱ་བ།'] == 'translator_revisor') trans = 'translator_reviser';
return "<tname>" + tname + "</tname>" + breakline + "<aname>" + aname + "</aname>" + breakline +
"<sname>" + sname + "</sname>" + breakline + "<cname></cname>" + breakline + "<vol></vol>" + breakline +
"<homage>" + homage + "</homage>" + breakline + "<subject>" + subject + "</subject>" + breakline +
"<yana>" + yana + "</yana>" + breakline + "<charka>" + charka + "</charka>" + breakline + "<location>" +
location + "</location>" + breakline + "<audience>" + audience + "</audience>" + breakline + "<aurthor>" +
aurthor + "</aurthor>" + breakline + "<requester>" + requester + "</requester>" + breakline + "<dharma>" +
dharma + "</dharma>" + breakline + "<purpose>" + purpose + "</purpose>" + breakline + "<collect>" + collect +
"</collect>" + breakline + "<bampo>" + bampo + "</bampo>" + breakline + "<relation>" + relation + "</relation>" +
breakline + "<debate>" + debate + "</debate>" + breakline + "<" + trans + ">" + translator + "</" + trans + ">" +
breakline + "<reviser>" + reviser + "</reviser>" + breakline + "</sutra>";
}
var breakline = RegExp('\n');
/*var writexml = function(xml){
fs.writeFileSync('bio.xml',JSON.stringify(xml,'',' '),'utf8');
}*/
|
/*
* grunt-simple-templates
* https://github.com/jclem/grunt-simple-templates
*
* Copyright (c) 2013 Jonathan Clem
* Licensed under the MIT license.
*/
'use strict';
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
jshint: {
all: [
'Gruntfile.js',
'tasks/*.js',
'<%= nodeunit.tests %>',
],
options: {
jshintrc: '.jshintrc',
},
},
// Before generating any new files, remove any previously-created files.
clean: {
tests: ['tmp'],
},
// Configuration to be run (and then tested).
templates: {
default_options: {
src: "test/fixtures/",
dest: "tmp/default_options"
},
custom_options: {
src: "test/fixtures/",
dest: "tmp/custom_options",
options: {
namespace: "CUSTOM_TEMPLATES",
extension: "hbs"
}
}
},
// Unit tests.
nodeunit: {
tests: ['test/*_test.js'],
},
});
// Actually load this plugin's task(s).
grunt.loadTasks('tasks');
// These plugins provide necessary tasks.
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-nodeunit');
// Whenever the "test" task is run, first clean the "tmp" dir, then run this
// plugin's task(s), then test the result.
grunt.registerTask('test', ['clean', 'templates', 'nodeunit']);
// By default, lint and run all tests.
grunt.registerTask('default', ['jshint', 'test']);
};
|
require('./navbar-list');
class ScrollSpy {
/**
* @param {NavBarList} navBarList
* @param {number} offset
*/
constructor (navBarList, offset) {
this.navBarList = navBarList;
this.offset = offset;
}
scrollEventListener () {
let activeLinkTarget = null;
let linkTargets = this.navBarList.getTargets();
let offset = this.offset;
let linkTargetsPastThreshold = [];
linkTargets.forEach(function (linkTarget) {
if (linkTarget) {
let offsetTop = linkTarget.getBoundingClientRect().top;
if (offsetTop < offset) {
linkTargetsPastThreshold.push(linkTarget);
}
}
});
if (linkTargetsPastThreshold.length === 0) {
activeLinkTarget = linkTargets[0];
} else if (linkTargetsPastThreshold.length === linkTargets.length) {
activeLinkTarget = linkTargets[linkTargets.length - 1];
} else {
activeLinkTarget = linkTargetsPastThreshold[linkTargetsPastThreshold.length - 1];
}
if (activeLinkTarget) {
this.navBarList.clearActive();
this.navBarList.setActive(activeLinkTarget.getAttribute('id'));
}
}
spy () {
window.addEventListener(
'scroll',
this.scrollEventListener.bind(this),
true
);
}
}
module.exports = ScrollSpy;
|
var d = require('../dtrace-provider');
var dtp = d.createDTraceProvider('test');
dtp.addProbe('probe1', 'int', 'int');
dtp.addProbe('probe2', 'int', 'int');
dtp.enable();
var dtp2 = d.createDTraceProvider('test');
dtp2.addProbe('probe3', 'int', 'int');
dtp2.addProbe('probe1', 'int', 'int');
dtp2.enable();
var dtp3 = d.createDTraceProvider('test', 'mymod1');
dtp3.addProbe('probe1', 'int', 'int');
dtp3.addProbe('probe2', 'int', 'int');
dtp3.enable();
var dtp4 = d.createDTraceProvider('test', 'mymod2');
dtp4.addProbe('probe1', 'int', 'int');
dtp4.addProbe('probe3', 'int', 'int');
dtp4.enable();
dtp.fire('probe1', function () {
return ([12, 3]);
});
dtp2.fire('probe1', function () {
return ([12, 73]);
});
dtp3.fire('probe1', function () {
return ([12, 3]);
});
dtp4.fire('probe1', function () {
return ([12, 73]);
});
|
'use strict';
// Given a bound list and the time steps,
// return the LB and UB at each timestep.
// List is in format of {LB:lb,UB:ub}
var months = ['JAN','FEB','MAR','APR','MAY','JUN','JUL','AUG','SEP','OCT','NOV','DEC'];
function getMonth(dateString) {
var m = parseInt(dateString.split('-')[1])-1;
return months[m];
}
module.exports = function(bounds, steps, callback) {
var steps_bound = [];
var month, month_cost = {};
var i,bound;
var bm = []; // Temporary bounds
// Start with no bounds
steps.forEach(function(step) {
// lb, ub, lb defined
steps_bound.push([0, null, false]);
});
var c = 0;
bounds.forEach(function(bound, index){
switch(bound.type) {
case 'NOB': // We are good
return;
case 'LBC':
for(i = 0; i < steps.length; i++) {
if( steps_bound[i][0] === null || steps_bound[i][0] < bound.bound ){
steps_bound[i][0] = bound.bound;
steps_bound[i][2] = true;
}
}
return;
case 'LBM':
case 'LBT':
var b;
bm = {};
bound.bound.forEach(function(b) {
bm[b[0]] = b[1];
});
for(i = 0; i < steps.length; i++) {
// Almost the same code for LBM and LBT
b = (bound.type === 'LBM') ? bm[getMonth(steps[i])] : bm[steps[i]];
if( (typeof b !== 'undefined' && b !== null) && (steps_bound[i][0] === null || steps_bound[i][0] < b) ){
steps_bound[i][0] = b;
steps_bound[i][2] = true;
}
}
return;
case 'UBC':
for( i = 0; i < steps.length; i++ ){
if( steps_bound[i][1] === null || steps_bound[i][1] > bound.bound) {
steps_bound[i][1] = bound.bound;
}
}
return;
case 'UBM':
case 'UBT':
bm = {};
bound.bound.forEach(function(b) {
bm[b[0]] = b[1];
});
for( i = 0; i < steps.length; i++ ){
// Almost the same code for BM and BT
b = (bound.type === 'UBM') ? bm[getMonth(steps[i])] : bm[steps[i]];
if( (typeof b !== 'undefined' && b !== null ) && (steps_bound[i][1] === null || steps_bound[i][1] > b) ) {
steps_bound[i][1] = b;
}
}
return;
case 'EQT':
var b;
bm = {};
bound.bound.forEach(function(b) {
bm[b[0]] = b[1];
});
for( i = 0; i < steps.length; i++ ){
b = bm[steps[i]];
if( typeof b !=='undefined' && b !== null) {
if( steps_bound[i][0] === null || steps_bound[i][0] < b ) {
steps_bound[i][0] = b;
steps_bound[i][2] = true;
}
if( steps_bound[i][1] === null || steps_bound[i][1] > b ) {
steps_bound[i][1] = b;
}
}
}
return;
default :
throw new Error('Bad Bound Type: '+bound.type);
}
});
return steps_bound.map((bound) => {
return {
LB : bound[0],
UB : bound[1],
LBDefined : bound[2]
}
});
};
|
const AssignmentExpression = require('./AssignmentExpression');
const Class = require('./Class');
const DecoratorDescriptor = require('./DecoratorDescriptor');
const ExpressionStatement = require('./ExpressionStatement');
const Function = require('./Function');
const Identifier = require('./Identifier');
const MemberExpression = require('./MemberExpression');
const ModuleDeclarationInterface = require('./ModuleDeclarationInterface');
const VariableDeclaration = require('./VariableDeclaration');
/**
* @memberOf Jymfony.Component.Autoloader.Parser.AST
*/
class ExportNamedDeclaration extends implementationOf(ModuleDeclarationInterface) {
/**
* Constructor.
*
* @param {Jymfony.Component.Autoloader.Parser.AST.SourceLocation} location
* @param {Jymfony.Component.Autoloader.Parser.AST.VariableDeclaration} declarations
* @param {Jymfony.Component.Autoloader.Parser.AST.ExportSpecifier[]} specifiers
* @param {Jymfony.Component.Autoloader.Parser.AST.Literal} source
*/
__construct(location, declarations, specifiers, source) {
/**
* @type {Jymfony.Component.Autoloader.Parser.AST.SourceLocation}
*/
this.location = location;
/**
* @type {Jymfony.Component.Autoloader.Parser.AST.VariableDeclaration}
*
* @private
*/
this._declarations = declarations;
/**
* @type {Jymfony.Component.Autoloader.Parser.AST.ExportSpecifier[]}
*
* @private
*/
this._specifiers = specifiers;
/**
* @type {Jymfony.Component.Autoloader.Parser.AST.Literal}
*
* @private
*/
this._source = source;
/**
* @type {string}
*/
this.docblock = null;
/**
* @type {null|[string, Jymfony.Component.Autoloader.Parser.AST.ExpressionInterface][]}
*/
this.decorators = null;
}
/**
* @inheritdoc
*/
compile(compiler) {
if (null === this._declarations) {
for (const specifier of this._specifiers) {
compiler.compileNode(
new ExpressionStatement(null, new AssignmentExpression(
null,
'=',
new MemberExpression(null, new Identifier(null, 'exports'), specifier.exported),
specifier.local
))
);
compiler._emit(';\n');
}
return;
}
compiler.compileNode(this._declarations);
compiler._emit(';\n');
if (this._declarations instanceof VariableDeclaration) {
for (const declarator of this._declarations.declarators) {
ExportNamedDeclaration._exportDeclarator(compiler, declarator);
}
} else if (this._declarations instanceof DecoratorDescriptor) {
compiler.compileNode(
new ExpressionStatement(null, new AssignmentExpression(
null, '=',
new MemberExpression(null, new Identifier(null, 'exports'), new Identifier(null, this._declarations.mangledName)),
new Identifier(null, this._declarations.mangledName)
))
);
} else if (this._declarations instanceof Function || this._declarations instanceof Class) {
if (this.decorators) {
this._declarations.declarators = this.decorators;
}
compiler.compileNode(
new ExpressionStatement(null, new AssignmentExpression(
null,
'=',
new MemberExpression(null, new Identifier(null, 'exports'), this._declarations.id),
this._declarations.id
))
);
}
}
/**
* Compile a declarator export.
*
* @param {Jymfony.Component.Autoloader.Parser.Compiler} compiler
* @param {Jymfony.Component.Autoloader.Parser.AST.VariableDeclarator} declarator
*
* @private
*/
static _exportDeclarator(compiler, declarator) {
for (const exportedName of declarator.id.names) {
compiler.compileNode(
new ExpressionStatement(null, new AssignmentExpression(
null,
'=',
new MemberExpression(null, new Identifier(null, 'exports'), exportedName),
exportedName
))
);
}
}
}
module.exports = ExportNamedDeclaration;
|
export const APP_LAYOUT_INIT = 'APP_LAYOUT_INIT';
export const APP_LAYOUT_CHANGE = 'APP_LAYOUT_CHANGE';
|
var helloWorldController = function(app){
app.get('/hello/world', function(request, response){
var responseObject = { "hello": "world"}
response.send(responseObject);
});
};
module.exports = helloWorldController;
|
(function(){
angular.module('form', ['participants'])
.component('formComp', {
templateUrl: 'components/form/template.html',
bindings: {
addParticipant: '<'
},
controller: function(Participants){
this.participant = {};
this.submit = function(participant){
if (!this.password) {
delete this.participant.pass;
}
if (!this.email) {
delete this.participant.email;
}
this.addParticipant(participant);
};
}
});
})();
|
define(['../../moduleDef', 'angular'], function(module, angular) {
'use strict';
module.provider('$dateParser', function() {
var proto = Date.prototype;
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
var defaults = this.defaults = {
format: 'shortDate',
strict: false
};
this.$get = function($locale) {
var DateParserFactory = function(config) {
var options = angular.extend({}, defaults, config);
var $dateParser = {};
var regExpMap = {
'sss' : '[0-9]{3}',
'ss' : '[0-5][0-9]',
's' : options.strict ? '[1-5]?[0-9]' : '[0-5][0-9]',
'mm' : '[0-5][0-9]',
'm' : options.strict ? '[1-5]?[0-9]' : '[0-5][0-9]',
'HH' : '[01][0-9]|2[0-3]',
'H' : options.strict ? '[0][1-9]|[1][012]' : '[01][0-9]|2[0-3]',
'hh' : '[0][1-9]|[1][012]',
'h' : options.strict ? '[1-9]|[1][012]' : '[0]?[1-9]|[1][012]',
'a' : 'AM|PM',
'EEEE' : $locale.DATETIME_FORMATS.DAY.join('|'),
'EEE' : $locale.DATETIME_FORMATS.SHORTDAY.join('|'),
'dd' : '[0-2][0-9]{1}|[3][01]{1}',
'd' : options.strict ? '[1-2]?[0-9]{1}|[3][01]{1}' : '[0-2][0-9]{1}|[3][01]{1}',
'MMMM' : $locale.DATETIME_FORMATS.MONTH.join('|'),
'MMM' : $locale.DATETIME_FORMATS.SHORTMONTH.join('|'),
'MM' : '[0][1-9]|[1][012]',
'M' : options.strict ? '[1-9]|[1][012]' : '[0][1-9]|[1][012]',
'yyyy' : '(?:(?:[1]{1}[0-9]{1}[0-9]{1}[0-9]{1})|(?:[2]{1}[0-9]{3}))(?![[0-9]])',
'yy' : '(?:(?:[0-9]{1}[0-9]{1}))(?![[0-9]])'
};
var setFnMap = {
'sss' : proto.setMilliseconds,
'ss' : proto.setSeconds,
's' : proto.setSeconds,
'mm' : proto.setMinutes,
'm' : proto.setMinutes,
'HH' : proto.setHours,
'H' : proto.setHours,
'hh' : proto.setHours,
'h' : proto.setHours,
'dd' : proto.setDate,
'd' : proto.setDate,
'a' : function(value) { var hours = this.getHours(); return this.setHours(value.match(/pm/i) ? hours + 12 : hours); },
'MMMM' : function(value) { return this.setMonth($locale.DATETIME_FORMATS.MONTH.indexOf(value)); },
'MMM' : function(value) { return this.setMonth($locale.DATETIME_FORMATS.SHORTMONTH.indexOf(value)); },
'MM' : function(value) { return this.setMonth(1 * value - 1); },
'M' : function(value) { return this.setMonth(1 * value - 1); },
'yyyy' : proto.setFullYear,
'yy' : function(value) { return this.setFullYear(2000 + 1 * value); },
'y' : proto.setFullYear
};
var regex, setMap;
$dateParser.init = function() {
$dateParser.$format = $locale.DATETIME_FORMATS[options.format] || options.format;
regex = regExpForFormat($dateParser.$format);
setMap = setMapForFormat($dateParser.$format);
};
$dateParser.isValid = function(date) {
if(angular.isDate(date)) return !isNaN(date.getTime());
return regex.test(date);
};
$dateParser.parse = function(value, baseDate) {
if(angular.isDate(value)) return value;
var matches = regex.exec(value);
if(!matches) return false;
var date = baseDate || new Date(0);
for(var i = 0; i < matches.length - 1; i++) {
setMap[i] && setMap[i].call(date, matches[i+1]);
}
return date;
};
// Private functions
function setMapForFormat(format) {
var keys = Object.keys(setFnMap), i;
var map = [], sortedMap = [];
// Map to setFn
var clonedFormat = format;
for(i = 0; i < keys.length; i++) {
if(format.split(keys[i]).length > 1) {
var index = clonedFormat.search(keys[i]);
format = format.split(keys[i]).join('');
if(setFnMap[keys[i]]) map[index] = setFnMap[keys[i]];
}
}
// Sort result map
angular.forEach(map, function(v) {
sortedMap.push(v);
});
return sortedMap;
}
function escapeReservedSymbols(text) {
return text.replace(/\//g, '[\\/]').replace('/-/g', '[-]').replace(/\./g, '[.]').replace(/\\s/g, '[\\s]');
}
function regExpForFormat(format) {
var keys = Object.keys(regExpMap), i;
var re = format;
// Abstract replaces to avoid collisions
for(i = 0; i < keys.length; i++) {
re = re.split(keys[i]).join('${' + i + '}');
}
// Replace abstracted values
for(i = 0; i < keys.length; i++) {
re = re.split('${' + i + '}').join('(' + regExpMap[keys[i]] + ')');
}
format = escapeReservedSymbols(format);
return new RegExp('^' + re + '$', ['i']);
}
$dateParser.init();
return $dateParser;
};
return DateParserFactory;
};
});
});
|
/**
* @copyright 2013 Sonia Keys
* @copyright 2016 commenthol
* @license MIT
* @module solarxyz
*/
/**
* Solarxyz: Chapter 26, Rectangular Coordinates of the Sun.
*/
import base from './base.js'
import nutation from './nutation.js'
import solar from './solar.js'
/**
* Position returns rectangular coordinates referenced to the mean equinox of date.
* @param {planetposition.Planet} earth - VSOP87Planet Earth
* @param {Number} jde - Julian ephemeris day
* @return {object} rectangular coordinates
* {Number} x
* {Number} y
* {Number} z
*/
export function position (earth, jde) { // (e *pp.V87Planet, jde float64) (x, y, z float64)
// (26.1) p. 171
const { lon, lat, range } = solar.trueVSOP87(earth, jde)
const [sε, cε] = base.sincos(nutation.meanObliquity(jde))
const [ss, cs] = base.sincos(lon)
const sβ = Math.sin(lat)
const x = range * cs
const y = range * (ss * cε - sβ * sε)
const z = range * (ss * sε + sβ * cε)
return { x, y, z }
}
/**
* LongitudeJ2000 returns geometric longitude referenced to equinox J2000.
* @param {planetposition.Planet} earth - VSOP87Planet Earth
* @param {Number} jde - Julian ephemeris day
* @return {Number} geometric longitude referenced to equinox J2000.
*/
export function longitudeJ2000 (earth, jde) {
const lon = earth.position2000(jde).lon
return base.pmod(lon + Math.PI - 0.09033 / 3600 * Math.PI / 180, 2 * Math.PI)
}
/**
* PositionJ2000 returns rectangular coordinates referenced to equinox J2000.
* @param {planetposition.Planet} earth - VSOP87Planet Earth
* @param {Number} jde - Julian ephemeris day
* @return {object} rectangular coordinates
* {Number} x
* {Number} y
* {Number} z
*/
export function positionJ2000 (earth, jde) {
const { x, y, z } = xyz(earth, jde)
// (26.3) p. 174
return {
x: x + 0.00000044036 * y - 0.000000190919 * z,
y: -0.000000479966 * x + 0.917482137087 * y - 0.397776982902 * z,
z: 0.397776982902 * y + 0.917482137087 * z
}
}
export function xyz (earth, jde) {
const { lon, lat, range } = earth.position2000(jde)
const s = lon + Math.PI
const β = -lat
const [ss, cs] = base.sincos(s)
const [sβ, cβ] = base.sincos(β)
// (26.2) p. 172
const x = range * cβ * cs
const y = range * cβ * ss
const z = range * sβ
return { x, y, z }
}
/**
* PositionB1950 returns rectangular coordinates referenced to B1950.
*
* Results are referenced to the mean equator and equinox of the epoch B1950
* in the FK5 system, not FK4.
*
* @param {planetposition.Planet} earth - VSOP87Planet Earth
* @param {Number} jde - Julian ephemeris day
* @return {object} rectangular coordinates
* {Number} x
* {Number} y
* {Number} z
*/
export function positionB1950 (earth, jde) { // (e *pp.V87Planet, jde float64) (x, y, z float64)
const { x, y, z } = xyz(earth, jde)
return {
x: 0.999925702634 * x + 0.012189716217 * y + 0.000011134016 * z,
y: -0.011179418036 * x + 0.917413998946 * y - 0.397777041885 * z,
z: -0.004859003787 * x + 0.397747363646 * y + 0.917482111428 * z
}
}
const ζt = [2306.2181, 0.30188, 0.017998]
const zt = [2306.2181, 1.09468, 0.018203]
const θt = [2004.3109, -0.42665, -0.041833]
/**
* PositionEquinox returns rectangular coordinates referenced to an arbitrary epoch.
*
* Position will be computed for given Julian day "jde" but referenced to mean
* equinox "epoch" (year).
*
* @param {planetposition.Planet} earth - VSOP87Planet Earth
* @param {Number} jde - Julian ephemeris day
* @param {Number} epoch
* @return {object} rectangular coordinates
* {Number} x
* {Number} y
* {Number} z
*/
export function positionEquinox (earth, jde, epoch) {
const xyz = positionJ2000(earth, jde)
const x0 = xyz.x
const y0 = xyz.y
const z0 = xyz.z
const t = (epoch - 2000) * 0.01
const ζ = base.horner(t, ζt) * t * Math.PI / 180 / 3600
const z = base.horner(t, zt) * t * Math.PI / 180 / 3600
const θ = base.horner(t, θt) * t * Math.PI / 180 / 3600
const [sζ, cζ] = base.sincos(ζ)
const [sz, cz] = base.sincos(z)
const [sθ, cθ] = base.sincos(θ)
const xx = cζ * cz * cθ - sζ * sz
const xy = sζ * cz + cζ * sz * cθ
const xz = cζ * sθ
const yx = -cζ * sz - sζ * cz * cθ
const yy = cζ * cz - sζ * sz * cθ
const yz = -sζ * sθ
const zx = -cz * sθ
const zy = -sz * sθ
const zz = cθ
return {
x: xx * x0 + yx * y0 + zx * z0,
y: xy * x0 + yy * y0 + zy * z0,
z: xz * x0 + yz * y0 + zz * z0
}
}
export default {
position,
longitudeJ2000,
positionJ2000,
xyz,
positionB1950,
positionEquinox
}
|
/**
* New node file
*/
var log4js = require('log4js');
var UserSession = require('./UserSession');
/* Room corresponds to each conference room*/
function UsersRegistry() {
"use strict";
/* If this constructor is called without the "new" operator, "this" points
* to the global object. Log a warning and call it correctly. */
if (false === (this instanceof UsersRegistry)) {
console.log('Warning: UsersRegistry constructor called without "new" operator');
return new UsersRegistry();
}
var log = log4js.getLogger('web');
var usersByName = {};
var usersBySessionId = {};
var idCounter = 0;
this.register = function(usersession){
usersByName[usersession.getName()] = usersession;
usersBySessionId[usersession.getWebSessionId()] = usersession;
}
this.getByName = function(name){
return usersByName[name];
}
this.exists = function(name) {
var isUserExists = !!usersByName[name];
return isUserExists;
}
this.getBySession = function(id){
return usersBySessionId[id];
}
this.removeBySession = function(id) {
var user = this.getBySession(id);
if(user){
delete usersByName[user.getName()];
delete usersBySessionId [user.getWebSessionId()];
}
return user;
}
this.nextUniqueId = function() {
idCounter++;
if(idCounter < 0){
idCounter = 1; // reset the counter, we will never have 65535 simultaneous clients anytime soon.
// lets try finding number which does not exist in our map
while (idExists(idCounter)) idCounter++;
}
return idCounter.toString();
}
this.idExists = function(id){
if (!usersBySessionId[id])
return false;
return true;
}
this.printRegistryInfo = function(){
//log.debug("usersByName --> ", usersByName);
//log.debug("usersBySessionId --> ", usersByName);
}
}
module.exports.UsersRegistry = UsersRegistry;
|
describe('TimeFilter', function () {
beforeEach(module('ngMovies'));
var TimeFilter;
beforeEach(inject(function ($filter) {
TimeFilter = $filter('TimeFilter');
}));
it('should be a filter', function () {
expect(TimeFilter).not.toBe(undefined);
});
it('should convert minutes to hours', function () {
expect(TimeFilter('110 min')).toBe('1 hour 50 minutes');
expect(TimeFilter('120 min')).toBe('2 hours');
expect(TimeFilter('140 min')).toBe('2 hours 20 minutes');
expect(TimeFilter('15 min')).toBe('15 minutes');
});
it('should handle invalid time', function () {
expect(TimeFilter('N/A')).toBe('N/A');
expect(TimeFilter('Error')).toBe('N/A');
});
});
|
// import should from 'should';
import { createStore } from 'redux';
import reredeux, { deux, LABELS } from '../src';
const { INIT, SELECT, ACTION, REDUCER, VALUE } = LABELS;
import todo from './todo';
import counter from './counter';
import phonebook from './phonebook';
const app = reredeux('example', [
counter,
todo,
deux('nest', [
phonebook
])
]);
let store;
let state;
describe('app', () => {
beforeEach(() => {
store = createStore(app[REDUCER], app[INIT]);
state = store.getState();
});
describe(INIT, () => {
describe('example', () => {
describe('counter', () => {
it('eql to 0', () => {
state.example.counter
.should.be.eql(0);
});
});
describe('todo', () => {
it('', () => {
state.example.todo
.should.be.eql([
{ name: 'brush teeth', complete: true },
{ name: 'dishes' , complete: false },
]);
});
});
describe('nest', () => {
describe('phonebook', () => {
it('== []', () => {
state.example.nest.phonebook
.should.be.eql([
{ name: 'person1', number: '1(222)333-4444'},
{ name: 'person2', number: '1(333)444-5555'},
]);
});
});
});
});
});
describe(SELECT, () => {
describe('example', () => {
describe('counter', () => {
describe(VALUE, () => {
it('== 0', () => {
app[SELECT].example.counter[VALUE](state)
.should.be.eql(0);
});
});
describe('succ', () => {
it('== 1', () => {
app[SELECT].example.counter.succ(state)
.should.be.eql(1);
});
});
describe('pred', () => {
it('== -1', () => {
app[SELECT].example.counter.pred(state)
.should.be.eql(-1);
});
});
});
describe('todo', () => {
describe('value', () => {
it('returns all the data', () => {
app[SELECT].example.todo.value(state)
.should.be.eql([
{ name: 'brush teeth', complete: true },
{ name: 'dishes' , complete: false },
]);
});
});
describe('titles', () => {
it('returns a list of todo titles', () => {
app[SELECT].example.todo.titles(state)
.should.be.eql(['brush teeth', 'dishes']);
});
});
describe('statuses', () => {
it('returns a list of completion status', () => {
app[SELECT].example.todo.statuses(state)
.should.be.eql([true, false]);
});
});
describe('completed', () => {
it('returns only complete todos', () => {
app[SELECT].example.todo.completed(state)
.should.be.eql([
{ name: 'brush teeth', complete: true },
]);
});
});
describe('pending', () => {
it('returns only incomplete todos', () => {
app[SELECT].example.todo.pending(state)
.should.be.eql([
{ name: 'dishes' , complete: false },
]);
});
});
});
describe('nest', () => {
describe('phonebook', () => {
describe('value', () => {
it('returns the list of entries', () => {
app[SELECT].example.nest.phonebook.value(state)
.should.be.eql([
{ name: 'person1', number: '1(222)333-4444'},
{ name: 'person2', number: '1(333)444-5555'},
]);
});
});
describe('nameToNumber', () => {
it('returns the map from name to number', () => {
app[SELECT].example.nest.phonebook.nameToNumber(state)
.should.be.eql({
'person1': { name: 'person1', number: '1(222)333-4444'},
'person2': { name: 'person2', number: '1(333)444-5555'},
});
});
});
describe('numberToName', () => {
it('returns the map from number to name', () => {
app[SELECT].example.nest.phonebook.numberToName(state)
.should.be.eql({
'1(222)333-4444': { name: 'person1', number: '1(222)333-4444'},
'1(333)444-5555': { name: 'person2', number: '1(333)444-5555'},
});
});
});
});
});
});
});
describe(ACTION, () => {
it('increment', () => {
app[ACTION].increment()
.should.have.property('type');
app[ACTION].increment()
.should.not.have.property('payload');
});
it('decrement', () => {
app[ACTION].decrement()
.should.have.property('type');
app[ACTION].decrement()
.should.not.have.property('payload');
});
});
describe(REDUCER, () => {
describe('counter', () => {
it('increment', () => {
store.dispatch(app[ACTION].increment());
state = store.getState();
state.example.counter
.should.be.eql(1);
});
it('decrement', () => {
store.dispatch(app[ACTION].decrement());
state = store.getState();
state.example.counter
.should.be.eql(-1);
});
});
});
});
|
module.exports = function (grunt) {
// Project configuration.
grunt.initConfig({
// Metadata.
pkg : grunt.file.readJSON('storelocator.jquery.json'),
banner : '/*! <%= pkg.title || pkg.name %> - v<%= pkg.version %> - ' +
'<%= grunt.template.today("yyyy-mm-dd") %>\n' +
'<%= pkg.homepage ? "* " + pkg.homepage + "\\n" : "" %>' +
'* Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %>;' +
' Licensed <%= _.map(pkg.licenses, "type").join(", ") %> */\n',
// Task configuration.
clean : {
files: ['dist']
},
sass : {
dist: {
files: {
'dist/assets/css/storelocator.css' : 'src/css/storelocator.scss',
'dist/assets/css/bootstrap-example.css' : 'src/css/bootstrap-example.scss'
}
}
},
concat : {
options: {
stripBanners: true
},
dist : {
src : ['src/js/jquery.<%= pkg.name %>.js'],
dest: 'dist/assets/js/plugins/storeLocator/jquery.<%= pkg.name %>.js'
}
},
uglify: {
dist: {
files: {
'dist/assets/js/plugins/storeLocator/jquery.<%= pkg.name %>.min.js': '<%= concat.dist.dest %>',
'dist/assets/js/libs/handlebars.min.js' : 'libs/handlebars/*.js',
'dist/assets/js/geocode.min.js' : 'src/js/geocode.js',
'dist/assets/js/libs/markerclusterer.min.js' : 'libs/markerclusterer/*.js',
}
}
},
qunit : {
files: ['test/**/*.html']
},
jshint : {
gruntfile: {
options: {
jshintrc: '.jshintrc'
},
src : 'Gruntfile.js'
},
src : {
options: {
jshintrc: 'src/.jshintrc'
},
globals: {
jQuery: true,
google: true
},
src : ['src/**/*.js']
},
test : {
options: {
jshintrc: 'test/.jshintrc'
},
src : ['test/**/*.js']
}
},
usebanner: {
dist: {
options: {
position: 'top',
banner : '<%= banner %>'
},
files : {
'dist/assets/js/plugins/storeLocator/jquery.<%= pkg.name %>.js' : 'dist/assets/js/plugins/storeLocator/jquery.<%= pkg.name %>.js',
'dist/assets/js/plugins/storeLocator/jquery.<%= pkg.name %>.min.js': 'dist/assets/js/plugins/storeLocator/jquery.<%= pkg.name %>.min.js'
}
}
},
cssmin : {
dist: {
files: {
'dist/assets/css/storelocator.min.css': 'dist/assets/css/storelocator.css',
'dist/assets/css/bootstrap-example.min.css': 'dist/assets/css/bootstrap-example.css'
}
}
},
handlebars : {
dist: {
files: {
'dist/assets/js/plugins/storeLocator/templates/compiled/standard-templates.js': 'src/templates/standard/*.html',
'dist/assets/js/plugins/storeLocator/templates/compiled/kml-templates.js': 'src/templates/kml/*.html'
}
}
},
watch : {
gruntfile: {
files: '<%= jshint.gruntfile.src %>',
tasks: ['jshint:gruntfile']
},
src : {
files : ['src/**/*'],
tasks : ['sass', 'concat', 'uglify', 'usebanner', 'cssmin'],
options: {
spawn : false
}
},
test : {
files: '<%= jshint.test.src %>',
tasks: ['jshint:test', 'qunit']
}
}
});
// These plugins provide necessary tasks.
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-sass');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-qunit');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-banner');
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.loadNpmTasks('grunt-contrib-handlebars');
// Build
grunt.registerTask('build', ['sass', 'concat', 'uglify', 'usebanner', 'cssmin']);
//Watch src build
grunt.registerTask('watchsrc', ['watch:src']);
};
|
import { expect } from 'chai';
import productReducer from './productReducer';
import * as actions from '../actions/productActions';
import * as types from '../constants/actionTypes';
import initialState from './initialState';
describe('Product Reducer', () => {
it ('should set isFetching to true on all request actions', () => {
let newState = productReducer({ ...initialState.products }, actions.updateProduct({}));
expect(newState.isFetching).to.equal(true);
newState = productReducer({ ...initialState.products }, actions.deleteProduct(0));
expect(newState.isFetching).to.equal(true);
newState = productReducer({ ...initialState.products }, actions.createProduct({}));
expect(newState.isFetching).to.equal(true);
newState = productReducer({ ...initialState.products }, actions.getProduct(0));
expect(newState.isFetching).to.equal(true);
newState = productReducer({ ...initialState.products }, actions.getAllProducts());
expect(newState.isFetching).to.equal(true);
});
it ('should set isFetching to false on all request completions', () => {
let newState = productReducer({ ...initialState.products, isFetching: true }, { type: types.PRODUCTS_REQUEST_SUCCESS });
expect(newState.isFetching).to.equal(false);
newState = productReducer({ ...initialState.products, isFetching: true }, { type: types.PRODUCT_REQUEST_SUCCESS });
expect(newState.isFetching).to.equal(false);
newState = productReducer({ ...initialState.products, isFetching: true }, { type: types.UPDATE_PRODUCT_SUCCESS });
expect(newState.isFetching).to.equal(false);
newState = productReducer({ ...initialState.products, isFetching: true }, { type: types.DELETE_PRODUCT_SUCCESS });
expect(newState.isFetching).to.equal(false);
newState = productReducer({ ...initialState.products, isFetching: true }, { type: types.PRODUCT_REQUEST_FAILURE });
expect(newState.isFetching).to.equal(false);
});
it ('should set editing values on modal actions', () => {
const product = {
id: 0,
name: 'test'
};
const action = actions.showEditModal(product);
let newState = productReducer({ ...initialState.products }, action);
expect(newState.editing.modalOpen).to.equal(true);
expect(newState.editing.product).to.deep.equal(product);
newState = productReducer(newState, actions.closeEditModal());
expect(newState.editing.modalOpen).to.equal(false);
});
it (`should set product list on ${types.UPDATE_PRODUCT_SUCCESS}`, () => {
const state = {
list: [{
id: 1,
name: 'test'
},{
id: 2,
name: 'test'
}]
};
const newName = 'test2';
const action = {
type: types.UPDATE_PRODUCT_SUCCESS,
result: {
id: 1,
name: newName
}
};
let newState = productReducer(state, action);
expect(newState.list[1].name).to.equal(newName);
});
it (`should set product list on ${types.CREATE_PRODUCT_SUCCESS}`, () => {
const state = {
list: [{
id: 1,
name: 'test'
},{
id: 2,
name: 'test'
}]
};
const action = {
type: types.CREATE_PRODUCT_SUCCESS,
result: {
id: 3,
name: 'test3'
}
};
let newState = productReducer(state, action);
expect(newState.list[2].name).to.equal('test3');
});
it (`should set product list on ${types.DELETE_PRODUCT_SUCCESS}`, () => {
const state = {
list: [{
id: 1,
name: 'test'
},{
id: 2,
name: 'test'
}]
};
const action = {
type: types.DELETE_PRODUCT_SUCCESS,
result: {
id: 1
}
};
let newState = productReducer(state, action);
expect(newState.list[0].id).to.equal(2);
});
it (`should set error on ${types.PRODUCT_REQUEST_FAILURE}`, () => {
const error = {
message: 'test'
};
const action = {
type: types.PRODUCT_REQUEST_FAILURE,
error
};
let newState = productReducer({ ...initialState.products }, action);
expect(newState.error).to.deep.equal(error);
});
});
|
/*
* /MathJax-v2/localization/en/en.js
*
* Copyright (c) 2009-2018 The MathJax Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
MathJax.Localization.addTranslation("en",null,{menuTitle:"English",version:"2.7.8",isLoaded:true,domains:{_:{version:"2.7.8",isLoaded:true,strings:{CookieConfig:"MathJax has found a user-configuration cookie that includes code to be run. Do you want to run it?\n\n(You should press Cancel unless you set up the cookie yourself.)",MathProcessingError:"Math processing error",MathError:"Math error",LoadFile:"Loading %1",Loading:"Loading",LoadFailed:"File failed to load: %1",ProcessMath:"Processing math: %1%%",Processing:"Processing",TypesetMath:"Typesetting math: %1%%",Typesetting:"Typesetting",MathJaxNotSupported:"Your browser does not support MathJax",ErrorTips:"Debugging tips: use %%1, inspect %%2 in the browser console"}},FontWarnings:{},"HTML-CSS":{},HelpDialog:{},MathML:{},MathMenu:{},TeX:{}},plural:function(a){if(a===1){return 1}return 2},number:function(a){return a}});MathJax.Ajax.loadComplete("[MathJax]/localization/en/en.js");
|
;(function(){
'use strict'
const express = require('express');
const router = express.Router();
router.post('/', function(req, res){
console.error('route: /create, ip: %s, time: %s', req.ip, new Date().toTimeString().substr(0,9));
console.error(Object.keys(req));
console.error(req.body);
res.status(200).json('user created!');
});
module.exports = router;
})();
|
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
var async = require("async");
var path = require("path");
var Tapable = require("tapable");
var ContextModule = require("./ContextModule");
var ContextElementDependency = require("./dependencies/ContextElementDependency");
function ContextModuleFactory(resolvers) {
Tapable.call(this);
this.resolvers = resolvers;
}
module.exports = ContextModuleFactory;
ContextModuleFactory.prototype = Object.create(Tapable.prototype);
ContextModuleFactory.prototype.create = function(context, dependency, callback) {
this.applyPluginsAsyncWaterfall("before-resolve", {
context: context,
request: dependency.request,
recursive: dependency.recursive,
regExp: dependency.regExp
}, function(err, result) {
if(err) return callback(err);
// Ignored
if(!result) return callback();
var context = result.context;
var request = result.request;
var recursive = result.recursive;
var regExp = result.regExp;
var loaders, resource, loadersPrefix = "";
var idx = request.lastIndexOf("!");
if(idx >= 0) {
loaders = request.substr(0, idx+1);
for(var i = 0; i < loaders.length && loaders[i] === "!"; i++) {
loadersPrefix += "!";
}
loaders = loaders.substr(i).replace(/!+$/, "").replace(/!!+/g, "!");
if(loaders == "") loaders = [];
else loaders = loaders.split("!");
resource = request.substr(idx+1);
} else {
loaders = [];
resource = request;
}
async.parallel([
this.resolvers.context.resolve.bind(this.resolvers.context, context, resource),
async.map.bind(async, loaders, this.resolvers.loader.resolve.bind(this.resolvers.loader, context))
], function(err, result) {
if(err) return callback(err);
this.applyPluginsAsyncWaterfall("after-resolve", {
loaders: loadersPrefix + result[1].join("!") + (result[1].length > 0 ? "!" : ""),
resource: result[0],
recursive: recursive,
regExp: regExp
}, function(err, result) {
if(err) return callback(err);
// Ignored
if(!result) return callback();
return callback(null, new ContextModule(this.resolveDependencies.bind(this), result.resource, result.recursive, result.regExp, result.loaders));
}.bind(this));
}.bind(this));
}.bind(this));
};
ContextModuleFactory.prototype.resolveDependencies = function resolveDependencies(fs, resource, recursive, regExp, callback) {
(function addDirectory(directory, callback) {
fs.readdir(directory, function(err, files) {
if(!files || files.length == 0) return callback();
async.map(files, function(seqment, callback) {
var subResource = path.join(directory, seqment)
fs.stat(subResource, function(err, stat) {
if(err) return callback(err);
if(stat.isDirectory()) {
if(!recursive) return callback();
addDirectory.call(this, subResource, callback);
} else if(stat.isFile()) {
var obj = {
context: resource,
request: "." + subResource.substr(resource.length).replace(/\\/g, "/")
};
this.applyPluginsAsyncWaterfall("alternatives", [obj], function(err, alternatives) {
alternatives = alternatives.filter(function(obj) {
return regExp.test(obj.request);
}).map(function(obj) {
var dep = new ContextElementDependency(obj.request);
dep.optional = true;
return dep;
});
callback(null, alternatives);
});
} else callback();
}.bind(this));
}.bind(this), function(err, result) {
if(err) return callback(err);
if(!result) return callback(null, []);
callback(null, result.filter(function(i) { return !!i; }).reduce(function(a, i) {
return a.concat(i);
}, []));
});
}.bind(this));
}.call(this, resource, callback));
};
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _from = require('babel-runtime/core-js/array/from');
var _from2 = _interopRequireDefault(_from);
exports.default = sortChunks;
var _toposort = require('toposort');
var _toposort2 = _interopRequireDefault(_toposort);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// see https://github.com/jantimon/html-webpack-plugin/blob/8131d8bb1dc9b185b3c1709264a3baf32ef799bc/lib/chunksorter.js
function sortChunks(chunks, chunkGroups) {
// We build a map (chunk-id -> chunk) for faster access during graph building.
var nodeMap = {};
chunks.forEach(function (chunk) {
nodeMap[chunk.id] = chunk;
});
// Add an edge for each parent (parent -> child)
var edges = chunkGroups.reduce(function (result, chunkGroup) {
return result.concat((0, _from2.default)(chunkGroup.parentsIterable, function (parentGroup) {
return [parentGroup, chunkGroup];
}));
}, []);
var sortedGroups = _toposort2.default.array(chunkGroups, edges);
// flatten chunkGroup into chunks
var sortedChunks = sortedGroups.reduce(function (result, chunkGroup) {
return result.concat(chunkGroup.chunks);
}, []).map(function (chunk) {
return (// use the chunk from the list passed in, since it may be a filtered list
nodeMap[chunk.id]
);
}).filter(function (chunk, index, self) {
// make sure exists (ie excluded chunks not in nodeMap)
var exists = !!chunk;
// make sure we have a unique list
var unique = self.indexOf(chunk) === index;
return exists && unique;
});
return sortedChunks;
}
|
"use strict"
const should = require('should')
const rewire = require('rewire')
const IC = rewire('../commands/new.js')
describe('New command',() => {
let mockFS = {
outputFile : (filename,content) => {
console.log(`mock writing to ${filename}`);
return {
then : () => { return { catch : () => {} }}
}
}
}
let mockFindADRDir = ( callback,startFrom,notFoundHandler) => { callback('.') }
let mockEditorCommand = "mockEditor"
let mockPropUtil = {
parse : (file,opts,cb) => {
cb(undefined,{editor : mockEditorCommand})
}
}
let dummyLaunchEditor = _ => {}
let commonMocks = {
fs : mockFS
, propUtil : mockPropUtil
, launchEditorForADR : dummyLaunchEditor
, writeADR : (adrFilename,newADR) => { console.log(`Pretending to write to ${adrFilename}`)}
}
function modifiedCommonMocks(specificMocks) {
let copy = {}
for (var k in commonMocks) copy[k] = commonMocks[k]
for (var j in specificMocks) copy[j] = specificMocks[j]
return copy;
}
it("Should fail if passed an invalid title - that can't be used as a filename", () => {
let revert = IC.__set__({
findADRDir : (startFrom, callback,notFoundHandler) => { callback('.') }
, withAllADRFiles : (callback) => { callback(['1-adr1.md','2-adr2.md'])}
})
let block = () => {IC(["bla","###"])}
block.should.throw()
revert()
})
it ("Should assign the next number for the new ADR - one higher than the last available ADR", () => {
let testTitle = "test"
let mocksWithHighestNumber = n => {
return {
findADRDir : mockFindADRDir
, withAllADRFiles : callback => {callback(['1-adr1.md', n + '-adr2.md'])}
, adrContent : (num,title,date) => { num.should.eql(n+1)}
}
}
var revert = IC.__set__(modifiedCommonMocks(mocksWithHighestNumber(2)))
IC([testTitle])
revert()
revert = IC.__set__(modifiedCommonMocks(mocksWithHighestNumber(5)))
IC(["test"])
revert();
})
it("Should use the title given as title parts when creating the new ADR content", () => {
let testTitle = "test"
var revert = IC.__set__(modifiedCommonMocks({
findADRDir : mockFindADRDir
, withAllADRFiles : (callback) => { callback(['1-adr1.md'])}
, adrContent : (num,title,date) => {
title.should.eql(testTitle)
}
}))
IC([testTitle])
revert();
let adrWithSeveralParts = ["adr","part","2"]
revert = IC.__set__(modifiedCommonMocks({
findADRDir : mockFindADRDir
, withAllADRFiles : (callback) => { callback(['1-adr1.md'])}
, adrContent : (num,title,date) => {
console.log(`Title mock got: ${title}`)
title.should.eql(adrWithSeveralParts.join(' '))
}
}))
IC(adrWithSeveralParts)
revert();
})
it("should attempt writing the content to a file", function() {
let testTitle = "test"
var revert = IC.__set__(modifiedCommonMocks({
findADRDir : mockFindADRDir
, withAllADRFiles : (callback) => { callback(['1-adr1.md'])}
, common : {
writeTextFileAndNotifyUser : (filename, content, msg) => {
filename.should.startWith('2') //default file name scheme starts with the expected ID
content.should.match(new RegExp(testTitle)) //The title should be somewhere in the content
msg.should.startWith('Writing')
}
}
}))
IC([testTitle])
revert()
})
})
|
module.exports = {
entry: {
main: ['babel-polyfill', './lib/index.js'],
test: ['babel-polyfill', 'mocha!./test/index.js'],
},
output: {
path: __dirname,
filename: '[name].bundle.js',
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel',
query: {
presets: ['es2015', 'react'],
},
},
{ test: /\.css$/, loader: 'style!css' },
{ test: /\.scss$/, loader: 'style!css!sass' },
{ test: /\.svg/, loader: 'svg-url-loader'},
{ test: /\.png$/, loader: "url-loader", query: { mimetype: "image/png" },
},
{ test: /\.(jpe?g|png|gif|svg)$/i, loaders: [
'file?hash=sha512&digest=hex&name=[hash].[ext]',
'image-webpack?bypassOnDebug&optimizationLevel=7&interlaced=false']
}
],
},
resolve: {
extensions: ['', '.js', '.jsx', '.json', '.scss', '.css'],
},
};
|
var webpackConfig = require("./webpack.config.js");
webpackConfig.devtool = "inline-source-map";
delete webpackConfig.externals;
delete webpackConfig.entry;
delete webpackConfig.output;
module.exports = function (config) {
config.set({
basePath: ".",
frameworks: ["es6-shim", "chai", "mocha", "sinon"],
files: ["tests.bundle.js"],
preprocessors: {
"tests.bundle.js": ["webpack", "sourcemap"],
},
reporters: ["dots", "coverage"],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ["Chrome"],
singleRun: false,
concurrency: Infinity,
webpack: webpackConfig,
webpackMiddleware: {
noInfo: false,
},
coverageReporter: {
type: "lcov",
dir: "coverage/",
},
});
};
|
import React from 'react';
import {
header,
tabs,
tab,
description,
importExample,
title,
divider,
example,
playground,
api,
testkit,
} from 'wix-storybook-utils/Sections';
import { storySettings } from '../test/storySettings';
import Star from 'wix-ui-icons-common/Star';
import * as examples from './examples';
import CounterBadge from '..';
export default {
category: storySettings.category,
storyName: 'CounterBadge',
component: CounterBadge,
componentPath: '..',
componentProps: {
size: 'small',
children: 1,
skin: 'general',
showShadow: false,
},
exampleProps: {
children: [
{ label: 'number', value: 1 },
{ label: 'string', value: 'New!' },
{ label: 'node', value: <Star /> },
],
},
sections: [
header({
component: <CounterBadge>1</CounterBadge>,
}),
tabs([
tab({
title: 'Description',
sections: [
description({
title: 'Description',
text:
'`CounterBadge` gives you a quick preview to indicate more action is required.',
}),
importExample("import { CounterBadge } from 'wix-style-react';"),
divider(),
title('Examples'),
example({
title: 'Number counter',
text:
'The most common use of CounterBadge is with a number value truncated to 99. CounterBadge comes in two sizes `small` (default) and `medium`.',
source: examples.numbers,
}),
example({
title: 'Skins',
text:
'Background color can be one of the following: `general`, `danger`, `urgent`, `standard`, `warning`, `success` and `light`.',
source: examples.skins,
}),
example({
title: 'Shadow',
text: 'CounterBadge can add a shadow using `showShadow` prop',
source: examples.shadow,
}),
example({
title: 'Custom node',
text: 'CounterBadge can display a custom node, like an icon.',
source: examples.custom,
}),
example({
title: 'Advanced',
text: 'An example for a CounterBadge counting items in cart.',
source: examples.advanced,
}),
],
}),
...[
{ title: 'API', sections: [api()] },
{ title: 'Testkit', sections: [testkit()] },
{ title: 'Playground', sections: [playground()] },
].map(tab),
]),
],
};
|
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
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;
};
Object.defineProperty(exports, "__esModule", { value: true });
var core_1 = require("@angular/core");
var paginated_list_component_1 = require("../../paginated-list/paginated-list.component");
var TopicTrendingComponent = (function (_super) {
__extends(TopicTrendingComponent, _super);
function TopicTrendingComponent(route, postService, topicService) {
var _this = _super.call(this) || this;
_this.route = route;
_this.postService = postService;
_this.topicService = topicService;
return _this;
}
TopicTrendingComponent.prototype.ngOnInit = function () {
var _this = this;
this.route.params.subscribe(function (params) {
_this.id = +params['id'];
_this.topicService.getDetail(_this.id)
.then(function (res) { return _this.topic = res; });
});
_super.prototype.ngOnInit.call(this);
};
TopicTrendingComponent.prototype.loadNextPage = function (currentPage, perPage) {
var _this = this;
this.postService.getTrending(currentPage, perPage, this.id)
.then(function (res) { return _this.addPage(res); });
};
return TopicTrendingComponent;
}(paginated_list_component_1.PaginatedListComponent));
TopicTrendingComponent = __decorate([
core_1.Component({
selector: 'app-topic-trending',
templateUrl: './topic-trending.component.html',
styleUrls: ['./topic-trending.component.css']
})
], TopicTrendingComponent);
exports.TopicTrendingComponent = TopicTrendingComponent;
|
jQuery.each(("blur focus focusin focusout click dblclick " +
"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave").split(" "),
function(i, name) {
jQuery.fn[name] = function() {
var el = this[0];
var ev = document.createEvent('MouseEvent');
ev.initMouseEvent(
name,
true /* bubble */, true /* cancelable */,
window, null,
0, 0, 0, 0, /* coordinates */
false, false, false, false, /* modifier keys */
0 /*left*/, null
);
el.dispatchEvent(ev);
};
} );
|
import React from 'react';
import PropTypes from 'prop-types';
import Header from './Header';
// This is a class-based component because the current
// version of hot reloading won't hot reload a stateless
// component at the top-level.
class App extends React.Component {
render() {
return (
<div className="container">
<Header/>
{this.props.children}
</div>
);
}
}
App.propTypes = {
children: PropTypes.element
};
export default App;
|
/**
* Copyright (c) 2014, Oracle and/or its affiliates.
* All rights reserved.
*/
"use strict";var l={"PRY_ASUNCION":[null,"Assun\u00E7\u00E3o"],"BRA_BRASILIA":[null,"Bras\u00EDlia"],"URY_MONTEVIDEO":[null,"Montevid\u00E9u"],"COL_BOGOTA":[null,"Bogot\u00E1"],"TTO_PORT_OF_SPAIN":[null,"Porto de Espanha"],"BRA_SAO_PAULO":[null,"S\u00E3o Paulo"]};(this?this:window)['DvtBaseMapManager']['_UNPROCESSED_MAPS'][2].push(["southAmerica","cities",l]);
|
'use strict';
var assert = require('assert');
var run = require('./helpers').runMocha;
var args = [];
describe('suite w/no callback', function() {
it('should throw a helpful error message when a callback for suite is not supplied', function(done) {
run(
'suite/suite-no-callback.fixture.js',
args,
function(err, res) {
if (err) {
return done(err);
}
var result = res.output.match(/no callback was supplied/) || [];
assert.equal(result.length, 1);
done();
},
{stdio: 'pipe'}
);
});
});
describe('skipped suite w/no callback', function() {
it('should not throw an error when a callback for skipped suite is not supplied', function(done) {
run('suite/suite-skipped-no-callback.fixture.js', args, function(err, res) {
if (err) {
return done(err);
}
var pattern = new RegExp('Error', 'g');
var result = res.output.match(pattern) || [];
assert.equal(result.length, 0);
done();
});
});
});
describe('skipped suite w/ callback', function() {
it('should not throw an error when a callback for skipped suite is supplied', function(done) {
run('suite/suite-skipped-callback.fixture.js', args, function(err, res) {
if (err) {
return done(err);
}
var pattern = new RegExp('Error', 'g');
var result = res.output.match(pattern) || [];
assert.equal(result.length, 0);
done();
});
});
});
describe('suite returning a value', function() {
it('should give a deprecation warning for suite callback returning a value', function(done) {
run(
'suite/suite-returning-value.fixture.js',
args,
function(err, res) {
if (err) {
return done(err);
}
var pattern = new RegExp('Deprecation Warning', 'g');
var result = res.output.match(pattern) || [];
assert.equal(result.length, 1);
done();
},
{stdio: 'pipe'}
);
});
});
|
/*****************************
ACT I: THE SETUP
1. Hat guy
2. Lovers
// then let's start escalating...
******************************/
function Stage_Start(self){
// Create Peeps
self.world.clearPeeps();
self.world.addBalancedPeeps(20);
}
function Stage_Hat(self){
// A Hat Guy
var hat = new HatPeep(self);
self.world.addPeep(hat);
// Director
self.director.callbacks = {
takePhoto: function(d){
// DECLARATIVE
d.tryChyron(function(d){
var p = d.photoData;
var caught = d.caught({
hat: {_CLASS_:"HatPeep"}
});
if(caught.hat){
p.audience = 3;
p.caughtHat = caught.hat;
d.chyron = "OOH NICE HAT";
return true;
}
return false;
}).otherwise(_chyPeeps);
},
movePhoto: function(d){
d.audience_movePhoto();
},
cutToTV: function(d){
// If you did indeed catch a hat peep...
var p = d.photoData;
if(p.caughtHat){
self.world.addBalancedPeeps(1); // Add with moar!
d.audience_cutToTV(function(peep){
peep.wearHat();
}); // make all viewers wear HATS!
p.caughtHat.kill(); // Get rid of hat
Stage_Lovers(self); // Next stage
}else{
d.audience_cutToTV();
}
}
};
}
function Stage_Lovers(self){
// LOVERS
var lover1 = new LoverPeep(self);
lover1.setType("circle");
var lover2 = new LoverPeep(self);
lover2.setType("square");
lover2.follow(lover1);
self.world.addPeep(lover1);
self.world.addPeep(lover2);
// Director
self.director.callbacks = {
takePhoto: function(d){
// MODULAR & DECLARATIVE
d.tryChyron(_chyLovers)
.otherwise(_chyHats)
.otherwise(_chyPeeps);
},
movePhoto: function(d){
d.audience_movePhoto();
},
cutToTV: function(d){
// MODULAR & DECLARATIVE
d.tryCut2TV(_cutLovers)
.otherwise(_cutHats)
.otherwise(_cutPeeps);
// And whatever happens, just go to the next stage
// ACT II!!!
Stage_Screamer(self);
}
};
}
///////////////////////////////////////
///////////////////////////////////////
////// DECLARATIVE CHYRON MODULES /////
///////////////////////////////////////
///////////////////////////////////////
function _chyLovers(d){
var p = d.photoData;
var caught = d.caught({
lover: {_CLASS_:"LoverPeep"}
});
if(caught.lover){
if(caught.lover.isEmbarrassed){
d.chyron = "yeah git on outta here";
}else{
p.caughtLovers = true;
p.forceChyron = true;
d.chyron = "GROSS, GO GET A ROOM";
}
return true;
}
return false;
}
function _chyHats(d){
var p = d.photoData;
var caught = d.caught({
hat: {_CLASS_:"NormalPeep", wearingHat:true}
});
if(caught.hat){
p.audience = 1;
p.caughtHat = true;
d.chyron = "nvm hats aren't cool anymore";
return true;
}
return false;
}
function _chyPeeps(d){
var p = d.photoData;
if(d.scene.camera.isOverTV(true)){
d.chyron = "A TV... ON TV!";
}else{
var caught = d.caught({
peeps: {_CLASS_:"NormalPeep", returnAll:true},
crickets: {_CLASS_:"Cricket", returnAll:true}
});
if(caught.crickets.length>0){
p.CAUGHT_A_CRICKET = true;
if(caught.crickets.length==1){
d.chyron = "LIL' CRICKY <3";
}else{
d.chyron = "okay that's too many crickets";
}
}else if(caught.peeps.length>0){
if(caught.peeps.length==1){
d.chyron = "just a normal peep";
}else{
d.chyron = "just some normal peeps";
}
}else{
p.ITS_NOTHING = true;
d.chyron = "WOWWEE, IT'S NOTHING";
}
}
return true;
}
///////////////////////////////////////
///////////////////////////////////////
///// DECLARATIVE CUTTING MODULES /////
///////////////////////////////////////
///////////////////////////////////////
function _cutLovers(d){
var p = d.photoData;
if(p.caughtLovers){
// Crickets
d.audience_cutToTV();
// MAKE LOVERS EMBARRASSED
d.scene.world.peeps.filter(function(peep){
return peep._CLASS_=="LoverPeep";
}).forEach(function(lover){
lover.makeEmbarrassed();
});
return true;
}else{
return false;
}
}
function _cutHats(d){
var p = d.photoData;
if(p.caughtHat){
// Only get the hat-wearers, make 'em take off the hat.
d.audience_cutToTV(
function(peep){ peep.takeOffHat(); },
function(peep){ return peep.wearingHat; }
);
return true;
}else{
// And if not, have them decrease by 1 each time anyway.
var hatPeeps = d.scene.world.peeps.slice(0).filter(function(peep){
return peep.wearingHat;
});
if(hatPeeps.length>0){
var randomIndex = Math.floor(Math.random()*hatPeeps.length);
hatPeeps[randomIndex].takeOffHat(true);
}
return false;
}
}
function _cutPeeps(d){
d.audience_cutToTV();
return true;
}
|
'use strict';
angular.module('app').service('dialogService', [
'$q',
function($q) {
var remote = require('remote');
var dialog = remote.require('dialog');
function DialogService() {}
DialogService.prototype.showOpenDialog = function() {
var deferred = $q.defer();
dialog.showOpenDialog(function(fileNames) {
return deferred.resolve(fileNames);
});
return deferred.promise;
};
DialogService.prototype.showSaveDialog = function() {
var deferred = $q.defer();
dialog.showSaveDialog(function(fileNames) {
return deferred.resolve(fileNames);
});
return deferred.promise;
};
return new DialogService();
}
]);
|
angular.module('authService', [])
.factory('AuthService',
['$q', '$timeout', '$http', '$rootScope',
function ($q, $timeout, $http, $rootScope) {
// create user variable
var user = null;
// return available functions for use in the controllers
return ({
isLoggedIn: isLoggedIn,
getUserStatus: getUserStatus,
login: login,
logout: logout,
register: register,
getRegUsers: getRegUsers,
deleteUser: deleteUser
});
function isLoggedIn() {
return user;
}
function getUserStatus() {
return $http.get('/user/status')
// handle success
.success(function (data) {
user = data.status;
})
// handle error
.error(function (data) {
user = false;
});
}
function login(username, password) {
// create a new instance of deferred
var deferred = $q.defer();
// send a post request to the server
$http.post('/user/login',
{username: username, password: password})
// handle success
.success(function (data, status) {
if (status === 200 && data.status) {
user = true;
$rootScope.user = data.user;
window.sessionStorage["userInfo"] = JSON.stringify(data.user);
$rootScope.userInfo = JSON.parse(window.sessionStorage["userInfo"]);
window.sessionStorage["user"] = data.user;
deferred.resolve(data.user);
} else {
user = false;
deferred.reject();
}
})
// handle error
.error(function (data) {
user = false;
deferred.reject();
});
// return promise object
return deferred.promise;
}
function logout() {
// create a new instance of deferred
var deferred = $q.defer();
// send a get request to the server
$http.get('/user/logout')
// handle success
.success(function (data) {
user = false;
deferred.resolve();
})
// handle error
.error(function (data) {
user = false;
deferred.reject();
});
// return promise object
return deferred.promise;
}
function register(regUser) {
// create a new instance of deferred
var deferred = $q.defer();
// send a post request to the server
$http.post('/user/signup', regUser)
// handle success
.success(function (data, status) {
if (status === 200 && data.status) {
deferred.resolve();
} else {
deferred.reject();
}
})
// handle error
.error(function (data) {
deferred.reject();
});
// return promise object
return deferred.promise;
}
function getRegUsers() {
var deferred = $q.defer();
$http.get('/user/allUsers')
.success(function (data, status) {
if (status === 200) {
$rootScope.regUsers = data;
deferred.resolve();
}
else {
deferred.reject();
}
})
// handle error
.error(function () {
deferred.reject();
});
// return promise object
return deferred.promise;
}
function deleteUser(id) {
var deferred = $q.defer();
$http.delete('/user/deleteUser', {params: {username: id}})
.success(function (data, status) {
if (status === 200) {
deferred.resolve();
}
})
// handle error
.error(function () {
deferred.reject();
});
return deferred.promise;
}
}
]
);
|
(function() {
'use strict';
/**
* idHeader
*
* This component renders the application header.
*/
angular
.module('app.components')
.component('idHeader', header());
/**
* Internal function that returns the component.
* @returns {object} the angular component
*/
function header() {
return {
templateUrl: 'app/components/header.component.html',
controller: HeaderCtrl,
controllerAs: 'vm'
};
}
/**
* Constructor function for the component's controller.
* @constructor
*/
HeaderCtrl.$inject = ['$state', 'eventingService', 'authService'];
function HeaderCtrl($state, eventingService, authService) {
var vm = this;
// lifecycle hooks
vm.$onInit = onInit;
// scope functions
vm.executeSearch = executeSearch;
vm.goToIdeas = goToIdeas;
vm.goToPeople = goToPeople;
vm.goToAccount = goToAccount;
vm.logout = logout;
vm.clearSearchValue = clearSearchValue;
/////////////////////
/**
* Initializes the component.
*/
function onInit() {
var currentUser = authService.currentUser();
if (currentUser) {
vm.currentUserName = currentUser.firstName + ' ' + currentUser.lastName;
}
vm.headerVisible = true;
vm.searchValue = '';
vm.searchResultsVisible = false;
eventingService.registerListener('accountChange', 'header', function(user) {
vm.currentUserName = !user ? '' : user.firstName + ' ' + user.lastName;
});
}
/**
* Executes a search.
*/
function executeSearch() {
vm.searchResultsVisible = true;
}
/**
* Navigates to the Ideas view.
*/
function goToIdeas() {
$state.go('ideas');
}
/**
* Navigates to the People view.
*/
function goToPeople() {
$state.go('people');
}
/**
* Navigates to the Account view.
*/
function goToAccount() {
$state.go('account');
}
/**
* Logs the current user out of the application.
*/
function logout() {
authService.logout()
.then(function() {
$state.go('login');
});
}
/**
* Clears the search text field.
*/
function clearSearchValue() {
vm.searchValue = '';
}
}
})();
|
var files =
[
[ "API", "dir_19ea4dbfe8f0e4681f60b9b97f7b5d11.html", "dir_19ea4dbfe8f0e4681f60b9b97f7b5d11" ]
];
|
/*global angular */
/**
* The main controller for the app. The controller:
* - retrieves and persists the model via the todoStorage service
* - exposes the model to the template and provides event handlers
*/
angular.module('todomvc')
.controller('TodoCtrl', function TodoCtrl($scope, $routeParams, $filter, store) {
'use strict';
var todos = $scope.todos = store.todos;
$scope.newTodo = '';
$scope.editedTodo = null;
$scope.$watch('todos', function () {
$scope.remainingCount = $filter('filter')(todos, { completed: false }).length;
$scope.completedCount = todos.length - $scope.remainingCount;
$scope.allChecked = !$scope.remainingCount;
}, true);
// Monitor the current route for changes and adjust the filter accordingly.
$scope.$on('$routeChangeSuccess', function () {
var status = $scope.status = $routeParams.status || '';
$scope.statusFilter = (status === 'active') ?
{ completed: false } : (status === 'completed') ?
{ completed: true } : '';
});
$scope.addTodo = function () {
var newTodo = {
title: $scope.newTodo.trim(),
completed: false
};
if (!newTodo.title) {
return;
}
$scope.saving = true;
store.insert(newTodo)
.then(function success() {
$scope.newTodo = '';
})
.finally(function () {
$scope.saving = false;
});
};
$scope.editTodo = function (todo) {
$scope.editedTodo = todo;
// Clone the original todo to restore it on demand.
$scope.originalTodo = angular.extend({}, todo);
};
$scope.saveEdits = function (todo, event) {
// Blur events are automatically triggered after the form submit event.
// This does some unfortunate logic handling to prevent saving twice.
if (event === 'blur' && $scope.saveEvent === 'submit') {
$scope.saveEvent = null;
return;
}
$scope.saveEvent = event;
if ($scope.reverted) {
// Todo edits were reverted-- don't save.
$scope.reverted = null;
return;
}
todo.title = todo.title.trim();
if (todo.title === $scope.originalTodo.title) {
$scope.editedTodo = null;
return;
}
store[todo.title ? 'put' : 'delete'](todo)
.then(function success() {}, function error() {
todo.title = $scope.originalTodo.title;
})
.finally(function () {
$scope.editedTodo = null;
});
};
$scope.revertEdits = function (todo) {
todos[todos.indexOf(todo)] = $scope.originalTodo;
$scope.editedTodo = null;
$scope.originalTodo = null;
$scope.reverted = true;
};
$scope.removeTodo = function (todo) {
store.delete(todo);
};
$scope.saveTodo = function (todo) {
store.put(todo);
};
$scope.toggleCompleted = function (todo, completed) {
if (angular.isDefined(completed)) {
todo.completed = completed;
}
store.put(todo, todos.indexOf(todo))
.then(function success() {}, function error() {
todo.completed = !todo.completed;
});
};
$scope.clearCompletedTodos = function () {
store.clearCompleted();
};
$scope.markAll = function (completed) {
todos.forEach(function (todo) {
if (todo.completed !== completed) {
$scope.toggleCompleted(todo, completed);
}
});
};
});
|
version https://git-lfs.github.com/spec/v1
oid sha256:bdecbb5008fcaa6e28cdb99aada4e0c3dc8dfa6bd53bb4d6e63005c7538ee886
size 30020
|
// Load required packages
var express = require('express');
var triggerPageController = require('../controllers/triggerPage');
// Create our Express router
var router = express.Router();
// Create endpoint handlers for trigger pages
router.route('/q/:code')
.get(triggerPageController.getTriggerPagesQr);
router.route('/n/:code')
.get(triggerPageController.getTriggerPagesNfc);
router.route('/s/:code')
.get(triggerPageController.getTriggerPagesShort);
module.exports = router;
|
GridRenderer.prototype.extend(
{
});
|
/**
* Created by admin on 16/10/11.
*/
var a=12,b=12,c=12;console.log(a,b,c,'hello')
|
export default { port: 1989 }
|
var mongoose = require('mongoose');
var Post = require('../models/Post').Post;
var config = require('../config');
var http = require('http');
var site = "";
var token = "";
var options = {
host: 'data.zz.baidu.com',
path: '/urls?site=' + site + '&token=' + token,
method: 'POST',
headers: {
'Accept': '*/*',
'Connection': 'Keep-Alive',
'User-Agent': 'curl/7.12.1 '
}
};
var callback = function (res) {
var buffers = [];
var nread = 0;
res.on('data', function (chunk) {
buffers.push(chunk);
nread += chunk.length;
});
res.on('end', function () {
console.log(buffers);
});
}
var req = http.request(options, callback);
mongoose.connect(config.db.production);
var db = mongoose.connection;
db.once('open', function (callback) {
Post.find({}, {pid: 1})
.exec(function (err, posts) {
var urls = posts.map(function (post) {
return 'http://' + config.site.url + '/post/' + post.pid;
});
var data = urls.join('\n');
console.log(data,urls.length);
req.write(data);
req.end();
});
});
|
const { shallow, mount } = require('enzyme');
const React = require('react');
function Fixture() {
return (
<div id="root">
<span id="child">Test</span>
</div>
);
}
describe('toHaveHTML', () => {
it('works with `shallow` renders', () => {
const wrapper = shallow(<Fixture />);
expect(wrapper.find('#child')).toHaveHTML(
'<span id="child">Test</span>'
);
});
it('works with `mount` renders', () => {
const wrapper = mount(<Fixture />);
expect(wrapper.find('#child')).toHaveHTML(
'<span id="child">Test</span>'
);
});
it('normalizes the quotations used', () => {
const wrapper = shallow(<Fixture />);
expect(wrapper.find('#child')).toHaveHTML(
'<span id="child">Test</span>'
);
expect(wrapper.find('#child')).toHaveHTML(
'<span id=\'child\'>Test</span>'
);
});
it('works with with jasmines negation', () => {
const wrapper = shallow(<Fixture />);
expect(wrapper.find('#child')).not.toHaveHTML('foo');
});
});
|
function test(chart) {
// Set hoverPoint
chart.series[0].points[2].onMouseOver();
}
|
describe("Related Assets", function(){
let project = require('../fixture')
let subject = project.documents.at('assets/data-source-spec')
it("relates assets across different content collections", function(){
subject.related.data_sources.length.should.equal(2)
})
it("provides a related data summary", function(){
subject.relatedData.should.have.property('nested')
subject.relatedData.nested.should.have.property('data')
subject.relatedData.nested.data.should.have.property('explanation')
subject.relatedData.nested.data.explanation.length.should.not.equal(0)
})
})
|
var path = require('path');
var webpack = require('webpack');
var WebpackCleanupPlugin = require("webpack-cleanup-plugin");
module.exports = {
entry: './react/index.jsx',
output: { path: __dirname + '/www', filename: 'bundle.js' },
module: {
loaders: [
{
test: /\.scss$/,
loaders: ["style", "css", "resolve-url", "sass?sourceMap"]
},
{
test: /.jsx?$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['es2015', "es2016", "es2017", "react"],
plugins: ["transform-class-properties"]
}
}
]
},
plugins: [
new WebpackCleanupPlugin({
exclude: ["index.html"], //Include any important stuff here
})
]
}
|
'use strict';
var yeoman = require('yeoman-generator');
var yosay = require('yosay');
var chalk = require('chalk');
var _ = require('lodash');
module.exports = yeoman.generators.Base.extend({
/**
* Constructor
* @return {undefined}
*/
constructor: function () {
yeoman.generators.Base.apply(this, arguments);
this.option('skip-install', {
desc: 'Skips the installation of dependencies',
type: Boolean
});
},
/**
* Prompt the user
* @return {undefined}
*/
prompting: function () {
var done = this.async();
this.log('Welcome to ' + chalk.red('uniform') + '. The fullstack form generator tool. Built with love. By developers, for developers.');
var prompts = [{
type: 'input',
name: 'configFile',
message: 'What\'s the name of your config file?',
default: 'uniform.json'
}];
this.prompt(prompts, function (answers) {
this.uniformConfig = require(this.destinationPath(answers.configFile));
done();
}.bind(this));
},
/**
* Writing
* @type {Object}
*/
writing: {
/**
* package.json
* @return {undefined}
*/
packageJSON: function() {
this.template('_package.json', 'package.json');
},
/**
* Git
* @return {undefined}
*/
git: function() {
this.copy('gitignore', '.gitignore');
},
/**
* Bower
* @return {undefined}
*/
bower: function() {
this.template('_bower.json', 'bower.json');
this.copy('bowerrc', '.bowerrc');
},
/**
* Main app
* @return {undefined}
*/
app: function() {
// root level folders
this.mkdir('bin');
this.mkdir('public');
this.mkdir('public/components');
this.mkdir('routes');
this.mkdir('views');
// Main route
this.template('routes/apiV1.js', 'routes/apiV1.js');
// Node error view
this.copy('views/error.jade', 'views/error.jade');
// app files
this.copy('bin/www', 'bin/www');
this.copy('app.js', 'app.js');
},
/**
* Images
* @return {undefined}
*/
img: function() {
this.mkdir('public/img');
},
/**
* Javascript
* @return {undefined}
*/
javascript: function() {
this.mkdir('public/js');
this.mkdir('public/js/forms');
this.mkdir('public/js/models');
this.mkdir('public/js/routers');
this.mkdir('public/js/views');
// Forms
this.copy('public/js/forms/entryform.js', 'public/js/forms/entryform.js');
// Models
this.template('public/js/models/_entry.js', 'public/js/models/entry.js');
// Routers
this.copy('public/js/routers/default.js', 'public/js/routers/default.js');
// Views
this.copy('public/js/views/landingView.js', 'public/js/views/landingView.js');
this.copy('public/js/views/successView.js', 'public/js/views/successView.js');
// Main js file
this.copy('public/js/main.js', 'public/js/main.js');
},
/**
* [styles description]
* @return {[type]} [description]
*/
styles: function() {
this.mkdir('public/css');
this.copy('public/css/main.styl', 'public/css/main.styl');
},
/**
* Templates
* @return {undefined}
*/
templates: function() {
this.mkdir('public/templates');
this.template('public/templates/landing.hbs', 'public/templates/landing.hbs');
this.template('public/templates/form.hbs', 'public/templates/form.hbs');
this.copy('public/templates/success.hbs', 'public/templates/success.hbs');
},
/**
* Dist
* @return {undefined}
*/
dist: function() {
// Directories
this.mkdir('public/dist');
this.mkdir('public/dist/css');
this.mkdir('public/dist/js');
this.mkdir('public/dist/templates');
},
/**
* HTML
* @return {undefined}
*/
html: function() {
this.copy('public/index.html', 'public/index.html');
},
/**
* Misc files
* @return {undefined}
*/
miscFiles: function() {
this.copy('public/.editorconfig', 'public/.editorconfig');
this.copy('public/.gitattributes', 'public/.gitattributes');
this.copy('public/.gitignore', 'public/.gitignore');
this.copy('public/.htaccess', 'public/.htaccess');
this.copy('public/apple-touch-icon.png', 'public/apple-touch-icon.png');
this.copy('public/browserconfig.xml', 'public/browserconfig.xml');
this.copy('public/crossdomain.xml', 'public/crossdomain.xml');
this.copy('public/favicon.ico', 'public/favicon.ico');
this.copy('public/LICENSE.txt', 'public/LICENSE.txt');
this.copy('public/robots.txt', 'public/robots.txt');
this.copy('public/tile-wide.png', 'public/tile-wide.png');
this.copy('public/tile.png', 'public/tile.png');
},
/**
* Gulp
* @return {undefined}
*/
gulp: function() {
this.copy('gulpfile.js', 'gulpfile.js');
}
},
/**
* Install Dependencies
* @return {undefined}
*/
install: function() {
this.installDependencies({
skipInstall: this.options['skip-install']
});
}
});
|
'use strict'
require('./controllers/listCtrl.js');
require('./controllers/loginCtrl.js');
require('./services/pageService.js');
angular.module('app.router',
['ui.router', 'app.list', 'app.login'])
.config(configFn);
configFn.$inject = ['$locationProvider', '$stateProvider', '$urlRouterProvider'];
function configFn($locationProvider, $stateProvider, $urlRouterProvider){
$urlRouterProvider.when('', '/');
$urlRouterProvider.otherwise("/404");
$stateProvider
.state('list', {
url: "/",
template: require('ng-cache!./views/list.html'),
// controller: 'listCtrl'
})
.state('signin', {
url: "/login",
template: require('ng-cache!./views/login.html'),
// controller: 'loginCtrl'
})
.state('404', {
url: "/404",
template: require('ng-cache!./views/404.html'),
controller: function(pageService) {
pageService.setTitle('404');
}
});
}
|
/**
* Created by josip on 20.1.2017..
*/
angular.module('mainModule').config(function($routeProvider, $locationProvider){
$routeProvider
.when('/', {
templateUrl: '/home/home.view.html',
controller: 'homeCtrl',
controllerAs: 'vm'
})
.when('/register', {
templateUrl: '/register/register.view.html',
controller: 'registerCtrl',
controllerAs: 'vm'
})
.when('/login', {
templateUrl: '/login/login.view.html',
controller: 'loginCtrl',
controllerAs: 'vm'
})
.when('/profile', {
templateUrl: '/profile/profile.view.html',
controller: 'profileCtrl',
controllerAs: 'vm'
})
.when('/forgot-password', {
templateUrl: '/forgot-password/forgot.password.view.html',
controller: 'forgotPassCtrl',
controllerAs: 'vm'
})
.when('/measurement',{
templateUrl:'/measurement/measurement.view.html',
controller: 'measurementCtrl',
controllerAs: 'vm'
})
.otherwise({redirectTo: '/'});
// use the HTML5 History API
$locationProvider.html5Mode(true);
});
|
import './mc-project-settings.component';
import './project-settings.service';
|
define(function(require) {
'use strict';
const _ = require('underscore');
const $ = require('jquery');
const __ = require('orotranslation/js/translator');
const BaseView = require('oroui/js/app/views/base/view');
const Confirmation = require('oroui/js/delete-confirmation');
const AttributeFormOptionRowView = BaseView.extend({
tagName: 'tr',
events: {
'click .delete-form-option': 'triggerRemove',
'click .edit-form-option': 'triggerEdit'
},
options: {
template: null,
data: {
label: null,
property_path: null,
required: false
}
},
/**
* @inheritDoc
*/
constructor: function AttributeFormOptionRowView(options) {
AttributeFormOptionRowView.__super__.constructor.call(this, options);
},
/**
* @inheritDoc
*/
initialize: function(options) {
this.options = _.defaults(options || {}, this.options);
const template = this.options.template || $('#attribute-form-option-row-template').html();
this.template = _.template(template);
},
update: function(data) {
this.options.data = data;
this.render();
},
triggerEdit: function(e) {
e.preventDefault();
this.trigger('editFormOption', this.options.data);
},
triggerRemove: function(e) {
e.preventDefault();
const confirm = new Confirmation({
content: __('Are you sure you want to delete this field?')
});
confirm.on('ok', _.bind(function() {
this.trigger('removeFormOption', this.options.data);
}, this));
confirm.open();
},
getTemplateData: function() {
return this.options.data;
}
});
return AttributeFormOptionRowView;
});
|
import 'whatwg-fetch';
export default function post(url, data) {
return fetch(url, {
method: "POST",
body: JSON.stringify(data),
headers: {
"Content-Type": "application/json"
},
credentials: "same-origin"
}).then(function (response) {
response.status //=> number 100–599
response.statusText //=> String
response.headers //=> Headers
response.url //=> String
return response.text()
}, function (error) {
error.message //=> String
});
}
|
// Write your tests here!
// Here is an example.
Tinytest.add('Pixedelic Slideshow started', function (test) {
test.isNotNull($('#target').camera, 'camera should exist');
test.equal(true, true);
});
|
/**
* Created by rg12 on 02/05/2016.
*/
/**
* @desc Add to uib-timepicker to fix timezone issues
* @example <uib-timepicker cp-widget-datetimepicker-patch></uib-timepicker>
*/
(function () {
'use strict';
angular
.module('app.widgets')
.directive('cpWidgetDatetimepickerPatch', cpWidgetDatetimepickerPatch);
function cpWidgetDatetimepickerPatch() {
return {
restrict: 'A',
priority: 1,
require: 'ngModel',
link: function (scope, element, attrs, ctrl) {
ctrl.$formatters.push(function (value) {
var date = new Date(value);
date = new Date(date.getTime() + (60000 * date.getTimezoneOffset()));
return date;
});
ctrl.$parsers.push(function (value) {
var date = new Date(value.getTime() - (60000 * value.getTimezoneOffset()));
return date;
});
}
};
}
})();
|
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
(function(global) {
global.ng = global.ng || {};
global.ng.common = global.ng.common || {};
global.ng.common.locales = global.ng.common.locales || {};
const u = undefined;
function plural(n) {
let i = Math.floor(Math.abs(n)), v = n.toString().replace(/^[^.]*\.?/, '').length;
if (i === 1 && v === 0) return 1;
return 5;
}
root.ng.common.locales['de-be'] = [
'de-BE',
[['AM', 'PM'], u, u],
u,
[
['S', 'M', 'D', 'M', 'D', 'F', 'S'], ['So.', 'Mo.', 'Di.', 'Mi.', 'Do.', 'Fr.', 'Sa.'],
['Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag'],
['So.', 'Mo.', 'Di.', 'Mi.', 'Do.', 'Fr.', 'Sa.']
],
[
['S', 'M', 'D', 'M', 'D', 'F', 'S'], ['So', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa'],
['Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag'],
['So.', 'Mo.', 'Di.', 'Mi.', 'Do.', 'Fr.', 'Sa.']
],
[
['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'],
[
'Jan.', 'Feb.', 'März', 'Apr.', 'Mai', 'Juni', 'Juli', 'Aug.', 'Sept.', 'Okt.', 'Nov.',
'Dez.'
],
[
'Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September',
'Oktober', 'November', 'Dezember'
]
],
[
['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'],
['Jan', 'Feb', 'Mär', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dez'],
[
'Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September',
'Oktober', 'November', 'Dezember'
]
],
[['v. Chr.', 'n. Chr.'], u, u],
1,
[6, 0],
['dd.MM.yy', 'dd.MM.y', 'd. MMMM y', 'EEEE, d. MMMM y'],
['HH:mm', 'HH:mm:ss', 'HH:mm:ss z', 'HH:mm:ss zzzz'],
['{1}, {0}', u, '{1} \'um\' {0}', u],
[',', '.', ';', '%', '+', '-', 'E', '·', '‰', '∞', 'NaN', ':'],
['#,##0.###', '#,##0 %', '#,##0.00 ¤', '#E0'],
'€',
'Euro',
{
'ATS': ['öS'],
'AUD': ['AU$', '$'],
'BGM': ['BGK'],
'BGO': ['BGJ'],
'CUC': [u, 'Cub$'],
'DEM': ['DM'],
'FKP': [u, 'Fl£'],
'GNF': [u, 'F.G.'],
'KMF': [u, 'FC'],
'RON': [u, 'L'],
'RWF': [u, 'F.Rw'],
'SYP': [],
'THB': ['฿'],
'TWD': ['NT$'],
'XXX': [],
'ZMW': [u, 'K']
},
plural,
[
[
['Mitternacht', 'morgens', 'vorm.', 'mittags', 'nachm.', 'abends', 'nachts'], u,
['Mitternacht', 'morgens', 'vormittags', 'mittags', 'nachmittags', 'abends', 'nachts']
],
[
['Mitternacht', 'Morgen', 'Vorm.', 'Mittag', 'Nachm.', 'Abend', 'Nacht'], u,
['Mitternacht', 'Morgen', 'Vormittag', 'Mittag', 'Nachmittag', 'Abend', 'Nacht']
],
[
'00:00', ['05:00', '10:00'], ['10:00', '12:00'], ['12:00', '13:00'], ['13:00', '18:00'],
['18:00', '24:00'], ['00:00', '05:00']
]
]
];
})(typeof globalThis !== 'undefined' && globalThis || typeof global !== 'undefined' && global ||
typeof window !== 'undefined' && window);
|
'use strict';
// Declare app level module which depends on views, and components
var ntApp = angular.module('ntApp', [
//'ngRoute',
'ui.router',
'ntApp.myDesigns',
'ntApp.designDetail',
'ntApp.myInfo',
'ntApp.couponList',
'ntApp.createDesign',
'ntApp.activities',
'ntApp.management',
'ui.bootstrap',
'angularFileUpload',
'angular-carousel',
//'ngDragDrop',
'angular-gestures',
'angular-md5'
//'ngAnimate'
]);
/*ntApp.config(['$routeProvider', function($routeProvider) {
//ntApp.registerCtrl = $controllerProvider.register;
$routeProvider
// .when('/myDesigns', {
// templateUrl: 'views/myDesigns.html',
// //controller: 'MyDesignsListCtrl'
// resolve: controller('myDesigns')
// })
// .when('/design/:designId', {
// templateUrl: 'views/designDetail.html',
// //controller: 'DesignDetailCtrl'
// resolve: controller('designDetail')
// })
.otherwise({
redirectTo: '/myDesigns'
});
}]);*/
ntApp.config(function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise("myDesigns");
//
// Now set up the states
$stateProvider
.state('myInfo', {
url: "/myInfo",
templateUrl: 'views/myInfo.html',
controller: 'MyInfoCtrl'
})
.state('couponList', {
url: "/couponList",
templateUrl: 'views/couponList.html',
controller: 'CouponListCtrl'
})
.state('management', {
url: "/temp/management",
templateUrl: 'views/management.html',
controller: 'ManagementControl'
})
.state('activities', {
url: "/activities",
templateUrl: 'views/activities.html',
controller: 'ActivitiesControl'
})
.state('orderListAuth', {
url: '/orderListAuth',
template: '<div></div>',
controller: function($window, $location) {
if (!sTempCode) {
$window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' +
'wxf26855bd0cda23bd' + '&redirect_uri=' +
encodeURIComponent('http://design.weavesfun.com/#/orderList') +
'&response_type=code&scope=snsapi_base&state=mine#wechat_redirect';
}
}
});
});
|
describe("Fragments", function () {
it('replace node with fragment', function () {
var node = render(
d('div', null,
'Hello',
d('div', null, 'World')
), document.body);
compare(node.dom, div(text('Hello'), div(text('World'))));
node = update(node,
d('div', null,
d('@', null, 1, 2, 3),
'Boom'
));
compare(node.dom, udiv(text(1), text(2), text(3), text('Boom')));
});
it('replace fragment with fragment', function () {
var node = render(
d('div', null,
'Hello',
d('@', null, 1, 2, 3),
'World'
), document.body);
compare(node.dom, div(text('Hello'), text(1), text(2), text(3), text('World')));
node = update(node,
d('div', null,
'Hello',
d('@', null, 4, 5, 6),
'World'
));
compare(node.dom, udiv(utext('Hello'), utext(4), utext(5), utext(6), utext('World')));
});
it('replace deep fragment with deep fragment', function () {
var node = render(
d('div', null,
'Hello',
0,
d('@', null,
1,
d('@', null,
4,
d('@', null, 7, 8),
5),
3),
'World'), document.body);
compare(node.dom, div(text('Hello'), text(0), text(1), text(4), text(7), text(8), text(5), text(3), text('World')));
node = update(node,
d('div', null,
'Hello',
d('@', null, 3, 4),
d('@', null,
1,
d('@', null,
d('@', null, 7, 8),
4,
5),
3),
'World'));
compare(node.dom, udiv(utext('Hello'), text(3), text(4), utext(1), text(7), text(8), text(4), utext(5), utext(3), utext('World')));
});
it("replace fragment with node", function () {
var node = render(
d('div', null,
d('@', null,
1,
d('@', null, 4, 5, 6),
3
)), document.body);
compare(node.dom, div(text(1), text(4), text(5), text(6), text(3)));
node = update(node,
d('div', null,
d('@', null,
1, 2, 3)));
compare(node.dom, udiv(utext(1), text(2), utext(3)));
});
it("set attrs", function () {
var node = render(
d('div', null,
d('@', {class: 'cls'}, 1, 2)), document.body);
compare(node.dom, div(text(1), text(2)));
node = update(node, d('div', null,
d('@', {class: 'cls'}, 1, 2)));
compare(node.dom, udiv(utext(1), utext(2)));
});
});
|
function supports_html5_storage() {
try {
return 'localStorage' in window && window['localStorage'] !== null;
} catch (e) {
return false;
}
}
function randomString(length) {
var text = "";
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for(var i=0; i < length; i++) {
text += chars.charAt(Math.floor(Math.random() * chars.length));
}
return text;
}
function register(baseUrl, username, email, password) {
var deferred = new $.Deferred();
if (username && email && password) {
challenge = randomString(10)
encrypted_challenge = sjcl.encrypt(password, challenge)
$.when(
$.ajax({
type: "POST",
url: baseUrl,
data: {
"username" : username,
"email" : email,
"challenge" : challenge,
"encrypted_challenge" : encrypted_challenge
}
})
).done(function() {
deferred.resolve("Registration completed");
}).fail(function() {
deferred.reject("Registration failed");
});
} else {
deferred.reject("Invalid parameters");
}
return deferred.promise();
}
function login(baseUrl, username, password) {
var deferred = new $.Deferred();
if (username && password) {
$.when(
$.ajax({
type: "GET",
url: baseUrl + "?username=" + username,
})
).then(function(data) {
return sjcl.decrypt(password, data)
}).then(function(challenge) {
return $.ajax({
type: "POST",
url: baseUrl,
data: {
"username" : username,
"challenge" : challenge,
}
})
}).then(function(rsa_public) {
if (supports_html5_storage()) {
localStorage.setItem("rsa_public", rsa_public);
}
}).done(function(data) {
deferred.resolve("Login completed");
}).fail(function() {
deferred.reject("Login failed");
});
} else {
deferred.reject("Invalid parameters");
}
return deferred.promise();
}
|
import test from 'ava';
import fn from './';
test('to decimal', t => {
t.true(fn(65) === 0.65);
t.true(fn(1234.5) === 12.345);
t.true(fn(0.1) === 0.001);
t.true(fn(12.1245, {digits: 2}) === 0.12);
t.true(fn(6158.4256, {digits: 5}) === 61.58426);
t.true(fn(1234.5, {digits: 0}) === 12);
t.end();
});
|
// app/routes.js
module.exports = function(app, request, Lob) {
var googleApiKey = 'AIzaSyAVcJflF_0GpUzioGph0e8edJQeatd-330';
app.get('/', function(req, res) {
res.sendfile('./public/index.html');
});
app.get('/api/getreps', function(req, res) {
var zip = req.query.zip;
var url = 'https://www.googleapis.com/civicinfo/v2/representatives?address='+ zip +'&key=' + googleApiKey
request(url, function (error, response, body) {
var bodyObj = JSON.parse(body);
if (!error && response.statusCode == 200) {
var officials = bodyObj.officials;
var offices = bodyObj.offices;
if(officials && offices) {
var resObj = {};
resObj.userCity = bodyObj.normalizedInput.city;
resObj.userState = bodyObj.normalizedInput.state;
resObj.userZip = bodyObj.normalizedInput.zip;
resObj.reps = [];
for(var i = 0; i < offices.length; i++) {
for(var j = 0; j < offices[i].officialIndices.length; j++) {
var officialIndex = offices[i].officialIndices[j];
if(officials[officialIndex].address) {
var official = officials[officialIndex];
var rep = {};
rep.officeName = offices[i].name;
rep.repName = official.name;
rep.address = official.address[0];
rep.photoUrl = official.photoUrl;
resObj.reps.push(rep);
}
}
}
res.send(resObj);
} else {
res.send(resObj);
}
} else {
if(bodyObj.error) {
res.status(bodyObj.error.code);
res.send(bodyObj);
} else {
res.status(404);
res.send(false);
}
}
});
});
app.post('/api/sendletter', function(req, res) {
var letter = req.body;
Lob.letters.create(letter, function (loberr, lobres) {
if(loberr) {
console.log('loberr:', loberr);
res.status(loberr.status_code);
res.send(loberr);
}
res.send(lobres);
});
});
};
|
import { combineReducers } from 'redux-immutable';
import gluttonousSnake from 'isomerism/reducers/components/game/gluttonousSnake';
export default combineReducers({
gluttonousSnake,
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.