code stringlengths 2 1.05M | repo_name stringlengths 5 114 | path stringlengths 4 991 | language stringclasses 1 value | license stringclasses 15 values | size int32 2 1.05M |
|---|---|---|---|---|---|
var Cubid = require("cubid");
var aufs = ["", "U", "U2", "U'"];
// Note these are the *inverses*
var pllInverses = {
"": "",
"Aa": "R B' R F2 R' B R F2 R2",
"Ab": "R' F R' B2 R F' R' B2 R2",
"E": "R' U L' D2 L U' R L' U R' D2 R U' L",
"F": "R' U R U' R2 F' U' F U R F R' F' R2 U'",
"Ga": "R' U' R B2 D L' U L U' L D' B2",
"Gb": "R2 U (R' U R' U') R U' R2 D U' R' U R D'",
"Gc": "L U2 L' U F' L' U' L U L F U L' U' L' U L",
"Gd": "L' U' L U L U' F' L' U' L' U L F U' L U2 L'",
"H": "M2 U M2 U2 M2 U M2",
"Ja": "B' U F' U2 B U' B' U2 F B",
"Jb": "B U' F U2 B' U B U2 F' B'",
"Na": "L U' R U2 L' U R' L U' R U2 L' U R'",
"Nb": "R' U L' U2 R U' L R' U L' U2 R U' L",
"Ra": "R U2 R' U2 R B' R' U' R U R B R2 U",
"Rb": "R' U2 R U2 R' F R U R' U' R' F' R2' U'",
"T": "R U R' U' R' F R2 U' R' U' R U R' F'",
"Ua": "R' U R' U' R' U' R' U R U R2",
"Ub": "R2 U' R' U' R U R U R U' R",
"V": "R' U R' U' B' R' B2 U' B' U B' R B R",
"Y": "F R U' R' U' R U R' F' R U R' U' R' F R F'",
"Z": "M2 U M2 U M' U2 M2 U2 M' U2",
};
var pllNames = Object.keys(pllInverses);
var whichPll = function(alg) {
var cube = new Cubid("");
var preAufdCube;
var plldCube;
var postAufdCube;
for (var preAuf = 0; preAuf < aufs.length; preAuf++) {
preAufdCube = cube.apply(aufs[preAuf]);
for (var pll = 0; pll < pllNames.length; pll++) {
plldCube = preAufdCube.apply(pllInverses[pllNames[pll]]);
for (var postAuf = 0; postAuf < aufs.length; postAuf++) {
postAufdCube = plldCube.apply(aufs[postAuf]);
if (postAufdCube.apply(alg).isSolved()) {
return pllNames[pll];
}
}
}
}
return "?";
};
module.exports = whichPll;
| justinj/which-pll | index.js | JavaScript | mit | 1,703 |
/*
Text Rotor is a simple class that allows you to easily make the scrolly-generating text you see some places.
Simply Create a new Rotor with "var foo = new Text_Rotor("YOUR_INTRO_BIT_OF_TEXT", "THE ID OF THE DIV WHERE THE TEXT GOES");
Then add additional rotors with foo.add_rotor("NEW PIECE of Text")l
TODO: Add (optional) cursor thingie at the end.
TODO: Add ability to remove rotors
*/
function Text_rotor(targetdiv, static_text){
thisCore = this;
this.rotating_text = [];
this.add_rotors = function(rotortext){
var rotorArray = rotortext.split(",");
for (var i in rotorArray){
thisCore.rotating_text.push(rotorArray[i]);
}
};
this.start_rotor_cycle = function(){
var theWord = thisCore.rotating_text[0];
thisCore.print_letters(theWord, 0, 0);
};
this.print_letters = function(word, position, location){
var text_area = document.getElementById(targetdiv);
if (position === 0){
//Reset Everything if you're at the start of a word
if (static_text !== undefined){
text_area.textContent = static_text;
}
else{
text_area.textContent = null;
}
}
if (word[position] !== undefined){
text_area.textContent += word[position];
window.setTimeout(function(){
position++;
thisCore.print_letters(word, position, location);
}, 50);
}
else{
setTimeout(function(){
location++;
if (thisCore.rotating_text[location] !== undefined){
thisCore.print_letters(thisCore.rotating_text[location], 0, location);
}
else{
// If you're at the end, go back to the first
thisCore.print_letters(thisCore.rotating_text[0], 0, 0);
}
}, 2000);
}
};
}
//SAMPLE ROTOR CALL:
/*
var sampleRotor = new Text_rotor("word-area");
sampleRotor.add_rotors("Awesomatastic,Superfluenzic,Bodacious");
sampleRotor.start_rotor_cycle();
*/
| ejonasson/text-rotor-js | text_rotor.js | JavaScript | mit | 1,819 |
/*
(c) Copyright 2016-2017 Hewlett Packard Enterprise Development LP
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.
*/
import Enhance from '../oneview-sdk/utils/enhance';
import ResourceTransforms from './utils/resource-transforms';
import DeveloperListener from './developer';
import ServerHardwareListener from './server-hardware';
import ServerProfilesListener from './server-profiles';
import ServerProfileTemplateListener from './server-profile-templates';
import BotListener from './bot';
import NotificationsFilter from './notifications-filter';
export default function(robot, client) {
const enhance = new Enhance(client.host);
const transform = new ResourceTransforms(robot);
const filter = new NotificationsFilter(robot);
const dev = new DeveloperListener(robot, client, transform);
const sh = new ServerHardwareListener(robot, client, transform);
const sp = new ServerProfilesListener(robot, client, transform, sh);
const spt = new ServerProfileTemplateListener(robot, client, transform, sh, sp);
// LAST!!
new BotListener(robot, client, transform, dev, sh, sp, spt);
// TODO: Bug This should not be bound here, probably want a NotificationsListener instead
// connect to the SCMB to emit notifications
robot.on('__hpe__notification__', function (message) {
//TODO This is a total hack, we need to pull the transformer out of the client
client.ClientConnection.__newSession__().then((auth) => {
return enhance.transformHyperlinks(auth, message);
}).then((resource) => {
let checkedMessage = filter.check(message);
if (typeof checkedMessage !== 'undefined' && checkedMessage.length > 0) {
transform.messageRoom(client.notificationsRoom, resource.resource);
}
}).catch((err) => {
robot.logger.error(err);
});
});
}
| jonmccormick/hpe-oneview-hubot | src/listener/ov-listener.js | JavaScript | mit | 2,790 |
module.exports = function(grunt) {
//grunt-twig-render
grunt.config('twigRender', {
dest: {
files: [
{
data: '<%= config.twig.data.dir %>/<%= config.twig.data.file %>',
expand: true,
cwd: '<%= config.twig.dir %>',
src: ['*.twig'],
dest: '<%= config.html.dir %>',
ext: '.html'
}
]
}
});
//grunt-w3c-html-validation
grunt.config('validation', {
options: {
reset: true,
stoponerror: false,
reportpath: false,
generateReport: false
},
files: {
src: '<%= config.html.dir %>/*.html'
}
});
}; | SnceGroup/grunt-config-for-websites | grunt/html.js | JavaScript | mit | 801 |
function uploadFile(callback) {
scp.send({
file: filepathNew,
user: scpUser,
host: scpHost,
port: scpPort,
path: scpRemotePath
}, function uploadDone(err) {
if (err) {
console.log(err);
} else {
// Write to DB if feature enabled in config
if (config.app.archive.enabled) {
var timestamp = moment().unix();
db.put(imageName, {
filename: imageNameNew,
url: imageRemoteURL,
date: timestamp
});
// Log to console to make it easier to retrieve past uploads (if enabled in the config file)
if (config.app.archive.logging) {
var upload = db.get(imageName);
console.log(colors.green(upload.url) + " - " + moment.unix(upload.date).format("dddd, MMMM Do YYYY, h:mm:ss a"));
}
}
// Copy to clipboard
copy(imageRemoteURL);
// Send notification to OS
notifier.notify({
'title': 'ScreenUpload',
'subtitle': 'Upload finished',
'contentImage': filepathNew,
'message': 'The URL is now in your clipboard.',
'open': 'file://' + __dirname + '/archive/' + imageNameNew
});
callback();
}
});
} | dewey/ScreenUpload | upload.js | JavaScript | mit | 1,446 |
"use strict";
// Logger modules
var gutil = require("gulp-util");
var colors = gutil.colors;
// Gulp specific modules
var gulp = require("gulp");
gulp.task("common", ["copy", "svg-sprite", "data-store", "collections", "html", "sass", "js", "jsbundle", "resource"]);
gulp.task("dev", ["common", "watcher"], function (done) {
gutil.log(colors.bold.yellow("Watchers Established. You can now start coding."));
done();
});
gulp.task("release", ["release-copy", "common"], function (done) {
gutil.log(colors.bold.yellow("Product build is ready."));
});
gulp.task("default", ["release"], function (done) {
done();
});
var exported = {};
module.exports = function () {
return exported;
}; | webf-zone/webf | gulp/gulp-run.js | JavaScript | mit | 711 |
// http://eslint.org/docs/user-guide/configuring
module.exports = {
root: true,
parser: 'babel-eslint',
parserOptions: {
sourceType: 'module'
},
env: {
browser: true,
},
// https://github.com/feross/standard/blob/master/RULES.md#javascript-standard-style
extends: 'standard',
// required to lint *.vue files
plugins: [
'html'
],
// add your custom rules here
'rules': {
// allow paren-less arrow functions
'arrow-parens': 0,
// allow async-await
'generator-star-spacing': 0,
// allow debugger during development
'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0
},
globals: {
'Foundation': false,
'$': false
}
}
| Nee-V/NeeV | .eslintrc.js | JavaScript | mit | 700 |
import React from 'react';
import Input from './Input';
import Wrapper from './Wrapper';
function InputIcon(props) {
const { icon, ...newProps } = props;
return (
<Wrapper>
{icon}
<Input {...newProps} />
</Wrapper>
);
}
InputIcon.propTypes = {
type: React.PropTypes.any,
placeholder: React.PropTypes.any,
value: React.PropTypes.any,
onChange: React.PropTypes.any,
icon: React.PropTypes.any,
};
export default InputIcon;
| gustblima/what-can-i-play-with-my-friends | client/app/components/InputIcon/index.js | JavaScript | mit | 460 |
// Credits: borrowed code from fcomb/redux-logger
import { deepCopy } from './util'
export default function createLogger ({
collapsed = true,
filter = (mutation, stateBefore, stateAfter) => true,
transformer = state => state,
mutationTransformer = mut => mut
} = {}) {
return store => {
let prevState = deepCopy(store.state)
store.subscribe((mutation, state) => {
if (typeof console === 'undefined') {
return
}
const nextState = deepCopy(state)
if (filter(mutation, prevState, nextState)) {
const time = new Date()
const formattedTime = ` @ ${pad(time.getHours(), 2)}:${pad(time.getMinutes(), 2)}:${pad(time.getSeconds(), 2)}.${pad(time.getMilliseconds(), 3)}`
const formattedMutation = mutationTransformer(mutation)
const message = `mutation ${mutation.type}${formattedTime}`
const startMessage = collapsed
? console.groupCollapsed
: console.group
// render
try {
startMessage.call(console, message)
} catch (e) {
console.log(message)
}
console.log('%c prev state', 'color: #9E9E9E; font-weight: bold', transformer(prevState))
console.log('%c mutation', 'color: #03A9F4; font-weight: bold', formattedMutation)
console.log('%c next state', 'color: #4CAF50; font-weight: bold', transformer(nextState))
try {
console.groupEnd()
} catch (e) {
console.log('—— log end ——')
}
}
prevState = nextState
})
}
}
function repeat (str, times) {
return (new Array(times + 1)).join(str)
}
function pad (num, maxLength) {
return repeat('0', maxLength - num.toString().length) + num
}
| wenhuabin/merlin | src/utils/logger.js | JavaScript | mit | 1,739 |
/* globals XMLHttpRequest, File, FileReader */
import Typeson from 'typeson';
import {string2arraybuffer} from '../utils/stringArrayBuffer.js';
const file = {
file: {
test (x) { return Typeson.toStringTag(x) === 'File'; },
replace (f) { // Sync
const req = new XMLHttpRequest();
req.overrideMimeType('text/plain; charset=x-user-defined');
req.open('GET', URL.createObjectURL(f), false); // Sync
req.send();
// Seems not feasible to accurately simulate
/* istanbul ignore next */
if (req.status !== 200 && req.status !== 0) {
throw new Error('Bad File access: ' + req.status);
}
return {
type: f.type,
stringContents: req.responseText,
name: f.name,
lastModified: f.lastModified
};
},
revive ({name, type, stringContents, lastModified}) {
return new File([string2arraybuffer(stringContents)], name, {
type,
lastModified
});
},
replaceAsync (f) {
return new Typeson.Promise(function (resolve, reject) {
/*
if (f.isClosed) { // On MDN, but not in https://w3c.github.io/FileAPI/#dfn-Blob
reject(new Error('The File is closed'));
return;
}
*/
const reader = new FileReader();
reader.addEventListener('load', function () {
resolve({
type: f.type,
stringContents: reader.result,
name: f.name,
lastModified: f.lastModified
});
});
// Seems not feasible to accurately simulate
/* istanbul ignore next */
reader.addEventListener('error', function () {
reject(reader.error);
});
reader.readAsBinaryString(f);
});
}
}
};
export default file;
| dfahlander/typeson-registry | types/file.js | JavaScript | mit | 2,165 |
/*
* This program is distributed under the terms of the MIT license:
* <https://github.com/v0lkan/talks/blob/master/LICENSE.md>
* Send your comments and suggestions to <me@volkan.io>.
*/
window.Caller = {
callMeMaybe: function () {
var self = this;
var id = setTimeout(function () {
console.log('Hi there!');
self.callMeMaybe();
}, 1000);
return id;
}
};
/*id =*/ window.Caller.callMeMaybe();
window.Caller = null; // will still leak.
delete window.Caller; // ditto!
//clearTimeout(id);
| v0lkan/talks | udemy/efficient-javascript/support/leaks_structural_timers.js | JavaScript | mit | 563 |
import React from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
class Question extends React.Component {
constructor() {
super();
this.state = {
id: '',
title: '',
type: '',
number: 0,
page: 0,
answers: '',
isMandatory: false,
hasMandatoryLabel: false,
hasQuestionNumbers: false,
isEditMode: false,
rangeValue: 5
};
this.onChecked = this.onChecked.bind(this);
this.onChange = this.onChange.bind(this);
this.onEditAnswer = this.onEditAnswer.bind(this);
this.onAddAnswer = this.onAddAnswer.bind(this);
this.onRemoveAnswer = this.onRemoveAnswer.bind(this);
this.onEdit = this.onEdit.bind(this);
this.onRemove = this.onRemove.bind(this);
this.onSave = this.onSave.bind(this);
this.onCancel = this.onCancel.bind(this);
this.onChangeRangeQuestion = this.onChangeRangeQuestion.bind(this);
}
componentWillMount() {
const { question } = this.props;
this.setState({
id: question.id,
title: question.title,
type: question.type,
number: question.number,
page: question.page,
answers: question.answers,
isMandatory: question.isMandatory,
hasMandatoryLabel: this.props.hasMandatoryLabel,
hasQuestionNumbers: this.props.hasQuestionNumbers,
});
this.questionParams = this.state;
}
componentWillReceiveProps(nextProps) {
this.setState({
title: nextProps.question.title,
answers: nextProps.question.answers,
number: nextProps.question.number,
isMandatory: nextProps.question.isMandatory,
hasMandatoryLabel: nextProps.hasMandatoryLabel,
hasQuestionNumbers: nextProps.hasQuestionNumbers
});
}
onChecked(e) {
this.setState({
[e.target.name]: e.target.checked
});
}
onChange(e) {
this.setState({
[e.target.name]: e.target.value
});
}
onEditAnswer(e) {
let index = e.target.name.split('_')[1];
let value = e.target.value;
let arr = this.state.answers.slice();
arr[index] = value;
this.setState({
answers: arr
});
}
onAddAnswer() {
let arr = this.state.answers.slice();
if (arr.length === 10) {
this.props.addFlashMessage({
type: 'warning',
text: `Too many answers for the question ${this.state.number}.
Please remove the redundant ones and try again.`
});
} else {
arr.push('');
this.setState({
answers: arr
});
}
}
onRemoveAnswer() {
let arr = this.state.answers.slice();
if (arr.length === 1) {
this.props.addFlashMessage({
type: 'warning',
text: `An answer can not be empty.
Please add new answers to the question ${this.state.number}
and try again.`
});
} else {
arr.pop();
this.setState({
answers: arr
});
}
}
onEdit() {
this.setState({
isEditMode: true
});
}
onRemove(id) {
this.props.onRemoveQuestion(id);
}
onSave(e) {
e.preventDefault();
let question = {
id: this.state.id,
title: this.state.title,
number: this.state.number,
page: this.state.page,
isMandatory: this.state.isMandatory,
answers: this.state.answers,
type: this.state.type
};
this.props.onSaveQuestion(question);
this.setState({
isEditMode: false
});
}
onCancel() {
this.setState({
isEditMode: false,
id: this.props.question.id,
title: this.props.question.title,
type: this.props.question.type,
number: this.props.question.number,
page: this.props.question.page,
answers: this.props.question.answers,
isMandatory: this.props.question.isMandatory,
});
}
onChangeRangeQuestion(e) {
this.setState({
[e.target.name]: e.target.value
});
}
render() {
const {
title,
id,
number,
type,
answers,
isMandatory,
hasMandatoryLabel,
hasQuestionNumbers,
isEditMode,
rangeValue } = this.state;
const canEdit = <a
onClick={this.onEdit}
className="pointer no-color"
type="button"
>
<i className="fa fa-pencil pull-right" aria-hidden="true"></i>
</a>;
const canMakeMandatory = (
<div className="pull-right make-some-right-margin">
<input
onChange={this.onChecked}
name="isMandatory"
id="mandatory"
type="checkbox"
checked={isMandatory}
/>
<label htmlFor="mandatory">Mandatory</label>
</div>
);
const canEditTitle = (<div className="form-group">
<input
onChange={this.onChange}
name="title"
type="text"
value={title}
className="form-control"
placeholder="Enter new question title here"
/>
</div>
);
const canRemove = <a
onClick={() => this.onRemove(id)}
className="pointer no-color"
type="button"
>
<i className="fa fa-trash-o pull-right" aria-hidden="true"></i>
</a>;
const addNewAnswer = <a
onClick={this.onAddAnswer}
type="button"
className="no-color pointer"
>
<i className="fa fa-plus-circle" aria-hidden="true"></i>
</a>;
const removeAnswer = <a
onClick={this.onRemoveAnswer}
type="button"
className="no-color pointer"
>
<i className="fa fa-minus-circle" aria-hidden="true"></i>
</a>;
const btnGroup = (
<div className="btn-group" role="group">
<button
onClick={this.onSave}
type="button"
className="btn btn-md btn-success"
>
Save
</button>
<button
onClick={this.onCancel}
type="button"
className="btn btn-md btn-default"
>
Cancel
</button>
</div>
);
const renderTitle = (
<h6
className={classnames({ 'required': isMandatory && hasMandatoryLabel })}
>
{hasQuestionNumbers ? number + '. ' : ''}{title}
</h6>
);
let renderQuestion = '';
let renderAnswers = '';
let renderEditAnswers = answers.map((item, index) => {
if (index === answers.length - 1) {
return (
<div key={index} className="form-group">
<input
onChange={this.onEditAnswer}
type="text"
name={'answer_' + index}
value={answers[index]}
placeholder="Enter answer here" />
{removeAnswer} {addNewAnswer}
</div>
);
} else {
return (
<div key={index} className="form-group">
<input
onChange={this.onEditAnswer}
type="text"
name={'answer_' + index}
value={answers[index]}
placeholder="Enter answer here" />
</div>
);
}
});
switch (type) {
case 'Single':
renderAnswers = answers.map((item, index) => {
return (
<div key={index + item} className="form-group">
<input name={'radioQuestion' + number} type="radio" /> {answers[index]}
</div>
);
});
return renderQuestion = (
<div>
{!isEditMode ? canEdit : ''}
{!isEditMode ? renderTitle : canEditTitle}
{isEditMode ? canRemove : ''}
{isEditMode ? canMakeMandatory : ''}
{!isEditMode ? renderAnswers : renderEditAnswers}
{isEditMode ? btnGroup : ''}
<hr />
</div>
);
case 'Multiple':
renderAnswers = answers.map((item, index) => {
return (
<div key={index + item} className="form-group">
<input name={'answer' + number} type="checkbox" /> {answers[index]}
</div>
);
});
return renderQuestion = (
<div>
{!isEditMode ? canEdit : ''}
{!isEditMode ? renderTitle : canEditTitle}
{isEditMode ? canRemove : ''}
{isEditMode ? canMakeMandatory : ''}
{!isEditMode ? renderAnswers : renderEditAnswers}
{isEditMode ? btnGroup : ''}
<hr />
</div>
);
case 'Text':
return (
<div>
{!isEditMode ? canEdit : ''}
{!isEditMode ? renderTitle : canEditTitle}
{isEditMode ? canRemove : ''}
{isEditMode ? canMakeMandatory : ''}
<div className="form-group">
<textarea
name="textQuestion"
rows="2"
placeholder=" Enter your answer here"
className="form-control"
>
</textarea>
</div>
{isEditMode ? btnGroup : ''}
<hr />
</div>
);
case 'File':
return (
<div>
{!isEditMode ? canEdit : ''}
{!isEditMode ? renderTitle : canEditTitle}
<div className="form-group">
<div className="file-upload" data-text="Choose your file">
<input type="file" />
</div>
</div>
{isEditMode ? canRemove : ''}
{isEditMode ? canMakeMandatory : ''}
{isEditMode ? btnGroup : ''}
<hr />
</div>
);
case 'Star':
return (
<div>
{!isEditMode ? canEdit : ''}
{!isEditMode ? renderTitle : canEditTitle}
{isEditMode ? canRemove : ''}
{isEditMode ? canMakeMandatory : ''}
<div className="clearfix">
<div className="pull-left form-group rating">
<input
type="radio"
id={'star5' + number}
name={'rating' + number}
value="5☆"
/>
<label htmlFor={'star5' + number} >5 stars</label>
<input
type="radio"
id={'star4' + number}
name={'rating' + number}
value="4☆"
/>
<label htmlFor={'star4' + number} >4 stars</label>
<input
type="radio"
id={'star3' + number}
name={'rating' + number}
value="3☆"
/>
<label htmlFor={'star3' + number} >3 stars</label>
<input
type="radio"
id={'star2' + number}
name={'rating' + number}
value="2☆"
/>
<label htmlFor={'star2' + number} >2 stars</label>
<input
type="radio"
id={'star1' + number}
name={'rating' + number}
value="1☆"
/>
<label htmlFor={'star1' + number} >1 star</label>
</div>
</div>
{isEditMode ? btnGroup : ''}
<hr />
</div>
);
case 'Range':
return (
<div>
{!isEditMode ? canEdit : ''}
{!isEditMode ? renderTitle : canEditTitle}
{isEditMode ? canRemove : ''}
{isEditMode ? canMakeMandatory : ''}
<div className="form-group">
<input
className="range-input"
onChange={this.onChangeRangeQuestion}
name="rangeValue"
type="range"
min="0"
max="5"
step="0.5"
/>
<span className="text-center help-block">{rangeValue}</span>
</div>
{isEditMode ? btnGroup : ''}
<hr />
</div>
);
default:
return { renderQuestion };
}
}
}
Question.propTypes = {
question: PropTypes.object.isRequired,
onSaveQuestion: PropTypes.func.isRequired,
onRemoveQuestion: PropTypes.func.isRequired,
hasMandatoryLabel: PropTypes.bool.isRequired,
hasQuestionNumbers: PropTypes.bool.isRequired,
addFlashMessage: PropTypes.func.isRequired
};
export default Question;
| AnatolyBelobrovik/itechartlabs | client/components/surveys/edit/Question.js | JavaScript | mit | 12,038 |
'use strict';
module.exports = {
app: {
title: 'gymjao',
description: 'Full-Stack JavaScript with MongoDB, Express, AngularJS, and Node.js',
keywords: 'directory,search,listing,',
googleAnalyticsTrackingID: process.env.GOOGLE_ANALYTICS_TRACKING_ID || 'GOOGLE_ANALYTICS_TRACKING_ID'
},
port: process.env.PORT || 3000,
templateEngine: 'swig',
sessionSecret: 'MEAN',
sessionCollection: 'sessions',
logo: 'modules/core/img/brand/logo.png',
favicon: 'modules/core/img/brand/favicon.ico'
};
| dxnaveen/gymjao | config/env/default.js | JavaScript | mit | 518 |
/// <reference path="../base/base.js" />
/// <reference path="../base/app.js" />
/// <reference path="../base/util.js" />
FlashBuy.testeConexao = {
init: function () {
document.addEventListener("online", FlashBuy.util.onInternet, false);
document.addEventListener("offline", FlashBuy.util.onInternet, false);
},
ready: function () {
jQuery("#btTestarTipoConexao").click(function () {
alert(FlashBuy.util.tipoInternet());
});
jQuery("#btTestarConexao").click(function () {
alert(FlashBuy.util.conectadoInternet());
});
}
};
| jhonasn/FlashBuyMobile | www/js/controllers/testeConexao.js | JavaScript | mit | 635 |
var fs = require('fs');
var cbaSerialization = require('./cbaSerialization.js')
var util = require('util');
const zlib = require('zlib');
var fileNames = fs.readdirSync('full_exchange_3').sort();
console.log(fileNames);
// fileNames = [fileNames[1]]
for(var file of fileNames) {
if(file.indexOf('.pdf') >= 0) continue;
console.log('--------------')
console.log('file:', file);
var request1 = fs.readFileSync('full_exchange_3/' + file);
cbaSerialization.setBuffer(request1);
result = cbaSerialization.readHashtable();
deepInspect(result);
console.log(util.inspect(result, false, null));
}
function deepInspect(data) {
if(data == null || data.value == null || typeof data.value != 'object') return;
for(key in data.value) {
// console.log("Inspect key", key);
// console.log("value", data.value[key]);
if(key == "BA" && data.value[key].type == 99) {
console.log("GOT BA", data.value[key]);
if(data.value[key].value.length > 32) {
cbaSerialization.setBuffer(data.value[key].value);
try {
console.log("DECODED", cbaSerialization.readHashtable());
} catch(e) {
}
}
} else if(key == "dt") {
console.log("GOT DT", data.value[key]);
var unzippedBuffer = zlib.inflateRawSync(data.value[key].value);
cbaSerialization.setBuffer(unzippedBuffer);
data.value[key].decoded = cbaSerialization.readDataTable();
}
if(typeof data.value[key] == 'object') {
deepInspect(data.value[key]);
}
}
}
| kraynel/sila-cli | cbaSerialization.test.js | JavaScript | mit | 1,520 |
(function ($) {
$.fn.fakeLoader = function(options) {
//Defaults
var settings = $.extend({
pos:'fixed',// Default Position
top:'0px', // Default Top value
left:'0px', // Default Left value
width:'100%', // Default width
height:'100%', // Default Height
zIndex: '999', // Default zIndex
bgColor: '#2ecc71', // Default background color
spinner:'spinner7', // Default Spinner
imagePath:'' // Default Path custom image
}, options);
//Customized Spinners
var spinner01 = '<div class="fl spinner1"><div class="double-bounce1"></div><div class="double-bounce2"></div></div>';
var spinner02 = '<div class="fl spinner2"><div class="spinner-container container1"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container2"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container3"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div></div>';
var spinner03 = '<div class="fl spinner3"><div class="dot1"></div><div class="dot2"></div></div>';
var spinner04 = '<div class="fl spinner4"></div>';
var spinner05 = '<div class="fl spinner5"><div class="cube1"></div><div class="cube2"></div></div>';
var spinner06 = '<div class="fl spinner6"><div class="rect1"></div><div class="rect2"></div><div class="rect3"></div><div class="rect4"></div><div class="rect5"></div></div>';
var spinner07 = '<div class="fl spinner7"><div class="circ1"></div><div class="circ2"></div><div class="circ3"></div><div class="circ4"></div></div>';
//The target
var el = $(this);
//Init styles
var initStyles = {
'position':settings.pos,
'width':settings.width,
'height':settings.height,
'top':settings.top,
'left':settings.left,
'display': ""
};
//Apply styles
el.css(initStyles);
//Each
el.each(function() {
var a = settings.spinner;
//console.log(a)
switch (a) {
case 'spinner1':
el.html(spinner01);
break;
case 'spinner2':
el.html(spinner02);
break;
case 'spinner3':
el.html(spinner03);
break;
case 'spinner4':
el.html(spinner04);
break;
case 'spinner5':
el.html(spinner05);
break;
case 'spinner6':
el.html(spinner06);
break;
case 'spinner7':
el.html(spinner07);
break;
default:
el.html(spinner01);
}
//Add customized loader image
if (settings.imagePath !='') {
el.html('<div class="fl"><img src="'+settings.imagePath+'"></div>');
centerLoader();
}
});
//Return Styles
return this.css({
'backgroundColor':settings.bgColor,
'zIndex':settings.zIndex
});
}; // End Fake Loader
//Center Spinner
function centerLoader() {
var winW = $(window).width();
var winH = $(window).height();
var spinnerW = $('.fl').outerWidth();
var spinnerH = $('.fl').outerHeight();
$('.fl').css({
'position':'absolute',
'left':(winW/2)-(spinnerW/2),
'top':(winH/2)-(spinnerH/2)
});
}
$(window).load(function(){
centerLoader();
$(window).resize(function(){
centerLoader();
});
});
}(jQuery));
| VladimirRadeski/twitterstats | assets/js/fakeLoader.js | JavaScript | mit | 4,344 |
module.exports = {
install (less, pluginManager, functions) {
functions.add('args', node => {
if (typeof node.value === 'string') {
return node.value
}
let result = []
for (let i = 0; i < node.value.length; i++) {
result.push(node.value[i].value)
}
return result.join(', ')
})
}
}
| ecomfe/veui | packages/veui-theme-dls/functions.js | JavaScript | mit | 345 |
var mongoose = require('mongoose');
var registered = mongoose.Schema({
firstName: String,
lastName: String,
email: String,
password: String
});
module.exports = mongoose.model('Registered', registered); | defunctzombie/socket.io-cloud-examples | console/models/registered.js | JavaScript | mit | 212 |
'use strict';
const _ = require('lodash');
const bcrypt = require('bcryptjs');
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const connection = require('../connection/mongoDefault');
/* jshint maxlen: false */
const UserSchema = new Schema({
email: {
type: String,
required: true,
unique: true,
lowercase: true,
trim: true,
validate: {
validator: function (v) {
return v.length >= 5 && v.length <= 35 && /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)$/.test(v);
},
message: '{VALUE} is not a valid email'
}
},
name: {
type: String,
trim: true,
validate: {
validator: function (v) {
return /^[a-zA-Z0-9-_]{3,10}$/.test(v);
},
message: '{VALUE} is not a valid playername'
}
},
password: {
type: String,
trim: true
}
}, {
timestamps: true,
versionKey: false,
toObject: {
virtuals: true
},
toJSON: {
virtuals: true
}
});
UserSchema.statics = {
/**
* Load User by email or name
* @param {string} nameOrEmail
* @return {Promise}
*/
getByNameOrEmail: function (nameOrEmail) {
return this
.find({
$or : [
{ email: nameOrEmail },
{ name: nameOrEmail }
]
})
.exec();
}
};
/* hides/deletes password when returned to client */
UserSchema.methods.toJSON = function () {
const user = this.toObject();
delete user.password;
return user;
};
UserSchema.methods.comparePasswords = function (password, callback) {
bcrypt.compare(password, this.password, callback);
};
/* pre -save hook for hooking up the encryption */
UserSchema.pre('save', function (next) {
/* check if there is a modification to the password before hashing */
if (!user.isModified('password')) {
return next();
}
/* generate a salt to use in the hash function */
bcrypt.genSalt(10, (err, salt) => {
if (err) {
return next(err);
}
/* do the actual hashing */
bcrypt.hash(user.password, salt, (err, hash) => {
if (err) {
return next(err);
}
this.password = hash;
next();
});
});
});
module.exports = connection.model('User', UserSchema);
| konstantinzolotarev/generator-hapi-micro | src/app/templates/models/User.js | JavaScript | mit | 2,307 |
import { Router } from 'express'
import moment from 'moment'
import { version } from '../../../package.json'
import config from '~/config'
import client from '~/redis'
import { providersByScope } from '~/utils'
const status = () => {
let r = Router()
r.get('/', async (req, res) => {
const uptime = moment.duration(process.uptime(), 'seconds').humanize() // process uptime
const redis = client.server_info // redis info at connect (not live)
// list of routes on /api/v1
// hardcoded as routes inside routers do not have a path value
const routes = ['/status', '/reverse-geocode', '/speed-limit']
// api.stack.forEach(singleRoute => {
// routes.push(singleRoute.route.path)
// })
try {
const [keys, rawStats] = await client.multi().dbsize().get(config.stats.redisKey).execAsync()
const stats = rawStats ? JSON.parse(rawStats) : {} // stats object containing lookup counts
return res.json({ uptime, keys, providers: providersByScope, routes, stats, version, redis })
} catch (err) {
if (err instanceof SyntaxError) {
return res.status(500).json({ errors: ['problem parsing cached value'] })
} else {
return res.status(500).json({ errors: ['problem with redis/cached value'] })
}
}
})
return r
}
export default status
| marshallford/reverse-geocoder | src/api/routes/status.js | JavaScript | mit | 1,324 |
$(function () {
$('#container').highcharts({
chart: {
plotBorderWidth: 1
},
xAxis: {
categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
},
yAxis: {
endOnTick: false
},
series: [{
data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
}]
});
}); | Oxyless/highcharts-export-image | lib/highcharts.com/samples/highcharts/yaxis/endontick-false/demo.js | JavaScript | mit | 442 |
import { Subject } from "rxjs/Subject";
/**
* @hidden
*/
var PagerContextService = (function () {
function PagerContextService() {
this.changes = new Subject();
this.pageChange = new Subject();
}
PagerContextService.prototype.notifyChanges = function (changes) {
this.total = changes.total;
this.pageSize = changes.pageSize;
this.skip = changes.skip;
this.changes.next(changes);
};
PagerContextService.prototype.changePage = function (page) {
this.pageChange.next({ skip: page * this.pageSize, take: this.pageSize });
};
PagerContextService.prototype.changePageSize = function (value) {
this.pageChange.next({ skip: 0, take: value });
};
return PagerContextService;
}());
export { PagerContextService };
| antpost/antpost-client | node_modules/@progress/kendo-angular-grid/dist/es/pager/pager-context.service.js | JavaScript | mit | 806 |
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import createHistory from 'history/lib/createBrowserHistory';
import { Provider } from 'react-redux';
import { Router } from 'react-router';
import { ReduxRouter } from 'redux-react-router';
import { DebugPanel, DevTools, LogMonitor } from 'redux-devtools/lib/react';
import { setActivePanel } from 'lanai';
import { observe } from 'urbanist';
import { reloadSession } from 'seismic';
import Facebook from 'facia';
import createStore from './store';
import routes from './routes';
const facebook = new Facebook({ appId: '1509569572667330', scope: 'public_profile,email,user_friends' })
, store = createStore(createHistory, { session: { facebook }});
ReactDOM.render(
<div>
<Provider store={store}>
<ReduxRouter>{routes}</ReduxRouter>
</Provider>
</div>
, document.getElementById('app'));
store.dispatch(reloadSession());
const currentPath = state => {
return state.router.location.pathname;
};
observe(store, currentPath, (path) => store.dispatch(setActivePanel(path)));
| defact/gabbro | lib/app.js | JavaScript | mit | 1,076 |
// Welcome!
// Add your github user if you accepted the challenge!
var players = [
'raphamorim',
'israelst',
'afonsopacifer',
'rafaelfragosom',
'brunokinoshita',
'paulinhoerry',
'enieber',
'alanrsoares',
'viniciusdacal',
'thiagosantana',
'brunodsgn',
'danilorb',
'andersonweb'
];
module.exports = players;
| andersonweb/write-code-every-day | challengers.js | JavaScript | mit | 360 |
var dir_0225d63c745c15da368977ac0d11cfd7 =
[
[ "DatabaseSessionHandler.php", "_database_session_handler_8php.html", [
[ "DatabaseSessionHandler", "class_yeah_1_1_fw_1_1_session_1_1_database_session_handler.html", "class_yeah_1_1_fw_1_1_session_1_1_database_session_handler" ]
] ],
[ "NullSessionHandler.php", "_null_session_handler_8php.html", [
[ "NullSessionHandler", "class_yeah_1_1_fw_1_1_session_1_1_null_session_handler.html", "class_yeah_1_1_fw_1_1_session_1_1_null_session_handler" ]
] ],
[ "SessionHandlerAbstract.php", "_session_handler_abstract_8php.html", [
[ "SessionHandlerAbstract", "class_yeah_1_1_fw_1_1_session_1_1_session_handler_abstract.html", "class_yeah_1_1_fw_1_1_session_1_1_session_handler_abstract" ]
] ]
]; | Palethorn/Yeah | docs/dir_0225d63c745c15da368977ac0d11cfd7.js | JavaScript | mit | 776 |
//= require bootstrap-all
//= require ./commentable
//= require dataTables/jquery.dataTables
//= require dataTables/jquery.dataTables.bootstrap
//= require dataTables/jquery.dataTables.api.fnGetColumnData | Epictetus/feedback | app/assets/javascripts/feedback/index.js | JavaScript | mit | 204 |
({
app: Ti.UI.currentWindow.app,
f: Ti.UI.currentWindow.app.foundation,
win: Ti.UI.currentWindow,
init: function() {
Ti.App.addEventListener(this.f.UI.Event.MENU_AVAILABLE, function() {
Ti.API.info('menu available (event triggered)');
});
var menu = this.f.UI.createMenu([
{
title: 'Alert',
image: this.f.UI.GENERIC_ICON,
callback: function() {
alert('Triggered from Menu: Alert button');
}
},
{
title: 'Disabled',
image: this.f.UI.GENERIC_ICON,
enabled: false
},
{
title: 'Android only',
platforms: this.f.Platform.ANDROID
},
{
title: 'iOS only',
platforms: this.f.Platform.IOS
},
{
title: 'Android & iOS (default)',
platforms: [this.f.Platform.ANDROID, this.f.Platform.IOS]
}
]);
if(this.f.Platform.isAndroid()) {
this.win.add(Ti.UI.createLabel({text: 'Press the Menu button on your device.', textAlign: Ti.UI.TEXT_ALIGNMENT_CENTER}));
}
else if(this.f.Platform.isIOS()) {
var self = this;
this.win.add(Ti.UI.createLabel({text: 'Press the top right button', textAlign: Ti.UI.TEXT_ALIGNMENT_CENTER}));
var button = Ti.UI.createButton({systemButton: Ti.UI.iPhone.SystemButton.ACTION});
button.addEventListener('click', function() {
menu.show();
});
self.win.rightNavButton = button;
}
}
}).init(); | taniele/Foundation | FoundationTest/Views/Menu.js | JavaScript | mit | 1,358 |
import ProfileAdvancedModeConfirmation from './ProfileAdvancedModeConfirmation'
import ProfileAvatar from './ProfileAvatar'
import ProfileLeavingConfirmation from './ProfileLeavingConfirmation'
import ProfileRemovalConfirmation from './ProfileRemovalConfirmation'
export {
ProfileAdvancedModeConfirmation,
ProfileAvatar,
ProfileLeavingConfirmation,
ProfileRemovalConfirmation
}
| ArkEcosystem/ark-desktop | src/renderer/components/Profile/index.js | JavaScript | mit | 387 |
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var wrench = exports.wrench = { "viewBox": "0 0 8 8", "children": [{ "name": "path", "attribs": { "d": "M5.5 0c-1.38 0-2.5 1.12-2.5 2.5 0 .32.08.62.19.91l-2.91 2.88c-.39.39-.39 1.05 0 1.44.2.2.46.28.72.28.26 0 .52-.09.72-.28l2.88-2.91c.28.11.58.19.91.19 1.38 0 2.5-1.12 2.5-2.5 0-.16 0-.32-.03-.47l-.97.97h-2v-2l.97-.97c-.15-.03-.31-.03-.47-.03zm-4.5 6.5c.28 0 .5.22.5.5s-.22.5-.5.5-.5-.22-.5-.5.22-.5.5-.5z" } }] }; | xuan6/admin_dashboard_local_dev | node_modules/react-icons-kit/iconic/wrench.js | JavaScript | mit | 496 |
const express = require('express')
const path = require('path')
const compression = require('compression')
const logger = require('morgan')
// For forcing SSL on Heroku
function sslRedirect(req, res, next) {
if (process.env.NODE_ENV !== 'production')
return next()
// Check `x-forwarded-proto` header set by Heroku
const forwardedProto = req.headers['x-forwarded-proto']
const notHTTPS = forwardedProto && forwardedProto !== 'https'
if (notHTTPS) {
const url = path.join(req.get('Host'), req.url)
res.redirect(`https://${url}`)
return
}
next()
}
const app = express()
app.use(logger('dev'))
app.use(sslRedirect)
app.use(compression());
app.use(express.static(path.join(__dirname, 'public'), { maxAge: 1000 * 60 * 60 * 24 * 7 }))
app.get('*', (req, res) => {
const fileURL = path.join(__dirname, 'public', 'index.html')
res.sendFile(fileURL)
})
module.exports = app | refugeetech/project_interactivemap | server.js | JavaScript | mit | 906 |
(function () {
angular.module('app')
.directive('adDirective', function () {
return {
templateUrl: "/templates/ad-template.html",
scope: 'false',
controller: 'AdContoller'
}
});
}()) | andrei-bozhilov/AngularJS-Project-SoftUni | directives/adDirective.js | JavaScript | mit | 254 |
const helpers = require('../../helpers')
module.exports = {
command: 'cancel <resultId>',
desc: 'Cancel an active test run.',
builder: {},
handler: async function (argv) {
const client = helpers.getClient(argv)
const result = await client.cancelTestResult(argv.resultId)
if (argv.json) {
helpers.printJson(result)
} else {
helpers.print({
message: `Result cancelled: ${result.name}`,
id: result._id,
})
}
process.exit(0)
},
}
| ghost-inspector/node-ghost-inspector | bin/commands/test-result/cancel.js | JavaScript | mit | 496 |
const sinon = require('sinon');
const { assert, skip, test, module: describe, only } = require('qunit');
const { CPUKernel } = require('../../../src');
describe('internal: CPUKernel');
test('.build() checks if already built, and returns early if true', () => {
const mockContext = {
built: true,
setupConstants: sinon.spy(),
};
CPUKernel.prototype.build.apply(mockContext);
assert.equal(mockContext.setupConstants.callCount, 0);
}); | gpujs/gpu.js | test/internal/backend/cpu-kernel.js | JavaScript | mit | 450 |
/**
* A Swagger v2 serializer.
* This implementation has the following limitations:
* - it will not create a global security field (securityDefinitions will be included though).
* - it will not use the externalDocs, as this is field is still not supported
* - the auths field in a Request **MUST** only be composed of References
* - null Auth not supported at the moment
*
* NOTE: we allow use of undefined in this file as it works nicely with JSON.stringify, which drops
* keys with a value of undefined.
* ```
* const swagger = { info, security }
* ```
* is easier to read than
* ```
* const swagger = { info }
* if (security) {
* swagger.security = security
* }
* ```
*
* NOTE: we make the assumption that keys of a container are equal to the uuids of the objects it
* holds.
*
* NOTE: we assume that keys of a response map are status codes
* NOTE: we assume that keys of a methods map are method names.
*/
/* eslint-disable no-undefined */
import { List, Map } from 'immutable'
import Group from '../../../models/Group'
import Reference from '../../../models/Reference'
import Auth from '../../../models/Auth'
import { convertEntryListInMap } from '../../../utils/fp-utils'
const __meta__ = {
format: 'postman-collection',
version: 'v2.0'
}
const methods = {}
/**
* A Serializer to convert Api Records into Postman collections v2.
*/
export class PostmanSerializer {
static __meta__ = __meta__
/**
* serializes an Api into a Postman collection v2 formatted string
* @param {Api} api: the api to convert
* @returns {string} the corresponding postman collection, as a string
*/
static serialize(api) {
return methods.serialize(api)
}
/**
* returns a quality score for a content string wrt. to the collection v2 format.
* @param {String} content: the content of the file to analyze
* @returns {number} the quality of the content
*/
static validate(content) {
return methods.validate(content)
}
}
/**
* returns a quality score for a content string wrt. to the collection v2 format.
* @param {String} content: the content of the file to analyze
* @returns {number} the quality of the content
*/
methods.validate = () => {
return 0
}
/**
* extracts the info name field from an api.
* @param {Api} api: the Api from which to get the title to use in the info name
* @returns {Entry<string, string>} the corresponding entry
*/
methods.createInfoName = (api) => {
const title = api.getIn([ 'info', 'title' ]) || 'API-Flow export'
return { key: 'name', value: title }
}
/**
* creates an entry that holds the schema info field
* @returns {Entry<string, string>} the corresponding entry
*/
methods.createInfoSchema = () => {
const schemaUrl = 'https://schema.getpostman.com/json/collection/v2.0.0/collection.json'
return { key: 'schema', value: schemaUrl }
}
/**
* extracts the info description from an Api.
* @param {Api} api: the Api from which to get the description
* @returns {Entry<string, string>?} the corresponding entry, if it exists
*/
methods.createInfoDescription = (api) => {
const description = api.getIn([ 'info', 'description' ])
if (!description) {
return null
}
return { key: 'description', value: description }
}
/**
* extracts the info version from the an Api.
* @param {Api} api: the Api from which to get the version
* @returns {Entry<string, string>?} the corresponding entry, if it exists
*/
methods.createInfoVersion = (api) => {
const version = api.getIn([ 'info', 'version' ])
if (!version) {
return null
}
return { key: 'version', value: version }
}
/**
* creates a postman info object from an api
* @param {Api} api: the Api to get the information from
* @returns {Entry<string, PostmanInfo>} the corresponding entry
*/
methods.createInfo = (api) => {
const kvs = [
methods.createInfoName(api),
methods.createInfoSchema(),
methods.createInfoDescription(api),
methods.createInfoVersion(api)
].filter(v => !!v)
return { key: 'info', value: kvs.reduce(convertEntryListInMap, {}) }
}
/**
* extracts the name of an Item from a Group or a Resource
* @param {Group|Resource} groupOrResource: the group or resource whose name is to be extracted
* @returns {Entry<string, string>?} the corresponding entry, if it exists
*/
methods.createItemName = (groupOrResource) => {
const name = groupOrResource.get('name')
if (!name) {
return null
}
return { key: 'name', value: name }
}
/**
* extracts the description of an Item from a Group or a Resource
* @param {Group|Resource} groupOrResource: the group or resource whose description is to be
* extracted
* @returns {Entry<string, string>?} the corresponding entry, if it exists
*/
methods.createItemDescription = (groupOrResource) => {
const description = groupOrResource.get('description')
if (!description) {
return null
}
return { key: 'description', value: description }
}
/**
* extracts an endpoint out of a resource and a request, preferring the one from the request to the
* one from the resource
* @param {Resource} resource: the resource to get an endpoint from
* @param {Request} request: the request to get an endpoint from
* @returns {Endpoint?} the corresponding endpoint, if it exists
*/
methods.getEndpointOrReferenceFromResourceAndRequest = (resource, request) => {
const requestEndpoint = request.get('endpoints').valueSeq().get(0)
const resourceEndpoint = resource.get('endpoints').valueSeq().get(0)
if (requestEndpoint) {
return requestEndpoint
}
if (resourceEndpoint) {
return resourceEndpoint
}
return null
}
/**
* extracts an endpoint url from a shared variable
* @param {Variable} variable: the variable to convert into an endpoint url
* @returns {string?} the corresponding url, if it exists
*/
methods.getEndpointFromVariable = (variable) => {
if (!variable) {
return null
}
const url = variable.get('values').valueSeq().get(0) || null
return url
}
/**
* extracts an endpoint or an endpoint url from a reference (by fetching it in the store)
* @param {Api} api: the api to use to resolve shared objects
* @param {Reference} reference: the reference to use to resolve the endpoint
* @returns {Endpoint?|string?} the corresponding endpoint or endpoint url, if it exists
*/
methods.getEndpointFromReference = (api, reference) => {
if (reference.get('type') === 'variable') {
const variable = api.getIn([ 'store', 'variable', reference.get('uuid') ])
return methods.getEndpointFromVariable(variable)
}
const type = reference.get('type') || 'endpoint'
const uuid = reference.get('uuid')
return api.getIn([ 'store', type, uuid ]) || null
}
/**
* extracts a query parameter key value pair from a reference
* @param {Api} api: the api to use to resolve shared parameters
* @param {Reference} reference: the reference to use to resolve the query parameter
* @returns {string?} the corresponding query parameter key value pair, as a string, if it exists
*/
methods.extractQueryKeyValuePairFromReference = (api, reference) => {
const resolved = api.getIn([ 'store', 'parameter', reference.get('uuid') ])
if (!resolved) {
return null
}
const key = resolved.get('key')
const value = '{{' + reference.get('uuid') + '}}'
return key + '=' + value
}
/**
* extracts a query parameter key value pair from a parameter
* @param {Parameter} param: the parameter to convert
* @returns {string} the corresponding query parameter key value pair, as a string
*/
methods.extractQueryKeyValuePairFromParameter = (param) => {
const key = param.get('key')
const value = param.getJSONSchema().default || ''
return key + '=' + value
}
/**
* extract a query parameter key value pair from a Parameter or a Reference
* @param {Api} api: the api to use to resolve shared parameters
* @param {Parameter|Reference} param: the Parameter or Reference to convert into a query parameter
* @returns {string?} the corresponding query parameter key value pair, as a string, if it exists
*/
methods.extractQueryKeyValuePairFromParameterOrReference = (api, param) => {
if (param instanceof Reference) {
return methods.extractQueryKeyValuePairFromReference(api, param)
}
return methods.extractQueryKeyValuePairFromParameter(param)
}
/**
* extracts a query string from a request
* @param {Api} api: the api to use to resolve shared parameters
* @param {Request} request: the request to extract the query string from
* @returns {string} the corresponding queryString
*/
methods.extractQueryStringFromRequest = (api, request) => {
const queryString = request.getIn([ 'parameters', 'queries' ])
.map(param => {
return methods.extractQueryKeyValuePairFromParameterOrReference(api, param)
})
.filter(v => !!v)
.valueSeq()
.toJS()
.join('&')
if (queryString === '') {
return queryString
}
return '?' + queryString
}
/**
* merges together a base url with a path and a queryString
* @param {string} baseUrl: the base url from the endpoint of a request/resoure
* @param {string} path: the path of the resource this url belongs to
* @param {string} queryString: the queryString associated with the request this url belongs to
* @returns {Entry<string, string>} the corresponding complete url, as an Entry
*/
methods.combineUrlComponents = (baseUrl, path, queryString) => {
if (baseUrl[baseUrl.length - 1] === '/' && path[0] === '/' || path === '/') {
const url = baseUrl + path.slice(1)
return { key: 'url', value: url + queryString }
}
const url = baseUrl + path
return { key: 'url', value: url + queryString }
}
/**
* extracts a url from an endpoint
* @param {URL|string} endpoint: the endpoint to extract a url from
* @returns {string} the corresponding url
*/
methods.extractBaseUrlFromEndpoint = (endpoint) => {
const baseUrl = typeof endpoint === 'string' ?
endpoint :
endpoint.generate(List([ '{{', '}}' ]))
return baseUrl
}
/**
* extract a path from a resource
* @param {Resource} resource: the resource to get the path from
* @returns {string} the corresponding path
*/
methods.extractPathFromResource = (resource) => {
const pathname = resource.getIn([ 'path', 'pathname' ])
if (!pathname) {
return '/'
}
const path = pathname
.generate(List([ ':', '' ]))
return path
}
/**
* creates a postman url entry from a request and its containing resource
* @param {Api} api: the Api record to use to resolve shared objects
* @param {Resource} resource: the resource from which to get the path and shared endpoints
* @param {Request} request: the request from which to get the shared endpoints. It overrides the
* ones from the Resource level
* @returns {Entry<string, string>?} the corresponding entry, if it exists
*/
methods.createRequestUrl = (api, resource, request) => {
const endpointOrReference = methods.getEndpointOrReferenceFromResourceAndRequest(
resource, request
)
let endpoint = endpointOrReference
if (endpointOrReference instanceof Reference) {
endpoint = methods.getEndpointFromReference(api, endpointOrReference)
}
if (!endpoint) {
return null
}
const baseUrl = methods.extractBaseUrlFromEndpoint(endpoint)
const path = methods.extractPathFromResource(resource)
const queryString = methods.extractQueryStringFromRequest(api, request)
return methods.combineUrlComponents(baseUrl, path, queryString)
}
/**
* converts an AWSSig4 auth into a postmanAuth property
* @param {Auth} auth: the auth to convert
* @returns {{
* type: 'awsv4',
* awsv4: Object
* }} the corresponding postmanAuth property
*/
methods.createRequestAuthFromAWSSig4Auth = (auth) => {
const kvs = [
{ key: 'accessKey', value: auth.get('key') },
{ key: 'secretKey', value: auth.get('secret') },
{ key: 'region', value: auth.get('region') },
{ key: 'service', value: auth.get('service') }
].filter(({ value }) => !!value)
if (!kvs.length) {
return { type: 'awsv4' }
}
return { type: 'awsv4', awsv4: kvs.reduce(convertEntryListInMap, {}) }
}
/**
* converts a Basic auth into a postmanAuth property
* @param {Auth} auth: the auth to convert
* @returns {{
* type: 'basic',
* basic: Object
* }} the corresponding postmanAuth property
*/
methods.createRequestAuthFromBasicAuth = (auth) => {
const kvs = [
{ key: 'username', value: auth.get('username') },
{ key: 'password', value: auth.get('password') }
].filter(({ value }) => !!value)
if (!kvs.length) {
return { type: 'basic' }
}
return { type: 'basic', basic: kvs.reduce(convertEntryListInMap, {}) }
}
/**
* converts a Digest auth into a postmanAuth property
* @param {Auth} auth: the auth to convert
* @returns {{
* type: 'digest',
* digest: Object
* }} the corresponding postmanAuth property
*/
methods.createRequestAuthFromDigestAuth = (auth) => {
const kvs = [
{ key: 'username', value: auth.get('username') },
{ key: 'password', value: auth.get('password') }
].filter(({ value }) => !!value)
if (!kvs.length) {
return { type: 'digest' }
}
return { type: 'digest', digest: kvs.reduce(convertEntryListInMap, {}) }
}
/**
* converts an Hawk auth into a postmanAuth property
* @param {Auth} auth: the auth to convert
* @returns {{
* type: 'hawk',
* hawk: Object
* }} the corresponding postmanAuth property
*/
methods.createRequestAuthFromHawkAuth = (auth) => {
const kvs = [
{ key: 'authId', value: auth.get('id') },
{ key: 'authKey', value: auth.get('key') },
{ key: 'algorithm', value: auth.get('algorithm') }
].filter(({ value }) => !!value)
if (!kvs.length) {
return { type: 'hawk' }
}
return { type: 'hawk', hawk: kvs.reduce(convertEntryListInMap, {}) }
}
/**
* converts an OAuth1 auth into a postmanAuth property
* @param {Auth} auth: the auth to convert
* @returns {{
* type: 'oauth1',
* oauth1: Object
* }} the corresponding postmanAuth property
*/
methods.createRequestAuthFromOAuth1Auth = (auth) => {
const kvs = [
{ key: 'consumerSecret', value: auth.get('consumerSecret') },
{ key: 'consumerKey', value: auth.get('consumerKey') },
{ key: 'token', value: auth.get('token') },
{ key: 'tokenSecret', value: auth.get('tokenSecret') },
{ key: 'signatureMethod', value: auth.get('algorithm') },
{ key: 'nonce', value: auth.get('nonce') },
{ key: 'version', value: auth.get('version') }
].filter(({ value }) => !!value)
if (!kvs.length) {
return { type: 'oauth1' }
}
return { type: 'oauth1', oauth1: kvs.reduce(convertEntryListInMap, {}) }
}
/**
* converts an OAuth2 auth into a postmanAuth property
* @param {Auth} auth: the auth to convert
* @returns {{
* type: 'oauth2',
* oauth2: Object
* }} the corresponding postmanAuth property
*/
methods.createRequestAuthFromOAuth2Auth = (auth) => {
const kvs = [
{ key: 'authUrl', value: auth.get('authorizationUrl') },
{ key: 'accessTokenUrl', value: auth.get('tokenUrl') },
{ key: 'scope', value: auth.get('scopes').map(({ key }) => key).join(' ') || null }
].filter(({ value }) => !!value)
if (!kvs.length) {
return { type: 'oauth2' }
}
return { type: 'oauth2', oauth2: kvs.reduce(convertEntryListInMap, {}) }
}
/* eslint-disable max-statements */
/**
* converts an Auth into a postmanAuth
* @param {Auth} auth: the auth to convert
* @returns {Entry<string, PostmanAuth>?} the corresponding postmanAuth entry, if it exists
*/
methods.createRequestAuthFromAuth = (auth) => {
let postmanAuth = null
if (auth instanceof Auth.AWSSig4) {
postmanAuth = methods.createRequestAuthFromAWSSig4Auth(auth)
}
if (auth instanceof Auth.Basic) {
postmanAuth = methods.createRequestAuthFromBasicAuth(auth)
}
if (auth instanceof Auth.Digest) {
postmanAuth = methods.createRequestAuthFromDigestAuth(auth)
}
if (auth instanceof Auth.Hawk) {
postmanAuth = methods.createRequestAuthFromHawkAuth(auth)
}
if (auth instanceof Auth.OAuth1) {
postmanAuth = methods.createRequestAuthFromOAuth1Auth(auth)
}
if (auth instanceof Auth.OAuth2) {
postmanAuth = methods.createRequestAuthFromOAuth2Auth(auth)
}
if (!postmanAuth) {
return null
}
return { key: 'auth', value: postmanAuth }
}
/* eslint-enable max-statements */
/**
* converts the Auths from a request into a postmanAuth
* @param {Api} api: the Api from which to get the shared auth methods
* @param {Request} request: the request from which to get the *potentially null* auth references
* @returns {Entry<string, PostmanAuth>?} the corresponding postmanAuth entry, if it exists.
*/
methods.createRequestAuth = (api, request) => {
const auths = request.get('auths').valueSeq()
if (!auths.size) {
return null
}
const auth = auths.get(0)
if (!auth) {
return { key: 'auth', value: { type: 'noauth', noauth: {} } }
}
const authData = api.getIn([ 'store', 'auth', auth.get('uuid') ])
const postmanAuth = methods.createRequestAuthFromAuth(authData)
return postmanAuth || null
}
/**
* extracts a PostmanMethod from a request
* @param {Request} request: the request from which to extract the method
* @returns {Entry<string, string>?} the corresponding entry, if it exists
*/
methods.createMethod = (request) => {
const method = request.get('method')
if (!method) {
return null
}
return { key: 'method', value: method.toUpperCase() }
}
/**
* creates a Header from a reference
* @param {Api} api: the api to use to resolve the shared parameters
* @param {Reference} reference: the reference to convert into a header
* @returns {Entry<string?, string>?} the corresponding header, formatted as an entry, if it exists
*/
methods.createHeaderFromReference = (api, reference) => {
const param = api.getIn([ 'store', 'parameter', reference.get('uuid') ])
if (!param) {
return null
}
const key = param.get('key')
const value = '{{' + reference.get('uuid') + '}}'
return { key, value }
}
/**
* creates a header from a Parameter
* @param {Parameter} param: the parameter to convert into a header
* @returns {Entry<string, string>?} the corresponding header, formatted as an Entry, if it exists
*/
methods.createHeaderFromParameter = (param) => {
const key = param.get('key')
if (!key) {
return null
}
const schema = param.getJSONSchema()
if (schema.default) {
return { key, value: schema.default }
}
if (schema.enum) {
return { key, value: schema.enum[0] }
}
return { key, value: null }
}
/**
* extracts a header from a Parameter or Reference
* @param {Api} api: the api to use to resolve shared parameters
* @param {Parameter|Reference} paramOrReference: the parameter or reference to convert into a
* header
* @returns {Entry<string?, string>?} the corresponding header, formatted as an Entry, if it exists
*/
methods.createHeaderFromParameterOrReference = (api, paramOrReference) => {
if (paramOrReference instanceof Reference) {
return methods.createHeaderFromReference(api, paramOrReference)
}
if (!paramOrReference || !paramOrReference.get('key')) {
return null
}
return methods.createHeaderFromParameter(paramOrReference)
}
/**
* extracts a PostmanHeader from a request
* @param {Api} api: the api to use to resolve shared parameters
* @param {Request} request: the request from which to extract the headers
* @returns {Entry<string, PostmanHeader>?} the corresponding entry, if it exists
*/
methods.createHeader = (api, request) => {
const headers = request.getIn([ 'parameters', 'headers' ])
.map(header => methods.createHeaderFromParameterOrReference(api, header))
.filter(v => !!v)
if (!headers.size) {
return null
}
return { key: 'header', value: headers.valueSeq().toJS() }
}
/**
* extracts content-type parameters from the headers of request
* @param {Api} api: the api to use to resolve shared parameters
* @param {Request} request: the request to get the content-type parameters from
* @returns {List<Parameter>} the corresponding List of Content-Type Parameters
*/
methods.getContentTypeParamsFromHeaders = (api, request) => {
const contentTypeHeaders = request.get('parameters')
.resolve(api.get('store'))
.get('headers')
.filter(header => header.get('key') === 'Content-Type')
.valueSeq()
.toList()
return contentTypeHeaders
}
/**
* extracts content-type parameters from a context
* @param {Context} context: the context to extract the content-type parameters from
* @returns {List<Parameter>} the corresponding List of Content-Type Parameters
*/
methods.getContentTypeParamsFromContext = (context) => {
return context.get('constraints').filter(param => {
return param.get('key') === 'Content-Type' &&
param.get('in') === 'headers' &&
param.get('usedIn') === 'request'
})
}
/**
* extracts content-type parameters from a context, or from the headers of a request, if the context
* does not exist
* @param {Api} api: the api to use to resolve shared parameters
* @param {Request} request: the request to get the headers from
* @param {Context?} context: the context to extract content-type parameters from
* @returns {List<Parameter>} the corresponding list of content-type Parameters
*/
methods.getContentTypeParamsFromRequestOrContext = (api, request, context) => {
if (!context) {
return methods.getContentTypeParamsFromHeaders(api, request)
}
return methods.getContentTypeParamsFromContext(context)
}
/**
* extracts a postman body mode from the `default` field of a schema
* @param {JSONSchema} schema: the schema to extract the body mode from
* @returns {'urlencoded'|'formdata'|'raw'} the corresponding body mode
*/
methods.createBodyModeFromSchemaDefault = (schema) => {
const modeMap = [
{ key: 'application/x-www-form-urlencoded', value: 'urlencoded' },
{ key: 'multipart/form-data', value: 'formdata' }
]
const mode = modeMap
.filter(({ key }) => schema.default.match(key))
.map(({ value }) => value)[0]
return mode || 'raw'
}
/**
* extracts a postman body mode from the `enum` field of a schema
* @param {JSONSchema} schema: the schema to extract the body mode from
* @returns {'urlencoded'|'formdata'|'raw'} the corresponding body mode
*/
methods.createBodyModeFromSchemaEnum = (schema) => {
const modeMap = [
{ key: 'application/x-www-form-urlencoded', value: 'urlencoded' },
{ key: 'multipart/form-data', value: 'formdata' }
]
const mode = modeMap
.filter(({ key }) => {
return schema.enum.filter(contentType => contentType.match(key)).length > 0
})
.map(({ value }) => value)[0]
return mode || 'raw'
}
/**
* extracts a postman body mode from a List of Content Type Parameters
* @param {List<Parameter>} contentTypeParams: the List of Parameter from which to extract a body
* mode
* @returns {'urlencoded'|'formdata'|'raw'} the corresponding body mode
*/
methods.createBodyModeFromContentTypeParams = (contentTypeParams) => {
if (contentTypeParams.size !== 1) {
return 'raw'
}
const contentTypesConstraint = contentTypeParams.get(0)
const contentTypeSchema = contentTypesConstraint.getJSONSchema()
if (contentTypeSchema.default) {
return methods.createBodyModeFromSchemaDefault(contentTypeSchema)
}
if (contentTypeSchema.enum) {
return methods.createBodyModeFromSchemaEnum(contentTypeSchema)
}
return 'raw'
}
/**
* extracts a PostmanBodyMode from a Context
* @param {Api} api: the api to use to resolve shared parameters
* @param {Request} request: the request from which to get the body parameters
* @param {Context} context: the context from which to infer the body mode
* @returns {'raw'|'formdata'|'urlencoded'} the corresponding body mode
*/
methods.createBodyMode = (api, request, context) => {
const contentTypeParams = methods.getContentTypeParamsFromRequestOrContext(api, request, context)
return methods.createBodyModeFromContentTypeParams(contentTypeParams)
}
/**
* converts a Map of Body Parameters into a raw postman parameters string
* @param {OrderedMap<string, Parameter>} params: the body parameters to convert into raw parameters
* @returns {string} the corresponding raw parameters string
*/
methods.convertBodyParametersIntoRawParameters = (params) => {
const rawBody = params
.map(param => {
if (param.get('key')) {
return '{{' + param.get('key') + '}}'
}
return JSON.stringify(param.getJSONSchema(), null, 2)
})
.valueSeq()
.toJS()
.join('\n')
return rawBody
}
/**
* extracts a PostmanRawBody entry from a request in a specific context
* @param {OrderedMap<string, Parameter>} bodyParams: the body parameters to convert into raw
* parameters
* @returns {Entry<string, PostmanRawBody>?} the corresponding entry, if it exists
*/
methods.createBodyFromRawMode = (bodyParams) => {
if (!bodyParams.size) {
return null
}
const rawBody = methods.convertBodyParametersIntoRawParameters(bodyParams)
return { key: 'raw', value: rawBody }
}
/**
* extracts a PostmanUrlEncodedBody entry from a request in a specific context
* @param {OrderedMap<string, Parameter>} bodyParams: the body parameters to convert into
* postman url-encoded parameters
* @returns {Entry<string, PostmanUrlEncodedBody>?} the corresponding entry, if it exists
*/
methods.createBodyFromUrlEncodedMode = (bodyParams) => {
const postmanParams = bodyParams.map(param => {
return {
key: param.get('key'),
value: param.get('default') || ('{{' + param.get('key') + '}}'),
enabled: true
}
}).valueSeq().toJS()
return { key: 'urlencoded', value: postmanParams }
}
/**
* extracts a PostmanFormDataBody entry from a request in a specific context
* @param {OrderedMap<string, Parameter>} bodyParams: the body parameters to convert into
* postman url-encoded parameters
* @returns {Entry<string, PostmanFormDataBody>?} the corresponding entry, if it exists
*/
methods.createBodyFromFormDataMode = (bodyParams) => {
const postmanParams = bodyParams.map(param => {
return {
key: param.get('key'),
value: param.get('default') || ('{{' + param.get('key') + '}}'),
enabled: true
}
}).valueSeq().toJS()
return { key: 'formdata', value: postmanParams }
}
/**
* extracts a PostmanModalBody entry from a request in a specific context and mode
* @param {OrderedMap<string, Parameter>} bodyParams: the body parameters to convert into
* postman modal parameters (e.g. depending on the mode, they are converted differently)
* @param {string} mode: the mode in which the body should be formatted
* @returns {Entry<string, PostmanModalBody>?} the corresponding entry, if it exists
*/
methods.createBodyFromMode = (bodyParams, mode) => {
if (mode === 'raw') {
return methods.createBodyFromRawMode(bodyParams)
}
if (mode === 'urlencoded') {
return methods.createBodyFromUrlEncodedMode(bodyParams)
}
if (mode === 'formdata') {
return methods.createBodyFromFormDataMode(bodyParams)
}
return null
}
/**
* prepares body parameters from a request based on a store and context
* @param {Api} api: the api that holds the store used to resolve shared parameters
* @param {Request} request: the request to extract the body parameters from
* @param {Context?} context: the context to use to filter the body parameters
* @returns {OrderedMap<string, Parameter>} the corresponding body parameters container block
*/
methods.getBodyParamsFromRequest = (api, request, context) => {
const constraints = context ? context.get('constraints') : List()
const bodyParams = request.get('parameters')
.resolve(api.get('store'))
.filter(constraints)
.get('body')
return bodyParams
}
/**
* extracts a PostmanBody entry from a request
* @param {Api} api: the api to use to resolve shared parameters
* @param {Request} request: the request from which to get the body parameters
* @returns {Entry<string, PostmanBody>?} the corresponding entry, if it exists
*/
methods.createBody = (api, request) => {
const context = request.get('contexts').get(0)
const bodyParams = methods.getBodyParamsFromRequest(api, request, context)
const mode = methods.createBodyMode(api, request, context)
const kvs = [
{ key: 'mode', value: mode },
methods.createBodyFromMode(bodyParams, mode)
].filter(v => !!v)
if (kvs.length <= 1) {
return null
}
return { key: 'body', value: kvs.reduce(convertEntryListInMap, {}) }
}
/**
* extracts a PostmanRequest entry from a request
* @param {Api} api: the api to use to resolve shared parameters
* @param {Resource} resource: the resource to use to generate the url
* @param {Request} request: the request from which to get the body parameters
* @returns {Entry<string, PostmanRequest>?} the corresponding entry, if it exists
*/
methods.createRequestFromRequest = (api, resource, request) => {
const kvs = [
methods.createRequestUrl(api, resource, request),
methods.createRequestAuth(api, request),
methods.createMethod(request),
methods.createHeader(api, request),
methods.createBody(api, request)
].filter(v => !!v)
if (!kvs.length) {
return null
}
return { key: 'request', value: kvs.reduce(convertEntryListInMap, {}) }
}
/**
* extracts a PostmanItem from a request
* @param {Api} api: the api to use to resolve shared parameters
* @param {Resource} resource: the resource to use to generate the url for the request associated
* with this item
* @param {Request} request: the request from which to get the body parameters
* @returns {PostmanItem} the corresponding PostmanItem
*/
methods.createItemFromRequest = (api, resource, request) => {
const kvs = [
methods.createItemName(request),
methods.createItemDescription(request),
methods.createRequestFromRequest(api, resource, request)
].filter(v => !!v)
return kvs.reduce(convertEntryListInMap, {})
}
/**
* extracts an array of PostmanItems from a resource
* @param {Api} api: the api to use to resolve shared parameters
* @param {Resource} resource: the resource to use to generate the PostmanItems
* @returns {Array<PostmanItem>} the corresponding array of PostmanItems
*/
methods.createItemsFromResource = (api, resource) => {
const items = resource.get('methods')
.map(request => methods.createItemFromRequest(api, resource, request))
.valueSeq()
.toJS()
return items
}
/**
* creates an Item Name from a Resource
* @param {Resource} resource: the resource to extract a name from
* @returns {Entry<string, string>} the corresponding name, as an Entry
*/
methods.createItemNameFromResource = (resource) => {
const name = resource.get('name') ||
resource.get('description') ||
resource.getIn([ 'path', 'pathname' ]).generate(List([ ':', '' ]))
return { key: 'name', value: name }
}
/**
* extracts a PostmanItemGroup entry from an Api and a resourceId
* @param {Api} api: the api to use to resolve shared parameters
* @param {string} id: the resourceId to use to resolve the resource in the Api
* @returns {Entry<string, PostmanItemGroup>?} the corresponding entry, if it exists
*/
methods.createItemGroupFromResource = (api, id) => {
const resource = api.getIn([ 'resources', id ])
if (!resource) {
return null
}
const kvs = [
methods.createItemNameFromResource(resource),
methods.createItemDescription(resource),
{ key: 'item', value: methods.createItemsFromResource(api, resource) }
].filter(v => !!v)
const result = kvs.reduce(convertEntryListInMap, {})
return result
}
/**
* extracts a PostmanItem property as an entry from an Api and a Group or a Resource
* @param {Api} api: the api to use to resolve shared objects
* @param {Group|Resource} groupOrResource: the group or resource to convert into a
* PostmanItemGroup
* @returns {Entry<string, PostmanItemGroup>} the corresponding entry, if it exists
*/
methods.createItemGroupFromGroupOrResource = (api, groupOrResource) => {
if (groupOrResource instanceof Group) {
return methods.createItemGroup(api, groupOrResource)
}
return methods.createItemGroupFromResource(api, groupOrResource)
}
/**
* extracts a PostmanItem property as an entry from an Api and a Group
* @param {Api} api: the api to use to resolve shared objects
* @param {Group} group: the group from which to convert into a PostmanItemGroupProperty
* @returns {Entry<string, PostmanItemGroupProperty>} the corresponding entry, if it exists
*/
methods.createItemProp = (api, group) => {
const items = group.get('children')
.map(child => methods.createItemGroupFromGroupOrResource(api, child))
.filter(v => !!v)
return { key: 'item', value: items.valueSeq().toJS() }
}
/**
* creates an PostmanItemGroup from an Api and a Group
* @param {Api} api: the api to use to resolve shared objects
* @param {Group} group: the group from which to convert into a PostmanItemGroup
* @returns {Entry<string, PostmanItemGroup>} the corresponding entry
*/
methods.createItemGroup = (api, group) => {
const kvs = [
methods.createItemName(group),
methods.createItemDescription(group),
methods.createItemProp(api, group)
].filter(v => !!v)
return kvs.reduce(convertEntryListInMap, {})
}
/**
* merges item groups that have the same name. This is done because there are no constraints on the
* unicity of a Resource wrt to its name/description/path in Api.get('resources'). This unicity
* principle would be violated by the Paw/Postman and curl parser otherwise
* @param {Map<string, PostmanItemGroup>} namedMap: the accumulator map that is used to merge
* item groups together
* @param {PostmanItemGroup} itemGroup: the item group to merge or add to the accumulator
* @returns {Map<string, PostmanItemGroup>} the updated accumulator
*/
methods.mergeItemGroupsWithSameName = (namedMap, itemGroup) => {
const namedItemGroup = namedMap.get(itemGroup.name)
if (namedItemGroup) {
namedItemGroup.item = [].concat(namedItemGroup.item || [], itemGroup.item || [])
return namedMap.set(itemGroup.name, namedItemGroup)
}
return namedMap.set(itemGroup.name, itemGroup)
}
/**
* creates an PostmanRootItem from an Api
* @param {Api} api: the api to use to extract groups
* @returns {Entry<string, PostmanRootItem>} the corresponding entry
*/
methods.createRootItem = (api) => {
const group = api.get('group')
if (!group) {
return { key: 'item', value: [] }
}
const items = api.get('resources')
.map((_, id) => methods.createItemGroupFromResource(api, id))
.filter(v => !!v)
.reduce(methods.mergeItemGroupsWithSameName, Map())
.valueSeq()
.toJS()
return { key: 'item', value: items }
}
/*
NOTE: This should be used once postman is capable of dealing with multiple nesting level
methods.createRootItem = (api) => {
const group = api.get('group')
if (!group) {
return { key: 'item', value: [] }
}
return { key: 'item', value: [ methods.createItemGroup(api, group) ] }
}
*/
/**
* converts a **shared** Parameter into a postman variable
* @param {Parameter} param: the parameter to converts
* @param {string} key: the key of the parameter in TypedStore that contains it (equals the uuid of
* potential references to it)
* @returns {PostmanVariable?} the corresponding postman variable, if it exists
*/
methods.convertParameterIntoVariable = (param, key) => {
const kvs = [
{ key: 'id', value: key },
{ key: 'value', value: param.get('default') },
{ key: 'type', value: param.get('type') },
{ key: 'name', value: param.get('key') }
].filter(({ value }) => !!value)
if (!kvs.length) {
return null
}
return kvs.reduce(convertEntryListInMap, {})
}
/**
* creates an PostmanVariable from an Api
* @param {Api} api: the api to use to resolve shared objects
* @returns {Entry<string, PostmanVariable>?} the corresponding entry, if it exists
*/
methods.createVariable = (api) => {
const sharedParams = api.getIn([ 'store', 'parameter' ])
if (!sharedParams.size) {
return null
}
const variables = sharedParams
.map(methods.convertParameterIntoVariable)
.filter(v => !!v)
.valueSeq()
.toJS()
if (!variables.length) {
return null
}
return { key: 'variable', value: variables }
}
/**
* creates a PostmanCollection from an Api
* @param {Api} api: the api to use to convert into a PostmanCollection
* @returns {Entry<string, PostmanCollection>} the corresponding entry
*/
methods.createPostmanCollection = (api) => {
const kvs = [
methods.createInfo(api),
methods.createRootItem(api),
methods.createVariable(api)
].filter(v => !!v)
return kvs.reduce(convertEntryListInMap, {})
}
/**
* serializes an Api into a Swagger formatted string
* @param {Api} api: the api to convert
* @returns {string} the corresponding swagger object, as a string
*/
methods.serialize = ({ api }) => {
try {
const postmanCollection = methods.createPostmanCollection(api)
const serialized = JSON.stringify(postmanCollection, null, 2)
return serialized
}
catch (e) {
throw e
}
}
export const __internals__ = methods
export default PostmanSerializer
/* eslint-enable no-undefined */
| luckymarmot/API-Flow | src/serializers/postman/v2.0/Serializer.js | JavaScript | mit | 37,261 |
var f = function(){
//定义测试模块
module("ui-card");
var _ = NEJ.P,
_e = _('nej.e'),
_p = _('nej.ui');
//开始单元测试
test('card',function(){
stop();
var _card = _p._$$Card._$allocate({
parent:'card-box',
top:10,
left:10,
destroyable:true,
content:'<div>您要显示的内容HTML或节点</div>',
oncontentready:function(_html){
ok(true,'设置卡片内容成功');
},
onbeforerecycle:function(){
ok(true,'destroyable属性决定回收前是否触发');
start();
}
});
// _card._$show();
});
}
module('依赖模块');
test('define',function(){
define('{pro}uiCardTest.js',['{lib}ui/layer/card.js','{pro}log.js'],f);
}); | hushulin/synbass | public/assets/js/nej/baseline/qunit/javascript/ui/cardTest.js | JavaScript | mit | 878 |
var copyable_8h =
[
[ "swap", "namespacehryky.html#a39d9ffc629490589a9941a892b7073c8", null ]
]; | hiroyuki-seki/hryky-codebase | doc/html/copyable_8h.js | JavaScript | mit | 100 |
var chai = require('chai');
var expect = chai.expect;
var Share = require("./share");
var Test = require("../../../utils/test");
describe('Planning Poker Module / Share', function () {
var t, share, vote1, vote2, bot, message, story;
it('Declares to the adapter when the function should be executed', function() {
t.bot().will.reactTo('Share results for (.*)');
share.listenedBy(bot);
});
it('Describes what it can do', function() {
expect(share.description()).to.equal('Share the results of a Planning Poker by saying `Share results for (.*)`\n');
});
it('Lets you know when there is no story for the mentioned key.', function () {
story = t.aStory().withKey('BLR-1337').build();
t.getMock('story').expects('get').once().withArgs('BLR-1337').returns(Promise.resolve(story));
t.bot().will.reply('I\'m afraid I have no result for this story.');
share.results(bot, message);
});
it('Gives out the voting results for the mentioned story.', function () {
vote1 = t.aVote().withUser('jprivard').withValue(8).build();
vote2 = t.aVote().withUser('etremblay').withValue(5).build();
story = t.aStory().withKey('BLR-1337').addVote(vote1).addVote(vote2).build();
t.getMock('story').expects('get').once().withArgs('BLR-1337').returns(Promise.resolve(story));
t.bot().will.reply(['results for BLR-1337', '<@jprivard> voted 8', '<@etremblay> voted 5']);
share.results(bot, message);
});
beforeEach(function () {
t = new Test();
message = t.aMessage('jprivard', 'BLR-1337');
bot = t.createMock('bot', t.aBot());
share = new Share(t.createMock('story', Test.Story.Object));
});
afterEach(function () {
t.verifyMocks();
});
});
| jprivard/podrick | podrick/modules/planning-poker/functions/share.test.js | JavaScript | mit | 1,816 |
import compile from '../';
let mockCompiler;
jest.mock('../createCompiler', () => () => mockCompiler);
const webpackConfig = { config: true };
let webpackError;
let errors;
let assets;
beforeEach(() => {
webpackError = undefined;
errors = [];
assets = {};
mockCompiler = {
run: fn =>
fn(webpackError, {
compilation: {
assets,
errors,
},
}),
};
});
const givenWebpackError = error => {
webpackError = error;
};
const givenCompileError = error => {
errors.push(error);
};
const givenAsset = (path, src) => {
assets[path] = { source: () => src };
};
it('rejects when webpack errors internally', async () => {
givenWebpackError('internal webpack error');
try {
await compile(webpackConfig);
throw new Error('`compile` should have failed');
} catch (e) {
expect(e).toEqual(['internal webpack error']);
}
});
it('rejects with webpack fails to compile', async () => {
givenCompileError('file 1 failed to compile');
givenCompileError('file 2 failed to compile');
try {
await compile(webpackConfig);
throw new Error('`compile` should have failed');
} catch (e) {
expect(e).toEqual(['file 1 failed to compile', 'file 2 failed to compile']);
}
});
it('resolves with compiled files when webpack succeeds', async () => {
givenAsset('/file1.js', 'const x = 1;');
givenAsset('/file2.css', '.foo { background: red; }');
const files = await compile(webpackConfig);
expect(files).toEqual({
'/file1.js': 'const x = 1;',
'/file2.css': '.foo { background: red; }',
});
});
| percy/react-percy | packages/react-percy-webpack/src/compile/__tests__/compile-tests.js | JavaScript | mit | 1,592 |
"use strict"
const BinaryArray = require('..')
const getMax = (spec) => Object.keys(spec).reduce((r, k) => Math.max(r, spec[k]), 0) + 1
const ROLE = {
ADMIN_MANAGER : 0,
DEVELOPPER : 1,
BUSINESS_OWNER : 2,
CUSTOMER_SUPPORT_VIEW : 3,
CUSTOMER_SUPPORT_UPDATE : 4,
}
const ROLE_MAX = getMax(ROLE)
const ba = new BinaryArray(ROLE_MAX)
for(let i = 0; i < ROLE_MAX; ++i){
ba.bitOn(i)
}
if(ba.at(ROLE.ADMIN_MANAGER)){
console.log("ADMIN")
}
console.log(ba.serialize(ROLE))
console.log(ba.toArray(ROLE).join(""))
| you21979/node-binaryarray | example/ex_admin_flag.js | JavaScript | mit | 537 |
/*
* This example show how to load complex shapes created with PhysicsEditor (https://www.codeandweb.com/physicseditor)
*/
var config = {
type: Phaser.AUTO,
width: 1200,
height: 960,
parent: 'game',
scene: {
preload: preload,
create: create
},
physics: {
default: "matter",
matter: {
debug: true
}
}
};
var game = new Phaser.Game(config);
function preload() {
// Load sprite sheet generated with TexturePacker
this.load.atlas('sheet', 'assets/fruit-sprites.png', 'assets/fruit-sprites.json');
// Load body shapes from JSON file generated using PhysicsEditor
this.load.json('shapes', 'assets/fruit-shapes.json');
}
function create() {
var shapes = this.cache.json.get('shapes');
this.matter.world.setBounds(0, 0, game.config.width, game.config.height);
this.add.image(0, 0, 'sheet', 'background').setOrigin(0, 0);
// sprites are positioned at their center of mass
var ground = this.matter.add.sprite(0, 0, 'sheet', 'ground', {shape: shapes.ground});
ground.setPosition(0 + ground.centerOfMass.x, 280 + ground.centerOfMass.y); // corrected position: (0,280)
this.add.text(10, 10, 'Test 03');
var mattersprites = { };
mattersprites.crate = this.matter.add.sprite(200, 50, 'sheet', 'crate', {shape: shapes.crate});
mattersprites.banana = this.matter.add.sprite(250, 250, 'sheet', 'banana', {shape: shapes.banana});
mattersprites.orange = this.matter.add.sprite(360, 50, 'sheet', 'orange', {shape: shapes.orange});
mattersprites.cherries = this.matter.add.sprite(400, 250, 'sheet', 'cherries', {shape: shapes.cherries});
mattersprites.crate.setInteractive();
this.input.setDraggable(mattersprites.crate);
mattersprites.banana.setInteractive();
this.input.setDraggable(mattersprites.banana);
mattersprites.orange.setInteractive();
this.input.setDraggable(mattersprites.orange);
mattersprites.cherries.setInteractive();
this.input.setDraggable(mattersprites.cherries);
this.input.on('drag', function (pointer, gameObject, dragX, dragY) {
gameObject.x = dragX;
gameObject.y = dragY;
});
}
| dariocavada/dariocavada.github.com | static/public/phaser3matterjsTest/index03.js | JavaScript | mit | 2,223 |
import $ from 'jquery';
import { deprecatedCreateFlash as Flash } from './flash';
import { __ } from './locale';
import { parseBoolean } from './lib/utils/common_utils';
/*
example HAML:
```
%button.js-project-feature-toggle.project-feature-toggle{ type: "button",
class: "#{'is-checked' if enabled?}",
'aria-label': _('Toggle Kubernetes Cluster') }
%input{ type: "hidden", class: 'js-project-feature-toggle-input', value: enabled? }
```
*/
function updateToggle(toggle, isOn) {
toggle.classList.toggle('is-checked', isOn);
}
function onToggleClicked(toggle, input, clickCallback) {
const previousIsOn = parseBoolean(input.value);
// Visually change the toggle and start loading
updateToggle(toggle, !previousIsOn);
toggle.setAttribute('disabled', true);
toggle.classList.toggle('is-loading', true);
Promise.resolve(clickCallback(!previousIsOn, toggle))
.then(() => {
// Actually change the input value
input.setAttribute('value', !previousIsOn);
})
.catch(() => {
// Revert the visuals if something goes wrong
updateToggle(toggle, previousIsOn);
})
.then(() => {
// Remove the loading indicator in any case
toggle.removeAttribute('disabled');
toggle.classList.toggle('is-loading', false);
$(input).trigger('trigger-change');
})
.catch(() => {
Flash(__('Something went wrong when toggling the button'));
});
}
export default function setupToggleButtons(container, clickCallback = () => {}) {
const toggles = container.querySelectorAll('.js-project-feature-toggle');
toggles.forEach(toggle => {
const input = toggle.querySelector('.js-project-feature-toggle-input');
const isOn = parseBoolean(input.value);
// Get the visible toggle in sync with the hidden input
updateToggle(toggle, isOn);
toggle.addEventListener('click', onToggleClicked.bind(null, toggle, input, clickCallback));
});
}
| mmkassem/gitlabhq | app/assets/javascripts/toggle_buttons.js | JavaScript | mit | 1,942 |
game.square = me.DraggableEntity.extend({
/**
* constructor
*/
init: function (x, y, settings) {
// call the super constructor
this._super(me.DraggableEntity, 'init', [x, y, settings]);
// set the color to white
this.color = "white";
},
/**
* update function
*/
update: function () {
return true;
},
/**
* draw the square
*/
draw: function (renderer) {
renderer.setColor(this.color);
renderer.fillRect(this.pos.x, this.pos.y, this.width, this.height);
},
/**
* dragStart overwrite function
*/
dragStart: function (e) {
// call the super function
this._super(me.DraggableEntity, 'dragStart', [e]);
// set the color to blue
this.color = 'blue';
},
dragEnd: function (e) {
// call the super function
this._super(me.DraggableEntity, 'dragEnd', [e]);
// set the color to white
this.color = 'white';
}
});
| MarkoIvanetic/melonJS | examples/multitouch/js/entities/entities.js | JavaScript | mit | 1,016 |
/*! jQuery UI - v1.9.2 - 2015-05-31
* http://jqueryui.com
* Copyright 2015 jQuery Foundation and other contributors; Licensed MIT */
(function(e){e.effects.effect.fold=function(t,i){var s,a,n=e(this),r=["position","top","bottom","left","right","height","width"],o=e.effects.setMode(n,t.mode||"hide"),l="show"===o,h="hide"===o,u=t.size||15,d=/([0-9]+)%/.exec(u),c=!!t.horizFirst,p=l!==c,m=p?["width","height"]:["height","width"],f=t.duration/2,g={},v={};e.effects.save(n,r),n.show(),s=e.effects.createWrapper(n).css({overflow:"hidden"}),a=p?[s.width(),s.height()]:[s.height(),s.width()],d&&(u=parseInt(d[1],10)/100*a[h?0:1]),l&&s.css(c?{height:0,width:u}:{height:u,width:0}),g[m[0]]=l?a[0]:u,v[m[1]]=l?a[1]:0,s.animate(g,f,t.easing).animate(v,f,t.easing,function(){h&&n.hide(),e.effects.restore(n,r),e.effects.removeWrapper(n),i()})}})(jQuery); | cthit/nollkIT | js/jquery.custom/development-bundle/ui/minified/jquery.ui.effect-fold.min.js | JavaScript | mit | 844 |
{
this.label = label;
this.left = left;
this.right = right;
}
| stas-vilchik/bdd-ml | data/2817.js | JavaScript | mit | 68 |
export Project from './Project';
| codejunkienick/starter-lapis | app/screens/App/screens/Projects/shared/index.js | JavaScript | mit | 33 |
import memoize from 'lru-memoize';
import {createValidator, required, maxLength} from './validation';
const personalDataValidation = createValidator({
firstname: [required, maxLength(20)],
surname: [required, maxLength(20)]
});
export default memoize(10)(personalDataValidation); | tgallin/accompagnerlautisme | app/js/validation/personalDataValidation.js | JavaScript | mit | 284 |
/**
* This class implements authentication against google
* using the client-side OAuth2 authorization flow in a popup window.
*/
import Oauth2Bearer from 'torii/providers/oauth2-bearer';
import {configurable} from 'torii/configuration';
var GoogleOauth2Bearer = Oauth2Bearer.extend({
name: 'google-oauth2-bearer',
baseUrl: 'https://accounts.google.com/o/oauth2/auth',
// additional params that this provider requires
optionalUrlParams: ['scope', 'request_visible_actions'],
requestVisibleActions: configurable('requestVisibleActions', ''),
responseParams: ['access_token'],
scope: configurable('scope', 'email'),
redirectUri: configurable('redirectUri',
'http://localhost:4200/oauth2callback')
});
export default GoogleOauth2Bearer;
| mwpastore/torii | addon/providers/google-oauth2-bearer.js | JavaScript | mit | 793 |
/* global describe, it, require */
'use strict';
// MODULES //
var // Expectation library:
chai = require( 'chai' ),
// Module to be tested:
ones = require( './../lib/matrix.js' );
// VARIABLES //
var expect = chai.expect,
assert = chai.assert;
// TESTS //
describe( 'ones-filled matrix', function tests() {
it( 'should export a function', function test() {
expect( ones ).to.be.a( 'function' );
});
it( 'should return a ones-filled matrix', function test() {
var actual, expected;
actual = ones( [2,2], 'int32' );
expected = new Int32Array( 4 );
for ( var i = 0; i < expected.length; i++ ) {
expected[ i ] = 1;
}
assert.deepEqual( actual.shape, [2,2] );
assert.strictEqual( actual.dtype, 'int32' );
assert.deepEqual( actual.data, expected );
});
});
| compute-io/ones | test/test.matrix.js | JavaScript | mit | 795 |
require('chai').should();
require('./basic');
| konsserto/konsserto | dist/node_modules/konsserto/node_modules/express.io/test/test.js | JavaScript | mit | 47 |
"use strict";
var MotionVector = require('./common/mv.js');
class mb_info {
constructor() {
//mv_base_info
this.base = {
y_mode: 0, //4;
uv_mode: 0, //4;
segment_id: 0, //2;
ref_frame: 0, //2;
skip_coeff: 0, //1;
need_mc_border: 0, //1;
partitioning: null, //2;'enum splitmv_partitioning'
mv: new MotionVector(),
eob_mask: 0
};
var mvs = new Array(16);
var i = 16;
while (i--)
mvs[i] = new MotionVector();
this.splitt =
{
mvs: mvs,
modes: new Uint8Array(16)//16,'todo:enum prediction_mode')
};
}
}
module.exports = mb_info;
| FlareMediaPlayer/FlareVPX | src/MacroblockInfo.js | JavaScript | mit | 794 |
/*
* Copyright (c) 2015-2016 PointSource, LLC.
* MIT Licensed
*/
var request = require('request'),
assert = require('assert'),
util = require('./launchUtil');
describe('SERVER1 - test simple REST calls', function () {
this.timeout(5000);
before(function (done) {
util.launch('server1', done);
});
after(function (done) {
util.finish(done);
});
it('GET /endpoint1', function (done) {
request('http://localhost:' + (process.env.PORT || 5000) + '/endpoint1', function(err, resp, body) {
assert.equal(null, err);
var json = JSON.parse(body);
assert.equal('endpoint1', json.name);
done();
});
});
it('POST /endpoint1', function (done) {
request.post('http://localhost:' + (process.env.PORT || 5000) + '/endpoint1', function(err, resp, body) {
assert.equal(null, err);
var json = JSON.parse(body);
assert.equal('endpoint1', json.name);
done();
});
});
it('PUT /endpoint1', function (done) {
request.put('http://localhost:' + (process.env.PORT || 5000) + '/endpoint1', function(err, resp, body) {
assert.equal(null, err);
var json = JSON.parse(body);
assert.equal('endpoint1', json.name);
done();
});
});
it('DELETE /endpoint1', function (done) {
request.del('http://localhost:' + (process.env.PORT || 5000) + '/endpoint1', function(err, resp, body) {
assert.equal(null, err);
var json = JSON.parse(body);
assert.equal('endpoint1', json.name);
done();
});
});
}); | BlueOakJS/blueoak-server | test/integration/testHandlers.js | JavaScript | mit | 1,699 |
'use strict';
var app = angular.module('myApp', [
'ngRoute'
]);
app.config(['$routeProvider', function ($routeProvider) {
$routeProvider
// Home
// Blog
.when("/", {templateUrl: "view/homepage.html", controller: "BlogCtrl"})
.when("/about", {templateUrl: "view/about.html", controller: "BlogCtrl"})
.when("/blog", {templateUrl: "view/blog.html", controller: "BlogCtrl"})
.when("/contact", {templateUrl: "view/contact.html", controller: "BlogCtrl"})
.when("/view1", {templateUrl: "view1/view1.html", controller: "BlogCtrl"})
.when("/view2", {templateUrl: "view2/view2.html", controller: "BlogCtrl"})
.when("/resume", {templateUrl: "view/resume.html", controller: "BlogCtrl"})
.when("/bootstrap1", {templateUrl: "view/bootstrap1.html", controller: "BlogCtrl"})
.when("/bootstrap2", {templateUrl: "view/bootstrap2.html", controller: "BlogCtrl"})
.when("/bootstrap3", {templateUrl: "view/bootstrap3.html", controller: "BlogCtrl"})
.otherwise("/404", {templateUrl: "view/resume.html", controller: "BlogCtrl"});
}]);
/**
* Controls the Blog
*/
app.controller('BlogCtrl', function (/* $scope, $location, $http */) {
console.log("Blog Controller reporting for duty.");
});
| smileybuddha/smileybuddha.github.io | app.js | JavaScript | mit | 1,199 |
import React, { Component } from 'react';
export default class About extends Component {
render() {
return (
<div>
Hey whats up
</div>
);
}
}
| rmwdeveloper/portfolio | src/containers/About/About.js | JavaScript | mit | 175 |
var mongoose = require('mongoose');
var requiredMessage = '{PATH} is required';
module.exports.init = function () {
var videosSchema = mongoose.Schema({
title: { type: String, index: true },
content: String,
dateCreated: {
type: Date,
default: Date.now
},
isDeleted: { type: Boolean, default: false },
hidden: { type: Boolean, default: false },
video: { data: Buffer, contentType: String, encoding: String },
});
videosSchema.methods.mapDTO = function (dto) {
this.video.data = Buffer.from(dto.video.base64Data[0]);
this.video.contentType = dto.video.contentType;
this.video.encoding = dto.video.encoding;
this.title = dto.title;
this.content = dto.content;
};
var Video = mongoose.model('Video', videosSchema)
};
| hpslavov/NodeGallery | server/data/models/Video.js | JavaScript | mit | 858 |
function createTextView(node, view) {
var result;
var isLine = node.spec.hints.some(function (hint) {
return hint === "line";
});
if (isLine) {
result = document.createElement("input");
if (node.spec.visibility === "concealed") {
result.type = "password";
}
if (node.spec.visibility === "concealed" || node.spec.visibility === "revealed") {
view.addEventListener("lynx-visibility-change", function () {
if (view.lynxGetVisibility() === "concealed") {
result.type = "password";
} else {
result.type = "text";
}
});
}
} else {
result = document.createElement("textarea");
}
return result;
}
export function textInputViewBuilder(node) {
var view = document.createElement("div");
var textView = createTextView(node, view);
textView.name = node.spec.input || "";
if (node.value === null || node.value === undefined) {
textView.value = "";
} else {
textView.value = node.value.toString();
}
view.appendChild(textView);
view.lynxGetValue = function () {
return textView.value;
};
view.lynxSetValue = function (val) {
if (textView.value === val) return;
textView.value = val;
raiseValueChangeEvent(textView);
};
view.lynxHasValue = function (val) {
return Promise.resolve(textView.value === val);
};
view.lynxClearValue = function () {
view.lynxSetValue("");
};
view.lynxGetFocusableView = function () {
return textView;
};
return view;
}
function raiseValueChangeEvent(view) {
var inputEvent = document.createEvent("Event");
inputEvent.initEvent("input", true, false);
view.dispatchEvent(inputEvent);
var changeEvent = document.createEvent("Event");
changeEvent.initEvent("change", true, false);
view.dispatchEvent(changeEvent);
}
| lynx-json/jsua-lynx | src/builders/text-input-view-builder.js | JavaScript | mit | 1,828 |
'use strict';
const gw2Api = require('../api');
const Worker = require('../../../../bot/modules/Worker');
class WorkerApiChecker extends Worker {
constructor(bot) {
super(bot, 'api-checker');
}
async check() {
try {
await gw2Api.build().get();
// API is working normally, hopefully
this.onFire(false);
} catch (err) {
if (!err.response || (err.response && err.response.status >= 400)) {
// API is on fire!
this.onFire(true);
}
}
}
onFire(fire) {
const module = this.getModule();
const wasOnFire = module.isApiOnFire();
if (wasOnFire !== fire) {
this.log(`API ${fire ? 'went on fire' : 'is back to normal'}`);
this.emit('on-fire', fire);
module.isApiOnFire(fire);
}
}
async enableWorker() {
this._intervalId = setInterval(this.check.bind(this), 300000);
setTimeout(this.check.bind(this), 1000);
}
async disableWorker() {
if (this._intervalId) {
clearInterval(this._intervalId);
}
}
}
module.exports = WorkerApiChecker;
| Archomeda/kormir-discord-bot | src/modules/guildwars2/workers/ApiChecker.js | JavaScript | mit | 1,203 |
function pipesGetPipeList(ctx, cbs){
var pipeList = {};
for(var pipeName in ctx._fp.pipe.prototype.namedPipes){
pipeList[pipeName] = ctx._fp.pipe.prototype.namedPipes[pipeName];
}
ctx._fp.util.setObjectValueByString(ctx, this.cfg.target, pipeList);
if(cbs && cbs.success){
cbs.success(ctx);
}
}
pipesGetPipeList.flux_pipe = {
name: 'Pipes : Get Pipe List',
description: 'Copies the current list of registered pipes to the target attribute',
configs:[
{
name: 'target',
description: 'Target Attribute'
}
]
};
module.exports = pipesGetPipeList; | chromecide/flux-pipes | lib/actions/pipes/getPipeList.js | JavaScript | mit | 647 |
export default {
sections: [
{
'title': 'Economist on iPhone',
'href': 'https://itunes.apple.com/us/app/economist-global-business/id951457811?ls=1&mt=8',
internal: false,
},
{
'title': 'Economist on iPad',
'href': 'https://search.itunes.apple.com/WebObjects/MZContentLink.woa/wa/link?path=apps%2ftheeconomist',
internal: false,
},
{
'title': 'Espresso',
'href': '/digital',
},
{
'title': 'Global Business Review',
'href': '/sections/business-finance',
},
{
'title': 'Work in Figures',
'href': 'https://worldinfigures.com/',
},
],
'media': [
{
'title': 'Apps',
'meta': 'apps',
'href': '/digital',
'internal': false,
'icon': {
'useBackground': true,
'color': 'chicago',
'icon': 'apps',
},
},
{
'title': 'Audio',
'meta': 'headset',
'href': '/audio-edition',
'internal': false,
'icon': {
'useBackground': true,
'color': 'chicago',
'icon': 'headset',
},
},
{
'title': 'Video',
'meta': 'video',
'href': 'http://www.economist.com/multimedia',
'internal': false,
'icon': {
'useBackground': true,
'color': 'chicago',
'icon': 'video',
},
},
{
'title': 'Radio',
'meta': 'radio',
'href': 'http://radio.economist.com/',
'internal': false,
'icon': {
'useBackground': true,
'color': 'chicago',
'icon': 'radio',
},
},
{
'title': 'Films',
'meta': 'film',
'href': 'http://films.economist.com/',
'internal': false,
'icon': {
'useBackground': true,
'color': 'chicago',
'icon': 'film',
},
},
],
'blogs': [
{
'title': 'Events',
'href': '/events-conferences',
},
{
'title': 'Jobs Board',
'href': 'http://jobs.economist.com/',
},
{
'title': 'Which MBA',
'href': '/whichmba',
},
{
'title': 'Executive Education Navigator',
'href': 'https://execed.economist.com/',
},
{
'title': 'GMAT tutor',
'href': 'https://gmat.economist.com/',
},
{
'title': 'GRE tutor',
'href': 'https://gre.economist.com/',
},
{
'title': 'Learning.ly',
'href': 'https://learning.ly',
internal: false,
},
{
'title': '1843',
'href': '/help/about-us',
},
],
};
| fabiosantoscode/component-navigation | test/more-balloon-data.js | JavaScript | mit | 2,535 |
/* global module */
'use strict';
var SpotifyWebApi = (function() {
var _baseUri = 'https://api.spotify.com/v1';
var _accessToken = null;
var _promiseImplementation = null;
var WrapPromiseWithAbort = function(promise, onAbort) {
promise.abort = onAbort;
return promise;
};
var _promiseProvider = function(promiseFunction, onAbort) {
var returnedPromise;
if (_promiseImplementation !== null) {
var deferred = _promiseImplementation.defer();
promiseFunction(function(resolvedResult) {
deferred.resolve(resolvedResult);
}, function(rejectedResult) {
deferred.reject(rejectedResult);
});
returnedPromise = deferred.promise;
} else {
if (window.Promise) {
returnedPromise = new window.Promise(promiseFunction);
}
}
if (returnedPromise) {
return new WrapPromiseWithAbort(returnedPromise, onAbort);
} else {
return null;
}
};
var _extend = function() {
var args = Array.prototype.slice.call(arguments);
var target = args[0];
var objects = args.slice(1);
target = target || {};
objects.forEach(function(object) {
for (var j in object) {
if (object.hasOwnProperty(j)) {
target[j] = object[j];
}
}
});
return target;
};
var _buildUrl = function(url, parameters) {
var qs = '';
for (var key in parameters) {
if (parameters.hasOwnProperty(key)) {
var value = parameters[key];
qs += encodeURIComponent(key) + '=' + encodeURIComponent(value) + '&';
}
}
if (qs.length > 0) {
// chop off last '&'
qs = qs.substring(0, qs.length - 1);
url = url + '?' + qs;
}
return url;
};
var _performRequest = function(requestData, callback) {
var req = new XMLHttpRequest();
var promiseFunction = function(resolve, reject) {
function success(data) {
if (resolve) {
resolve(data);
}
if (callback) {
callback(null, data);
}
}
function failure() {
if (reject) {
reject(req);
}
if (callback) {
callback(req, null);
}
}
var type = requestData.type || 'GET';
req.open(type, _buildUrl(requestData.url, requestData.params));
if (_accessToken) {
req.setRequestHeader('Authorization', 'Bearer ' + _accessToken);
}
req.onreadystatechange = function() {
if (req.readyState === 4) {
var data = null;
try {
data = req.responseText ? JSON.parse(req.responseText) : '';
} catch (e) {
console.error(e);
}
if (req.status >= 200 && req.status < 300) {
success(data);
} else {
failure();
}
}
};
if (type === 'GET') {
req.send(null);
} else {
req.send(requestData.postData ? JSON.stringify(requestData.postData) : null);
}
};
if (callback) {
promiseFunction();
return null;
} else {
return _promiseProvider(promiseFunction, function() {
req.abort();
});
}
};
var _checkParamsAndPerformRequest = function(requestData, options, callback, optionsAlwaysExtendParams) {
var opt = {};
var cb = null;
if (typeof options === 'object') {
opt = options;
cb = callback;
} else if (typeof options === 'function') {
cb = options;
}
// options extend postData, if any. Otherwise they extend parameters sent in the url
var type = requestData.type || 'GET';
if (type !== 'GET' && requestData.postData && !optionsAlwaysExtendParams) {
requestData.postData = _extend(requestData.postData, opt);
} else {
requestData.params = _extend(requestData.params, opt);
}
return _performRequest(requestData, cb);
};
var Constr = function() {};
Constr.prototype = {
constructor: SpotifyWebApi
};
/**
* Fetches a resource through a generic GET request.
*
* @param {string} url The URL to be fetched
* @param {function(Object,Object)} callback An optional callback
* @return {Object} Null if a callback is provided, a `Promise` object otherwise
*/
Constr.prototype.getGeneric = function(url, callback) {
var requestData = {
url: url
};
return _checkParamsAndPerformRequest(requestData, callback);
};
/**
* Fetches information about the current user.
* See [Get Current User's Profile](https://developer.spotify.com/web-api/get-current-users-profile/) on
* the Spotify Developer site for more information about the endpoint.
*
* @param {Object} options A JSON object with options that can be passed
* @param {function(Object,Object)} callback An optional callback that receives 2 parameters. The first
* one is the error object (null if no error), and the second is the value if the request succeeded.
* @return {Object} Null if a callback is provided, a `Promise` object otherwise
*/
Constr.prototype.getMe = function(options, callback) {
var requestData = {
url: _baseUri + '/me'
};
return _checkParamsAndPerformRequest(requestData, options, callback);
};
/**
* Fetches current user's saved tracks.
* See [Get Current User's Saved Tracks](https://developer.spotify.com/web-api/get-users-saved-tracks/) on
* the Spotify Developer site for more information about the endpoint.
*
* @param {Object} options A JSON object with options that can be passed
* @param {function(Object,Object)} callback An optional callback that receives 2 parameters. The first
* one is the error object (null if no error), and the second is the value if the request succeeded.
* @return {Object} Null if a callback is provided, a `Promise` object otherwise
*/
Constr.prototype.getMySavedTracks = function(options, callback) {
var requestData = {
url: _baseUri + '/me/tracks'
};
return _checkParamsAndPerformRequest(requestData, options, callback);
};
/**
* Adds a list of tracks to the current user's saved tracks.
* See [Save Tracks for Current User](https://developer.spotify.com/web-api/save-tracks-user/) on
* the Spotify Developer site for more information about the endpoint.
*
* @param {Array<string>} trackIds The ids of the tracks. If you know their Spotify URI it is easy
* to find their track id (e.g. spotify:track:<here_is_the_track_id>)
* @param {Object} options A JSON object with options that can be passed
* @param {function(Object,Object)} callback An optional callback that receives 2 parameters. The first
* one is the error object (null if no error), and the second is the value if the request succeeded.
* @return {Object} Null if a callback is provided, a `Promise` object otherwise
*/
Constr.prototype.addToMySavedTracks = function(trackIds, options, callback) {
var requestData = {
url: _baseUri + '/me/tracks',
type: 'PUT',
postData: trackIds
};
return _checkParamsAndPerformRequest(requestData, options, callback);
};
/**
* Remove a list of tracks from the current user's saved tracks.
* See [Remove Tracks for Current User](https://developer.spotify.com/web-api/remove-tracks-user/) on
* the Spotify Developer site for more information about the endpoint.
*
* @param {Array<string>} trackIds The ids of the tracks. If you know their Spotify URI it is easy
* to find their track id (e.g. spotify:track:<here_is_the_track_id>)
* @param {Object} options A JSON object with options that can be passed
* @param {function(Object,Object)} callback An optional callback that receives 2 parameters. The first
* one is the error object (null if no error), and the second is the value if the request succeeded.
* @return {Object} Null if a callback is provided, a `Promise` object otherwise
*/
Constr.prototype.removeFromMySavedTracks = function(trackIds, options, callback) {
var requestData = {
url: _baseUri + '/me/tracks',
type: 'DELETE',
postData: trackIds
};
return _checkParamsAndPerformRequest(requestData, options, callback);
};
/**
* Checks if the current user's saved tracks contains a certain list of tracks.
* See [Check Current User's Saved Tracks](https://developer.spotify.com/web-api/check-users-saved-tracks/) on
* the Spotify Developer site for more information about the endpoint.
*
* @param {Array<string>} trackIds The ids of the tracks. If you know their Spotify URI it is easy
* to find their track id (e.g. spotify:track:<here_is_the_track_id>)
* @param {Object} options A JSON object with options that can be passed
* @param {function(Object,Object)} callback An optional callback that receives 2 parameters. The first
* one is the error object (null if no error), and the second is the value if the request succeeded.
* @return {Object} Null if a callback is provided, a `Promise` object otherwise
*/
Constr.prototype.containsMySavedTracks = function(trackIds, options, callback) {
var requestData = {
url: _baseUri + '/me/tracks/contains',
params: { ids: trackIds.join(',') }
};
return _checkParamsAndPerformRequest(requestData, options, callback);
};
/**
* Get a list of the albums saved in the current Spotify user's "Your Music" library.
* See [Get Current User's Saved Albums](https://developer.spotify.com/web-api/get-users-saved-albums/) on
* the Spotify Developer site for more information about the endpoint.
*
* @param {Object} options A JSON object with options that can be passed
* @param {function(Object,Object)} callback An optional callback that receives 2 parameters. The first
* one is the error object (null if no error), and the second is the value if the request succeeded.
* @return {Object} Null if a callback is provided, a `Promise` object otherwise
*/
Constr.prototype.getMySavedAlbums = function(options, callback) {
var requestData = {
url: _baseUri + '/me/albums'
};
return _checkParamsAndPerformRequest(requestData, options, callback);
};
/**
* Save one or more albums to the current user's "Your Music" library.
* See [Save Albums for Current User](https://developer.spotify.com/web-api/save-albums-user/) on
* the Spotify Developer site for more information about the endpoint.
*
* @param {Array<string>} albumIds The ids of the albums. If you know their Spotify URI, it is easy
* to find their album id (e.g. spotify:album:<here_is_the_album_id>)
* @param {Object} options A JSON object with options that can be passed
* @param {function(Object,Object)} callback An optional callback that receives 2 parameters. The first
* one is the error object (null if no error), and the second is the value if the request succeeded.
* @return {Object} Null if a callback is provided, a `Promise` object otherwise
*/
Constr.prototype.addToMySavedAlbums = function(albumIds, options, callback) {
var requestData = {
url: _baseUri + '/me/albums',
type: 'PUT',
postData: albumIds
};
return _checkParamsAndPerformRequest(requestData, options, callback);
};
/**
* Remove one or more albums from the current user's "Your Music" library.
* See [Remove Albums for Current User](https://developer.spotify.com/web-api/remove-albums-user/) on
* the Spotify Developer site for more information about the endpoint.
*
* @param {Array<string>} albumIds The ids of the albums. If you know their Spotify URI, it is easy
* to find their album id (e.g. spotify:album:<here_is_the_album_id>)
* @param {Object} options A JSON object with options that can be passed
* @param {function(Object,Object)} callback An optional callback that receives 2 parameters. The first
* one is the error object (null if no error), and the second is the value if the request succeeded.
* @return {Object} Null if a callback is provided, a `Promise` object otherwise
*/
Constr.prototype.removeFromMySavedAlbums = function(albumIds, options, callback) {
var requestData = {
url: _baseUri + '/me/albums',
type: 'DELETE',
postData: albumIds
};
return _checkParamsAndPerformRequest(requestData, options, callback);
};
/**
* Check if one or more albums is already saved in the current Spotify user's "Your Music" library.
* See [Check User's Saved Albums](https://developer.spotify.com/web-api/check-users-saved-albums/) on
* the Spotify Developer site for more information about the endpoint.
*
* @param {Array<string>} albumIds The ids of the albums. If you know their Spotify URI, it is easy
* to find their album id (e.g. spotify:album:<here_is_the_album_id>)
* @param {Object} options A JSON object with options that can be passed
* @param {function(Object,Object)} callback An optional callback that receives 2 parameters. The first
* one is the error object (null if no error), and the second is the value if the request succeeded.
* @return {Object} Null if a callback is provided, a `Promise` object otherwise
*/
Constr.prototype.containsMySavedAlbums = function(albumIds, options, callback) {
var requestData = {
url: _baseUri + '/me/albums/contains',
params: { ids: albumIds.join(',') }
};
return _checkParamsAndPerformRequest(requestData, options, callback);
};
/**
* Get the current user’s top artists based on calculated affinity.
* See [Get a User’s Top Artists](https://developer.spotify.com/web-api/get-users-top-artists-and-tracks/) on
* the Spotify Developer site for more information about the endpoint.
*
* @param {Object} options A JSON object with options that can be passed
* @param {function(Object,Object)} callback An optional callback that receives 2 parameters. The first
* one is the error object (null if no error), and the second is the value if the request succeeded.
* @return {Object} Null if a callback is provided, a `Promise` object otherwise
*/
Constr.prototype.getMyTopArtists = function(options, callback) {
var requestData = {
url: _baseUri + '/me/top/artists'
};
return _checkParamsAndPerformRequest(requestData, options, callback);
};
/**
* Get the current user’s top tracks based on calculated affinity.
* See [Get a User’s Top Tracks](https://developer.spotify.com/web-api/get-users-top-artists-and-tracks/) on
* the Spotify Developer site for more information about the endpoint.
*
* @param {Object} options A JSON object with options that can be passed
* @param {function(Object,Object)} callback An optional callback that receives 2 parameters. The first
* one is the error object (null if no error), and the second is the value if the request succeeded.
* @return {Object} Null if a callback is provided, a `Promise` object otherwise
*/
Constr.prototype.getMyTopTracks = function(options, callback) {
var requestData = {
url: _baseUri + '/me/top/tracks'
};
return _checkParamsAndPerformRequest(requestData, options, callback);
};
/**
* Get tracks from the current user’s recently played tracks.
* See [Get Current User’s Recently Played Tracks](https://developer.spotify.com/web-api/web-api-personalization-endpoints/get-recently-played/) on
* the Spotify Developer site for more information about the endpoint.
*
* @param {Object} options A JSON object with options that can be passed
* @param {function(Object,Object)} callback An optional callback that receives 2 parameters. The first
* one is the error object (null if no error), and the second is the value if the request succeeded.
* @return {Object} Null if a callback is provided, a `Promise` object otherwise
*/
Constr.prototype.getMyRecentlyPlayedTracks = function(options, callback) {
var requestData = {
url: _baseUri + '/me/player/recently-played'
};
return _checkParamsAndPerformRequest(requestData, options, callback);
};
/**
* Adds the current user as a follower of one or more other Spotify users.
* See [Follow Artists or Users](https://developer.spotify.com/web-api/follow-artists-users/) on
* the Spotify Developer site for more information about the endpoint.
*
* @param {Array<string>} userIds The ids of the users. If you know their Spotify URI it is easy
* to find their user id (e.g. spotify:user:<here_is_the_user_id>)
* @param {function(Object,Object)} callback An optional callback that receives 2 parameters. The first
* one is the error object (null if no error), and the second is an empty value if the request succeeded.
* @return {Object} Null if a callback is provided, a `Promise` object otherwise
*/
Constr.prototype.followUsers = function(userIds, callback) {
var requestData = {
url: _baseUri + '/me/following/',
type: 'PUT',
params: {
ids: userIds.join(','),
type: 'user'
}
};
return _checkParamsAndPerformRequest(requestData, callback);
};
/**
* Adds the current user as a follower of one or more artists.
* See [Follow Artists or Users](https://developer.spotify.com/web-api/follow-artists-users/) on
* the Spotify Developer site for more information about the endpoint.
*
* @param {Array<string>} artistIds The ids of the artists. If you know their Spotify URI it is easy
* to find their artist id (e.g. spotify:artist:<here_is_the_artist_id>)
* @param {function(Object,Object)} callback An optional callback that receives 2 parameters. The first
* one is the error object (null if no error), and the second is an empty value if the request succeeded.
* @return {Object} Null if a callback is provided, a `Promise` object otherwise
*/
Constr.prototype.followArtists = function(artistIds, callback) {
var requestData = {
url: _baseUri + '/me/following/',
type: 'PUT',
params: {
ids: artistIds.join(','),
type: 'artist'
}
};
return _checkParamsAndPerformRequest(requestData, callback);
};
/**
* Add the current user as a follower of one playlist.
* See [Follow a Playlist](https://developer.spotify.com/web-api/follow-playlist/) on
* the Spotify Developer site for more information about the endpoint.
*
* @param {string} ownerId The id of the playlist owner. If you know the Spotify URI of
* the playlist, it is easy to find the owner's user id
* (e.g. spotify:user:<here_is_the_owner_id>:playlist:xxxx)
* @param {string} playlistId The id of the playlist. If you know the Spotify URI it is easy
* to find the playlist id (e.g. spotify:user:xxxx:playlist:<here_is_the_playlist_id>)
* @param {Object} options A JSON object with options that can be passed. For instance,
* whether you want the playlist to be followed privately ({public: false})
* @param {function(Object,Object)} callback An optional callback that receives 2 parameters. The first
* one is the error object (null if no error), and the second is an empty value if the request succeeded.
* @return {Object} Null if a callback is provided, a `Promise` object otherwise
*/
Constr.prototype.followPlaylist = function(ownerId, playlistId, options, callback) {
var requestData = {
url: _baseUri + '/users/' + encodeURIComponent(ownerId) + '/playlists/' + playlistId + '/followers',
type: 'PUT',
postData: {}
};
return _checkParamsAndPerformRequest(requestData, options, callback);
};
/**
* Removes the current user as a follower of one or more other Spotify users.
* See [Unfollow Artists or Users](https://developer.spotify.com/web-api/unfollow-artists-users/) on
* the Spotify Developer site for more information about the endpoint.
*
* @param {Array<string>} userIds The ids of the users. If you know their Spotify URI it is easy
* to find their user id (e.g. spotify:user:<here_is_the_user_id>)
* @param {function(Object,Object)} callback An optional callback that receives 2 parameters. The first
* one is the error object (null if no error), and the second is an empty value if the request succeeded.
* @return {Object} Null if a callback is provided, a `Promise` object otherwise
*/
Constr.prototype.unfollowUsers = function(userIds, callback) {
var requestData = {
url: _baseUri + '/me/following/',
type: 'DELETE',
params: {
ids: userIds.join(','),
type: 'user'
}
};
return _checkParamsAndPerformRequest(requestData, callback);
};
/**
* Removes the current user as a follower of one or more artists.
* See [Unfollow Artists or Users](https://developer.spotify.com/web-api/unfollow-artists-users/) on
* the Spotify Developer site for more information about the endpoint.
*
* @param {Array<string>} artistIds The ids of the artists. If you know their Spotify URI it is easy
* to find their artist id (e.g. spotify:artist:<here_is_the_artist_id>)
* @param {function(Object,Object)} callback An optional callback that receives 2 parameters. The first
* one is the error object (null if no error), and the second is an empty value if the request succeeded.
* @return {Object} Null if a callback is provided, a `Promise` object otherwise
*/
Constr.prototype.unfollowArtists = function(artistIds, callback) {
var requestData = {
url: _baseUri + '/me/following/',
type: 'DELETE',
params: {
ids: artistIds.join(','),
type: 'artist'
}
};
return _checkParamsAndPerformRequest(requestData, callback);
};
/**
* Remove the current user as a follower of one playlist.
* See [Unfollow a Playlist](https://developer.spotify.com/web-api/unfollow-playlist/) on
* the Spotify Developer site for more information about the endpoint.
*
* @param {string} ownerId The id of the playlist owner. If you know the Spotify URI of
* the playlist, it is easy to find the owner's user id
* (e.g. spotify:user:<here_is_the_owner_id>:playlist:xxxx)
* @param {string} playlistId The id of the playlist. If you know the Spotify URI it is easy
* to find the playlist id (e.g. spotify:user:xxxx:playlist:<here_is_the_playlist_id>)
* @param {function(Object,Object)} callback An optional callback that receives 2 parameters. The first
* one is the error object (null if no error), and the second is an empty value if the request succeeded.
* @return {Object} Null if a callback is provided, a `Promise` object otherwise
*/
Constr.prototype.unfollowPlaylist = function(ownerId, playlistId, callback) {
var requestData = {
url: _baseUri + '/users/' + encodeURIComponent(ownerId) + '/playlists/' + playlistId + '/followers',
type: 'DELETE'
};
return _checkParamsAndPerformRequest(requestData, callback);
};
/**
* Checks to see if the current user is following one or more other Spotify users.
* See [Check if Current User Follows Users or Artists](https://developer.spotify.com/web-api/check-current-user-follows/) on
* the Spotify Developer site for more information about the endpoint.
*
* @param {Array<string>} userIds The ids of the users. If you know their Spotify URI it is easy
* to find their user id (e.g. spotify:user:<here_is_the_user_id>)
* @param {function(Object,Object)} callback An optional callback that receives 2 parameters. The first
* one is the error object (null if no error), and the second is an array of boolean values that indicate
* whether the user is following the users sent in the request.
* @return {Object} Null if a callback is provided, a `Promise` object otherwise
*/
Constr.prototype.isFollowingUsers = function(userIds, callback) {
var requestData = {
url: _baseUri + '/me/following/contains',
type: 'GET',
params: {
ids: userIds.join(','),
type: 'user'
}
};
return _checkParamsAndPerformRequest(requestData, callback);
};
/**
* Checks to see if the current user is following one or more artists.
* See [Check if Current User Follows](https://developer.spotify.com/web-api/check-current-user-follows/) on
* the Spotify Developer site for more information about the endpoint.
*
* @param {Array<string>} artistIds The ids of the artists. If you know their Spotify URI it is easy
* to find their artist id (e.g. spotify:artist:<here_is_the_artist_id>)
* @param {function(Object,Object)} callback An optional callback that receives 2 parameters. The first
* one is the error object (null if no error), and the second is an array of boolean values that indicate
* whether the user is following the artists sent in the request.
* @return {Object} Null if a callback is provided, a `Promise` object otherwise
*/
Constr.prototype.isFollowingArtists = function(artistIds, callback) {
var requestData = {
url: _baseUri + '/me/following/contains',
type: 'GET',
params: {
ids: artistIds.join(','),
type: 'artist'
}
};
return _checkParamsAndPerformRequest(requestData, callback);
};
/**
* Check to see if one or more Spotify users are following a specified playlist.
* See [Check if Users Follow a Playlist](https://developer.spotify.com/web-api/check-user-following-playlist/) on
* the Spotify Developer site for more information about the endpoint.
*
* @param {string} ownerId The id of the playlist owner. If you know the Spotify URI of
* the playlist, it is easy to find the owner's user id
* (e.g. spotify:user:<here_is_the_owner_id>:playlist:xxxx)
* @param {string} playlistId The id of the playlist. If you know the Spotify URI it is easy
* to find the playlist id (e.g. spotify:user:xxxx:playlist:<here_is_the_playlist_id>)
* @param {Array<string>} userIds The ids of the users. If you know their Spotify URI it is easy
* to find their user id (e.g. spotify:user:<here_is_the_user_id>)
* @param {function(Object,Object)} callback An optional callback that receives 2 parameters. The first
* one is the error object (null if no error), and the second is an array of boolean values that indicate
* whether the users are following the playlist sent in the request.
* @return {Object} Null if a callback is provided, a `Promise` object otherwise
*/
Constr.prototype.areFollowingPlaylist = function(ownerId, playlistId, userIds, callback) {
var requestData = {
url: _baseUri + '/users/' + encodeURIComponent(ownerId) + '/playlists/' + playlistId + '/followers/contains',
type: 'GET',
params: {
ids: userIds.join(',')
}
};
return _checkParamsAndPerformRequest(requestData, callback);
};
/**
* Get the current user's followed artists.
* See [Get User's Followed Artists](https://developer.spotify.com/web-api/get-followed-artists/) on
* the Spotify Developer site for more information about the endpoint.
*
* @param {Object} [options] Options, being after and limit.
* @param {function(Object,Object)} callback An optional callback that receives 2 parameters. The first
* one is the error object (null if no error), and the second is an object with a paged object containing
* artists.
* @returns {Promise|undefined} A promise that if successful, resolves to an object containing a paging object which contains
* artists objects. Not returned if a callback is given.
*/
Constr.prototype.getFollowedArtists = function(options, callback) {
var requestData = {
url: _baseUri + '/me/following',
type: 'GET',
params: {
type: 'artist'
}
};
return _checkParamsAndPerformRequest(requestData, options, callback);
};
/**
* Fetches information about a specific user.
* See [Get a User's Profile](https://developer.spotify.com/web-api/get-users-profile/) on
* the Spotify Developer site for more information about the endpoint.
*
* @param {string} userId The id of the user. If you know the Spotify URI it is easy
* to find the id (e.g. spotify:user:<here_is_the_id>)
* @param {Object} options A JSON object with options that can be passed
* @param {function(Object,Object)} callback An optional callback that receives 2 parameters. The first
* one is the error object (null if no error), and the second is the value if the request succeeded.
* @return {Object} Null if a callback is provided, a `Promise` object otherwise
*/
Constr.prototype.getUser = function(userId, options, callback) {
var requestData = {
url: _baseUri + '/users/' + encodeURIComponent(userId)
};
return _checkParamsAndPerformRequest(requestData, options, callback);
};
/**
* Fetches a list of the current user's playlists.
* See [Get a List of a User's Playlists](https://developer.spotify.com/web-api/get-list-users-playlists/) on
* the Spotify Developer site for more information about the endpoint.
*
* @param {string} userId An optional id of the user. If you know the Spotify URI it is easy
* to find the id (e.g. spotify:user:<here_is_the_id>). If not provided, the id of the user that granted
* the permissions will be used.
* @param {Object} options A JSON object with options that can be passed
* @param {function(Object,Object)} callback An optional callback that receives 2 parameters. The first
* one is the error object (null if no error), and the second is the value if the request succeeded.
* @return {Object} Null if a callback is provided, a `Promise` object otherwise
*/
Constr.prototype.getUserPlaylists = function(userId, options, callback) {
var requestData;
if (typeof userId === 'string') {
requestData = {
url: _baseUri + '/users/' + encodeURIComponent(userId) + '/playlists'
};
} else {
requestData = {
url: _baseUri + '/me/playlists'
};
callback = options;
options = userId;
}
return _checkParamsAndPerformRequest(requestData, options, callback);
};
/**
* Fetches a specific playlist.
* See [Get a Playlist](https://developer.spotify.com/web-api/get-playlist/) on
* the Spotify Developer site for more information about the endpoint.
*
* @param {string} userId The id of the user. If you know the Spotify URI it is easy
* to find the user id (e.g. spotify:user:<here_is_the_user_id>:playlist:xxxx)
* @param {string} playlistId The id of the playlist. If you know the Spotify URI it is easy
* to find the playlist id (e.g. spotify:user:xxxx:playlist:<here_is_the_playlist_id>)
* @param {Object} options A JSON object with options that can be passed
* @param {function(Object,Object)} callback An optional callback that receives 2 parameters. The first
* one is the error object (null if no error), and the second is the value if the request succeeded.
* @return {Object} Null if a callback is provided, a `Promise` object otherwise
*/
Constr.prototype.getPlaylist = function(userId, playlistId, options, callback) {
var requestData = {
url: _baseUri + '/users/' + encodeURIComponent(userId) + '/playlists/' + playlistId
};
return _checkParamsAndPerformRequest(requestData, options, callback);
};
/**
* Fetches the tracks from a specific playlist.
* See [Get a Playlist's Tracks](https://developer.spotify.com/web-api/get-playlists-tracks/) on
* the Spotify Developer site for more information about the endpoint.
*
* @param {string} userId The id of the user. If you know the Spotify URI it is easy
* to find the user id (e.g. spotify:user:<here_is_the_user_id>:playlist:xxxx)
* @param {string} playlistId The id of the playlist. If you know the Spotify URI it is easy
* to find the playlist id (e.g. spotify:user:xxxx:playlist:<here_is_the_playlist_id>)
* @param {Object} options A JSON object with options that can be passed
* @param {function(Object,Object)} callback An optional callback that receives 2 parameters. The first
* one is the error object (null if no error), and the second is the value if the request succeeded.
* @return {Object} Null if a callback is provided, a `Promise` object otherwise
*/
Constr.prototype.getPlaylistTracks = function(userId, playlistId, options, callback) {
var requestData = {
url: _baseUri + '/users/' + encodeURIComponent(userId) + '/playlists/' + playlistId + '/tracks'
};
return _checkParamsAndPerformRequest(requestData, options, callback);
};
/**
* Creates a playlist and stores it in the current user's library.
* See [Create a Playlist](https://developer.spotify.com/web-api/create-playlist/) on
* the Spotify Developer site for more information about the endpoint.
*
* @param {string} userId The id of the user. You may want to user the "getMe" function to
* find out the id of the current logged in user
* @param {Object} options A JSON object with options that can be passed
* @param {function(Object,Object)} callback An optional callback that receives 2 parameters. The first
* one is the error object (null if no error), and the second is the value if the request succeeded.
* @return {Object} Null if a callback is provided, a `Promise` object otherwise
*/
Constr.prototype.createPlaylist = function(userId, options, callback) {
var requestData = {
url: _baseUri + '/users/' + encodeURIComponent(userId) + '/playlists',
type: 'POST',
postData: options
};
return _checkParamsAndPerformRequest(requestData, options, callback);
};
/**
* Change a playlist's name and public/private state
* See [Change a Playlist's Details](https://developer.spotify.com/web-api/change-playlist-details/) on
* the Spotify Developer site for more information about the endpoint.
*
* @param {string} userId The id of the user. You may want to user the "getMe" function to
* find out the id of the current logged in user
* @param {string} playlistId The id of the playlist. If you know the Spotify URI it is easy
* to find the playlist id (e.g. spotify:user:xxxx:playlist:<here_is_the_playlist_id>)
* @param {Object} data A JSON object with the data to update. E.g. {name: 'A new name', public: true}
* @param {function(Object,Object)} callback An optional callback that receives 2 parameters. The first
* one is the error object (null if no error), and the second is the value if the request succeeded.
* @return {Object} Null if a callback is provided, a `Promise` object otherwise
*/
Constr.prototype.changePlaylistDetails = function(userId, playlistId, data, callback) {
var requestData = {
url: _baseUri + '/users/' + encodeURIComponent(userId) + '/playlists/' + playlistId,
type: 'PUT',
postData: data
};
return _checkParamsAndPerformRequest(requestData, data, callback);
};
/**
* Add tracks to a playlist.
* See [Add Tracks to a Playlist](https://developer.spotify.com/web-api/add-tracks-to-playlist/) on
* the Spotify Developer site for more information about the endpoint.
*
* @param {string} userId The id of the user. If you know the Spotify URI it is easy
* to find the user id (e.g. spotify:user:<here_is_the_user_id>:playlist:xxxx)
* @param {string} playlistId The id of the playlist. If you know the Spotify URI it is easy
* to find the playlist id (e.g. spotify:user:xxxx:playlist:<here_is_the_playlist_id>)
* @param {Array<string>} uris An array of Spotify URIs for the tracks
* @param {Object} options A JSON object with options that can be passed
* @param {function(Object,Object)} callback An optional callback that receives 2 parameters. The first
* one is the error object (null if no error), and the second is the value if the request succeeded.
* @return {Object} Null if a callback is provided, a `Promise` object otherwise
*/
Constr.prototype.addTracksToPlaylist = function(userId, playlistId, uris, options, callback) {
var requestData = {
url: _baseUri + '/users/' + encodeURIComponent(userId) + '/playlists/' + playlistId + '/tracks',
type: 'POST',
postData: {
uris: uris
}
};
return _checkParamsAndPerformRequest(requestData, options, callback, true);
};
/**
* Replace the tracks of a playlist
* See [Replace a Playlist's Tracks](https://developer.spotify.com/web-api/replace-playlists-tracks/) on
* the Spotify Developer site for more information about the endpoint.
*
* @param {string} userId The id of the user. If you know the Spotify URI it is easy
* to find the user id (e.g. spotify:user:<here_is_the_user_id>:playlist:xxxx)
* @param {string} playlistId The id of the playlist. If you know the Spotify URI it is easy
* to find the playlist id (e.g. spotify:user:xxxx:playlist:<here_is_the_playlist_id>)
* @param {Array<string>} uris An array of Spotify URIs for the tracks
* @param {function(Object,Object)} callback An optional callback that receives 2 parameters. The first
* one is the error object (null if no error), and the second is the value if the request succeeded.
* @return {Object} Null if a callback is provided, a `Promise` object otherwise
*/
Constr.prototype.replaceTracksInPlaylist = function(userId, playlistId, uris, callback) {
var requestData = {
url: _baseUri + '/users/' + encodeURIComponent(userId) + '/playlists/' + playlistId + '/tracks',
type: 'PUT',
postData: {uris: uris}
};
return _checkParamsAndPerformRequest(requestData, {}, callback);
};
/**
* Reorder tracks in a playlist
* See [Reorder a Playlist’s Tracks](https://developer.spotify.com/web-api/reorder-playlists-tracks/) on
* the Spotify Developer site for more information about the endpoint.
*
* @param {string} userId The id of the user. If you know the Spotify URI it is easy
* to find the user id (e.g. spotify:user:<here_is_the_user_id>:playlist:xxxx)
* @param {string} playlistId The id of the playlist. If you know the Spotify URI it is easy
* to find the playlist id (e.g. spotify:user:xxxx:playlist:<here_is_the_playlist_id>)
* @param {number} rangeStart The position of the first track to be reordered.
* @param {number} insertBefore The position where the tracks should be inserted. To reorder the tracks to
* the end of the playlist, simply set insert_before to the position after the last track.
* @param {Object} options An object with optional parameters (range_length, snapshot_id)
* @param {function(Object,Object)} callback An optional callback that receives 2 parameters. The first
* one is the error object (null if no error), and the second is the value if the request succeeded.
* @return {Object} Null if a callback is provided, a `Promise` object otherwise
*/
Constr.prototype.reorderTracksInPlaylist = function(userId, playlistId, rangeStart, insertBefore, options, callback) {
/* eslint-disable camelcase */
var requestData = {
url: _baseUri + '/users/' + encodeURIComponent(userId) + '/playlists/' + playlistId + '/tracks',
type: 'PUT',
postData: {
range_start: rangeStart,
insert_before: insertBefore
}
};
/* eslint-enable camelcase */
return _checkParamsAndPerformRequest(requestData, options, callback);
};
/**
* Remove tracks from a playlist
* See [Remove Tracks from a Playlist](https://developer.spotify.com/web-api/remove-tracks-playlist/) on
* the Spotify Developer site for more information about the endpoint.
*
* @param {string} userId The id of the user. If you know the Spotify URI it is easy
* to find the user id (e.g. spotify:user:<here_is_the_user_id>:playlist:xxxx)
* @param {string} playlistId The id of the playlist. If you know the Spotify URI it is easy
* to find the playlist id (e.g. spotify:user:xxxx:playlist:<here_is_the_playlist_id>)
* @param {Array<Object>} uris An array of tracks to be removed. Each element of the array can be either a
* string, in which case it is treated as a URI, or an object containing the properties `uri` (which is a
* string) and `positions` (which is an array of integers).
* @param {function(Object,Object)} callback An optional callback that receives 2 parameters. The first
* one is the error object (null if no error), and the second is the value if the request succeeded.
* @return {Object} Null if a callback is provided, a `Promise` object otherwise
*/
Constr.prototype.removeTracksFromPlaylist = function(userId, playlistId, uris, callback) {
var dataToBeSent = uris.map(function(uri) {
if (typeof uri === 'string') {
return { uri: uri };
} else {
return uri;
}
});
var requestData = {
url: _baseUri + '/users/' + encodeURIComponent(userId) + '/playlists/' + playlistId + '/tracks',
type: 'DELETE',
postData: {tracks: dataToBeSent}
};
return _checkParamsAndPerformRequest(requestData, {}, callback);
};
/**
* Remove tracks from a playlist, specifying a snapshot id.
* See [Remove Tracks from a Playlist](https://developer.spotify.com/web-api/remove-tracks-playlist/) on
* the Spotify Developer site for more information about the endpoint.
*
* @param {string} userId The id of the user. If you know the Spotify URI it is easy
* to find the user id (e.g. spotify:user:<here_is_the_user_id>:playlist:xxxx)
* @param {string} playlistId The id of the playlist. If you know the Spotify URI it is easy
* to find the playlist id (e.g. spotify:user:xxxx:playlist:<here_is_the_playlist_id>)
* @param {Array<Object>} uris An array of tracks to be removed. Each element of the array can be either a
* string, in which case it is treated as a URI, or an object containing the properties `uri` (which is a
* string) and `positions` (which is an array of integers).
* @param {string} snapshotId The playlist's snapshot ID against which you want to make the changes
* @param {function(Object,Object)} callback An optional callback that receives 2 parameters. The first
* one is the error object (null if no error), and the second is the value if the request succeeded.
* @return {Object} Null if a callback is provided, a `Promise` object otherwise
*/
Constr.prototype.removeTracksFromPlaylistWithSnapshotId = function(userId, playlistId, uris, snapshotId, callback) {
var dataToBeSent = uris.map(function(uri) {
if (typeof uri === 'string') {
return { uri: uri };
} else {
return uri;
}
});
/* eslint-disable camelcase */
var requestData = {
url: _baseUri + '/users/' + encodeURIComponent(userId) + '/playlists/' + playlistId + '/tracks',
type: 'DELETE',
postData: {
tracks: dataToBeSent,
snapshot_id: snapshotId
}
};
/* eslint-enable camelcase */
return _checkParamsAndPerformRequest(requestData, {}, callback);
};
/**
* Remove tracks from a playlist, specifying the positions of the tracks to be removed.
* See [Remove Tracks from a Playlist](https://developer.spotify.com/web-api/remove-tracks-playlist/) on
* the Spotify Developer site for more information about the endpoint.
*
* @param {string} userId The id of the user. If you know the Spotify URI it is easy
* to find the user id (e.g. spotify:user:<here_is_the_user_id>:playlist:xxxx)
* @param {string} playlistId The id of the playlist. If you know the Spotify URI it is easy
* to find the playlist id (e.g. spotify:user:xxxx:playlist:<here_is_the_playlist_id>)
* @param {Array<number>} positions array of integers containing the positions of the tracks to remove
* from the playlist.
* @param {string} snapshotId The playlist's snapshot ID against which you want to make the changes
* @param {function(Object,Object)} callback An optional callback that receives 2 parameters. The first
* one is the error object (null if no error), and the second is the value if the request succeeded.
* @return {Object} Null if a callback is provided, a `Promise` object otherwise
*/
Constr.prototype.removeTracksFromPlaylistInPositions = function(userId, playlistId, positions, snapshotId, callback) {
/* eslint-disable camelcase */
var requestData = {
url: _baseUri + '/users/' + encodeURIComponent(userId) + '/playlists/' + playlistId + '/tracks',
type: 'DELETE',
postData: {
positions: positions,
snapshot_id: snapshotId
}
};
/* eslint-enable camelcase */
return _checkParamsAndPerformRequest(requestData, {}, callback);
};
/**
* Fetches an album from the Spotify catalog.
* See [Get an Album](https://developer.spotify.com/web-api/get-album/) on
* the Spotify Developer site for more information about the endpoint.
*
* @param {string} albumId The id of the album. If you know the Spotify URI it is easy
* to find the album id (e.g. spotify:album:<here_is_the_album_id>)
* @param {Object} options A JSON object with options that can be passed
* @param {function(Object,Object)} callback An optional callback that receives 2 parameters. The first
* one is the error object (null if no error), and the second is the value if the request succeeded.
* @return {Object} Null if a callback is provided, a `Promise` object otherwise
*/
Constr.prototype.getAlbum = function(albumId, options, callback) {
var requestData = {
url: _baseUri + '/albums/' + albumId
};
return _checkParamsAndPerformRequest(requestData, options, callback);
};
/**
* Fetches the tracks of an album from the Spotify catalog.
* See [Get an Album's Tracks](https://developer.spotify.com/web-api/get-albums-tracks/) on
* the Spotify Developer site for more information about the endpoint.
*
* @param {string} albumId The id of the album. If you know the Spotify URI it is easy
* to find the album id (e.g. spotify:album:<here_is_the_album_id>)
* @param {Object} options A JSON object with options that can be passed
* @param {function(Object,Object)} callback An optional callback that receives 2 parameters. The first
* one is the error object (null if no error), and the second is the value if the request succeeded.
* @return {Object} Null if a callback is provided, a `Promise` object otherwise
*/
Constr.prototype.getAlbumTracks = function(albumId, options, callback) {
var requestData = {
url: _baseUri + '/albums/' + albumId + '/tracks'
};
return _checkParamsAndPerformRequest(requestData, options, callback);
};
/**
* Fetches multiple albums from the Spotify catalog.
* See [Get Several Albums](https://developer.spotify.com/web-api/get-several-albums/) on
* the Spotify Developer site for more information about the endpoint.
*
* @param {Array<string>} albumIds The ids of the albums. If you know their Spotify URI it is easy
* to find their album id (e.g. spotify:album:<here_is_the_album_id>)
* @param {Object} options A JSON object with options that can be passed
* @param {function(Object,Object)} callback An optional callback that receives 2 parameters. The first
* one is the error object (null if no error), and the second is the value if the request succeeded.
* @return {Object} Null if a callback is provided, a `Promise` object otherwise
*/
Constr.prototype.getAlbums = function(albumIds, options, callback) {
var requestData = {
url: _baseUri + '/albums/',
params: { ids: albumIds.join(',') }
};
return _checkParamsAndPerformRequest(requestData, options, callback);
};
/**
* Fetches a track from the Spotify catalog.
* See [Get a Track](https://developer.spotify.com/web-api/get-track/) on
* the Spotify Developer site for more information about the endpoint.
*
* @param {string} trackId The id of the track. If you know the Spotify URI it is easy
* to find the track id (e.g. spotify:track:<here_is_the_track_id>)
* @param {Object} options A JSON object with options that can be passed
* @param {function(Object,Object)} callback An optional callback that receives 2 parameters. The first
* one is the error object (null if no error), and the second is the value if the request succeeded.
* @return {Object} Null if a callback is provided, a `Promise` object otherwise
*/
Constr.prototype.getTrack = function(trackId, options, callback) {
var requestData = {};
requestData.url = _baseUri + '/tracks/' + trackId;
return _checkParamsAndPerformRequest(requestData, options, callback);
};
/**
* Fetches multiple tracks from the Spotify catalog.
* See [Get Several Tracks](https://developer.spotify.com/web-api/get-several-tracks/) on
* the Spotify Developer site for more information about the endpoint.
*
* @param {Array<string>} trackIds The ids of the tracks. If you know their Spotify URI it is easy
* to find their track id (e.g. spotify:track:<here_is_the_track_id>)
* @param {Object} options A JSON object with options that can be passed
* @param {function(Object,Object)} callback An optional callback that receives 2 parameters. The first
* one is the error object (null if no error), and the second is the value if the request succeeded.
* @return {Object} Null if a callback is provided, a `Promise` object otherwise
*/
Constr.prototype.getTracks = function(trackIds, options, callback) {
var requestData = {
url: _baseUri + '/tracks/',
params: { ids: trackIds.join(',') }
};
return _checkParamsAndPerformRequest(requestData, options, callback);
};
/**
* Fetches an artist from the Spotify catalog.
* See [Get an Artist](https://developer.spotify.com/web-api/get-artist/) on
* the Spotify Developer site for more information about the endpoint.
*
* @param {string} artistId The id of the artist. If you know the Spotify URI it is easy
* to find the artist id (e.g. spotify:artist:<here_is_the_artist_id>)
* @param {Object} options A JSON object with options that can be passed
* @param {function(Object,Object)} callback An optional callback that receives 2 parameters. The first
* one is the error object (null if no error), and the second is the value if the request succeeded.
* @return {Object} Null if a callback is provided, a `Promise` object otherwise
*/
Constr.prototype.getArtist = function(artistId, options, callback) {
var requestData = {
url: _baseUri + '/artists/' + artistId
};
return _checkParamsAndPerformRequest(requestData, options, callback);
};
/**
* Fetches multiple artists from the Spotify catalog.
* See [Get Several Artists](https://developer.spotify.com/web-api/get-several-artists/) on
* the Spotify Developer site for more information about the endpoint.
*
* @param {Array<string>} artistIds The ids of the artists. If you know their Spotify URI it is easy
* to find their artist id (e.g. spotify:artist:<here_is_the_artist_id>)
* @param {Object} options A JSON object with options that can be passed
* @param {function(Object,Object)} callback An optional callback that receives 2 parameters. The first
* one is the error object (null if no error), and the second is the value if the request succeeded.
* @return {Object} Null if a callback is provided, a `Promise` object otherwise
*/
Constr.prototype.getArtists = function(artistIds, options, callback) {
var requestData = {
url: _baseUri + '/artists/',
params: { ids: artistIds.join(',') }
};
return _checkParamsAndPerformRequest(requestData, options, callback);
};
/**
* Fetches the albums of an artist from the Spotify catalog.
* See [Get an Artist's Albums](https://developer.spotify.com/web-api/get-artists-albums/) on
* the Spotify Developer site for more information about the endpoint.
*
* @param {string} artistId The id of the artist. If you know the Spotify URI it is easy
* to find the artist id (e.g. spotify:artist:<here_is_the_artist_id>)
* @param {Object} options A JSON object with options that can be passed
* @param {function(Object,Object)} callback An optional callback that receives 2 parameters. The first
* one is the error object (null if no error), and the second is the value if the request succeeded.
* @return {Object} Null if a callback is provided, a `Promise` object otherwise
*/
Constr.prototype.getArtistAlbums = function(artistId, options, callback) {
var requestData = {
url: _baseUri + '/artists/' + artistId + '/albums'
};
return _checkParamsAndPerformRequest(requestData, options, callback);
};
/**
* Fetches a list of top tracks of an artist from the Spotify catalog, for a specific country.
* See [Get an Artist's Top Tracks](https://developer.spotify.com/web-api/get-artists-top-tracks/) on
* the Spotify Developer site for more information about the endpoint.
*
* @param {string} artistId The id of the artist. If you know the Spotify URI it is easy
* to find the artist id (e.g. spotify:artist:<here_is_the_artist_id>)
* @param {string} countryId The id of the country (e.g. ES for Spain or US for United States)
* @param {Object} options A JSON object with options that can be passed
* @param {function(Object,Object)} callback An optional callback that receives 2 parameters. The first
* one is the error object (null if no error), and the second is the value if the request succeeded.
* @return {Object} Null if a callback is provided, a `Promise` object otherwise
*/
Constr.prototype.getArtistTopTracks = function(artistId, countryId, options, callback) {
var requestData = {
url: _baseUri + '/artists/' + artistId + '/top-tracks',
params: { country: countryId }
};
return _checkParamsAndPerformRequest(requestData, options, callback);
};
/**
* Fetches a list of artists related with a given one from the Spotify catalog.
* See [Get an Artist's Related Artists](https://developer.spotify.com/web-api/get-related-artists/) on
* the Spotify Developer site for more information about the endpoint.
*
* @param {string} artistId The id of the artist. If you know the Spotify URI it is easy
* to find the artist id (e.g. spotify:artist:<here_is_the_artist_id>)
* @param {Object} options A JSON object with options that can be passed
* @param {function(Object,Object)} callback An optional callback that receives 2 parameters. The first
* one is the error object (null if no error), and the second is the value if the request succeeded.
* @return {Object} Null if a callback is provided, a `Promise` object otherwise
*/
Constr.prototype.getArtistRelatedArtists = function(artistId, options, callback) {
var requestData = {
url: _baseUri + '/artists/' + artistId + '/related-artists'
};
return _checkParamsAndPerformRequest(requestData, options, callback);
};
/**
* Fetches a list of Spotify featured playlists (shown, for example, on a Spotify player's "Browse" tab).
* See [Get a List of Featured Playlists](https://developer.spotify.com/web-api/get-list-featured-playlists/) on
* the Spotify Developer site for more information about the endpoint.
*
* @param {Object} options A JSON object with options that can be passed
* @param {function(Object,Object)} callback An optional callback that receives 2 parameters. The first
* one is the error object (null if no error), and the second is the value if the request succeeded.
* @return {Object} Null if a callback is provided, a `Promise` object otherwise
*/
Constr.prototype.getFeaturedPlaylists = function(options, callback) {
var requestData = {
url: _baseUri + '/browse/featured-playlists'
};
return _checkParamsAndPerformRequest(requestData, options, callback);
};
/**
* Fetches a list of new album releases featured in Spotify (shown, for example, on a Spotify player's "Browse" tab).
* See [Get a List of New Releases](https://developer.spotify.com/web-api/get-list-new-releases/) on
* the Spotify Developer site for more information about the endpoint.
*
* @param {Object} options A JSON object with options that can be passed
* @param {function(Object,Object)} callback An optional callback that receives 2 parameters. The first
* one is the error object (null if no error), and the second is the value if the request succeeded.
* @return {Object} Null if a callback is provided, a `Promise` object otherwise
*/
Constr.prototype.getNewReleases = function(options, callback) {
var requestData = {
url: _baseUri + '/browse/new-releases'
};
return _checkParamsAndPerformRequest(requestData, options, callback);
};
/**
* Get a list of categories used to tag items in Spotify (on, for example, the Spotify player's "Browse" tab).
* See [Get a List of Categories](https://developer.spotify.com/web-api/get-list-categories/) on
* the Spotify Developer site for more information about the endpoint.
*
* @param {Object} options A JSON object with options that can be passed
* @param {function(Object,Object)} callback An optional callback that receives 2 parameters. The first
* one is the error object (null if no error), and the second is the value if the request succeeded.
* @return {Object} Null if a callback is provided, a `Promise` object otherwise
*/
Constr.prototype.getCategories = function(options, callback) {
var requestData = {
url: _baseUri + '/browse/categories'
};
return _checkParamsAndPerformRequest(requestData, options, callback);
};
/**
* Get a single category used to tag items in Spotify (on, for example, the Spotify player's "Browse" tab).
* See [Get a Category](https://developer.spotify.com/web-api/get-category/) on
* the Spotify Developer site for more information about the endpoint.
*
* @param {string} categoryId The id of the category. These can be found with the getCategories function
* @param {Object} options A JSON object with options that can be passed
* @param {function(Object,Object)} callback An optional callback that receives 2 parameters. The first
* one is the error object (null if no error), and the second is the value if the request succeeded.
* @return {Object} Null if a callback is provided, a `Promise` object otherwise
*/
Constr.prototype.getCategory = function(categoryId, options, callback) {
var requestData = {
url: _baseUri + '/browse/categories/' + categoryId
};
return _checkParamsAndPerformRequest(requestData, options, callback);
};
/**
* Get a list of Spotify playlists tagged with a particular category.
* See [Get a Category's Playlists](https://developer.spotify.com/web-api/get-categorys-playlists/) on
* the Spotify Developer site for more information about the endpoint.
*
* @param {string} categoryId The id of the category. These can be found with the getCategories function
* @param {Object} options A JSON object with options that can be passed
* @param {function(Object,Object)} callback An optional callback that receives 2 parameters. The first
* one is the error object (null if no error), and the second is the value if the request succeeded.
* @return {Object} Null if a callback is provided, a `Promise` object otherwise
*/
Constr.prototype.getCategoryPlaylists = function(categoryId, options, callback) {
var requestData = {
url: _baseUri + '/browse/categories/' + categoryId + '/playlists'
};
return _checkParamsAndPerformRequest(requestData, options, callback);
};
/**
* Get Spotify catalog information about artists, albums, tracks or playlists that match a keyword string.
* See [Search for an Item](https://developer.spotify.com/web-api/search-item/) on
* the Spotify Developer site for more information about the endpoint.
*
* @param {string} query The search query
* @param {Array<string>} types An array of item types to search across.
* Valid types are: 'album', 'artist', 'playlist', and 'track'.
* @param {Object} options A JSON object with options that can be passed
* @param {function(Object,Object)} callback An optional callback that receives 2 parameters. The first
* one is the error object (null if no error), and the second is the value if the request succeeded.
* @return {Object} Null if a callback is provided, a `Promise` object otherwise
*/
Constr.prototype.search = function(query, types, options, callback) {
var requestData = {
url: _baseUri + '/search/',
params: {
q: query,
type: types.join(',')
}
};
return _checkParamsAndPerformRequest(requestData, options, callback);
};
/**
* Fetches albums from the Spotify catalog according to a query.
* See [Search for an Item](https://developer.spotify.com/web-api/search-item/) on
* the Spotify Developer site for more information about the endpoint.
*
* @param {string} query The search query
* @param {Object} options A JSON object with options that can be passed
* @param {function(Object,Object)} callback An optional callback that receives 2 parameters. The first
* one is the error object (null if no error), and the second is the value if the request succeeded.
* @return {Object} Null if a callback is provided, a `Promise` object otherwise
*/
Constr.prototype.searchAlbums = function(query, options, callback) {
return this.search(query, ['album'], options, callback);
};
/**
* Fetches artists from the Spotify catalog according to a query.
* See [Search for an Item](https://developer.spotify.com/web-api/search-item/) on
* the Spotify Developer site for more information about the endpoint.
*
* @param {string} query The search query
* @param {Object} options A JSON object with options that can be passed
* @param {function(Object,Object)} callback An optional callback that receives 2 parameters. The first
* one is the error object (null if no error), and the second is the value if the request succeeded.
* @return {Object} Null if a callback is provided, a `Promise` object otherwise
*/
Constr.prototype.searchArtists = function(query, options, callback) {
return this.search(query, ['artist'], options, callback);
};
/**
* Fetches tracks from the Spotify catalog according to a query.
* See [Search for an Item](https://developer.spotify.com/web-api/search-item/) on
* the Spotify Developer site for more information about the endpoint.
*
* @param {string} query The search query
* @param {Object} options A JSON object with options that can be passed
* @param {function(Object,Object)} callback An optional callback that receives 2 parameters. The first
* one is the error object (null if no error), and the second is the value if the request succeeded.
* @return {Object} Null if a callback is provided, a `Promise` object otherwise
*/
Constr.prototype.searchTracks = function(query, options, callback) {
return this.search(query, ['track'], options, callback);
};
/**
* Fetches playlists from the Spotify catalog according to a query.
* See [Search for an Item](https://developer.spotify.com/web-api/search-item/) on
* the Spotify Developer site for more information about the endpoint.
*
* @param {string} query The search query
* @param {Object} options A JSON object with options that can be passed
* @param {function(Object,Object)} callback An optional callback that receives 2 parameters. The first
* one is the error object (null if no error), and the second is the value if the request succeeded.
* @return {Object} Null if a callback is provided, a `Promise` object otherwise
*/
Constr.prototype.searchPlaylists = function(query, options, callback) {
return this.search(query, ['playlist'], options, callback);
};
/**
* Get audio features for a single track identified by its unique Spotify ID.
* See [Get Audio Features for a Track](https://developer.spotify.com/web-api/get-audio-features/) on
* the Spotify Developer site for more information about the endpoint.
*
* @param {string} trackId The id of the track. If you know the Spotify URI it is easy
* to find the track id (e.g. spotify:track:<here_is_the_track_id>)
* @param {function(Object,Object)} callback An optional callback that receives 2 parameters. The first
* one is the error object (null if no error), and the second is the value if the request succeeded.
* @return {Object} Null if a callback is provided, a `Promise` object otherwise
*/
Constr.prototype.getAudioFeaturesForTrack = function(trackId, callback) {
var requestData = {};
requestData.url = _baseUri + '/audio-features/' + trackId;
return _checkParamsAndPerformRequest(requestData, {}, callback);
};
/**
* Get audio features for multiple tracks based on their Spotify IDs.
* See [Get Audio Features for Several Tracks](https://developer.spotify.com/web-api/get-several-audio-features/) on
* the Spotify Developer site for more information about the endpoint.
*
* @param {Array<string>} trackIds The ids of the tracks. If you know their Spotify URI it is easy
* to find their track id (e.g. spotify:track:<here_is_the_track_id>)
* @param {function(Object,Object)} callback An optional callback that receives 2 parameters. The first
* one is the error object (null if no error), and the second is the value if the request succeeded.
* @return {Object} Null if a callback is provided, a `Promise` object otherwise
*/
Constr.prototype.getAudioFeaturesForTracks = function(trackIds, callback) {
var requestData = {
url: _baseUri + '/audio-features',
params: { ids: trackIds }
};
return _checkParamsAndPerformRequest(requestData, {}, callback);
};
/**
* Get audio analysis for a single track identified by its unique Spotify ID.
* See [Get Audio Analysis for a Track](https://developer.spotify.com/web-api/get-audio-analysis/) on
* the Spotify Developer site for more information about the endpoint.
*
* @param {string} trackId The id of the track. If you know the Spotify URI it is easy
* to find the track id (e.g. spotify:track:<here_is_the_track_id>)
* @param {function(Object,Object)} callback An optional callback that receives 2 parameters. The first
* one is the error object (null if no error), and the second is the value if the request succeeded.
* @return {Object} Null if a callback is provided, a `Promise` object otherwise
*/
Constr.prototype.getAudioAnalysisForTrack = function(trackId, callback) {
var requestData = {};
requestData.url = _baseUri + '/audio-analysis/' + trackId;
return _checkParamsAndPerformRequest(requestData, {}, callback);
};
/**
* Create a playlist-style listening experience based on seed artists, tracks and genres.
* See [Get Recommendations Based on Seeds](https://developer.spotify.com/web-api/get-recommendations/) on
* the Spotify Developer site for more information about the endpoint.
*
* @param {Object} options A JSON object with options that can be passed
* @param {function(Object,Object)} callback An optional callback that receives 2 parameters. The first
* one is the error object (null if no error), and the second is the value if the request succeeded.
* @return {Object} Null if a callback is provided, a `Promise` object otherwise
*/
Constr.prototype.getRecommendations = function(options, callback) {
var requestData = {
url: _baseUri + '/recommendations'
};
return _checkParamsAndPerformRequest(requestData, options, callback);
};
/**
* Retrieve a list of available genres seed parameter values for recommendations.
* See [Available Genre Seeds](https://developer.spotify.com/web-api/get-recommendations/#available-genre-seeds) on
* the Spotify Developer site for more information about the endpoint.
*
* @param {function(Object,Object)} callback An optional callback that receives 2 parameters. The first
* one is the error object (null if no error), and the second is the value if the request succeeded.
* @return {Object} Null if a callback is provided, a `Promise` object otherwise
*/
Constr.prototype.getAvailableGenreSeeds = function(callback) {
var requestData = {
url: _baseUri + '/recommendations/available-genre-seeds'
};
return _checkParamsAndPerformRequest(requestData, {}, callback);
};
/**
* Gets the access token in use.
*
* @return {string} accessToken The access token
*/
Constr.prototype.getAccessToken = function() {
return _accessToken;
};
/**
* Sets the access token to be used.
* See [the Authorization Guide](https://developer.spotify.com/web-api/authorization-guide/) on
* the Spotify Developer site for more information about obtaining an access token.
*
* @param {string} accessToken The access token
* @return {void}
*/
Constr.prototype.setAccessToken = function(accessToken) {
_accessToken = accessToken;
};
/**
* Sets an implementation of Promises/A+ to be used. E.g. Q, when.
* See [Conformant Implementations](https://github.com/promises-aplus/promises-spec/blob/master/implementations.md)
* for a list of some available options
*
* @param {Object} PromiseImplementation A Promises/A+ valid implementation
* @throws {Error} If the implementation being set doesn't conform with Promises/A+
* @return {void}
*/
Constr.prototype.setPromiseImplementation = function(PromiseImplementation) {
var valid = false;
try {
var p = new PromiseImplementation(function(resolve) {
resolve();
});
if (typeof p.then === 'function' && typeof p.catch === 'function') {
valid = true;
}
} catch (e) {
console.error(e);
}
if (valid) {
_promiseImplementation = PromiseImplementation;
} else {
throw new Error('Unsupported implementation of Promises/A+');
}
};
return Constr;
})();
if (typeof module === 'object' && typeof module.exports === 'object') {
module.exports = SpotifyWebApi;
}
| jefferyshivers/omi-exp | lib/spotify-web-api.js | JavaScript | mit | 70,439 |
/**
* @copyright
* The MIT License (MIT)
*
* Copyright (c) 2014 Cosmic Dynamo LLC
*
* 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.
* @module jazzHands.query.function.substring
*/
define([], function () {
/**
* returns substring of the input string
* @see http://www.w3.org/TR/xpath-functions/#func-substring
* @param {Object} execData
* @param {jazzHands.query.DataRow} dataRow
* @param {jazzHands.query._Expression} source
* @return {RdfJs.node.Literal<String>}
* @throws err:FORG0006, Invalid argument type
*/
function ucase(execData, dataRow, source) {
var string = source.resolve(execData, dataRow);
if (string) {
string.nominalValue = string.nominalValue.toUpperCase();
}
return string;
}
return ucase;
});
| CosmicDynamo/jazzHands | query/function/upper-case.js | JavaScript | mit | 1,852 |
var Client = require('../lib/Client');
var assert = require('assert');
var format = require('util').format;
var inspect = require('util').inspect;
var t = -1;
var testCaseTimeout = 10 * 1000;
var timeout;
var DEFAULT_HOST = process.env.DB_HOST || '127.0.0.1';
var DEFAULT_PORT = +(process.env.DB_PORT || 3306);
var DEFAULT_USER = process.env.DB_USER || 'root';
var DEFAULT_PASSWORD = process.env.DB_PASS || '';
function NOOP(err) { assert.strictEqual(err, null); }
var tests = [
{ what: 'Client::version()',
run: function() {
var version = Client.version();
assert.strictEqual(typeof version, 'string');
assert.notStrictEqual(version.length, 0);
next();
}
},
{ what: 'Client::escape()',
run: function() {
assert.strictEqual(Client.escape("hello 'world'"), "hello \\'world\\'");
next();
}
},
{ what: 'prepare()',
run: function() {
var client = new Client();
var fn;
fn = client.prepare("SELECT * FROM foo WHERE id = '123'");
assert.strictEqual(fn({ id: 456 }),
"SELECT * FROM foo WHERE id = '123'");
fn = client.prepare("SELECT * FROM foo WHERE id = :id");
assert.strictEqual(fn({ id: 123 }),
"SELECT * FROM foo WHERE id = '123'");
assert.strictEqual(fn({ id: 456 }),
"SELECT * FROM foo WHERE id = '456'");
fn = client.prepare("SELECT * FROM foo WHERE id = ?");
assert.strictEqual(fn([123]),
"SELECT * FROM foo WHERE id = '123'");
assert.strictEqual(fn([456]),
"SELECT * FROM foo WHERE id = '456'");
fn = client.prepare("SELECT * FROM foo WHERE id = :0 AND name = :1");
assert.strictEqual(fn(['123', 'baz']),
"SELECT * FROM foo WHERE id = '123' AND name = 'baz'");
// Edge cases
fn = client.prepare("SELECT * FROM foo WHERE id = :id"
+ " AND first = ? AND last = ? AND middle = '?'");
assert.strictEqual(fn(appendProps(['foo', 'bar', 'baz'], { id: '123' })),
"SELECT * FROM foo WHERE id = '123'"
+ " AND first = 'foo' AND last = 'bar'"
+ " AND middle = '?'");
fn = client.prepare("SELECT * FROM foo WHERE id = :id"
+ " AND first = ? AND last = '?' AND middle = ?");
assert.strictEqual(fn(appendProps(['foo', 'bar', 'baz'], { id: '123' })),
"SELECT * FROM foo WHERE id = '123'"
+ " AND first = 'foo' AND last = '?'"
+ " AND middle = 'bar'");
fn = client.prepare("SELECT * FROM foo WHERE id = :id"
+ " AND first = '?' AND last = '?' AND middle = ?");
assert.strictEqual(fn(appendProps(['foo', 'bar', 'baz'], { id: '123' })),
"SELECT * FROM foo WHERE id = '123'"
+ " AND first = '?' AND last = '?'"
+ " AND middle = 'foo'");
fn = client.prepare("SELECT * FROM foo WHERE id = :id"
+ " AND first = ? AND last = '?' AND middle = '?'");
assert.strictEqual(fn(appendProps(['foo', 'bar', 'baz'], { id: '123' })),
"SELECT * FROM foo WHERE id = '123'"
+ " AND first = 'foo' AND last = '?'"
+ " AND middle = '?'");
fn = client.prepare("SELECT * FROM foo WHERE id = '?'"
+ " AND first = ? AND last = '?' AND middle = '?'");
assert.strictEqual(fn(['foo', 'bar', 'baz']),
"SELECT * FROM foo WHERE id = '?'"
+ " AND first = 'foo' AND last = '?'"
+ " AND middle = '?'");
fn = client.prepare("SELECT 'test?value' FROM foo WHERE id = :id"
+ " AND first = ? AND last = '?' AND middle = '?'");
assert.strictEqual(fn(appendProps(['foo', 'bar', 'baz'], { id: '123' })),
"SELECT 'test?value' FROM foo WHERE id = '123'"
+ " AND first = 'foo' AND last = '?'"
+ " AND middle = '?'");
fn = client.prepare("SELECT ? FROM foo WHERE id = :id"
+ " AND first = ? AND last = '?' AND middle = '?'");
assert.strictEqual(fn(appendProps(['foo', 'bar', 'baz'], { id: '123' })),
"SELECT 'foo' FROM foo WHERE id = '123'"
+ " AND first = 'bar' AND last = '?'"
+ " AND middle = '?'");
fn = client.prepare("SELECT ?, '?' FROM foo WHERE id = :id"
+ " AND first = ? AND last = '?' AND middle = '?'");
assert.strictEqual(fn(appendProps(['foo', 'bar', 'baz'], { id: '123' })),
"SELECT 'foo', '?' FROM foo WHERE id = '123'"
+ " AND first = 'bar' AND last = '?'"
+ " AND middle = '?'");
fn = client.prepare("SELECT :id FROM foo WHERE id = :id"
+ " AND first = ? AND last = '?' AND middle = '?'");
assert.strictEqual(fn(appendProps(['foo', 'bar', 'baz'], { id: '123' })),
"SELECT '123' FROM foo WHERE id = '123'"
+ " AND first = 'foo' AND last = '?'"
+ " AND middle = '?'");
fn = client.prepare("SELECT ':id' FROM foo WHERE id = :id"
+ " AND first = ? AND last = '?' AND middle = '?'");
assert.strictEqual(fn(appendProps(['foo', 'bar', 'baz'], { id: '123' })),
"SELECT ':id' FROM foo WHERE id = '123'"
+ " AND first = 'foo' AND last = '?'"
+ " AND middle = '?'");
fn = client.prepare("SELECT '?', ':id', ?, :id FROM foo WHERE id = :id"
+ " AND first = ? AND last = '?' AND middle = '?'");
assert.strictEqual(fn(appendProps(['foo', 'bar', 'baz'], { id: '123' })),
"SELECT '?', ':id', 'foo', '123' FROM foo WHERE id = '123'"
+ " AND first = 'bar' AND last = '?'"
+ " AND middle = '?'");
next();
}
},
{ what: 'Non-empty threadId',
run: function() {
var finished = false;
var client = makeClient(function() {
assert.strictEqual(finished, true);
});
client.connect(function() {
assert.strictEqual(typeof client.threadId, 'string');
assert.notStrictEqual(client.threadId.length, 0);
finished = true;
client.end();
});
}
},
{ what: 'Empty threadId (explicit disable)',
run: function() {
var finished = false;
var client = makeClient({ threadId: false }, function() {
assert.strictEqual(finished, true);
});
client.connect(function() {
assert.strictEqual(client.threadId, undefined);
finished = true;
client.end();
});
}
},
{ what: 'escape()',
run: function() {
var finished = false;
var client = makeClient(function() {
assert.strictEqual(finished, true);
});
client.connect(function() {
assert.strictEqual(client.escape("hello 'world'"), "hello \\'world\\'");
finished = true;
client.end();
});
}
},
{ what: 'isMariaDB()',
run: function() {
var finished = false;
var client = makeClient(function() {
assert.strictEqual(finished, true);
});
client.connect(function() {
assert.strictEqual(typeof client.isMariaDB(), 'boolean');
finished = true;
client.end();
});
}
},
{ what: 'serverVersion()',
run: function() {
var finished = false;
var client = makeClient(function() {
assert.strictEqual(finished, true);
});
client.connect(function() {
var version = client.serverVersion();
assert.strictEqual(typeof version, 'string');
assert.notStrictEqual(version.length, 0);
finished = true;
client.end();
});
}
},
{ what: 'Buffered result (defaults)',
run: function() {
var finished = false;
var client = makeClient(function() {
assert.strictEqual(finished, true);
});
client.query("SELECT 'hello' col1, 'world' col2", function(err, rows) {
assert.strictEqual(err, null);
assert.deepStrictEqual(
rows,
appendProps(
[ {col1: 'hello', col2: 'world'} ],
{ info: {
numRows: '1',
affectedRows: '1',
insertId: '0',
metadata: undefined
}
}
)
);
finished = true;
client.end();
});
}
},
{ what: 'Buffered result (useArray)',
run: function() {
var finished = false;
var client = makeClient(function() {
assert.strictEqual(finished, true);
});
client.query("SELECT 'hello' col1, 'world' col2",
null,
{ useArray: true },
function(err, rows) {
assert.strictEqual(err, null);
assert.deepStrictEqual(
rows,
appendProps(
[ ['hello', 'world'] ],
{ info: {
numRows: '1',
affectedRows: '1',
insertId: '0',
metadata: undefined
}
}
)
);
finished = true;
client.end();
});
}
},
{ what: 'Buffered result (metadata)',
run: function() {
var finished = false;
var client = makeClient(function() {
assert.strictEqual(finished, true);
});
makeFooTable(client, {
id: { type: 'INT', options: ['AUTO_INCREMENT', 'PRIMARY KEY'] },
name: 'VARCHAR(255)'
});
client.query("INSERT INTO foo VALUES (NULL, 'hello world'),(NULL, 'bar')",
function(err, rows) {
assert.strictEqual(err, null);
assert.deepStrictEqual(
rows,
{ info: {
numRows: '0',
affectedRows: '2',
insertId: '1',
metadata: undefined
}
}
);
});
client.query('SELECT id, name FROM foo',
null,
{ metadata: true },
function(err, rows) {
assert.strictEqual(err, null);
assert.deepStrictEqual(
rows,
appendProps(
[ {id: '1', name: 'hello world'}, {id: '2', name: 'bar'} ],
{ info: {
numRows: '2',
affectedRows: '2',
insertId: '1',
metadata: {
id: {
org_name: 'id',
type: 'INTEGER',
flags: Client.NOT_NULL_FLAG
| Client.PRI_KEY_FLAG
| Client.AUTO_INCREMENT_FLAG
| Client.PART_KEY_FLAG
| Client.NUM_FLAG,
charsetnr: 63,
db: 'foo',
table: 'foo',
org_table: 'foo'
},
name: {
org_name: 'name',
type: 'VARCHAR',
flags: 0,
charsetnr: 8,
db: 'foo',
table: 'foo',
org_table: 'foo'
}
}
}
}
)
);
finished = true;
client.end();
});
}
},
{ what: 'Streamed result (defaults)',
run: function() {
var finished = false;
var client = makeClient(function() {
assert.strictEqual(finished, true);
assert.deepStrictEqual(
events,
[ 'result',
[ 'result.data', {col1: 'hello', col2: 'world'} ],
[ 'result.end',
{ numRows: '1',
affectedRows: '-1',
insertId: '0',
metadata: undefined
}
],
'query.end'
]
);
finished = true;
client.end();
});
var events = [];
var query = client.query("SELECT 'hello' col1, 'world' col2");
query.on('result', function(res) {
events.push('result');
res.on('data', function(row) {
events.push(['result.data', row]);
}).on('end', function() {
events.push(['result.end', res.info]);
});
}).on('end', function() {
events.push('query.end');
finished = true;
client.end();
});
}
},
{ what: 'Streamed result (useArray)',
run: function() {
var finished = false;
var client = makeClient(function() {
assert.strictEqual(finished, true);
assert.deepStrictEqual(
events,
[ 'result',
[ 'result.data', ['hello', 'world'] ],
[ 'result.end',
{ numRows: '1',
affectedRows: '-1',
insertId: '0',
metadata: undefined
}
],
'query.end'
]
);
finished = true;
client.end();
});
var events = [];
var query = client.query("SELECT 'hello' col1, 'world' col2",
null,
{ useArray: true });
query.on('result', function(res) {
events.push('result');
res.on('data', function(row) {
events.push(['result.data', row]);
}).on('end', function() {
events.push(['result.end', res.info]);
});
}).on('end', function() {
events.push('query.end');
finished = true;
client.end();
});
}
},
{ what: 'Streamed result (metadata)',
run: function() {
var finished = false;
var client = makeClient(function() {
assert.strictEqual(finished, true);
assert.deepStrictEqual(
events,
[ 'result',
[ 'result.data', {id: '1', name: 'hello world'} ],
[ 'result.data', {id: '2', name: 'bar'} ],
[ 'result.end',
{ numRows: '2',
affectedRows: '-1',
insertId: '1',
metadata: {
id: {
org_name: 'id',
type: 'INTEGER',
flags: Client.NOT_NULL_FLAG
| Client.PRI_KEY_FLAG
| Client.AUTO_INCREMENT_FLAG
| Client.PART_KEY_FLAG
| Client.NUM_FLAG,
charsetnr: 63,
db: 'foo',
table: 'foo',
org_table: 'foo'
},
name: {
org_name: 'name',
type: 'VARCHAR',
flags: 0,
charsetnr: 8,
db: 'foo',
table: 'foo',
org_table: 'foo'
}
}
}
],
'query.end'
]
);
finished = true;
client.end();
});
var events = [];
makeFooTable(client, {
id: { type: 'INT', options: ['AUTO_INCREMENT', 'PRIMARY KEY'] },
name: 'VARCHAR(255)'
});
client.query("INSERT INTO foo VALUES (NULL, 'hello world'),(NULL, 'bar')",
NOOP);
var query = client.query('SELECT id, name FROM foo',
null,
{ metadata: true });
query.on('result', function(res) {
events.push('result');
res.on('data', function(row) {
events.push(['result.data', row]);
}).on('end', function() {
events.push(['result.end', res.info]);
});
}).on('end', function() {
events.push('query.end');
finished = true;
client.end();
});
}
},
{ what: 'Streamed result (INSERT)',
run: function() {
var finished = false;
var client = makeClient(function() {
assert.strictEqual(finished, true);
assert.deepStrictEqual(
events,
[ 'result',
[ 'result.end',
{ numRows: '0',
affectedRows: '2',
insertId: '1',
metadata: undefined
}
],
'query.end'
]
);
finished = true;
client.end();
});
var events = [];
makeFooTable(client, {
id: { type: 'INT', options: ['AUTO_INCREMENT', 'PRIMARY KEY'] },
name: 'VARCHAR(255)'
});
var query = client.query(
"INSERT INTO foo VALUES (NULL, 'hello world'),(NULL, 'bar')"
);
query.on('result', function(res) {
events.push('result');
res.on('data', function(row) {
events.push(['result.data', row]);
}).on('end', function() {
events.push(['result.end', res.info]);
});
}).on('end', function() {
events.push('query.end');
finished = true;
client.end();
});
}
},
{ what: 'Streamed result (START TRANSACTION, no data listener)',
run: function() {
var finished = false;
var client = makeClient(function() {
assert.strictEqual(finished, true);
assert.deepStrictEqual(
events,
[ 'result',
[ 'result.end',
{ numRows: '0',
affectedRows: '0',
insertId: '0',
metadata: undefined
}
],
'query.end'
]
);
finished = true;
client.end();
});
var events = [];
var query = client.query('START TRANSACTION');
query.on('result', function(res) {
events.push('result');
res.on('end', function() {
events.push(['result.end', res.info]);
});
}).on('end', function() {
events.push('query.end');
finished = true;
client.end();
});
}
},
{ what: 'lastInsertId()',
run: function() {
var finished = false;
var client = makeClient(function() {
assert.strictEqual(finished, true);
});
makeFooTable(client, {
id: { type: 'INT', options: ['AUTO_INCREMENT', 'PRIMARY KEY'] },
name: 'VARCHAR(255)'
});
client.query("INSERT INTO foo (id, name) VALUES (NULL, 'hello')",
function(err) {
assert.strictEqual(err, null);
assert.strictEqual(client.lastInsertId(), '1');
client.query("INSERT INTO foo (id, name) VALUES (NULL, 'world')",
function(err) {
assert.strictEqual(err, null);
assert.strictEqual(client.lastInsertId(), '2');
finished = true;
client.end();
});
});
}
},
{ what: 'multiStatements',
run: function() {
var finished = false;
var client = makeClient({ multiStatements: true }, function() {
assert.strictEqual(finished, true);
});
client.query("SELECT 'hello' c1; SELECT 'world' c2", function(err, rows) {
assert.strictEqual(err, null);
assert.deepStrictEqual(
rows,
[ appendProps(
[ { c1: 'hello' } ],
{ info: {
numRows: '1',
affectedRows: '1',
insertId: '0',
metadata: undefined
}
}
),
appendProps(
[ { c2: 'world' } ],
{ info: {
numRows: '1',
affectedRows: '1',
insertId: '0',
metadata: undefined
}
}
)
]
);
finished = true;
client.end();
});
}
},
{ what: 'Process queue before connection close',
run: function() {
var finished = false;
var client = makeClient(function() {
assert.strictEqual(finished, true);
});
client.query("SELECT 'hello' col1", function(err, rows) {
assert.strictEqual(err, null);
assert.deepStrictEqual(
rows,
appendProps(
[ {col1: 'hello'} ],
{ info: {
numRows: '1',
affectedRows: '1',
insertId: '0',
metadata: undefined
}
}
)
);
});
client.query("SELECT 'world' col2", function(err, rows) {
assert.strictEqual(err, null);
assert.deepStrictEqual(
rows,
appendProps(
[ {col2: 'world'} ],
{ info: {
numRows: '1',
affectedRows: '1',
insertId: '0',
metadata: undefined
}
}
)
);
finished = true;
});
client.end();
}
},
{ what: 'Abort long running query',
run: function() {
var finished = false;
var sawAbortCb = false;
var closes = 0;
var client = makeClient({ _skipClose: true });
client.on('close', function() {
assert.strictEqual(++closes, 1);
checkDone();
});
client.query("SELECT SLEEP(60) ret", function(err, rows) {
assert.strictEqual(err, null);
assert.deepStrictEqual(
rows,
appendProps(
[ {ret: '1'} ],
{ info: {
numRows: '1',
affectedRows: '1',
insertId: '0',
metadata: undefined
}
}
)
);
finished = true;
client.end();
checkDone();
});
setTimeout(function() {
client.abort(function(err) {
assert.strictEqual(err, null);
sawAbortCb = true;
checkDone();
});
}, 1000);
function checkDone() {
if (finished && sawAbortCb && closes === 1)
next();
}
}
},
{ what: 'Abort connection',
run: function() {
var finished = false;
var sawAbortCb = false;
var sawError = false;
var closes = 0;
var client = makeClient({ _skipClose: true });
client.on('close', function() {
assert.strictEqual(++closes, 1);
checkDone();
});
client.on('error', function(err) {
assert.strictEqual(sawError, false);
assert.strictEqual(typeof err, 'object');
assert.strictEqual(err.code, 2013);
assert.strictEqual(client.connected, false);
sawError = true;
});
client.query("SELECT SLEEP(60) ret", function(err, rows) {
assert.strictEqual(typeof err, 'object');
assert.strictEqual(err.code, 2013);
assert.strictEqual(rows, undefined);
assert.strictEqual(client.connected, false);
finished = true;
checkDone();
});
setTimeout(function() {
client.abort(true, function(err) {
assert.strictEqual(err, null);
sawAbortCb = true;
checkDone();
});
}, 1000);
function checkDone() {
if (finished && sawAbortCb && sawError && closes === 1)
next();
}
}
},
{ what: 'clean up pending queries on close',
run: function() {
var finished1 = false;
var finished2 = false;
var finished3 = false;
var sawAbortCb = false;
var sawError = false;
var closes = 0;
var client = makeClient({ _skipClose: true });
client.on('close', function() {
assert.strictEqual(++closes, 1);
checkDone();
});
client.on('error', function(err) {
assert.strictEqual(sawError, false);
assert.strictEqual(typeof err, 'object');
assert.strictEqual(err.code, 2013);
assert.strictEqual(client.connected, false);
sawError = true;
});
client.query("SELECT SLEEP(60) ret", function(err, rows) {
assert.strictEqual(typeof err, 'object');
assert.strictEqual(err.code, 2013);
assert.strictEqual(rows, undefined);
assert.strictEqual(client.connected, false);
finished1 = true;
});
client.query("SELECT SLEEP(0.1) ret", function(err, rows) {
assert.strictEqual(typeof err, 'object');
assert.strictEqual(err.code, 2013);
assert.strictEqual(rows, undefined);
assert.strictEqual(client.connected, false);
finished2 = true;
});
client.query("SELECT SLEEP(0.1) ret", function(err, rows) {
assert.strictEqual(typeof err, 'object');
assert.strictEqual(err.code, 2013);
assert.strictEqual(rows, undefined);
assert.strictEqual(client.connected, false);
finished3 = true;
checkDone();
});
setTimeout(function() {
client.abort(true, function(err) {
assert.strictEqual(err, null);
sawAbortCb = true;
checkDone();
});
}, 1000);
function checkDone() {
if (finished1 && finished2 && finished3 && sawAbortCb && sawError
&& closes === 1) {
next();
}
}
}
},
{ what: 'keep pending queries on close',
run: function() {
var finished1 = false;
var finished2 = false;
var finished3 = false;
var sawAbortCb = false;
var sawError = false;
var closes = 0;
var client = makeClient({ keepQueries: true, _skipClose: true });
client.on('close', function() {
assert.strictEqual(finished1, true);
assert.strictEqual(sawError, true);
if (++closes === 1) {
assert.strictEqual(finished2, false);
assert.strictEqual(finished3, false);
client.connect();
return;
}
assert.strictEqual(closes, 2);
assert.strictEqual(finished2, true);
assert.strictEqual(finished3, true);
checkDone();
});
client.on('error', function(err) {
assert.strictEqual(sawError, false);
assert.strictEqual(typeof err, 'object');
assert.strictEqual(err.code, 2013);
assert.strictEqual(client.connected, false);
sawError = true;
});
client.query("SELECT SLEEP(60) ret", function(err, rows) {
assert.strictEqual(typeof err, 'object');
assert.strictEqual(err.code, 2013);
assert.strictEqual(rows, undefined);
assert.strictEqual(client.connected, false);
finished1 = true;
});
client.query("SELECT SLEEP(0.1) ret", function(err, rows) {
assert.strictEqual(err, null);
assert.deepStrictEqual(
rows,
appendProps(
[ {ret: '0'} ],
{ info: {
numRows: '1',
affectedRows: '1',
insertId: '0',
metadata: undefined
}
}
)
);
assert.strictEqual(client.connected, true);
finished2 = true;
});
client.query("SELECT SLEEP(0.1) ret", function(err, rows) {
assert.strictEqual(err, null);
assert.deepStrictEqual(
rows,
appendProps(
[ {ret: '0'} ],
{ info: {
numRows: '1',
affectedRows: '1',
insertId: '0',
metadata: undefined
}
}
)
);
assert.strictEqual(client.connected, true);
finished3 = true;
client.end();
});
setTimeout(function() {
client.abort(true, function(err) {
assert.strictEqual(err, null);
sawAbortCb = true;
checkDone();
});
}, 1000);
function checkDone() {
if (finished1 && finished2 && finished3 && sawAbortCb && sawError
&& closes === 2) {
next();
}
}
}
},
{ what: 'No server running',
run: function() {
var client = makeClient({ port: 3005 }, function() {
assert.deepStrictEqual(
events,
[ 'client.error' ]
);
client.end();
});
var events = [];
var query = client.query('SELECT 1');
query.on('result', function(res) {
events.push('result');
res.on('data', function(row) {
events.push(['result.data']);
}).on('end', function() {
events.push(['result.end']);
});
}).on('end', function() {
events.push('query.end');
});
client.on('error', function(err) {
assert.strictEqual(err.code, 2003);
events.push('client.error');
}).on('ready', function() {
events.push('ready');
});
}
},
{ what: 'Bad auth',
run: function() {
var client = makeClient({ password: 'foobarbaz890' }, function() {
assert.deepStrictEqual(
events,
[ 'client.error' ]
);
client.end();
});
var events = [];
var query = client.query('SELECT 1');
query.on('result', function(res) {
events.push('result');
res.on('data', function(row) {
events.push(['result.data']);
}).on('end', function() {
events.push(['result.end']);
});
}).on('end', function() {
events.push('query.end');
});
client.on('error', function(err) {
assert.strictEqual(err.code, 1045);
events.push('client.error');
}).on('ready', function() {
events.push('ready');
});
}
},
{ what: 'Stored procedure',
run: function() {
var client = makeClient();
client.query('CREATE DATABASE IF NOT EXISTS `foo`', NOOP);
client.query('USE `foo`', NOOP);
client.query('DROP PROCEDURE IF EXISTS `testproc`', NOOP);
client.query('CREATE PROCEDURE `testproc` ()\
BEGIN\
SELECT 1;\
END');
client.query('CALL testproc', function(err, rows) {
assert.strictEqual(err, null);
assert.deepStrictEqual(
rows,
[
appendProps(
[ {1: '1'} ],
{ info: {
numRows: '1',
affectedRows: '1',
insertId: '0',
metadata: undefined
}
}
),
{ info: {
numRows: '0',
affectedRows: '0',
insertId: '0',
metadata: undefined
}
}
]
);
assert.strictEqual(client.connected, true);
client.end();
});
client.query('DROP PROCEDURE IF EXISTS `testproc`', NOOP);
}
},
{ what: 'Stored procedure (bad second query)',
run: function() {
var client = makeClient();
client.query('CREATE DATABASE IF NOT EXISTS `foo`', NOOP);
client.query('USE `foo`', NOOP);
client.query('DROP PROCEDURE IF EXISTS `testproc`', NOOP);
client.query('CREATE PROCEDURE `testproc` ()\
BEGIN\
SELECT 1;\
SELECT f;\
END');
client.query('CALL testproc', function(err, rows) {
assert.strictEqual(err, null);
assert.strictEqual(rows.length, 2);
assert.deepStrictEqual(
rows[0],
appendProps(
[ {1: '1'} ],
{ info: {
numRows: '1',
affectedRows: '1',
insertId: '0',
metadata: undefined
}
}
)
);
assert.strictEqual(rows[1].code, 1054);
assert.strictEqual(client.connected, true);
client.end();
});
client.query('DROP PROCEDURE IF EXISTS `testproc`', NOOP);
}
},
];
function makeClient(opts, closeCb) {
var config = {
host: DEFAULT_HOST,
port: DEFAULT_PORT,
user: DEFAULT_USER,
password: DEFAULT_PASSWORD
};
if (typeof opts === 'object' && opts !== null) {
Object.keys(opts).forEach(function(key) {
if (key !== '_skipClose') // Internal option for testing only
config[key] = opts[key];
});
} else if (typeof opts === 'function') {
closeCb = opts;
opts = null;
}
var client = new Client(config);
if (!opts || !opts._skipClose) {
process.nextTick(function() {
if (typeof closeCb === 'function')
client.on('close', closeCb);
client.on('close', next);
});
}
return client;
}
function appendProps(dst, src) {
assert.strictEqual(typeof dst, 'object');
assert.notStrictEqual(dst, null);
assert.strictEqual(typeof src, 'object');
assert.notStrictEqual(src, null);
Object.keys(src).forEach(function(key) {
dst[key] = src[key];
});
return dst;
}
function makeFooTable(client, colDefs, tableOpts) {
var cols = [];
var query;
Object.keys(colDefs).forEach(function(name) {
var options = [];
var type = '';
if (typeof colDefs[name] === 'string')
type = colDefs[name];
else {
type = colDefs[name].type;
options = colDefs[name].options;
}
options = options.join(' ');
cols.push(format('`%s` %s %s', name, type, options));
});
if (typeof tableOpts === 'object' && tableOpts !== null) {
var opts = [];
Object.keys(tableOpts).forEach(function(key) {
opts.push(format('%s=%s', key, tableOpts[key]));
});
tableOpts = opts.join(' ');
} else
tableOpts = '';
client.query('CREATE DATABASE IF NOT EXISTS `foo`', NOOP);
client.query('USE `foo`', NOOP);
query = format('CREATE TEMPORARY TABLE `foo` (%s) ENGINE=MEMORY \
CHARACTER SET utf8 COLLATE utf8_unicode_ci %s',
cols.join(', '),
tableOpts);
client.query(query, NOOP);
}
function next() {
clearTimeout(timeout);
if (t > -1)
console.log('Finished %j', tests[t].what)
if (t === tests.length - 1)
return;
var v = tests[++t];
timeout = setTimeout(function() {
throw new Error(format('Test case %j timed out', v.what));
}, testCaseTimeout);
console.log('Executing %j', v.what);
v.run.call(v);
}
function makeMsg(msg) {
var fmtargs = ['[%s]: ' + msg, tests[t].what];
for (var i = 1; i < arguments.length; ++i)
fmtargs.push(arguments[i]);
return format.apply(null, fmtargs);
}
process.once('uncaughtException', function(err) {
if (t > -1 && !/(?:^|\n)AssertionError: /i.test(''+err))
console.error(makeMsg('Unexpected Exception:'));
else if (t > -1) {
// Only change the message format when it's necessary to make it potentially
// more readable
if ((typeof err.actual === 'object' && err.actual !== null)
|| (typeof err.expected === 'object' && err.expected !== null)) {
// Remake the assertion error since `JSON.stringify()` has a tendency to
// remove properties from `.actual` and `.expected` objects
err.message = format('\n%s\n%s\n%s',
inspect(err.actual, false, 6),
err.operator,
inspect(err.expected, false, 6));
}
// Hack in the name of the test that failed
var oldStack = err.stack;
var oldMsg = err.message;
err = new assert.AssertionError({
message: makeMsg(oldMsg)
});
err.stack = oldStack.replace(oldMsg, err.message);
}
throw err;
}).once('exit', function() {
assert(t === tests.length - 1,
makeMsg('Only finished %d/%d tests', (t + 1), tests.length));
});
process.nextTick(next);
if (!assert.deepStrictEqual) {
var toString = Object.prototype.toString;
function isPrimitive(arg) {
return arg === null || typeof arg !== 'object' && typeof arg !== 'function';
}
function objEquiv(a, b, strict) {
if (a === null || a === undefined || b === null || b === undefined)
return false;
// if one is a primitive, the other must be same
if (isPrimitive(a) || isPrimitive(b))
return a === b;
if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b))
return false;
var aIsArgs = toString.call(a) === '[object Arguments]',
bIsArgs = toString.call(b) === '[object Arguments]';
if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs))
return false;
if (aIsArgs) {
a = pSlice.call(a);
b = pSlice.call(b);
return _deepEqual(a, b, strict);
}
var ka = Object.keys(a),
kb = Object.keys(b),
key, i;
// having the same number of owned properties (keys incorporates
// hasOwnProperty)
if (ka.length !== kb.length)
return false;
//the same set of keys (although not necessarily the same order),
ka.sort();
kb.sort();
//~~~cheap key test
for (i = ka.length - 1; i >= 0; i--) {
if (ka[i] !== kb[i])
return false;
}
//equivalent values for every corresponding key, and
//~~~possibly expensive deep test
for (i = ka.length - 1; i >= 0; i--) {
key = ka[i];
if (!_deepEqual(a[key], b[key], strict)) return false;
}
return true;
}
function _deepEqual(actual, expected, strict) {
// 7.1. All identical values are equivalent, as determined by ===.
if (actual === expected) {
return true;
} else if (actual instanceof Buffer && expected instanceof Buffer) {
return compare(actual, expected) === 0;
// 7.2. If the expected value is a Date object, the actual value is
// equivalent if it is also a Date object that refers to the same time.
} else if (toString.call(actual) === '[object Date]' &&
toString.call(expected) === '[object Date]') {
return actual.getTime() === expected.getTime();
// 7.3 If the expected value is a RegExp object, the actual value is
// equivalent if it is also a RegExp object with the same source and
// properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).
} else if (toString.call(actual) === '[object RegExp]' &&
toString.call(expected) === '[object RegExp]') {
return actual.source === expected.source &&
actual.global === expected.global &&
actual.multiline === expected.multiline &&
actual.lastIndex === expected.lastIndex &&
actual.ignoreCase === expected.ignoreCase;
// 7.4. Other pairs that do not both pass typeof value == 'object',
// equivalence is determined by ==.
} else if ((actual === null || typeof actual !== 'object') &&
(expected === null || typeof expected !== 'object')) {
return strict ? actual === expected : actual == expected;
// 7.5 For all other Object pairs, including Array objects, equivalence is
// determined by having the same number of owned properties (as verified
// with Object.prototype.hasOwnProperty.call), the same set of keys
// (although not necessarily the same order), equivalent values for every
// corresponding key, and an identical 'prototype' property. Note: this
// accounts for both named and indexed properties on Arrays.
} else {
return objEquiv(actual, expected, strict);
}
}
function fail(actual, expected, message, operator, stackStartFunction) {
throw new assert.AssertionError({
message: message,
actual: actual,
expected: expected,
operator: operator,
stackStartFunction: stackStartFunction
});
}
assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) {
if (!_deepEqual(actual, expected, true)) {
fail(actual,
expected,
message,
'deepStrictEqual',
assert.deepStrictEqual);
}
};
}
| mscdex/node-mariasql | test/test.js | JavaScript | mit | 40,139 |
// Karma configuration
// http://karma-runner.github.io/0.12/config/configuration-file.html
// Generated on 2014-11-02 using
// generator-karma 0.8.3
module.exports = function(config) {
'use strict';
config.set({
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// base path, that will be used to resolve files and exclude
basePath: '../',
// testing framework to use (jasmine/mocha/qunit/...)
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'bower_components/angular/angular.js',
'bower_components/angular-mocks/angular-mocks.js',
'bower_components/firebase/firebase.js',
'bower_components/angularfire/dist/angularfire.js',
'bower_components/angular-animate/angular-animate.js',
'bower_components/angular-cookies/angular-cookies.js',
'bower_components/angular-resource/angular-resource.js',
'bower_components/angular-route/angular-route.js',
'bower_components/angular-sanitize/angular-sanitize.js',
'bower_components/angular-touch/angular-touch.js',
'bower_components/firebase-simple-login/firebase-simple-login.js',
'app/scripts/**/*.js',
'test/mock/**/*.js',
'test/spec/**/*.js'
],
// list of files / patterns to exclude
exclude: [],
// web server port
port: 8080,
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
browsers: [
'PhantomJS'
],
// Which plugins to enable
plugins: [
'karma-phantomjs-launcher',
'karma-jasmine'
],
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: false,
colors: true,
// level of logging
// possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
logLevel: config.LOG_INFO,
// Uncomment the following lines if you are using grunt's server to run the tests
// proxies: {
// '/': 'http://localhost:9000/'
// },
// URL root prevent conflicts with the site root
// urlRoot: '_karma_'
});
};
| tinacg/tinacg.github.io | angularjs/angularfire/generated-by-yo/test/karma.conf.js | JavaScript | mit | 2,262 |
/**
* BGP Tools.
*
* Copyright (C) 2012 Beat Gebistorf
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/MIT
*/
(function($) {
Tc.Module.Tool = Tc.Module.extend({
onBinding: function() {
var that = this;
$('button',that.$ctx).on('click',function(){
var name = $(this).attr('data-name');
if (name.split.length > 1)
var url = "api/tools/"+name+"/"+$('#'+name).val();
$.ajax({
url: url,
context: document.body
}).done(function(data) {
$.each(data, function(key, value) {
$("."+name+"_result",that.$ctx).html(value).removeClass('empty');
});
});
});
}
});
})(Tc.$);
| beatgeb/Tools | public/modules/Tool/js/Tc.Module.Tool.js | JavaScript | mit | 849 |
const User = require('../models/user');
const api = require('../index');
const db = require('mongoose');
describe('api tests', () => {
beforeAll(function connectDB(done) {
require('./connectTestDB')(done);
});
const testUser = {
username: 'hi',
email: "123@me.com",
password: "freedom",
confirm: "freedom"
};
describe('registration', () => {
let regResult = {};
beforeAll(function (done) {
User.collection.drop(
function (err, res) {
if (err && err.message !== 'ns not found') throw err;
api.register(
testUser,
function (err, result) {
if (err) throw err;
regResult = result;
done();
});
});
});
test('register success', () => expect(regResult.success).toBe(true));
test('has a user', () => expect(regResult.user).toBeDefined());
test('user is right', () => {
expect(regResult.user.username).toBe(testUser.username);
expect(regResult.user.email).toBe(testUser.email);
expect(regResult.user.password).toBe(testUser.password);
});
});
describe('authentication', () => {
let authResult = {};
beforeAll(function (done) {
api.authenticate(testUser.email, testUser.password, function (err, res) {
authResult = res;
done();
});
});
test('log in success', () => expect(authResult.success).toBe(true));
test('has a user', () => expect(authResult.user).toBeDefined());
});
describe("find user by email", () => {
let optResult = {};
beforeAll(done => {
api.findUserByEmail(testUser.email, res => {
optResult = res;
done();
});
});
it("should found the user", () => {
expect(optResult.success).toBe(true);
expect(optResult.user.email === testUser.email);
});
});
afterAll(function disconnectDB(done) {
db.disconnect(function (err) {
if (err) throw err;
done();
});
});
}); | gespiton/typingFun | membership/__tests__/api_spec.js | JavaScript | mit | 2,009 |
import {ImageInput} from '../../../../src'
import {mockUploadImage, mockMaterializeReference} from './mock/uploader'
export default ImageInput.create({
upload: mockUploadImage,
materializeReference: mockMaterializeReference
})
| VegaPublish/vega-studio | packages/@lyra/form-builder/examples/schema-testbed/components/custom/MyCustomImageInput.js | JavaScript | mit | 232 |
define({
"_widgetLabel": "가시성",
"observerLocation": "관찰자 위치",
"formatIconTooltip": "입력 형식 지정",
"addPointToolTip": "관찰자 위치 추가",
"fieldOfView": "시야각",
"useMilsText": "각도에 밀 사용",
"observerHeight": "관찰자 높이",
"minObsDistance": "관찰 가능한 최소 거리",
"maxObsDistance": "관찰 가능한 최대 거리",
"taskURLError": "연결할 수 없는 URL이 위젯 구성 파일에 포함되어 있습니다. 시스템 관리자에게 문의하세요.",
"taskURLInvalid": "이 위젯으로 구성된 지오프로세싱 작업이 올바르지 않습니다. 시스템 관리자에게 문의하세요.",
"viewshedError": "가시성을 생성하는 중 오류가 발생했습니다. 관찰자 위치가 고도 표면 범위에 속해 있는지 확인하세요.</p>",
"validationError": "<p>가시성 생성 양식의 매개변수가 누락되었거나 올바르지 않습니다. 다음을 확인하세요.</p><ul><li>관찰자 위치가 설정되어 있습니다.</li><li>관찰자 시야각이 0이 아닙니다.</li><li>관찰자 높이의 값이 올바릅니다.</li><li>관찰 가능한 최소 및 최대 거리의 값이 올바릅니다.</li></ul>",
"comfirmInputNotation": "입력 표기 확인",
"notationsMatch": "입력과 일치하는 표기입니다. 사용할 항목을 확인하세요.",
"createBtn": "생성",
"clearBtn": "지우기",
"setCoordFormat": "좌표 형식 문자열 설정",
"prefixNumbers": "양수와 음수에 '+/-' 접두사 추가",
"parseCoordinatesError": "좌표를 분석할 수 없습니다. 입력을 확인하세요.",
"cancelBtn": "취소",
"applyBtn": "적용",
"invalidMessage": "숫자 값을 입력하세요.",
"observerRangeMessage": "관찰자 높이가 유효하지 않음",
"minimumRangeMessage": "관찰 가능한 최소 범위가 유효하지 않음",
"maximumRangeMessage": "관찰 가능한 최대 범위는 관찰 가능한 최소 범위보다 커야 하며 ${limit}${units}을(를) 초과할 수 없습니다.",
"portalURLError": "ArcGIS Online 기관 또는 Portal for ArcGIS의 URL이 구성되지 않았습니다. 시스템 관리자에게 문의하세요.",
"privilegeError": "귀하의 사용자 역할은 분석을 수행할 수 없습니다. 분석을 수행하려면 내 기관의 관리자가 특정 <a href=”http://doc.arcgis.com/en/arcgis-online/reference/roles.htm” target=”_blank”>권한</a>을 부여해야 합니다.",
"noServiceError": "고도 분석 서비스를 사용할 수 없습니다. ArcGIS Online 기관 또는 Portal for ArcGIS의 구성을 확인하세요.",
"pointToolTooltip": "관찰자 위치를 추가하려면 클릭",
"degreesLabel": "도",
"milsLabel": "밀",
"DD": "DD",
"DDM": "DDM",
"DMS": "DMS",
"DDRev": "DDRev",
"DDMRev": "DDMRev",
"DMSRev": "DMSRev",
"USNG": "USNG",
"MGRS": "MGRS",
"UTM_H": "UTM(H)",
"UTM": "UTM",
"GARS": "GARS",
"GEOREF": "GEOREF",
"DDLatLongNotation": "십진수(DD) - 위도/경도",
"DDLongLatNotation": "십진수(DD) - 경도/위도",
"DDMLatLongNotation": "도-소수-분 - 위도/경도",
"DDMLongLatNotation": "도-소수-분 - 경도/위도",
"DMSLatLongNotation": "도-분-초 - 위도/경도",
"DMSLongLatNotation": "도-분-초 - 경도/위도",
"GARSNotation": "GARS",
"GEOREFNotation": "GEOREF",
"MGRSNotation": "MGRS",
"USNGNotation": "USNG",
"UTMBandNotation": "UTM - 밴드 문자",
"UTMHemNotation": "UTM - 반구(N/S)",
"mainPageTitle": "방사형 가시선",
"resultsTitle": "결과",
"publishBtnLabel": "발행",
"layerName": "발행된 레이어 이름",
"invalidLayerName": "레이어 이름에는 영숫자 문자와 밑줄만 포함해야 함",
"missingLayerName": "레이어 이름 입력",
"back": "돌아가기",
"publishingFailedLayerExists": "발행 실패: 이름이 {0}인 피처 서비스가 이미 있습니다. 다른 이름을 선택하세요.",
"checkService": "서비스 확인: [0]",
"createService": "서비스 생성: [0]",
"unableToCreate": "생성할 수 없음: {0}",
"addToDefinition": "정의에 추가: {0}",
"successfullyPublished": "웹 레이어가 발행되었음{0}웹 레이어 관리",
"userRole": "사용자에게 권한이 없어 서비스를 생성할 수 없음",
"publishToNewLayer": "새 피처 레이어에 결과 발행",
"missingLayerNameMessage": "발행하려면 먼저 올바른 레이어 이름을 입력해야 함",
"regionTypeLabel": "지역 유형",
"centerPointLabel": "중심점",
"observationHeightLabel": "관측 높이",
"heightUnitLabel": "높이 단위",
"minObservationDistanceLabel": "최소 관측 거리",
"maxObservationDistance": "최대 관측 거리",
"distanceUnitLabel": "거리 단위",
"fovstartAngleLabel": "FOV 시작 각",
"fovEndAngleLabel": "FOV 끝 각",
"andleUnitsLabel": "각도 단위"
}); | tmcgee/cmv-wab-widgets | wab/2.15/widgets/Visibility/nls/ko/strings.js | JavaScript | mit | 4,936 |
'use strict'
const AARectangle = require('../lib/aa-rectangle')
const expect = require('chai').expect
const now = require('performance-now')
describe('AARectangle', function () {
describe('constructor', function () {
it('initializes with default options', function () {
let box = new AARectangle()
expect(box.width).to.equal(1)
expect(box.height).to.equal(1)
expect(box.x).to.equal(0)
expect(box.y).to.equal(0)
})
it('initializes with given options', function () {
let box = new AARectangle(1, 2, 3, 4)
expect(box.width).to.equal(1)
expect(box.height).to.equal(2)
expect(box.x).to.equal(3)
expect(box.y).to.equal(4)
})
})
describe('#add', function () {
let parent = new AARectangle()
let child = new AARectangle()
parent.add(child)
it('sets parent box', function () {
expect(child.parent).to.equal(parent)
})
})
describe('#width/height', function () {
it('converts negative values to zero', function () {
let box = new AARectangle(-10, -20, 0, 0)
expect(box.width).to.equal(0)
expect(box.height).to.equal(0)
})
})
describe('#update', function () {
let box1 = new AARectangle(1, 1, 0, 0)
let box2 = new AARectangle(2, 2, 10, -20)
let box3 = new AARectangle(3, 3, -2, 4)
let box4 = new AARectangle(4, 4, 4, -8)
let box5 = new AARectangle(5, 5, 2, -2)
box1.add(box2)
box2.add(box3)
box3.add(box4)
box4.add(box5)
it('runs for less than 10 nanoseconds', function () {
let box2 = new AARectangle(2, 2, 10, -20)
let box3 = new AARectangle(3, 3, -2, 4)
this.retries(10) // allows engine to optimize
box2.flipX()
box3.flipY()
let time1, time2, i
for (i = 0; i < 10; ++i) {
time1 = now()
box4.update()
time2 = now()
expect(time2 - time1).to.be.at.most(0.01)
}
box2.unflipX()
box3.unflipY()
})
it('sets globals without orientation or translation', function () {
box1.update()
expect(box1.globalX).to.equal(0)
expect(box1.globalY).to.equal(0)
box2.update()
expect(box2.globalX).to.equal(10)
expect(box2.globalY).to.equal(-20)
box3.update()
expect(box3.globalX).to.equal(8)
expect(box3.globalY).to.equal(-16)
box4.update()
expect(box4.globalX).to.equal(12)
expect(box4.globalY).to.equal(-24)
box5.update()
expect(box5.globalX).to.equal(14)
expect(box5.globalY).to.equal(-26)
})
it('sets globals with translation', function () {
box1.translateX = 1
box1.translateY = -1
box1.update()
expect(box1.globalX).to.equal(0)
expect(box1.globalY).to.equal(0)
box2.translateX = 2
box2.translateY = -2
box2.update()
expect(box2.globalX).to.equal(11)
expect(box2.globalY).to.equal(-21)
box3.translateX = 3
box3.translateY = -3
box3.update()
expect(box3.globalX).to.equal(11)
expect(box3.globalY).to.equal(-19)
box4.translateX = 4
box4.translateY = -4
box4.update()
expect(box4.globalX).to.equal(18)
expect(box4.globalY).to.equal(-30)
box5.update()
expect(box5.globalX).to.equal(24)
expect(box5.globalY).to.equal(-36)
box1.translateX = 0
box1.translateY = 0
box2.translateX = 0
box2.translateY = 0
box3.translateX = 0
box3.translateY = 0
box4.translateX = 0
box4.translateY = 0
box5.translateX = 0
box5.translateY = 0
})
it('sets globals with orientation and translation', function () {
box1.translateX = 1
box1.translateY = -1
box2.flipX()
box2.update()
expect(box2.globalX).to.equal(11)
expect(box2.globalY).to.equal(-21)
box3.update()
expect(box3.globalX).to.equal(13)
expect(box3.globalY).to.equal(-17)
box4.update()
expect(box4.globalX).to.equal(9)
expect(box4.globalY).to.equal(-25)
box5.flipX()
box5.update()
expect(box5.globalX).to.equal(7)
expect(box5.globalY).to.equal(-27)
box2.unflipX()
box5.unflipX()
box1.translateX = 0
box1.translateY = 0
})
it('sets segments (X1-X2/Y1-Y2) according to width/height and translation', function () {
box1.update()
expect(box1.globalX1).to.equal(-0.5)
expect(box1.globalX2).to.equal(0.5)
expect(box1.globalY1).to.equal(-0.5)
expect(box1.globalY2).to.equal(0.5)
box2.update()
expect(box2.globalX1).to.equal(9)
expect(box2.globalX2).to.equal(11)
expect(box2.globalY1).to.equal(-21)
expect(box2.globalY2).to.equal(-19)
box2.translateX = 1
box2.update()
expect(box2.globalX1).to.equal(10)
expect(box2.globalX2).to.equal(12)
box1.translateX = 1
box2.update()
expect(box2.globalX1).to.equal(11)
expect(box2.globalX2).to.equal(13)
})
})
describe('#collision', function () {
it('returns true if a box is completely inside another', function () {
let box1 = new AARectangle(100, 100, 1, 1)
let box2 = new AARectangle(2, 2, -40, -40)
expect(box1.collision(box2)).to.equal(true)
})
it('returns true if sides and bases touch', function () {
let box1 = new AARectangle(2, 2, 1, 1)
let box2 = new AARectangle(2, 2, -1, -1)
expect(box1.collision(box2)).to.equal(true)
})
it('returns false if bases touch but sides do not', function () {
let box1 = new AARectangle(2, 2, 3, 1)
let box2 = new AARectangle(2, 2, -1, -1)
expect(box1.collision(box2)).to.equal(false)
})
it('returns false if sides touch but bases do not', function () {
let box1 = new AARectangle(2, 2, 1, 3)
let box2 = new AARectangle(2, 2, -1, -1)
expect(box1.collision(box2)).to.equal(false)
})
describe('with parent', function () {
it('returns true if box is dragged towards another by parent position', function () {
let parent = new AARectangle(0, 0, 0, 2)
let box1 = new AARectangle(2, 2, 1, 3)
let box2 = new AARectangle(2, 2, -1, -1)
expect(box1.collision(box2)).to.equal(false)
parent.add(box2) // parent position will bring box2 closer to box1
expect(box1.collision(box2)).to.equal(true)
})
it('returns true if box is dragged towards another by parent translation', function () {
let parent = new AARectangle(0, 0, 0, 0)
let box1 = new AARectangle(2, 2, 1, 3)
let box2 = new AARectangle(2, 2, -1, -1)
expect(box1.collision(box2)).to.equal(false)
parent.add(box2)
expect(box1.collision(box2)).to.equal(false)
parent.translateY = 2 // parent translation will bring box2 closer to box1
expect(box1.collision(box2)).to.equal(true)
})
})
})
})
| pauloddr/aa-rectangle-javascript | test/aa-rectangle.js | JavaScript | mit | 6,913 |
angular.module('tf-client')
.config(function($stateProvider){
$stateProvider.state('invitationDetails', {
url: '/invitation-details?id',
params: {
alert: undefined,
id: undefined
},
templateUrl: '/components/tasker/invitation-details/invitation-details.html',
controller: 'InvitationDetailsCtrl as details'
})
});
| talosdigital/TaskFlex | frontend/app/components/tasker/invitation-details/invitation-details.conf.js | JavaScript | mit | 350 |
var express = require('express');
var Debugger = require('../');
var app = module.exports = express();
var debug = new Debugger(app, 'development');
app.engine('.html', require('ejs').__express);
app.set('port', process.env.PORT || 5000);
app.set('views', __dirname + '/views');
app.set('view engine', 'html');
app.get('/', function(req, res){
res.render('index');
});
debug.start(); | zack-lin/mobile-debugger | example/server.js | JavaScript | mit | 388 |
import { ADD_EVENT, SET_EVENTS } from '../constants/ActionTypes';
const events = (state = {events: []}, action) => {
switch (action.type) {
case ADD_EVENT:
return {
events: [...state.events, action.event]
}
case SET_EVENTS:
return {
events: [...state.events, ...action.events]
}
default:
return state;
}
}
export default events;
export const getAllEvents = (state) => (state.events || []); | fredmarques/petshop | src/reducers/events.js | JavaScript | mit | 511 |
var through = require('through2')
module.exports = function (file) {
return through(function (buf, enc, next) {
var contents = buf.toString('utf8')
contents = contents.replace(/^.*utilise\/client[^]*?var (.*) = _interop.*$/gm, '')
contents = contents.replace(/_client2.default/gm, 'true')
contents = contents.replace(/require\('utilise\/client'\)/gi, 'true')
// TODO minify only
// remove log statements
// contents = contents.replace(/log = require\(([^,]*)/gm, 'log = require("utilise/identity")')
// contents = contents.replace(/err = require\(([^,]*)/gm, 'err = require("utilise/identity")')
// contents = contents.replace(/(0, _group2.default)/gm, '(function(_,f){f()})')
this.push(contents)
next()
})
} | lems111/bittrex-node-client | node_modules/rijs/clientify.js | JavaScript | mit | 779 |
/**
* @author Bilal Cinarli
*/
var expect = chai.expect;
describe('Testing UX Rocket Accordion', function() {
describe('Properties', function() {
it('should have version property', function() {
expect($.uxrcollapsible).to.have.property('version');
});
});
}); | uxrocket/uxrocket.accordion | test/tests.js | JavaScript | mit | 299 |
(function () {
'use strict';
var pubKeyManager = angular.module('PubKeyManager');
pubKeyManager.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {
$routeProvider
.when('/login', {
templateUrl: '/login.tpl',
controller: 'LoginCtrl',
})
.when('/register', {
templateUrl: '/register.tpl',
controller: 'RegisterCtrl',
})
.when('/', {
templateUrl: '/keylist.tpl',
controller: 'KeylistCtrl',
requireLogin: true
});
$routeProvider.otherwise('/login');
}]);
pubKeyManager.run(["$rootScope", "$location", "backendService",
function ($rootScope, $location, backendService) {
$rootScope.$on("$routeChangeStart", function (event, next, current) {
if (next.requireLogin && !backendService.getAuthenticatedUser()) {
$location.path('/login');
}
});
}]);
})(); | GerardSoleCa/PubKeyManager | public/assets/js/configs/routes.config.js | JavaScript | mit | 1,077 |
import { babel } from '../../package'
export default [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
loader: 'babel',
query: {
cacheDirectory: true,
plugins: babel.plugins,
presets: babel.presets,
env: {
development: {
plugins: [
[ 'react-transform', {
// omit HMR plugin by default and _only_ load in hot mode
transforms: [ {
transform: 'react-transform-catch-errors',
imports: [ 'react', 'redbox-react' ]
} ]
} ]
]
}
}
}
}
]
| shastajs/boilerplate | webpack/loaders/js.js | JavaScript | mit | 618 |
var fs = require("fs");
var path = require("path");
var cheerio = require("cheerio");
var escape = require('escape-html');
var Views = {
name: "Tabell, smal",
description: "Smal tabell som är högerjusterad",
getEditor: function(item) {
var editorTemplate = fs.readFileSync(__dirname + "/editor.html", "utf8");
for (var key in item) {
var find = new RegExp("{" + key + "}", "g");
editorTemplate = editorTemplate.replace(find, item[key]);
}
//Specific tags
var findNumber = new RegExp("edit:" + item.name + ":number:value", "g");
editorTemplate = editorTemplate.replace(findNumber, escape(item.content.number));
var findText = new RegExp("edit:" + item.name + ":text:value", "g");
editorTemplate = editorTemplate.replace(findText, escape(item.content.text));
var findTitle = new RegExp("edit:" + item.name + ":title:value", "g");
editorTemplate = editorTemplate.replace(findTitle, escape(item.content.title));
var findId = new RegExp("edit:" + item.name + ":id:value", "g");
editorTemplate = editorTemplate.replace(findId, escape(item.content.id));
return editorTemplate;
},
getOutput: function(item) {
var output = fs.readFileSync(__dirname + "/output.html", "utf8");
output = output.replace(new RegExp("{number}", "g"), item.content.number);
//Fix id
if (item.content.id !== "" && item.content.id !== "undefined" && item.content.id !== undefined) {
output = output.replace(new RegExp("{id}", "g"), " id=\"" + item.content.id + "\"");
} else {
output = output.replace(new RegExp("{id}", "g"), " id=\"table_" + item.content.number + "_header\"");
}
if (item.content.title && item.content.title !== "") {
var resultHtml = item.content.title;
//Determine based on settings if any postprocessing should be omitted for the current item
if (!(item.settings.postprocessors && item.settings.postprocessors["genericas.js"] === "true")) {
resultHtml = require("../../postprocessors/genericas.js").process(resultHtml);
}
if (!(item.settings.postprocessors && item.settings.postprocessors["boxlinks.js"] === "true")) {
resultHtml = require("../../postprocessors/boxlinks.js").process(resultHtml);
}
if (!(item.settings.postprocessors && item.settings.postprocessors["references.js"] === "true")) {
resultHtml = require("../../postprocessors/references.js").process(resultHtml);
}
if (!(item.settings.postprocessors && item.settings.postprocessors["pagefootnotes.js"] === "true")) {
resultHtml = require("../../postprocessors/pagefootnotes.js").process(resultHtml);
}
output = output.replace(new RegExp("{title}", "g"), resultHtml);
} else {
output = output.replace(new RegExp("{title}", "g"), "");
}
var $ = cheerio.load(item.content.text);
//Count max columns in a row
var maxColumns = 1;
var table = $("table").first();
if (table.length === 1) {
table.find("tr").each(function(index, element) {
var tr = $(element);
var rowColumns = 0;
tr.find("td").each(function(i, e) {
if ($(e).attr("colspan") !== undefined) {
rowColumns += parseInt($(e).attr("colspan"));
} else {
rowColumns++;
}
});
if (rowColumns > maxColumns) {
maxColumns = rowColumns;
}
});
}
output = output.replace(new RegExp("{columns}", "g"), maxColumns);
var resultHtml = "<tr><td>" + item.content.text + "</td></tr>";
if (table.length === 1) {
//Render only <tbody> contents
resultHtml = $("tbody").first().html();
}
//Determine based on settings if any postprocessing should be omitted for the current item
if (!(item.settings.postprocessors && item.settings.postprocessors["genericas.js"] === "true")) {
resultHtml = require("../../postprocessors/genericas.js").process(resultHtml);
}
if (!(item.settings.postprocessors && item.settings.postprocessors["boxlinks.js"] === "true")) {
resultHtml = require("../../postprocessors/boxlinks.js").process(resultHtml);
}
if (!(item.settings.postprocessors && item.settings.postprocessors["references.js"] === "true")) {
resultHtml = require("../../postprocessors/references.js").process(resultHtml);
}
if (!(item.settings.postprocessors && item.settings.postprocessors["pagefootnotes.js"] === "true")) {
resultHtml = require("../../postprocessors/pagefootnotes.js").process(resultHtml);
}
output = output.replace(new RegExp("{text}", "g"), resultHtml);
return output;
},
preProcess: function(item, id) {
//Remove the actual links to self and keep only the hash
if (!(item.settings.preprocessors && item.settings.preprocessors["fixlinkstoself.js"] === "true")) {
item.content.text = require(path.join(__dirname, "..", "..", "preprocessors", "fixlinkstoself.js")).process(item.content.text, id);
}
return item;
},
getDefaultType: function() {
return JSON.parse(fs.readFileSync(__dirname + "/default.json"));
}
};
module.exports = Views; | lakemedelsboken/LB | servers/cms/contenttypes/tablenarrow/views.js | JavaScript | mit | 4,923 |
if (require !== 'undefined') {
var d3 = require('d3');
}
var Graph = {};
/*--------------------------------------
colors
http://www.nytimes.com/interactive/2012/11/30/us/tax-burden.html?_r=1&
---------------------------------------*/
Graph.setColor = function (color) {
var switchObj = {
"blue": {
lineColor: '#1f77b4',
areaColor: '#1f77b4'
// lineColor: 'steelblue',
// areaColor: 'lightsteelblue'
},
"red": {
lineColor: '#d62728',
areaColor: '#d62728'
},
"orange": {
lineColor: '#ff7f0e',
areaColor: '#ff7f0e'
},
"green": {
lineColor: '#2ca02c',
areaColor: '#2ca02c'
}
};
return switchObj[color] || switchObj.blue;
};
Graph.setMultipliers = function (widthContainerActual) {
var switchObj = {
"a": {
heightDivisor: 1.8,
axisMultiplier: {
x: 0.20,
y: 0.20
// y: 0.17
// y: 0.14
}
},
"b": {
heightDivisor: 2,
axisMultiplier: {
x: 0.14,
y: 0.12
}
},
"c": {
heightDivisor: 2,
axisMultiplier: {
x: 0.11,
y: 0.08
}
},
// default = 1200 if greater than 800
"default": {
heightDivisor: 2,
axisMultiplier: {
x: 0.09,
y: 0.06
}
}
}, multipliers = switchObj["default"];
// console.log("widthContainerActual:" + widthContainerActual);
// need less height + bigger margins on small screens
if (widthContainerActual < 520) {
multipliers = switchObj["a"];
(widthContainerActual > 400) && (multipliers.axisMultiplier.y = 0.14);
} else {
if (widthContainerActual < 1100) {
multipliers = (widthContainerActual < 880) ? switchObj["b"] : switchObj["c"];
// multipliers = (widthContainerActual < 720) ? switchObj["b"] : switchObj["c"];
}
}
return multipliers;
};
Graph.setOpts = function () {
var insetAxisLabels = this.get('insetAxisLabels'),
insetYLabel = insetAxisLabels && insetAxisLabels.indexOf('y') !== -1,
el = this.get('el');
// check if el is a DOM node or not
if (!el.nodeType) {
el = d3.select(this.get('el'));
}
return this.set({
'insetYLabel': insetYLabel,
'el': el,
'alreadyInserted': el && el.children && el.children.length
});
};
Graph.setDimensions = function () {
var buffer = 0.05,
widthContainerActual = parseInt(this.get('width') || this.get('el').style('width'), 10),
// widthContainerActual = parseInt(this.get('width') || d3.select(this.get('el')).style('width'), 10),
svgWidth = widthContainerActual,
widthContainer = parseFloat((widthContainerActual * (1 - buffer))),
svgLeft = (this.get('centerGraph')) ? widthContainer * (buffer / 2) : 0,
multipliers = this.setMultipliers(widthContainerActual),
heightContainer = this.get('height') || (widthContainer / multipliers.heightDivisor),
yAxisMultiplier = (this.get('insetYLabel')) ? multipliers.axisMultiplier.y / 2 : multipliers.axisMultiplier.y,
xAxisMultiplier = (this.get('xAxisLabelClasses')) ? multipliers.axisMultiplier.x / 2 : multipliers.axisMultiplier.x,
yAxisWidth = widthContainer * yAxisMultiplier,
xAxisHeight = heightContainer * xAxisMultiplier,
// reduce graph width by same amount as transform + 0.5 to stop antialiasing - 20 for 1/2 a label width
graphWidth = widthContainerActual - yAxisWidth + 0.5 - 18,
// reduce graph height by same amount as transform
graphHeight = heightContainer - (xAxisHeight * 2),
dimensions = {
widthContainerActual: widthContainerActual,
graphWidth: (widthContainerActual < 380) ? graphWidth : graphWidth - 10,
svgWidth: svgWidth,
graphHeight: graphHeight,
yAxisWidth: yAxisWidth,
xAxisHeight: xAxisHeight,
svgLeft: svgLeft,
svgHeight: heightContainer,
gradientStyle: 'url("#'+ this.get('gradientId') + '")'
};
return this.set(dimensions);
};
/*--------------------------------------
Exports
---------------------------------------*/
if (module !== 'undefined' && module.exports) {
module.exports = Graph;
} | techjacker/d3base | lib/setup.js | JavaScript | mit | 3,979 |
/**
* Created by G on 28-11-2016.
*/
Array.prototype.sum = Array.prototype.sum || function () {
return this.reduce(function (sum, a) {
return sum + Number(a)
}, 0);
}
Array.prototype.average = Array.prototype.average || function () {
return this.sum() / (this.length || 1);
}
var ws = new WebSocket('ws://20.0.0.112:3030');
var currentValues = {
'a0': {raw: {data: 0}, avg: [0, 0, 0, 0, 0], avgValue: 0}
};
ws.onopen = function () {
$('#websocket_conn_status_container_id').removeClass('websocket-not-connected');
$('#websocket_conn_status_container_id').addClass('websocket-connected');
};
ws.onclose = function () {
$('#websocket_conn_status_container_id').removeClass('websocket-connected');
$('#websocket_conn_status_container_id').addClass('websocket-not-connected');
};
ws.onmessage = function (payload) {
var data = '';
try {
data = JSON.parse(payload.data);
} catch (e) {
data = payload.data;
}
// console.log(typeof data);
if (typeof data === 'object') {
updateStatus(data);
// updateGraph(data);
} else {
console.log('uno.js::ws.onmessage: ' + data);
}
};
$(function () {
console.log('Uno loaded');
// $('#update_status_btn_id').on('click', function (e) {
// $.getJSON('api', updateStatus);
// });
//
// $('#update_item_5_value_btn_id').on('click', function (e) {
// var item_id = this.id.split('_')[2];
// var item_value = $('#item_input_field_id').val();
//
// if (item_value) {
// $.getJSON('api/' + item_id + '/' + item_value, updateItemValue);
// } else {
// alert('The new value can\'t be empty!!');
// }
// });
//
$('#ws_close_btn_id').on('click', function (e) {
ws.send('exit');
});
//
// $('#start_chopper_btn_id').on('click', function (e) {
// $.post('api', {
// command: 'start motor',
// value: 150
// }, updateCommandFeedback);
// });
//
// $('#set_chopper_btn_id').on('click', function (e) {
// $.post('api', {
// command: 'set motor',
// value: $('#set_chopper_value_input_field_id').val()
// }, updateCommandFeedback);
// });
//
// $('#stop_chopper_btn_id').on('click', function (e) {
// $.post('api', {
// command: 'stop motor',
// value: 150
// }, updateCommandFeedback);
// });
//
// $('#test_chopper_btn_id').on('click', function (e) {
// $.post('api', {
// command: 'test motor',
// value: 100
// }, updateCommandFeedback);
// });
// $.getJSON('api', updateStatus);
});
function updateCommandFeedback(data) {
console.log({location: 'control.js::updateCommandFeedback (data): ', msg: data});
$('#command_feedback_field_id').text(data.msg);
}
function updateStatus(data) {
if (data.item) {
currentValues[data.item].raw = data;
currentValues[data.item].avg.push(data.data);
currentValues[data.item].avg.shift();
currentValues[data.item].avgValue = currentValues[data.item].avg.average();
$('#' + data.item + '_current_value_field_id').text('(' + temp2(data.data) + ')');
}
}
function temp2(raw) {
var rSense = 63800;
var rRef = 75000; // gues ;)
var r = (raw / ((1023 - raw) / rSense)) - 150;
var A1 = 3.354016E-03;
var B1 = 2.460382E-04;
var C1 = 3.405377E-06;
var D1 = 1.034240E-07;
var lr = Math.log(r/rRef);
var t = 1 / (A1 + B1 * lr + C1 * lr * lr + D1 * lr * lr *lr);
var t = t - 273.15;
return t.toFixed(2);
}
| gjgjwmertens/ATI | public/js/uno.js | JavaScript | mit | 3,723 |
'use strict';
import assert from 'yeoman-assert';
export default ({
website,
graphql,
server
}) => {
it('.babelrc', () => {
let presets = [
'env',
'stage-0'
];
let plugins = [
'transform-object-assign',
['module-resolver', {
root: ['./src']
}]
];
const alias = {
utils: 'utils'
};
if(website) {
presets = [
'react',
...presets
];
plugins = [
'transform-decorators-legacy',
...plugins
];
alias.public = 'public';
alias.components = 'components';
alias.componentsShare = 'components/share';
if(graphql) {
plugins = [
'relay',
...plugins
];
alias.containers = 'containers';
}
}
if(server) {
alias.routers = 'routers';
if(graphql)
alias.schemas = 'schemas';
}
assert.jsonFileContent('package.json', {
scripts: {
babel: 'rm -rf ./lib && babel src --out-dir lib --ignore __tests__',
'babel:watch': 'rm -rf ./lib && babel -w src --out-dir lib --ignore __tests__'
}
});
assert.jsonFileContent('.babelrc', {presets});
assert.jsonFileContent('.babelrc', {plugins});
assert.jsonFileContent('.babelrc', {
plugins: [
...plugins.slice(0, plugins.length - 1),
['module-resolver', {
alias
}]
]
});
});
};
| HsuTing/generator-cat | __tests__/files/babel/babelrc.js | JavaScript | mit | 1,439 |
/*
* Represents a Student. Has a one-to-one mapping to the User table (i.e. a
* student must be a user, but a user does not need to be a student).
*/
module.exports = (sequelize, DataTypes) => sequelize.define('Student', {
id: {
primaryKey: true,
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
},
studyLevel: {
type: DataTypes.STRING,
allowNull: true,
},
degree: {
type: DataTypes.STRING,
allowNull: true,
},
photoUrl: {
type: DataTypes.TEXT,
allowNull: true,
},
firstLaunch: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: true,
},
}, {
timestamps: true,
});
| unihackhq/skilled-acolyte-backend | app/models/Student.js | JavaScript | mit | 651 |
function ready() {
$('#review_rating, .modal-review-rating').each(function() {
$(this).barrating({
theme: 'fontawesome-stars',
hoverState: true
});
});
$('.review-rate').barrating({
theme: 'fontawesome-stars-o',
readonly: true
});
$('.avg-rating').barrating({
theme: 'fontawesome-stars-o',
readonly: true,
initialRating: $('.avg-rating').data('rating-cache')
});
}
$(document).ready(ready);
$(document).on('turbolinks:load', ready);
| JakubKopysDev/RailsShop | app/assets/javascripts/products.js | JavaScript | mit | 488 |
function isPrimitive(valueToCheck) {
return valueToCheck === null || typeof valueToCheck !== `object`;
}
function flattenObject(objectToVisit, separator = `_`, flattenedObject = {}, keyBeingBuilt = ``, currentKey = ``) {
if (currentKey !== ``) {
keyBeingBuilt = `${keyBeingBuilt}${keyBeingBuilt !== `` ? separator : ``}${currentKey}`;
}
Object.keys(objectToVisit)
.forEach(key => {
if (!isPrimitive(objectToVisit[key])) {
flattenObject(objectToVisit[key], separator, flattenedObject, keyBeingBuilt, key);
} else {
let flattenedKey = keyBeingBuilt !== `` ? `${keyBeingBuilt}${separator}${key}` : key;
flattenedObject[flattenedKey] = objectToVisit[key];
}
});
return flattenedObject;
}
/**
* Flattens an object. Keys within the object become flattened as well.
*
* @param {object} objectToFlatten The object to flatten.
* @param {string} [separator=_] The separator for keys when flattening a key.
*
* @return {object} The flattened object.
*/
function flatten(objectToFlatten, separator = `_`) {
if (isPrimitive(objectToFlatten)) {
return objectToFlatten;
}
return flattenObject(objectToFlatten, separator);
}
export default flatten;
| nickytonline/b-flat | src/flatten.js | JavaScript | mit | 1,224 |
Array.max = function( array ){
return Math.max.apply( Math, array );
};
Array.min = function( array ){
return Math.min.apply( Math, array );
};
/********************* Convolucion **********************/
//Imagen original de muestra
var canvas1 = document.getElementById('canvas1');
var canvas2 = document.getElementById('canvas2');
var canvas3 = document.getElementById('canvas3');
var img = new Image();
img.src = './../../images/lenna256.jpg';
var ak = AkLoadImage(img,LOAD_IMAGE_GRAYSCALE);
//Grey Scale
AkLoadOnCanvas(ak,canvas1);
//Separar los dos primeros canales
var AkFFT= AkDFT(ak,DXT_FORWARD,false);
Arrays = AkSplit(AkFFT);
var _real = Arrays[0];
var _imag = Arrays[1];
for (var k = 0;k<_real.length;k++){
_real[k] = Math.log(
Math.sqrt(
(_real[k]*_real[k] + _imag[k]*_imag[k])
)+0.1
)/Math.log(10);
}
var Magnitud = AkCreateImage([256,256],DEPTH_32F,1);
AkMerge(_real,_real,_real,0,Magnitud);
AkLoadOnCanvas(Magnitud,canvas2);
AkFFT= AkDFT(AkFFT,DXT_INVERSE,false);
var Arrays = AkSplit(AkFFT);
_real = Arrays[0];
var Ak_inverted = AkCreateImage([256,256],32,1);
AkMerge(_real,_real,_real,0,Ak_inverted);
//RGB
//
AkLoadOnCanvas(Ak_inverted,canvas3);
| alefortvi/akimagejs | Demos/Modules/js/AkDFT.js | JavaScript | mit | 1,238 |
let map = new WeakMap();
/** Class representing a first-in-first-out (FIFO) queue of elements. */
export class Queue {
/**
* Creates a queue.
*/
constructor() {
map.set(this, []);
}
/**
* Get a string representation of queue.
* @returns {string} The string representation of queue.
*/
toString() {
let queue = map.get(this);
return queue.toString();
}
/**
* Removes the first element from the queue.
* @returns {*} Element removed from queue.
*/
dequeue() {
let queue = map.get(this);
return queue.shift();
}
/**
* Places an element onto queue.
* @param {*} element - Element to be added to queue.
*/
enqueue(element) {
let queue = map.get(this);
queue.push(element);
}
/**
* Gets the size of queue.
* @returns {number} The size of queue.
*/
size() {
let queue = map.get(this);
return queue.length;
}
/**
* Checks whether queue is empty.
* @returns {boolean} True if empty, false if not.
*/
isEmpty() {
let queue = map.get(this);
return queue.length === 0;
}
/**
* Gets first element of queue without removing it.
* @returns {*} First element of queue.
*/
front() {
let queue = map.get(this);
return queue[0];
}
/**
* Removes all elements from queue.
*/
clear() {
let queue = map.get(this);
queue.splice(0, queue.length);
}
}
| tsck/structd | src/structures/queue/Queue.js | JavaScript | mit | 1,408 |
/*
* Copyright (c) André Bargull
* Alle Rechte vorbehalten / All Rights Reserved. Use is subject to license terms.
*
* <https://github.com/anba/es6draft>
*/
const {
assertSyntaxError, fail
} = Assert;
// Note: break/continue are currently disallowed in loop-headers.
assertSyntaxError(`for (var k in do { break; }) ;`);
assertSyntaxError(`for (var k in do { continue; }) ;`);
assertSyntaxError(`L: for (var k in do { break L; }) ;`);
assertSyntaxError(`for (var {k = do { break; }} in []) ;`);
assertSyntaxError(`for (var {k = do { continue; }} in []) ;`);
assertSyntaxError(`L: for (var {k = do { break L; }} in []) ;`);
assertSyntaxError(`for (var k of do { break; }) ;`);
assertSyntaxError(`for (var k of do { continue; }) ;`);
assertSyntaxError(`L: for (var k of do { break L; }) ;`);
assertSyntaxError(`for (var {k = do { break; }} of []) ;`);
assertSyntaxError(`for (var {k = do { continue; }} of []) ;`);
assertSyntaxError(`L: for (var {k = do { break L; }} of []) ;`);
assertSyntaxError(`for (do { break; }; ; ) ;`);
assertSyntaxError(`for (; do { break; }; ) ;`);
assertSyntaxError(`for (; ; do { break; }) ;`);
assertSyntaxError(`for (do { continue; }; ; ) ;`);
assertSyntaxError(`for (; do { continue; }; ) ;`);
assertSyntaxError(`for (; ; do { continue; }) ;`);
assertSyntaxError(`L: for (do { break L; }; ; ) ;`);
assertSyntaxError(`L: for (; do { break L; }; ) ;`);
assertSyntaxError(`L: for (; ; do { break L; }) ;`);
assertSyntaxError(`switch (do { break; }) {}`);
assertSyntaxError(`L: switch (do { break L; }) {}`);
// break/continue in loop-header (currently) target outer loop.
do {
while (do { break; }) {
fail `unreachable`;
}
fail `unreachable`;
} while (0);
do {
while (do { continue; }) {
fail `unreachable`;
}
fail `unreachable`;
} while (0);
| anba/es6draft | src/test/scripts/suite/semantic/doExpression/invalid_break.js | JavaScript | mit | 1,811 |
var generators = require('yeoman-generator');
var path = require('path');
var _ = require('lodash');
var packages = require('./packages');
var utils = require('../lib/utils');
module.exports = generators.Base.extend({
initializing: function () {
this.pkg = this.fs.readJSON(this.destinationPath('package.json'), {});
// Pre set the default props from the information we have at this point
this.props = {
name: this.pkg.name,
description: this.pkg.description,
version: this.pkg.version,
homepage: this.pkg.homepage,
repository: this.pkg.repository
};
this.mainFiles = [
'_gitignore',
'license.md',
'readme.md',
'default/templates/file.js',
'default/index.js',
'test/index.js'
];
},
prompting: function () {
var done = this.async();
var prompts = [{
name: 'name',
message: 'Project name',
when: !this.pkg.name,
default: process.cwd().split(path.sep).pop()
}, {
name: 'description',
message: 'Description',
when: !this.pkg.description
}, {
name: 'homepage',
message: 'Project homepage url',
when: !this.pkg.homepage
}, {
name: 'githubAccount',
message: 'GitHub username or organization',
when: !this.pkg.repository
}, {
name: 'authorName',
message: 'Author\'s Name',
when: !this.pkg.author,
store: true
}, {
name: 'authorEmail',
message: 'Author\'s Email',
when: !this.pkg.author,
store: true
}, {
name: 'authorUrl',
message: 'Author\'s Homepage',
when: !this.pkg.author,
store: true
}, {
name: 'keywords',
message: 'Application keywords',
when: !this.pkg.keywords,
filter: _.words
}];
this.prompt(prompts, function (props) {
this.props = _.extend(this.props, props);
this.props.name = _.kebabCase(this.props.name);
this.props.addName = this.props.name.replace('donejs-', '');
done();
}.bind(this));
},
writing: function () {
var self = this;
this.fs.writeJSON('package.json', {
name: this.props.name,
version: '0.0.0',
description: this.props.description,
homepage: this.props.homepage,
repository: this.props.repository,
author: {
name: this.props.authorName,
email: this.props.authorEmail,
url: this.props.authorUrl
},
license: "MIT",
main: "lib/",
scripts: {
test: "npm run jshint && npm run mocha",
jshint: "jshint test/. default/index.js --config",
mocha: "mocha test/ --timeout 120000",
publish: "git push origin --tags && git push origin",
'release:patch': "npm version patch && npm publish",
'release:minor': "npm version minor && npm publish",
'release:major': "npm version major && npm publish"
},
keywords: this.props.keywords
});
var deps = utils.toNpmInstallStrings(packages.dependencies);
var devDeps = utils.toNpmInstallStrings(packages.devDependencies);
this.npmInstall(deps, { 'save': true });
this.npmInstall(devDeps, { 'saveDev': true });
this.fs.copy(this.templatePath('static'), this.destinationPath());
this.fs.copy(this.templatePath('static/.*'), this.destinationPath());
this.mainFiles.forEach(function(name) {
// Handle bug where npm has renamed .gitignore to .npmignore
// https://github.com/npm/npm/issues/3763
self.fs.copyTpl(
self.templatePath(name),
self.destinationPath((name === "_gitignore") ? ".gitignore" : name),
self.props
);
});
}
});
| retro/generator-canjs | generator/index.js | JavaScript | mit | 3,676 |
var recipeModel = require('../models/recipe');
module.exports = function (req, res, next) {
res.tpl.recipes = [];
recipeModel.find({
}).populate('_assignedto').exec(function (err, results) {
if (err) {
return next(new Error('Error getting recipes'));
}
res.tpl.recipes = results;
return next();
});
} | csutorasr/server-side-js-course | middlewares/listrecipe.js | JavaScript | mit | 362 |
/* eslint-disable no-console */
const _ = require("lodash");
const kleur = require("kleur");
const cluster = require("cluster");
const { humanize } = require("../../src/utils");
const padS = _.padStart;
const padE = _.padEnd;
const NODE_PREFIX = process.env.NODE_PREFIX || "node";
function val(value) {
if (Number.isNaN(value)) return "-";
if (value > 1000 * 1000)
return Number(value / 1000 / 1000).toFixed(0) + "M";
if (value > 1000)
return Number(value / 1000).toFixed(0) + "K";
return Number(value).toFixed(0);
}
module.exports = {
name: "nodes",
settings: {
printIO: false,
printRegistry: true
},
actions: {
scale: {
params: {
count: "number",
kill: "boolean|optional"
},
handler(ctx) {
return this.scale(ctx.params.count, { kill: !!ctx.params.kill });
}
},
},
/*events: {
"$metrics.snapshot"(ctx) {
ctx.params.map(metric => this.addMetric(metric, ctx.nodeID));
}
},*/
events: {
"$services.changed"(ctx) {
if (this.settings.printRegistry)
this.printRegistry();
},
"$node.disconnected"(ctx) {
if (this.settings.printRegistry)
this.printRegistry();
}
},
methods: {
scale(num, opts) {
if (num > this.nodes.length) {
// Start new nodes
this.logger.info(`Starting ${num - this.nodes.length} new nodes...`);
return _.times(num - this.nodes.length, () => this.startNewNode(this.getNextNodeID()));
} else if (num < this.nodes.length && num >= 0) {
// Stop random nodes
this.logger.info(`Stopping ${this.nodes.length - num} nodes...`);
const tmp = Array.from(this.nodes);
return _.times(this.nodes.length - num, () => {
const idx = _.random(tmp.length - 1);
const node = tmp.splice(idx, 1)[0];
if (opts.kill)
return this.killNode(node);
else
return this.stopNode(node);
});
}
},
getNextNodeID() {
let c = 1;
let nodeID = `${NODE_PREFIX}-${c}`;
while (this.nodes.find(n => n.nodeID == nodeID)) {
nodeID = `${NODE_PREFIX}-${++c}`;
}
return nodeID;
},
startNewNode(nodeID) {
this.logger.info(`Starting ${nodeID} node...`);
const worker = cluster.fork();
worker.nodeID = nodeID;
worker.on("message", msg => this.workerMessageHandler(worker, msg));
worker.on("disconnect", () => {
const idx = this.nodes.findIndex(node => node.worker == worker);
if (idx != -1) {
const node = this.nodes[idx];
this.nodes.splice(idx, 1);
this.logger.info(`Node ${node.nodeID} stopped.`);
this.removeNodeIDFromMetric(node.nodeID);
}
});
worker.send({ cmd: "start", nodeID });
this.nodes.push({ nodeID, worker });
},
stopNode(node) {
this.logger.info(`Stopping ${node.nodeID} node...`);
node.worker.send({ cmd: "stop" });
},
killNode(node) {
this.logger.info(`Killing ${node.nodeID} node...`);
node.worker.kill("SIGTERM");
},
workerMessageHandler(worker, msg) {
if (msg.event == "started") {
// No started
} else if (msg.event == "metrics") {
if (msg.list && msg.list.length > 0)
msg.list.map(metric => this.addMetric(metric, worker.nodeID));
} else if (msg.event == "registry") {
this.updateWorkerRegistry(worker.nodeID, msg.nodes);
if (this.settings.printRegistry)
this.printRegistry();
} else {
this.logger.info(msg);
}
},
updateWorkerRegistry(nodeID, nodes) {
this.workerRegistry[nodeID] = nodes;
},
addMetric(metric, nodeID) {
if (!this.metrics[metric.name])
this.metrics[metric.name] = {};
const item = this.metrics[metric.name];
item[nodeID] = metric.values;
},
removeNodeIDFromMetric(nodeID) {
Object.keys(this.metrics).map(name => {
if (this.metrics[name][nodeID])
delete this.metrics[name][nodeID];
});
},
printMetrics() {
console.log(kleur.yellow().bold("\nMetrics: "), kleur.grey("Time:"), kleur.grey(humanize(process.uptime() * 1000)));
console.log(kleur.yellow().bold( "========"));
const rows = [];
let totalTx = 0, totalTxRate = 0, totalTxBytes = 0, totalTxBytesRate = 0;
let totalRx = 0, totalRxRate = 0, totalRxBytes = 0, totalRxBytesRate = 0;
this.nodes.forEach(node => {
const txPackets = this.getMetricValueByNode(node.nodeID, "moleculer.transporter.packets.sent.total", "value");
if (txPackets) totalTx += txPackets;
const txPacketsRate = this.getMetricValueByNode(node.nodeID, "moleculer.transporter.packets.sent.total", "rate");
if (txPacketsRate) totalTxRate += txPacketsRate;
const txBytes = this.getMetricValueByNode(node.nodeID, "moleculer.transporter.packets.sent.bytes", "value");
if (txBytes) totalTxBytes += txBytes;
const txBytesRate = this.getMetricValueByNode(node.nodeID, "moleculer.transporter.packets.sent.bytes", "rate");
if (txBytesRate) totalTxBytesRate += txBytesRate;
const rxPackets = this.getMetricValueByNode(node.nodeID, "moleculer.transporter.packets.received.total", "value");
if (rxPackets) totalRx += rxPackets;
const rxPacketsRate = this.getMetricValueByNode(node.nodeID, "moleculer.transporter.packets.received.total", "rate");
if (rxPacketsRate) totalRxRate += rxPacketsRate;
const rxBytes = this.getMetricValueByNode(node.nodeID, "moleculer.transporter.packets.received.bytes", "value");
if (rxBytes) totalRxBytes += rxBytes;
const rxBytesRate = this.getMetricValueByNode(node.nodeID, "moleculer.transporter.packets.received.bytes", "rate");
if (rxBytesRate) totalRxBytesRate += rxBytesRate;
if (txPackets) {
rows.push([
padE(node.nodeID, 8),
kleur.grey("TX:"),
kleur.green().bold(padS(val(txPackets) + " pck", 8)),
kleur.green().bold(padS(val(txPacketsRate / 60) + " p/s", 8)),
kleur.green().bold(padS(this.humanReadableBytes(txBytes), 8)),
kleur.grey("/"),
kleur.green().bold(padS(this.humanReadableBps(txBytesRate), 8)),
kleur.grey(" RX:"),
kleur.green().bold(padS(val(rxPackets) + " pck", 8)),
kleur.green().bold(padS(val(rxPacketsRate / 60) + " p/s", 8)),
kleur.green().bold(padS(this.humanReadableBytes(rxBytes), 8)),
kleur.grey("/"),
kleur.green().bold(padS(this.humanReadableBps(rxBytesRate), 8))
].join(" "));
}
});
this.columnize(rows, 2).forEach(row => console.log(" ", ...row));
// Total
if (totalTx || totalRx) {
console.log(padE(" ", 80, "-"));
console.log([" ",
padE("Total", 8),
kleur.grey("TX:"),
kleur.green().bold(padS(val(totalTx) + " pck", 8)),
kleur.green().bold(padS(val(totalTxRate / 60) + " p/s", 8)),
kleur.green().bold(padS(this.humanReadableBytes(totalTxBytes), 8)),
kleur.grey("/"),
kleur.green().bold(padS(this.humanReadableBps(totalTxBytesRate), 8)),
kleur.grey(" RX:"),
kleur.green().bold(padS(val(totalRx) + " pck", 8)),
kleur.green().bold(padS(val(totalRxRate / 60) + " p/s", 8)),
kleur.green().bold(padS(this.humanReadableBytes(totalRxBytes), 8)),
kleur.grey("/"),
kleur.green().bold(padS(this.humanReadableBps(totalRxBytesRate), 8))
].join(" "));
}
},
printRegistry: _.debounce(function() {
console.log("\x1b[2J");
console.log("\x1b[0;0H");
console.log(kleur.yellow().bold("\nRegistry: "), kleur.grey("Time:"), kleur.grey(humanize(process.uptime() * 1000)));
console.log(kleur.yellow().bold( "========"));
const nodeIDs = _.uniq([].concat(
Object.keys(this.workerRegistry),
this.broker.registry.nodes.toArray().map(node => node.id)
))
.filter(nodeID => nodeID != this.broker.nodeID)
.sort((a, b) => Number(a.replace(/[^\d]/g, "")) - Number(b.replace(/[^\d]/g, "")));
nodeIDs.forEach(nodeID => this.printWorkerRegistry(nodeID, this.workerRegistry[nodeID], nodeIDs));
}, 250),
printWorkerRegistry(mainNodeID, nodes, allNodeIDs) {
let s = " ";
const mainNode = this.broker.registry.nodes.get(mainNodeID);
const available = mainNode && mainNode.available;
s += available ? kleur.green(padE(mainNodeID, 10)) : kleur.red(padE(mainNodeID, 10));
s += "│";
allNodeIDs.forEach(nodeID => {
if (!available) {
s += " ";
return;
}
if (nodes && nodes[nodeID]) {
const node = nodes[nodeID];
if (node.available)
s += kleur.green().bold("█");
else
s += kleur.red().bold("█");
} else {
s += kleur.red().bold("█");
}
});
s += "│";
console.log(s);
},
columnize(arr, count) {
const res = [];
let tmp = [];
arr.forEach((item, i) => {
if ((i+1) % count == 0) {
tmp.push(item);
res.push(tmp);
tmp = [];
} else {
tmp.push(item + " |");
}
});
if (tmp.length > 0)
res.push(tmp);
return res;
},
getMetricValueByNode(nodeID, metricName, valueName, agg) {
const item = this.metrics[metricName];
if (item) {
const values = item[nodeID];
if (values) {
return this.aggregateValues(values, valueName, agg);
}
}
},
aggregateValues(values, valueName = "value", agg = "sum") {
if (agg == "sum") {
return values.reduce((a, b) => a + b[valueName], 0);
} else if (agg == "avg") {
return values.reduce((a, b) => a + b[valueName], 0) / values.length;
}
},
humanReadableBps(bpm) {
if (bpm == null || Number.isNaN(bpm)) return "-";
const bps = (bpm * 8) / 60;
if (bps >= 1000 * 1000) return `${(bps / 1000 / 1000).toFixed(0)} Mbps`;
if (bps >= 1000) return `${(bps / 1000).toFixed(0)} kbps`;
else return `${bps.toFixed(0)} bps`;
},
humanReadableBytes(bytes) {
if (bytes == null || Number.isNaN(bytes)) return "-";
if (bytes >= 1000 * 1000) return `${(bytes / 1000 / 1000).toFixed(0)} MB`;
if (bytes >= 1000) return `${(bytes / 1000).toFixed(0)} kB`;
else return `${bytes.toFixed(0)} B`;
},
},
created() {
this.nodes = [];
this.metrics = {};
this.workerRegistry = {};
},
started() {
// Print after the fresh metrics received
if (this.settings.printIO)
this.metricTimer = setInterval(() => this.printMetrics(), 5000);
//if (this.settings.printRegistry)
// this.metricTimer = setInterval(() => this.printRegistry(), 2000);
},
stopped() {
clearInterval(this.metricTimer);
}
};
| ice-services/moleculer | examples/multi-nodes/node-controller.service.js | JavaScript | mit | 10,193 |
/**
* Throws an error with `msg` if `expr` is false.
*/
function assert(expr, msg) {
if (!expr) {
throw new Error (msg);
}
}
let x = 5;
try {
assert (x === 5); // (1)
} catch (err) {
console.log("1. ERROR:" + err.message);
}
x = 4;
try {
assert (x === 5); // (2)
} catch (err) {
console.log("2. ERROR:" + err.message);
}
try {
assert (x === 5, "X isn't 5") // (3)
} catch (err) {
console.log("3. ERROR:" + err.message);
}
| kerrishotts/Mastering-PhoneGap-Code-Package | snippets/06/ex1-basic-assertions/a/index.js | JavaScript | mit | 498 |
var tweetCodingApp = angular.module('tweetCodingApp', ['ngCookies']);
tweetCodingApp.run(['$anchorScroll', function($anchorScroll) {
$anchorScroll.yOffset = 100; // always scroll by 50 extra pixels
}])
tweetCodingApp.run(['$http', '$cookies', function($http, $cookies) {
$http.defaults.headers.post['X-CSRFToken'] = $cookies['csrftoken'];
$http.defaults.headers.put['X-CSRFToken'] = $cookies['csrftoken'];
}]);
tweetCodingApp.controller('TweetListCtrlA', function($scope, $sce) {
});
tweetCodingApp.controller('TweetListCtrl',
['$scope', '$window', '$document', '$cookies', '$sce', '$http', '$location', '$anchorScroll', '$q',
function($scope, $window, $document, $cookies, $sce, $http, $location, $anchorScroll, $q) {
$scope.codes = [];
$scope.code_schemes = [];
$scope.selected = 0;
$scope.tweets = [];
$scope.next = 0;
$scope.user = null;
//$scope.csrftoken = $cookies.get('csrftoken');
$scope.page = angular.element("body").data("page");
console.log("page: " + $scope.page);
$scope.assignment_id = angular.element("body").data("assignment");
/*
*
* http requests
*
*/
var user_promise = $http.get('/api/user/current/.json');
var codes_promise = $http.get('/api/codescheme/.json', {params: {assignment: $scope.assignment_id}});
//var tweets_promise = $http.get('/api/tweet/.json');
var dataset_promise = $http.get('/api/dataset/' + dataset_id + '/.json');
var instance_promise = $http.get('/api/codeinstance/.json', {params: {assignment: $scope.assignment_id}});
var assignment_promise = $http.get('/api/assignment/' + $scope.assignment_id + '/.json');
//var instances_promise = $http.get('/api/code_instance/.json')
$q.all([user_promise, codes_promise, dataset_promise, instance_promise, assignment_promise ])
.then(function(data){
console.dir(data[0]);
console.dir(data[1]);
console.dir(data[2]);
console.dir(data[3]);
console.dir(data[4]);
var tweets = data[2].data.tweet_set;
var instances = data[3].data;
for(var i = 0; i < tweets.length; i++) {
tweets[i].html = $sce.trustAsHtml(tweets[i].embed_code);
tweets[i].codes = [];
for(j = 0; j < instances.length; j++) {
if(instances[j].tweet == tweets[i].id && instances[j].deleted == false) {
tweets[i].codes.push(instances[j]);
}
}
}
$scope.user = data[0].data;
$scope.tweets = tweets;
$scope.code_schemes = data[1].data;
$scope.assignment = data[4].data;
for(var i = 0; i < $scope.code_schemes.length; i++) {
var cs = $scope.code_schemes[i];
for(var j = 0; j < cs.code_set.length; j++) {
var code = cs.code_set[j];
code.scheme_idx = i;
$scope.codes.push(code);
}
}
$scope.$broadcast("data:loaded");
//twttr.widgets.load();
});
/*
*
* translators
*
*/
$scope.tweetLookupById = function(id) {
var len = $scope.tweets.length;
for(var i = 0; i < len; i++ ) {
if( $scope.tweets[i].id == id ) {
return $scope.tweets[i];
}
}
return null;
}
$scope.tweetLookupByIndex = function(idx) {
if($scope.tweets.length > idx) {
}
}
$scope.codeLookupById = function(id) {
var len = $scope.codes.length;
for(var i = 0; i < len; i++ ) {
if($scope.codes[i].id == id ) {
return $scope.codes[i];
}
}
return null;
}
$scope.codeLookupByIndex = function(idx) {
if($scope.codes.length > idx) {
return $scope.codes[idx];
}
return {id: -1, name: "<<invalid>>"}
}
$scope.getSelectedTweet = function() {
if($scope.tweets.length > $scope.selected) {
return $scope.tweets[$scope.selected];
}
return null;
}
/*
*
* filters
*
*/
$scope.codeFilterBySchema0 = function(code_instance) {
if(code_instance.code != undefined && $scope.codes.length > 0) {
var code = $scope.codeLookupById(code_instance.code);
return code.scheme_idx === 0 || code.scheme_idx == 2;
}
}
$scope.codeFilterBySchema1 = function(code_instance) {
if(code_instance.code != undefined && $scope.codes.length > 0) {
var code = $scope.codeLookupById(code_instance.code);
return code.scheme_idx === 1;
}
}
$scope.codeFilterBySchema2 = function(code_instance) {
if(code_instance.code != undefined && $scope.codes.length > 0) {
var code = $scope.codeLookupById(code_instance.code);
return code.scheme_idx === 2;
}
}
$scope.incomplete = function() {
var count = 0;
for(var i = 0; i < $scope.tweets.length; i++ ) {
var tweet = $scope.tweets[i];
count += tweet.codes.length;
}
return count < 3;
//return true;
}
$scope.oneTweet = function() {
return $scope.user.condition == 1 || $scope.user.condition == 3;
}
/*
*
* actions
*
*/
$scope.setSelectedTweetIdx = function(idx) {
if(idx >= 0 && idx < $scope.tweets.length ) {
$scope.selected = idx;
$location.hash("tweet-" + idx);
//$anchorScroll("tweet-" + idx);
//console.log("idx: " + idx.toString())
//$window.scrollTo(0, $("#tweet-" + (idx+1)).offset().top )
//$anchorScroll();
}
}
$scope.moveNext = function(ev){
if($scope.selected +1 < $scope.tweets.length) {
$scope.setSelectedTweetIdx($scope.selected+1);
}
if(ev) {
ev.stopPropagation();
ev.preventDefault();
}
}
$scope.movePrev = function(ev){
if($scope.selected >= 0) {
//$scope.tweets[$scope.selected].selected = false;
//$scope.selected -= 1;
$scope.setSelectedTweetIdx($scope.selected-1);
//$scope.tweets[$scope.selected].selected = true;
}
if(ev) {
ev.stopPropagation();
ev.preventDefault();
}
}
$scope.addCode = function(idTweet, idCode) {
var code = $scope.codeLookupById(idCode),
tweet = $scope.tweetLookupById(idTweet),
temp_id = Math.floor(Math.random() * 99999);
if(tweet) {
tweet.codes.push({
code: idCode,
date: Date.now(),
temp_id: temp_id
});
$http.post("/api/codeinstance/", {
"deleted": false,
"code": idCode,
"tweet": idTweet,
"assignment": $scope.assignment.id
})
.success(function(data){
for(var i = 0; i < tweet.codes.length; i++) {
if(tweet.codes[i].temp_id == temp_id) {
//tweet.codes[i].deleted = data.deleted;
tweet.codes[i].date = data.date;
tweet.codes[i].id = data.id;
}
}
})
.error(function(data, status, headers, config){
console.error("error adding code (" + temp_id + ") : " + status);
});
}
}
$scope.removeCode = function(idTweet, idCode) {
var tweet = $scope.tweetLookupById(idTweet);
if(tweet != null && tweet.codes ) {
for(var i = 0; i < tweet.codes.length; i++) {
if( tweet.codes[i].code == idCode ) {
code = tweet.codes.splice(i,1)[0];
if(code.id && code.id >= 0) {
code.deleted = true;
delete code.temp_id;
code.tweet = idTweet;
code.assignment = $scope.assignment.id;
$http.put("/api/codeinstance/" + code.id + "/", code)
.success(function(data) {
console.log("deleted code: " + code.id);
})
.error(function(data,status,headers,config){
console.error("error deleting code :" + status );
})
}
return true;
}
}
} else {
console.error('tweet is null');
}
return false
}
$scope.toggleCode = function(tweet, idCode) {
if(tweet != null) {
if(!$scope.removeCode(tweet.id, idCode)) {
$scope.addCode(tweet.id, idCode);
}
}
}
$scope.toggleCodeByTweetId = function(idTweet, idCode) {
var tweet = $scope.tweetLookupById(idTweet);
$scope.toggleCode(tweet, idCode);
}
$scope.toggleCodeOnSelectedTweet = function(idCode) {
var tweet = $scope.getSelectedTweet();
$scope.toggleCode(tweet, idCode);
}
/*
*
* event handlers
*
*/
$scope.itemClicked = function($index) {
//console.log('+' + $index);
$scope.selected = $index;
$scope.setSelectedTweetIdx($index);
}
$scope.onKeyPress = function(ev) {
console.dir(ev);
console.log("keycode: " + ev.keyCode);
var handled = false;
//console.log("-selected: " + $scope.selected); switch(ev.keyCode) {
if( ev.keyCode != 38 && ev.keyCode != 40 && ev.keyCode != 13 ) {
if($scope.code_schemes) {
for(var csid = 0; csid < $scope.code_schemes.length; csid++ ) {
var cs = $scope.code_schemes[csid];
for(var cid = 0; cid < cs.code_set.length; cid++) {
var code = cs.code_set[cid];
if(code.key == String.fromCharCode(ev.keyCode)) {
$scope.toggleCodeOnSelectedTweet( code.id );
handled = true;
}
}
}
}
} else {
switch(ev.keyCode) {
case 38:
$scope.movePrev();
handled = true;
break;
case 40:
case 13:
$scope.moveNext();
handled = true;
break;
}
}
/*
if($scope.schema0_visible && ev.keyCode >= 49 && ev.keyCode <= 51) {
$scope.toggleCodeOnSelectedTweet( ev.keyCode - 48 );
handled = true;
}else if($scope.schema1_visible && ev.keyCode >= 52 && ev.keyCode < 55) {
$scope.toggleCodeOnSelectedTweet( ev.keyCode - 48 );
handled = true;
} else {
}
*/
//$scope.apply($scope.selected);
//$scope.$apply();
if(handled) {
$scope.$apply();
return false;
}
}
$scope.onRemoveCodeClicked = function(ev, tweet, code) {
console.dir(code);
ev.preventDefault();
ev.stopPropagation();
$scope.removeCode(tweet.id, code.code )
return false;
}
// add global keybinding
angular.element(window).on('keydown', $scope.onKeyPress);
//$document.bind("keypress", $scope.onKeyPress);
/*
$scope.$on('keypress', function(onEvent, onKeyPress){
console.log("%%");
console.dir(onEvent);
});
*/
}]);
tweetCodingApp.controller('TweetCodeNavBar', ['$scope', '$document',
function($scope, $document) {
//$scope.
/*
$scope.$on('data:loaded', function(event, args) {
console.log('data:loaded');
console.dir(event);
console.dir(args);
window.twttr = (function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0],
t = window.twttr || {};
if (d.getElementById(id)) return t;
js = d.createElement(s);
js.id = id;
js.src = "//platform.twitter.com/widgets.js";
fjs.parentNode.insertBefore(js, fjs);
t._e = [];
t.ready = function(f) {
t._e.push(f);
};
return t;
}(document, "script", "twitter-wjs"));
$location.hash("tweet-" + idx);
//twttr.widgets.load();
//$document[0].body.innerHTML += "<script async src=\"//platform.twitter.com/widgets.js\" charset=\"utf-8\"></script>";
});
*/
}]);
| geosoco/coding_experiment | main/static/js/controllers.js | JavaScript | mit | 10,416 |
"use strict";
exports.__esModule = true;
var file_1 = require("ack-path/js/file");
exports.file = file_1.method;
| AckerApple/ack-node | js/modules/File.js | JavaScript | mit | 113 |
(function() {
'use strict'
app.factory('createObj', [
function() {
return {
event: function(activity, firstName, lastName, email, group, mobileUserId) {
var newEvent = {
activity: activity,
firstName: firstName,
lastName: lastName,
email: email,
group: group,
mobileUserId: mobileUserId || '',
inFormatted: moment().format('MMMM Do YYYY, h:mm:ss a'),
day: moment().format('MMMM Do, YYYY'),
in: moment().format(),
signedIn: true,
outFormatted: '',
out: '',
totalMins: '',
totalSecs: ''
}
return newEvent
},
newVisitor: function(visitorEmail, visitorFirstName, visitorLastName) {
var newVisitor = {
visitorEmail: visitorEmail,
visitorFirstName: visitorFirstName,
visitorLastName: visitorLastName
}
return newVisitor
},
updateEventObj: function(eventObj) {
eventObj.signedIn = false
eventObj.outFormatted = moment().format('MMMM Do YYYY, h:mm:ss a')
eventObj.out = moment().format()
var timeIn = eventObj.in.toString()
var timeOut = eventObj.out.toString()
var duration = moment(timeIn).twix(timeOut)
var durationMins = duration.count('minutes')
var durationSecs = duration.count('seconds')
eventObj.totalMins = durationMins
eventObj.totalSecs = durationSecs
return eventObj
}
}
}
])
})()
| NathanBaldwin/clocker-2.0 | public/app/Factories/createObj.factory.js | JavaScript | mit | 1,638 |
var stream = require('stream');
var EventEmitter = require('events').EventEmitter;
var util = require('util');
var TimeoutError = function () {
var err = Error.apply(this, arguments);
this.stack = err.stack;
this.message = err.message;
return this;
};
/**
* Creates a new DelayedResponse instance.
*
* @param {http.ClientRequest} req The incoming HTTP request
* @param {http.ServerResponse} res The HTTP response to delay
* @param {Function} next The next function to invoke, when DelayedResponse is used as middleware with
* express or connect.
*/
var DelayedResponse = function (req, res, next) {
if (!req) throw new Error('req is required');
if (!res) throw new Error('res is required');
var delayed = this;
this.req = req;
this.res = res;
this.next = next;
this.timers = {};
// if request is aborted, end the response immediately
req.on('close', function () {
abort.call(delayed);
});
// make sure timers stop if response is ended or closed
res.on('close', function () {
delayed.stop();
}).on('finish', function () {
delayed.stop();
});
EventEmitter.call(this);
};
util.inherits(DelayedResponse, EventEmitter);
/**
* Shorthand for adding the "Content-Type" header for returning JSON.
* @return {DelayedResponse} The same instance, for chaining calls
*/
DelayedResponse.prototype.json = function () {
this.res.setHeader('Content-Type', 'application/json');
return this;
};
/**
* Waits for callback results without long-polling.
*
* @param {Number} timeout The maximum amount of time to wait before cancelling
* @return {Function} The callback handler to use to end the delayed response (same as DelayedResponse.end).
*/
DelayedResponse.prototype.wait = function (timeout) {
if (this.started) throw new Error('instance already started');
var delayed = this;
// setup the cancel timer
if (timeout) {
this.timers.timeout = setTimeout(function () {
// timeout implies status is unknown, set HTTP Accepted status
delayed.res.statusCode = 202;
delayed.end(new TimeoutError('timeout occurred'));
}, timeout);
}
return this.end.bind(delayed);
};
/**
* Starts long-polling to keep the connection alive while waiting for the callback results.
* Also sets the response to status code 202 (Accepted).
*
* @param {Number} interval The interval at which "heartbeat" events are emitted
* @param {Number} initialDelay The initial delay before starting the polling process
* @param {Number} timeout The maximum amount of time to wait before cancelling
* @return {Function} The callback handler to use to end the delayed response (same as DelayedResponse.end).
*/
DelayedResponse.prototype.start = function (interval, initialDelay, timeout) {
if (this.started) throw new Error('instance already started');
var delayed = this;
interval = interval || 100;
initialDelay = typeof initialDelay === 'undefined' ? interval : initialDelay;
// set HTTP Accepted status code
this.res.statusCode = 202;
// disable socket buffering: make sure content is flushed immediately during long-polling
this.res.socket && this.res.socket.setNoDelay();
// start the polling and initial delay timers
this.timers.initialDelay = setTimeout(function () {
delayed.timers.poll = setInterval(heartbeat.bind(delayed), interval);
}, initialDelay);
this.started = true;
// setup the cancel timer
if (timeout) {
this.timers.timeout = setTimeout(function () {
delayed.end(new TimeoutError('timeout occurred'));
}, timeout);
}
return this.end.bind(delayed);
};
function heartbeat() {
// always emit "poll" event
this.emit('poll');
// if "heartbeat" event is attached, delegate to handlers
if (this.listeners('heartbeat').length) {
return this.emit('heartbeat');
}
// default behavior: write the heartbeat character (a space)
this.res.write(' ');
}
function abort() {
this.stop();
if (this.listeners('abort').length) {
return this.emit('abort');
}
// default behavior: end the response with no fanfare
this.res.end();
}
/**
* Ends this delayed response, writing the contents to the HTTP response and ending it. Attach a handler on the "done"
* event to manually end the response, or "error" to manually handle the error.
*
* @param {Error} err The error to throw if the operation has failed.
* @param {*} data The return value to render in the response.
*/
DelayedResponse.prototype.end = function (err, data) {
// detect a promise-like object
if (err && 'then' in err && typeof err.then === 'function') {
var promise = err;
var delayed = this;
return promise.then(function (result) {
delayed.end(null, result);
return result;
}, function (err) {
// this will throw err
delayed.end(err);
});
}
// prevent double processing
if (this.ended) return console.warn('DelayedResponse.end has been called twice!');
this.ended = true;
// restore socket buffering
this.res.socket && this.res.socket.setNoDelay(false);
// handle an error
if (err) {
if (err instanceof TimeoutError && this.listeners('cancel').length) {
return this.emit('cancel');
} else if (this.listeners('error').length) {
return this.emit('error', err);
} else if (this.next) {
return this.next(err);
}
throw err;
}
// if "done" handlers are attached, they are in charge of ending the response
if (this.listeners('done').length) {
return this.emit('done', data);
}
// otherwise, end the response with default behavior
if (typeof data === 'undefined' || data === null) {
this.res.end();
} else if (data instanceof stream.Readable) {
data.pipe(this.res);
} else if (typeof data === 'string' || Buffer.isBuffer(data)) {
this.res.end(data);
} else {
this.res.end(JSON.stringify(data));
}
};
/**
* Stops long-polling without affecting the response.
*/
DelayedResponse.prototype.stop = function () {
// stop initial delay
clearTimeout(this.timers.initialDelay);
this.timers.initialDelay = null;
// stop polling
clearInterval(this.timers.poll);
this.timers.poll = null;
// stop timeout
clearTimeout(this.timers.timeout);
this.timers.timeout = null;
};
module.exports = DelayedResponse;
| extrabacon/http-delayed-response | index.js | JavaScript | mit | 6,706 |
'use strict';
var Post = require('../models/post'),
_ = require('underscore'),
gm = require('gm'),
path = require('path'),
fs = require('fs'),
async = require('async'),
ss = require('socket.io-stream'),
postHelpers = require('../helpers/post'),
albumHelpers = require('../helpers/album'),
Album = require('../models/album'),
postSocket = {};
/** This socket handles the post update page. It allows all users
* logged in or anonymous to create city, restaurant, category, items
* and ensure proper linkage. Successively, if user has logged in and is the owner
* of the post in question, it allows an edit. Succisevely, it sends updated
* post information to all post client listeners.
*/
postSocket.update = function(socket, callback) {
socket.on('post-update', function(data) {
Post.findOne({ _id: data.id }, function(err, post) {
async.parallel([
function(next) {
postHelpers.getOrCreateCityRestaurantCategoryItem(data.city, data.restaurant, data.category, data.item, next);
}
], function(err, results) {
if (post) {
console.log(socket.handshake.user);
if (post.userHasRights(socket.handshake.user)) {
var opts = {
title: data.title,
description: data.description,
_city: results[0].city.id,
_category: results[0].category.id,
_restaurant: results[0].restaurant.id,
_item: results[0].item.id
};
postHelpers.updatePost(post, opts, socket, 'post');
} else {
socket.emit('post', {error: 'Permission denied'});
}
} else {
socket.emit('post', {error: 'Post not found'});
if (!!callback)
callback(err, post);
}
});
});
});
};
/** This socket will allow logged in user to upload
* an image either individually or as an album. It
* checks if the album flag has been checked to true.
* If an album id is also specified, it adds the pictures
* to the album. It also gathers city, restaurant, category
* and item information and attaches it to the uploaded images
* but not to the album (TODO)
* If image has been uploaded to album, it sends new image information
* to all client socket album listeners.
*/
postSocket.imageUpload = function(socket, io, callback) {
ss(socket).on('image-upload', function(stream, data) {
if (!!socket.handshake && !!!socket.handshake.user.id) {
socket.emit('post', {error: 'Permission denied'});
} else {
var filename, elementId = data.elementId;
if (!!data.link) {
filename = path.basename(data.link).split('?')[0];
} else {
filename = path.basename(data.name.name);
}
async.waterfall([
function(next) { // get file path
postHelpers.getFilePath(filename, 'original', socket.handshake.user, function(err, filepath) {
next(null, filepath);
});
},
function(filepath, next) { // get url
postHelpers.getImageUrl(filepath, function(url){
next(null, filepath, url);
});
},
function(filepath, url, next) { // start stream
if (!!data.link) {
var http = require('http'),
https = require('https'),
download = fs.createWriteStream(filepath);
var httpProtocol = !data.link.indexOf('https') ? https : http;
var httpStream = httpProtocol.get(data.link, function(res) {
res.pipe(download);
var totalSize = res.headers['content-length'];
var downloadedSize = 0;
res.on('data', function(buffer) {
downloadedSize += buffer.length;
socket.emit('downloadProgress', {'progress': downloadedSize/totalSize * 100 + '%' });
});
});
download.on('finish', function(err, data) {
next(err, filepath, url, elementId);
});
} else {
var upload = fs.createWriteStream(filepath);
stream.pipe(upload);
stream.on('end', function(err, data) {
next(err, filepath, url, elementId);
});
}
}
], function(err, filepath, url, elementId) {
if (err) throw err;
// Create city, restaurant, category first before saving post
async.parallel({
album: function(next) {
if (!!data.album || !!data.create) {
albumHelpers.createOrGetAlbum(data.album, socket, io, next);
} else {
next(null, null);
}
},
cityRestaurantCategoryItem: function(next) {
postHelpers.getOrCreateCityRestaurantCategoryItem(data.city, data.restaurant, data.category, data.item, next);
},
thumb: function(next) {
postHelpers.getFilePath(path.basename(filepath), 'thumb/240x160', socket.handshake.user, function(err, thumbPath) {
gm(filepath).resize(240, 160, '!').gravity('Center').crop(240, 160, 0, 0).write(thumbPath, function(err) {
if (err) throw err;
postHelpers.getImageUrl(thumbPath, function(url){
next(null, { path: thumbPath, url: url });
});
});
});
}
}, function(err, results) {
var opts = {
user: {
_id: socket.handshake.user.id,
name: socket.handshake.user.profile.name
},
_user: socket.handshake.user.id,
pic: {
originalPath: filepath,
originalUrl: url,
thumbPath: results.thumb.path,
thumbUrl: results.thumb.url,
},
_city: results.cityRestaurantCategoryItem.city.id,
_restaurant: results.cityRestaurantCategoryItem.restaurant.id,
_category: results.cityRestaurantCategoryItem.category.id,
_item: results.cityRestaurantCategoryItem.item.id
};
async.waterfall([
function(next) {
albumHelpers.populatePostOptsWithAlbumValues(results.cityRestaurantCategoryItem, results.album, opts, next);
},
function(opts, next) {
Post(opts).save(next);
},
function(post, numberSaved, next) {
albumHelpers.assignPostToAlbum(post, results.album, socket.handshake.user, io, next);
}
], function(err, results) {
postHelpers.socketNewPost(results.post, results.album, elementId, socket, callback);
});
});
});
}
});
};
/** This socket handles removal of post. It checks first
* if the user has permission to the post
*/
postSocket.remove = function(io, socket, callback) {
socket.on('post:remove', function(data) {
if (!!!socket.handshake.user.id) {
socket.emit('post', {error: 'Permission denied'});
} else {
Post.findOneAndRemove({_id: data.id, '_user': socket.handshake.user.id}, function(err, post) {
if (!!post) {
post.remove();
var elements = {};
elements['#' + data.id] = 'Post deleted';
// if in new post page, remove element
io.sockets.in('post-new-' + post.id).emit('post-update', [{
action: 'remove',
elements: elements
}]);
// Redirect if on post delete page
io.sockets.in('post-delete-' + post.id).emit('post-update', [{
action: 'redirect',
url: socket.handshake.user.url
}]);
} else {
socket.emit('post', {error: 'Post not found'});
}
if (!!callback)
callback(err, post);
});
}
});
};
/** This socket handles user events on the post upload page, when they
* delete any of the city, restaurant, category attributes by clicking
* on the delete icon. It then updates the post realtime to all post listeneners
*/
postSocket.removeAttr = function(socket, attr, callback) {
socket.on('post.' + attr + ':remove', function(data) {
Post.findOne({_id: data.id, '_user': socket.handshake.user.id}, function(err, post) {
post[attr] = null;
post.save(function(err, doc) {
var elements = {};
elements['#' + data.id + ' .' + attr ] = "";
socket.to('post-' + data.id).emit('post-update', [{
action: 'html',
elements: elements
}]);
if (!!callback)
callback(err, post);
});
});
});
};
// Enables socket connection for post methods
postSocket.socket = function(io, socket, app) {
postSocket.update(socket);
postSocket.imageUpload(socket, io);
postSocket.remove(io, socket);
postSocket.removeAttr(socket, '_city');
postSocket.removeAttr(socket, '_restaurant');
postSocket.removeAttr(socket, '_category');
};
module.exports = postSocket;
| ramseydsilva/menugrapher | socket.io/post.js | JavaScript | mit | 10,805 |
$( document ).ready(function() {
/*window.addEventListener('page-slider-controllet_selected', function(e){
ln["localization"] = "en";
if(e.srcElement.id == "slider_dataset") {
switch (e.detail.selected) {
case 0:
room.$.slider_dataset.setTitle(ln["slide1Title_" + ln["localization"]], ln["slide1Subtitle_" + ln["localization"]]);
room.$.slider_dataset.chevronLeft("invisible");
(room.$.dataset_selection.$.selected_url.invalid) ? room.$.slider_dataset.chevronRight(true) : room.$.slider_dataset.chevronRight(false);
break;
case 1:
room.$.slider_dataset.setTitle(ln["slide2Title_" + ln["localization"]], ln["slide2Subtitle_" + ln["localization"]]);
room.$.slider_dataset.chevronLeft(true);
room.$.slider_dataset.chevronRight("invisible");
break;
}
}
});
window.addEventListener('datalet-slider-controllet_selected', function(e){
room.$.postits_controllet.setPostits(COCREATION.postits[e.detail.dataletId], e.detail.dataletId);
});
window.addEventListener('data-ready', function(e) {
if(e.detail.ready) {
room.$.slider_dataset.chevronRight(true);
room.$.dataset_selection.$.selected_url.invalid = false;
}
else
room.$.dataset_selection.$.selected_url.invalid = true;
room.$.dataset_selection.showDatasetInfo();
});
window.addEventListener('select-dataset-controllet_data-url', function(e){
room.$.slider_dataset.chevronRight(false);
room.$.select_data_controllet.dataUrl = e.detail.url;
room.$.select_data_controllet.init();
});
window.addEventListener('select-fields-controllet_selected-fields', function(e){
room.selectedDatasetFields = room.$.select_data_controllet.getSelectedFields();
});
window.addEventListener('datalet-slider-controllet_attached', function(e){
room.$.datalets_slider.setDatalets(COCREATION.datalets);
});*/
window.addEventListener('info-list-controllet_attached', function(e){
room.$.info_list_controllet.setInfo(COCREATION.info);
});
});
room.splitScreenActive = false;
room.current_selected_container = null;
room.handleSelectUIMode = function(mode){
room.$.opera.style.visibility = (!room.splitScreenActive) ? "hidden" : "visible";
room.$.discussion.style.visibility = 'hidden';
room.$.info.style.visibility = 'hidden';
switch(mode){
case 'opera':
room.current_selected_container = room.$.opera;
room.$.opera.style.visibility = "visible";
break;
case 'discussion':
room.current_selected_container = room.$.discussion;
room.$.discussion.style.visibility = 'visible';
SPODDISCUSSION.init();
break;
case 'info':
room.current_selected_container = room.$.info;
room.$.info.style.visibility = 'visible';
break;
case 'split':
room.$.split_checkbox.checked = !room.$.split_checkbox.checked;
room.handleSplitScreen(room.$.split_checkbox);
break;
}
};
room.handleSplitScreen = function(e){
room.splitScreenActive = e.checked;
if(room.splitScreenActive){//active split screen
room.$.opera.disabled = true;
room.$.opera.style.visibility = "visible";
//room.$.datalets.style.visibility = 'hidden';
room.$.info.style.visibility = 'hidden';
room.$.discussion.style.visibility = 'visible';
if(room.current_selected_container === null){
room.current_selected_container = room.$.opera;
room.$.section_menu.selected = 5;
}
room.current_selected_container.style.visibility = "visible";
$(room.$.info).addClass("split_size_card_right");
$(room.$.discussion).addClass("split_size_card_right");
//$(room.$.datalets).addClass("split_size_card_right");
$(room.$.opera).addClass("split_size_card_left");
}else{
room.$.opera.disabled = false;
room.$.opera.style.visibility = "visible";
//room.$.datalets.style.visibility = 'hidden';
room.$.info.style.visibility = 'hidden';
room.$.discussion.style.visibility = 'hidden';
$(room.$.info).removeClass("split_size_card_right");
$(room.$.discussion).removeClass("split_size_card_right");
$(room.$.opera).removeClass("split_size_card_left");
//$(room.$.datalets).removeClass("split_size_card_right");
}
};
room.loadDiscussion = function(){
$.post(OW.ajaxComponentLoaderRsp + "?cmpClass=COCREATION_CMP_DiscussionWrapper",
{params: "[\"" + COCREATION.roomId + "\"]"},
function (data, status) {
data = JSON.parse(data);
$('#discussion_container').html(data.content);
//onloadScript
var onload = document.createElement('script');
onload.setAttribute("type","text/javascript");
onload.innerHTML = data.onloadScript;
});
}; | routetopa/spod-plugin-cocreation | static/js/cocreation-commentarium.js | JavaScript | mit | 5,277 |
// GPG4Browsers - An OpenPGP implementation in javascript
// Copyright (C) 2011 Recurity Labs GmbH
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
/**
* Implementation of type key id ({@link http://tools.ietf.org/html/rfc4880#section-3.3|RFC4880 3.3})<br/>
* <br/>
* A Key ID is an eight-octet scalar that identifies a key.
* Implementations SHOULD NOT assume that Key IDs are unique. The
* section "Enhanced Key Formats" below describes how Key IDs are
* formed.
* @requires util
* @module type/keyid
*/
module.exports = Keyid;
var util = require('../util.js');
/**
* @constructor
*/
function Keyid() {
this.bytes = '';
}
/**
* Parsing method for a key id
* @param {String} input Input to read the key id from
*/
Keyid.prototype.read = function(bytes) {
this.bytes = bytes.substr(0, 8);
};
Keyid.prototype.write = function() {
return this.bytes;
};
Keyid.prototype.toHex = function() {
return util.hexstrdump(this.bytes);
};
Keyid.prototype.equals = function(keyid) {
return this.bytes == keyid.bytes;
};
Keyid.prototype.isNull = function() {
return this.bytes === '';
};
module.exports.mapToHex = function (keyId) {
return keyId.toHex();
};
module.exports.fromClone = function (clone) {
var keyid = new Keyid();
keyid.bytes = clone.bytes;
return keyid;
};
| openilabs/crypto | node_modules/openpgp/src/type/keyid.js | JavaScript | mit | 2,004 |
var fs = require('fs');
function Parser() {
if (!(this instanceof Parser))
return new Parser(arguments);
return this;
}
Parser.prototype.parseFile = function(filename) {
fs.readFile(filename, 'utf8', function (err,data) {
if (err) return console.error(err.msg);
var dict = {};
data.split(/\W+/).forEach( function (word) {
var w = word.toLowerCase();
if (dict[w] === undefined)
dict[w] = 1;
else
dict[w] = dict[w] + 1;
});
var wordList = fs.readFileSync('wordfreq.tsv', 'utf8').split(/\W+/);
for (var i = 0; i<wordList.length; i++) {
wordList[i] = wordList[i].toLowerCase();
}
for (var word in dict) {
if (wordList.indexOf(word) !== -1)
delete(dict[word]);
}
var i = 0, j = 0;
for (var word in dict) {
i++;
if (dict[word] > 100) {
j++;
console.log(word + ': \t' + dict[word]);
}
}
console.log('\n' + i + ' words total, ' + j + ' displayed.');
});
}
module.exports = new Parser();
| mbogochow/TeamToo | lib/parse/index.js | JavaScript | mit | 1,054 |
function initNew3DView()
{
initNormalDetection();
viewportObj = new Viewport( signals );
viewport = viewportObj.viewportContainer;
viewport.setTop( '2px' );
viewport.setRight( '2px' );
viewport.setLeft( '2px' );
//viewport.setWidth( '-webkit-calc(100% - 300px)', '-moz-calc(100% - 300px)', 'calc(100% - 300px)' );
//viewport.setHeight( '-webkit-calc(100% - 32px)', '-moz-calc(100% - 32px)', 'calc(100% - 32px)' );
viewport.setWidth((window.innerWidth) + 'px');
viewport.setHeight((window.innerHeight) + 'px');
document.body.appendChild( viewport.dom );
// set focus on Viewport to get hotkeys working
// right from the initial page load
//alert(renderer);
// create default scene
signals.resetScene.dispatch();
//
var onWindowResize = function ( event ) {
signals.windowResize.dispatch();
};
var createDummyMaterial = function () {
return new THREE.MeshPhongMaterial();
};
//
onWindowResize();
window.addEventListener( 'resize', onWindowResize, false );
var temp = document.getElementById('DymanicMenuContainer');
temp.zIndex = '1px';
//alert(viewport.dom.innerHTML);
//viewport.dom.lastElementChild.setAttribute("width", window.innerWidth);
if(isSet)
{
//toggleToBirdEyeView();
//customRenderAll();
for(var i = 0; i < objectsOnPathArray.length; i++)
{
if(objectsOnPathArray[i]) {
if(objectsOnPathArray[i].type == 'group')
{
var objInGroup = [];
objInGroup = objectsOnPathArray[i].getObjects();
for(var i=0; i<objInGroup.length; i++)
{
objInGroup[i].samePath = true;
}
}
objectsOnPathArray[i].pathAdded = true;
//pathArray3D.push(convert2DObject(objectsOnPathArray[i]));
var pushable = convert2DObject(objectsOnPathArray[i]);
if( pushable && !pushable.isPictureCube)
//pathArray3D.push(pushable);
pathArray3D[ i ] = pushable;
}
}
for(var i = 0; i < pathArray3D.length; i++)
{
if(!pathArray3D[i])
pathArray3D.splice(i, 1);
}
if(pathArray3D. length)
pathObjectCount = pathArray3D.length;
for(var k = 0;k < mainFabricCanvas._objects.length; k++)
{
var obj = mainFabricCanvas._objects[k];
var frameFlag;
if(obj && obj.name != "mainInfiniteRect" && obj.name != "superGrid" && isNotTagArea(obj) && !obj.pathAdded)
{
if(obj.isFrame)
{
var frameChild = getArrayOfFrameObjects(obj);
for(var i = 0; i<frameChild.length; i++)
frameChild[i].frameChild = true;
}
if(obj.isType('group'))
{
var objInGroup = [];
objInGroup = obj.getObjects();
for(var i=0; i<objInGroup.length; i++)
{
if(objInGroup[i].isFrame)
frameFlag = true;
}
for(var i=0; i<objInGroup.length; i++)
{
if(!frameFlag) {
if(objInGroup[i].isType('group'))
{
var groupInGroup = [];
groupInGroup = objInGroup[i].getObjects();
for(var j = 0; j<groupInGroup.length; j++)
{
groupInGroup[j].groupChild = true;
if(objInGroup[i].isRotate)
groupInGroup[j].isRotate = true;
if(objInGroup[i].isLinear)
groupInGroup[j].isLinear = true;
if(objInGroup[i].isZoom)
groupInGroup[j].isZoom = true;
convert2DObject(groupInGroup[j]);
}
}
else
{
if(obj.isRotate)
objInGroup[i].isRotate = true;
if(obj.isLinear)
objInGroup[i].isLinear = true;
if(obj.isZoom)
objInGroup[i].isZoom = true;
objInGroup[i].groupChild = true;
convert2DObject(objInGroup[i]);
}
}
else {
if(obj.isRotate)
objInGroup[i].isRotate = true;
if(obj.isLinear)
objInGroup[i].isLinear = true;
if(obj.isZoom)
objInGroup[i].isZoom = true;
objInGroup[i].groupChild = true;
convert2DObject(objInGroup[i]);
}
}
}
convert2DObject(obj);
}
}
}
var menuItems = document.getElementById('vertical_menu');
var arrowButton = document.getElementById('verticalMenuShowHide');
menuItems.style.display = 'none';
arrowButton.style.display = 'none';
viewport.dom.focus();
if(div3D)
{
div3D.style.display = 'none';
viewport.dom.appendChild(div3D);
}
var camera_element = document.getElementById('camera_menu');
if(camera_element) {
if(objectsOnPathArray.length)
camera_element.style.display = 'block';
else
camera_element.style.display = 'none';
var stop = document.getElementById('exitCamera');
stop.style.display = 'block';
if(document.getElementById("theme"))
{
document.getElementById("theme").checked = true;
panoramaView();
}
viewport.dom.appendChild(stop);
viewport.dom.appendChild(camera_element);
}
//var camera_menu = document.getElementById('camera_menu');
//camera_menu.style.display = 'block';
}
function convert2DObject(obj)
{
var retObj;
if( obj.hasConverted )
return obj.threeDConvertedObject;
if( obj.isSlide )
return insertSlide(obj);
switch(obj.type)
{
case 'rect':
if(!obj.isFrame)
{
retObj = insertCube(obj);
}
else if(obj.isFrame)
{
retObj = insertRectanglePlate(obj);
}
break;
case 'triangle':
if(!obj.isFrame)
{
retObj = insertTriangle3D(obj);
}
else if(obj.isFrame)
{
retObj = insertRectanglePlate(obj);
}
break;
case 'circle':
if(!obj.isFrame)
{
retObj = insertCircle3D(obj);
}
else if(obj.isFrame)
{
retObj = insertCirclePlate(obj);
}
break;
case 'image':
if(obj.is3D)
{
var x = obj.getLeft();
var y = obj.getTop();
var lengthOf3DObjects = mainFabricCanvas._objects.length;
var zFac = (zPosition/lengthOf3DObjects);
var z = zFactor;
var height = obj.currentHeight;
if(x && y) {
x = x;
y = y;
if(obj.frameChild)
{
y = height/2;
z = y;
}
else
{
z = zFactor;
zFactor += zFac;
}
}
//detectPath(obj);
switch( obj.threeDProperties.threeDtype )
{
case '3DCube':
retObj = insertCube3D( x, y, z, obj, "interface3D" );
break;
case '3DBoy':
if(obj.frameChild)
{
y = height/2;
z = y;
}
retObj = insertBoy( x, y, z, obj, "interface3D" );
break;
case '3DGirl':
retObj = insertGirl( x, y, z, obj, "interface3D" );
break;
case '3DDuck':
retObj = insertDuck( x, y, z, obj, "interface3D" );
break;
case '3DHouse':
retObj = insertHouse( x, y, z, obj, "interface3D" );
break;
case '3DTruck':
retObj = insertTruck( x, y, z, obj, "interface3D" );
break;
}
}
else if (obj.name == "video")
retObj = insertVideoInto3D(obj);
else if(obj.id && obj.id.toString().match(/audio/) != null)
insertAudioInto3D(obj);
else if (typeof(obj.picturedCube)=='number' && obj.picturedCube > -1) {
{
if(insertPicturedCube)
{
insertPicturedCube = false;
insertTexturedCube();
}
}
}
else
retObj = insertImageInto3D(obj);
break;
case 'path':
if( obj.shapeProperty == 'dragon')
{
retObj = insertDragonModel(obj);
}
else if(obj.shapeProperty == 'bracFrame' || obj.shapeProperty == 'frame3D')
{
retObj = insertRectanglePlate(obj);
}
else
{
retObj = insertFreeDrawObject(obj);
}
break;
case 'ellipse':
if(!obj.isFrame)
{
retObj = insertCircle3D(obj);
}
else if(obj.isFrame)
{
retObj = insertCirclePlate(obj);
}
break
case 'line':
retObj = insertLine3D(obj);
break;
case 'text':
retObj = insertText3D(obj);
break;
}
return retObj;
}
function getTheme3D()
{
switch(currTheme)
{
case "galaxyTheme":
themeImage3D = 'resources/0.jpg';
break;
case 'chessTheme':
themeImage3D = 'resources/5.jpg';
break;
case 'oceanTheme':
themeImage3D = 'resources/1.jpg';
break;
case 'slateTheme':
themeImage3D = 'resources/2.jpg';
break;
case 'marioTheme':
themeImage3D = 'resources/3.jpg';
break;
default:
themeImage3D = 'resources/panorama1.jpg';
break;
}
}
function toggleTheme(event)
{
event.preventDefault();
event.stopPropagation();
var themeChecked = document.getElementById("theme") ? document.getElementById("theme").checked : false;
if(themeChecked)
{
scene.add(panorama);
}
else
{
scene.remove(panorama);
}
} | ankitbishtkec/next-generation-presentation-tool | t10/3D/scripts/interface3D.js | JavaScript | mit | 8,913 |
'use strict';
module.exports = function (gulp, config) {
var files = './node_modules/angular/angular.js';
task.waitFor = config.buildStep1;
function task() {
return gulp.src(files)
.pipe(gulp.dest(config.distDir + '/js'));
}
return task;
}; | marlun78/angular-es6 | tasks/copy.js | JavaScript | mit | 281 |
/* global angular, doTA */
(function(global, factory) {
factory(global, global.document, global.doTA);
}(typeof window !== 'undefined' ? window : this, function(window, document, doTA) {
var msie = document.documentMode;
var ie8 = msie <= 8;
var textContent = ie8 ? 'innerText' : 'textContent';
var listenerName = ie8 ? 'attachEvent' : 'addEventListener';
var frag, newNode = doTA.N;
var BoolMap = {0: 0, 'false': 0, 1: 1, 'true': 1};
setTimeout(function() {
frag = document.createDocumentFragment();
});
function makeBool(attr, defaultValue){
return attr in BoolMap ? BoolMap[attr] : attr || defaultValue;
}
function forEachArray(src, iter, ctx) {
if (!src) { return; }
if (src.forEach) {
return src.forEach(iter);
}
for (var key = 0, length = src.length; key < length; key++) {
iter.call(ctx, src[key], key);
}
}
//retrieve nested value from object, support a.b or a[b]
function resolveDot(path, obj) {
//console.log(['resolveDot', path, obj]);
if (path.indexOf('.') > 0) {
var chunks = path.split('.');
return chunks.reduce(function (prev, curr) {
return prev ? prev[curr] : undefined;
}, obj);
} else {
return obj[path];
}
}
function resolveObject(path, obj) {
if (path.indexOf('[') > 0) {
var result;
while (path.indexOf('[') > 0) {
/*jshint loopfunc: true */
path = path.replace(/([$\w.]+)\[([^[\]]+)\](?:\.([$\w.]+))?/g, function($0, lpart, part, rpart) {
var lobj = resolveDot(lpart, obj);
//console.log(['part', part, 'lpart', lpart, 'lobj', lobj]);
var robj = resolveDot(part, lobj);
//console.log(['part', part, 'lobj', lobj, 'robj', robj]);
if (typeof robj === 'object' && rpart) {
return (result = resolveDot(rpart, robj));
}
return (result = robj);
});
/*jshint loopfunc: false */
}
return result;
} else {
return resolveDot(path, obj);
}
}
// var obj2 = {
// params: { groups: {'test': 1234, abcd: 'efgh'}},
// groups: [{_id: 'test'},{_id: 'abcd'}]
// };
// console.log(resolveObject('params.groups[groups[0]._id]', obj2));
// console.log(resolveObject('params.groups[groups[1]._id]', obj2));
// console.log(resolveObject('groups.0._id', obj2));
// console.log(resolveObject('groups.0', obj2));
function parseDot(path, obj) {
//console.log(['resolveDot', path, obj]);
if (path.indexOf('.') > 0) {
var chunks = path.split('.');
path = chunks.pop();
obj = chunks.reduce(function (prev, curr) {
// console.log('parseObject', [prev, curr])
if (!prev[curr]) {
prev[curr] = {};
}
return prev[curr];
}, obj);
}
return {
assign: function(val) {
obj[path] = val;
}
};
}
//get nested value as assignable fn like $parse.assign
function parseObject(path, obj) {
if (path.indexOf('[') > 0) {
var result;
while (path.indexOf('[') > 0) {
/*jshint loopfunc: true */
path = path.replace(/([$\w.]+)\[([^[\]]+)\](?:\.([$\w.]+))?/g, function($0, lpart, part, rpart) {
var lobj = resolveDot(lpart, obj);
//console.log(['part', part, 'lpart', lpart, 'lobj', lobj]);
if (rpart) {
var robj = resolveDot(part, lobj);
result = parseDot(rpart, robj);
return resolveDot(rpart, robj);
} else {
result = parseDot(part, lobj);
return resolveDot(part, lobj);
}
});
/*jshint loopfunc: false */
}
return result;
} else {
return parseDot(path, obj);
}
}
// var obj = {};
// var parsed = parseObject('name', obj);
// parsed.assign('test');
// console.log(obj);
// parsed = parseObject('three.one', obj);
// parsed.assign('haha');
// console.log(obj);
// var obj2 = {
// params: { groups: {'test': 1234, abcd: 'efgh'}},
// groups: [{_id: 'test'},{_id: 'abcd'}]
// };
// parsed = parseObject('groups.1._id', obj2);
// console.log(obj2);
// parsed.assign('zzzz');
// console.log(JSON.stringify(obj2,0,4));
// parsed = parseObject('params.groups[groups[0]._id]', obj2);
// console.log(obj2);
// parsed.assign(23923223);
// console.log(JSON.stringify(obj2,0,4));
//debounce for events like resize
function debounce(fn, timeout) {
if (timeout === undefined) {
timeout = 500;
}
var timeoutId;
var args, thisArgs;
function debounced() {
fn.apply(thisArgs, args);
}
return function() {
args = arguments;
thisArgs = this;
if (timeoutId) {
clearTimeout(timeoutId);
}
// console.log('debounce: new timer', [timer]);
timeoutId = setTimeout(debounced, timeout);
};
}
doTA.debounce = debounce;
//throttle for events like input
function throttle(fn, timeout) {
if (timeout === undefined) {
timeout = 200;
}
var timeoutId;
var start = +new Date(), now;
// console.log('timeout', timeout)
var args, thisArgs;
function throttled() {
fn.apply(thisArgs, args);
}
return function() {
args = arguments;
thisArgs = this;
now = +new Date();
if (timeoutId) {
clearTimeout(timeoutId);
}
if (now - start >= timeout) {
// console.log(now - start)
start = now;
throttled();
return;
}
// console.log('throttled: new timer', [timer]);
timeoutId = setTimeout(throttled, timeout);
};
}
doTA.throttle = throttle; //export
//hide and destroy children
function destroyChildren(elem) {
var child = elem.firstChild, hiddenTags = [];
if (child) {
child.hidden = 1;
hiddenTags.push(child);
while ((child = child.nextSibling)) {
child.hidden = 1;
hiddenTags.push(child);
}
}
//destroying children block everything
// so do it later, since deleting don't have to be synchronous
setTimeout(function(){
console.time('removeChild');
forEachArray(hiddenTags, function(child) {
if (child && child.parentNode) {
child.parentNode.removeChild(child);
}
});
console.timeEnd('removeChild');
});
}
function evalExpr(expr) {
return new Function('S', 'return ' + expr.replace(/[$\w.]+/g, function($0) {
return 'S.' + $0;
}));
}
function eventHandlerFn(scope, expr) {
var propagate = expr && expr[0] === '^';
return function(evt){
evt.target = evt.target || evt.srcElement || document;
if (propagate) {
scope.$eval(expr.substr(1), {$event: evt})
scope.$applyAsync();
} else {
if (ie8) {
//make $event.target always available
evt.returnValue = false;
evt.cancelBubble = true;
} else {
evt.preventDefault();
evt.stopPropagation();
}
scope.$evalAsync(expr, {$event: evt});
}
};
}
function getElements(elem, selector) {
return ie8 ? elem.querySelectorAll('.' + selector) : elem.getElementsByClassName(selector);
}
function addEventUnknown(partial, scope) {
if (partial.de) { return; } //only attach events once
partial.de = 1;
var attributes = partial.attributes, attrName, attrVal;
// console.log('attributes', attributes);
for(var i = 0, l = attributes.length; i < l; i++) {
if (!attributes[i] || !attributes[i].name || !attributes[i].value) { continue; }
attrName = attributes[i].name;
attrVal = attributes[i].value;
if (attrName.substr(0, 3) === 'de-') {
//remove attribute, so never bind again
partial[listenerName]((ie8 ? 'on' : '') + attrName.substr(3),
eventHandlerFn(scope, attrVal));
// console.log('event added', attrName);
}
}
}
//specified events
function addEventKnown(partial, scope, events) {
if (partial.ded) { return; } //only attach events once
partial.ded = 1;
var attrName, attrVal;
// console.log('attributes', attributes);
for(var i = 0, l = events.length; i < l; i++) {
attrName = 'de-' + events[i];
attrVal = partial.getAttribute(attrName);
// console.log(i, [attrVal, events[i]])
if (!attrVal) { continue; }
partial[listenerName]((ie8 ? 'on' : '') + events[i],
eventHandlerFn(scope, attrVal));
}
}
function addEvents(elem, scope, event, uniqueId) {
//getElementsByClassName is faster than querySelectorAll
//http://jsperf.com/queryselectorall-vs-getelementsbytagname/20
// console.time('find-nodes:');
var elements = getElements(elem, 'de' + uniqueId);
var i, l;
// console.timeEnd('find-nodes:');
if (typeof event === 'number') {
for (i = 0, l = elements.length; i < l; i++) {
addEventUnknown(elements[i], scope);
}
} else {
var events = event.split(' ');
for (i = 0, l = elements.length; i < l; i++) {
addEventKnown(elements[i], scope, events);
}
}
}
doTA.addEvents = addEvents;
function addNgModels(elem, scope, uniqueId) {
var elements = getElements(elem, 'dm' + uniqueId);
forEachArray(elements, function(partial) {
if (partial.dm) return;
partial.dm = 1;
var dotaPass = partial.getAttribute('dota-pass');
// console.log('dotaPass', [dotaPass]);
if (dotaPass != null) { // jshint ignore:line
return;
} //null or undefined
var isCheckBox = partial.type === 'checkbox';
var isRadio = partial.type === 'radio';
var modelName = partial.getAttribute('dota-model');
var initValue = isCheckBox ?
partial.getAttribute('checked') != null : partial.getAttribute('value');
//textbox default event is input unless IE8, all others are change event
var updateOn = partial.getAttribute('update-on') ||
(partial.type !== 'text' || ie8 ? 'change' : 'input');
var throttleVal = +partial.getAttribute('throttle') || 100;
//use checked property for checkbox and radio
var bindProp = partial.getAttribute('bind-prop') ||
((isCheckBox || partial.type === 'radio') && 'checked');
var curValue = resolveObject(modelName, scope);
console.log('partial1', [partial.tagName, partial.type, modelName, bindProp])
console.log('partial2', [partial.type, initValue, curValue, partial.value, partial[bindProp]]);
if (bindProp) {
//set true or false on dom properties
// if (initValue)
if (isCheckBox)
partial[bindProp] = initValue || curValue;
else if (isRadio)
partial[bindProp] = initValue == curValue;
// else
// partial[bindProp] = curValue;
} else {
if (typeof curValue !== 'undefined') {
partial.value = curValue;
//} else if (partial.tagName === 'SELECT') {
// partial.selectedIndex = 0;
}
}
//bind each events
var events = updateOn.split(' ');
for (var i = 0; i < events.length; i++) {
var evtName = events[i].trim();
partial.addEventListener(evtName, throttle((function (partial, modelName, bindProp) {
var parsed;
return function (evt) {
if (!parsed) {
parsed = parseObject(modelName, scope);
}
if (ie8) {
evt.returnValue = false;
evt.cancelBubble = true;
} else {
evt.preventDefault();
evt.stopPropagation();
}
// console.log('event', modelName, evtName, partial, bindProp, [partial[bindProp || 'value']]);
scope.$applyAsync((function () {
//console.log("value", [partial.value, partial.getAttribute('value'), curValue, bindProp, initValue, partial[bindProp]]);
if (bindProp) {
if (initValue) {
//partial.value
parsed.assign(isCheckBox ? partial.checked :
partial[bindProp] ? partial.value : undefined);
} else {
parsed.assign(partial[bindProp]);
}
} else {
parsed.assign(partial.value);
}
}));
};
})(partial, modelName, bindProp), throttleVal));
}
});
}
doTA.addNgModels = addNgModels;
angular.module('doTA', [])
.config(['$provide',function(P) {
P.factory('doTA', function(){
return doTA;
});
}])
.directive('render', render)
.directive('dotaInclude', ['$http', '$templateCache', '$compile', function($http, $templateCache, $compile) {
return {
restrict: 'A',
priority: 10000,
terminal: true,
compile: function() {
return function(scope, elem, attrs) {
var attrCompile = makeBool(attrs.compile, 1);
console.log('dotaInclude', attrs.dotaInclude);
$http.get(attrs.dotaInclude, {cache: $templateCache}).success(function (data) {
elem.html(data);
if (attrCompile !== 0) {
$compile(elem.contents())(scope);
}
});
};
}
};
}])
.directive('dotaTemplate', ['$http', '$templateCache', '$compile', function($http, $templateCache, $compile) {
return {
restrict: 'A',
priority: 10000,
terminal: true,
compile: function() {
return function(scope, elem, attrs) {
console.log('dotaTemplate - compile', [attrs.dotaTemplate]);
var attrCompile = makeBool(attrs.compile, 1);
scope.$watch(evalExpr(attrs.dotaTemplate), function(newVal, oldVal) {
if (newVal) {
console.log('dotaTemplate', newVal);
$http.get(newVal, {cache: $templateCache}).success(function (data) {
elem.html(data);
if (attrCompile !== 0) {
console.log('dotaTemplate $compile', newVal, data);
$compile(elem.contents())(scope);
}
});
}
});
};
}
};
}])
.factory('dotaHttp', ['$compile', '$http', '$templateCache', '$filter', 'doTA',
function($compile, $http, $templateCache, $filter, doTA) {
return function (name, scope, callback, _opt){
var options = {render: name, loose: 1};
if (_opt) {
for (var x in _opt) {
options[x] = _opt[x];
}
}
// /**/console.log('options')
if (doTA.C[name]) {
// /**/console.log('dotaHttp doTA cache', name);
callback(doTA.C[name](scope, $filter));
} else {
// /**/console.log('dotaHttp $http', name);
$http.get(name, {cache: $templateCache}).success(function(data) {
// /**/console.log('dotaHttp response', data);
doTA.C[name] = doTA.compile(data, options);
callback(doTA.C[name](scope, $filter));
});
}
};
}]);
render.$inject = ['doTA', '$http', '$filter', '$templateCache', '$compile', '$controller'];
function render(doTA, $http, $filter, $templateCache, $compile, $controller) {
return {
restrict: 'A',
priority: 10000,
terminal: true,
controller: angular.noop,
link: angular.noop,
compile: function() {
var Watchers = [], BindValues = {}, Scopes = {};
console.info('render compileFn');
return function($scope, elem, attrs) {
console.time('render');
//ToDo: check Watchers scope
while (Watchers.length) {
Watchers.pop()();
}
//used attributes, good for minification with closure compiler;
var attrCacheDOM = attrs.cacheDom | 0;
var attrRender = attrs.render;
var attrScope = attrs.scope;
var attrNgController = attrs.ngController;
var attrLoose = attrs.loose;
var attrEvent = attrs.event;
var attrDebug = attrs.debug;
var attrWatch = attrs.hasOwnProperty('watch') && attrs.watch;
var attrWatchDiff = attrs.watchDiff;
var attrCompile = attrs.compile;
var attrBind = attrs.bind;
var attrCompileAll = attrs.compileAll;
var attrOnload = attrs.onload;
var attrNgLoad = attrs.ngLoad;
var attrLoaded = attrs.loaded;
var attrInline = attrs.inline;
var origAttrMap = attrs.$attr;
var params = {};
var NewScope;
var uniqueId;
attrs.loose = makeBool(attrLoose, 1); //if set, falsy => ''
attrs.optimize = makeBool(attrs.optimize, 0);
attrs.comment = makeBool(attrs.comment, 1); //if 0, remove comments
attrDebug = attrs.debug = makeBool(attrDebug, 0);
attrEvent = attrs.event = makeBool(attrEvent, 1); //ng-click to native click
if (attrs.diffLevel) {
attrs.diffLevel = +attrs.diffLevel;
}
//to prevent angular binding this
if (attrNgController) {
elem.removeAttr('ng-controller');
}
if (attrCacheDOM && doTA.D[attrRender]) {
// alert( doTA.D[attrRender].innerHTML);
console.log('cacheDOM: just moved cached DOM', doTA.D[attrRender]);
var cachedElem = msie ? doTA.D[attrRender].cloneNode(true) : doTA.D[attrRender];
elem[0].parentNode.replaceChild(cachedElem, elem[0]);
if (attrCacheDOM === 2) {
onLoad();
}
return;
}
//attributes on render tags to be accessiable as $attr in templates
for (var x in origAttrMap) {
var z = origAttrMap[x];
//map data-* attributes into origAttrMap (inline text)
if (!z.indexOf('data-')) {
params[z.slice(5)] = attrs[x];
attrs.params = 1;
//map scope-* attributes into origAttrMap (first level var from scope)
} else if (!z.indexOf('scope-')) {
attrs.params = 1;
if (attrs[x].indexOf('.') >= 0 || attrs[x].indexOf('[') >= 0) {
if (attrs[x].indexOf('$index') > 0) {
params[z.slice(6)] = $scope.$eval(attrs[x]);
} else {
params[z.slice(6)] = resolveObject(attrs[x], $scope);
}
} else {
params[z.slice(6)] = $scope[attrs[x]];
}
}
}
//create new scope if scope=1 or ng-controller is specified
if (attrScope || attrNgController) {
console.log('scope', attrScope, elem, elem.scope());
//$destroy previously created scope or will leak.
if (Scopes[attrRender]) {
Scopes[attrRender].$destroy();
// /**/console.log('newScope $destroy', attrRender, NewScope);
}
NewScope = Scopes[attrRender] = $scope.$new();
// /**/console.log('newScope created', attrRender, NewScope);
} else {
NewScope = $scope;
}
//attach ng-controller, and remove attr to prevent angular running again
if (attrNgController) {
var asPos = attrNgController.indexOf(' as ');
if (asPos > 0) {
attrNgController = attrNgController.substr(0, asPos).trim();
}
console.log('new controller', attrNgController);
var l = {$scope: NewScope}, controller = $controller(attrNgController, l);
//untested controller-as attr or as syntax
if (attrs.controllerAs || asPos > 0) {
NewScope[attrs.controllerAs || attrNgController.substr(asPos + 4).trim()] = controller;
}
elem.data('$ngControllerController', controller);
elem.children().data('$ngControllerController', controller);
console.log('new controller created', attrRender);
}
// watch and re-render the whole template when change
if(attrWatch) {
console.log(attrRender, 'registering watch for', attrWatch);
var oneTimePos = attrWatch.indexOf('::');
if (oneTimePos >= 0) {
attrWatch = attrWatch.slice(oneTimePos + 2);
}
var oneTimeExp = NewScope['$watch' + (attrWatch[0] === '[' ? 'Collection': '')](evalExpr(attrWatch), function(newVal, oldVal){
if(newVal !== undefined && newVal !== oldVal && doTA.C[attrRender]) {
if (oneTimePos >= 0) oneTimeExp();
console.log(attrRender, 'watch before render');
renderTemplate(doTA.C[attrRender]);
console.log(attrRender, 'watch after render');
}
});
}
// watch and partially render by diffing. diff-level = 2 may be used to patch children
if(attrWatchDiff) {
console.log(attrRender, 'registering diff watch for', attrWatchDiff);
NewScope['$watch' + (attrWatchDiff[0] === '[' ? 'Collection': '')](evalExpr(attrWatchDiff), function(newVal, oldVal){
if(newVal !== oldVal && doTA.C[attrRender]) {
console.log(attrRender, 'diff watch before render');
renderTemplate(doTA.C[attrRender], true);
console.log(attrRender, 'diff watch after render');
}
});
}
// run the loader
loader();
////////////////////////////////////////////////////////////////////////////
// cache-dom for static html, $scope will not be triggered
////////////////////////////////////////////////////////////////////////////
function cacheDOM(){
// console.log('cacheDOM()', attrs)
$scope.$on("$destroy", function(){
console.log('$destroy', elem);
// alert(['$destroy', elem[0], frag]);
if (frag) {
doTA.D[attrRender] = elem[0];
frag.appendChild(elem[0]);
}
});
}
////////////////////////////////////////////////////////////////////////////
// doTA.compile and return compiledFn
////////////////////////////////////////////////////////////////////////////
function compile(template) {
if(attrDebug) {
console.log(attrRender + ':' + template);
}
console.log(attrRender,'before compile');
var compiledFn;
//compile the template html text to function like doT does
try {
console.time('compile:' + attrRender);
compiledFn = doTA.compile(template, attrs);
console.timeEnd('compile:' + attrRender);
uniqueId = doTA.U[attrRender];
console.log(attrRender,'after compile(no-cache)');
} catch (x) {
/**/console.log('compile error', attrs, template);
throw x;
}
//compiled func into cache for later use
if (attrRender) {
doTA.C[attrRender] = compiledFn;
}
return compiledFn;
}
////////////////////////////////////////////////////////////////////////////
// attach ng-bind
////////////////////////////////////////////////////////////////////////////
function addNgBind(rawElem, scope, uniqueId) {
var elements = getElements(rawElem, 'db' + uniqueId);
forEachArray(elements, function(partial) {
if (partial.db) return;
partial.db = 1;
//override ng-bind
var bindExpr = partial.getAttribute('dota-bind');
var oneTimePos = bindExpr.indexOf('::');
if (oneTimePos >= 0) {
bindExpr = bindExpr.slice(oneTimePos + 2);
}
if (BindValues[bindExpr]) {
partial.innerHTML = BindValues[bindExpr];
}
console.log('binding', bindExpr);
console.time('dota-bind');
var oneTimeExp = scope['$watch' + (bindExpr[0] === '[' ? 'Collection': '')](evalExpr(bindExpr), function(newVal, oldVal){
if (newVal && oneTimePos >= 0) { oneTimeExp(); }
console.log('watch fired before bindExpr', [newVal, oldVal]);
partial[textContent] = BindValues[bindExpr] = newVal || '';
console.log('watch fired after render');
});
Watchers.push(oneTimeExp);
console.timeEnd('dota-bind');
console.log(partial);
});
}
////////////////////////////////////////////////////////////////////////////
// attach ng-model, events, ng-bind, and $compile
////////////////////////////////////////////////////////////////////////////
function attachEventsAndCompile(rawElem, scope) {
console.log('attachEventsAndCompile', attrRender, attrs.model, attrEvent, attrBind, attrCompile, attrCompileAll);
if (attrs.model) {
console.time('ngModel:' + attrRender);
addNgModels(rawElem, scope, uniqueId);
console.timeEnd('ngModel:' + attrRender);
}
//attach events before replacing
if (attrEvent) {
console.time('ng-events:' + attrRender);
addEvents(rawElem, scope, attrEvent, uniqueId);
console.timeEnd('ng-events:' + attrRender);
}
//ng-bind
if (attrBind) {
console.time('ngBind:' + attrRender);
addNgBind(rawElem, scope, uniqueId);
console.timeEnd('ngBind:' + attrRender);
}
if (attrs.ngModel) {
elem.removeAttr('render');
console.time('suicide:' + attrRender);
$compile(elem[0])(scope);
console.timeEnd('suicide:' + attrRender);
//$compile html if you need ng-model or ng-something
} else if (attrCompile){
//partially compile each dota-pass and its childs,
// not sure this is suitable if you have so many dota-passes
console.time('$compile:' + attrRender);
forEachArray(rawElem.querySelectorAll('[dota-pass]'), function(partial){
// console.log('$compile:partial:' + attrRender, partial);
$compile(partial)(scope);
});
console.timeEnd('$compile:' + attrRender);
console.log(attrRender,'after $compile partial');
} else if (attrCompileAll){
//compile child nodes
console.time('compile-all:' + attrRender);
$compile(rawElem.contentDocument || rawElem.childNodes)(scope);
console.timeEnd('compile-all:' + attrRender);
console.log(attrRender,'after $compile all');
}
}
function onLoad() {
if(attrOnload){
setTimeout(function(){
var onLoadFn = new Function(attrOnload);
onLoadFn.apply(elem[0]);
console.log(attrRender,'after eval');
});
}
//execute scope functions
if(attrNgLoad) {
setTimeout(function() {
NewScope.$evalAsync(attrNgLoad);
console.log(attrRender, 'after scope $evalAsync scheduled');
});
}
}
////////////////////////////////////////////////////////////////////////////
// render the template, cache-dom, run onload scripts, add dynamic watches
////////////////////////////////////////////////////////////////////////////
function renderTemplate(func, patch) {
//unless pre-render
if (func) {
//trigger destroying children
if (!patch && elem[0].firstChild) {
destroyChildren(elem[0]);
}
console.log('uniqueId', attrRender, uniqueId);
console.log(attrRender, 'before render', patch);
//execute render function against scope, $filter, etc.
var renderedHTML;
try {
console.time('render:' + attrRender);
renderedHTML = func(NewScope, $filter, params, patch);
console.timeEnd('render:' + attrRender);
console.log(attrRender,'after render', patch);
} catch (x) {
/**/console.log('render error', func);
throw x;
}
if(attrDebug) {
/* */console.log(attrRender, renderedHTML);
// console.log(attrRender, func.toString());
}
// console.log('patch?', [patch]);
if (patch) {
attachEventsAndCompile(elem[0], NewScope);
return;
}
//if node has some child, use appendChild
if (elem[0].firstChild) {
console.time('appendChild:' + attrRender);
var firstChild;
newNode.innerHTML = renderedHTML;
//if needed, attach events and $compile
attachEventsAndCompile(newNode, NewScope);
//move child from temp nodes
while ((firstChild = newNode.firstChild)) {
elem[0].appendChild(firstChild);
}
console.timeEnd('appendChild:' + attrRender);
console.log(attrRender, 'after appendChild');
//if node is blank, use innerHTML
} else {
console.time('innerHTML:' + attrRender);
elem[0].innerHTML = renderedHTML;
console.timeEnd('innerHTML:' + attrRender);
console.log(attrRender, 'after innerHTML');
//if needed, attach events and $compile
attachEventsAndCompile(elem[0], NewScope);
}
//attach client side to prerender context
} else {
attachEventsAndCompile(elem[0], NewScope);
}
//execute raw functions, like jQuery
onLoad();
if (attrCacheDOM) {
cacheDOM();
}
//you can now hide raw html before rendering done
// with loaded=false attribute and following css
/*
[render][loaded]:not([loaded=true]) {
display: none;
}
*/
if (attrLoaded) {
elem.attr("loaded",true);
}
//this watch may be dynamically add or remove
if (func && doTA.W[uniqueId]) {
var W = doTA.W[uniqueId];
console.log('partial watch', attrRender, W);
var scopes = {}, watches = {};
for(var i = 0; i < W.length; i++) {
var w = W[i];
// console.log('watch', w);
watches[w.I] = NewScope['$watch' + (w.W[0] === '[' ? 'Collection': '')](evalExpr(w.W), function(newVal, oldVal){
console.log('partial watch trigger', [newVal, oldVal]);
if (newVal === oldVal && !newVal) { return; }
console.log(attrRender, w.W, 'partial watch before render');
var oldTag = document.getElementById(w.I);
if (!oldTag) { return console.log('tag not found'); }
//we don't need new scope here
var content = w.F(NewScope, $filter, params, 0, w.N);
if (!content) { return console.log('no contents'); }
console.log('watch new content', content);
var newTag = angular.element(content);
//compile only if specified
if (w.C) {
//scope management
if (scopes[w.I]) {
scopes[w.I].$destroy();
console.log(attrRender, w.W, 'partial watch old $scope $destroy');
}
scopes[w.I] = NewScope.$new();
console.log(attrRender, w.W, 'partial watch new $scope');
}
angular.element(oldTag).replaceWith(newTag);
attachEventsAndCompile(newTag[0], scopes[w.I] || NewScope);
if (!attrCompile && !attrCompileAll && w.C) {
$compile(newTag)(scopes[w.I] || NewScope);
}
console.log(attrRender, w.W, 'partial watch content written', newTag[0]);
//unregister watch if wait once
if (w.O) {
console.log(attrRender, w.W, 'partial watch unregistered');
watches[w.I]();
}
console.log(attrRender, w.W, 'partial watch after render');
});
}
}
}
function loader(){
if(doTA.C[attrRender]){
uniqueId = doTA.U[attrRender];
console.log(attrRender,'get compile function from cache');
//watch need to redraw, also inline, because inline always hasChildNodes
if (elem[0].hasChildNodes() && !attrInline) {
console.log('hasChildNodes', attrRender);
renderTemplate();
} else {
renderTemplate(doTA.C[attrRender]);
}
} else if (attrInline) {
// render inline by loading inner html tags,
// html entities encoding sometimes need for htmlparser here or you may use htmlparser2 (untested)
console.log(attrRender,'before get innerHTML');
var v = elem[0].innerHTML;
console.log(attrRender,'after get innerHTML');
renderTemplate(compile(v, attrs));
} else if (attrRender) { //load real template
console.log('before $http', attrRender);
//server side rendering or miss to use inline attrs?
if (elem[0].hasChildNodes()) {
console.log('hasChildNodes', attrRender);
renderTemplate();
} else {
$http.get(attrRender, {cache: $templateCache}).success(function (v) {
console.log('after $http response', attrRender);
renderTemplate(compile(v, attrs));
});
}
}
}
console.timeEnd('render');
//////////////////////////////////////////////////
};
}
};
}
}));
| S-YOU/doTA | ngDoTA.js | JavaScript | mit | 31,300 |
'use strict';
require('jasmine-expect');
var proxyquire = require('proxyquire');
var sinon = require('sinon');
var fsStub = require('../fixtures/fs');
var FilePath = proxyquire('../../utils/file-path', {'fs': fsStub });
describe('file-path', function() {
it('should exist', function() {
expect(FilePath).toBeFunction();
});
describe('FilePath instance', function() {
describe('file', function() {
beforeEach(function() {
fsStub.__isDirectoryStub.returns(false);
sinon.stub(process, 'cwd').returns('/root/my-path');
this.path = '/root/subdir/subsubdir/file.ext';
this.filePath = new FilePath(this.path);
});
afterEach(function() {
process.cwd.restore();
});
it('should provide the file name', function() {
expect(this.filePath.filename).toBe('file');
});
it('should provide the file extension with period prefix', function() {
expect(this.filePath.extension).toBe('.ext');
});
it('should provide the directory path', function() {
expect(this.filePath.directory).toBe('/root/subdir/subsubdir');
});
it('should provide false for directory check', function() {
expect(this.filePath.isDirectory).toBe(false);
});
it('should provide a relative path', function() {
expect(this.filePath.relative).toBe('../subdir/subsubdir');
});
it('should provide the full path', function() {
expect(this.filePath.value).toBe(this.path);
});
});
describe('directory', function() {
beforeEach(function() {
fsStub.__isDirectoryStub.returns(true);
sinon.stub(process, 'cwd').returns('/root/my-path');
this.path = '/root/subdir/subsubdir/my-dir';
this.filePath = new FilePath(this.path);
});
afterEach(function() {
process.cwd.restore();
});
it('should provide the directory name', function() {
expect(this.filePath.filename).toBe('my-dir');
});
it('should provide empty string for the file extension', function() {
expect(this.filePath.extension).toBe('');
});
it('should provide the directory path', function() {
expect(this.filePath.directory).toBe('/root/subdir/subsubdir');
});
it('should provide true for directory check', function() {
expect(this.filePath.isDirectory).toBe(true);
});
it('should provide a relative path', function() {
expect(this.filePath.relative).toBe('../subdir/subsubdir');
});
it('should provide the full path with trailing slash', function() {
expect(this.filePath.value).toBe(this.path+'/');
});
});
});
});
| alistairjcbrown/gulp-lint-filepath | test/utils/file-path.test.js | JavaScript | mit | 2,730 |