code stringlengths 2 1.05M |
|---|
var gatherTheFlock = require('../../src/gatherTheFlock');
var mockDir = 'test/support/mockServers/';
describe('gatherTheFlock', function() {
context('when all the mocks are functional', function() {
it('number of mocks should be 2', function() {
expect(gatherTheFlock(mockDir + '2good').length).to.be.equal(2);
});
});
context('when one of the mocks contains errors during loading time', function() {
it('number of mocks should be 1', function() {
expect(gatherTheFlock(mockDir + '1bad1good').length).to.be.equal(1);
});
});
context('when one of the mocks contains errors during loading time and the other during runtime', function() {
it('number of mocks should be 1', function() {
expect(gatherTheFlock(mockDir + '2bad').length).to.be.equal(1);
});
});
});
|
import React from 'react'
import {
TableRow,
TableCell
} from 'material-ui/Table'
import TeamChip from 'containers/Asians/TabControls/_components/TeamChip'
import RoomTypeChips from 'containers/Asians/TabControls/_components/RoomTypeChips'
import AdjudicatorDragAndDrop from './AdjudicatorDragAndDrop'
import AdjudicatorDropZone from './AdjudicatorDropZone'
export default (
round,
roomsDraft,
onChange,
roomTypeRanks,
isDragging,
onDrag,
adjudicatorsById,
teamsById,
minimumRelevantAdjudicatorPoint,
classes
) => {
let arr = []
roomsDraft.forEach(room => {
const chair = room.chair
? <AdjudicatorDropZone
position={'chair'}
isDragging={isDragging}
adjudicator={room.chair}
room={room}
roomsDraft={roomsDraft}
onChange={onChange}
adjudicatorsById={adjudicatorsById}
teamsById={teamsById}
>
<AdjudicatorDragAndDrop
round={round}
position={'chair'}
room={room}
adjudicator={room.chair}
isDragging={isDragging}
onDrag={onDrag}
minimumRelevantAdjudicatorPoint={minimumRelevantAdjudicatorPoint}
margin={false}
/>
</AdjudicatorDropZone>
: <AdjudicatorDropZone
position={'chair'}
isDragging={isDragging}
room={room}
roomsDraft={roomsDraft}
onChange={onChange}
adjudicatorsById={adjudicatorsById}
teamsById={teamsById}
/>
const panels = []
room.panels.forEach((panel, index) => {
let margin = true
if (index > 0) {
margin = false
}
panels.push(
<AdjudicatorDropZone
key={panel}
position={'panels'}
isDragging={isDragging}
adjudicator={panel}
room={room}
roomsDraft={roomsDraft}
onChange={onChange}
adjudicatorsById={adjudicatorsById}
teamsById={teamsById}
>
<AdjudicatorDragAndDrop
round={round}
position={'panels'}
adjudicator={panel}
isDragging={isDragging}
onDrag={onDrag}
room={room}
minimumRelevantAdjudicatorPoint={minimumRelevantAdjudicatorPoint}
margin={margin}
/>
</AdjudicatorDropZone>
)
})
if (panels.length < 2) {
panels.push(
<AdjudicatorDropZone
key={'dropZone'}
position={'panels'}
isDragging={isDragging}
room={room}
roomsDraft={roomsDraft}
onChange={onChange}
adjudicatorsById={adjudicatorsById}
teamsById={teamsById}
/>
)
}
const trainees = []
room.trainees.forEach(trainee => {
trainees.push(
<AdjudicatorDropZone
key={trainee}
position={'trainees'}
isDragging={isDragging}
adjudicator={trainee}
room={room}
roomsDraft={roomsDraft}
onChange={onChange}
adjudicatorsById={adjudicatorsById}
teamsById={teamsById}
>
<AdjudicatorDragAndDrop
round={round}
position={'trainees'}
room={room}
adjudicator={trainee}
isDragging={isDragging}
onDrag={onDrag}
minimumRelevantAdjudicatorPoint={minimumRelevantAdjudicatorPoint}
margin
/>
</AdjudicatorDropZone>
)
})
trainees.push(
<AdjudicatorDropZone
key={'dropZone'}
position={'trainees'}
isDragging={isDragging}
room={room}
roomsDraft={roomsDraft}
onChange={onChange}
adjudicatorsById={adjudicatorsById}
teamsById={teamsById}
/>
)
arr.push(
<TableRow
key={room.rank}
>
<TableCell
children={room.rank + 1}
className={classes.tableCell}
/>
<TableCell
children={<RoomTypeChips room={room} />}
className={classes.tableCell}
/>
<TableCell
children={<TeamChip team={room.gov} round={round} />}
className={classes.tableCell}
/>
<TableCell
children={<TeamChip team={room.opp} round={round} />}
className={classes.tableCell}
/>
<TableCell
children={chair}
className={classes.tableCell}
/>
<TableCell
children={panels}
className={classes.tableCell}
/>
<TableCell
children={trainees}
className={classes.tableCell}
/>
</TableRow>
)
})
return arr
}
|
var board = function(args) {
this.width = args.width;
this.height = args.height;
this.portal = args.portal;
};
board.prototype.checkForPortal = function(x, y, direction) {
var thereIsAPortal = false;
if(this.portal) {
if((this.portal.x === x) && (this.portal.y === y) && (this.portal.direction === direction)) {
thereIsAPortal = true;
}
}
return thereIsAPortal;
};
board.prototype.validatePosition = function(x, y) {
var valid = false;
if((0 <= x) && (x < this.width) && (0 <= y) && (y < this.height)) {
valid = true;
}
return valid;
};
module.exports = board;
|
var playState = {
create: function(){
var background = game.add.sprite(0, 0, 'cidade');
background.width = 1300;
background.height = 650;
graphics = game.add.graphics(0, 0);
groupCidade = game.add.group();
groupCidade.inputEnableChildren = true;
var x = 100;
for (var i = 0; i < 3; i++){
// Gera os retangulos que ficarão atras das imagens
graphics.beginFill(0xFFFFFF);
graphics.lineStyle(3, 0x05005e, 1);
graphics.drawRoundedRect(x, 200, 315, 190, 10);
graphics.endFill();
var button = groupCidade.create(x, 200, graphics.generateTexture());
button.tint = 0xff8800;
button.name = 'groupCidade-child-' + i;
x = x + 400;
}
graphics.destroy();
var cachorro = game.add.sprite(110, 210, 'cachorro');
cachorro.width = 300;
cachorro.height = 170;
// Desenha o gato e a borda da box
var gato = game.add.sprite(510, 210, 'gato');
gato.width = 300;
gato.height = 170;
// Desenha o passaro e a borda da box
var passaro = game.add.sprite(910, 210, 'passaro');
passaro.width = 300;
passaro.height = 170;
start();
game.time.events.add(Phaser.Timer.SECOND * 4, initial, this);
function start(){
groupCidade.children[1].alpha = 0;
groupCidade.children[2].alpha = 0;
gato.alpha = 0;
passaro.alpha = 0;
background.alpha = 0.5;
groupCidade.children[0].x += 230;
cachorro.x += 230;
groupCidade.children[0].y -= 70;
cachorro.y -= 70;
game.add.tween(groupCidade.children[0].scale).to( { x: 2, y: 2 }, 1000, Phaser.Easing.Linear.Out, true);
game.add.tween(cachorro.scale).to( { x: 1, y: 1 }, 1000, Phaser.Easing.Linear.Out, true);
}
function initial(){
game.add.tween(groupCidade.children[0].scale).to( { x: 1, y: 1 }, 1000, Phaser.Easing.Linear.In, true);
game.add.tween(cachorro.scale).to( { x: 0.5, y: 0.5 }, 500, Phaser.Easing.Linear.In, true);
groupCidade.children[0].x -= 230;
cachorro.x -= 230;
groupCidade.children[0].y += 70;
cachorro.y += 70;
background.alpha = 0.5;
game.add.tween(groupCidade.children[1]).to( { alpha: 1 }, 1000, Phaser.Easing.Linear.None, true);
game.add.tween(groupCidade.children[2]).to( { alpha: 1 }, 1000, Phaser.Easing.Linear.None, true);
game.add.tween(gato).to( { alpha: 1 }, 1000, Phaser.Easing.Linear.None, true);
game.add.tween(passaro).to( { alpha: 1 }, 1000, Phaser.Easing.Linear.None, true);
game.add.tween(background).to( { alpha: 1 }, 1000, Phaser.Easing.Linear.None, true);
activateButtons();
}
function activateButtons(){
groupCidade.onChildInputDown.add(onDown, this);
groupCidade.onChildInputOver.add(onOver, this);
groupCidade.onChildInputOut.add(onOut, this);
}
function onDown (sprite) {
sprite.tint = 0x00ff00;
}
function onOver (sprite) {
sprite.tint = 0xffff00;
}
function onOut (sprite) {
sprite.tint = 0xff8800;
// sprite.tint = Math.random() * 0xffffff;
}
},
update: function(){
},
Win: function(){
game.state.start('win');
}
}; |
import { expect } from 'chai'
import jsdom from 'jsdom-global'
/*eslint-disable*/
import React from 'react'
import TestUtils from 'react-addons-test-utils'
import { Provider } from 'react-redux'
import CounterPage from '../../src/containers/CounterPage'
import configureStore from '../../src/store/configureStore'
/*eslint-enable*/
function setup (initialState) {
const store = configureStore(initialState)
const app = TestUtils.renderIntoDocument(
<Provider store={store}>
<CounterPage />
</Provider>
)
return {
app: app,
buttons: TestUtils.scryRenderedDOMComponentsWithTag(app, 'button').map(button => {
return button
}),
p: TestUtils.findRenderedDOMComponentWithTag(app, 'p')
}
}
describe('containers', () => {
jsdom()
describe('App', () => {
it('should display initial count', () => {
const { p } = setup()
expect(p.textContent).to.match(/^Clicked: 0 times/)
})
it('should display updated count after increment button click', () => {
const { buttons, p } = setup()
TestUtils.Simulate.click(buttons[0])
expect(p.textContent).to.match(/^Clicked: 1 times/)
})
it('should display updated count after descrement button click', () => {
const { buttons, p } = setup()
TestUtils.Simulate.click(buttons[1])
expect(p.textContent).to.match(/^Clicked: -1 times/)
})
it('should undo increment action on undo button click', () => {
const { buttons, p } = setup()
TestUtils.Simulate.click(buttons[0])
expect(p.textContent).to.match(/^Clicked: 1 times/)
TestUtils.Simulate.click(buttons[2])
expect(p.textContent).to.match(/^Clicked: 0 times/)
})
it('should redo after undo on redo button click', () => {
const { buttons, p } = setup()
TestUtils.Simulate.click(buttons[0])
expect(p.textContent).to.match(/^Clicked: 1 times/)
TestUtils.Simulate.click(buttons[2])
expect(p.textContent).to.match(/^Clicked: 0 times/)
TestUtils.Simulate.click(buttons[3])
expect(p.textContent).to.match(/^Clicked: 1 times/)
})
})
})
|
/**
* Created by alisabelousova on 3/27/15.
*/
module.exports = {
attributes: {
text : { type: 'string', unique: true, required: true },
isApproved : { type: 'boolean', defaultsTo: true },
isModerated : { type: 'boolean', defaultsTo: false }
}
};
|
import {vec3} from '../../global';
/**
* Tw2GeometryMeshArea
*
* @property {string} name
* @property {number} start
* @property {number} count
* @property {vec3} minBounds
* @property {vec3} maxBounds
* @property {vec3} boundsSpherePosition
* @property {number} boundsSphereRadius
*/
export class Tw2GeometryMeshArea
{
name = '';
start = 0;
count = 0;
minBounds = vec3.create();
maxBounds = vec3.create();
boundsSpherePosition = vec3.create();
boundsSphereRadius = 0;
}
|
import React, {Component} from 'react';
import {Router, Route, IndexRoute, browserHistory} from 'react-router';
import { IntlActions } from 'react-redux-multilingual'
import App from 'views/app';
import Home from 'views/home';
import About from 'views/about';
import Lens from 'views/lens';
import NotFound from 'views/404';
const publicPath = '/';
export const routeCodes = {
HOME: publicPath,
ABOUT: 'about',
LENS: 'lens',
LENS_DETAIL: 'lens/:id',
};
export const getRoutes = (store) => {
const localization = ['en', 'vi'];
const innerRoutes = (
<Route>
<IndexRoute component={ Home }/>
<Route path={ routeCodes.ABOUT } component={ About }/>
<Route path={ routeCodes.LENS } component={ Home }/>
<Route path={ routeCodes.LENS_DETAIL } components={ Lens } />
<Route path='*' component={ NotFound }/>
</Route>
);
return (
<Router history={ browserHistory }>
<Route path={ publicPath } component={ App }>
{
localization.map(lang => {
return (
<Route key={lang} path={lang} onEnter={() => store.dispatch(IntlActions.setLocale(lang))}>
{innerRoutes}
</Route>
);
})
}
{innerRoutes}
</Route>
</Router>
);
}
|
var gulp = require('gulp');
gulp.task('build', ['browserify', 'sass', 'images', 'fonts'])
|
module.exports = require("npm:fbemitter@2.0.0/index"); |
import ReactDOM from 'react-dom';
import React from 'react';
import TestUtils from 'react-addons-test-utils';
import {Progress} from '../../../src/index';
describe('Progress', () => {
it('should have .ui.progress class by default', () => {
let instance = TestUtils.renderIntoDocument(
<Progress></Progress>
);
expect(ReactDOM.findDOMNode(instance).className).toMatch('ui');
expect(ReactDOM.findDOMNode(instance).className).toMatch('progress');
});
it('should have child by default', () => {
let instance = TestUtils.renderIntoDocument(
<Progress>123</Progress>
);
expect(ReactDOM.findDOMNode(instance).textContent).toEqual('123');
});
it('should have custom class with custom className', () => {
let instance = TestUtils.renderIntoDocument(
<Progress className="custom"></Progress>
);
expect(ReactDOM.findDOMNode(instance).className).toMatch('custom');
});
it('should have value for item data-value', () => {
let instance = TestUtils.renderIntoDocument(
<Progress value="1"></Progress>
);
expect(ReactDOM.findDOMNode(instance).getAttribute('data-value')).toMatch('1');
});
it('should have percent for item data-percent', () => {
let instance = TestUtils.renderIntoDocument(
<Progress percent="1"></Progress>
);
expect(ReactDOM.findDOMNode(instance).getAttribute('data-percent')).toMatch('1');
});
it('should have total for item data-total', () => {
let instance = TestUtils.renderIntoDocument(
<Progress total="1"></Progress>
);
expect(ReactDOM.findDOMNode(instance).getAttribute('data-total')).toMatch('1');
});
it('should display Progress name', () => {
let Component = (
<Progress></Progress>
);
expect(Component.type.displayName).toMatch('Progress');
});
});
|
import EchonestSerializer from 'ember-data-echonest/serializers/echonest';
export default EchonestSerializer.extend({
modelKey: 'biography',
removalList: ['truncated']
});
|
import React, { Component } from 'react';
import {
Text,
View,
StyleSheet
} from 'react-native';
var styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'row',
justifyContent: 'space-between',
padding: 5
},
weekday: {
paddingLeft: 15
},
date: {
paddingRight: 10
},
text: {
fontWeight: 'bold',
color: "#000000"
}
})
export default class ListDateComponent extends Component {
render() {
return (
<View style={styles.container}>
<View style={styles.weekday}>
<Text style={styles.text}>{this.props.weekday}</Text>
</View>
<View style={styles.date}>
<Text style={styles.text}>{this.props.date}</Text>
</View>
</View>
)
}
}
|
var searchData=
[
['commands_2ecpp',['Commands.cpp',['../_commands_8cpp.html',1,'']]],
['commands_2ed',['Commands.d',['../_commands_8d.html',1,'']]],
['configuration_2eh',['Configuration.h',['../_configuration_8h.html',1,'']]]
];
|
export { default } from 'ember-appkit-admin/components/admin-header/component'; |
import createFactoryFunction from '../utilities/create-factory-function.js';
import { InputControllerHelper } from '../utilities/input-controller.js';
class DateController extends InputControllerHelper {
constructor($scope, iVXjs, iVXjsActions) {
super($scope, iVXjs, iVXjsActions);
}
}
DateController.$inject = ['$scope', 'iVXjs', 'ivxjs.actions'];
export default createFactoryFunction(DateController); |
const build_object = require("../lib/build_object.js");
const api = require("../lib/knomatic_api.js");
const config = require("../config/studio.js");
const request = require('request');
const qbHelper = require("../lib/qbHelper");
const qbConfig = require('../config/qbConfig');
module.exports = {
datasetName: "QuickBooksInsertInvoice",
columns: [
{
columnName: "WorkitemCaseId",
type: "string"
},
{
columnName: "AccountID",
type: "string"
},
{
columnName: "Amount",
type: "string"
},
{
columnName: "VendorID",
type: "string"
}],
selectHandler: function (req) {
return new Promise((resolve, reject) => {
var token = null;
api.getSession(config.registration.username, config.registration.password)
.then((token) => {
return Promise.all([api.getWorkitem(token, req.payload.parameters.uuid), api.getDataset(token, qbConfig.datasetUuid)])
})
.then((arrayResp) => {
console.log('workItem.data:' + JSON.stringify(workItem.data))
var workitem = arrayResp[0];
var amount = workItem.data["67c57956-704e-420a-b7cc-0006f70de7ec/4b50fa67-9103-4d81-8fed-39225384d102"];
var companyName = workItem.data["67c57956-704e-420a-b7cc-0006f70de7ec/28daa601-82e2-40c9-bcc0-394cf5439958"];
var vendor = workItem.data["67c57956-704e-420a-b7cc-0006f70de7ec/5bae15af-e934-45d7-8eab-812f098943c3"];
var currentRow = arrayResp[1].rows.filter(row => row.cells[1] === "Sandbox US 1")[0].cells; //replace 'Sandbox US 1' with request.query.q
const accesstoken = currentRow[5] + currentRow[6] + currentRow[7] + currentRow[8];
const realmId = currentRow[2];
request.post({
uri: `https://sandbox-quickbooks.api.intuit.com/v3/company/${realmId}/bill?minorversion=4`,
headers: {
'Authorization': `Bearer ${accesstoken}`,
'Accept': 'application/json',
'User-Agent': 'node-quickbooks: version 2.0.23'
},
form: {
"Line":[
{
"Id":"1",
"Amount": amount,
"DetailType":"AccountBasedExpenseLineDetail",
"AccountBasedExpenseLineDetail":
{
"AccountRef":
{
"value":"7"
}
}
}
],
"VendorRef":
{
"value":vendor
}
}
},
function (error, response, body) {
if (error) {
qbHelper.refreshAllAccessTokens();
console.log('error:', error); // Print the error if one occurred
}
var reponseObj = JSON.parse(body);
if (reponseObj.error) {
qbHelper.refreshAllAccessTokens();
}
});
})
})
}
} |
import axios from 'axios';
import { setUserIsLoggedIn, clearUserData } from './user';
export function loginRequest(userData) {
return (dispatch) => {
// API login call
return axios.post('/api/v1/login', userData);
};
}
export function userSignupRequest(userData) {
return (dispatch) => {
return axios.post('/api/v1/user', userData);
};
}
// clean up Redux state and make API call to log user out
export function logout() {
return (dispatch) => {
axios.get('/api/v1/logout');
dispatch(setUserIsLoggedIn(false));
dispatch(clearUserData());
};
}
|
const globby = require('globby');
const fs = require('fs');
function encode(str) {
return str
.replace(/\\/g, '\\\\')
.replace(/`/g, '\\`')
.replace(/\$\{/g, '$\\{')
.trim();
}
var kernel = encode(fs.readFileSync('lib/jison-parser-kernel.js', 'utf8'));
var parseErrorCode = encode(fs.readFileSync('lib/jison-parser-parseError-function.js', 'utf8'));
var errorClassCode = encode(fs.readFileSync('lib/jison-parser-error-code.js', 'utf8'));
var debugTraceCode = encode(fs.readFileSync('lib/jison-parser-debugTrace-function.js', 'utf8'));
var commonJsMainCode = encode(fs.readFileSync('lib/jison-parser-commonJsMain-function.js', 'utf8'));
var parserAPIs1Code = encode(fs.readFileSync('lib/jison-parser-API-section1.js', 'utf8'))
.replace(/^[^{]*\{/, '')
.replace(/\}[^\}]*$/, '')
.trim();
// DIAGNOSTICS/DEBUGGING:
//
// set `test` to TRUE to help verify that all code chunks are properly detected and edited:
const test = false;
if (test) {
kernel = 'kernel::xxxxxx';
parseErrorCode = 'parseError::xxxxxx';
errorClassCode = 'errorClass::xxxxxx';
debugTraceCode = 'debugTrace::xxxxxx';
commonJsMainCode = 'commonJsMain::xxxxxx';
parserAPIs1Code = 'APIchunk::xxxxxx';
}
globby(['lib/jison.js']).then(paths => {
var count = 0;
var edit_cnt = 0;
//console.log(paths);
paths.forEach(path => {
var updated = false;
//console.log('path: ', path);
var src = fs.readFileSync(path, 'utf8');
var dst = src
.replace(/(\/\/ --- START parser kernel ---)[^]+?(\/\/ --- END( of)? parser kernel ---)/, function f(m, p1, p2) {
edit_cnt++;
return p1 + `
parser.parse = \`
${kernel}
\`;
` + p2;
})
.replace(/(\/\/ --- START parser error class ---)[^]+?(\/\/ --- END( of)? parser error class ---)/, function f(m, p1, p2) {
edit_cnt++;
return p1 + `
const prelude = \`
${errorClassCode}
\`;
` + p2;
})
.replace(/(const parseErrorSourceCode = `)[^]+?(\/\/ --- END( of)? parseErrorSourceCode chunk ---)/, function f(m, p1, p2) {
edit_cnt++;
return p1 + '\n' + parseErrorCode + '\n\`;\n' + p2;
})
.replace(/(const debugTraceSrc = `)[^]+?(\/\/ --- END( of)? debugTraceSrc chunk ---)/, function f(m, p1, p2) {
edit_cnt++;
return p1 + '\n' + debugTraceCode + '\n\`;\n' + p2;
})
.replace(/(const commonJsMain = `)[^]+?(\/\/ --- END( of)? commonJsMain chunk ---)/, function f(m, p1, p2) {
edit_cnt++;
return p1 + '\n' + commonJsMainCode + '\n\`;\n' + p2;
})
.replace(/(const define_parser_APIs_1 = `)[^]+?(\/\/ --- END( of)? define_parser_APIs_1 chunk ---)/, function f(m, p1, p2) {
edit_cnt++;
return p1 + '\n ' + parserAPIs1Code + '\n\`;\n' + p2;
});
updated = (dst !== src);
if (updated) {
count++;
console.log('updated: ', path);
fs.writeFileSync(path, dst, {
encoding: 'utf8',
flags: 'w'
});
}
});
if (edit_cnt !== 6) {
console.error('ERROR: unexpected number of edits: check jison.js and this patch tool\'s regexes, then fix them or this verification number:', edit_cnt);
process.exit(1);
}
console.log('\nUpdated', count, 'files\' parser kernel core code.');
});
|
// is input key code
export function isInputKeyCode(event) {
let result = false;
const { keyCode, altKey, ctrlKey, shiftKey } = event;
// exclude keys
if (altKey || ctrlKey || shiftKey) {
return result;
}
// Digit0 to Digit9
if ((keyCode >= 48 && keyCode <= 57) || (keyCode >= 96 && keyCode <= 105)) {
result = true;
}
// A to Z
else if (keyCode >= 65 && keyCode <= 90) {
result = true;
} else if (
[186, 187, 188, 189, 190, 191, 192, 219, 220, 221, 222].indexOf(
keyCode,
) > -1
) {
/*
Semicolon:186
Equal("="):187
Comma (","):188
Minus("-"):189
Period("."):190
Slash("/"):191
Backquote("`"):192
Open square bracket ("["):219
Backslash("\"):220
Close square bracket ("]"):221
Quote("'"):222
*/
result = true;
}
// Support non-English languages. Chinese, Japanese, French, etc.
else if (keyCode == 229) {
result = true;
}
return result;
}
// is direction key code
export function isDirectionKeyCode(keyCode) {
return [37, 38, 39, 40].indexOf(keyCode) > -1;
}
// is single key
// export function isSingleKey() {}
|
import React from 'react';
import { css } from 'emotion';
import { createClassNameFromProps, withStyles } from './common/StyleManager';
import { joinClasses } from '../../utils/componentUtils';
import { Container } from './containers/Container';
import {colorList, modularScale} from '../../theme/Theme';
const componentStyle = css`
background-color: ${colorList.grey1};
border-radius: 0;
padding: ${modularScale.ms4} ${modularScale.ms2}
`;
class BJumbotron extends React.PureComponent {
render () {
return (
<div
className={joinClasses(createClassNameFromProps(this.props), componentStyle)}>
<Container>{this.props.children}</Container></div>
);
}
}
export const Jumbotron = withStyles('jumbotron')(BJumbotron); |
import React from 'react'
import { Container, Content, HeroFoot, Icon } from 're-bulma'
const Footer = () => (
<HeroFoot>
<Container>
<Content>
<p style={{ textAlign: 'center', padding: '10px' }}>
made with <Icon icon="fa fa-heart" size="isSmall" style={{ color: 'red' }} /> by <a href="http://www.nextgensoft.co.th">Nextgensoft</a>
</p>
</Content>
</Container>
</HeroFoot>
)
export default Footer
|
#!/usr/bin/env node
var sys = require('sys');
require('child_process')
.exec("gulp remove-proxy", function(error, stdout, stderr) {
sys.puts(stdout)
});
|
_r("post", "/group/join", token2, {
id: group._id
});
|
import random from '@turf/random';
import Benchmark from 'benchmark';
import meta from './';
const fixtures = {
point: random('points'),
points: random('points', 1000),
polygon: random('polygon'),
polygons: random('polygons', 1000)
};
const suite = new Benchmark.Suite('turf-meta');
/**
* Benchmark Results
* segmentEach - point x 3,541,484 ops/sec ±6.03% (88 runs sampled)
* segmentReduce - point x 3,245,821 ops/sec ±0.95% (86 runs sampled)
* flattenEach - point x 6,447,234 ops/sec ±5.56% (79 runs sampled)
* flattenReduce - point x 5,415,555 ops/sec ±1.28% (85 runs sampled)
* coordEach - point x 19,941,547 ops/sec ±0.64% (84 runs sampled)
* coordReduce - point x 11,959,189 ops/sec ±1.53% (85 runs sampled)
* propEach - point x 29,317,809 ops/sec ±1.38% (85 runs sampled)
* propReduce - point x 14,552,839 ops/sec ±1.06% (90 runs sampled)
* geomEach - point x 22,137,140 ops/sec ±0.95% (88 runs sampled)
* geomReduce - point x 12,416,033 ops/sec ±0.94% (88 runs sampled)
* featureEach - point x 29,588,658 ops/sec ±1.02% (88 runs sampled)
* featureReduce - point x 15,372,497 ops/sec ±1.11% (89 runs sampled)
* coordAll - point x 8,348,718 ops/sec ±0.68% (92 runs sampled)
* segmentEach - points x 7,568 ops/sec ±1.42% (90 runs sampled)
* segmentReduce - points x 7,719 ops/sec ±0.88% (90 runs sampled)
* flattenEach - points x 18,821 ops/sec ±7.17% (76 runs sampled)
* flattenReduce - points x 17,848 ops/sec ±1.10% (88 runs sampled)
* coordEach - points x 71,017 ops/sec ±0.80% (90 runs sampled)
* coordReduce - points x 46,986 ops/sec ±1.24% (91 runs sampled)
* propEach - points x 137,509 ops/sec ±0.38% (96 runs sampled)
* propReduce - points x 67,197 ops/sec ±1.44% (92 runs sampled)
* geomEach - points x 69,417 ops/sec ±0.77% (93 runs sampled)
* geomReduce - points x 45,830 ops/sec ±1.18% (92 runs sampled)
* featureEach - points x 151,234 ops/sec ±0.45% (92 runs sampled)
* featureReduce - points x 71,235 ops/sec ±1.51% (92 runs sampled)
* coordAll - points x 40,960 ops/sec ±0.88% (94 runs sampled)
* segmentEach - polygon x 884,579 ops/sec ±2.06% (82 runs sampled)
* segmentReduce - polygon x 770,112 ops/sec ±1.65% (85 runs sampled)
* flattenEach - polygon x 6,262,904 ops/sec ±2.84% (85 runs sampled)
* flattenReduce - polygon x 4,944,606 ops/sec ±4.15% (82 runs sampled)
* coordEach - polygon x 6,153,922 ops/sec ±2.36% (87 runs sampled)
* coordReduce - polygon x 3,348,489 ops/sec ±2.08% (91 runs sampled)
* propEach - polygon x 30,816,868 ops/sec ±0.96% (88 runs sampled)
* propReduce - polygon x 15,664,358 ops/sec ±0.88% (91 runs sampled)
* geomEach - polygon x 21,426,447 ops/sec ±1.19% (91 runs sampled)
* geomReduce - polygon x 11,585,812 ops/sec ±2.61% (84 runs sampled)
* featureEach - polygon x 29,478,632 ops/sec ±1.86% (87 runs sampled)
* featureReduce - polygon x 14,642,632 ops/sec ±2.62% (81 runs sampled)
* coordAll - polygon x 2,080,425 ops/sec ±13.27% (61 runs sampled)
* segmentEach - polygons x 1,042 ops/sec ±3.16% (76 runs sampled)
* segmentReduce - polygons x 912 ops/sec ±4.70% (80 runs sampled)
* flattenEach - polygons x 17,587 ops/sec ±3.05% (85 runs sampled)
* flattenReduce - polygons x 16,576 ops/sec ±1.33% (86 runs sampled)
* coordEach - polygons x 3,040 ops/sec ±15.62% (41 runs sampled)
* coordReduce - polygons x 4,100 ops/sec ±7.31% (85 runs sampled)
* propEach - polygons x 126,455 ops/sec ±0.85% (87 runs sampled)
* propReduce - polygons x 61,469 ops/sec ±2.96% (83 runs sampled)
* geomEach - polygons x 59,267 ops/sec ±5.22% (81 runs sampled)
* geomReduce - polygons x 24,424 ops/sec ±12.17% (52 runs sampled)
* featureEach - polygons x 110,212 ops/sec ±7.42% (71 runs sampled)
* featureReduce - polygons x 63,244 ops/sec ±3.74% (81 runs sampled)
* coordAll - polygons x 1,662 ops/sec ±19.73% (44 runs sampled)
*/
Object.keys(fixtures).forEach(name => {
const geojson = fixtures[name];
suite
.add('segmentEach - ' + name, () => meta.segmentEach(geojson, () => {}))
.add('segmentReduce - ' + name, () => meta.segmentReduce(geojson, () => {}))
.add('flattenEach - ' + name, () => meta.flattenEach(geojson, () => {}))
.add('flattenReduce - ' + name, () => meta.flattenReduce(geojson, () => {}))
.add('coordEach - ' + name, () => meta.coordEach(geojson, () => {}))
.add('coordReduce - ' + name, () => meta.coordReduce(geojson, () => {}))
.add('propEach - ' + name, () => meta.propEach(geojson, () => {}))
.add('propReduce - ' + name, () => meta.propReduce(geojson, () => {}))
.add('geomEach - ' + name, () => meta.geomEach(geojson, () => {}))
.add('geomReduce - ' + name, () => meta.geomReduce(geojson, () => {}))
.add('featureEach - ' + name, () => meta.featureEach(geojson, () => {}))
.add('featureReduce - ' + name, () => meta.featureReduce(geojson, () => {}))
.add('coordAll - ' + name, () => meta.coordAll(geojson));
});
suite
.on('cycle', e => console.log(String(e.target)))
.on('complete', () => {})
.run();
|
const _ = require(`lodash`)
const { emitter, store } = require(`../redux`)
const apiRunnerNode = require(`../utils/api-runner-node`)
const { boundActionCreators } = require(`../redux/actions`)
const { deletePage, deleteComponentsDependencies } = boundActionCreators
let pagesDirty = false
let graphql
emitter.on(`CREATE_NODE`, action => {
if (action.payload.internal.type !== `SitePage`) {
pagesDirty = true
}
})
emitter.on(`DELETE_NODE`, action => {
pagesDirty = true
debouncedCreatePages()
})
emitter.on(`API_RUNNING_QUEUE_EMPTY`, () => {
if (pagesDirty) {
runCreatePages()
}
})
const runCreatePages = async () => {
pagesDirty = false
const plugins = store.getState().plugins
// Test which plugins implement createPagesStatefully so we can
// ignore their pages.
const statefulPlugins = plugins
.filter(p => {
try {
const gatsbyNode = require(`${p.resolve}/gatsby-node`)
if (gatsbyNode.createPagesStatefully) {
return true
} else {
return false
}
} catch (e) {
return false
}
})
.map(p => p.id)
const timestamp = new Date().toJSON()
await apiRunnerNode(`createPages`, {
graphql,
traceId: `createPages`,
waitForCascadingActions: true,
})
// Delete pages that weren't updated when running createPages.
Array.from(store.getState().pages.values()).forEach(page => {
if (
!_.includes(statefulPlugins, page.pluginCreatorId) &&
page.updatedAt < timestamp
) {
deleteComponentsDependencies([page.path])
deletePage(page)
}
})
emitter.emit(`CREATE_PAGE_END`)
}
const debouncedCreatePages = _.debounce(runCreatePages, 100)
module.exports = graphqlRunner => {
graphql = graphqlRunner
}
|
class system_runtime_remoting_contexts_context {
constructor() {
// int ContextID {get;}
this.ContextID = undefined;
// System.Runtime.Remoting.Contexts.IContextProperty[] ContextProperties {get;}
this.ContextProperties = undefined;
}
// void DoCallBack(System.Runtime.Remoting.Contexts.CrossContextDelegate deleg)
DoCallBack() {
}
// bool Equals(System.Object obj)
Equals() {
}
// void Freeze()
Freeze() {
}
// int GetHashCode()
GetHashCode() {
}
// System.Runtime.Remoting.Contexts.IContextProperty GetProperty(string name)
GetProperty() {
}
// type GetType()
GetType() {
}
// void SetProperty(System.Runtime.Remoting.Contexts.IContextProperty prop)
SetProperty() {
}
// string ToString()
ToString() {
}
}
module.exports = system_runtime_remoting_contexts_context;
|
({
completeAllTodos: function(component) {
return function(dispatch, getState){
var action = component.get("c.completeAllTodos"),
state = getState(),
todoList = state.todos;
action.setParams({
todos: todoList
});
action.setCallback(this, function(response){
switch(response.getState(response)){
case "SUCCESS":
return dispatch({
type: 'COMPLETE_ALL'
});
case "ERROR":
break;
}
});
$A.enqueueAction(action);
}
},
removeCompletedTodos: function(component) {
return function(dispatch, getState){
var action = component.get("c.removeCompletedTodos"),
state = getState(),
todoList = state.todos;
action.setParams({
todos: todoList
});
action.setCallback(this, function(response){
switch(response.getState(response)){
case "SUCCESS":
return dispatch({
type: 'CLEAR_COMPLETED'
});
case "ERROR":
break;
}
});
$A.enqueueAction(action);
}
}
}) |
/**
* Created by lvliqi on 2017/7/21.
*/
module.exports.Token = require('./AccessToken');
module.exports.AuthInfo = require('./AuthInfo');
module.exports.PreAuthCode = require('./PreAuthCode');
module.exports.QueryAuth = require('./QueryAuth');
module.exports.Xcx = require('./Xcx'); |
/**
* Created by Tarnos on 2016-12-26.
*/
lotfw.factory('Game', function(EnemyList, logService){
var Game = function() {
this.stats = ['strength', 'endurance', 'dexterity', 'agility'];
this.isLoaded = true;//set to false to show intro
this.name = "Legend of the Fallen Warrior";
this.id = 0;//item id
this.enemyId = 0;
this.startGame = function(){
this.isLoaded = !this.isLoaded;
};
};
Game.prototype.nextEnemy = function(){
this.enemyId++;
logService.log("Next enemy set to " + this.enemyId);
if(EnemyList.enemies[this.enemyId]) return;//if enemy exist, return...
this.enemyId--;
};
Game.prototype.prevEnemy = function(){
this.enemyId--;
if(EnemyList.enemies[this.enemyId]) return;
this.enemyId++
};
Game.prototype.getCurrentEnemy = function(){
return EnemyList.enemies[this.enemyId];
};
return new Game();
}); |
export const ic_volume_down_outline = {"viewBox":"0 0 24 24","children":[{"name":"path","attribs":{"d":"M0 0h24v24H0V0z","fill":"none"},"children":[]},{"name":"path","attribs":{"d":"M16 7.97v8.05c1.48-.73 2.5-2.25 2.5-4.02 0-1.77-1.02-3.29-2.5-4.03zM5 9v6h4l5 5V4L9 9H5zm7-.17v6.34L9.83 13H7v-2h2.83L12 8.83z"},"children":[]}]}; |
'use strict';
// ==================================================================================
// internet.js
// ----------------------------------------------------------------------------------
// Description: System Information - library
// for Node.js
// Copyright: (c) 2014 - 2017
// Author: Sebastian Hildebrandt
// ----------------------------------------------------------------------------------
// License: MIT
// ==================================================================================
// 12. Internet
// ----------------------------------------------------------------------------------
const os = require('os');
const exec = require('child_process').exec;
const util = require('./util');
let _platform = os.type();
const _linux = (_platform === 'Linux');
const _darwin = (_platform === 'Darwin');
const _windows = (_platform === 'Windows_NT');
const NOT_SUPPORTED = 'not supported';
// --------------------------
// check if external site is available
function inetChecksite(url, callback) {
return new Promise((resolve, reject) => {
process.nextTick(() => {
let result = {
url: url,
ok: false,
status: 404,
ms: -1
};
if (url) {
url = url.toLowerCase();
let t = Date.now();
if (_linux || _darwin) {
let args = " -I --connect-timeout 5 -m 5 " + url + " 2>/dev/null | head -n 1 | cut -d ' ' -f2";
let cmd = "curl";
exec(cmd + args, function (error, stdout) {
let statusCode = parseInt(stdout.toString());
result.status = statusCode || 404;
result.ok = !error && (statusCode === 200 || statusCode === 301 || statusCode === 302 || statusCode === 304);
result.ms = (result.ok ? Date.now() - t : -1);
if (callback) { callback(result) }
resolve(result);
})
}
if (_windows) { // if this is stable, this can be used for all OS types
const http = (url.startsWith('https:') ? require('https') : require('http'));
try {
http.get(url, (res) => {
const statusCode = res.statusCode;
result.status = statusCode || 404;
result.ok = (statusCode === 200 || statusCode === 301 || statusCode === 302 || statusCode === 304);
if (statusCode !== 200) {
res.resume();
result.ms = (result.ok ? Date.now() - t : -1);
if (callback) { callback(result) }
resolve(result);
} else {
res.on('data', (chunk) => { });
res.on('end', () => {
result.ms = (result.ok ? Date.now() - t : -1);
if (callback) { callback(result) }
resolve(result);
})
}
}).on('error', err => {
if (callback) { callback(result) }
resolve(result);
});
} catch (err) {
if (callback) { callback(result) }
resolve(result);
}
}
} else {
if (callback) { callback(result) }
resolve(result);
}
});
});
}
exports.inetChecksite = inetChecksite;
// --------------------------
// check inet latency
function inetLatency(host, callback) {
// fallback - if only callback is given
if (util.isFunction(host) && !callback) {
callback = host;
host = '';
}
host = host || '8.8.8.8';
return new Promise((resolve, reject) => {
process.nextTick(() => {
let t = Date.now();
let cmd;
if (_linux || _darwin) {
if (_linux) {
cmd = "ping -c 2 -w 3 " + host + " | grep rtt | cut -d'/' -f4 | awk '{ print $3 }'";
}
if (_darwin) {
cmd = "ping -c 2 -t 3 " + host + " | grep avg | cut -d'/' -f4 | awk '{ print $3 }'";
}
exec(cmd, function (error, stdout) {
let result = -1;
if (!error) {
result = parseFloat(stdout.toString());
}
if (callback) { callback(result) }
resolve(result);
})
}
if (_windows) {
exec('ping ' + host + ' -n 1', function (error, stdout) {
let result = -1;
if (!error) {
let lines = stdout.toString().split('\r\n');
lines.shift();
lines.forEach(function (line) {
if (line.toLowerCase().startsWith(' min')) {
let l = line.replace(/ +/g, " ").split(' ');
if (l.length > 8) {
result = parseFloat(l[9])
}
}
});
}
if (callback) { callback(result) }
resolve(result);
})
}
});
});
}
exports.inetLatency = inetLatency;
|
import { combineReducers } from "redux";
import items from "./items";
// Combine reducers
const itemApp = combineReducers({
items
});
export default itemApp;
|
angular.module('designerWorkplaceApp')
.controller('messagesCtrl', ['$scope', '$mdSidenav', 'messageService', 'userService', 'workplaceService', 'notificationService',
function ($scope, $mdSidenav, messageService, userService, workplaceService, notificationService) {
'use strict';
var currentUser = userService.getCurrentUser();
function getMessages() {
$scope.isLoading = true;
messageService.getMessages(currentUser).then(function (messages) {
$scope.messages = messages;
$scope.isLoading = false;
});
}
$scope.acceptMessage = function (m) {
m.isProcessing = true;
workplaceService.finishExchangeWorkplace(currentUser, m.id)
.then(function () {
notificationService.info('Обмен принят');
m.isRead = true;
m.isProcessing = false;
},
function (errMsg) {
notificationService.error(errMsg);
m.isProcessing = false;
});
};
$scope.declineMessage = function (m) {
m.isProcessing = true;
workplaceService.declineExchangeWorkplace(currentUser, m.id)
.then(function () {
notificationService.info('Обмен отклонен');
m.isRead = true;
m.isProcessing = false;
},
function (errMsg) {
notificationService.error(errMsg);
m.isProcessing = false;
});
};
$scope.$on('messagesOpen', function () {
getMessages();
});
}]); |
var class_smooth_function =
[
[ "SmoothFunction", "class_smooth_function.html#ab47b4d1be729afadb652b373bfadecf0", null ],
[ "~SmoothFunction", "class_smooth_function.html#af866864f7e676fa2a9bb91742261a942", null ],
[ "SmoothFunction", "class_smooth_function.html#ab47b4d1be729afadb652b373bfadecf0", null ],
[ "~SmoothFunction", "class_smooth_function.html#af866864f7e676fa2a9bb91742261a942", null ],
[ "add_sample_gradient", "class_smooth_function.html#afe31df508da8008797b0eeae6703f1ca", null ],
[ "add_sample_gradient", "class_smooth_function.html#afe31df508da8008797b0eeae6703f1ca", null ],
[ "add_sample_gradient2", "class_smooth_function.html#aa886ebb7bcde88d7336455900df77706", null ],
[ "add_sample_gradient2", "class_smooth_function.html#aa886ebb7bcde88d7336455900df77706", null ],
[ "add_sample_gradient3", "class_smooth_function.html#ac5c39ab475b56d20ad7dd73dae404d7b", null ],
[ "add_sample_gradient3", "class_smooth_function.html#ac5c39ab475b56d20ad7dd73dae404d7b", null ],
[ "add_scal_grad", "class_smooth_function.html#aeb001785ee984cf091399256ab293440", null ],
[ "add_scal_grad", "class_smooth_function.html#aeb001785ee984cf091399256ab293440", null ],
[ "choose_random_batch", "class_smooth_function.html#ad3e51bea2c8e20802091ee43df81ed0e", null ],
[ "choose_random_batch", "class_smooth_function.html#ad3e51bea2c8e20802091ee43df81ed0e", null ],
[ "choose_random_fixedbatch", "class_smooth_function.html#a9b970e1e1417344cc72a9afc4e3f7e96", null ],
[ "choose_random_fixedbatch", "class_smooth_function.html#a9b970e1e1417344cc72a9afc4e3f7e96", null ],
[ "constantL", "class_smooth_function.html#a41a89c963cbe89fc617c951e2644433b", null ],
[ "constantL", "class_smooth_function.html#a41a89c963cbe89fc617c951e2644433b", null ],
[ "dotprod_gradient3", "class_smooth_function.html#a4ee263d742ce1f12d57a7e7e6e1517c9", null ],
[ "dotprod_gradient3", "class_smooth_function.html#a4ee263d742ce1f12d57a7e7e6e1517c9", null ],
[ "eval", "class_smooth_function.html#aeeb7b9287f6a68372a46de2ef66ff41b", null ],
[ "eval", "class_smooth_function.html#aeeb7b9287f6a68372a46de2ef66ff41b", null ],
[ "eval_block", "class_smooth_function.html#a1a8db0a7643dfe5c8047d311c2b83189", null ],
[ "eval_block", "class_smooth_function.html#a1a8db0a7643dfe5c8047d311c2b83189", null ],
[ "eval_simple", "class_smooth_function.html#aad50b0419e979570abe899a0ec33192f", null ],
[ "eval_simple", "class_smooth_function.html#aad50b0419e979570abe899a0ec33192f", null ],
[ "genericL", "class_smooth_function.html#a950311a2d3c43d9852367bd38a2f64d3", null ],
[ "genericL", "class_smooth_function.html#a950311a2d3c43d9852367bd38a2f64d3", null ],
[ "get_batch", "class_smooth_function.html#abef90434d996534707a62ac71236804f", null ],
[ "get_batch", "class_smooth_function.html#abef90434d996534707a62ac71236804f", null ],
[ "getL", "class_smooth_function.html#ad66cfee8a477318cbb57725c75eaaa89", null ],
[ "getL", "class_smooth_function.html#ad66cfee8a477318cbb57725c75eaaa89", null ],
[ "getY", "class_smooth_function.html#aa3542a8398624a1272a40bbd9c73e25d", null ],
[ "getY", "class_smooth_function.html#aa3542a8398624a1272a40bbd9c73e25d", null ],
[ "gradient_simple", "class_smooth_function.html#a77f13eee8e69be37dd8586a17c0ee536", null ],
[ "gradient_simple", "class_smooth_function.html#a77f13eee8e69be37dd8586a17c0ee536", null ],
[ "n", "class_smooth_function.html#a79868d849424e93dfb2e84284ffbea38", null ],
[ "n", "class_smooth_function.html#a79868d849424e93dfb2e84284ffbea38", null ],
[ "nbatches", "class_smooth_function.html#ac00800b18358e48c5f9457e695c53e31", null ],
[ "nbatches", "class_smooth_function.html#ac00800b18358e48c5f9457e695c53e31", null ],
[ "num_batch", "class_smooth_function.html#ab8cd5e40767af21430daa24d4d9a6997", null ],
[ "num_batch", "class_smooth_function.html#ab8cd5e40767af21430daa24d4d9a6997", null ],
[ "num_batches", "class_smooth_function.html#ad992d39c2a400d01cfd7d7fe31ea58a5", null ],
[ "num_batches", "class_smooth_function.html#ad992d39c2a400d01cfd7d7fe31ea58a5", null ],
[ "p", "class_smooth_function.html#a0b31c126c619eed1e2a5eb95375d7b73", null ],
[ "p", "class_smooth_function.html#a0b31c126c619eed1e2a5eb95375d7b73", null ],
[ "refData", "class_smooth_function.html#ae54a6edeb902bfb404728ac8cfe134a5", null ],
[ "refData", "class_smooth_function.html#ae54a6edeb902bfb404728ac8cfe134a5", null ],
[ "sampleL", "class_smooth_function.html#ae4f0ffc1d899e1c6d33a6beda34827c4", null ],
[ "sampleL", "class_smooth_function.html#ae4f0ffc1d899e1c6d33a6beda34827c4", null ],
[ "scal_grad", "class_smooth_function.html#a8d1463619b590286000c5ac01084dedd", null ],
[ "scal_grad", "class_smooth_function.html#a8d1463619b590286000c5ac01084dedd", null ],
[ "setMiniBatches", "class_smooth_function.html#aace785132377fb4dbba114050aa4e2fe", null ],
[ "setMiniBatches", "class_smooth_function.html#aace785132377fb4dbba114050aa4e2fe", null ],
[ "setRandom", "class_smooth_function.html#ad69ec2dcdd4725456ed6fe7e1c4b446e", null ],
[ "setRandom", "class_smooth_function.html#ad69ec2dcdd4725456ed6fe7e1c4b446e", null ],
[ "subsample", "class_smooth_function.html#a5a7db906265679f8d5587f961e0e4d75", null ],
[ "subsample", "class_smooth_function.html#a5a7db906265679f8d5587f961e0e4d75", null ],
[ "un_subsample", "class_smooth_function.html#ae3e91bb66fcc2f04d232a1a4e5dcb549", null ],
[ "un_subsample", "class_smooth_function.html#ae3e91bb66fcc2f04d232a1a4e5dcb549", null ],
[ "_constantL", "class_smooth_function.html#a10f692e2ddc471aa677ab0c272d09125", null ],
[ "_counter", "class_smooth_function.html#a1ebed438b00564895904a1fdd30db8fc", null ],
[ "_current_batch", "class_smooth_function.html#a28f8686cd96e30fafcd377c736672509", null ],
[ "_genericL", "class_smooth_function.html#a29ecaef50673bf12604426745cbcab35", null ],
[ "_is_normalized", "class_smooth_function.html#a143dda63a382d5d5c9a82e2514155679", null ],
[ "_L", "class_smooth_function.html#ae5685d768717865bb5db873f4df9c683", null ],
[ "_n", "class_smooth_function.html#aa1311b1cd8669d444f40dfd69d1410fb", null ],
[ "_nbatches", "class_smooth_function.html#a9b729ff6038a440a68632c75798c97a8", null ],
[ "_num_batch", "class_smooth_function.html#af8c9b85acc50aa172428f02c07a0848d", null ],
[ "_num_batches", "class_smooth_function.html#a85e94a906ad5e13e7f95808244815da7", null ],
[ "_p", "class_smooth_function.html#a3c8b095ea6f1ae786ce6fbce09cdfaca", null ],
[ "_random", "class_smooth_function.html#af05593bdcf5ee2e04311da9089f35c56", null ],
[ "_save_n", "class_smooth_function.html#a0b1c8e84ecbe0e596b89346a57567d06", null ],
[ "_sizebatch", "class_smooth_function.html#a529618b2e22d0954082f232fdf36b434", null ],
[ "_tmp", "class_smooth_function.html#a32dd89e0f0e502468b649b88db855bc9", null ],
[ "_Xt", "class_smooth_function.html#aabcf2acbf5707fcc57c41d019ccbe9cd", null ],
[ "_y", "class_smooth_function.html#adbb34e7585b5355b9bf34691549e77d4", null ]
]; |
var fs = require('fs');
var parser = require("xdg-parse");
module.exports = function readXdgFile(file){
return fs.promises.readFile(file,{encoding:'utf8'}).then((c)=>parser(c));
}
|
import { Template } from 'meteor/templating';
import './tBlankLayout.html';
Template.tBlankLayout.helpers({
target() {
return this.targetTemplate
}
}); |
import React from 'react';
import IconButton from '@material-ui/core/IconButton';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import Menu from '@material-ui/core/Menu';
import MenuItem from '@material-ui/core/MenuItem';
import MoreVertIcon from '@material-ui/icons/MoreVert';
const styles = {
root: {
margin: '200px 0 200px',
background: 'papayawhip',
padding: '0 100px',
},
};
const options = [
'None',
'Atria',
'Callisto',
'Dione',
'Ganymede',
'Hangouts Call',
'Luna',
'Oberon',
'Phobos',
'Pyxis',
'Sedna',
'Titania',
'Triton',
'Umbriel',
];
const ITEM_HEIGHT = 48;
class LongMenu extends React.Component {
buttonRef = React.createRef();
state = {
anchorEl: null,
};
componentDidMount() {
this.setState({ anchorEl: this.buttonRef.current });
}
render() {
const { classes } = this.props;
const { anchorEl } = this.state;
const open = Boolean(anchorEl);
return (
<div className={classes.root}>
<IconButton
ref={this.buttonRef}
aria-label="more"
aria-owns={open ? 'long-menu' : undefined}
aria-haspopup="true"
onClick={this.handleClick}
>
<MoreVertIcon />
</IconButton>
<Menu
id="long-menu"
anchorEl={anchorEl}
open={open}
PaperProps={{
style: {
maxHeight: ITEM_HEIGHT * 4.5,
width: 200,
},
}}
>
{options.map((option) => (
<MenuItem key={option} selected={option === 'Pyxis'}>
{option}
</MenuItem>
))}
</Menu>
</div>
);
}
}
LongMenu.propTypes = {
classes: PropTypes.object.isRequired,
};
export default withStyles(styles)(LongMenu);
|
import {Utils} from "./Utils.class";
/**
* @class
* @constructor
*/
export class Mesh {
constructor() {
this._obj = {};
this._textures = {};
this.objIndex = null; // for store new indexes
this.indexMax=0;
}
/**
* Load a point
*/
loadPoint() {
this._obj.vertexArray = [0.0, 0.0, 0.0, 0.0];
this._obj.normalArray = [0.0, 1.0, 0.0, 0.0];
this._obj.textureArray = [0.0, 0.0, 0.0, 0.0];
this._obj.textureUnitArray = [0.0];
this._obj.indexArray = [0];
return this._obj;
};
/**
* Load a triangle
* @param {Object} jsonIn
* @param {number} [jsonIn.scale=1.0]
* @param {number} [jsonIn.side=1.0]
*/
loadTriangle(jsonIn) {
let sca = (jsonIn !== undefined && jsonIn.scale !== undefined) ? jsonIn.scale : 1.0;
let side = (jsonIn !== undefined && jsonIn.side !== undefined) ? jsonIn.side : 1.0 ;
this._obj.vertexArray = [ 0.0, 0.0, 0.0, 1.0,
(side/2)*sca, 0.0, -1.0*sca, 1.0,
-(side/2)*sca, 0.0, -1.0*sca, 1.0];
this._obj.normalArray = [ 0.0, 0.0, 1.0, 1.0,
0.0, 0.0, 1.0, 1.0,
0.0, 0.0, 1.0, 1.0];
this._obj.textureArray = [ 0.0, 0.0, 0.0, 1.0,
1.0, 0.0, 0.0, 1.0,
1.0, 1.0, 0.0, 1.0];
this._obj.textureUnitArray = [0.0, 0.0, 0.0];
this._obj.indexArray = [0, 1, 2];
return this._obj;
};
/**
* Load a quad
* @param {number} length
* @param {number} height
* @returns {Object}
*/
loadQuad(length, height) {
let l=(length===undefined)?0.5:length;
let h=(height===undefined)?0.5:height;
this._obj = {};
this._obj.vertexArray = [ -l, -h, 0.0, 1.0,// Front face
l, -h, 0.0, 1.0,
l, h, 0.0, 1.0,
-l, h, 0.0, 1.0];
this._obj.normalArray = [ 0.0, 0.0, 1.0, 1.0,// Front face
0.0, 0.0, 1.0, 1.0,
0.0, 0.0, 1.0, 1.0,
0.0, 0.0, 1.0, 1.0];
this._obj.textureArray = [ 0.0, 0.0, 0.0, 1.0,// Front face
1.0, 0.0, 0.0, 1.0,
1.0, 1.0, 0.0, 1.0,
0.0, 1.0, 0.0, 1.0];
this._obj.textureUnitArray = [0.0,0.0,0.0,0.0];
this._obj.indexArray = [0, 1, 2, 0, 2, 3];// Front face
return this._obj;
};
/**
* Load a circle
* @param {Object} jsonIn
* @param {int} jsonIn.segments
* @param {number} jsonIn.radius
* @returns {Object}
*/
loadCircle(jsonIn) {
this._obj = { "vertexArray": [],
"normalArray": [],
"textureArray": [],
"textureUnitArray": [],
"indexArray": []};
this.objIndex = [];
this.indexMax=0;
let segments = (jsonIn !== undefined && jsonIn.segments !== undefined) ? jsonIn.segments : 6;
let rad = (jsonIn !== undefined && jsonIn.radius !== undefined) ? jsonIn.radius : 0.5;
let stepAngle = 360.0/(segments);
let numSegH = 360.0/stepAngle;
let cos = (function(val) {return Math.cos(new Utils().degToRad(val))}).bind(this);
let sin = (function(val) {return Math.sin(new Utils().degToRad(val))}).bind(this);
for(let h=1, fh = numSegH; h <= fh; h++) {
let currAngleH = stepAngle*h;
// PRIMER TRIÁNGULO
// vertices
let vA1 = $V3([ cos(currAngleH) *rad,
0.0,
sin(currAngleH) *rad]);
let vB1 = $V3([ cos(currAngleH-stepAngle) *rad,
0.0,
sin(currAngleH-stepAngle) *rad]);
let vC1 = $V3([ 0.0, 0.0, 0.0]);
// normales
let norm = vB1.subtract(vA1).cross(vC1.subtract(vA1)).normalize();
// texturas
let tA1 = $V3([currAngleH/360.0, 0.0, 0.0]);
let tB1 = $V3([(currAngleH-stepAngle)/360.0, 0.0, 0.0]);
let tC1 = $V3([0.0, 0.0, 0.0]);
//indices
let indexA = this.testIfInIndices(this._obj, vA1, norm, tA1);
let indexB = this.testIfInIndices(this._obj, vB1, norm, tB1);
let indexC = this.testIfInIndices(this._obj, vC1, norm, tC1);
this._obj.indexArray.push(indexA,indexB,indexC);
}
return this._obj;
};
testIfInIndices(_obj, vA1, norm, tA1) {
let indexA = undefined;
for(let nB = 0, fb = this.objIndex.length; nB < fb; nB++) {
if(this.objIndex[nB].v.e[0] === vA1.e[0] && this.objIndex[nB].v.e[1] === vA1.e[1] && this.objIndex[nB].v.e[2] === vA1.e[2]) {
indexA = this.objIndex[nB].i;
}
}
if(indexA === undefined) {
indexA = this.indexMax;
this.objIndex.push({i:indexA,v:$V3([vA1.e[0],vA1.e[1],vA1.e[2]])});
this.indexMax++;
_obj.vertexArray.push(vA1.e[0],vA1.e[1],vA1.e[2], 1.0);
_obj.normalArray.push(norm.e[0],norm.e[1],norm.e[2], 1.0);
_obj.textureArray.push((vA1.e[0]+0.5),(vA1.e[2]+0.5),vA1.e[2]+0.5, 1.0);
_obj.textureUnitArray.push(0.0);
}
return indexA;
};
/**
* Load a box
* @returns {Object}
*/
loadBox() {
this._obj = {};
let d = new Float32Array([0.5,0.5,0.5]);
this._obj.vertexArray = [ -1.0*d[0], -1.0*d[1], 1.0*d[2], 1.0,// Front face
1.0*d[0], -1.0*d[1], 1.0*d[2], 1.0,
1.0*d[0], 1.0*d[1], 1.0*d[2], 1.0,
-1.0*d[0], 1.0*d[1], 1.0*d[2], 1.0,
// Back face
-1.0*d[0], -1.0*d[1], -1.0*d[2], 1.0,
-1.0*d[0], 1.0*d[1], -1.0*d[2], 1.0,
1.0*d[0], 1.0*d[1], -1.0*d[2], 1.0,
1.0*d[0], -1.0*d[1], -1.0*d[2], 1.0,
// Top face
-1.0*d[0], 1.0*d[1], -1.0*d[2], 1.0,
-1.0*d[0], 1.0*d[1], 1.0*d[2], 1.0,
1.0*d[0], 1.0*d[1], 1.0*d[2], 1.0,
1.0*d[0], 1.0*d[1], -1.0*d[2], 1.0,
// Bottom face
-1.0*d[0], -1.0*d[1], -1.0*d[2], 1.0,
1.0*d[0], -1.0*d[1], -1.0*d[2], 1.0,
1.0*d[0], -1.0*d[1], 1.0*d[2], 1.0,
-1.0*d[0], -1.0*d[1], 1.0*d[2], 1.0,
// Right face
1.0*d[0], -1.0*d[1], -1.0*d[2], 1.0,
1.0*d[0], 1.0*d[1], -1.0*d[2], 1.0,
1.0*d[0], 1.0*d[1], 1.0*d[2], 1.0,
1.0*d[0], -1.0*d[1], 1.0*d[2], 1.0,
// Left face
-1.0*d[0], -1.0*d[1], -1.0*d[2], 1.0,
-1.0*d[0], -1.0*d[1], 1.0*d[2], 1.0,
-1.0*d[0], 1.0*d[1], 1.0*d[2], 1.0,
-1.0*d[0], 1.0*d[1], -1.0*d[2], 1.0];
this._obj.normalArray = [ 0.0, 0.0, 1.0, 1.0,// Front face
0.0, 0.0, 1.0, 1.0,
0.0, 0.0, 1.0, 1.0,
0.0, 0.0, 1.0, 1.0,
// Back face
0.0, 0.0, -1.0, 1.0,
0.0, 0.0, -1.0, 1.0,
0.0, 0.0, -1.0, 1.0,
0.0, 0.0, -1.0, 1.0,
// Top face
0.0, 1.0, 0.0, 1.0,
0.0, 1.0, 0.0, 1.0,
0.0, 1.0, 0.0, 1.0,
0.0, 1.0, 0.0, 1.0,
// Bottom face
0.0, -1.0, 0.0, 1.0,
0.0, -1.0, 0.0, 1.0,
0.0, -1.0, 0.0, 1.0,
0.0, -1.0, 0.0, 1.0,
// Right face
1.0, 0.0, 0.0, 1.0,
1.0, 0.0, 0.0, 1.0,
1.0, 0.0, 0.0, 1.0,
1.0, 0.0, 0.0, 1.0,
// Left face
-1.0, 0.0, 0.0, 1.0,
-1.0, 0.0, 0.0, 1.0,
-1.0, 0.0, 0.0, 1.0,
-1.0, 0.0, 0.0, 1.0];
this._obj.textureArray = [ 0.0, 0.0, 0.0, 1.0,// Front face
1.0, 0.0, 0.0, 1.0,
1.0, 1.0, 0.0, 1.0,
0.0, 1.0, 0.0, 1.0,
// Back face
1.0, 0.0, 0.0, 1.0,
1.0, 1.0, 0.0, 1.0,
0.0, 1.0, 0.0, 1.0,
0.0, 0.0, 0.0, 1.0,
// Top face
0.0, 1.0, 0.0, 1.0,
0.0, 0.0, 0.0, 1.0,
1.0, 0.0, 0.0, 1.0,
1.0, 1.0, 0.0, 1.0,
// Bottom face
1.0, 1.0, 0.0, 1.0,
0.0, 1.0, 0.0, 1.0,
0.0, 0.0, 0.0, 1.0,
1.0, 0.0, 0.0, 1.0,
// Right face
1.0, 0.0, 0.0, 1.0,
1.0, 1.0, 0.0, 1.0,
0.0, 1.0, 0.0, 1.0,
0.0, 0.0, 0.0, 1.0,
// Left face
0.0, 0.0, 0.0, 1.0,
1.0, 0.0, 0.0, 1.0,
1.0, 1.0, 0.0, 1.0,
0.0, 1.0, 0.0, 1.0];
this._obj.textureUnitArray = [ 0.0,0.0,0.0,0.0,// Front face
// Back face
0.0,0.0,0.0,0.0,
// Top face
0.0,0.0,0.0,0.0,
// Bottom face
0.0,0.0,0.0,0.0,
// Right face
0.0,0.0,0.0,0.0,
// Left face
0.0,0.0,0.0,0.0];
this._obj.indexArray = [ 0, 1, 2, 0, 2, 3, // Front face
4, 5, 6, 4, 6, 7, // Back face
8, 9, 10, 8, 10, 11, // Top face
12, 13, 14, 12, 14, 15, // Bottom face
16, 17, 18, 16, 18, 19, // Right face
20, 21, 22, 20, 22, 23]; // Left face
return this._obj;
};
/**
* @typedef {Object} Mesh~ImageData
* @property {int} Mesh~ImageData.fileUrl
* @property {int} Mesh~ImageData.materialName
*/
/**
* This callback is displayed as part of the onSelectNode
* @callback Mesh~loadObj~onload
* @param {Mesh} mesh
* @param {Mesh~ImageData} textures
*/
/**
* Load a object from url of obj file
* @param {String} objUrl
* @param {Mesh~loadObj~onload} onload
*/
loadObj(objUrl, onload) {
let objDirectory = '';
let expl = objUrl.split("/");
for(let n = 0, f = expl.length-1; n < f; n++)
objDirectory = objDirectory+expl[n]+'/';
let req = new XMLHttpRequest();
req.open("GET", objUrl, true);
req.responseType = "blob";
req.onload = (function(onload) {
let filereader = new FileReader();
filereader.onload = (function(onload, event) {
let text = event.target.result;
this.loadObjFromSourceText({"sourceText": text, "objDirectory": objDirectory});
if(onload !== undefined && typeof(onload) === 'function')
onload(this._obj, this._textures);
}).bind(this, onload);
filereader.readAsText(req.response);
}).bind(this, onload);
req.send(null);
};
/**
* Load a object from text-plain on obj format
* @param {Object} jsonIn
* @param {String} jsonIn.sourceText
* @param {String} jsonIn.objDirectory
*/
loadObjFromSourceText(jsonIn) {
this._obj = {};
this._textures = {};
let _node,_sourceText,_objDirectory;
_sourceText = (jsonIn.sourceText !== undefined) ? jsonIn.sourceText : undefined;
_objDirectory = (jsonIn.objDirectory !== undefined) ? jsonIn.objDirectory : undefined;
let lines = _sourceText.split("\r\n");
if(lines.length === 1) lines = _sourceText.split("\n");
if(lines[0].match(/OBJ/gim) == null) {alert('Not OBJ file'); return;}
let vertexArrayX = [];let vertexArrayY = [];let vertexArrayZ = [];
let normalArrayX = [];let normalArrayY = [];let normalArrayZ = [];
let textureArrayX = [];let textureArrayY = [];let textureArrayZ = [];
let textureUnitArray = [];
let currentTextureUnit = 0;
let indexArray = [];
let currentIDX = 0;
let currentIDX_INDEX = 0;
let bufferEnCola = false;
let vertexX = [];let vertexY = [];let vertexZ = [];
let normalX = [];let normalY = [];let normalZ = [];
let textureX = [];let textureY = [];let textureZ = [];
let currentIDX_vertex = 0;let currentIDX_normal = 0;let currentIDX_texture = 0;
let indexVNT = [];
let currentIndex = 0;
let groups = {};
let currentGroup = [-1, 0];
groups["_unnamed"] = currentGroup;
let mtlFile = "";
let currentMtlName = "";
for(let n = 0, f = lines.length; n < f; n++) {
let line = lines[n].replace(/\t+/gi, " ").replace(/\s+$/gi, "").replace(/\s+/gi, " ");
if(line[0] === "#") continue;// ignore comments
let array = line.split(" ");
if(array[0] === "mtllib") {
mtlFile = array[1];
}
if(array[0] === "g") {
currentGroup = [indexArray.length, 0];
groups[array[1]] = currentGroup;
}
if(array[0] === "v") {
vertexX[currentIDX_vertex] = parseFloat(array[1]);
vertexY[currentIDX_vertex] = parseFloat(array[2]);
vertexZ[currentIDX_vertex] = parseFloat(array[3]);
currentIDX_vertex++;
}
if(array[0] === "vn") {
normalX[currentIDX_normal] = parseFloat(array[1]);
normalY[currentIDX_normal] = parseFloat(array[2]);
normalZ[currentIDX_normal] = parseFloat(array[3]);
currentIDX_normal++;
}
if(array[0] === "vt") {
textureX[currentIDX_texture] = parseFloat(array[1]);
textureY[currentIDX_texture] = parseFloat(array[2]);
textureZ[currentIDX_texture] = parseFloat(array[3]);
currentIDX_texture++;
}
if(array[0] === "usemtl") {
currentMtlName = array[1];
this._textures[currentTextureUnit] = { "fileUrl": _objDirectory+mtlFile,
"materialName": currentMtlName};
currentTextureUnit++;
}
if(array[0] === "f") {
if(array.length !== 4)
console.log("*** Error: face '"+line+"' not handled");
// recorremos cada vtx/tex/nor de la linea 'f vtxA/texA/norA vtxB/texB/norB vtxC/texC/norC'
// puede ser tambien de tipo f vtx vtx vtx
for(let i = 1, fi = 4; i < fi; ++i) { // primero vtxA/texA/norA, luego vtxB/texB/norB y luego vtxC/texC/norC
bufferEnCola = true;
let expl = array[i].split("/"); // array[i] = "vtxX/texX/norX"
if(indexVNT[array[i]] === undefined) { //si no existe current "vtxX/texX/norX" en array indexVNT se añade nuevo indice
let vtx, nor, tex;
if(expl.length === 1) { // si es de tipo solo vtx
vtx = parseInt(expl[0]) - 1; // usamos vtx en todos
nor = vtx;
tex = vtx;
} else if(expl.length === 3) { // si es de tipo vtx/tex/nor
vtx = parseInt(expl[0]) - 1;
tex = parseInt(expl[1]) - 1;
nor = parseInt(expl[2]) - 1;
// se resta 1 por que en el formato obj el primero comienza en 1.
// en los arrays donde hemos almacenado vertex, normal y texture el primero comienza en 0.
} else {
//obj.ctx.console.log("*** Error: did not understand face '"+array[i]+"'");
return null;
}
textureUnitArray[currentIDX] = (currentTextureUnit-1);
vertexArrayX[currentIDX] = 0.0;
vertexArrayY[currentIDX] = 0.0;
vertexArrayZ[currentIDX] = 0.0;
if(vtx < vertexZ.length) {
vertexArrayX[currentIDX] = vertexX[vtx];
vertexArrayY[currentIDX] = vertexY[vtx];
vertexArrayZ[currentIDX] = vertexZ[vtx];
}
textureArrayX[currentIDX] = 0.0;
textureArrayY[currentIDX] = 0.0;
textureArrayZ[currentIDX] = 0.0;
if(tex < textureZ.length) {
textureArrayX[currentIDX] = textureX[tex];
textureArrayY[currentIDX] = textureY[tex];
textureArrayZ[currentIDX] = textureZ[tex];
}
normalArrayX[currentIDX] = 0.0;
normalArrayY[currentIDX] = 0.0;
normalArrayZ[currentIDX] = 1.0;
if(nor < normalZ.length) {
normalArrayX[currentIDX] = normalX[nor];
normalArrayY[currentIDX] = normalY[nor];
normalArrayZ[currentIDX] = normalZ[nor];
}
currentIDX++;
indexVNT[array[i]] = currentIndex; // indexVNT[vtxX/texX/norX] = currentIndex;
currentIndex++;
}
indexArray[currentIDX_INDEX] = indexVNT[array[i]];
currentIDX_INDEX++;
currentGroup[1]++;
}
}
}
if(bufferEnCola === true) {
this._obj.vertexArray = new Float32Array(vertexArrayX.length*4);
for(let n = 0, fn = vertexArrayX.length; n < fn; n++) {
let idx = n*4;
this._obj.vertexArray[idx] = vertexArrayX[n];
this._obj.vertexArray[idx+1] = vertexArrayY[n];
this._obj.vertexArray[idx+2] = vertexArrayZ[n];
this._obj.vertexArray[idx+3] = 1.0;
}
this._obj.normalArray = new Float32Array(normalArrayX.length*4);
for(let n = 0, fn = normalArrayX.length; n < fn; n++) {
let idx = n*4;
this._obj.normalArray[idx] = normalArrayX[n];
this._obj.normalArray[idx+1] = normalArrayY[n];
this._obj.normalArray[idx+2] = normalArrayZ[n];
this._obj.normalArray[idx+3] = 1.0;
}
this._obj.textureArray = new Float32Array(textureArrayX.length*4);
for(let n = 0, fn = textureArrayX.length; n < fn; n++) {
let idx = n*4;
this._obj.textureArray[idx] = textureArrayX[n];
this._obj.textureArray[idx+1] = textureArrayY[n];
this._obj.textureArray[idx+2] = textureArrayZ[n];
this._obj.textureArray[idx+3] = 1.0;
}
this._obj.textureUnitArray = textureUnitArray;
this._obj.indexArray = indexArray;
// RESET
/*let bufferEnCola = false;
vertexArrayX = [];vertexArrayY = [];vertexArrayZ = [];
normalArrayX = [];normalArrayY = [];normalArrayZ = [];
textureArrayX = [];textureArrayY = [];textureArrayZ = [];
textureUnitArray = [];
//currentTextureUnit = 0;
indexArray = [];
currentIDX = 0;
currentIDX_INDEX = 0;
//vertexX = [];vertexY = [];vertexZ = [];
//normalX = [];normalY = [];normalZ = [];
//textureX = [];textureY = [];textureZ = [];
//currentIDX_vertex = 0;currentIDX_normal = 0;currentIDX_texture = 0;
indexVNT = [];
currentIndex = 0;*/
}
};
}
global.Mesh = Mesh;
module.exports.Mesh = Mesh; |
export default [
"X-WWW-FORM-URLENCODED",
"FORM-DATA",
"BINARY",
"JSON",
"RAW",
"XML"
] |
"use strict";
const fs = require("fs");
const path = require("path");
const less = require("less");
const baseDir = path.join(__dirname, "app/css");
let cssFiles = fs.readdirSync(baseDir);
var compilingPromises = [];
for (let cssFile of cssFiles) {
if (!path.isAbsolute(cssFile)) {
cssFile = path.join(baseDir, cssFile);
}
if (fs.statSync(cssFile).isDirectory()) {
let subFiles = fs.readdirSync(cssFile);
let deltaPath = path.relative(baseDir, cssFile);
for (let subFile of subFiles) {
cssFiles.push(path.join(baseDir, deltaPath, subFile));
}
continue;
}
if (path.extname(cssFile).toLowerCase() !== ".less")
continue;
console.log(`Compiling: ${cssFile}`);
compilingPromises.push(new Promise(function (resolve, reject) {
fs.readFile(cssFile, "utf8", function (err, data) {
if (err) return reject(err);
less.render(data, {
"paths": [baseDir],
"filename": path.basename(cssFile),
"strictMath": true
}, function (err, output) {
if (err) return reject(err);
let writingPath = path.resolve(path.dirname(cssFile), path.basename(cssFile, ".less") + ".css")
fs.writeFile(writingPath, output.css, "utf8", function (err) {
if (err) return reject(err);
resolve();
});
});
});
}));
}
Promise.all(compilingPromises).then(function () {
console.log("Done compiling");
process.exit(0);
}).catch(function (err) {
console.error("Error compiling:");
console.error("\t" + err.message);
console.error(err);
}); |
Template.storeSlotList.onRendered(function() {
this.$('.ui.dropdown').dropdown();
}); |
console.log('Hello')
console.log('Goodbye')
|
/**
* @fileoverview Tests for wrap-iife rule.
* @author Ilya Volodin
*/
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
var eslintTester = require("eslint-tester");
//------------------------------------------------------------------------------
// Tests
//------------------------------------------------------------------------------
eslintTester.addRuleTest("lib/rules/wrap-iife", {
valid: [
"(function(){ }());",
"(function(){ })();",
"(function a(){ }());",
"(function a(){ })();"
],
invalid: [
{ code: "0, function(){ }();",
errors: [{ message: "Wrap an immediate function invocation in parentheses.", type: "CallExpression"}] },
{ code: "[function(){ }()];",
errors: [{ message: "Wrap an immediate function invocation in parentheses.", type: "CallExpression"}] },
{ code: "var a = function(){ }();",
errors: [{ message: "Wrap an immediate function invocation in parentheses.", type: "CallExpression"}] },
{ code: "(function(){ }(), 0);",
errors: [{ message: "Wrap an immediate function invocation in parentheses.", type: "CallExpression"}] }
]
});
|
var controllers = require('../controllers'),
passport = require('passport');
module.exports = function(app) {
app.get('/login', controllers.authCtrl.login);
app.post('/login', passport.authenticate('local-login', {
successRedirect : '/main',
failureRedirect : '/login',
failureFlash : true
}));
app.get('/logout', controllers.authCtrl.logout);
app.get('/signup', controllers.authCtrl.signup);
app.post('/signup', passport.authenticate('local-signup', {
successRedirect: '/main',
failureRedirect: '/signup',
failureFlash: true
}))
app.get('/main', controllers.authCtrl.isLoggedIn, controllers.userCtrl.getMain);
app.get('/', function(req, res) {
res.render('index.ejs');
})
} |
/*!
* segment-display.js
*
* Copyright 2012, Rüdiger Appel
* http://www.3quarks.com
* Published under Creative Commons 3.0 License.
*
* Date: 2012-02-14
* Version: 1.0.0
*
* Dokumentation: http://www.3quarks.com/de/Segmentanzeige
* Documentation: http://www.3quarks.com/en/SegmentDisplay
*/
// Segment display types
SegmentDisplay.SevenSegment = 7;
SegmentDisplay.FourteenSegment = 14;
SegmentDisplay.SixteenSegment = 16;
// Segment corner types
SegmentDisplay.SymmetricCorner = 0;
SegmentDisplay.SquaredCorner = 1;
SegmentDisplay.RoundedCorner = 2;
function SegmentDisplay(displayId) {
this.displayId = displayId;
this.pattern = '##:##:##';
this.value = '12:34:56';
this.digitHeight = 20;
this.digitWidth = 10;
this.digitDistance = 2.5;
this.displayAngle = 12;
this.segmentWidth = 2.5;
this.segmentDistance = 0.2;
this.segmentCount = SegmentDisplay.SevenSegment;
this.cornerType = SegmentDisplay.RoundedCorner;
this.colorOn = 'rgb(233, 93, 15)';
this.colorOff = 'rgb(75, 30, 5)';
// MS for built in number handling
this.intValue = 0;
this.intMin = 0;
this.intMax = 999999;
this.zeroPad = false;
this.onValueChanged = false;
};
SegmentDisplay.prototype.offsetToDigit = function(offset) {
for (var i = 0; i < this.digitOffsets.length; i++) {
if (this.digitOffsets[i] > offset)
return i - 1;
}
return -1;
}
SegmentDisplay.prototype.onMouseEvent = function(event) {
var lsdigit = this.digitOffsets.length - 2;
var digit = this.offsetToDigit(event.offsetX);
if (digit < 0)
return;
var mult = Math.pow(10, lsdigit - digit);
var newvalue = this.intValue;
if (event.type === 'mousedown') {
if (event.offsetY > event.target.clientHeight / 2)
newvalue -= mult;
else
newvalue += mult;
} else if (event.type === 'mousewheel') {
if (event.wheelDelta < 0)
newvalue -= mult;
else
newvalue += mult;
} else {
console.debug(event);
return;
}
if (newvalue < this.intMin)
newvalue = this.intMin;
if (newvalue > this.intMax)
newvalue = this.intMax;
this.setIntValue(newvalue);
if (this.onValueChanged)
this.onValueChanged(newvalue);
}
SegmentDisplay.prototype.setValue = function(value) {
this.value = value;
this.draw();
};
// Formats an integer value, displayed right-justified and
// ignoring any decimals or colons present in the pattern
SegmentDisplay.prototype.setIntValue = function(value) {
var valuestr = value.toString();
var digit = valuestr.length - 1;
var valueout = "";
for (var i = this.pattern.length - 1; i >= 0; i--) {
if (this.pattern[i] == '#')
if (digit < 0)
valueout = (this.zeroPad ? '0' : ' ') + valueout;
else
valueout = valuestr[digit--] + valueout;
else
valueout = ' ' + valueout;
}
this.intValue = value;
this.setValue(valueout);
};
SegmentDisplay.prototype.enableMouse = function() {
// MS Add event handlers
var display = document.getElementById(this.displayId);
(function(p) {
display.addEventListener("mousewheel", function (event) { p.onMouseEvent(event); });
display.addEventListener("mousedown", function (event) { p.onMouseEvent(event); });
}) (this);
}
SegmentDisplay.prototype.draw = function() {
var display = document.getElementById(this.displayId);
if (display) {
var context = display.getContext('2d');
if (context) {
// clear canvas
context.clearRect(0, 0, display.width, display.height);
// compute and check display width
var width = 0;
var first = true;
if (this.pattern) {
for (var i = 0; i < this.pattern.length; i++) {
var c = this.pattern.charAt(i).toLowerCase();
if (c == '#') {
width += this.digitWidth;
} else if (c == '.' || c == ':') {
width += this.segmentWidth;
} else if (c != ' ') {
return;
}
width += first ? 0 : this.digitDistance;
first = false;
}
}
if (width <= 0) {
return;
}
// compute skew factor
var angle = -1.0 * Math.max(-45.0, Math.min(45.0, this.displayAngle));
var skew = Math.tan((angle * Math.PI) / 180.0);
// compute scale factor
var scale = Math.min(display.width / (width + Math.abs(skew * this.digitHeight)), display.height / this.digitHeight);
// compute display offset
var offsetX = (display.width - (width + skew * this.digitHeight) * scale) / 2.0;
var offsetY = (display.height - this.digitHeight * scale) / 2.0;
// context transformation
context.save();
context.translate(offsetX, offsetY);
context.scale(scale, scale);
context.transform(1, 0, skew, 1, 0, 0);
// draw segments
var xPos = 0;
var size = (this.value) ? this.value.length : 0;
this.digitOffsets = [offsetX]
for (var i = 0; i < this.pattern.length; i++) {
var mask = this.pattern.charAt(i);
var value = (i < size) ? this.value.charAt(i).toLowerCase() : ' ';
xPos += this.drawDigit(context, xPos, mask, value);
if (mask == '#') {
// MS Store digit offsets for mouse handling
this.digitOffsets.push(offsetX + xPos * scale);
}
}
// finish drawing
context.restore();
}
}
};
SegmentDisplay.prototype.drawDigit = function(context, xPos, mask, c) {
switch (mask) {
case '#':
var r = Math.sqrt(this.segmentWidth * this.segmentWidth / 2.0);
var d = Math.sqrt(this.segmentDistance * this.segmentDistance / 2.0);
var e = d / 2.0;
var f = (this.segmentWidth - d) * Math.sin((45.0 * Math.PI) / 180.0);
var g = f / 2.0;
var h = (this.digitHeight - 3.0 * this.segmentWidth) / 2.0;
var w = (this.digitWidth - 3.0 * this.segmentWidth) / 2.0;
var s = this.segmentWidth / 2.0;
var t = this.digitWidth / 2.0;
// draw segment a (a1 and a2 for 16 segments)
if (this.segmentCount == 16) {
var x = xPos;
var y = 0;
context.fillStyle = this.getSegmentColor(c, null, '02356789abcdefgiopqrstz@%');
context.beginPath();
switch (this.cornerType) {
case SegmentDisplay.SymmetricCorner:
context.moveTo(x + s + d, y + s);
context.lineTo(x + this.segmentWidth + d, y);
break;
case SegmentDisplay.SquaredCorner:
context.moveTo(x + s + e, y + s - e);
context.lineTo(x + this.segmentWidth, y);
break;
default:
context.moveTo(x + this.segmentWidth - f, y + this.segmentWidth - f - d);
context.quadraticCurveTo(x + this.segmentWidth - g, y, x + this.segmentWidth, y);
}
context.lineTo(x + t - d - s, y);
context.lineTo(x + t - d, y + s);
context.lineTo(x + t - d - s, y + this.segmentWidth);
context.lineTo(x + this.segmentWidth + d, y + this.segmentWidth);
context.fill();
var x = xPos;
var y = 0;
context.fillStyle = this.getSegmentColor(c, null, '02356789abcdefgiopqrstz@');
context.beginPath();
context.moveTo(x + this.digitWidth - this.segmentWidth - d, y + this.segmentWidth);
context.lineTo(x + t + d + s, y + this.segmentWidth);
context.lineTo(x + t + d, y + s);
context.lineTo(x + t + d + s, y);
switch (this.cornerType) {
case SegmentDisplay.SymmetricCorner:
context.lineTo(x + this.digitWidth - this.segmentWidth - d, y);
context.lineTo(x + this.digitWidth - s - d, y + s);
break;
case SegmentDisplay.SquaredCorner:
context.lineTo(x + this.digitWidth - this.segmentWidth, y);
context.lineTo(x + this.digitWidth - s - e, y + s - e);
break;
default:
context.lineTo(x + this.digitWidth - this.segmentWidth, y);
context.quadraticCurveTo(x + this.digitWidth - this.segmentWidth + g, y, x + this.digitWidth - this.segmentWidth + f, y + this.segmentWidth - f - d);
}
context.fill();
} else {
var x = xPos;
var y = 0;
context.fillStyle = this.getSegmentColor(c, '02356789acefp', '02356789abcdefgiopqrstz@');
context.beginPath();
switch (this.cornerType) {
case SegmentDisplay.SymmetricCorner:
context.moveTo(x + s + d, y + s);
context.lineTo(x + this.segmentWidth + d, y);
context.lineTo(x + this.digitWidth - this.segmentWidth - d, y);
context.lineTo(x + this.digitWidth - s - d, y + s);
break;
case SegmentDisplay.SquaredCorner:
context.moveTo(x + s + e, y + s - e);
context.lineTo(x + this.segmentWidth, y);
context.lineTo(x + this.digitWidth - this.segmentWidth, y);
context.lineTo(x + this.digitWidth - s - e, y + s - e);
break;
default:
context.moveTo(x + this.segmentWidth - f, y + this.segmentWidth - f - d);
context.quadraticCurveTo(x + this.segmentWidth - g, y, x + this.segmentWidth, y);
context.lineTo(x + this.digitWidth - this.segmentWidth, y);
context.quadraticCurveTo(x + this.digitWidth - this.segmentWidth + g, y, x + this.digitWidth - this.segmentWidth + f, y + this.segmentWidth - f - d);
}
context.lineTo(x + this.digitWidth - this.segmentWidth - d, y + this.segmentWidth);
context.lineTo(x + this.segmentWidth + d, y + this.segmentWidth);
context.fill();
}
// draw segment b
x = xPos + this.digitWidth - this.segmentWidth;
y = 0;
context.fillStyle = this.getSegmentColor(c, '01234789adhpy', '01234789abdhjmnopqruwy');
context.beginPath();
switch (this.cornerType) {
case SegmentDisplay.SymmetricCorner:
context.moveTo(x + s, y + s + d);
context.lineTo(x + this.segmentWidth, y + this.segmentWidth + d);
break;
case SegmentDisplay.SquaredCorner:
context.moveTo(x + s + e, y + s + e);
context.lineTo(x + this.segmentWidth, y + this.segmentWidth);
break;
default:
context.moveTo(x + f + d, y + this.segmentWidth - f);
context.quadraticCurveTo(x + this.segmentWidth, y + this.segmentWidth - g, x + this.segmentWidth, y + this.segmentWidth);
}
context.lineTo(x + this.segmentWidth, y + h + this.segmentWidth - d);
context.lineTo(x + s, y + h + this.segmentWidth + s - d);
context.lineTo(x, y + h + this.segmentWidth - d);
context.lineTo(x, y + this.segmentWidth + d);
context.fill();
// draw segment c
x = xPos + this.digitWidth - this.segmentWidth;
y = h + this.segmentWidth;
context.fillStyle = this.getSegmentColor(c, '013456789abdhnouy', '01346789abdghjmnoqsuw@', '%');
context.beginPath();
context.moveTo(x, y + this.segmentWidth + d);
context.lineTo(x + s, y + s + d);
context.lineTo(x + this.segmentWidth, y + this.segmentWidth + d);
context.lineTo(x + this.segmentWidth, y + h + this.segmentWidth - d);
switch (this.cornerType) {
case SegmentDisplay.SymmetricCorner:
context.lineTo(x + s, y + h + this.segmentWidth + s - d);
context.lineTo(x, y + h + this.segmentWidth - d);
break;
case SegmentDisplay.SquaredCorner:
context.lineTo(x + s + e, y + h + this.segmentWidth + s - e);
context.lineTo(x, y + h + this.segmentWidth - d);
break;
default:
context.quadraticCurveTo(x + this.segmentWidth, y + h + this.segmentWidth + g, x + f + d, y + h + this.segmentWidth + f); //
context.lineTo(x, y + h + this.segmentWidth - d);
}
context.fill();
// draw segment d (d1 and d2 for 16 segments)
if (this.segmentCount == 16) {
x = xPos;
y = this.digitHeight - this.segmentWidth;
context.fillStyle = this.getSegmentColor(c, null, '0235689bcdegijloqsuz_=@');
context.beginPath();
context.moveTo(x + this.segmentWidth + d, y);
context.lineTo(x + t - d - s, y);
context.lineTo(x + t - d, y + s);
context.lineTo(x + t - d - s, y + this.segmentWidth);
switch (this.cornerType) {
case SegmentDisplay.SymmetricCorner:
context.lineTo(x + this.segmentWidth + d, y + this.segmentWidth);
context.lineTo(x + s + d, y + s);
break;
case SegmentDisplay.SquaredCorner:
context.lineTo(x + this.segmentWidth, y + this.segmentWidth);
context.lineTo(x + s + e, y + s + e);
break;
default:
context.lineTo(x + this.segmentWidth, y + this.segmentWidth);
context.quadraticCurveTo(x + this.segmentWidth - g, y + this.segmentWidth, x + this.segmentWidth - f, y + f + d);
context.lineTo(x + this.segmentWidth - f, y + f + d);
}
context.fill();
x = xPos;
y = this.digitHeight - this.segmentWidth;
context.fillStyle = this.getSegmentColor(c, null, '0235689bcdegijloqsuz_=@', '%');
context.beginPath();
context.moveTo(x + t + d + s, y + this.segmentWidth);
context.lineTo(x + t + d, y + s);
context.lineTo(x + t + d + s, y);
context.lineTo(x + this.digitWidth - this.segmentWidth - d, y);
switch (this.cornerType) {
case SegmentDisplay.SymmetricCorner:
context.lineTo(x + this.digitWidth - s - d, y + s);
context.lineTo(x + this.digitWidth - this.segmentWidth - d, y + this.segmentWidth);
break;
case SegmentDisplay.SquaredCorner:
context.lineTo(x + this.digitWidth - s - e, y + s + e);
context.lineTo(x + this.digitWidth - this.segmentWidth, y + this.segmentWidth);
break;
default:
context.lineTo(x + this.digitWidth - this.segmentWidth + f, y + f + d);
context.quadraticCurveTo(x + this.digitWidth - this.segmentWidth + g, y + this.segmentWidth, x + this.digitWidth - this.segmentWidth, y + this.segmentWidth);
}
context.fill();
}
else {
x = xPos;
y = this.digitHeight - this.segmentWidth;
context.fillStyle = this.getSegmentColor(c, '0235689bcdelotuy_', '0235689bcdegijloqsuz_=@');
context.beginPath();
context.moveTo(x + this.segmentWidth + d, y);
context.lineTo(x + this.digitWidth - this.segmentWidth - d, y);
switch (this.cornerType) {
case SegmentDisplay.SymmetricCorner:
context.lineTo(x + this.digitWidth - s - d, y + s);
context.lineTo(x + this.digitWidth - this.segmentWidth - d, y + this.segmentWidth);
context.lineTo(x + this.segmentWidth + d, y + this.segmentWidth);
context.lineTo(x + s + d, y + s);
break;
case SegmentDisplay.SquaredCorner:
context.lineTo(x + this.digitWidth - s - e, y + s + e);
context.lineTo(x + this.digitWidth - this.segmentWidth, y + this.segmentWidth);
context.lineTo(x + this.segmentWidth, y + this.segmentWidth);
context.lineTo(x + s + e, y + s + e);
break;
default:
context.lineTo(x + this.digitWidth - this.segmentWidth + f, y + f + d);
context.quadraticCurveTo(x + this.digitWidth - this.segmentWidth + g, y + this.segmentWidth, x + this.digitWidth - this.segmentWidth, y + this.segmentWidth);
context.lineTo(x + this.segmentWidth, y + this.segmentWidth);
context.quadraticCurveTo(x + this.segmentWidth - g, y + this.segmentWidth, x + this.segmentWidth - f, y + f + d);
context.lineTo(x + this.segmentWidth - f, y + f + d);
}
context.fill();
}
// draw segment e
x = xPos;
y = h + this.segmentWidth;
context.fillStyle = this.getSegmentColor(c, '0268abcdefhlnoprtu', '0268acefghjklmnopqruvw@');
context.beginPath();
context.moveTo(x, y + this.segmentWidth + d);
context.lineTo(x + s, y + s + d);
context.lineTo(x + this.segmentWidth, y + this.segmentWidth + d);
context.lineTo(x + this.segmentWidth, y + h + this.segmentWidth - d);
switch (this.cornerType) {
case SegmentDisplay.SymmetricCorner:
context.lineTo(x + s, y + h + this.segmentWidth + s - d);
context.lineTo(x, y + h + this.segmentWidth - d);
break;
case SegmentDisplay.SquaredCorner:
context.lineTo(x + s - e, y + h + this.segmentWidth + s - d + e);
context.lineTo(x, y + h + this.segmentWidth);
break;
default:
context.lineTo(x + this.segmentWidth - f - d, y + h + this.segmentWidth + f);
context.quadraticCurveTo(x, y + h + this.segmentWidth + g, x, y + h + this.segmentWidth);
}
context.fill();
// draw segment f
x = xPos;
y = 0;
context.fillStyle = this.getSegmentColor(c, '045689abcefhlpty', '045689acefghklmnopqrsuvwy@', '%');
context.beginPath();
context.moveTo(x + this.segmentWidth, y + this.segmentWidth + d);
context.lineTo(x + this.segmentWidth, y + h + this.segmentWidth - d);
context.lineTo(x + s, y + h + this.segmentWidth + s - d);
context.lineTo(x, y + h + this.segmentWidth - d);
switch (this.cornerType) {
case SegmentDisplay.SymmetricCorner:
context.lineTo(x, y + this.segmentWidth + d);
context.lineTo(x + s, y + s + d);
break;
case SegmentDisplay.SquaredCorner:
context.lineTo(x, y + this.segmentWidth);
context.lineTo(x + s - e, y + s + e);
break;
default:
context.lineTo(x, y + this.segmentWidth);
context.quadraticCurveTo(x, y + this.segmentWidth - g, x + this.segmentWidth - f - d, y + this.segmentWidth - f);
context.lineTo(x + this.segmentWidth - f - d, y + this.segmentWidth - f);
}
context.fill();
// draw segment g for 7 segments
if (this.segmentCount == 7) {
x = xPos;
y = (this.digitHeight - this.segmentWidth) / 2.0;
context.fillStyle = this.getSegmentColor(c, '2345689abdefhnoprty-=');
context.beginPath();
context.moveTo(x + s + d, y + s);
context.lineTo(x + this.segmentWidth + d, y);
context.lineTo(x + this.digitWidth - this.segmentWidth - d, y);
context.lineTo(x + this.digitWidth - s - d, y + s);
context.lineTo(x + this.digitWidth - this.segmentWidth - d, y + this.segmentWidth);
context.lineTo(x + this.segmentWidth + d, y + this.segmentWidth);
context.fill();
}
// draw inner segments for the fourteen- and sixteen-segment-display
if (this.segmentCount != 7) {
// draw segment g1
x = xPos;
y = (this.digitHeight - this.segmentWidth) / 2.0;
context.fillStyle = this.getSegmentColor(c, null, '2345689aefhkprsy-+*=', '%');
context.beginPath();
context.moveTo(x + s + d, y + s);
context.lineTo(x + this.segmentWidth + d, y);
context.lineTo(x + t - d - s, y);
context.lineTo(x + t - d, y + s);
context.lineTo(x + t - d - s, y + this.segmentWidth);
context.lineTo(x + this.segmentWidth + d, y + this.segmentWidth);
context.fill();
// draw segment g2
x = xPos;
y = (this.digitHeight - this.segmentWidth) / 2.0;
context.fillStyle = this.getSegmentColor(c, null, '234689abefghprsy-+*=@', '%');
context.beginPath();
context.moveTo(x + t + d, y + s);
context.lineTo(x + t + d + s, y);
context.lineTo(x + this.digitWidth - this.segmentWidth - d, y);
context.lineTo(x + this.digitWidth - s - d, y + s);
context.lineTo(x + this.digitWidth - this.segmentWidth - d, y + this.segmentWidth);
context.lineTo(x + t + d + s, y + this.segmentWidth);
context.fill();
// draw segment j
x = xPos + t - s;
y = 0;
context.fillStyle = this.getSegmentColor(c, null, 'bdit+*', '%');
context.beginPath();
if (this.segmentCount == 14) {
context.moveTo(x, y + this.segmentWidth + this.segmentDistance);
context.lineTo(x + this.segmentWidth, y + this.segmentWidth + this.segmentDistance);
} else {
context.moveTo(x, y + this.segmentWidth + d);
context.lineTo(x + s, y + s + d);
context.lineTo(x + this.segmentWidth, y + this.segmentWidth + d);
}
context.lineTo(x + this.segmentWidth, y + h + this.segmentWidth - d);
context.lineTo(x + s, y + h + this.segmentWidth + s - d);
context.lineTo(x, y + h + this.segmentWidth - d);
context.fill();
// draw segment m
x = xPos + t - s;
y = this.digitHeight;
context.fillStyle = this.getSegmentColor(c, null, 'bdity+*@', '%');
context.beginPath();
if (this.segmentCount == 14) {
context.moveTo(x, y - this.segmentWidth - this.segmentDistance);
context.lineTo(x + this.segmentWidth, y - this.segmentWidth - this.segmentDistance);
} else {
context.moveTo(x, y - this.segmentWidth - d);
context.lineTo(x + s, y - s - d);
context.lineTo(x + this.segmentWidth, y - this.segmentWidth - d);
}
context.lineTo(x + this.segmentWidth, y - h - this.segmentWidth + d);
context.lineTo(x + s, y - h - this.segmentWidth - s + d);
context.lineTo(x, y - h - this.segmentWidth + d);
context.fill();
// draw segment h
x = xPos + this.segmentWidth;
y = this.segmentWidth;
context.fillStyle = this.getSegmentColor(c, null, 'mnx\\*');
context.beginPath();
context.moveTo(x + this.segmentDistance, y + this.segmentDistance);
context.lineTo(x + this.segmentDistance + r, y + this.segmentDistance);
context.lineTo(x + w - this.segmentDistance , y + h - this.segmentDistance - r);
context.lineTo(x + w - this.segmentDistance , y + h - this.segmentDistance);
context.lineTo(x + w - this.segmentDistance - r , y + h - this.segmentDistance);
context.lineTo(x + this.segmentDistance, y + this.segmentDistance + r);
context.fill();
// draw segment k
x = xPos + w + 2.0 * this.segmentWidth;
y = this.segmentWidth;
context.fillStyle = this.getSegmentColor(c, null, '0kmvxz/*', '%');
context.beginPath();
context.moveTo(x + w - this.segmentDistance, y + this.segmentDistance);
context.lineTo(x + w - this.segmentDistance, y + this.segmentDistance + r);
context.lineTo(x + this.segmentDistance + r, y + h - this.segmentDistance);
context.lineTo(x + this.segmentDistance, y + h - this.segmentDistance);
context.lineTo(x + this.segmentDistance, y + h - this.segmentDistance - r);
context.lineTo(x + w - this.segmentDistance - r, y + this.segmentDistance);
context.fill();
// draw segment l
x = xPos + w + 2.0 * this.segmentWidth;
y = h + 2.0 * this.segmentWidth;
context.fillStyle = this.getSegmentColor(c, null, '5knqrwx\\*');
context.beginPath();
context.moveTo(x + this.segmentDistance, y + this.segmentDistance);
context.lineTo(x + this.segmentDistance + r, y + this.segmentDistance);
context.lineTo(x + w - this.segmentDistance , y + h - this.segmentDistance - r);
context.lineTo(x + w - this.segmentDistance , y + h - this.segmentDistance);
context.lineTo(x + w - this.segmentDistance - r , y + h - this.segmentDistance);
context.lineTo(x + this.segmentDistance, y + this.segmentDistance + r);
context.fill();
// draw segment n
x = xPos + this.segmentWidth;
y = h + 2.0 * this.segmentWidth;
context.fillStyle = this.getSegmentColor(c, null, '0vwxz/*', '%');
context.beginPath();
context.moveTo(x + w - this.segmentDistance, y + this.segmentDistance);
context.lineTo(x + w - this.segmentDistance, y + this.segmentDistance + r);
context.lineTo(x + this.segmentDistance + r, y + h - this.segmentDistance);
context.lineTo(x + this.segmentDistance, y + h - this.segmentDistance);
context.lineTo(x + this.segmentDistance, y + h - this.segmentDistance - r);
context.lineTo(x + w - this.segmentDistance - r, y + this.segmentDistance);
context.fill();
}
return this.digitDistance + this.digitWidth;
case '.':
context.fillStyle = (c == '#') || (c == '.') ? this.colorOn : this.colorOff;
this.drawPoint(context, xPos, this.digitHeight - this.segmentWidth, this.segmentWidth);
return this.digitDistance + this.segmentWidth;
case ':':
context.fillStyle = (c == '#') || (c == ':') ? this.colorOn : this.colorOff;
var y = (this.digitHeight - this.segmentWidth) / 2.0 - this.segmentWidth;
this.drawPoint(context, xPos, y, this.segmentWidth);
this.drawPoint(context, xPos, y + 2.0 * this.segmentWidth, this.segmentWidth);
return this.digitDistance + this.segmentWidth;
default:
return this.digitDistance;
}
};
SegmentDisplay.prototype.drawPoint = function(context, x1, y1, size) {
var x2 = x1 + size;
var y2 = y1 + size;
var d = size / 4.0;
context.beginPath();
context.moveTo(x2 - d, y1);
context.quadraticCurveTo(x2, y1, x2, y1 + d);
context.lineTo(x2, y2 - d);
context.quadraticCurveTo(x2, y2, x2 - d, y2);
context.lineTo(x1 + d, y2);
context.quadraticCurveTo(x1, y2, x1, y2 - d);
context.lineTo(x1, y1 + d);
context.quadraticCurveTo(x1, y1, x1 + d, y1);
context.fill();
};
SegmentDisplay.prototype.getSegmentColor = function(c, charSet7, charSet14, charSet16) {
if (c == '#') {
return this.colorOn;
} else {
switch (this.segmentCount) {
case 7: return (charSet7.indexOf(c) == -1) ? this.colorOff : this.colorOn;
case 14: return (charSet14.indexOf(c) == -1) ? this.colorOff : this.colorOn;
case 16: var pattern = charSet14 + (charSet16 === undefined ? '' : charSet16);
return (pattern.indexOf(c) == -1) ? this.colorOff : this.colorOn;
default: return this.colorOff;
}
}
};
|
// To run this file, type the following on your command prompt:
// node exercise01.js
// console.log is used for printing out text.
console.log("Hello World!");
console.log("Hello Again");
console.log("I like typing this.");
console.log("This is fun.");
console.log('Yay! Printing.');
console.log("I'd much rather you 'not'.");
console.log('I "said" do not touch this.'); |
import React from 'react';
import PropTypes from 'prop-types';
import { defineMessages, FormattedMessage } from 'react-intl';
import { graphql } from 'react-apollo';
import gql from 'graphql-tag';
import withIntl from '../../../lib/withIntl';
import Avatar from '../../../components/Avatar';
import { capitalize, formatCurrency } from '../../../lib/utils';
import Link from '../../../components/Link';
import SmallButton from '../../../components/SmallButton';
import Moment from '../../../components/Moment';
import AmountCurrency from './AmountCurrency';
import ExpenseDetails from './ExpenseDetails';
import ApproveExpenseBtn from './ApproveExpenseBtn';
import RejectExpenseBtn from './RejectExpenseBtn';
import PayExpenseBtn from './PayExpenseBtn';
import EditPayExpenseFeesForm from './EditPayExpenseFeesForm';
import colors from '../../../constants/colors';
class Expense extends React.Component {
static propTypes = {
collective: PropTypes.object,
host: PropTypes.object,
expense: PropTypes.object,
view: PropTypes.string, // "compact" for homepage (can't edit expense, don't show header), "summary" for list view, "details" for details view
editable: PropTypes.bool,
includeHostedCollectives: PropTypes.bool,
LoggedInUser: PropTypes.object,
allowPayAction: PropTypes.bool,
lockPayAction: PropTypes.func,
unlockPayAction: PropTypes.func,
};
constructor(props) {
super(props);
this.state = {
modified: false,
expense: {},
mode: undefined,
};
this.save = this.save.bind(this);
this.handleChange = this.handleChange.bind(this);
this.toggleDetails = this.toggleDetails.bind(this);
this.toggleEdit = this.toggleEdit.bind(this);
this.messages = defineMessages({
pending: { id: 'expense.pending', defaultMessage: 'pending' },
paid: { id: 'expense.paid', defaultMessage: 'paid' },
approved: { id: 'expense.approved', defaultMessage: 'approved' },
rejected: { id: 'expense.rejected', defaultMessage: 'rejected' },
closeDetails: {
id: 'expense.closeDetails',
defaultMessage: 'Close Details',
},
edit: { id: 'expense.edit', defaultMessage: 'edit' },
cancelEdit: { id: 'expense.cancelEdit', defaultMessage: 'cancel edit' },
viewDetails: {
id: 'expense.viewDetails',
defaultMessage: 'View Details',
},
});
this.currencyStyle = {
style: 'currency',
currencyDisplay: 'symbol',
minimumFractionDigits: 2,
maximumFractionDigits: 2,
};
}
toggleDetails() {
this.setState({
mode: this.state.mode === 'details' ? 'summary' : 'details',
});
}
cancelEdit() {
this.setState({ modified: false, mode: 'details' });
}
edit() {
this.setState({ modified: false, mode: 'edit' });
}
toggleEdit() {
this.state.mode === 'edit' ? this.cancelEdit() : this.edit();
}
handleChange(obj) {
const newState = { ...this.state, modified: true, ...obj };
this.setState(newState);
}
async save() {
const expense = {
id: this.props.expense.id,
...this.state.expense,
};
await this.props.editExpense(expense);
this.setState({ modified: false, mode: 'details' });
}
render() {
const { intl, collective, host, expense, includeHostedCollectives, LoggedInUser, editable } = this.props;
if (!expense.fromCollective) {
console.error('No FromCollective for expense', expense);
return <div />;
}
const title = expense.description;
const status = expense.status.toLowerCase();
const view = this.props.view || 'summary';
let { mode } = this.state;
if (editable && LoggedInUser && !mode) {
switch (expense.status) {
case 'PENDING':
mode = LoggedInUser.canApproveExpense(expense) && 'details';
break;
case 'APPROVED':
mode = LoggedInUser.canPayExpense(expense) && 'details';
break;
}
}
mode = mode || view;
const canPay = LoggedInUser && LoggedInUser.canPayExpense(expense) && expense.status === 'APPROVED';
const canReject =
LoggedInUser &&
LoggedInUser.canApproveExpense(expense) &&
(expense.status === 'PENDING' ||
(expense.status === 'APPROVED' &&
(Date.now() - new Date(expense.updatedAt).getTime() < 60 * 1000 * 15 || // admin of collective can reject the expense for up to 10mn after approving it
LoggedInUser.canEditCollective(collective.host))));
const canApprove =
LoggedInUser &&
LoggedInUser.canApproveExpense(expense) &&
(expense.status === 'PENDING' ||
(expense.status === 'REJECTED' && Date.now() - new Date(expense.updatedAt).getTime() < 60 * 1000 * 15)); // we can approve an expense for up to 10mn after rejecting it
return (
<div className={`expense ${status} ${this.state.mode}View`}>
<style jsx>
{`
.expense {
width: 100%;
margin: 0.5em 0;
padding: 0.5em;
transition: max-height 1s cubic-bezier(0.25, 0.46, 0.45, 0.94);
overflow: hidden;
position: relative;
display: flex;
}
.ExpenseId {
color: ${colors.gray};
margin-left: 0.5rem;
}
.expense.detailsView {
background-color: #fafafa;
}
a {
cursor: pointer;
}
.fromCollective {
float: left;
margin-right: 1.6rem;
}
.body {
overflow: hidden;
font-size: 1.4rem;
width: 100%;
}
.description {
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
display: block;
}
.meta {
color: #919599;
font-size: 1.2rem;
}
.meta .metaItem {
margin: 0 0.2rem;
}
.meta .collective {
margin-right: 0.2rem;
}
.amount .balance {
font-size: 1.2rem;
color: #919599;
}
.amount {
margin-left: 0.5rem;
text-align: right;
font-size: 1.5rem;
font-weight: 300;
}
.rejected .status {
color: #e21a60;
}
.approved .status {
color: #72ce00;
}
.status {
text-transform: uppercase;
}
.actions > div {
align-items: flex-end;
display: flex;
flex-wrap: wrap;
margin: 0.5rem 0;
}
.actions .leftColumn {
width: 72px;
margin-right: 1rem;
float: left;
}
.expenseActions {
display: flex;
}
.expenseActions :global(> div) {
margin-right: 0.5rem;
}
@media (max-width: 600px) {
.expense {
max-height: 50rem;
padding: 2rem 0.5rem;
}
.expense.detailsView {
max-height: 45rem;
}
.details {
max-height: 30rem;
}
}
`}
</style>
<style jsx global>
{`
.expense .actions > div > div {
margin-right: 0.5rem;
}
@media screen and (max-width: 700px) {
.expense .PayExpenseBtn ~ .RejectExpenseBtn {
flex-grow: 1;
}
.expense .SmallButton {
flex-grow: 1;
margin-top: 1rem;
}
.expense .SmallButton button {
width: 100%;
}
}
`}
</style>
<div className="fromCollective">
<Link
route="collective"
params={{ slug: expense.fromCollective.slug }}
title={expense.fromCollective.name}
passHref
>
<Avatar
src={expense.fromCollective.image}
type={expense.fromCollective.type}
name={expense.fromCollective.name}
key={expense.fromCollective.id}
radius={40}
className="noFrame"
/>
</Link>
</div>
<div className="body">
<div className="header">
<div className="amount pullRight">
<AmountCurrency amount={-expense.amount} currency={expense.currency} />
</div>
<div className="description">
<Link route={`/${collective.slug}/expenses/${expense.id}`} title={capitalize(title)}>
{capitalize(title)}
{view !== 'compact' && <span className="ExpenseId">#{expense.id}</span>}
</Link>
</div>
<div className="meta">
<Moment relative={true} value={expense.incurredAt} />
{' | '}
{includeHostedCollectives && (
<span className="collective">
<Link route={`/${expense.collective.slug}`}>{expense.collective.slug}</Link> (balance:{' '}
{formatCurrency(expense.collective.stats.balance, expense.collective.currency)}){' | '}
</span>
)}
<span className="status">{intl.formatMessage(this.messages[status])}</span>
{' | '}
<span className="metaItem">
<Link
route="expenses"
params={{
collectiveSlug: expense.collective.slug,
filter: 'categories',
value: expense.category,
}}
scroll={false}
>
{capitalize(expense.category)}
</Link>
</span>
{editable && LoggedInUser && LoggedInUser.canEditExpense(expense) && (
<span>
{' | '}
<a className="toggleEditExpense" onClick={this.toggleEdit}>
{intl.formatMessage(this.messages[`${mode === 'edit' ? 'cancelEdit' : 'edit'}`])}
</a>
</span>
)}
{mode !== 'edit' && view === 'summary' && (
<span>
{' | '}
<a className="toggleDetails" onClick={this.toggleDetails}>
{intl.formatMessage(this.messages[`${mode === 'details' ? 'closeDetails' : 'viewDetails'}`])}
</a>
</span>
)}
</div>
</div>
<ExpenseDetails
LoggedInUser={LoggedInUser}
expense={expense}
collective={collective}
onChange={expense => this.handleChange({ expense })}
mode={mode}
/>
{editable && (
<div className="actions">
{mode === 'edit' && this.state.modified && (
<div>
<div className="leftColumn" />
<div className="rightColumn">
<SmallButton className="primary save" onClick={this.save}>
<FormattedMessage id="expense.save" defaultMessage="save" />
</SmallButton>
</div>
</div>
)}
{mode !== 'edit' && (canPay || canApprove || canReject) && (
<div className="manageExpense">
{canPay && expense.payoutMethod === 'other' && (
<EditPayExpenseFeesForm
canEditPlatformFee={LoggedInUser.isRoot()}
currency={collective.currency}
onChange={fees => this.handleChange({ fees })}
/>
)}
<div className="expenseActions">
{canPay && (
<PayExpenseBtn
expense={expense}
collective={collective}
host={host}
{...this.state.fees}
disabled={!this.props.allowPayAction}
lock={this.props.lockPayAction}
unlock={this.props.unlockPayAction}
/>
)}
{canApprove && <ApproveExpenseBtn id={expense.id} />}
{canReject && <RejectExpenseBtn id={expense.id} />}
</div>
</div>
)}
</div>
)}
</div>
</div>
);
}
}
const editExpenseQuery = gql`
mutation editExpense($expense: ExpenseInputType!) {
editExpense(expense: $expense) {
id
description
amount
attachment
category
privateMessage
payoutMethod
status
}
}
`;
const addMutation = graphql(editExpenseQuery, {
props: ({ mutate }) => ({
editExpense: async expense => {
return await mutate({ variables: { expense } });
},
}),
});
export default withIntl(addMutation(Expense));
|
var browserSync = require('./browser-sync.js')
var paths = require('./paths.js');
module.exports = function () {
browserSync.init({
server: {
baseDir: paths.rootDir
},
open: 'local'
});
};
|
class Controller {
constructor(dataService, templateLoader, notificator, validator, utils) {
if (typeof validator !== 'object' || validator === null) {
throw new Error("Validator must be a valid object!");
}
this.validator = validator;
this.dataService = dataService;
this.templateLoader = templateLoader;
this.notificator = notificator;
this.utils = utils;
}
get dataService() {
return this._dataService;
}
set dataService(x) {
this.validator.validateNullObject(x, "User data service must not be null");
this._dataService = x;
}
get templateLoader() {
return this._templateLoader;
}
set templateLoader(x) {
this.validator.validateNullObject(x, "Template loader must not be null");
this._templateLoader = x;
}
get notificator() {
return this._notificator;
}
set notificator(x) {
this.validator.validateNullObject(x, "Notificator must not be null");
this._notificator = x;
}
get utils() {
return this._utils;
}
set utils(x) {
this.validator.validateNullObject(x, "Utils must not be null");
this._utils = x;
}
}
export { Controller }; |
// AMD Wrapper Header
define(function(require, exports, module) {
// moment.js language configuration
// language : esperanto (eo)
// author : Colin Dean : https://github.com/colindean
// komento: Mi estas malcerta se mi korekte traktis akuzativojn en tiu traduko.
// Se ne, bonvolu korekti kaj avizi min por ke mi povas lerni!
require('../moment').lang('eo', {
months : "januaro_februaro_marto_aprilo_majo_junio_julio_aŭgusto_septembro_oktobro_novembro_decembro".split("_"),
monthsShort : "jan_feb_mar_apr_maj_jun_jul_aŭg_sep_okt_nov_dec".split("_"),
weekdays : "Dimanĉo_Lundo_Mardo_Merkredo_Ĵaŭdo_Vendredo_Sabato".split("_"),
weekdaysShort : "Dim_Lun_Mard_Merk_Ĵaŭ_Ven_Sab".split("_"),
weekdaysMin : "Di_Lu_Ma_Me_Ĵa_Ve_Sa".split("_"),
longDateFormat : {
LT : "HH:mm",
L : "YYYY-MM-DD",
LL : "D-\\an \\de MMMM, YYYY",
LLL : "D-\\an \\de MMMM, YYYY LT",
LLLL : "dddd, \\l\\a D-\\an \\d\\e MMMM, YYYY LT"
},
meridiem : function (hours, minutes, isLower) {
if (hours > 11) {
return isLower ? 'p.t.m.' : 'P.T.M.';
} else {
return isLower ? 'a.t.m.' : 'A.T.M.';
}
},
calendar : {
sameDay : '[Hodiaŭ je] LT',
nextDay : '[Morgaŭ je] LT',
nextWeek : 'dddd [je] LT',
lastDay : '[Hieraŭ je] LT',
lastWeek : '[pasinta] dddd [je] LT',
sameElse : 'L'
},
relativeTime : {
future : "je %s",
past : "antaŭ %s",
s : "sekundoj",
m : "minuto",
mm : "%d minutoj",
h : "horo",
hh : "%d horoj",
d : "tago",//ne 'diurno', ĉar estas uzita por proksimumo
dd : "%d tagoj",
M : "monato",
MM : "%d monatoj",
y : "jaro",
yy : "%d jaroj"
},
ordinal : "%da",
week : {
dow : 1, // Monday is the first day of the week.
doy : 7 // The week that contains Jan 1st is the first week of the year.
}
});
// AMD Wrapper Footer
});
|
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Copyright 2012, 2013 Matthew Jaquish
// Licensed under The MIT License
// http://opensource.org/licenses/MIT
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/*
* A behavior object.
*
*/
define(['kokou/emitter', 'kokou/sorted-table', './registry'],
function (emitter, table, registry) {
var behavior = {};
var module = {};
var objCount = 0;
var behaviorRegistry = registry.create().initRegistry();
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Behavior mixin.
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
var asBehavior = (function () {
/*
* Config object:
* name : String // the behavior's name
* entity : Object<entity> // the parent entity object
* emitter: Object<emitter> // optional emitter to use for events
*/
function initBehavior(config) {
config = config || {};
this.data.name = config.name || 'defaultBehaviorName';
this.data.entity = config.entity || null;
this.data.emitter = config.emitter || emitter.create({});
this.data.id = this.data.name + '-' + (objCount += 1);
behaviorRegistry.add( this.data.id, this );
return this;
}
/*
* Tell the behavior to terminate itself and clean up.
*/
function terminateBehavior() {
// override to implement specific behavior.
}
/*
* Tell the behavior to bind to any events it is interested in.
*/
function bindBehaviorEvents() {
// override to implement specific behavior.
}
/*
* Tell the behavior to unbind from its events.
*/
function unbindBehaviorEvents() {
// override to implement specific behavior.
}
return function () {
this.initBehavior = initBehavior;
this.terminateBehavior = terminateBehavior;
this.bindBehaviorEvents = bindBehaviorEvents;
this.unbindBehaviorEvents = unbindBehaviorEvents;
};
} ());
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Prototype.
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
asBehavior.call(behavior);
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Factory function
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
function create(config) {
// Create a new instance of an attribute.
var obj = Object.create(behavior);
config = ( typeof config === 'object' ) ? config : null ;
if ( config !== null ) {
obj.initBehavior(config);
}
return obj;
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Public module.
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
module.create = create; // factory function
module.asBehavior = asBehavior; // mixin
module.registry = behaviorRegistry; // registry of all behaviors
return module;
});
|
import React from 'react';
import { View, ActivityIndicator, StyleSheet } from 'react-native';
const LoadingIcon = props => {
return(
<View style={styles.loadingContainer}>
<ActivityIndicator
size={props.size || 'large'}
/>
</View>
);
};
export { LoadingIcon };
const styles = StyleSheet.create({
loadingContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center'
}
});
|
import { app } from 'electron';
import jetpack from 'fs-jetpack';
const userDataDir = jetpack.cwd(app.getPath('userData'));
const filename = 'settings.json';
export class AppSettings {
constructor() {
this.settings = {
isGroupNotificationsEnabled: false,
isGroupFlashTaskbarEnabled: false,
isGroupNotificationSoundEnabled: false,
isDirectNotificationsEnabled: true,
isDirectFlashTaskbarEnabled: true,
isDirectNotificationSoundEnabled: false,
};
}
isGroupNotificationSoundEnabled() {
return this.settings.isGroupNotificationSoundEnabled;
}
toggleGroupNotificationSoundEnabled() {
this.settings.isGroupNotificationSoundEnabled = !this.settings
.isGroupNotificationSoundEnabled;
}
isGroupFlashTaskbarEnabled() {
return this.settings.isGroupFlashTaskbarEnabled;
}
toggleGroupFlashTaskbarEnabled() {
this.settings.isGroupFlashTaskbarEnabled = !this.settings.isGroupFlashTaskbarEnabled;
}
isDirectNotificationSoundEnabled() {
return this.settings.isDirectNotificationSoundEnabled;
}
toggleDirectNotificationSoundEnabled() {
this.settings.isDirectNotificationSoundEnabled = !this.settings
.isDirectNotificationSoundEnabled;
}
isGroupNotificationsEnabled() {
return this.settings.isGroupNotificationsEnabled;
}
toggleGroupNotificationsEnabled() {
this.settings.isGroupNotificationsEnabled = !this.settings.isGroupNotificationsEnabled;
}
isDirectNotificationsEnabled() {
return this.settings.isDirectNotificationsEnabled;
}
toggleDirectNotificationsEnabled() {
this.settings.isDirectNotificationsEnabled = !this.settings.isDirectNotificationsEnabled;
}
isDirectFlashTaskbarEnabled() {
return this.settings.isDirectFlashTaskbarEnabled;
}
toggleDirectFlashTaskbarEnabled() {
this.settings.isDirectFlashTaskbarEnabled = !this.settings.isDirectFlashTaskbarEnabled;
}
initialize() {
var savedSettings = {};
try {
savedSettings = userDataDir.read(filename, 'json');
} catch (err) {}
Object.assign(this.settings, savedSettings);
}
save() {
userDataDir.write(filename, this.settings, { atomic: true });
}
}
|
import React from 'react';
import cx from 'classnames';
import additionalProps from '../util/additionalProps';
export default ({
className,
data,
x = 0,
y = 0,
width,
height,
rx,
ry,
fill = 'steelblue',
fillOpacity,
stroke,
strokeWidth,
strokeDasharray,
strokeLinecap,
strokeLinejoin,
strokeMiterlimit,
strokeOpacity,
...restProps,
}) => {
return (
<rect
className={cx('vx-bar', className)}
x={x}
y={y}
width={width}
height={height}
rx={rx}
ry={ry}
fill={fill}
fillOpacity={fillOpacity}
stroke={stroke}
strokeWidth={strokeWidth}
strokeDasharray={strokeDasharray}
strokeLinecap={strokeLinecap}
strokeLinejoin={strokeLinejoin}
strokeMiterlimit={strokeMiterlimit}
strokeOpacity={strokeOpacity}
{...additionalProps(restProps, data)}
/>
);
}
|
define(["./Matrix2-c6c16658","./when-4bbc8319","./EllipseGeometry-5510aad8","./RuntimeError-5b082e8f","./ComponentDatatype-3d0a0aac","./WebGLConstants-508b9636","./GeometryOffsetAttribute-821af768","./Transforms-f15de320","./combine-e9466e32","./EllipseGeometryLibrary-a4ac7ccc","./GeometryAttribute-8350368e","./GeometryAttributes-7827a6c2","./GeometryInstance-0b07c761","./GeometryPipeline-0fb7cb2c","./AttributeCompression-f7a901f9","./EncodedCartesian3-b1495e46","./IndexDatatype-ddbc25a7","./IntersectionTests-a4e54d9a","./Plane-26e67b94","./VertexFormat-7b982b01"],function(r,n,a,e,t,i,o,c,s,b,l,m,d,f,p,y,u,G,E,C){"use strict";return function(e,t){return(e=n.defined(t)?a.EllipseGeometry.unpack(e,t):e)._center=r.Cartesian3.clone(e._center),e._ellipsoid=r.Ellipsoid.clone(e._ellipsoid),a.EllipseGeometry.createGeometry(e)}}); |
'use strict';
var equal = require('assert').strictEqual;
var promiseToCallback = require('./');
['q', 'bluebird', 'pinkie-promise'].forEach(function (name) {
var Promise = require(name);
if (Promise.Promise) {
Promise = Promise.Promise;
}
it(name + ': success', function (done) {
var success = new Promise(function (resolve) {
resolve('success');
});
promiseToCallback(success)(function (err, data) {
equal(data, 'success');
done();
});
});
it(name + ': failure', function (done) {
var failure = new Promise(function (resolve, reject) {
reject('failure');
});
promiseToCallback(failure)(function (err) {
equal(err, 'failure');
done();
});
});
});
|
var cjson = require("circular-json");
global.CJSONString = function (obj) {
return cjson.stringify(obj);
};
global.CJSONParse = function (str) {
return cjson.parse(str);
};
global.jclone = function (obj) {
return JSON.parse(JSON.stringify(obj));
};
|
import {isFunction} from 'lodash';
function getPercent(loaded, total, computable){
if (!computable) return 100;
return ((loaded / total) * 100);
}
export default function(progress){
if (!isFunction(progress)) return;
return function(loaded, total, lengthComputable){
progress({
percent: getPercent(loaded, total, lengthComputable)
, loaded: loaded
, total: total
});
};
};
|
/**
* The InteractionContext contains all the entities which can be interact with.
* @private
*/
var InteractionContext = (function () {
var aabbMap = {}; // all axis aligned bounding boxes in current frame, indexed by id
var obbMap = {}; // all oriented bounding boxes in current frame, indexed by id
function InteractionContext () {
this.entities = []; // array of interactable entities in this context, sorted from back to front
}
InteractionContext.prototype._clear = function () {
this.entities.length = 0;
};
/**
* Pick the top most entity, using their oriented bounding boxes.
* @param {Vec2} worldPosition
* @return {Entity}
*/
InteractionContext.prototype.pick = function (worldPosition) {
for (var i = this.entities.length - 1; i >= 0; --i) {
var entity = this.entities[i];
if (entity.isValid) {
// aabb test
var aabb = aabbMap[entity.id];
if (aabb.contains(worldPosition)) {
// obb test
var obb = obbMap[entity.id];
var polygon = new Fire.Polygon(obb);
if (polygon.contains(worldPosition)) {
return entity;
}
}
}
}
return null;
};
InteractionContext.prototype._updateRecursilvey = function (entity) {
var renderer = entity.getComponent(Fire.Renderer);
if (renderer && renderer._enabled) {
this.entities.push(entity);
var id = entity.id;
if ( !obbMap[id] ) {
var obb = renderer.getWorldOrientedBounds();
var aabb = Math.calculateMaxRect(new Rect(), obb[0], obb[1], obb[2], obb[3]);
obbMap[id] = obb;
aabbMap[id] = aabb;
}
}
for ( var i = 0, len = entity._children.length; i < len; ++i ) {
var child = entity._children[i];
if (child._active) {
this._updateRecursilvey(child);
}
}
};
InteractionContext.prototype.update = function (entities) {
// 目前还没有专门处理physics的模块,暂时hack一下
var newFrame = !Engine.isPlaying || this === Engine._interactionContext;
if (newFrame) {
aabbMap = {};
obbMap = {};
}
// clear intersection data
this._clear();
// recursively process each entity
for (var i = 0, len = entities.length; i < len; ++i) {
var entity = entities[i];
if (entity._active) {
this._updateRecursilvey(entity);
}
}
};
// entity 必须是 entities 里面的
InteractionContext.prototype.getAABB = function (entity) {
return aabbMap[entity.id];
};
// entity 必须是 entities 里面的
InteractionContext.prototype.getOBB = function (entity) {
return obbMap[entity.id];
};
return InteractionContext;
})();
Fire._InteractionContext = InteractionContext;
|
'use strict';
angular.module('visualizerApp', []);
angular.module('visualizerApp').controller('VisualizerCtrl', ['$scope', function($scope) {
var fog = undefined;
function loadDebugMessages(debugMessages) {
var res = [];
for (var playerIndex = 0; playerIndex < debugMessages.length; playerIndex++) {
var byTurn = {};
var turns = debugMessages[playerIndex];
for (var turnIndex = 0; turnIndex < turns.length; turnIndex++) {
var turn = turns[turnIndex];
var turnNumber = turn[0] - 1;
turnNumber = Math.max(0, turnNumber);
if (!byTurn[turnNumber]) {
byTurn[turnNumber] = [];
}
var level = turn[1];
var messages = turn[2];
for (var messageIndex = 0; messageIndex < messages.length; messageIndex++) {
var message = messages[messageIndex];
byTurn[turnNumber].push({
level: level,
message: message
});
}
}
res.push(byTurn);
}
return res;
}
function init() {
var options = new Options();
options.data_dir = window.pirates_data_dir || '../visualizer/data/';
options.embedded = true;
options.local_run = window.local_run;
options.playercolors = window.playercolors;
if (options.local_run) {
$scope.displayLog = false;
} else {
options.turn = 0;
}
options.updateExternalView = function() {
setTimeout(function() {
$scope.$apply(function() {
if (!$scope.debugMessages) {
$scope.debugMessages = loadDebugMessages($scope.visualizer.state.replay.meta.debug_messages);
}
$scope.turn = $scope.visualizer.state.time | 0;
$scope.playing = $scope.visualizer.director.playing();
$scope.cutoff = $scope.visualizer.state.replay.meta.replaydata.cutoff;
$scope.maxpoints = $scope.visualizer.state.replay.meta.replaydata.maxpoints || 1000;
$scope.isLastTurn =
$scope.turn >= $scope.visualizer.state.replay.duration;
//TODO: hacky, move to directive
var debugTurnEl = document.getElementsByClassName('debug-turn' + ($scope.turn + 1));
if (debugTurnEl.length > 0) {
//debugTurnEl[0].scrollIntoView(true);
}
});
}, 0);
};
setTimeout(function() {
$scope.visualizer = new Visualizer(document.getElementById('game-canvas'), options);
$scope.visualizer.loadReplayData(window.replayData);
}, 0);
}
$scope.showFog = function(id) {
if (fog !== id) {
fog = id;
} else {
fog = undefined;
}
$scope.visualizer.showFog(fog);
};
$scope.play = function() {
$scope.visualizer.director.play();
};
$scope.firstTurn = function() {
$scope.visualizer.director.gotoTick(0);
};
$scope.lastTurn = function() {
$scope.visualizer.director.gotoTick($scope.visualizer.director.duration);
};
$scope.prevTurn = function() {
var stop = Math.ceil($scope.visualizer.state.time * 2) - 1;
$scope.visualizer.director.slowmoTo(stop / 2);
};
$scope.nextTurn = function() {
var stop = Math.floor($scope.visualizer.state.time * 2) + 1;
$scope.visualizer.director.slowmoTo(stop / 2);
};
$scope.togglePlay = function() {
$scope.visualizer.director.playStop();
$scope.visualizer.draw();
};
$scope.speed = function(amount) {
$scope.visualizer.modifySpeed(amount);
};
$scope.gotoTurn = function(turn) {
$scope.visualizer.director.gotoTick(turn - 1);
};
$scope.togglePiratesText = function() {
var lbl = $scope.visualizer.state.config['label'];
$scope.visualizer.setPirateLabels((lbl + 1) % 3);
$scope.visualizer.director.draw();
};
$scope.toggleLog = function() {
$scope.displayLog = !$scope.displayLog;
$scope.visualizer.state.config['showZones'] = !$scope.visualizer.state.config['showZones'];
setTimeout(function() {
$scope.visualizer.resize(true);
}, 0);
};
$scope.download = function() {
var data = JSON.stringify(JSON.stringify($scope.visualizer.state.replay.meta.replaydata.ants));
var text = 'turns = ' + data + '\n' + document.getElementById('replay-code').textContent;
var pom = document.createElement('a');
pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
pom.setAttribute('download', 'dummy.py');
pom.style.display = 'none';
document.body.appendChild(pom);
pom.click();
document.body.removeChild(pom);
};
$scope.debugPlayerIndex = 1;
init();
}]); |
'use strict';
var RULES = {
CM: [
/^(134[0-8]|13[5-9]\d|147\d|15[0-27-9]\d|178\d|18[2-47-8]\d)\d{7}$/,
/^1705\d{7}$/
],
CT: [
/^(133\d|1349|153\d|177\d|18[0-19]\d)\d{7}$/,
/^1700\d{7}$/
],
CU: [
/^(13[0-2]|145|15[5-6]|176|18[5-6])\d{8}$/,
/^1709\d{7}$/
]
};
module.exports = {
Valid: {
rules: RULES.CM.concat(RULES.CT, RULES.CU)
},
CM: {
alias: 'ChinaMobile',
rules: RULES.CM
},
CT: {
alias: 'ChinaTelecom',
rules: RULES.CT
},
CU: {
alias: 'ChinaUnicom',
rules: RULES.CU
},
CV: {
alias: 'ChinaVirtual',
rules: [RULES.CM[1], RULES.CT[1], RULES.CU[1]]
}
};
// http://zh.wikipedia.org/wiki/中国内地移动终端通讯号码
|
document.appLauncher = (function (document, window) {
console.log("app-launcher loaded.");
function init(containerElement, apps) {
var table = document.createElement("table");
table.className = "app-launcher-apps";
var tr = document.createElement("tr");
table.appendChild(tr);
var columns = 5; // todo option.
apps.forEach(function(app, index) {
if (index % columns === 0) {
tr = document.createElement("tr");
table.appendChild(tr);
}
var td = document.createElement("td");
tr.appendChild(td);
var a = document.createElement("a");
a.href = app.href;
a.title = app.name; // Added because of the ellipses.
// todo: support images in the future.
//var img = document.createElement("img");
//img.src = "http://placehold.it/100x100";
//a.appendChild(img);
var div = document.createElement("div");
var iconLetter = (app.name) ? app.name.substring(0, 1).toLowerCase() : "z";
div.className = "app-launcher-icon-" + iconLetter
+ " app-launcher-icon-" + app.name.toLowerCase().replace(" ", "-").replace(/\W/g, "");
var span = document.createElement("span");
var iconText = document.createTextNode(iconLetter);
span.appendChild(iconText);
div.appendChild(span);
a.appendChild(div);
var linkText = document.createTextNode(app.name);
a.appendChild(linkText);
td.appendChild(a);
});
while (containerElement.firstChild) {
containerElement.removeChild(containerElement.firstChild);
}
containerElement.appendChild(table);
}
/**
* Use XHR to get the dom of the app list page.
* @param {} callback
* @returns {}
*/
function getAppListDom(uri, callback) {
var xhr = new XMLHttpRequest();
xhr.onload = function () {
console.log(this.responseXML.title);
callback(this.responseXML);
}
xhr.open("GET", uri);
xhr.responseType = "document";
xhr.send();
}
/**
* Using a dom, find the app list table and convert into an object.
*/
function tableDomToAppList(columnNumber, dom) {
console.log(dom.title);
var rows = dom.querySelector("table").querySelectorAll("tr");
var apps = [];
// start at 1 since the first row is a header.
for (var index = 1; index < rows.length; index++) {
var name = rows[index].cells[0].innerText.trim();
var a = rows[index].cells[columnNumber].querySelector("a");
if (!a) {
continue;
}
apps.push({ "name": name, "href": a.href });
}
console.log(JSON.stringify(apps));
return apps;
}
/**
* Get the app list data from a table on a page.
* To prevent CORS issues: Use relative URL, protocol agnostic (beginning with //),
* or "direct" url without redirects.
* Give the table column number starting with zero.
* @param {} uri
* @param {} columnNumber
* @param {} callback
* @returns {}
*/
function scrapeTable(uri, columnNumber, callback) {
getAppListDom(uri, function (dom) {
var appList = tableDomToAppList(columnNumber, dom);
callback(appList);
});
}
return {
"init": init,
"scrapeTable" : scrapeTable
};
})(document, window); |
System.config({
transpiler: "babel",
babelOptions: {
optional: [
"runtime"
]
},
map: {
babel: './libs/browser.js',
jquery: './libs/jquery-2.1.2.min.js',
handlebars: './libs/handlebars-v3.0.3.js'
}
});
|
var express = require('express');
var mDB = require('../model/db.js');
var router = express.Router();
router.post('/', function(req, res)
{
var expReg = /[^\$:;%&#@!,|/ª=º\[\]{}\\()\+<>*"'?\^]/g;
if (expReg.test(req.body.nombre) && expReg.test(req.body.clave))
{
mDB.qLogin(req.body.nombre, req.body.clave, function(err, item)
{
if (item)
{
if(item.nombre === req.body.nombre && item.clave === req.body.clave)
{
req.session.user = req.body.nombre;
if (item.rol === 'usuario')
{
res.redirect('rutina');
}
else if(item.rol === 'admin')
{
res.redirect('admin');
}
else
{
res.redirect('error', { error: "rol desconocido. avise al administrador del sitio." , trace: err });
}
}
else
{
res.render('login', { error: "el nombre y/o la clave son incorectos" });
}
}
else
{
res.render('login', { error: "el nombre y/o la clave son incorectos" , trace: err });
}
});
}
else
{
res.render('login', { error: "el nombre y/o la clave son incorectos" });
}
});
module.exports = router; |
import uiButtonBase from '../mixins/ui-button-base';
import layout from '../templates/components/ui-button';
import Component from '@ember/component';
/**
ui-button component see {{#crossLink "mixins.UiButtonBase"}}{{/crossLink}}
@module components
@class UiButton
@namespace components
@constructor
*/
export default Component.extend(uiButtonBase, {
layout: layout
});
|
// see http://vuejs-templates.github.io/webpack for documentation.
var path = require('path')
module.exports = {
build: {
env: require('./prod.env'),
index: path.resolve(__dirname, '../dist/index.html'),
assetsRoot: path.resolve(__dirname, '../dist'),
assetsSubDirectory: 'static',
assetsPublicPath: '/',
productionSourceMap: true,
// Gzip off by default as many popular static hosts such as
// Surge or Netlify already gzip all static assets for you.
// Before setting to `true`, make sure to:
// npm install --save-dev compression-webpack-plugin
productionGzip: false,
productionGzipExtensions: ['js', 'css'],
// Run the build command with an extra argument to
// View the bundle analyzer report after build finishes:
// `npm run build --report`
// Set to `true` or `false` to always turn it on or off
bundleAnalyzerReport: process.env.npm_config_report
},
dev: {
env: require('./dev.env'),
port: 8080,
autoOpenBrowser: true,
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {},
// CSS Sourcemaps off by default because relative paths are "buggy"
// with this option, according to the CSS-Loader README
// (https://github.com/webpack/css-loader#sourcemaps)
// In our experience, they generally work as expected,
// just be aware of this issue when enabling this option.
cssSourceMap: false
}
};
|
'use strict';
describe('angular', function() {
var element;
afterEach(function() {
dealoc(element);
});
describe('case', function() {
it('should change case', function() {
expect(lowercase('ABC90')).toEqual('abc90');
expect(manualLowercase('ABC90')).toEqual('abc90');
expect(uppercase('abc90')).toEqual('ABC90');
expect(manualUppercase('abc90')).toEqual('ABC90');
});
});
describe("copy", function() {
it("should return same object", function() {
var obj = {};
var arr = [];
expect(copy({}, obj)).toBe(obj);
expect(copy([], arr)).toBe(arr);
});
it("should preserve prototype chaining", function() {
var GrandParentProto = {};
var ParentProto = Object.create(GrandParentProto);
var obj = Object.create(ParentProto);
expect(ParentProto.isPrototypeOf(copy(obj))).toBe(true);
expect(GrandParentProto.isPrototypeOf(copy(obj))).toBe(true);
var Foo = function() {};
expect(copy(new Foo()) instanceof Foo).toBe(true);
});
it("should copy Date", function() {
var date = new Date(123);
expect(copy(date) instanceof Date).toBeTruthy();
expect(copy(date).getTime()).toEqual(123);
expect(copy(date) === date).toBeFalsy();
});
it("should copy RegExp", function() {
var re = new RegExp(".*");
expect(copy(re) instanceof RegExp).toBeTruthy();
expect(copy(re).source).toBe(".*");
expect(copy(re) === re).toBe(false);
});
it("should copy literal RegExp", function() {
var re = /.*/;
expect(copy(re) instanceof RegExp).toBeTruthy();
expect(copy(re).source).toEqual(".*");
expect(copy(re) === re).toBeFalsy();
});
it("should copy RegExp with flags", function() {
var re = new RegExp('.*', 'gim');
expect(copy(re).global).toBe(true);
expect(copy(re).ignoreCase).toBe(true);
expect(copy(re).multiline).toBe(true);
});
it("should copy RegExp with lastIndex", function() {
var re = /a+b+/g;
var str = 'ab aabb';
expect(re.exec(str)[0]).toEqual('ab');
expect(copy(re).exec(str)[0]).toEqual('aabb');
});
it("should deeply copy literal RegExp", function() {
var objWithRegExp = {
re: /.*/
};
expect(copy(objWithRegExp).re instanceof RegExp).toBeTruthy();
expect(copy(objWithRegExp).re.source).toEqual(".*");
expect(copy(objWithRegExp.re) === objWithRegExp.re).toBeFalsy();
});
it("should copy a Uint8Array with no destination", function() {
if (typeof Uint8Array !== 'undefined') {
var src = new Uint8Array(2);
src[1] = 1;
var dst = copy(src);
expect(copy(src) instanceof Uint8Array).toBeTruthy();
expect(dst).toEqual(src);
expect(dst).not.toBe(src);
}
});
it("should copy a Uint8ClampedArray with no destination", function() {
if (typeof Uint8ClampedArray !== 'undefined') {
var src = new Uint8ClampedArray(2);
src[1] = 1;
var dst = copy(src);
expect(copy(src) instanceof Uint8ClampedArray).toBeTruthy();
expect(dst).toEqual(src);
expect(dst).not.toBe(src);
}
});
it("should copy a Uint16Array with no destination", function() {
if (typeof Uint16Array !== 'undefined') {
var src = new Uint16Array(2);
src[1] = 1;
var dst = copy(src);
expect(copy(src) instanceof Uint16Array).toBeTruthy();
expect(dst).toEqual(src);
expect(dst).not.toBe(src);
}
});
it("should copy a Uint32Array with no destination", function() {
if (typeof Uint32Array !== 'undefined') {
var src = new Uint32Array(2);
src[1] = 1;
var dst = copy(src);
expect(copy(src) instanceof Uint32Array).toBeTruthy();
expect(dst).toEqual(src);
expect(dst).not.toBe(src);
}
});
it("should copy a Int8Array with no destination", function() {
if (typeof Int8Array !== 'undefined') {
var src = new Int8Array(2);
src[1] = 1;
var dst = copy(src);
expect(copy(src) instanceof Int8Array).toBeTruthy();
expect(dst).toEqual(src);
expect(dst).not.toBe(src);
}
});
it("should copy a Int16Array with no destination", function() {
if (typeof Int16Array !== 'undefined') {
var src = new Int16Array(2);
src[1] = 1;
var dst = copy(src);
expect(copy(src) instanceof Int16Array).toBeTruthy();
expect(dst).toEqual(src);
expect(dst).not.toBe(src);
}
});
it("should copy a Int32Array with no destination", function() {
if (typeof Int32Array !== 'undefined') {
var src = new Int32Array(2);
src[1] = 1;
var dst = copy(src);
expect(copy(src) instanceof Int32Array).toBeTruthy();
expect(dst).toEqual(src);
expect(dst).not.toBe(src);
}
});
it("should copy a Float32Array with no destination", function() {
if (typeof Float32Array !== 'undefined') {
var src = new Float32Array(2);
src[1] = 1;
var dst = copy(src);
expect(copy(src) instanceof Float32Array).toBeTruthy();
expect(dst).toEqual(src);
expect(dst).not.toBe(src);
}
});
it("should copy a Float64Array with no destination", function() {
if (typeof Float64Array !== 'undefined') {
var src = new Float64Array(2);
src[1] = 1;
var dst = copy(src);
expect(copy(src) instanceof Float64Array).toBeTruthy();
expect(dst).toEqual(src);
expect(dst).not.toBe(src);
}
});
it("should throw an exception if a Uint8Array is the destination", function() {
if (typeof Uint8Array !== 'undefined') {
var src = new Uint8Array();
var dst = new Uint8Array(5);
expect(function() { copy(src, dst); })
.toThrowMinErr("ng", "cpta", "Can't copy! TypedArray destination cannot be mutated.");
}
});
it("should throw an exception if a Uint8ClampedArray is the destination", function() {
if (typeof Uint8ClampedArray !== 'undefined') {
var src = new Uint8ClampedArray();
var dst = new Uint8ClampedArray(5);
expect(function() { copy(src, dst); })
.toThrowMinErr("ng", "cpta", "Can't copy! TypedArray destination cannot be mutated.");
}
});
it("should throw an exception if a Uint16Array is the destination", function() {
if (typeof Uint16Array !== 'undefined') {
var src = new Uint16Array();
var dst = new Uint16Array(5);
expect(function() { copy(src, dst); })
.toThrowMinErr("ng", "cpta", "Can't copy! TypedArray destination cannot be mutated.");
}
});
it("should throw an exception if a Uint32Array is the destination", function() {
if (typeof Uint32Array !== 'undefined') {
var src = new Uint32Array();
var dst = new Uint32Array(5);
expect(function() { copy(src, dst); })
.toThrowMinErr("ng", "cpta", "Can't copy! TypedArray destination cannot be mutated.");
}
});
it("should throw an exception if a Int8Array is the destination", function() {
if (typeof Int8Array !== 'undefined') {
var src = new Int8Array();
var dst = new Int8Array(5);
expect(function() { copy(src, dst); })
.toThrowMinErr("ng", "cpta", "Can't copy! TypedArray destination cannot be mutated.");
}
});
it("should throw an exception if a Int16Array is the destination", function() {
if (typeof Int16Array !== 'undefined') {
var src = new Int16Array();
var dst = new Int16Array(5);
expect(function() { copy(src, dst); })
.toThrowMinErr("ng", "cpta", "Can't copy! TypedArray destination cannot be mutated.");
}
});
it("should throw an exception if a Int32Array is the destination", function() {
if (typeof Int32Array !== 'undefined') {
var src = new Int32Array();
var dst = new Int32Array(5);
expect(function() { copy(src, dst); })
.toThrowMinErr("ng", "cpta", "Can't copy! TypedArray destination cannot be mutated.");
}
});
it("should throw an exception if a Float32Array is the destination", function() {
if (typeof Float32Array !== 'undefined') {
var src = new Float32Array();
var dst = new Float32Array(5);
expect(function() { copy(src, dst); })
.toThrowMinErr("ng", "cpta", "Can't copy! TypedArray destination cannot be mutated.");
}
});
it("should throw an exception if a Float64Array is the destination", function() {
if (typeof Float64Array !== 'undefined') {
var src = new Float64Array();
var dst = new Float64Array(5);
expect(function() { copy(src, dst); })
.toThrowMinErr("ng", "cpta", "Can't copy! TypedArray destination cannot be mutated.");
}
});
it("should deeply copy an array into an existing array", function() {
var src = [1, {name:"value"}];
var dst = [{key:"v"}];
expect(copy(src, dst)).toBe(dst);
expect(dst).toEqual([1, {name:"value"}]);
expect(dst[1]).toEqual({name:"value"});
expect(dst[1]).not.toBe(src[1]);
});
it("should deeply copy an array into a new array", function() {
var src = [1, {name:"value"}];
var dst = copy(src);
expect(src).toEqual([1, {name:"value"}]);
expect(dst).toEqual(src);
expect(dst).not.toBe(src);
expect(dst[1]).not.toBe(src[1]);
});
it('should copy empty array', function() {
var src = [];
var dst = [{key: "v"}];
expect(copy(src, dst)).toEqual([]);
expect(dst).toEqual([]);
});
it("should deeply copy an object into an existing object", function() {
var src = {a:{name:"value"}};
var dst = {b:{key:"v"}};
expect(copy(src, dst)).toBe(dst);
expect(dst).toEqual({a:{name:"value"}});
expect(dst.a).toEqual(src.a);
expect(dst.a).not.toBe(src.a);
});
it("should deeply copy an object into a non-existing object", function() {
var src = {a:{name:"value"}};
var dst = copy(src, undefined);
expect(src).toEqual({a:{name:"value"}});
expect(dst).toEqual(src);
expect(dst).not.toBe(src);
expect(dst.a).toEqual(src.a);
expect(dst.a).not.toBe(src.a);
});
it("should copy primitives", function() {
expect(copy(null)).toEqual(null);
expect(copy('')).toBe('');
expect(copy('lala')).toBe('lala');
expect(copy(123)).toEqual(123);
expect(copy([{key:null}])).toEqual([{key:null}]);
});
it('should throw an exception if a Scope is being copied', inject(function($rootScope) {
expect(function() { copy($rootScope.$new()); }).
toThrowMinErr("ng", "cpws", "Can't copy! Making copies of Window or Scope instances is not supported.");
}));
it('should throw an exception if a Window is being copied', function() {
expect(function() { copy(window); }).
toThrowMinErr("ng", "cpws", "Can't copy! Making copies of Window or Scope instances is not supported.");
});
it('should throw an exception when source and destination are equivalent', function() {
var src, dst;
src = dst = {key: 'value'};
expect(function() { copy(src, dst); }).toThrowMinErr("ng", "cpi", "Can't copy! Source and destination are identical.");
src = dst = [2, 4];
expect(function() { copy(src, dst); }).toThrowMinErr("ng", "cpi", "Can't copy! Source and destination are identical.");
});
it('should not copy the private $$hashKey', function() {
var src,dst;
src = {};
hashKey(src);
dst = copy(src);
expect(hashKey(dst)).not.toEqual(hashKey(src));
});
it('should retain the previous $$hashKey when copying object with hashKey', function() {
var src,dst,h;
src = {};
dst = {};
// force creation of a hashkey
h = hashKey(dst);
hashKey(src);
dst = copy(src,dst);
// make sure we don't copy the key
expect(hashKey(dst)).not.toEqual(hashKey(src));
// make sure we retain the old key
expect(hashKey(dst)).toEqual(h);
});
it('should retain the previous $$hashKey when copying non-object', function() {
var dst = {};
var h = hashKey(dst);
copy(null, dst);
expect(hashKey(dst)).toEqual(h);
copy(42, dst);
expect(hashKey(dst)).toEqual(h);
copy(new Date(), dst);
expect(hashKey(dst)).toEqual(h);
});
it('should handle circular references', function() {
var a = {b: {a: null}, self: null, selfs: [null, null, [null]]};
a.b.a = a;
a.self = a;
a.selfs = [a, a.b, [a]];
var aCopy = copy(a, null);
expect(aCopy).toEqual(a);
expect(aCopy).not.toBe(a);
expect(aCopy).toBe(aCopy.self);
expect(aCopy).toBe(aCopy.selfs[2][0]);
expect(aCopy.selfs[2]).not.toBe(a.selfs[2]);
var copyTo = [];
aCopy = copy(a, copyTo);
expect(aCopy).toBe(copyTo);
expect(aCopy).not.toBe(a);
expect(aCopy).toBe(aCopy.self);
});
it('should deeply copy XML nodes', function() {
var anElement = document.createElement('foo');
anElement.appendChild(document.createElement('bar'));
var theCopy = anElement.cloneNode(true);
expect(copy(anElement).outerHTML).toEqual(theCopy.outerHTML);
expect(copy(anElement)).not.toBe(anElement);
});
it('should not try to call a non-function called `cloneNode`', function() {
expect(copy.bind(null, { cloneNode: 100 })).not.toThrow();
});
it('should handle objects with multiple references', function() {
var b = {};
var a = [b, -1, b];
var aCopy = copy(a);
expect(aCopy[0]).not.toBe(a[0]);
expect(aCopy[0]).toBe(aCopy[2]);
var copyTo = [];
aCopy = copy(a, copyTo);
expect(aCopy).toBe(copyTo);
expect(aCopy[0]).not.toBe(a[0]);
expect(aCopy[0]).toBe(aCopy[2]);
});
it('should handle date/regex objects with multiple references', function() {
var re = /foo/;
var d = new Date();
var o = {re: re, re2: re, d: d, d2: d};
var oCopy = copy(o);
expect(oCopy.re).toBe(oCopy.re2);
expect(oCopy.d).toBe(oCopy.d2);
oCopy = copy(o, {});
expect(oCopy.re).toBe(oCopy.re2);
expect(oCopy.d).toBe(oCopy.d2);
});
it('should clear destination arrays correctly when source is non-array', function() {
expect(copy(null, [1,2,3])).toEqual([]);
expect(copy(undefined, [1,2,3])).toEqual([]);
expect(copy({0: 1, 1: 2}, [1,2,3])).toEqual([1,2]);
expect(copy(new Date(), [1,2,3])).toEqual([]);
expect(copy(/a/, [1,2,3])).toEqual([]);
expect(copy(true, [1,2,3])).toEqual([]);
});
it('should clear destination objects correctly when source is non-array', function() {
expect(copy(null, {0:1,1:2,2:3})).toEqual({});
expect(copy(undefined, {0:1,1:2,2:3})).toEqual({});
expect(copy(new Date(), {0:1,1:2,2:3})).toEqual({});
expect(copy(/a/, {0:1,1:2,2:3})).toEqual({});
expect(copy(true, {0:1,1:2,2:3})).toEqual({});
});
it('should copy objects with no prototype parent', function() {
var obj = extend(Object.create(null), {
a: 1,
b: 2,
c: 3
});
var dest = copy(obj);
expect(Object.getPrototypeOf(dest)).toBe(null);
expect(dest.a).toBe(1);
expect(dest.b).toBe(2);
expect(dest.c).toBe(3);
expect(Object.keys(dest)).toEqual(['a', 'b', 'c']);
});
});
describe("extend", function() {
it('should not copy the private $$hashKey', function() {
var src,dst;
src = {};
dst = {};
hashKey(src);
dst = extend(dst,src);
expect(hashKey(dst)).not.toEqual(hashKey(src));
});
it('should retain the previous $$hashKey', function() {
var src,dst,h;
src = {};
dst = {};
h = hashKey(dst);
hashKey(src);
dst = extend(dst,src);
// make sure we don't copy the key
expect(hashKey(dst)).not.toEqual(hashKey(src));
// make sure we retain the old key
expect(hashKey(dst)).toEqual(h);
});
it('should work when extending with itself', function() {
var src,dst,h;
dst = src = {};
h = hashKey(dst);
dst = extend(dst,src);
// make sure we retain the old key
expect(hashKey(dst)).toEqual(h);
});
it('should copy dates by reference', function() {
var src = { date: new Date() };
var dst = {};
extend(dst, src);
expect(dst.date).toBe(src.date);
});
});
describe('merge', function() {
it('should recursively copy objects into dst from left to right', function() {
var dst = { foo: { bar: 'foobar' }};
var src1 = { foo: { bazz: 'foobazz' }};
var src2 = { foo: { bozz: 'foobozz' }};
merge(dst, src1, src2);
expect(dst).toEqual({
foo: {
bar: 'foobar',
bazz: 'foobazz',
bozz: 'foobozz'
}
});
});
it('should replace primitives with objects', function() {
var dst = { foo: "bloop" };
var src = { foo: { bar: { baz: "bloop" }}};
merge(dst, src);
expect(dst).toEqual({
foo: {
bar: {
baz: "bloop"
}
}
});
});
it('should replace null values in destination with objects', function() {
var dst = { foo: null };
var src = { foo: { bar: { baz: "bloop" }}};
merge(dst, src);
expect(dst).toEqual({
foo: {
bar: {
baz: "bloop"
}
}
});
});
it('should copy references to functions by value rather than merging', function() {
function fn() {}
var dst = { foo: 1 };
var src = { foo: fn };
merge(dst, src);
expect(dst).toEqual({
foo: fn
});
});
it('should create a new array if destination property is a non-object and source property is an array', function() {
var dst = { foo: NaN };
var src = { foo: [1,2,3] };
merge(dst, src);
expect(dst).toEqual({
foo: [1,2,3]
});
expect(dst.foo).not.toBe(src.foo);
});
it('should copy dates by value', function() {
var src = { date: new Date() };
var dst = {};
merge(dst, src);
expect(dst.date).not.toBe(src.date);
expect(isDate(dst.date)).toBeTruthy();
expect(dst.date.valueOf()).toEqual(src.date.valueOf());
});
it('should copy regexp by value', function() {
var src = { regexp: /blah/ };
var dst = {};
merge(dst, src);
expect(dst.regexp).not.toBe(src.regexp);
expect(isRegExp(dst.regexp)).toBe(true);
expect(dst.regexp.toString()).toBe(src.regexp.toString());
});
});
describe('shallow copy', function() {
it('should make a copy', function() {
var original = {key:{}};
var copy = shallowCopy(original);
expect(copy).toEqual(original);
expect(copy.key).toBe(original.key);
});
it('should omit "$$"-prefixed properties', function() {
var original = {$$some: true, $$: true};
var clone = {};
expect(shallowCopy(original, clone)).toBe(clone);
expect(clone.$$some).toBeUndefined();
expect(clone.$$).toBeUndefined();
});
it('should copy "$"-prefixed properties from copy', function() {
var original = {$some: true};
var clone = {};
expect(shallowCopy(original, clone)).toBe(clone);
expect(clone.$some).toBe(original.$some);
});
it('should handle arrays', function() {
var original = [{}, 1],
clone = [];
var aCopy = shallowCopy(original);
expect(aCopy).not.toBe(original);
expect(aCopy).toEqual(original);
expect(aCopy[0]).toBe(original[0]);
expect(shallowCopy(original, clone)).toBe(clone);
expect(clone).toEqual(original);
});
it('should handle primitives', function() {
var src = 1,
dst = 2;
expect(shallowCopy(src, dst)).toBe(src);
expect(shallowCopy('test')).toBe('test');
expect(shallowCopy(3)).toBe(3);
expect(shallowCopy(true)).toBe(true);
});
});
describe('elementHTML', function() {
it('should dump element', function() {
expect(startingTag('<div attr="123">something<span></span></div>')).
toEqual('<div attr="123">');
});
});
describe('equals', function() {
it('should return true if same object', function() {
var o = {};
expect(equals(o, o)).toEqual(true);
expect(equals(o, {})).toEqual(true);
expect(equals(1, '1')).toEqual(false);
expect(equals(1, '2')).toEqual(false);
});
it('should recurse into object', function() {
expect(equals({}, {})).toEqual(true);
expect(equals({name:'misko'}, {name:'misko'})).toEqual(true);
expect(equals({name:'misko', age:1}, {name:'misko'})).toEqual(false);
expect(equals({name:'misko'}, {name:'misko', age:1})).toEqual(false);
expect(equals({name:'misko'}, {name:'adam'})).toEqual(false);
expect(equals(['misko'], ['misko'])).toEqual(true);
expect(equals(['misko'], ['adam'])).toEqual(false);
expect(equals(['misko'], ['misko', 'adam'])).toEqual(false);
});
it('should ignore undefined member variables during comparison', function() {
var obj1 = {name: 'misko'},
obj2 = {name: 'misko', undefinedvar: undefined};
expect(equals(obj1, obj2)).toBe(true);
expect(equals(obj2, obj1)).toBe(true);
});
it('should ignore $ member variables', function() {
expect(equals({name:'misko', $id:1}, {name:'misko', $id:2})).toEqual(true);
expect(equals({name:'misko'}, {name:'misko', $id:2})).toEqual(true);
expect(equals({name:'misko', $id:1}, {name:'misko'})).toEqual(true);
});
it('should ignore functions', function() {
expect(equals({func: function() {}}, {bar: function() {}})).toEqual(true);
});
it('should work well with nulls', function() {
expect(equals(null, '123')).toBe(false);
expect(equals('123', null)).toBe(false);
var obj = {foo:'bar'};
expect(equals(null, obj)).toBe(false);
expect(equals(obj, null)).toBe(false);
expect(equals(null, null)).toBe(true);
});
it('should work well with undefined', function() {
expect(equals(undefined, '123')).toBe(false);
expect(equals('123', undefined)).toBe(false);
var obj = {foo:'bar'};
expect(equals(undefined, obj)).toBe(false);
expect(equals(obj, undefined)).toBe(false);
expect(equals(undefined, undefined)).toBe(true);
});
it('should treat two NaNs as equal', function() {
expect(equals(NaN, NaN)).toBe(true);
});
it('should compare Scope instances only by identity', inject(function($rootScope) {
var scope1 = $rootScope.$new(),
scope2 = $rootScope.$new();
expect(equals(scope1, scope1)).toBe(true);
expect(equals(scope1, scope2)).toBe(false);
expect(equals($rootScope, scope1)).toBe(false);
expect(equals(undefined, scope1)).toBe(false);
}));
it('should compare Window instances only by identity', function() {
expect(equals(window, window)).toBe(true);
expect(equals(window, window.parent)).toBe(false);
expect(equals(window, undefined)).toBe(false);
});
it('should compare dates', function() {
expect(equals(new Date(0), new Date(0))).toBe(true);
expect(equals(new Date(0), new Date(1))).toBe(false);
expect(equals(new Date(0), 0)).toBe(false);
expect(equals(0, new Date(0))).toBe(false);
expect(equals(new Date(undefined), new Date(undefined))).toBe(true);
expect(equals(new Date(undefined), new Date(0))).toBe(false);
expect(equals(new Date(undefined), new Date(null))).toBe(false);
expect(equals(new Date(undefined), new Date('wrong'))).toBe(true);
expect(equals(new Date(), /abc/)).toBe(false);
});
it('should correctly test for keys that are present on Object.prototype', function() {
/* jshint -W001 */
expect(equals({}, {hasOwnProperty: 1})).toBe(false);
expect(equals({}, {toString: null})).toBe(false);
});
it('should compare regular expressions', function() {
expect(equals(/abc/, /abc/)).toBe(true);
expect(equals(/abc/i, new RegExp('abc', 'i'))).toBe(true);
expect(equals(new RegExp('abc', 'i'), new RegExp('abc', 'i'))).toBe(true);
expect(equals(new RegExp('abc', 'i'), new RegExp('abc'))).toBe(false);
expect(equals(/abc/i, /abc/)).toBe(false);
expect(equals(/abc/, /def/)).toBe(false);
expect(equals(/^abc/, /abc/)).toBe(false);
expect(equals(/^abc/, '/^abc/')).toBe(false);
expect(equals(/abc/, new Date())).toBe(false);
});
it('should return false when comparing an object and an array', function() {
expect(equals({}, [])).toBe(false);
expect(equals([], {})).toBe(false);
});
it('should return false when comparing an object and a RegExp', function() {
expect(equals({}, /abc/)).toBe(false);
expect(equals({}, new RegExp('abc', 'i'))).toBe(false);
});
it('should return false when comparing an object and a Date', function() {
expect(equals({}, new Date())).toBe(false);
});
it('should safely compare objects with no prototype parent', function() {
var o1 = extend(Object.create(null), {
a: 1, b: 2, c: 3
});
var o2 = extend(Object.create(null), {
a: 1, b: 2, c: 3
});
expect(equals(o1, o2)).toBe(true);
o2.c = 2;
expect(equals(o1, o2)).toBe(false);
});
it('should safely compare objects which shadow Object.prototype.hasOwnProperty', function() {
/* jshint -W001 */
var o1 = {
hasOwnProperty: true,
a: 1,
b: 2,
c: 3
};
var o2 = {
hasOwnProperty: true,
a: 1,
b: 2,
c: 3
};
expect(equals(o1, o2)).toBe(true);
o1.hasOwnProperty = function() {};
expect(equals(o1, o2)).toBe(false);
});
});
describe('csp', function() {
function mockCspElement(cspAttrName, cspAttrValue) {
return spyOn(document, 'querySelector').andCallFake(function(selector) {
if (selector == '[' + cspAttrName + ']') {
var html = '<div ' + cspAttrName + (cspAttrValue ? ('="' + cspAttrValue + '" ') : '') + '></div>';
return jqLite(html)[0];
}
});
}
var originalFunction;
beforeEach(function() {
spyOn(window, 'Function');
});
afterEach(function() {
delete csp.rules;
});
it('should return the false for all rules when CSP is not enabled (the default)', function() {
expect(csp()).toEqual({ noUnsafeEval: false, noInlineStyle: false });
});
it('should return true for noUnsafeEval if eval causes a CSP security policy error', function() {
window.Function.andCallFake(function() { throw new Error('CSP test'); });
expect(csp()).toEqual({ noUnsafeEval: true, noInlineStyle: false });
expect(window.Function).toHaveBeenCalledWith('');
});
it('should return true for all rules when CSP is enabled manually via empty `ng-csp` attribute', function() {
var spy = mockCspElement('ng-csp');
expect(csp()).toEqual({ noUnsafeEval: true, noInlineStyle: true });
expect(spy).toHaveBeenCalledWith('[ng-csp]');
expect(window.Function).not.toHaveBeenCalled();
});
it('should return true when CSP is enabled manually via [data-ng-csp]', function() {
var spy = mockCspElement('data-ng-csp');
expect(csp()).toEqual({ noUnsafeEval: true, noInlineStyle: true });
expect(spy).toHaveBeenCalledWith('[data-ng-csp]');
expect(window.Function).not.toHaveBeenCalled();
});
it('should return true for noUnsafeEval if it is specified in the `ng-csp` attribute value', function() {
var spy = mockCspElement('ng-csp', 'no-unsafe-eval');
expect(csp()).toEqual({ noUnsafeEval: true, noInlineStyle: false });
expect(spy).toHaveBeenCalledWith('[ng-csp]');
expect(window.Function).not.toHaveBeenCalled();
});
it('should return true for noInlineStyle if it is specified in the `ng-csp` attribute value', function() {
var spy = mockCspElement('ng-csp', 'no-inline-style');
expect(csp()).toEqual({ noUnsafeEval: false, noInlineStyle: true });
expect(spy).toHaveBeenCalledWith('[ng-csp]');
expect(window.Function).not.toHaveBeenCalled();
});
it('should return true for all styles if they are all specified in the `ng-csp` attribute value', function() {
var spy = mockCspElement('ng-csp', 'no-inline-style;no-unsafe-eval');
expect(csp()).toEqual({ noUnsafeEval: true, noInlineStyle: true });
expect(spy).toHaveBeenCalledWith('[ng-csp]');
expect(window.Function).not.toHaveBeenCalled();
});
});
describe('jq', function() {
var element;
beforeEach(function() {
element = document.createElement('html');
});
afterEach(function() {
delete jq.name_;
});
it('should return undefined when jq is not set, no jQuery found (the default)', function() {
expect(jq()).toBe(undefined);
});
it('should return empty string when jq is enabled manually via [ng-jq] with empty string', function() {
element.setAttribute('ng-jq', '');
spyOn(document, 'querySelector').andCallFake(function(selector) {
if (selector === '[ng-jq]') return element;
});
expect(jq()).toBe('');
});
it('should return empty string when jq is enabled manually via [data-ng-jq] with empty string', function() {
element.setAttribute('data-ng-jq', '');
spyOn(document, 'querySelector').andCallFake(function(selector) {
if (selector === '[data-ng-jq]') return element;
});
expect(jq()).toBe('');
expect(document.querySelector).toHaveBeenCalledWith('[data-ng-jq]');
});
it('should return empty string when jq is enabled manually via [x-ng-jq] with empty string', function() {
element.setAttribute('x-ng-jq', '');
spyOn(document, 'querySelector').andCallFake(function(selector) {
if (selector === '[x-ng-jq]') return element;
});
expect(jq()).toBe('');
expect(document.querySelector).toHaveBeenCalledWith('[x-ng-jq]');
});
it('should return empty string when jq is enabled manually via [ng:jq] with empty string', function() {
element.setAttribute('ng:jq', '');
spyOn(document, 'querySelector').andCallFake(function(selector) {
if (selector === '[ng\\:jq]') return element;
});
expect(jq()).toBe('');
expect(document.querySelector).toHaveBeenCalledWith('[ng\\:jq]');
});
it('should return "jQuery" when jq is enabled manually via [ng-jq] with value "jQuery"', function() {
element.setAttribute('ng-jq', 'jQuery');
spyOn(document, 'querySelector').andCallFake(function(selector) {
if (selector === '[ng-jq]') return element;
});
expect(jq()).toBe('jQuery');
expect(document.querySelector).toHaveBeenCalledWith('[ng-jq]');
});
it('should return "jQuery" when jq is enabled manually via [data-ng-jq] with value "jQuery"', function() {
element.setAttribute('data-ng-jq', 'jQuery');
spyOn(document, 'querySelector').andCallFake(function(selector) {
if (selector === '[data-ng-jq]') return element;
});
expect(jq()).toBe('jQuery');
expect(document.querySelector).toHaveBeenCalledWith('[data-ng-jq]');
});
it('should return "jQuery" when jq is enabled manually via [x-ng-jq] with value "jQuery"', function() {
element.setAttribute('x-ng-jq', 'jQuery');
spyOn(document, 'querySelector').andCallFake(function(selector) {
if (selector === '[x-ng-jq]') return element;
});
expect(jq()).toBe('jQuery');
expect(document.querySelector).toHaveBeenCalledWith('[x-ng-jq]');
});
it('should return "jQuery" when jq is enabled manually via [ng:jq] with value "jQuery"', function() {
element.setAttribute('ng:jq', 'jQuery');
spyOn(document, 'querySelector').andCallFake(function(selector) {
if (selector === '[ng\\:jq]') return element;
});
expect(jq()).toBe('jQuery');
expect(document.querySelector).toHaveBeenCalledWith('[ng\\:jq]');
});
});
describe('parseKeyValue', function() {
it('should parse a string into key-value pairs', function() {
expect(parseKeyValue('')).toEqual({});
expect(parseKeyValue('simple=pair')).toEqual({simple: 'pair'});
expect(parseKeyValue('first=1&second=2')).toEqual({first: '1', second: '2'});
expect(parseKeyValue('escaped%20key=escaped%20value')).
toEqual({'escaped key': 'escaped value'});
expect(parseKeyValue('emptyKey=')).toEqual({emptyKey: ''});
expect(parseKeyValue('flag1&key=value&flag2')).
toEqual({flag1: true, key: 'value', flag2: true});
});
it('should ignore key values that are not valid URI components', function() {
expect(function() { parseKeyValue('%'); }).not.toThrow();
expect(parseKeyValue('%')).toEqual({});
expect(parseKeyValue('invalid=%')).toEqual({ invalid: undefined });
expect(parseKeyValue('invalid=%&valid=good')).toEqual({ invalid: undefined, valid: 'good' });
});
it('should parse a string into key-value pairs with duplicates grouped in an array', function() {
expect(parseKeyValue('')).toEqual({});
expect(parseKeyValue('duplicate=pair')).toEqual({duplicate: 'pair'});
expect(parseKeyValue('first=1&first=2')).toEqual({first: ['1','2']});
expect(parseKeyValue('escaped%20key=escaped%20value&&escaped%20key=escaped%20value2')).
toEqual({'escaped key': ['escaped value','escaped value2']});
expect(parseKeyValue('flag1&key=value&flag1')).
toEqual({flag1: [true,true], key: 'value'});
expect(parseKeyValue('flag1&flag1=value&flag1=value2&flag1')).
toEqual({flag1: [true,'value','value2',true]});
});
it('should ignore properties higher in the prototype chain', function() {
expect(parseKeyValue('toString=123')).toEqual({
'toString': '123'
});
});
it('should ignore badly escaped = characters', function() {
expect(parseKeyValue('test=a=b')).toEqual({
'test': 'a=b'
});
});
});
describe('toKeyValue', function() {
it('should serialize key-value pairs into string', function() {
expect(toKeyValue({})).toEqual('');
expect(toKeyValue({simple: 'pair'})).toEqual('simple=pair');
expect(toKeyValue({first: '1', second: '2'})).toEqual('first=1&second=2');
expect(toKeyValue({'escaped key': 'escaped value'})).
toEqual('escaped%20key=escaped%20value');
expect(toKeyValue({emptyKey: ''})).toEqual('emptyKey=');
});
it('should serialize true values into flags', function() {
expect(toKeyValue({flag1: true, key: 'value', flag2: true})).toEqual('flag1&key=value&flag2');
});
it('should serialize duplicates into duplicate param strings', function() {
expect(toKeyValue({key: [323,'value',true]})).toEqual('key=323&key=value&key');
expect(toKeyValue({key: [323,'value',true, 1234]})).
toEqual('key=323&key=value&key&key=1234');
});
});
describe('forEach', function() {
it('should iterate over *own* object properties', function() {
function MyObj() {
this.bar = 'barVal';
this.baz = 'bazVal';
}
MyObj.prototype.foo = 'fooVal';
var obj = new MyObj(),
log = [];
forEach(obj, function(value, key) { log.push(key + ':' + value); });
expect(log).toEqual(['bar:barVal', 'baz:bazVal']);
});
it('should not break if obj is an array we override hasOwnProperty', function() {
/* jshint -W001 */
var obj = [];
obj[0] = 1;
obj[1] = 2;
obj.hasOwnProperty = null;
var log = [];
forEach(obj, function(value, key) {
log.push(key + ':' + value);
});
expect(log).toEqual(['0:1', '1:2']);
});
it('should handle JQLite and jQuery objects like arrays', function() {
var jqObject = jqLite("<p><span>s1</span><span>s2</span></p>").find("span"),
log = [];
forEach(jqObject, function(value, key) { log.push(key + ':' + value.innerHTML); });
expect(log).toEqual(['0:s1', '1:s2']);
});
it('should handle NodeList objects like arrays', function() {
var nodeList = jqLite("<p><span>a</span><span>b</span><span>c</span></p>")[0].childNodes,
log = [];
forEach(nodeList, function(value, key) { log.push(key + ':' + value.innerHTML); });
expect(log).toEqual(['0:a', '1:b', '2:c']);
});
it('should handle HTMLCollection objects like arrays', function() {
document.body.innerHTML = "<p>" +
"<a name='x'>a</a>" +
"<a name='y'>b</a>" +
"<a name='x'>c</a>" +
"</p>";
var htmlCollection = document.getElementsByName('x'),
log = [];
forEach(htmlCollection, function(value, key) { log.push(key + ':' + value.innerHTML); });
expect(log).toEqual(['0:a', '1:c']);
});
if (document.querySelectorAll) {
it('should handle the result of querySelectorAll in IE8 as it has no hasOwnProperty function', function() {
document.body.innerHTML = "<p>" +
"<a name='x'>a</a>" +
"<a name='y'>b</a>" +
"<a name='x'>c</a>" +
"</p>";
var htmlCollection = document.querySelectorAll('[name="x"]'),
log = [];
forEach(htmlCollection, function(value, key) { log.push(key + ':' + value.innerHTML); });
expect(log).toEqual(['0:a', '1:c']);
});
}
it('should handle arguments objects like arrays', function() {
var args,
log = [];
(function() { args = arguments; }('a', 'b', 'c'));
forEach(args, function(value, key) { log.push(key + ':' + value); });
expect(log).toEqual(['0:a', '1:b', '2:c']);
});
it('should handle string values like arrays', function() {
var log = [];
forEach('bar', function(value, key) { log.push(key + ':' + value); });
expect(log).toEqual(['0:b', '1:a', '2:r']);
});
it('should handle objects with length property as objects', function() {
var obj = {
'foo': 'bar',
'length': 2
},
log = [];
forEach(obj, function(value, key) { log.push(key + ':' + value); });
expect(log).toEqual(['foo:bar', 'length:2']);
});
it('should handle objects of custom types with length property as objects', function() {
function CustomType() {
this.length = 2;
this.foo = 'bar';
}
var obj = new CustomType(),
log = [];
forEach(obj, function(value, key) { log.push(key + ':' + value); });
expect(log).toEqual(['length:2', 'foo:bar']);
});
it('should not invoke the iterator for indexed properties which are not present in the collection', function() {
var log = [];
var collection = [];
collection[5] = 'SPARSE';
forEach(collection, function(item, index) {
log.push(item + index);
});
expect(log.length).toBe(1);
expect(log[0]).toBe('SPARSE5');
});
it('should safely iterate through objects with no prototype parent', function() {
var obj = extend(Object.create(null), {
a: 1, b: 2, c: 3
});
var log = [];
var self = {};
forEach(obj, function(val, key, collection) {
expect(this).toBe(self);
expect(collection).toBe(obj);
log.push(key + '=' + val);
}, self);
expect(log.length).toBe(3);
expect(log).toEqual(['a=1', 'b=2', 'c=3']);
});
it('should safely iterate through objects which shadow Object.prototype.hasOwnProperty', function() {
/* jshint -W001 */
var obj = {
hasOwnProperty: true,
a: 1,
b: 2,
c: 3
};
var log = [];
var self = {};
forEach(obj, function(val, key, collection) {
expect(this).toBe(self);
expect(collection).toBe(obj);
log.push(key + '=' + val);
}, self);
expect(log.length).toBe(4);
expect(log).toEqual(['hasOwnProperty=true', 'a=1', 'b=2', 'c=3']);
});
describe('ES spec api compliance', function() {
function testForEachSpec(expectedSize, collection) {
var that = {};
forEach(collection, function(value, key, collectionArg) {
expect(collectionArg).toBe(collection);
expect(collectionArg[key]).toBe(value);
expect(this).toBe(that);
expectedSize--;
}, that);
expect(expectedSize).toBe(0);
}
it('should follow the ES spec when called with array', function() {
testForEachSpec(2, [1,2]);
});
it('should follow the ES spec when called with arguments', function() {
testForEachSpec(2, (function() { return arguments; }(1,2)));
});
it('should follow the ES spec when called with string', function() {
testForEachSpec(2, '12');
});
it('should follow the ES spec when called with jQuery/jqLite', function() {
testForEachSpec(2, jqLite("<span>a</span><span>b</span>"));
});
it('should follow the ES spec when called with childNodes NodeList', function() {
testForEachSpec(2, jqLite("<p><span>a</span><span>b</span></p>")[0].childNodes);
});
it('should follow the ES spec when called with getElementsByTagName HTMLCollection', function() {
testForEachSpec(2, jqLite("<p><span>a</span><span>b</span></p>")[0].getElementsByTagName("*"));
});
it('should follow the ES spec when called with querySelectorAll HTMLCollection', function() {
testForEachSpec(2, jqLite("<p><span>a</span><span>b</span></p>")[0].querySelectorAll("*"));
});
it('should follow the ES spec when called with JSON', function() {
testForEachSpec(2, {a: 1, b: 2});
});
it('should follow the ES spec when called with function', function() {
function f() {}
f.a = 1;
f.b = 2;
testForEachSpec(2, f);
});
});
});
describe('encodeUriSegment', function() {
it('should correctly encode uri segment and not encode chars defined as pchar set in rfc3986',
function() {
//don't encode alphanum
expect(encodeUriSegment('asdf1234asdf')).
toEqual('asdf1234asdf');
//don't encode unreserved'
expect(encodeUriSegment("-_.!~*'(); -_.!~*'();")).
toEqual("-_.!~*'();%20-_.!~*'();");
//don't encode the rest of pchar'
expect(encodeUriSegment(':@&=+$, :@&=+$,')).
toEqual(':@&=+$,%20:@&=+$,');
//encode '/' and ' ''
expect(encodeUriSegment('/; /;')).
toEqual('%2F;%20%2F;');
});
});
describe('encodeUriQuery', function() {
it('should correctly encode uri query and not encode chars defined as pchar set in rfc3986',
function() {
//don't encode alphanum
expect(encodeUriQuery('asdf1234asdf')).
toEqual('asdf1234asdf');
//don't encode unreserved
expect(encodeUriQuery("-_.!~*'() -_.!~*'()")).
toEqual("-_.!~*'()+-_.!~*'()");
//don't encode the rest of pchar
expect(encodeUriQuery(':@$, :@$,')).
toEqual(':@$,+:@$,');
//encode '&', ';', '=', '+', and '#'
expect(encodeUriQuery('&;=+# &;=+#')).
toEqual('%26;%3D%2B%23+%26;%3D%2B%23');
//encode ' ' as '+'
expect(encodeUriQuery(' ')).
toEqual('++');
//encode ' ' as '%20' when a flag is used
expect(encodeUriQuery(' ', true)).
toEqual('%20%20');
//do not encode `null` as '+' when flag is used
expect(encodeUriQuery('null', true)).
toEqual('null');
//do not encode `null` with no flag
expect(encodeUriQuery('null')).
toEqual('null');
});
});
describe('angularInit', function() {
var bootstrapSpy;
var element;
beforeEach(function() {
element = {
hasAttribute: function(name) {
return !!element[name];
},
querySelector: function(arg) {
return element.querySelector[arg] || null;
},
getAttribute: function(name) {
return element[name];
}
};
bootstrapSpy = jasmine.createSpy('bootstrapSpy');
});
it('should do nothing when not found', function() {
angularInit(element, bootstrapSpy);
expect(bootstrapSpy).not.toHaveBeenCalled();
});
it('should look for ngApp directive as attr', function() {
var appElement = jqLite('<div ng-app="ABC"></div>')[0];
element.querySelector['[ng-app]'] = appElement;
angularInit(element, bootstrapSpy);
expect(bootstrapSpy).toHaveBeenCalledOnceWith(appElement, ['ABC'], jasmine.any(Object));
});
it('should look for ngApp directive using querySelectorAll', function() {
var appElement = jqLite('<div x-ng-app="ABC"></div>')[0];
element.querySelector['[x-ng-app]'] = appElement;
angularInit(element, bootstrapSpy);
expect(bootstrapSpy).toHaveBeenCalledOnceWith(appElement, ['ABC'], jasmine.any(Object));
});
it('should bootstrap anonymously', function() {
var appElement = jqLite('<div x-ng-app></div>')[0];
element.querySelector['[x-ng-app]'] = appElement;
angularInit(element, bootstrapSpy);
expect(bootstrapSpy).toHaveBeenCalledOnceWith(appElement, [], jasmine.any(Object));
});
it('should bootstrap if the annotation is on the root element', function() {
var appElement = jqLite('<div ng-app=""></div>')[0];
angularInit(appElement, bootstrapSpy);
expect(bootstrapSpy).toHaveBeenCalledOnceWith(appElement, [], jasmine.any(Object));
});
it('should complain if app module cannot be found', function() {
var appElement = jqLite('<div ng-app="doesntexist"></div>')[0];
expect(function() {
angularInit(appElement, angular.bootstrap);
}).toThrowMatching(
new RegExp('\\[\\$injector:modulerr] Failed to instantiate module doesntexist due to:\\n' +
'.*\\[\\$injector:nomod] Module \'doesntexist\' is not available! You either ' +
'misspelled the module name or forgot to load it\\.')
);
});
it('should complain if an element has already been bootstrapped', function() {
var element = jqLite('<div>bootstrap me!</div>');
angular.bootstrap(element);
expect(function() {
angular.bootstrap(element);
}).toThrowMatching(
/\[ng:btstrpd\] App Already Bootstrapped with this Element '<div class="?ng\-scope"?( ng[0-9]+="?[0-9]+"?)?>'/i
);
dealoc(element);
});
it('should complain if manually bootstrapping a document whose <html> element has already been bootstrapped', function() {
angular.bootstrap(document.getElementsByTagName('html')[0]);
expect(function() {
angular.bootstrap(document);
}).toThrowMatching(
/\[ng:btstrpd\] App Already Bootstrapped with this Element 'document'/i
);
dealoc(document);
});
it('should bootstrap in strict mode when ng-strict-di attribute is specified', function() {
bootstrapSpy = spyOn(angular, 'bootstrap').andCallThrough();
var appElement = jqLite('<div ng-app="" ng-strict-di></div>');
angularInit(jqLite('<div></div>').append(appElement[0])[0], bootstrapSpy);
expect(bootstrapSpy).toHaveBeenCalledOnce();
expect(bootstrapSpy.mostRecentCall.args[2].strictDi).toBe(true);
var injector = appElement.injector();
function testFactory($rootScope) {}
expect(function() {
injector.instantiate(testFactory);
}).toThrowMinErr('$injector', 'strictdi');
dealoc(appElement);
});
});
describe('angular service', function() {
it('should override services', function() {
module(function($provide) {
$provide.value('fake', 'old');
$provide.value('fake', 'new');
});
inject(function(fake) {
expect(fake).toEqual('new');
});
});
it('should inject dependencies specified by $inject and ignore function argument name', function() {
expect(angular.injector([function($provide) {
$provide.factory('svc1', function() { return 'svc1'; });
$provide.factory('svc2', ['svc1', function(s) { return 'svc2-' + s; }]);
}]).get('svc2')).toEqual('svc2-svc1');
});
});
describe('isDate', function() {
it('should return true for Date object', function() {
expect(isDate(new Date())).toBe(true);
});
it('should return false for non Date objects', function() {
expect(isDate([])).toBe(false);
expect(isDate('')).toBe(false);
expect(isDate(23)).toBe(false);
expect(isDate({})).toBe(false);
});
});
describe('isRegExp', function() {
it('should return true for RegExp object', function() {
expect(isRegExp(/^foobar$/)).toBe(true);
expect(isRegExp(new RegExp('^foobar$/'))).toBe(true);
});
it('should return false for non RegExp objects', function() {
expect(isRegExp([])).toBe(false);
expect(isRegExp('')).toBe(false);
expect(isRegExp(23)).toBe(false);
expect(isRegExp({})).toBe(false);
expect(isRegExp(new Date())).toBe(false);
});
});
describe('isWindow', function() {
it('should return true for the Window object', function() {
expect(isWindow(window)).toBe(true);
});
it('should return false for any object that is not a Window', function() {
expect(isWindow([])).toBe(false);
expect(isWindow('')).toBeFalsy();
expect(isWindow(23)).toBe(false);
expect(isWindow({})).toBe(false);
expect(isWindow(new Date())).toBe(false);
expect(isWindow(document)).toBe(false);
});
});
describe('compile', function() {
it('should link to existing node and create scope', inject(function($rootScope, $compile) {
var template = angular.element('<div>{{greeting = "hello world"}}</div>');
element = $compile(template)($rootScope);
$rootScope.$digest();
expect(template.text()).toEqual('hello world');
expect($rootScope.greeting).toEqual('hello world');
}));
it('should link to existing node and given scope', inject(function($rootScope, $compile) {
var template = angular.element('<div>{{greeting = "hello world"}}</div>');
element = $compile(template)($rootScope);
$rootScope.$digest();
expect(template.text()).toEqual('hello world');
}));
it('should link to new node and given scope', inject(function($rootScope, $compile) {
var template = jqLite('<div>{{greeting = "hello world"}}</div>');
var compile = $compile(template);
var templateClone = template.clone();
element = compile($rootScope, function(clone) {
templateClone = clone;
});
$rootScope.$digest();
expect(template.text()).toEqual('{{greeting = "hello world"}}');
expect(element.text()).toEqual('hello world');
expect(element).toEqual(templateClone);
expect($rootScope.greeting).toEqual('hello world');
}));
it('should link to cloned node and create scope', inject(function($rootScope, $compile) {
var template = jqLite('<div>{{greeting = "hello world"}}</div>');
element = $compile(template)($rootScope, noop);
$rootScope.$digest();
expect(template.text()).toEqual('{{greeting = "hello world"}}');
expect(element.text()).toEqual('hello world');
expect($rootScope.greeting).toEqual('hello world');
}));
});
describe('nodeName_', function() {
it('should correctly detect node name with "namespace" when xmlns is defined', function() {
var div = jqLite('<div xmlns:ngtest="http://angularjs.org/">' +
'<ngtest:foo ngtest:attr="bar"></ngtest:foo>' +
'</div>')[0];
expect(nodeName_(div.childNodes[0])).toBe('ngtest:foo');
expect(div.childNodes[0].getAttribute('ngtest:attr')).toBe('bar');
});
it('should correctly detect node name with "namespace" when xmlns is NOT defined', function() {
var div = jqLite('<div xmlns:ngtest="http://angularjs.org/">' +
'<ngtest:foo ngtest:attr="bar"></ng-test>' +
'</div>')[0];
expect(nodeName_(div.childNodes[0])).toBe('ngtest:foo');
expect(div.childNodes[0].getAttribute('ngtest:attr')).toBe('bar');
});
it('should return undefined for elements without the .nodeName property', function() {
//some elements, like SVGElementInstance don't have .nodeName property
expect(nodeName_({})).toBeUndefined();
});
});
describe('nextUid()', function() {
it('should return new id per call', function() {
var seen = {};
var count = 100;
while (count--) {
var current = nextUid();
expect(typeof current).toBe('number');
expect(seen[current]).toBeFalsy();
seen[current] = true;
}
});
});
describe('version', function() {
it('version should have full/major/minor/dot/codeName properties', function() {
expect(version).toBeDefined();
expect(version.full).toBe('"NG_VERSION_FULL"');
expect(version.major).toBe("NG_VERSION_MAJOR");
expect(version.minor).toBe("NG_VERSION_MINOR");
expect(version.dot).toBe("NG_VERSION_DOT");
expect(version.codeName).toBe('"NG_VERSION_CODENAME"');
});
});
describe('bootstrap', function() {
it('should bootstrap app', function() {
var element = jqLite('<div>{{1+2}}</div>');
var injector = angular.bootstrap(element);
expect(injector).toBeDefined();
expect(element.injector()).toBe(injector);
dealoc(element);
});
it("should complain if app module can't be found", function() {
var element = jqLite('<div>{{1+2}}</div>');
expect(function() {
angular.bootstrap(element, ['doesntexist']);
}).toThrowMatching(
new RegExp('\\[\\$injector:modulerr\\] Failed to instantiate module doesntexist due to:\\n' +
'.*\\[\\$injector:nomod\\] Module \'doesntexist\' is not available! You either ' +
'misspelled the module name or forgot to load it\\.'));
expect(element.html()).toBe('{{1+2}}');
dealoc(element);
});
describe('deferred bootstrap', function() {
var originalName = window.name,
element;
beforeEach(function() {
window.name = '';
element = jqLite('<div>{{1+2}}</div>');
});
afterEach(function() {
dealoc(element);
window.name = originalName;
});
it('should provide injector for deferred bootstrap', function() {
var injector;
window.name = 'NG_DEFER_BOOTSTRAP!';
injector = angular.bootstrap(element);
expect(injector).toBeUndefined();
injector = angular.resumeBootstrap();
expect(injector).toBeDefined();
});
it('should resume deferred bootstrap, if defined', function() {
var injector;
window.name = 'NG_DEFER_BOOTSTRAP!';
angular.resumeDeferredBootstrap = noop;
var spy = spyOn(angular, "resumeDeferredBootstrap");
injector = angular.bootstrap(element);
expect(spy).toHaveBeenCalled();
});
it('should wait for extra modules', function() {
window.name = 'NG_DEFER_BOOTSTRAP!';
angular.bootstrap(element);
expect(element.html()).toBe('{{1+2}}');
angular.resumeBootstrap();
expect(element.html()).toBe('3');
expect(window.name).toEqual('');
});
it('should load extra modules', function() {
element = jqLite('<div>{{1+2}}</div>');
window.name = 'NG_DEFER_BOOTSTRAP!';
var bootstrapping = jasmine.createSpy('bootstrapping');
angular.bootstrap(element, [bootstrapping]);
expect(bootstrapping).not.toHaveBeenCalled();
expect(element.injector()).toBeUndefined();
angular.module('addedModule', []).value('foo', 'bar');
angular.resumeBootstrap(['addedModule']);
expect(bootstrapping).toHaveBeenCalledOnce();
expect(element.injector().get('foo')).toEqual('bar');
});
it('should not defer bootstrap without window.name cue', function() {
angular.bootstrap(element, []);
angular.module('addedModule', []).value('foo', 'bar');
expect(function() {
element.injector().get('foo');
}).toThrowMinErr('$injector', 'unpr', 'Unknown provider: fooProvider <- foo');
expect(element.injector().get('$http')).toBeDefined();
});
it('should restore the original window.name after bootstrap', function() {
window.name = 'NG_DEFER_BOOTSTRAP!my custom name';
angular.bootstrap(element);
expect(element.html()).toBe('{{1+2}}');
angular.resumeBootstrap();
expect(element.html()).toBe('3');
expect(window.name).toEqual('my custom name');
});
});
});
describe('startingElementHtml', function() {
it('should show starting element tag only', function() {
expect(startingTag('<ng-abc x="2A"><div>text</div></ng-abc>')).
toBe('<ng-abc x="2A">');
});
});
describe('startingTag', function() {
it('should allow passing in Nodes instead of Elements', function() {
var txtNode = document.createTextNode('some text');
expect(startingTag(txtNode)).toBe('some text');
});
});
describe('snake_case', function() {
it('should convert to snake_case', function() {
expect(snake_case('ABC')).toEqual('a_b_c');
expect(snake_case('alanBobCharles')).toEqual('alan_bob_charles');
});
it('should allow separator to be overridden', function() {
expect(snake_case('ABC', '&')).toEqual('a&b&c');
expect(snake_case('alanBobCharles', '&')).toEqual('alan&bob&charles');
});
});
describe('fromJson', function() {
it('should delegate to JSON.parse', function() {
var spy = spyOn(JSON, 'parse').andCallThrough();
expect(fromJson('{}')).toEqual({});
expect(spy).toHaveBeenCalled();
});
});
describe('toJson', function() {
it('should delegate to JSON.stringify', function() {
var spy = spyOn(JSON, 'stringify').andCallThrough();
expect(toJson({})).toEqual('{}');
expect(spy).toHaveBeenCalled();
});
it('should format objects pretty', function() {
expect(toJson({a: 1, b: 2}, true)).
toBe('{\n "a": 1,\n "b": 2\n}');
expect(toJson({a: {b: 2}}, true)).
toBe('{\n "a": {\n "b": 2\n }\n}');
expect(toJson({a: 1, b: 2}, false)).
toBe('{"a":1,"b":2}');
expect(toJson({a: 1, b: 2}, 0)).
toBe('{"a":1,"b":2}');
expect(toJson({a: 1, b: 2}, 1)).
toBe('{\n "a": 1,\n "b": 2\n}');
expect(toJson({a: 1, b: 2}, {})).
toBe('{\n "a": 1,\n "b": 2\n}');
});
it('should not serialize properties starting with $$', function() {
expect(toJson({$$some:'value'}, false)).toEqual('{}');
});
it('should serialize properties starting with $', function() {
expect(toJson({$few: 'v'}, false)).toEqual('{"$few":"v"}');
});
it('should not serialize $window object', function() {
expect(toJson(window)).toEqual('"$WINDOW"');
});
it('should not serialize $document object', function() {
expect(toJson(document)).toEqual('"$DOCUMENT"');
});
it('should not serialize scope instances', inject(function($rootScope) {
expect(toJson({key: $rootScope})).toEqual('{"key":"$SCOPE"}');
}));
it('should serialize undefined as undefined', function() {
expect(toJson(undefined)).toEqual(undefined);
});
});
describe('isElement', function() {
it('should return a boolean value', inject(function($compile, $document, $rootScope) {
var element = $compile('<p>Hello, world!</p>')($rootScope),
body = $document.find('body')[0],
expected = [false, false, false, false, false, false, false, true, true],
tests = [null, undefined, "string", 1001, {}, 0, false, body, element];
angular.forEach(tests, function(value, idx) {
var result = angular.isElement(value);
expect(typeof result).toEqual('boolean');
expect(result).toEqual(expected[idx]);
});
}));
// Issue #4805
it('should return false for objects resembling a Backbone Collection', function() {
// Backbone stuff is sort of hard to mock, if you have a better way of doing this,
// please fix this.
var fakeBackboneCollection = {
children: [{}, {}, {}],
find: function() {},
on: function() {},
off: function() {},
bind: function() {}
};
expect(isElement(fakeBackboneCollection)).toBe(false);
});
it('should return false for arrays with node-like properties', function() {
var array = [1,2,3];
array.on = true;
expect(isElement(array)).toBe(false);
});
});
});
|
'use strict';
var myLevels = (function() {
var myLevels = {
clearWorld: clearWorld,
addFourWalls: addFourWalls,
addLeftWall: addLeftWall,
addRightWall: addRightWall,
addGround: addGround,
addCeiling: addCeiling,
catapult: catapult,
newtonsCradle: newtonsCradle,
car: car
};
function clearWorld() {
Matter.World.clear(myMatter.world, false);
Matter.World.add(myMatter.world, myMatter.mouseConstraint);
myLevels.addFourWalls(myMatter);
}
function catapult() {
myLevels.clearWorld();
var stack = Matter.Composites.stack(250, 255, 1, 6, 0, 0, function(x, y) {
var body = Matter.Bodies.rectangle(x, y, 30, 30);
body.isMoveable = true;
return body;
});
var catapult = Matter.Bodies.rectangle(400, 540, 320, 20, {});
catapult.isMoveable = true;
var catapult_stand_left = Matter.Constraint.create({bodyA: catapult, pointB: {x: 390, y: 600}});
var catapult_stand_right = Matter.Constraint.create({bodyA: catapult, pointB: {x: 410, y: 600}});
var holder = Matter.Bodies.rectangle(250, 580, 20, 60, {isStatic: true});
var ball = Matter.Bodies.circle(560, 100, 50, {density: 0.005});
ball.isMoveable = true;
var elements = [
stack,
catapult,
catapult_stand_left,
catapult_stand_right,
holder,
ball
];
// add all of the bodies to the world
Matter.World.add(myMatter.world, elements);
}
function newtonsCradle() {
myLevels.clearWorld();
var cradle = Matter.Composites.newtonsCradle(280, 180, 7, 20, 140);
markCompoundAsMovable(cradle);
Matter.World.add(myMatter.world, cradle);
Matter.Body.translate(cradle.bodies[0], { x: -140, y: -100 });
}
function car() {
myLevels.clearWorld();
var scale = 0.9;
var car = Matter.Composites.car(150, 100, 100 * scale, 40 * scale, 30 * scale);
markCompoundAsMovable(car);
Matter.World.add(myMatter.world, car);
scale = 0.8;
car = Matter.Composites.car(350, 300, 100 * scale, 40 * scale, 30 * scale);
markCompoundAsMovable(car);
Matter.World.add(myMatter.world, car);
Matter.World.add(myMatter.world, [
Matter.Bodies.rectangle(200, 150, 650, 20, { isStatic: true, angle: Math.PI * 0.06 }),
Matter.Bodies.rectangle(500, 350, 650, 20, { isStatic: true, angle: -Math.PI * 0.06 }),
Matter.Bodies.rectangle(340, 580, 700, 20, { isStatic: true, angle: Math.PI * 0.04 })
]);
}
function markCompoundAsMovable(compound) {
for (var index in compound.bodies) {
compound.bodies[index].isMoveable = true;
}
}
function addFourWalls(matter) {
myLevels.addLeftWall(matter);
myLevels.addRightWall(matter);
myLevels.addGround(matter);
myLevels.addCeiling(matter);
}
function addLeftWall(matter) {
var wall_left = Matter.Bodies.rectangle(-51, 0, 100, 1260, {isStatic: true});
Matter.World.add(matter.world, wall_left);
}
function addRightWall(matter) {
var wall_right = Matter.Bodies.rectangle(851, 0, 100, 1260, {isStatic: true});
Matter.World.add(matter.world, wall_right);
}
function addGround(matter) {
var ground = Matter.Bodies.rectangle(400, 651, 900, 100, {isStatic: true});
Matter.World.add(matter.world, ground);
}
function addCeiling(matter) {
var ceiling = Matter.Bodies.rectangle(400, -51, 810, 100, {isStatic: true});
Matter.World.add(matter.world, ceiling);
}
return myLevels;
})();
|
// Karma configuration
// Generated on Tue Mar 01 2016 12:07:06 GMT+0000 (GMT)
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'dist/*.js',
'test/*.js',
'test/test.html'
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'dist/*.js': ['webpack'],
'test/*.js': ['webpack'],
'test/*.html': ['html2js']
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['dots'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['Chrome'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false,
// Concurrency level
// how many browser should be started simultaneous
concurrency: Infinity,
webpackServer: {
noInfo: true // please don't spam the console when running in karma!
}
})
};
|
// Invoke 'strict' JavaScript mode
'use strict';
// Set the main application name
var mainApplicationModuleName = 'mean';
// Create the main application
var mainApplicationModule = angular.module(mainApplicationModuleName, ['ngResource', 'ngRoute', 'users', 'example', 'articles','smartplugs','devices','powers','graphs','schedule']);
// Configure the hashbang URLs using the $locationProvider services
mainApplicationModule.config(['$locationProvider',
function($locationProvider) {
$locationProvider.hashPrefix('!');
}
]);
// Fix Facebook's OAuth bug
if (window.location.hash === '#_=_') window.location.hash = '#!';
// Manually bootstrap the AngularJS application
angular.element(document).ready(function() {
angular.bootstrap(document, [mainApplicationModuleName]);
}); |
var zousan = require('zousan');
require('../lib/fakesP');
module.exports = function upload(stream, idOrPath, tag, done) {
var blob = blobManager.create(account);
var tx = db.begin();
var blobIdP = blob.put(stream);
var fileP = self.byUuidOrPath(idOrPath).get();
var version, fileId, file;
zousan.all([blobIdP, fileP]).then(function(all) {
var blobId = all[0], fileV = all[1];
file = fileV;
var previousId = file ? file.version : null;
version = {
userAccountId: userAccount.id,
date: new Date(),
blobId: blobId,
creatorId: userAccount.id,
previousId: previousId,
};
version.id = Version.createHash(version);
return Version.insert(version).execWithin(tx);
}).then(function() {
if (!file) {
var splitPath = idOrPath.split('/');
var fileName = splitPath[splitPath.length - 1];
var newId = uuid.v1();
return self.createQuery(idOrPath, {
id: newId,
userAccountId: userAccount.id,
name: fileName,
version: version.id
}).then(function(q) {
return q.execWithin(tx);
}).then(function() {
return newId;
});
} else {
return file.id;
}
}).then(function(fileIdV) {
fileId = fileIdV;
return FileVersion.insert({
fileId: fileId,
versionId: version.id
}).execWithin(tx);
}).then(function() {
return File.whereUpdate({id: fileId}, {version: version.id})
.execWithin(tx);
}).then(function() {
tx.commit();
return done();
}, function(err) {
tx.rollback();
return done(err);
});
}
|
/**
* Copyright 2017-present, Callstack.
* All rights reserved.
*
* @flow
*/
import stripAnsi from 'strip-ansi';
import logger from '../logger';
beforeEach(() => {
// $FlowFixMe
console.log = jest.fn();
});
afterEach(() => jest.clearAllMocks());
test('section logs are always separated by one newline', () => {
logger.info('single line');
logger.info('multiple', 'entries');
logger.info('single line', 'with a newline\n');
logger.warn('single line');
logger.warn('multiple', 'entries');
logger.warn('single line', 'with a newline\n');
logger.error('single line');
logger.error('multiple', 'entries');
logger.error('single line', 'with a newline\n');
logger.done('single line');
logger.done('multiple', 'entries');
logger.done('single line', 'with a newline\n');
const { calls } = console.log.mock;
const logs = calls.map(call => call.join(' ')).join('\n');
expect(stripAnsi(logs)).toMatchSnapshot();
});
test('debug logs are displayed without extra newlines', () => {
logger.debug('pigeon', 'no space above');
logger.debug('pigeon', 'no space above, but has newline\n');
logger.debug('pigeon', 'space above');
const { calls } = console.log.mock;
const logs = calls.map(call => call.join(' ')).join('\n');
expect(stripAnsi(logs)).toMatchSnapshot();
});
|
'use strict'
var uniqid = require('uniqid');
var Promise = require('bluebird');
var validate = require('./validator');
var utils = require('../utils');
var processDividends = require('../dividend');
/**
* Result class
* @constructor
* @param {first} - first position the race
* @param {second} - second position the race
* @param {third} - third position the race
* @param {raceId} - Id of the current race
*/
function Result(first, second, third, raceId) {
this.resultId = uniqid();
this.first = first;
this.second = second;
this.third = third;
this.raceId = raceId;
}
/**
* This function takes the result string,parses it,
* validates the same before storing those in the storage.
*
* @param {resultString} - input string for result
* @param {raceId} - Id of the current race
* @param {cb} - callback
*/
Result.create = function (resultString, raceId, cb){
Promise.promisify(utils.parseResult)(resultString)
.then(function(parsedResult){
return parsedResult;
}).then(function(parsedResult){
return Promise.promisify(validate)(parsedResult.first, parsedResult.second, parsedResult.third)
.then(function(){
return parsedResult;
});
}).then(function(parsedResult){
var result = new Result (parsedResult.first, parsedResult.second, parsedResult.third, raceId);
return Promise.promisify(utils.create)('./db/', 'results.json', result)
.then(function(){
return result;
});
}).then(function(result){
// Calling method to process the dividend
return Promise.promisify(processDividends)(result)
.then(function(output){
return cb(null, output);
});
}).catch(function(err){
console.log("Error in validating/saving the result info.", err);
cb(err);
});
}
module.exports = Result; |
// Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '@angular-devkit/build-angular'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage-istanbul-reporter'),
require('@angular-devkit/build-angular/plugins/karma')
],
client: {
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
coverageIstanbulReporter: {
dir: require('path').join(__dirname, '../coverage'), reports: ['html', 'lcovonly'],
fixWebpackSourcePaths: true
},
reporters: ['progress', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false,
browserNoActivityTimeout: 80000,
browserDisconnectTimeout: 10000,
browserDisconnectTolerance: 1,
captureTimeout: 80000
});
};
|
//var context = require.context('./test', true, /.+\.spec\.jsx?$/);
//
//require('core-js/es5');
//
//context.keys().forEach(context);
//module.exports = context;
|
{
var node = createNode(
"<i>" +
"<i>1</i>" +
"<i>" +
"<i>" +
"<i>2</i>" +
"<i></i>" +
"</i>" +
"</i>" +
"<i>" +
"3" +
"<i>45</i>" +
"</i>" +
"</i>"
);
expectNodeOffset(getNodeForCharacterOffset(node, 3), "3", 1);
expectNodeOffset(getNodeForCharacterOffset(node, 5), "45", 2);
expect(getNodeForCharacterOffset(node, 10)).toBeUndefined();
}
|
(function (tree) {
tree.Operation = function (op, operands, isSpaced) {
this.op = op.trim();
this.operands = operands;
this.isSpaced = isSpaced;
};
tree.Operation.prototype = {
type: "Operation",
accept: function (visitor) {
this.operands = visitor.visit(this.operands);
},
eval: function (env) {
var a = this.operands[0].eval(env),
b = this.operands[1].eval(env),
temp;
if (env.isMathOn()) {
if (a instanceof tree.Dimension && b instanceof tree.Color) {
if (this.op === '*' || this.op === '+') {
temp = b, b = a, a = temp;
} else {
throw { type: "Operation",
message: "Can't substract or divide a color from a number" };
}
}
if (!a.operate) {
throw { type: "Operation",
message: "Operation on an invalid type" };
}
return a.operate(env, this.op, b);
} else {
return new(tree.Operation)(this.op, [a, b], this.isSpaced);
}
},
toCSS: function (env) {
var separator = this.isSpaced ? " " : "";
return this.operands[0].toCSS() + separator + this.op + separator + this.operands[1].toCSS();
}
};
tree.operate = function (env, op, a, b) {
switch (op) {
case '+': return a + b;
case '-': return a - b;
case '*': return a * b;
case '/': return a / b;
}
};
})(require('../tree'));
|
var BaseError = require('./baseError');
var captureStackTrace = require('capture-stack-trace');
function ServiceUnavailable() {
BaseError.apply(this, arguments);
captureStackTrace(this, ServiceUnavailable);
}
ServiceUnavailable.prototype = Object.create(BaseError.prototype);
ServiceUnavailable.prototype.constructor = ServiceUnavailable;
ServiceUnavailable.prototype.code = 503;
module.exports = ServiceUnavailable;
|
// @flow
import React from 'react'
import { shallow } from 'enzyme'
import toJson from 'enzyme-to-json'
import Comp from '../../pages/index'
test('snapshot', () => {
const x = shallow(<Comp />)
expect(toJson(x)).toMatchSnapshot()
})
|
/**
* Created by user on 7/19/14.
*/
jQuery(function () {
jQuery('#migrationutility-databasetables').bind('change',
function () {
var val = jQuery(this).find('option:selected').text();
if (val) {
var $elm = jQuery('#migrationutility-tables');
var val2 = $elm.val().replace(val + ',', '');
val = val2 + ',' + val;
val = val.replace(/,+/gi, ',').replace(/\s+/gi, '').replace(/^,/, '');
$elm.val(val);
}
});
});
jQuery(function () {
jQuery.fn.selectText = function () {
this.find('input').each(function () {
if ($(this).prev().length == 0 || !$(this).prev().hasClass('p_copy')) {
$('<p class="p_copy" style="position: absolute; z-index: -1;"></p>').insertBefore($(this));
}
$(this).prev().html($(this).val());
});
var doc = document;
var element = this[0];
console.log(this, element);
if (doc.body.createTextRange) {
var range = document.body.createTextRange();
range.moveToElementText(element);
range.select();
} else if (window.getSelection) {
var selection = window.getSelection();
var range = document.createRange();
range.selectNodeContents(element);
selection.removeAllRanges();
selection.addRange(range);
}
};
jQuery('#button-add-all')
.click(function () {
var $tables = jQuery('#migrationutility-tables');
$tables.val("");
jQuery("#migrationutility-databasetables > option")
.each(function () {
if (this.text != 'migration') {
$tables.val($tables.val() + ',' + this.text);
}
});
$tables.val($tables.val().replace(/^,+/, ''));
});
jQuery('#button-select-all')
.click(function () {
jQuery('#code-output').selectText();
});
jQuery('#button-select-all-drop')
.click(function () {
jQuery('#code-output-drop').selectText();
});
jQuery('#button-tables-convert')
.click(function () {
var $this = jQuery('#migrationutility-tables');
var $parent = $this.parent();
if ($this.attr('type') == "text") {
var $textarea = jQuery(document.createElement('textarea'));
$textarea.attr('id', $this.attr('id'));
$textarea.attr('type', 'textarea');
$textarea.attr('class', $this.attr('class'));
$textarea.attr('name', $this.attr('name'));
$textarea.html($this.val().replace(/\s+/g, '').replace(/,/g, "\n"));
$this.remove();
jQuery($textarea).insertAfter($parent.find('> label'));
} else {
var $input = jQuery(document.createElement('input'));
$input.attr('id', $this.attr('id'));
$input.attr('type', 'text');
$input.attr('class', $this.attr('class'));
$input.attr('name', $this.attr('name'));
$input.val($this.html().replace(/[\r\n]/g, ", "));
$this.remove();
jQuery($input).insertAfter($parent.find('> label'));
}
jQuery('#migrationutility-tables').blur();
});
});
|
import Resolution from '@unstoppabledomains/resolution';
import { toChecksumAddress } from 'web3-utils';
import Web3 from 'web3';
export default class UNS {
constructor(network, web3) {
const networkname = 'mainnet';
const polyname = 'polygon-mainnet';
const polyprovider = new Web3('https://nodes.mewapi.io/rpc/matic');
const resolution = Resolution.fromWeb3Version1Provider({
ens: false,
uns: {
locations: {
Layer1: {
network: networkname,
provider: web3.currentProvider
},
Layer2: {
network: polyname,
provider: polyprovider.currentProvider
}
}
}
});
this.resolver = resolution;
}
resolveName(name) {
return this.resolver
.addr(name, 'ETH')
.then(addr => toChecksumAddress(addr));
}
}
|
/* global QUnit */
import { DiscreteInterpolant } from '../../../../../src/math/interpolants/DiscreteInterpolant';
export default QUnit.module( 'Maths', () => {
QUnit.module( 'Interpolants', () => {
QUnit.module( 'DiscreteInterpolant', () => {
// INHERITANCE
QUnit.todo( 'Extending', ( assert ) => {
assert.ok( false, 'everything\'s gonna be alright' );
} );
// INSTANCING
QUnit.todo( 'Instancing', ( assert ) => {
assert.ok( false, 'everything\'s gonna be alright' );
} );
} );
} );
} );
|
'use strict';
// MODULES //
// PROPERTIES //
var props = {};
/**
* Element width.
*
* @type {Number}
* @default 500
*/
props.width = {
type: Number,
value: 500,
observer: '_widthChanged'
};
/**
* Background color of editor.
*
* @type {String}
* @default #FFFFFF
*/
props.backgroundColor = {
type: String,
value: '#FFFFFF'
};
/**
* Code to be evaluated.
*
* @type {String}
* @default undefined
*/
props.code = {
type: String,
observer: '_codeChanged'
};
/**
* Returned value of code evaluation.
*
* @type {String}
* @default empty string
*/
props.output = {
type: String,
readOnly: true,
value: ''
};
/**
* ACE-Editor object.
*
* @type {Object}
* @default undefined
*/
props.editor = {
type: Object
}
/**
* Whether ACE-editor event listeners are invoked or not.
*
* @type {Boolean}
* @default false
*/
props.silent = {
type: Boolean,
value: false
}
// EXPORTS //
module.exports = props;
|
var WebpackTapeRun = require('webpack-tape-run')
var path = require('path')
module.exports = {
entry: {
index: './index.test.js'
},
context: __dirname,
node: {
fs: 'empty' // otherwise require('tape') throws
},
output: {
filename: '[name].test.js',
path: path.join(__dirname, 'dist')
},
mode: 'development',
module: {
rules: [
{
// Due to problems in serving static files with tape-run,
// we import images as data URLs.
test: /\.(png|jpg|gif)$/,
use: 'url-loader'
},
{
test: /\.css$/,
use: [
{ loader: 'style-loader' },
{ loader: 'css-loader' }
]
}
]
},
plugins: [
new WebpackTapeRun({
tapeRun: {
browser: 'electron'
// port: 8000,
// node: true, // allows fs
// keepOpen: false,
// static: path.join(__dirname, 'lib'),
// basedir: path.join(__dirname, 'dist'),
},
reporter: 'tap-spec'
})
],
devtool: 'eval-source-map',
stats: 'minimal'
}
|
var _ = lodash;
var theme = {
debug: 'blue',
order: 'magenta'
};
if (Meteor.isServer) {
var colors = Npm.require('colors');
colors.setTheme(theme);
}
Meteor._ensure(Meteor, 'settings', 'public');
var debugEnabled = Meteor.settings.public.debug;
var logColor = function(msg, color) {
if (msg && color) {
if (_.has(theme, color)) {
color = theme[color];
}
if (Meteor.isClient) {
console.log('%c' + msg, 'color: ' + color);
} else if (Meteor.isServer) {
console.log(msg[color]);
}
} else {
console.log(msg);
}
};
var logDebug = function(namespace, color) {
if (!debugEnabled) {
return function() {};
}
color = color || 'debug'; // debug is the default color
return function() {
var desc, obj;
if (arguments.length === 2) {
desc = arguments[0];
obj = arguments[1];
} else {
obj = arguments[0];
}
var c = '';
if (namespace) {
c += namespace;
}
if (desc) {
c += ' - ' + desc;
}
logColor('[▼ ' + c + ' ▼]', color);
logColor(obj, color);
logColor('[▲ ' + c + ' ▲]', color);
};
};
Debug = {
enabled: debugEnabled,
log: logDebug('debug'),
order: function(filename) {
debugEnabled && logColor('Load: ' + filename, 'order');
}
};
// TODO delete this
// means debug for the package app-<key>
var packages = ['feed', 'home', 'login', 'messaging', 'menu', 'offers', 'users', 'utils', 'collections'];
_.each(packages, function(package) {
Debug[package] = logDebug('app-' + package);
});
// DELETE THIS END
if (debugEnabled) {
logColor('Debug enabled', 'red');
}
|
require('../testing-lib.js');
describe('Tester Core', function() {
const TesterCore = require('../src/TesterCore.js');
testThat('testThat should pass if nothing fails', function() {
var testPassed = false,
tester = new TesterCore();
tester.testThat('something', function() {
testPassed = true;
});
if(!testPassed) {
fail();
}
});
testThat('beforeEach should be run before each test', function() {
var step = 1,
steps = '',
tester = new TesterCore();
tester.beforeEach(function() {
steps += step.toString();
step++;
});
['a', 'b', 'c'].forEach(function(letter) {
tester.testThat('something', function() {
steps += letter;
});
});
if(steps !== '1a2b3c') {
fail();
}
});
var tester;
beforeEach(function() {
tester = new TesterCore();
});
testThat('assertThat should pass if assertion is true', function() {
var testPassed = false;
tester.testThat('something', function() {
assertThat(true, isTrue);
testPassed = true;
});
if(!testPassed) {
fail();
}
});
testThat('assertThat should fail test if assertion failed', function() {
var testFailed = false;
tester.testThat('something', function() {
assertThat(false, isTrue);
testFailed = true;
});
if(testFailed) {
fail();
}
});
testThat('testThat should be true if nothing fails', function() {
assertThat(
tester.testThat('something', function() {}).passed,
isTrue
);
});
testThat('testThat should be false if something fails', function() {
assertThat(
tester.testThat('something', fail).passed,
isFalse
);
});
testThat('describe should run the tests it contains', function() {
var numberOfRunTests = 0;
tester.describe('a feature', function() {
tester.testThat('a 1st test', function() {
numberOfRunTests++;
});
tester.testThat('a 2nd test', function() {
numberOfRunTests++;
})
});
assertThat(numberOfRunTests, equals(2));
});
testThat('describe should reset the beforeEach function after it is done', function() {
var steps = '';
tester.beforeEach(function() {
steps += 'a';
});
tester.testThat('', function() {});
tester.describe('b', function() {
tester.beforeEach(function() {
steps += 'b';
});
});
tester.testThat('', function() {});
assertThat(steps, equals('aa'));
});
testThat('describe should call the previous beforeEach function before its own', function() {
var steps = '';
tester.beforeEach(function() {
steps += 'a';
});
tester.testThat('', function() {});
tester.describe('b', function() {
tester.beforeEach(function() {
steps += 'b';
});
tester.testThat('', function() {});
});
tester.testThat('', function() {});
assertThat(steps, equals('aaba'));
});
testThat('testThat should return the name of the test', function() {
assertThat(
tester.testThat('the name of the test', function() {}).name,
equals('the name of the test'));
assertThat(
tester.testThat('the name of the test', function() { fail(); }).name,
equals('the name of the test'));
});
testThat('describe should return the description', function() {
var description = tester.describe('a description', function() {});
assertThat(description.name, equals('a description'));
});
testThat('describe should return a list of the tests it contains', function() {
var description = tester.describe('a description', function() {
tester.testThat('a test', function() {});
tester.testThat('a second test', function() {});
tester.testThat('a third test', function() {});
});
assertThat(description.tests.length, equals(3));
});
}); |
// test source file
App = Ember.Application.create();
App.Router.map(function() {
// put your routes here
});
App.IndexRoute = Ember.Route.extend({
model: function() {
return ['red', 'yellow', 'blue'];
}
}); |
/**
* HashMap - type utility
* @author Francis Desjardins <me@francisdesjardins.ca>
* Homepage: https://github.com/francisdesjardins/hashmap
*/
'use strict';
// Module dependencies.
var toString = Object.prototype.toString;
// Module variables.
var typeRegEx = /\[object (\S*)\]/gi;
// Module definition.
/**
* @param {*} target
* @returns {!string}
*/
module.exports = function (target) {
var type = toString.apply(target).replace(typeRegEx, '$1').toLowerCase();
if (type === 'number' && isNaN(target)) {
return 'nan';
}
if (type === 'object') {
switch (target) {
case null:
return 'null';
case undefined:
return 'undefined';
default:
return type;
}
}
return type;
};
|
import { Meteor } from 'meteor/meteor';
import { check, Match } from 'meteor/check';
import Records from '../records.js';
import intervalRecords from '../../../queries/records/interval-records';
// publish all records of a given user
Meteor.publish('records.all', function recordsAll() {
return Records.find({ userId: this.userId });
});
Meteor.publish('records.interval', function recordsInterval(
{ start, end },
sort = -1,
) {
check(start, Date);
check(end, Date);
check(sort, Match.OneOf(-1, 1));
const query = intervalRecords({ start, end }, sort);
return Records.find(
{
userId: this.userId,
...query.find,
},
query.options,
);
});
Meteor.publish('records.incomplete', function incomplete() {
return Records.find(
{
userId: this.userId,
end: null,
},
{
sort: { begin: 1 },
},
);
});
|
/**
* Testing our Button component
*/
import React from 'react';
import { mount } from 'enzyme';
import Button from '../index';
const handleRoute = () => {};
const href = 'http://google.com';
const children = (<h1>Test</h1>);
const renderComponent = (props = {}) => mount(
<Button href={href} {...props}>
{children}
</Button>
);
describe('<Button />', () => {
it('should render a <button> tag', () => {
const renderedComponent = renderComponent({ handleRoute });
expect(renderedComponent.find('button').length).toEqual(1);
});
it('should have children', () => {
const renderedComponent = renderComponent();
expect(renderedComponent.contains(children)).toEqual(true);
});
it('should handle click events', () => {
const onClickSpy = jest.fn();
const renderedComponent = renderComponent({ onClick: onClickSpy });
renderedComponent.find('a').simulate('click');
expect(onClickSpy).toHaveBeenCalled();
});
it('should have a className attribute', () => {
const renderedComponent = renderComponent();
expect(renderedComponent.find('a').prop('className')).toBeDefined();
});
it('should not adopt a type attribute when rendering a button', () => {
const type = 'submit';
const renderedComponent = renderComponent({ handleRoute, type });
expect(renderedComponent.find('button').prop('type')).toBeUndefined();
});
});
|
import React from 'react';
import IconBase from '@suitejs/icon-base';
function MdGames(props) {
return (
<IconBase viewBox="0 0 48 48" {...props}>
<path d="M30 15V4H18v11l6 6 6-6zm-15 3H4v12h11l6-6-6-6zm3 15v11h12V33l-6-6-6 6zm15-15l-6 6 6 6h11V18H33z" />
</IconBase>
);
}
export default MdGames;
|
exports = module.exports = function(express, middleware, handlers, path) {
var router = express();
router.route(path)
.all(middleware.isLoggedIn)
.get(handlers.message);
return router;
};
|
/*jslint node: true */
'use strict';
var moment = require('moment');
var uuid = require('node-uuid');
var faker = require('faker');
var TASKNAME = 'telepathy.backends.finance.trade';
function pendingJob(portfolio) {
return {
id: portfolio,
report: {
done: false,
elapsed: 60.03192901611328,
id: "Pilot",
state: "PENDING",
status: "PENDING",
task: "telepathy.backends.finance.trade",
task_id: uuid.v4()
}
};
}
function errorJob(portfolio) {
return {
id: portfolio,
report: {
done: true,
elapsed: 31.24971294403076,
failed: true,
id: "Pilot",
result: faker.Lorem.sentence(),
state: "FAILURE",
status: "FAILURE",
successful: false,
task: TASKNAME,
task_id: uuid.v4(),
traceback: faker.Lorem.paragraph()
}
};
}
function successJob(portfolio) {
return {
id: portfolio,
report: {
done: true,
elapsed: 170.38032007217407,
failed: false,
id: "Pilot",
result: {
algo_volatility: 0.8654841034599652,
algorithm_period_return: 0.78819989457053,
alpha: 1.375590744167798,
benchmark_period_return: -0.0980472764645417,
benchmark_volatility: 0.22661920195874466,
beta: 0.06383225545862309,
excess_return: 0.76209989457053,
information: 1.8045140577751067,
max_drawdown: 0.36556258963082855,
period_label: "2013-07",
sharpe: 1.5747205673166411,
sortino: 2.553627859601561,
trading_days: 143,
treasury_period_return: 0.0261
},
state: "SUCCESS",
status: "SUCCESS",
successful: true,
task: TASKNAME,
task_id: uuid.v4()
}
};
}
module.exports = {
postFeedback: function(portfolio) {
return {
enqueued: true,
id: portfolio,
start: moment().format('X'),
task_id: uuid.v4()
};
},
report: function(portfolio, state) {
var data = [];
if (portfolio) {
switch(state) {
case 'pending':
data.push(pendingJob(portfolio));
break;
case 'success':
data.push(successJob(portfolio));
break;
case 'error':
data.push(errorJob(portfolio));
break;
default:
data.push(pendingJob(portfolio));
}
}
return {workers: data};
},
notFound: function(wrongPortfolio) {
return {
data: {error: wrongPortfolio + ' not found in database'}
}
}
}
|
(function () {
'use strict';
/*global angular, platform, Audio */
/**
* This is the controller for cheat.
*
* The board has three section, holding the cards of the player one, player
* two and the middle area's.
*
* The section for player one is the main section, from the point of the
* player's view. All cards are sorted according to ranks.
*
* The section for player two is usually hidden which holds the opponent's
* cards.
*
* The section for middle area holds all the claimed and selected cards.
* Claimed cards will remain hidden and the selected cards are not until
* claimed.
*/
angular.module('myApp').controller('CheatCtrl',
['$scope', '$animate', '$timeout', '$q', 'cheatLogicService', 'gameService',
function ($scope, $animate, $timeout, $q, cheatLogicService, gameService) {
// Get the stage objects for convenience
var STAGE = cheatLogicService.STAGE;
// Return true if the card (index) is selected
$scope.isSelected = function(card) {
return $scope.middle.indexOf(card) !== -1;
};
// Return true if at least one card is selected
$scope.hasSelectedCards = function() {
// The cards in the middle area is more than the cards in the state's
// original middle area
return $scope.middle.length > $scope.state.middle.length;
};
// Return true if the card can be dragged/selected...
$scope.canDrag = function (card) {
if ($scope.isYourTurn && $scope.state.stage === STAGE.DO_CLAIM && $scope.state["card" + card] != null) {
if ($scope.middle.indexOf(card) !== -1) {
return true;
} else if ($scope.middle.length - $scope.state.middle.length < 4) {
return true;
}
}
return false;
};
// Store the card for later use during drag and drop
$scope.storeDraggingCard = function (card) {
$scope.draggingCard = parseInt(card);
};
// Select a card
$scope.selectCard = function(card) {
if ($scope.isYourTurn && $scope.state.stage === STAGE.DO_CLAIM) {
if ($scope.playMode === 'passAndPlay' && $scope.currIndex == 1) {
if ($scope.middle.indexOf(card) !== -1) {
$scope.middle.splice($scope.middle.indexOf(card), 1);
$scope.playerTwoCards.push(card);
} else if ($scope.middle.length - $scope.state.middle.length < 4) {
// Only select at most 4 cards!
if ($scope.playerTwoCards.indexOf(card) !== -1) {
$scope.playerTwoCards.splice($scope.playerTwoCards.indexOf(card), 1);
$scope.middle.push(card);
}
}
} else {
// Must select in the player's turn
if ($scope.middle.indexOf(card) !== -1) {
// The card is already selected, hence cancel the selection
// First delete the card in the middle area, then add it back
// to the player one area
$scope.middle.splice($scope.middle.indexOf(card), 1);
$scope.playerOneCards.push(card);
} else if ($scope.middle.length - $scope.state.middle.length < 4) {
// Only select at most 4 cards!
if ($scope.playerOneCards.indexOf(card) !== -1) {
// Select the card.
// First delete it from player one area, then add it to the
// middle area
$scope.playerOneCards.splice($scope.playerOneCards.indexOf(card), 1);
$scope.middle.push(card);
}
}
}
}
sortRanks();
// In case the board is not updated
if (!$scope.$$phase) {
$scope.$apply();
}
};
// Check the current stage
$scope.checkStage = function(stage) {
if (angular.isUndefined($scope.state)) {
return false;
}
return $scope.state.stage === stage;
};
// Make a claim
$scope.claim = function(rank) {
$('#doClaimModal').modal('hide');
var claim = [$scope.middle.length - $scope.state.middle.length, rank];
var diffM = $scope.middle.clone();
diffM.selfSubtract($scope.state.middle);
var operations = cheatLogicService.getClaimMove($scope.state, $scope.currIndex, claim, diffM);
gameService.makeMove(operations)
};
// Declare a cheater or pass
$scope.declare = function (declareCheater) {
$('#declareModal').modal('hide');
var operations = cheatLogicService.getDeclareCheaterMove($scope.state, $scope.currIndex, declareCheater);
gameService.makeMove(operations)
};
// Get the card data value for css usage
$scope.getCardDataValue = function(i) {
var dataValue = " ";
if ($scope.state['card' + i] !== null) {
var card = $scope.state['card' + i];
var suit = card.substring(0, 1);
var suitChar;
var rank = card.substring(1);
switch (suit) {
case "D":
suitChar = '\u2666';
break;
case "H":
suitChar = "\u2665";
break;
case "S":
suitChar = "\u2660";
break;
case "C":
suitChar = "\u2663";
break;
}
dataValue = rank + " " + suitChar;
}
return dataValue;
};
// Sort the cards according to the ranks
function sortRanks() {
var sortFunction = function(cardA, cardB) {
if ($scope.state["card" + cardA] !== null) {
// Only sort the cards while they are not hidden
var rankA = $scope.state["card" + cardA].substring(1);
var rankB = $scope.state["card" + cardB].substring(1);
var scoreA = cheatLogicService.getRankScore(rankA);
var scoreB = cheatLogicService.getRankScore(rankB);
return scoreA - scoreB;
}
return 1;
};
$scope.playerOneCards.sort(sortFunction);
$scope.playerTwoCards.sort(sortFunction);
}
// Update the ranks for claiming
function updateClaimRanks () {
if (angular.isUndefined($scope.state.claim)) {
$scope.claimRanks = cheatLogicService.getRankArray();
} else {
var rank = $scope.state.claim[1];
$scope.claimRanks = cheatLogicService.getRankArray(rank);
}
}
// Check the declaration
function checkDeclaration() {
var operations = cheatLogicService.getMoveCheckIfCheated($scope.state, $scope.currIndex);
gameService.makeMove(operations);
}
// Check if there's a winner
function hasWinner() {
return cheatLogicService.getWinner($scope.state) !== -1;
}
// Check if the game ends, and if so, send the end game operations
function checkEndGame() {
if (hasWinner() && $scope.stage === STAGE.DO_CLAIM) {
// Only send end game operations in DO_CLAIM stage
var operation = cheatLogicService.getWinMove($scope.state);
gameService.makeMove(operation);
}
}
// Send computer move
function sendComputerMove() {
var operations = cheatLogicService.createComputerMove($scope.state, $scope.currIndex);
if ($scope.currIndex === 1) {
gameService.makeMove(operations);
}
}
/**
* This method update the game's UI.
*/
function updateUI(params) {
// If the state is empty, first initialize the board...
if (cheatLogicService.isEmptyObj(params.stateAfterMove)) {
if (params.yourPlayerIndex === 0) {
gameService.makeMove(cheatLogicService.getInitialMove());
}
return;
}
// Get the new state
$scope.state = params.stateAfterMove;
// Get the current player index (For creating computer move...)
$scope.currIndex = params.turnIndexAfterMove;
$scope.isYourTurn = params.turnIndexAfterMove >= 0 && // game is ongoing
params.yourPlayerIndex === params.turnIndexAfterMove; // it's my turn
$scope.isAiMode = $scope.isYourTurn
&& params.playersInfo[params.yourPlayerIndex].playerId === '';
$scope.playMode = params.playMode;
// Get the cards for player one area, player two area and middle area
$scope.middle = $scope.state.middle.clone();
if (params.playMode === 'playAgainstTheComputer' || params.playMode === 'passAndPlay') {
// If the game is played in the same device, use the default setting
$scope.playerOneCards = $scope.state.white.clone();
$scope.playerTwoCards = $scope.state.black.clone();
} else {
// Otherwise, player one area holds the cards for the player self
if (params.yourPlayerIndex === 0) {
$scope.playerOneCards = $scope.state.white.clone();
$scope.playerTwoCards = $scope.state.black.clone();
} else {
$scope.playerOneCards = $scope.state.black.clone();
$scope.playerTwoCards = $scope.state.white.clone();
}
}
sortRanks();
// In case the board is not updated
if (!$scope.$$phase) {
$scope.$apply();
}
// If the game ends, send the end game operation directly
checkEndGame();
if ($scope.isYourTurn) {
switch($scope.state.stage) {
case STAGE.DO_CLAIM:
updateClaimRanks();
break;
case STAGE.DECLARE_CHEATER:
if (params.playMode === 'passAndPlay' || $scope.currIndex == 0) {
$('#declareModal').modal('show');
}
break;
case STAGE.CHECK_CLAIM:
checkDeclaration();
break;
default:
}
}
if ($scope.currIndex === 1 && $scope.isAiMode) {
$scope.isYourTurn = false;
$timeout(sendComputerMove, 1000);
}
}
/**
* Set the game!
*/
gameService.setGame({
gameDeveloperEmail: "yl1949@nyu.edu",
minNumberOfPlayers: 2,
maxNumberOfPlayers: 2,
//exampleGame: checkersLogicService.getExampleGame(),
//riddles: checkersLogicService.getRiddles(),
isMoveOk: cheatLogicService.isMoveOk,
updateUI: updateUI
});
}]);
}());
|
var breadcrumbs=[['-1',"",""],['2',"SOLUTION-WIDE PROPERTIES Reference","topic_0000000000000C16.html"],['408',"Tlece.Recruitment.Controllers Namespace","topic_000000000000018A.html"],['409',"AdministratorController Class","topic_000000000000018B.html"]]; |
module.exports.run = function() {
var path = require('path');
var rm = require('shelljs').rm;
var distPath = require('../../config').paths.dist;
var distFiles = path.join(distPath, '*');
var utils = require('../../utils');
if (!utils.dirExists(distPath)) {
return utils.dirSkippedDeletion(distPath);
}
rm('-r', distFiles);
};
|
/**
The MIT License (MIT)
Copyright (c) 2015 Steven Campbell.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
"use strict";
function KeepassHeader() {
var my = {
readHeader: readHeader
};
var AES_CIPHER_UUID = new Uint8Array([0x31,0xc1,0xf2,0xe6,0xbf,0x71,0x43,0x50,0xbe,0x58,0x05,0x21,0x6a,0xfc,0x5a,0xff]);
var littleEndian = (function() {
var buffer = new ArrayBuffer(2);
new DataView(buffer).setInt16(0, 256, true);
return new Int16Array(buffer)[0] === 256;
})();
function readHeader(buf) {
var sigHeader = new DataView(buf, 0, 8)
var h = {
sigKeePass: sigHeader.getUint32(0, littleEndian),
sigKeePassType: sigHeader.getUint32(4, littleEndian)
};
var DBSIG_KEEPASS = 0x9AA2D903;
var DBSIG_KDBX = 0xB54BFB67,
DBSIG_KDBX_ALPHA = 0xB54BFB66,
DBSIG_KDB = 0xB54BFB55,
DBSIG_KDB_NEW = 0xB54BFB65;
var VERSION_KDBX = 3;
if (h.sigKeePass != DBSIG_KEEPASS || (h.sigKeePassType != DBSIG_KDBX && h.sigKeePassType != DBSIG_KDBX_ALPHA && h.sigKeePassType != DBSIG_KDB && h.sigKeePassType != DBSIG_KDB_NEW)) {
//fail
console.log("Signature fail. sig 1:" + h.sigKeePass.toString(16) + ", sig2:" + h.sigKeePassType.toString(16));
throw new Error('This is not a valid KeePass file - file signature is not correct.')
}
if (h.sigKeePassType == DBSIG_KDBX || h.sigKeePassType == DBSIG_KDBX_ALPHA) {
readKdbxHeader(buf, 8, h);
} else {
readKdbHeader(buf, 8, h);
}
//console.log(h);
//console.log("version: " + h.version.toString(16) + ", keyRounds: " + h.keyRounds);
return h;
}
function readKdbHeader(buf, position, h) {
var FLAG_SHA2 = 1;
var FLAG_RIJNDAEL = 2;
var FLAG_ARCFOUR = 4;
var FLAG_TWOFISH = 8;
var dv = new DataView(buf, position, 116);
var flags = dv.getUint32(0, littleEndian);
if (flags & FLAG_RIJNDAEL != FLAG_RIJNDAEL) {
throw new Error('We only support AES (aka Rijndael) encryption on KeePass KDB files. This file is using something else.');
}
h.cipher = AES_CIPHER_UUID;
h.majorVersion = dv.getUint16(4, littleEndian);
h.minorVersion = dv.getUint16(6, littleEndian);
h.masterSeed = new Uint8Array(buf, position + 8, 16);
h.iv = new Uint8Array(buf, position + 24, 16);
h.numberOfGroups = dv.getUint32(40, littleEndian);
h.numberOfEntries = dv.getUint32(44, littleEndian);
h.contentsHash = new Uint8Array(buf, position + 48, 32);
h.transformSeed = new Uint8Array(buf, position + 80, 32);
h.keyRounds = dv.getUint32(112, littleEndian);
//constants for KDB:
h.keyRounds2 = 0;
h.compressionFlags = 0;
h.protectedStreamKey = window.crypto.getRandomValues(new Uint8Array(16)); //KDB does not have this, but we will create in order to protect the passwords
h.innerRandomStreamId = 0;
h.streamStartBytes = null;
h.kdb = true;
h.dataStart = position + 116; //=124 - the size of the KDB header
}
function readKdbxHeader(buf, position, h) {
var version = new DataView(buf, position, 4)
h.majorVersion = version.getUint16(0, littleEndian);
h.minorVersion = version.getUint16(2, littleEndian);
position += 4;
var done = false;
while (!done) {
var descriptor = new DataView(buf, position, 3);
var fieldId = descriptor.getUint8(0, littleEndian);
var len = descriptor.getUint16(1, littleEndian);
var dv = new DataView(buf, position + 3, len);
//console.log("fieldid " + fieldId + " found at " + position);
position += 3;
switch (fieldId) {
case 0: //end of header
done = true;
break;
case 2: //cipherid, 16 bytes
h.cipher = new Uint8Array(buf, position, len);
break;
case 3: //compression flags, 4 bytes
h.compressionFlags = dv.getUint32(0, littleEndian);
break;
case 4: //master seed
h.masterSeed = new Uint8Array(buf, position, len);
break;
case 5: //transform seed
h.transformSeed = new Uint8Array(buf, position, len);
break;
case 6: //transform rounds, 8 bytes
h.keyRounds = dv.getUint32(0, littleEndian);
h.keyRounds2 = dv.getUint32(4, littleEndian);
break;
case 7: //iv
h.iv = new Uint8Array(buf, position, len);
break;
case 8: //protected stream key
h.protectedStreamKey = new Uint8Array(buf, position, len);
break;
case 9:
h.streamStartBytes = new Uint8Array(buf, position, len);
break;
case 10:
h.innerRandomStreamId = dv.getUint32(0, littleEndian);
break;
default:
break;
}
position += len;
}
h.kdbx = true;
h.dataStart = position;
}
return my;
}
|
'use strict';
/*
* Defining the Package
*/
var Module = require('meanio').Module;
var Articles = new Module('articles');
/*
* All MEAN packages require registration
* Dependency injection is used to define required modules
*/
Articles.register(function(app, auth, database, circles, swagger) {
//We enable routing. By default the Package Object is passed to the routes
Articles.routes(app, auth, database);
Articles.aggregateAsset('css', 'articles.css');
//We are adding a link to the main menu for all authenticated users
Articles.menus.add({
'roles': ['authenticated'],
'title': 'Example Package',
'link': 'all articles'
});
// Articles.menus.add({
// 'roles': ['authenticated'],
// 'title': 'Create New Article',
// 'link': 'create article'
// });
Articles.events.defaultData({
type: 'post',
subtype: 'article'
});
/*
//Uncomment to use. Requires meanio@0.3.7 or above
// Save settings with callback
// Use this for saving data from administration pages
Articles.settings({'someSetting':'some value'},function (err, settings) {
//you now have the settings object
});
// Another save settings example this time with no callback
// This writes over the last settings.
Articles.settings({'anotherSettings':'some value'});
// Get settings. Retrieves latest saved settings
Articles.settings(function (err, settings) {
//you now have the settings object
});
*/
// Only use swagger.add if /docs and the corresponding files exists
swagger.add(__dirname);
return Articles;
});
|
module.exports = function notFoundFn(req,res){
if (req.accepts('html')) {
res.status(404);
res.render('404', {url: req.url});
return
};
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.