<commit_before>'use strict';

function setPlaceholder(event) {
	document.getElementsByClassName('placeholderName')[0].getElementsByTagName('input')[0].value = event.getAttribute('title');
	var placeholderList = document.getElementById('placeholder-list');
	var elements = placeholderList.getElementsByTagName('a');

	for (var i = 0; i < elements.length; i++) {
		elements[i].className = '';
	}

	event.className += 'active';
}

function search(text) {
	var placeholderList = document.getElementById('placeholder-list');
	var elements = placeholderList.getElementsByTagName('a');

	for (var i = 0; i < elements.length; i++) {
		var currentElement = elements[i];
		var title = currentElement.getAttribute('title');

		if (title && title.match(new RegExp(text, 'i')) !== null) {
			currentElement.style.display = 'block';
		} else {
			currentElement.style.display = 'none';
		}
	}
}

function initializeList() {
	var placeholderList = document.getElementById('placeholder-list');
	var elements = placeholderList.getElementsByTagName('a');

	for (var i = 0; i < elements.length; i++) {
		elements[i].className = '';
		elements[i].style.display = 'block';
	}
}

CKEDITOR.dialog.add( 'placeholder2', function( editor ) {
	var validNameRegex = /^[^\[\]<>]+$/;
	var placeholderList = editor.config.placeholder2.map(function(val) {
		return '' + val.value + '';
	});

	return {
		title: 'Placeholder Properties',
		minWidth: 600,
		minHeight: 400,
		contents: [
			{
				id: 'placeholderGroups',
				label: 'Groups',
				title: 'Groups',
				elements: [
					{
						type: 'text',
						id: 'placeholderSearch',
						className: 'placeholderSearch',
						label: 'Search',
						onKeyUp: function(e) {
							search(e.sender.$.value);
						}
					},
					{
						type: 'text',
						id: 'placeholderName',
						className: 'placeholderName',
						style: 'display: none;',
						required: true,
						'default': '',
						validate: CKEDITOR.dialog.validate.regex( validNameRegex, 'Invalid Placeholder' ),
						setup: function( widget ) {
							this.setValue( widget.data.name );
						},
						commit: function( widget ) {
							widget.setData( 'name', this.getValue() );
						}
					},
					{
						type: 'html',
						html: '
'+ placeholderList.join("\n") +'
'
					}
				]
			}
		],
		onOk: function() {
			initializeList();
		},
		onCancel: function() {
			initializeList();
		}
	};
} );
<commit_msg>fix wrong value place<commit_after>'use strict';

function setPlaceholder(event) {
	document.getElementsByClassName('placeholderName')[0].getElementsByTagName('input')[0].value = event.getAttribute('title');
	var placeholderList = document.getElementById('placeholder-list');
	var elements = placeholderList.getElementsByTagName('a');

	for (var i = 0; i < elements.length; i++) {
		elements[i].className = '';
	}

	event.className += 'active';
}

function search(text) {
	var placeholderList = document.getElementById('placeholder-list');
	var elements = placeholderList.getElementsByTagName('a');

	for (var i = 0; i < elements.length; i++) {
		var currentElement = elements[i];
		var title = currentElement.getAttribute('title');

		if (title && title.match(new RegExp(text, 'i')) !== null) {
			currentElement.style.display = 'block';
		} else {
			currentElement.style.display = 'none';
		}
	}
}

function initializeList() {
	var placeholderList = document.getElementById('placeholder-list');
	var elements = placeholderList.getElementsByTagName('a');

	for (var i = 0; i < elements.length; i++) {
		elements[i].className = '';
		elements[i].style.display = 'block';
	}
}

CKEDITOR.dialog.add( 'placeholder2', function( editor ) {
	var validNameRegex = /^[^\[\]<>]+$/;
	var placeholderList = editor.config.placeholder2.map(function(val) {
		return '' + val.label + '';
	});

	return {
		title: 'Placeholder Properties',
		minWidth: 600,
		minHeight: 400,
		contents: [
			{
				id: 'placeholderGroups',
				label: 'Groups',
				title: 'Groups',
				elements: [
					{
						type: 'text',
						id: 'placeholderSearch',
						className: 'placeholderSearch',
						label: 'Search',
						onKeyUp: function(e) {
							search(e.sender.$.value);
						}
					},
					{
						type: 'text',
						id: 'placeholderName',
						className: 'placeholderName',
						style: 'display: none;',
						required: true,
						'default': '',
						validate: CKEDITOR.dialog.validate.regex( validNameRegex, 'Invalid Placeholder' ),
						setup: function( widget ) {
							this.setValue( widget.data.name );
						},
						commit: function( widget ) {
							widget.setData( 'name', this.getValue() );
						}
					},
					{
						type: 'html',
						html: '
'+ placeholderList.join("\n") +'
'
					}
				]
			}
		],
		onOk: function() {
			initializeList();
		},
		onCancel: function() {
			initializeList();
		}
	};
} );
<|endoftext|>


<commit_before>// Future versions of Hyper may add additional config options,
// which will not automatically be merged into this file.
// See https://hyper.is#cfg for all currently supported options.

module.exports = {
  config: {
    // choose either `'stable'` for receiving highly polished,
    // or `'canary'` for less polished but more frequent updates
    updateChannel: "stable",

    // default font size in pixels for all tabs
    fontSize: 11,

    // font family with optional fallbacks
    fontFamily: "Menlo, monospace",

    // default font weight: 'normal' or 'bold'
    fontWeight: "normal",

    // font weight for bold characters: 'normal' or 'bold'
    fontWeightBold: "bold",

    // line height as a relative unit
    lineHeight: 1,

    // letter spacing as a relative unit
    letterSpacing: 0,

    // terminal cursor background color and opacity (hex, rgb, hsl, hsv, hwb or cmyk)
    cursorColor: "rgba(248,28,229,0.8)",

    // terminal text color under BLOCK cursor
    cursorAccentColor: "#000",

    // `'BEAM'` for |, `'UNDERLINE'` for _, `'BLOCK'` for █
    cursorShape: "BLOCK",

    // set to `true` (without backticks and without quotes) for blinking cursor
    cursorBlink: false,

    // color of the text
    foregroundColor: "#fff",

    // terminal background color
    // opacity is only supported on macOS
    backgroundColor: "#000",

    // terminal selection color
    selectionColor: "rgba(248,28,229,0.3)",

    // border color (window, tabs)
    borderColor: "#333",

    // custom CSS to embed in the main window
    css: "",

    // custom CSS to embed in the terminal window
    termCSS: "",

    // if you're using a Linux setup which show native menus, set to false
    // default: `true` on Linux, `true` on Windows, ignored on macOS
    showHamburgerMenu: "",

    // set to `false` (without backticks and without quotes) if you want to hide the minimize, maximize and close buttons
    // additionally, set to `'left'` if you want them on the left, like in Ubuntu
    // default: `true` (without backticks and without quotes) on Windows and Linux, ignored on macOS
    showWindowControls: "",

    // custom padding (CSS format, i.e.: `top right bottom left`)
    padding: "10px 12px",

    // the full list. if you're going to provide the full color palette,
    // including the 6 x 6 color cubes and the grayscale map, just provide
    // an array here instead of a color map object
    colors: {
      black: "#000000",
      red: "#C51E14",
      green: "#1DC121",
      yellow: "#C7C329",
      blue: "#0A2FC4",
      magenta: "#C839C5",
      cyan: "#20C5C6",
      white: "#C7C7C7",
      lightBlack: "#686868",
      lightRed: "#FD6F6B",
      lightGreen: "#67F86F",
      lightYellow: "#FFFA72",
      lightBlue: "#6A76FB",
      lightMagenta: "#FD7CFC",
      lightCyan: "#68FDFE",
      lightWhite: "#FFFFFF",
    },

    // the shell to run when spawning a new session (i.e. /usr/local/bin/fish)
    // if left empty, your system's login shell will be used by default
    //
    // Windows
    // - Make sure to use a full path if the binary name doesn't work
    // - Remove `--login` in shellArgs
    //
    // Bash on Windows
    // - Example: `C:\\Windows\\System32\\bash.exe`
    //
    // PowerShell on Windows
    // - Example: `C:\\WINDOWS\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`
    shell: "",

    // for setting shell arguments (i.e. for using interactive shellArgs: `['-i']`)
    // by default `['--login']` will be used
    shellArgs: ["--login"],

    // for environment variables
    env: {},

    // set to `false` for no bell
    bell: "SOUND",

    // if `true` (without backticks and without quotes), selected text will automatically be copied to the clipboard
    copyOnSelect: true,

    // if `true` (without backticks and without quotes), hyper will be set as the default protocol client for SSH
    defaultSSHApp: true,

    // if `true` (without backticks and without quotes), on right click selected text will be copied or pasted if no
    // selection is present (`true` by default on Windows and disables the context menu feature)
    quickEdit: false,

    // choose either `'vertical'`, if you want the column mode when Option key is hold during selection (Default)
    // or `'force'`, if you want to force selection regardless of whether the terminal is in mouse events mode
    // (inside tmux or vim with mouse mode enabled for example).
    macOptionSelectionMode: "vertical",

    // URL to custom bell
    // bellSoundURL: 'http://example.com/bell.mp3',

    // Whether to use the WebGL renderer. Set it to false to use canvas-based
    // rendering (slower, but supports transparent backgrounds)
    webGLRenderer: true,

    // for advanced config flags please refer to https://hyper.is/#cfg

    // hyper-pane (meta == cmd)
    paneNavigation: {
      debug: false,
      hotkeys: {
        navigation: {
          up: "ctrl+alt+up",
          down: "ctrl+alt+down",
          left: "ctrl+alt+left",
          right: "ctrl+alt+right",
        },
        jump_prefix: "ctrl+alt",
        maximize: "meta+enter",
      },
      showIndicators: true,
      indicatorPrefix: "",
      indicatorStyle: {
        position: "absolute",
        top: 0,
        left: 0,
        fontSize: "10px",
        color: "#444",
      },
      inactivePaneOpacity: 0.5,
    },
  },

  // a list of plugins to fetch and install from npm
  // format: [@org/]project[#version]
  // examples:
  //   `hyperpower`
  //   `@company/project`
  //   `project#1.0.1`
  plugins: [],

  // in development, you can create a directory under
  // `~/.hyper_plugins/local/` and include it here
  // to load it and avoid it being `npm install`ed
  localPlugins: [],

  keymaps: {
    // Fix the ESC-key on canary
    // "editor:break": "esc",
  },
};
<commit_msg>Reduce hyper font size<commit_after>// Future versions of Hyper may add additional config options,
// which will not automatically be merged into this file.
// See https://hyper.is#cfg for all currently supported options.

module.exports = {
  config: {
    // choose either `'stable'` for receiving highly polished,
    // or `'canary'` for less polished but more frequent updates
    updateChannel: "stable",

    // default font size in pixels for all tabs
    fontSize: 10,

    // font family with optional fallbacks
    fontFamily: "Menlo, monospace",

    // default font weight: 'normal' or 'bold'
    fontWeight: "normal",

    // font weight for bold characters: 'normal' or 'bold'
    fontWeightBold: "bold",

    // line height as a relative unit
    lineHeight: 1,

    // letter spacing as a relative unit
    letterSpacing: 0,

    // terminal cursor background color and opacity (hex, rgb, hsl, hsv, hwb or cmyk)
    cursorColor: "rgba(248,28,229,0.8)",

    // terminal text color under BLOCK cursor
    cursorAccentColor: "#000",

    // `'BEAM'` for |, `'UNDERLINE'` for _, `'BLOCK'` for █
    cursorShape: "BLOCK",

    // set to `true` (without backticks and without quotes) for blinking cursor
    cursorBlink: false,

    // color of the text
    foregroundColor: "#fff",

    // terminal background color
    // opacity is only supported on macOS
    backgroundColor: "#000",

    // terminal selection color
    selectionColor: "rgba(248,28,229,0.3)",

    // border color (window, tabs)
    borderColor: "#333",

    // custom CSS to embed in the main window
    css: "",

    // custom CSS to embed in the terminal window
    termCSS: "",

    // if you're using a Linux setup which show native menus, set to false
    // default: `true` on Linux, `true` on Windows, ignored on macOS
    showHamburgerMenu: "",

    // set to `false` (without backticks and without quotes) if you want to hide the minimize, maximize and close buttons
    // additionally, set to `'left'` if you want them on the left, like in Ubuntu
    // default: `true` (without backticks and without quotes) on Windows and Linux, ignored on macOS
    showWindowControls: "",

    // custom padding (CSS format, i.e.: `top right bottom left`)
    padding: "10px 12px",

    // the full list. if you're going to provide the full color palette,
    // including the 6 x 6 color cubes and the grayscale map, just provide
    // an array here instead of a color map object
    colors: {
      black: "#000000",
      red: "#C51E14",
      green: "#1DC121",
      yellow: "#C7C329",
      blue: "#0A2FC4",
      magenta: "#C839C5",
      cyan: "#20C5C6",
      white: "#C7C7C7",
      lightBlack: "#686868",
      lightRed: "#FD6F6B",
      lightGreen: "#67F86F",
      lightYellow: "#FFFA72",
      lightBlue: "#6A76FB",
      lightMagenta: "#FD7CFC",
      lightCyan: "#68FDFE",
      lightWhite: "#FFFFFF",
    },

    // the shell to run when spawning a new session (i.e. /usr/local/bin/fish)
    // if left empty, your system's login shell will be used by default
    //
    // Windows
    // - Make sure to use a full path if the binary name doesn't work
    // - Remove `--login` in shellArgs
    //
    // Bash on Windows
    // - Example: `C:\\Windows\\System32\\bash.exe`
    //
    // PowerShell on Windows
    // - Example: `C:\\WINDOWS\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`
    shell: "",

    // for setting shell arguments (i.e. for using interactive shellArgs: `['-i']`)
    // by default `['--login']` will be used
    shellArgs: ["--login"],

    // for environment variables
    env: {},

    // set to `false` for no bell
    bell: "SOUND",

    // if `true` (without backticks and without quotes), selected text will automatically be copied to the clipboard
    copyOnSelect: true,

    // if `true` (without backticks and without quotes), hyper will be set as the default protocol client for SSH
    defaultSSHApp: true,

    // if `true` (without backticks and without quotes), on right click selected text will be copied or pasted if no
    // selection is present (`true` by default on Windows and disables the context menu feature)
    quickEdit: false,

    // choose either `'vertical'`, if you want the column mode when Option key is hold during selection (Default)
    // or `'force'`, if you want to force selection regardless of whether the terminal is in mouse events mode
    // (inside tmux or vim with mouse mode enabled for example).
    macOptionSelectionMode: "vertical",

    // URL to custom bell
    // bellSoundURL: 'http://example.com/bell.mp3',

    // Whether to use the WebGL renderer. Set it to false to use canvas-based
    // rendering (slower, but supports transparent backgrounds)
    webGLRenderer: true,

    // for advanced config flags please refer to https://hyper.is/#cfg

    // hyper-pane (meta == cmd)
    paneNavigation: {
      debug: false,
      hotkeys: {
        navigation: {
          up: "ctrl+alt+up",
          down: "ctrl+alt+down",
          left: "ctrl+alt+left",
          right: "ctrl+alt+right",
        },
        jump_prefix: "ctrl+alt",
        maximize: "meta+enter",
      },
      showIndicators: true,
      indicatorPrefix: "",
      indicatorStyle: {
        position: "absolute",
        top: 0,
        left: 0,
        fontSize: "10px",
        color: "#444",
      },
      inactivePaneOpacity: 0.5,
    },
  },

  // a list of plugins to fetch and install from npm
  // format: [@org/]project[#version]
  // examples:
  //   `hyperpower`
  //   `@company/project`
  //   `project#1.0.1`
  plugins: [],

  // in development, you can create a directory under
  // `~/.hyper_plugins/local/` and include it here
  // to load it and avoid it being `npm install`ed
  localPlugins: [],

  keymaps: {
    // Fix the ESC-key on canary
    // "editor:break": "esc",
  },
};
<|endoftext|>


<commit_before>var expect = chai.expect;

// Call a function only if there's a error or on the $num attempt
function doneCountBuilder(num, done) {
   return (function () {
        var called = false;
        var count = 0;
        if (!num || num < 0) {
            throw new Error('First argument must be a positive integer.');
        }

        return function (err) {
            if (called === true) {
                return;
            }

            count += 1;
            if (count === num || err) {
                called = true;
                done(err);
            }
        };
    })();
};

describe("doneCountBuilder", function () {
    var builderSpy;
    var doneOnce;

    beforeEach(function () {
        builderSpy = sinon.spy();
        doneOnce = doneCountBuilder(4, builderSpy);
    });

    describe("when it's called a fewer number of times as $num", function () {
        beforeEach(function () {
            for (var i = 0; i <= 2; i += 1) {
                doneOnce();
            }
        });

        it("doesn't call the function", function () {
            expect(builderSpy.called).to.equal(false);
            expect(builderSpy.callCount).to.equal(0);
        });
    });

    describe("when it's called the same number of times as $num", function () {
        beforeEach(function () {
            for (var i = 0; i <= 4; i += 1) {
                doneOnce();
            }
        });

        it("calls the function only once", function () {
            expect(builderSpy.called).to.equal(true);
            expect(builderSpy.callCount).to.equal(1);
        });
    });

    describe("when it's called a greater number of times than $num", function () {
        beforeEach(function () {
            for (var i = 0; i <= 12; i += 1) {
                doneOnce();
            }
        });

        it("calls the function only once", function () {
            expect(builderSpy.called).to.equal(true);
            expect(builderSpy.callCount).to.equal(1);
        });
    });
});

describe("A Direct Connection", function () {
    this.timeout(30000);

    var testEnv;
    var directConnection;
    var follower = {};
    var followee = {};
    var groupId = respoke.makeGUID();
    var groupRole = {
        name: 'fixturerole',
        groups: {
            "*": {
                create: true,
                publish: true,
                subscribe: true,
                unsubscribe: true,
                getsubscribers: true
            }
        }
    };
    var testFixture = fixture("Calling Functional test", {
        roleParams: groupRole
    });

    var followerEndpoint;
    var followeeEndpoint;
    var followerGroup;
    var followeeGroup;
    var followerToken;
    var followeeToken;
    var appId;
    var roleId;

    beforeEach(function (done) {
        respoke.log.setLevel('debug');
        respoke.Q.nfcall(testFixture.beforeTest).then(function (env) {
            testEnv = env;

            return respoke.Q.nfcall(testFixture.createApp, testEnv.httpClient, {}, groupRole);
        }).then(function (params) {
            // create 2 tokens
            roleId = params.role.id;
            appId = params.app.id;
            return [respoke.Q.nfcall(testFixture.createToken, testEnv.httpClient, {
                roleId: roleId,
                appId: appId
            }), respoke.Q.nfcall(testFixture.createToken, testEnv.httpClient, {
                roleId: roleId,
                appId: appId
            })];
        }).spread(function (token1, token2) {
            followerToken = token1;
            followeeToken = token2;

            follower = respoke.createClient();
            followee = respoke.createClient();

            return respoke.Q.all([follower.connect({
                appId: Object.keys(testEnv.allApps)[0],
                baseURL: respokeTestConfig.baseURL,
                token: followerToken.tokenId
            }), followee.connect({
                appId: Object.keys(testEnv.allApps)[0],
                baseURL: respokeTestConfig.baseURL,
                token: followeeToken.tokenId
            })]);
        }).then(function () {
            expect(follower.endpointId).not.to.be.undefined;
            expect(follower.endpointId).to.equal(followerToken.endpointId);
            expect(followee.endpointId).not.to.be.undefined;
            expect(followee.endpointId).to.equal(followeeToken.endpointId);
            follower.listen('call', function () {});
            followee.listen('call', function () {});
        }).done(function () {
            followerEndpoint = followee.getEndpoint({id: follower.endpointId});
            followeeEndpoint = follower.getEndpoint({id: followee.endpointId});
            done();
        }, function (err) {
            expect(err).to.be.defined;
            expect(err.message).to.be.defined;
            done(err);
        });
    });

    describe("when starting a direct connection", function () {
        function callListener(evt) {
            if (!evt.directConnection.call.caller) {
                setTimeout(evt.directConnection.accept);
            }
        }

        describe("with call listener specified", function () {
            var hangupReason;
            var dc;

            beforeEach(function (done) {
                done = doneCountBuilder(1, done);
                followee.listen('direct-connection', callListener);

                directConnection = followeeEndpoint.startDirectConnection({
                    onOpen: function (evt) {
                        directConnection = followeeEndpoint.directConnection;
                        done();
                    },
                    onClose: function (evt) {
                        hangupReason = evt.reason;
                        done();
                    }
                }).done(null, done);
            });

            afterEach(function () {
                followee.ignore('direct-connection', callListener);
            });

            it("succeeds", function () {
                expect(directConnection).to.be.ok;
                expect(hangupReason).to.equal(undefined);
            });
        });
    });

    afterEach(function (done) {
        if (directConnection) {
            directConnection.close();
        }

        respoke.Q.all([follower.disconnect(), followee.disconnect()]).fin(function () {
            testFixture.afterTest(function (err) {
                if (err) {
                    done(new Error(JSON.stringify(err)));
                    return;
                }
                done();
            });
        }).done();
    });
});
<commit_msg>Can't get this one to pass, not worth holding up the whole feature.<commit_after>var expect = chai.expect;

// Call a function only if there's a error or on the $num attempt
function doneCountBuilder(num, done) {
   return (function () {
        var called = false;
        var count = 0;
        if (!num || num < 0) {
            throw new Error('First argument must be a positive integer.');
        }

        return function (err) {
            if (called === true) {
                return;
            }

            count += 1;
            if (count === num || err) {
                called = true;
                done(err);
            }
        };
    })();
};

describe("doneCountBuilder", function () {
    var builderSpy;
    var doneOnce;

    beforeEach(function () {
        builderSpy = sinon.spy();
        doneOnce = doneCountBuilder(4, builderSpy);
    });

    describe("when it's called a fewer number of times as $num", function () {
        beforeEach(function () {
            for (var i = 0; i <= 2; i += 1) {
                doneOnce();
            }
        });

        it("doesn't call the function", function () {
            expect(builderSpy.called).to.equal(false);
            expect(builderSpy.callCount).to.equal(0);
        });
    });

    describe("when it's called the same number of times as $num", function () {
        beforeEach(function () {
            for (var i = 0; i <= 4; i += 1) {
                doneOnce();
            }
        });

        it("calls the function only once", function () {
            expect(builderSpy.called).to.equal(true);
            expect(builderSpy.callCount).to.equal(1);
        });
    });

    describe("when it's called a greater number of times than $num", function () {
        beforeEach(function () {
            for (var i = 0; i <= 12; i += 1) {
                doneOnce();
            }
        });

        it("calls the function only once", function () {
            expect(builderSpy.called).to.equal(true);
            expect(builderSpy.callCount).to.equal(1);
        });
    });
});

describe("A Direct Connection", function () {
    this.timeout(30000);

    var testEnv;
    var directConnection;
    var follower = {};
    var followee = {};
    var groupId = respoke.makeGUID();
    var groupRole = {
        name: 'fixturerole',
        groups: {
            "*": {
                create: true,
                publish: true,
                subscribe: true,
                unsubscribe: true,
                getsubscribers: true
            }
        }
    };
    var testFixture = fixture("Calling Functional test", {
        roleParams: groupRole
    });

    var followerEndpoint;
    var followeeEndpoint;
    var followerGroup;
    var followeeGroup;
    var followerToken;
    var followeeToken;
    var appId;
    var roleId;

    beforeEach(function (done) {
        respoke.log.setLevel('debug');
        respoke.Q.nfcall(testFixture.beforeTest).then(function (env) {
            testEnv = env;

            return respoke.Q.nfcall(testFixture.createApp, testEnv.httpClient, {}, groupRole);
        }).then(function (params) {
            // create 2 tokens
            roleId = params.role.id;
            appId = params.app.id;
            return [respoke.Q.nfcall(testFixture.createToken, testEnv.httpClient, {
                roleId: roleId,
                appId: appId
            }), respoke.Q.nfcall(testFixture.createToken, testEnv.httpClient, {
                roleId: roleId,
                appId: appId
            })];
        }).spread(function (token1, token2) {
            followerToken = token1;
            followeeToken = token2;

            follower = respoke.createClient();
            followee = respoke.createClient();

            return respoke.Q.all([follower.connect({
                appId: Object.keys(testEnv.allApps)[0],
                baseURL: respokeTestConfig.baseURL,
                token: followerToken.tokenId
            }), followee.connect({
                appId: Object.keys(testEnv.allApps)[0],
                baseURL: respokeTestConfig.baseURL,
                token: followeeToken.tokenId
            })]);
        }).then(function () {
            expect(follower.endpointId).not.to.be.undefined;
            expect(follower.endpointId).to.equal(followerToken.endpointId);
            expect(followee.endpointId).not.to.be.undefined;
            expect(followee.endpointId).to.equal(followeeToken.endpointId);
            follower.listen('call', function () {});
            followee.listen('call', function () {});
        }).done(function () {
            followerEndpoint = followee.getEndpoint({id: follower.endpointId});
            followeeEndpoint = follower.getEndpoint({id: followee.endpointId});
            done();
        }, function (err) {
            expect(err).to.be.defined;
            expect(err.message).to.be.defined;
            done(err);
        });
    });

    describe("when starting a direct connection", function () {
        function callListener(evt) {
            if (!evt.directConnection.call.caller) {
                setTimeout(evt.directConnection.accept);
            }
        }

        // Still seeing intermittent failures.
        xdescribe("with call listener specified", function () {
            var hangupReason;
            var dc;

            beforeEach(function (done) {
                done = doneCountBuilder(1, done);
                followee.listen('direct-connection', callListener);

                directConnection = followeeEndpoint.startDirectConnection({
                    onOpen: function (evt) {
                        directConnection = followeeEndpoint.directConnection;
                        done();
                    },
                    onClose: function (evt) {
                        hangupReason = evt.reason;
                        done();
                    }
                }).done(null, done);
            });

            afterEach(function () {
                followee.ignore('direct-connection', callListener);
            });

            it("succeeds", function () {
                expect(directConnection).to.be.ok;
                expect(hangupReason).to.equal(undefined);
            });
        });
    });

    afterEach(function (done) {
        if (directConnection) {
            directConnection.close();
        }

        respoke.Q.all([follower.disconnect(), followee.disconnect()]).fin(function () {
            testFixture.afterTest(function (err) {
                if (err) {
                    done(new Error(JSON.stringify(err)));
                    return;
                }
                done();
            });
        }).done();
    });
});
<|endoftext|>


<commit_before>var _ = require('lodash');
var Promise = require('bluebird');

module.exports = {

  aggregateAuthors: function() {
    var getDuplicatesAuthors = function () {
      return sequelize.query("SELECT DISTINCT name FROM Collaborators where name in (SELECT name FROM (select name, count(*) as sum from Collaborators group by name order by sum desc) s where s.sum > 1) AND email is null order by name;", { type: sequelize.QueryTypes.SELECT});
    };

    return getDuplicatesAuthors().then(function(names) {
      return Promise.map(names, function(nameInstance) {
        var name = nameInstance.name;
        return Collaborator.findAll({
          where: {name: name},
          order: [['email', 'DESC']],
          include: [{
            model: PackageVersion,
            as: 'authored_packages'
          },
          {
            model: PackageVersion,
            as: 'maintained_packages',
            separate: true
          }],
        }).then(function(collaborators) {
          var stays = collaborators[0];
          var others = collaborators.slice(1);
          var authored = _.uniq(_.reduce(others, function(acc, collaborator) {
            return acc.concat(collaborator.authored_packages.map(function(p) {return p.id;}));
          }, []));
          var maintained = _.uniq(_.reduce(others, function(acc, collaborator) {
            return acc.concat(collaborator.maintained_packages.map(function(p) {return p.id;}));
          }, []));

          return stays.addAuthored_packages(authored).then(function(associations) {
            return PackageVersion.update({
              maintainer_id: stays.id
            }, {
              where: { id: { $in: maintained } }
            }).then(function(updated) {
              return Collaborator.destroy({
                where: {id: {$in: others.map(function(o) {return o.id;})}}
              }).then(function() {
                console.info("done: "+ name);
                return {name: name, result: 'success'};
              });
            });

          });

        });

      }, {concurrency:5});
    });

  },

  recoverMaintainer: function() {
    var getSourceJSON = function() {
      return sequelize.query("SELECT id, sourceJSON FROM PackageVersions where sourceJSON IS not null AND maintainer_id is null;", { type: sequelize.QueryTypes.SELECT});
    };

    return getSourceJSON().then(function(packageVersions) {
      return Promise.map(packageVersions, function(packageVersion) {
        var id = packageVersion.id;
        var sourceJSON = packageVersion.sourceJSON;
        var source = JSON.parse(sourceJSON);

        var maintainer = source.Maintainer;
        if (!maintainer) return { id: id, result: 'success'}; //nothing to do;
        var sanitized = AuthorService.authorsSanitizer(maintainer)[0];

        return Collaborator.insertAuthor(sanitized).then(function(maintainerInstance) {
          return PackageVersion.update({maintainer_id: maintainerInstance.id}, {
            where: {id: id},
            fields: ['maintainer_id']
          }).then(function(affecteds) {
            console.log("done: " + id);
            return { id: id, result: 'success'};
          });
        }).catch(function(err) {
          console.log("fail: " + id);
          console.log(err);
          return { id: id, result: 'error', message: err.toString()};
        });

      }, {concurrency: 5});
    });
  },

  extractPersonInfo: function(person) {
    var match = person.match(/[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/i);
    var personJSON = {};
    if(match) {
      person = person.replace(/[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/i
        , '').replace(/</,'').replace(/>/,'');
      personJSON.email = match[0].trim();
    }
    if(person.indexOf("\"")!==-1){
      person = person.split("\"")[1];
    }

    //console.log(person);
    if(person.match(/(\s*([A-Z][^\s,&]*)\s*)+/i)){
      personJSON.name = person.match(/(\s*([A-Z][^\s,&]*)\s*)+/i)[0].trim();

      if(personJSON.name[personJSON.name.length-1]=='.') {
        personJSON.name = personJSON.name.slice(0,personJSON.name.length-1);
      }

      var splittedName = personJSON.name.split(" ");
      if(splittedName.length > 2) {
        var middleName = splittedName[1];
        splittedName.splice(1, 1);
        var newName = splittedName.join(' ');
        personJSON.name = newName;
      }

    } else {
      personJSON = undefined;
    }

    return personJSON;

  },

  authorsSanitizer: function(authorString) {
    var sanitized = authorString.replace('<email>', '')
                                .replace('</email>', '')
                                .replace(/\[.*?\]/g,'')
                                .replace(/\(.*?\)/g,'')
                                .replace(/\n\s*/g,' ')
                                .replace('\t',' ')
                                .replace(/with.*$/g,'')
                                .replace(/based on.*$/g,'')
                                .replace(/assistance.*$/g,'')
                                .replace(/derived from.*$/g,'')
                                .replace(/uses.*$/g,'')
                                .replace(/as represented by.*$/g,'')
                                .replace(/contributions.*$/g,'')
                                .replace(/under.*$/g,'')
                                .replace(/and others.*$/g,'')
                                .replace(/and many others.*$/g,'')
                                .replace(/and authors.*$/g,'')
                                .replace(/assisted.*$/g,'')
                                .trim();

    var separated = sanitized.split(/,\s*and|,|\sand|&|;/);

    var trimmed = separated.map(function(item) {return item.trim();});

    var mapped = trimmed.map(AuthorService.extractPersonInfo);

    var filtered = mapped.filter(function(item){if(item == undefined){return false;} return true;});
    return filtered;

  },

  recoverAuthorsR: function(str){
    if(str.indexOf("as.person(")!==-1){
      return AuthorService.authorsSanitizer(str);
    }

    var person = str.split("person(");
    person.shift();
    var hasMaintainer = false;
    var result = {
      contributors : []
    };

    person.forEach(function(str){
      var list = str.split(",");
      var name = "", middle ="", family = "", email, isMaintainer = false;
      var fullName;
      // console.log("============");
      // console.log(list);

      list.forEach(function(piece){
        if(piece.match(Utils.emailRegex)) {
          email = piece.split("\"")[1];
        }
        if(piece.indexOf("cre")>=0&&!hasMaintainer) {
          isMaintainer=true;
          hasMaintainer=true;
        }
      });

      name = list[0].split("\"")[1];

      if(list[0].indexOf("c(")!==-1) {
        middle = list[1].split("\"")[1];
        family = list[2].split("\"")[1];
        fullName = name +" "+ middle + " "+family;
      }
      else {
        family = list[1].split("\"")[1];
        if (family.trim().match(/^(aut|com|ctb|cph|cre|ctr|dtc|ths|trl)$/))
          fullName = name;
        else
          fullName = name+" "+family;

      }
      var author = {};
      author.name = fullName;

      if(email) {
        author.email = email;
      }

      result.contributors.push(author);

      if(isMaintainer) {
        result.maintainer = author;
      }
    });
    return result;
  },

  parseAllAuthors: function(where) {
    return PackageVersion.findAll({
      where: where
    }).then(function(Results) {
      return Promise.mapSeries(Results, function(Result) {
        try {
          console.log(Result.package_name);
          if(Result.sourceJSON) {
            var json = JSON.parse(Result.sourceJSON);
            var auth = {contributors : []};
            if(json["Authors@R"] && json["Authors@R"].indexOf("as.person(")==-1) {
              auth = AuthorService.recoverAuthorsR(json["Authors@R"]);
            }
            else {
              if(json.Author){
                if(json.Author.indexOf("person(") !== -1) {
                  auth.contributors = AuthorService.recoverAuthorsR(json.Author).contributors;
                } else {
                  auth.contributors = AuthorService.authorsSanitizer(json.Author);
                }
              }
              if(json.Maintainer) {
                auth.maintainer = AuthorService.authorsSanitizer(json.Maintainer)[0];

              }
            }
            return Collaborator.replaceAllAuthors(auth, Result);
          } else return;
        } catch(err) {
          return;
        }
      });
    });
  }
};
<commit_msg>Return same format in all cases<commit_after>var _ = require('lodash');
var Promise = require('bluebird');

module.exports = {

  aggregateAuthors: function() {
    var getDuplicatesAuthors = function () {
      return sequelize.query("SELECT DISTINCT name FROM Collaborators where name in (SELECT name FROM (select name, count(*) as sum from Collaborators group by name order by sum desc) s where s.sum > 1) AND email is null order by name;", { type: sequelize.QueryTypes.SELECT});
    };

    return getDuplicatesAuthors().then(function(names) {
      return Promise.map(names, function(nameInstance) {
        var name = nameInstance.name;
        return Collaborator.findAll({
          where: {name: name},
          order: [['email', 'DESC']],
          include: [{
            model: PackageVersion,
            as: 'authored_packages'
          },
          {
            model: PackageVersion,
            as: 'maintained_packages',
            separate: true
          }],
        }).then(function(collaborators) {
          var stays = collaborators[0];
          var others = collaborators.slice(1);
          var authored = _.uniq(_.reduce(others, function(acc, collaborator) {
            return acc.concat(collaborator.authored_packages.map(function(p) {return p.id;}));
          }, []));
          var maintained = _.uniq(_.reduce(others, function(acc, collaborator) {
            return acc.concat(collaborator.maintained_packages.map(function(p) {return p.id;}));
          }, []));

          return stays.addAuthored_packages(authored).then(function(associations) {
            return PackageVersion.update({
              maintainer_id: stays.id
            }, {
              where: { id: { $in: maintained } }
            }).then(function(updated) {
              return Collaborator.destroy({
                where: {id: {$in: others.map(function(o) {return o.id;})}}
              }).then(function() {
                console.info("done: "+ name);
                return {name: name, result: 'success'};
              });
            });

          });

        });

      }, {concurrency:5});
    });

  },

  recoverMaintainer: function() {
    var getSourceJSON = function() {
      return sequelize.query("SELECT id, sourceJSON FROM PackageVersions where sourceJSON IS not null AND maintainer_id is null;", { type: sequelize.QueryTypes.SELECT});
    };

    return getSourceJSON().then(function(packageVersions) {
      return Promise.map(packageVersions, function(packageVersion) {
        var id = packageVersion.id;
        var sourceJSON = packageVersion.sourceJSON;
        var source = JSON.parse(sourceJSON);

        var maintainer = source.Maintainer;
        if (!maintainer) return { id: id, result: 'success'}; //nothing to do;
        var sanitized = AuthorService.authorsSanitizer(maintainer)[0];

        return Collaborator.insertAuthor(sanitized).then(function(maintainerInstance) {
          return PackageVersion.update({maintainer_id: maintainerInstance.id}, {
            where: {id: id},
            fields: ['maintainer_id']
          }).then(function(affecteds) {
            console.log("done: " + id);
            return { id: id, result: 'success'};
          });
        }).catch(function(err) {
          console.log("fail: " + id);
          console.log(err);
          return { id: id, result: 'error', message: err.toString()};
        });

      }, {concurrency: 5});
    });
  },

  extractPersonInfo: function(person) {
    var match = person.match(/[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/i);
    var personJSON = {};
    if(match) {
      person = person.replace(/[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/i
        , '').replace(/</,'').replace(/>/,'');
      personJSON.email = match[0].trim();
    }
    if(person.indexOf("\"")!==-1){
      person = person.split("\"")[1];
    }

    //console.log(person);
    if(person.match(/(\s*([A-Z][^\s,&]*)\s*)+/i)){
      personJSON.name = person.match(/(\s*([A-Z][^\s,&]*)\s*)+/i)[0].trim();

      if(personJSON.name[personJSON.name.length-1]=='.') {
        personJSON.name = personJSON.name.slice(0,personJSON.name.length-1);
      }

      var splittedName = personJSON.name.split(" ");
      if(splittedName.length > 2) {
        var middleName = splittedName[1];
        splittedName.splice(1, 1);
        var newName = splittedName.join(' ');
        personJSON.name = newName;
      }

    } else {
      personJSON = undefined;
    }

    return personJSON;

  },

  authorsSanitizer: function(authorString) {
    var sanitized = authorString.replace('<email>', '')
                                .replace('</email>', '')
                                .replace(/\[.*?\]/g,'')
                                .replace(/\(.*?\)/g,'')
                                .replace(/\n\s*/g,' ')
                                .replace('\t',' ')
                                .replace(/with.*$/g,'')
                                .replace(/based on.*$/g,'')
                                .replace(/assistance.*$/g,'')
                                .replace(/derived from.*$/g,'')
                                .replace(/uses.*$/g,'')
                                .replace(/as represented by.*$/g,'')
                                .replace(/contributions.*$/g,'')
                                .replace(/under.*$/g,'')
                                .replace(/and others.*$/g,'')
                                .replace(/and many others.*$/g,'')
                                .replace(/and authors.*$/g,'')
                                .replace(/assisted.*$/g,'')
                                .trim();

    var separated = sanitized.split(/,\s*and|,|\sand|&|;/);

    var trimmed = separated.map(function(item) {return item.trim();});

    var mapped = trimmed.map(AuthorService.extractPersonInfo);

    var filtered = mapped.filter(function(item){if(item == undefined){return false;} return true;});
    return filtered;

  },

  recoverAuthorsR: function(str){
    if(str.indexOf("as.person(")!==-1){
      return {
        contributors: AuthorService.authorsSanitizer(str)
      };
    }

    var person = str.split("person(");
    person.shift();
    var hasMaintainer = false;
    var result = {
      contributors : []
    };

    person.forEach(function(str){
      var list = str.split(",");
      var name = "", middle ="", family = "", email, isMaintainer = false;
      var fullName;
      // console.log("============");
      // console.log(list);

      list.forEach(function(piece){
        if(piece.match(Utils.emailRegex)) {
          email = piece.split("\"")[1];
        }
        if(piece.indexOf("cre")>=0&&!hasMaintainer) {
          isMaintainer=true;
          hasMaintainer=true;
        }
      });

      name = list[0].split("\"")[1];

      if(list[0].indexOf("c(")!==-1) {
        middle = list[1].split("\"")[1];
        family = list[2].split("\"")[1];
        fullName = name +" "+ middle + " "+family;
      }
      else {
        family = list[1].split("\"")[1];
        if (family.trim().match(/^(aut|com|ctb|cph|cre|ctr|dtc|ths|trl)$/))
          fullName = name;
        else
          fullName = name+" "+family;

      }
      var author = {};
      author.name = fullName;

      if(email) {
        author.email = email;
      }

      result.contributors.push(author);

      if(isMaintainer) {
        result.maintainer = author;
      }
    });
    return result;
  },

  parseAllAuthors: function(where) {
    return PackageVersion.findAll({
      where: where
    }).then(function(Results) {
      return Promise.mapSeries(Results, function(Result) {
        try {
          console.log(Result.package_name);
          if(Result.sourceJSON) {
            var json = JSON.parse(Result.sourceJSON);
            var auth = {contributors : []};
            if(json["Authors@R"] && json["Authors@R"].indexOf("as.person(")==-1) {
              auth = AuthorService.recoverAuthorsR(json["Authors@R"]);
            }
            else {
              if(json.Author){
                if(json.Author.indexOf("person(") !== -1) {
                  auth.contributors = AuthorService.recoverAuthorsR(json.Author).contributors;
                } else {
                  auth.contributors = AuthorService.authorsSanitizer(json.Author);
                }
              }
              if(json.Maintainer) {
                auth.maintainer = AuthorService.authorsSanitizer(json.Maintainer)[0];

              }
            }
            return Collaborator.replaceAllAuthors(auth, Result);
          } else return;
        } catch(err) {
          return;
        }
      });
    });
  }
};
<|endoftext|>


<commit_before>/*
 * Made with all the love in the world
 * by scireum in Remshalden, Germany
 *
 * Copyright by scireum GmbH
 * http://www.scireum.de - info@scireum.de
 */

(function ($) {
    $.fn.dragMe = function (options) {
        if (typeof options === 'undefined') {
            options = {};
        }
        var _div = this;
        var _touchTarget = $(options.touchTarget) || _div;
        var _container = $(options.container || 'body');
        var _window = $(window);
        _touchTarget.off('mousedown.dragMe').on('mousedown.dragMe', function (e) {
            if (e.which !== 1) {
                return;
            }
            var offset = $(this).offset();
            //mouse position relative to div
            var x = e.pageX - offset.left;
            var y = e.pageY - offset.top;
            _window.on('mousemove.dragMe', function (event) {
                var containerOffset = _container.offset();
                var maxBottom = containerOffset.top + _container.outerHeight() - _div.outerHeight();
                var maxRight = containerOffset.left + _container.outerWidth() - _div.outerWidth();
                var mouseY = event.clientY - y + _container.scrollTop();
                var mouseX = event.clientX - x + _container.scrollLeft()
                var top = Math.min(Math.max(containerOffset.top, mouseY), maxBottom);
                var left = Math.min(Math.max(containerOffset.left, mouseX), maxRight);
                _div.css({
                    position: 'absolute',
                    margin: '',
                    top: top + 'px',
                    left: left + 'px'
                });
            });
        });
        _window.on('mouseup.dragMe', function (e) {
            if (e.which === 1) {
                _window.off('mousemove.dragMe');
            }
        });
    }
}(jQuery));<commit_msg>Changes cursor while dragging<commit_after>/*
 * Made with all the love in the world
 * by scireum in Remshalden, Germany
 *
 * Copyright by scireum GmbH
 * http://www.scireum.de - info@scireum.de
 */

(function ($) {
    $.fn.dragMe = function (options) {
        if (typeof options === 'undefined') {
            options = {};
        }
        var _div = this;
        var _touchTarget = $(options.touchTarget) || _div;
        var _container = $(options.container || 'body');
        var _window = $(window);
        _touchTarget.off('mousedown.dragMe').on('mousedown.dragMe', function (e) {
            if (e.which !== 1) {
                return;
            }

            _touchTarget.css({ cursor: 'move' });

            var offset = $(this).offset();
            //mouse position relative to div
            var x = e.pageX - offset.left;
            var y = e.pageY - offset.top;
            _window.on('mousemove.dragMe', function (event) {
                var containerOffset = _container.offset();
                var maxBottom = containerOffset.top + _container.outerHeight() - _div.outerHeight();
                var maxRight = containerOffset.left + _container.outerWidth() - _div.outerWidth();
                var mouseY = event.clientY - y + _container.scrollTop();
                var mouseX = event.clientX - x + _container.scrollLeft()
                var top = Math.min(Math.max(containerOffset.top, mouseY), maxBottom);
                var left = Math.min(Math.max(containerOffset.left, mouseX), maxRight);
                _div.css({
                    position: 'absolute',
                    margin: '',
                    top: top + 'px',
                    left: left + 'px'
                });
            });
        });
        _window.on('mouseup.dragMe', function (e) {
            if (e.which === 1) {
                _window.off('mousemove.dragMe');

                _touchTarget.css({ cursor: '' });
            }
        });
    }
}(jQuery));<|endoftext|>


<commit_before>$(document).ready(function () {
    // Set initial text
    $('[data-boris]').text('Loading from BORIS...');

    $.getScript('//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.6.0/underscore-min.js', function(){
        $.getScript('//cdnjs.cloudflare.com/ajax/libs/underscore.string/2.3.3/underscore.string.min.js', function(){
            $('[data-boris]').iwiboris();
        });
    });
});

$.fn.exists = function () {
    return this.length > 0;
};

function compactNames(names) {
    return _.compact(_.map(names, function (d) {
        if (d.disp_name && d.disp_name.family) {
            return d.disp_name.family + ( d.disp_name.given ? ', ' + d.disp_name.given[0] + '.' : '' );
        } else if (d.name && d.name.family) {
            return d.name.family + ( d.name.given ? ', ' + d.name.given[0] + '.' : '' );
        }
    }));
}

$.fn.iwiboris = function (callback) {
    $('head').append('<link rel="stylesheet" href="//keetraxx.github.io/boris-loader/boris.css" type="text/css" />');
    var $el = $(this);

    var borisurl = $el.attr('data-boris');
    var $ul = $('
');
    $.getJSON(borisurl + '?callback=?', function (data) {
        $('[data-boris]').text('');
        $el.addClass('boris');

        var borisfilter = $el.attr('data-boris-filter') ? new RegExp($el.attr('data-boris-filter'), 'i') : null;
        $el.append($ul);
        data = _.sortBy(data, function(d){
            return d.date;
        });

        $.each(data, function (i, publication) {

            if (publication.type == "conference_item") {
                publication.type = "conference";
            }

            publication.extended_type = publication.type + '_' + publication[publication.type + '_type'];
            if (borisfilter && !publication.extended_type.match(borisfilter)) {
                return;
            }

            publication.compact_contributors = compactNames(publication.contributors).join(', ');
            publication.compact_editors = compactNames(publication.editors).join(', ');
            publication.compact_creators = compactNames(publication.creators).join(', ');

            publication.year = String(publication.date).match(/2\d{3}/)[0];
            var currentYear = new Date().getFullYear();
            publication.yeargroup = publication.year > currentYear - 10 ? publication.year : '-' + (currentYear - 10);

            var $li = $('
');
            $li.attr('data-year', publication.yeargroup);
            $li.attr('data-extended_type', publication.extended_type);
            var html = '';
            switch (publication.extended_type) {
                case "article_contribution":
                case "article_journal":
                    html += _.string.sprintf('%s (%s). %s. %s %s %s %s [ link ]',
                        publication.compact_creators,
                        publication.year,
                        publication.title[0].text,
                            publication.publication + ', ',
                        publication.volume ? publication.volume : '',
                        publication.number ? '(' + publication.number + '), ' : ', ',
                        publication.pagerange,
                        publication.uri
                    );
                    break;
                case "book_contribution":
                    html += _.string.sprintf('%s (%s). %s. In %s %s%s [ link ]',
                        publication.compact_creators,
                        publication.year,
                        publication.title[0].text,
                        publication.series,
                        publication.place_of_pub ? publication.place_of_pub + ': ' : '',
                        publication.publisher,
                        publication.uri
                    );
                    break;
                case "book_ed_volume":
                case "book_monograph":
                    html += _.string.sprintf('%s (%s). %s. %s%s [ link ]',
                        publication.compact_creators,
                        publication.year,
                        publication.title[0].text,
                        publication.place_of_pub ? publication.place_of_pub + ': ' : '',
                        publication.publisher,
                        publication.uri
                    );
                    break;
                case "book_section_chapter":
                case "book_section_contribution":
                case "book_section_encyclopedia":
                    html += _.string.sprintf('%s (%s). %s. In %s, %s %s %s%s. [ link ]',
                        publication.compact_creators,
                        publication.year,
                        publication.title[0].text,
                            publication.compact_editors.length > 0 ? publication.compact_editors + (publication.editors.length > 1 ? ' (Eds.)' : ' (Ed.)') : '',
                        publication.book_title,
                        publication.pagerange ? '(pp. ' + publication.pagerange + ').' : '',
                        publication.place_of_pub ? publication.place_of_pub + ': ' : '',
                        publication.publisher,
                        publication.uri
                    );
                    break;
                case "conference_speech":
                case "conference_paper":
                case "conference_abstract":
                    html += _.string.sprintf('%s (%s). %s. %s, %s. [ link ]',
                        publication.compact_creators,
                        publication.year,
                        publication.title[0].text,
                        publication.event_title,
                        publication.event_location,
                        publication.uri
                    );
                    break;
                case "report_report":
                    html += _.string.sprintf('%s (%s). %s. %s%s [ link ]',
                        publication.compact_creators,
                        publication.year,
                        publication.title[0].text,
                        publication.place_of_pub ? publication.place_of_pub + ': ' : '',
                        publication.publisher,
                        publication.uri
                    );
                    break;
                case "thesis_dissertation":
                    html += _.string.sprintf('%s (%s). %s (Doctoral dissertation). %s. [ link ]',
                        publication.compact_creators,
                        publication.year,
                        publication.title[0].text,
                        publication.institution,
                        publication.uri
                    );
                    break;
                default:
                    console.log(publication.extended_type, 'not supported yet...?', publication);
                    break;
            }

            $li.html(html);
            $ul.append($li);
            if ( callback ) {
                callback(null, data);
            }
        });

        tree = {};

        _.map(data, function (d) {
            tree[d.extended_type] = tree[d.extended_type] || [];
            tree[d.extended_type].push(d);
        });

        console.log(_.uniq(_.pluck(data, 'extended_type')).sort());

        $ul = $('
');
        _.map(_.compact(_.uniq(_.pluck(data, 'yeargroup'))).sort(), function (d) {
            $ul.prepend('
[ ' + d + ' ]
');
        });

        $el.prepend($ul);

        $('.yearnav li').click(function (ev) {
            ev.preventDefault();
            var year = $(this).attr('data-show');
            $('[data-year]').hide();
            $('[data-year="' + year + '"]').show();
        }).first().click();

    });
};
<commit_msg>Added some comments. close #1<commit_after>$(document).ready(function () {
    // Set initial text
    $('[data-boris]').text('Loading from BORIS...');

    // Load external scripts
    $.getScript('//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.6.0/underscore-min.js', function(){
        $.getScript('//cdnjs.cloudflare.com/ajax/libs/underscore.string/2.3.3/underscore.string.min.js', function(){
            $('[data-boris]').iwiboris();
        });
    });
});

$.fn.exists = function () {
    return this.length > 0;
};

function compactNames(names) {
    return _.compact(_.map(names, function (d) {
        if (d.disp_name && d.disp_name.family) {
            return d.disp_name.family + ( d.disp_name.given ? ', ' + d.disp_name.given[0] + '.' : '' );
        } else if (d.name && d.name.family) {
            return d.name.family + ( d.name.given ? ', ' + d.name.given[0] + '.' : '' );
        }
    }));
}

$.fn.iwiboris = function (callback) {
    $('head').append('<link rel="stylesheet" href="//keetraxx.github.io/boris-loader/boris.css" type="text/css" />');
    var $el = $(this);

    var borisurl = $el.attr('data-boris');
    var $ul = $('
');
    $.getJSON(borisurl + '?callback=?', function (data) {
        $('[data-boris]').text('');
        $el.addClass('boris');

        var borisfilter = $el.attr('data-boris-filter') ? new RegExp($el.attr('data-boris-filter'), 'i') : null;
        $el.append($ul);
        data = _.sortBy(data, function(d){
            return d.date;
        });

        $.each(data, function (i, publication) {

            if (publication.type == "conference_item") {
                publication.type = "conference";
            }

            publication.extended_type = publication.type + '_' + publication[publication.type + '_type'];
            if (borisfilter && !publication.extended_type.match(borisfilter)) {
                return;
            }

            publication.compact_contributors = compactNames(publication.contributors).join(', ');
            publication.compact_editors = compactNames(publication.editors).join(', ');
            publication.compact_creators = compactNames(publication.creators).join(', ');

            publication.year = String(publication.date).match(/2\d{3}/)[0];
            var currentYear = new Date().getFullYear();
            publication.yeargroup = publication.year > currentYear - 10 ? publication.year : '-' + (currentYear - 10);

            var $li = $('
');
            $li.attr('data-year', publication.yeargroup);
            $li.attr('data-extended_type', publication.extended_type);
            var html = '';
            switch (publication.extended_type) {
                case "article_contribution":
                case "article_journal":
                    html += _.string.sprintf('%s (%s). %s. %s %s %s %s [ link ]',
                        publication.compact_creators,
                        publication.year,
                        publication.title[0].text,
                            publication.publication + ', ',
                        publication.volume ? publication.volume : '',
                        publication.number ? '(' + publication.number + '), ' : ', ',
                        publication.pagerange,
                        publication.uri
                    );
                    break;
                case "book_contribution":
                    html += _.string.sprintf('%s (%s). %s. In %s %s%s [ link ]',
                        publication.compact_creators,
                        publication.year,
                        publication.title[0].text,
                        publication.series,
                        publication.place_of_pub ? publication.place_of_pub + ': ' : '',
                        publication.publisher,
                        publication.uri
                    );
                    break;
                case "book_ed_volume":
                case "book_monograph":
                    html += _.string.sprintf('%s (%s). %s. %s%s [ link ]',
                        publication.compact_creators,
                        publication.year,
                        publication.title[0].text,
                        publication.place_of_pub ? publication.place_of_pub + ': ' : '',
                        publication.publisher,
                        publication.uri
                    );
                    break;
                case "book_section_chapter":
                case "book_section_contribution":
                case "book_section_encyclopedia":
                    html += _.string.sprintf('%s (%s). %s. In %s, %s %s %s%s. [ link ]',
                        publication.compact_creators,
                        publication.year,
                        publication.title[0].text,
                            publication.compact_editors.length > 0 ? publication.compact_editors + (publication.editors.length > 1 ? ' (Eds.)' : ' (Ed.)') : '',
                        publication.book_title,
                        publication.pagerange ? '(pp. ' + publication.pagerange + ').' : '',
                        publication.place_of_pub ? publication.place_of_pub + ': ' : '',
                        publication.publisher,
                        publication.uri
                    );
                    break;
                case "conference_speech":
                case "conference_paper":
                case "conference_abstract":
                    html += _.string.sprintf('%s (%s). %s. %s, %s. [ link ]',
                        publication.compact_creators,
                        publication.year,
                        publication.title[0].text,
                        publication.event_title,
                        publication.event_location,
                        publication.uri
                    );
                    break;
                case "report_report":
                    html += _.string.sprintf('%s (%s). %s. %s%s [ link ]',
                        publication.compact_creators,
                        publication.year,
                        publication.title[0].text,
                        publication.place_of_pub ? publication.place_of_pub + ': ' : '',
                        publication.publisher,
                        publication.uri
                    );
                    break;
                case "thesis_dissertation":
                    html += _.string.sprintf('%s (%s). %s (Doctoral dissertation). %s. [ link ]',
                        publication.compact_creators,
                        publication.year,
                        publication.title[0].text,
                        publication.institution,
                        publication.uri
                    );
                    break;
                default:
                    console.log(publication.extended_type, 'not supported yet...?', publication);
                    break;
            }

            $li.html(html);
            $ul.append($li);
            if ( callback ) {
                callback(null, data);
            }
        });

        tree = {};

        _.map(data, function (d) {
            tree[d.extended_type] = tree[d.extended_type] || [];
            tree[d.extended_type].push(d);
        });

        console.log(_.uniq(_.pluck(data, 'extended_type')).sort());

        $ul = $('
');
        _.map(_.compact(_.uniq(_.pluck(data, 'yeargroup'))).sort(), function (d) {
            $ul.prepend('
[ ' + d + ' ]
');
        });

        $el.prepend($ul);

        $('.yearnav li').click(function (ev) {
            ev.preventDefault();
            var year = $(this).attr('data-show');
            $('[data-year]').hide();
            $('[data-year="' + year + '"]').show();
        }).first().click();

    });
};
<|endoftext|>


<commit_before>/**
 * The most accuracy jQuery plugin to detect transitionEnd event
 * https://github.com/pjetrucha/whenTransitionEnd
 *
 * @author Piotr Chrobak
 * @license MIT
 */
(function($, window, document){
	"use strict";

	/**
	 * Helpers (self-documenting)
	 */
	function map(arr, fn){
		for(var tmp = [], i = 0, l = arr.length; i < l; i++){
			tmp.push(fn(arr[i], i));
		}
		return tmp;
	}
	function toFloat(c){
		return parseFloat(c);
	}
	function strTrim(c){
		return c.trim();
	}
	function ifPositiveInteger(x){
		return parseInt(x) === x && x > 0 && x;
	}

	var defaults = {
			timeout: true,
			timeoutDelay: 100,
			endOnFirst: false,
		},
		transitionEnd = (function(){
			var t, el = document.createElement('p'),
				transition = {
					'transition': 'transitionend',
					'WebkitTransition': 'webkitTransitionEnd',
					'MozTransition': 'transitionend',
					'oTransition': 'oTransitionEnd',
				};

			for(t in transition){
				if(el.style[t] !== undefined){
					return transition[t];
				}
			}
			return false;
		})();

	/**
	 * Function detects information about `el` transition
	 * @param {HTMLElement} el
	 * @return {Object|Boolean} returns object with information or false if there's no information detected or event not supported
	 */
	function detect(el){

		if(!transitionEnd) return false;

		var prefix = ['-o-', '-moz-', '-webkit-', ''],
			styles = window.getComputedStyle(el);

		while(prefix.length){
			var pre = prefix.pop(),
				duration;

			/* check if property is set */
			if((duration = styles.getPropertyValue(pre + 'transition-duration'))){
				duration = map(duration.split(','), toFloat);

				/* get max from array */
				if(Math.max.apply(Math, duration) == 0){
					/* if it's 0, it's fake (Firefox) */
					continue;
				}

				var property = map(styles.getPropertyValue(pre + 'transition-property').split(','), strTrim),
					delay = map(styles.getPropertyValue(pre + 'transition-delay').split(','), toFloat),
					sum = -1, time, prop;

				/* find property name which ends last */
				for(var i = 0, l = duration.length; i < l; i++){
					if(sum < (sum = duration[i] + delay[i])){
						prop = property[i];
						time = sum;
					}
				}

				return {
					prop: prop,
					time: time
				};
			}
		}

		return false;
	}

	/**
	 * Wrapper to transitionend listener with setTimeout fallback
	 * @param {jQuery} el
	 * @param {Function} callback
	 * @param {Object} opts - options which extend `defaults`
	 */
	function eventListener(el, callback, opts){
		opts = $.extend(defaults, opts);
		var detected = detect(el[0]),
			ev = (transitionEnd || 'fakeTransitionEnd') + '._' + Date.now(),
			elem = el.eq(0),
			timer;

		elem.on(ev, function(e, type){
			if(
				opts.endOnFirst ||
				(type && (e.type = type)) ||
				detected.prop == 'all' ||
				detected.prop.indexOf(e.originalEvent.propertyName) !== -1 ||
				e.originalEvent.propertyName.indexOf(detected.prop) !== -1
			){
				elem.off(ev);
				clearTimeout(timer);
				callback.call(el, e);
			}
		});

		if(!detected){
			el.triggerHandler(ev, 'empty');
		}
		else if(opts.timeout){
			timer = setTimeout(function(){
				elem.triggerHandler(ev, 'timeout');
			}, ifPositiveInteger(opts.timeout) || (detected.time * 1000 (ifPositiveInteger(opts.timeoutDelay) || 0)));
		}
	}

	/**
	 * jQuery plugin
	 * @param {Function} callback
	 * @param {Object} opts - options which extend `defaults`
	 */
	$.fn.whenTransitionEnd = function(callback, opts){
		var t = this;
		/* trigger layout + setTimeout to ensure function will call after jQuery queue */
		return t[0] && t[0].offsetHeight + setTimeout(function(){
			eventListener(t, callback, opts);
		}) && t || t;
	}

})(jQuery, window, document);
<commit_msg>missing char<commit_after>/**
 * The most accuracy jQuery plugin to detect transitionEnd event
 * https://github.com/pjetrucha/whenTransitionEnd
 *
 * @author Piotr Chrobak
 * @license MIT
 */
(function($, window, document){
	"use strict";

	/**
	 * Helpers (self-documenting)
	 */
	function map(arr, fn){
		for(var tmp = [], i = 0, l = arr.length; i < l; i++){
			tmp.push(fn(arr[i], i));
		}
		return tmp;
	}
	function toFloat(c){
		return parseFloat(c);
	}
	function strTrim(c){
		return c.trim();
	}
	function ifPositiveInteger(x){
		return parseInt(x) === x && x > 0 && x;
	}

	var defaults = {
			timeout: true,
			timeoutDelay: 100,
			endOnFirst: false,
		},
		transitionEnd = (function(){
			var t, el = document.createElement('p'),
				transition = {
					'transition': 'transitionend',
					'WebkitTransition': 'webkitTransitionEnd',
					'MozTransition': 'transitionend',
					'oTransition': 'oTransitionEnd',
				};

			for(t in transition){
				if(el.style[t] !== undefined){
					return transition[t];
				}
			}
			return false;
		})();

	/**
	 * Function detects information about `el` transition
	 * @param {HTMLElement} el
	 * @return {Object|Boolean} returns object with information or false if there's no information detected or event not supported
	 */
	function detect(el){

		if(!transitionEnd) return false;

		var prefix = ['-o-', '-moz-', '-webkit-', ''],
			styles = window.getComputedStyle(el);

		while(prefix.length){
			var pre = prefix.pop(),
				duration;

			/* check if property is set */
			if((duration = styles.getPropertyValue(pre + 'transition-duration'))){
				duration = map(duration.split(','), toFloat);

				/* get max from array */
				if(Math.max.apply(Math, duration) == 0){
					/* if it's 0, it's fake (Firefox) */
					continue;
				}

				var property = map(styles.getPropertyValue(pre + 'transition-property').split(','), strTrim),
					delay = map(styles.getPropertyValue(pre + 'transition-delay').split(','), toFloat),
					sum = -1, time, prop;

				/* find property name which ends last */
				for(var i = 0, l = duration.length; i < l; i++){
					if(sum < (sum = duration[i] + delay[i])){
						prop = property[i];
						time = sum;
					}
				}

				return {
					prop: prop,
					time: time
				};
			}
		}

		return false;
	}

	/**
	 * Wrapper to transitionend listener with setTimeout fallback
	 * @param {jQuery} el
	 * @param {Function} callback
	 * @param {Object} opts - options which extend `defaults`
	 */
	function eventListener(el, callback, opts){
		opts = $.extend(defaults, opts);
		var detected = detect(el[0]),
			ev = (transitionEnd || 'fakeTransitionEnd') + '._' + Date.now(),
			elem = el.eq(0),
			timer;

		elem.on(ev, function(e, type){
			if(
				opts.endOnFirst ||
				(type && (e.type = type)) ||
				detected.prop == 'all' ||
				detected.prop.indexOf(e.originalEvent.propertyName) !== -1 ||
				e.originalEvent.propertyName.indexOf(detected.prop) !== -1
			){
				elem.off(ev);
				clearTimeout(timer);
				callback.call(el, e);
			}
		});

		if(!detected){
			el.triggerHandler(ev, 'empty');
		}
		else if(opts.timeout){
			timer = setTimeout(function(){
				elem.triggerHandler(ev, 'timeout');
			}, ifPositiveInteger(opts.timeout) || (detected.time * 1000 + (ifPositiveInteger(opts.timeoutDelay) || 0)));
		}
	}

	/**
	 * jQuery plugin
	 * @param {Function} callback
	 * @param {Object} opts - options which extend `defaults`
	 */
	$.fn.whenTransitionEnd = function(callback, opts){
		var t = this;
		/* trigger layout + setTimeout to ensure function will call after jQuery queue */
		return t[0] && t[0].offsetHeight + setTimeout(function(){
			eventListener(t, callback, opts);
		}) && t || t;
	}

})(jQuery, window, document);
<|endoftext|>


<commit_before>#!/usr/bin/env node
/**
 * swagger-spec-validator executable command.
 *
 * @copyright Copyright 2017 Kevin Locke <kevin@kevinlocke.name>
 * @license MIT
 */

'use strict';

var Yargs = require('yargs/yargs');
var arrayUniq = require('array-uniq');
var assign = require('object-assign');
var packageJson = require('../package.json');
var swaggerSpecValidator = require('..');
var url = require('url');

function parseHeader(line) {
  // Note: curl uses the header line literally.  We can't due to Node API.
  //       Node enforces name is a valid RFC 7230 token, so remove whitespace
  //       as a convenience for users.
  var match = /^\s*(\S+)\s*: ?(.*)$/.exec(line);
  if (!match) {
    throw new Error('Unable to parse header line "' + line + '"');
  }

  var name = match[1];
  var value = match[2];
  return [name, value];
}

function parseHeaders(lines) {
  return lines.map(parseHeader)
    .reduce(function(headerObj, header) {
      headerObj[header[0]] = header[1];
      return headerObj;
    }, {});
}

/** Calls yargs.parse and passes any thrown errors to the callback.
 * Workaround for https://github.com/yargs/yargs/issues/755
 * @private
 */
function parseYargs(yargs, args, callback) {
  try {
    yargs.parse(args, callback);
  } catch (err) {
    // Since yargs doesn't nextTick its callback, don't here either
    callback(err);
  }
}

/** Gets validation messages from a validation response object.
 * @private
 */
function getMessages(result) {
  var messages = [];
  if (result.messages) {
    messages = messages.concat(result.messages);
  }
  if (result.schemaValidationMessages) {
    messages = messages.concat(result.schemaValidationMessages.map(function(m) {
      return m.level + ': ' + m.message;
    }));
  }
  return messages;
}

function validateAll(specPaths, options, callback) {
  var hadError = false;
  var hadInvalid = false;
  var numValidated = 0;
  specPaths.forEach(function(specPath) {
    function onResult(err, result) {
      if (err) {
        hadError = true;
        if (options.verbosity >= -1) {
          options.err.write(specPath + ': ' + err + '\n');
          if (options.verbosity >= 1) {
            options.err.write(err.stack);
          }
        }
      } else {
        var messages = getMessages(result);
        if (messages.length > 0) {
          hadInvalid = true;
          if (options.verbosity >= 0) {
            options.out.write(messages.join('\n') + '\n');
          }
        }
      }

      numValidated += 1;
      if (numValidated === specPaths.length) {
        if (!hadError && !hadInvalid && options.verbosity >= 0) {
          options.err.write('All OpenAPI/Swagger specs are valid.\n');
        }

        callback(null, hadError ? 2 : hadInvalid ? 1 : 0);
      }
    }

    if (specPath === '-') {
      swaggerSpecValidator.validate(options.in, options, onResult);
    } else {
      swaggerSpecValidator.validateFile(specPath, options, onResult);
    }
  });
}

/** Options for command entry points.
 *
 * @typedef {{
 *   in: (stream.Readable|undefined),
 *   out: (stream.Writable|undefined),
 *   err: (stream.Writable|undefined)
 * }} CommandOptions
 * @property {stream.Readable=} in Stream from which input is read. (default:
 * process.stdin)
 * @property {stream.Writable=} out Stream to which output is written.
 * (default: process.stdout)
 * @property {stream.Writable=} err Stream to which errors (and non-output
 * status messages) are written. (default: process.stderr)
 */
// var CommandOptions;

/** Entry point for this command.
 *
 * @param {!Array<string>} args Command-line arguments.
 * @param {CommandOptions=} options Options.
 * @param {?function(Error, number=)=}
 * callback Callback for the exit code or an Error.
 * @return {Promise<number>|undefined} If callback is not given, a
 * Promise with the exit code or Error.
 * @exports swagger-spec-validator/bin/swagger-spec-validator
 */
function swaggerSpecValidatorCmd(args, options, callback) {
  if (!callback && typeof options === 'function') {
    callback = options;
    options = null;
  }

  if (!callback) {
    return new Promise(function(resolve, reject) {
      swaggerSpecValidatorCmd(args, options, function(err, result) {
        if (err) { reject(err); } else { resolve(result); }
      });
    });
  }

  if (typeof callback !== 'function') {
    throw new TypeError('callback must be a function');
  }

  try {
    if (args === undefined ||
        args === null ||
        (typeof args === 'object' && args.length === 0)) {
      args = [];
    } else if (typeof args !== 'object' ||
               Math.floor(args.length) !== args.length ||
               args.length < 2) {
      throw new TypeError('args must be Array-like with at least 2 elements');
    } else {
      args = Array.prototype.slice.call(args, 2).map(String);
    }

    if (options !== undefined && typeof options !== 'object') {
      throw new TypeError('options must be an object');
    }

    options = assign(
      {
        in: process.stdin,
        out: process.stdout,
        err: process.stderr
      },
      options
    );

    if (!options.in || typeof options.in.on !== 'function') {
      throw new TypeError('options.in must be a stream.Readable');
    }
    if (!options.out || typeof options.out.write !== 'function') {
      throw new TypeError('options.out must be a stream.Writable');
    }
    if (!options.err || typeof options.err.write !== 'function') {
      throw new TypeError('options.err must be a stream.Writable');
    }
  } catch (err) {
    process.nextTick(function() {
      callback(err);
    });
    return undefined;
  }

  var yargs = new Yargs()
    .usage('Usage: $0 [options] [swagger.yaml...]')
    .option('header', {
      alias: 'H',
      describe: 'Additional HTTP header to send',
      requiresArg: true,
      array: true,
      // Prevent array from eating non-option arguments
      nargs: 1,
      coerce: parseHeaders
    })
    .help()
    .alias('help', 'h')
    .alias('help', '?')
    .option('quiet', {
      alias: 'q',
      describe: 'Print less output',
      count: true
    })
    .option('url', {
      alias: 'u',
      describe: 'Validator URL',
      defaultDescription: swaggerSpecValidator.DEFAULT_URL
    })
    .option('verbose', {
      alias: 'v',
      describe: 'Print more output',
      count: true
    })
    .version(packageJson.name + ' ' + packageJson.version)
    .alias('version', 'V')
    .strict();
  parseYargs(yargs, args, function(err, argOpts, output) {
    if (err) {
      options.err.write(output ?
                          output + '\n' :
                          err.name + ': ' + err.message + '\n');
      callback(null, 3);
      return;
    }

    if (output) {
      options.out.write(output + '\n');
    }

    if (argOpts.help || argOpts.version) {
      callback(null, 0);
      return;
    }

    var verbosity = argOpts.verbose - argOpts.quiet;

    var specPaths = argOpts._;
    if (specPaths.length === 0) {
      // Default to validating stdin
      specPaths.push('-');
      if (verbosity > 1) {
        options.out.write('Reading spec from stdin...\n');
      }
    } else if (specPaths.length > 1) {
      specPaths = arrayUniq(specPaths);
    }

    var validateOpts = assign({}, options);
    validateOpts.request = argOpts.url ? url.parse(argOpts.url) : {};
    validateOpts.request.headers = argOpts.header;
    validateOpts.verbosity = verbosity;

    validateAll(specPaths, validateOpts, callback);
  });

  return undefined;
}

swaggerSpecValidatorCmd.default = swaggerSpecValidatorCmd;
module.exports = swaggerSpecValidatorCmd;

if (require.main === module) {
  // This file was invoked directly.
  /* eslint-disable no-process-exit */
  var mainOptions = {
    in: process.stdin,
    out: process.stdout,
    err: process.stderr
  };
  swaggerSpecValidatorCmd(process.argv, mainOptions, function(err, exitCode) {
    if (err) {
      if (err.stdout) { process.stdout.write(err.stdout); }
      if (err.stderr) { process.stderr.write(err.stderr); }
      process.stderr.write(err.name + ': ' + err.message + '\n');

      exitCode = typeof err.exitCode === 'number' ? err.exitCode : 1;
    }

    process.exit(exitCode);
  });
}
<commit_msg>Include path in validation messages<commit_after>#!/usr/bin/env node
/**
 * swagger-spec-validator executable command.
 *
 * @copyright Copyright 2017 Kevin Locke <kevin@kevinlocke.name>
 * @license MIT
 */

'use strict';

var Yargs = require('yargs/yargs');
var arrayUniq = require('array-uniq');
var assign = require('object-assign');
var packageJson = require('../package.json');
var swaggerSpecValidator = require('..');
var url = require('url');

function parseHeader(line) {
  // Note: curl uses the header line literally.  We can't due to Node API.
  //       Node enforces name is a valid RFC 7230 token, so remove whitespace
  //       as a convenience for users.
  var match = /^\s*(\S+)\s*: ?(.*)$/.exec(line);
  if (!match) {
    throw new Error('Unable to parse header line "' + line + '"');
  }

  var name = match[1];
  var value = match[2];
  return [name, value];
}

function parseHeaders(lines) {
  return lines.map(parseHeader)
    .reduce(function(headerObj, header) {
      headerObj[header[0]] = header[1];
      return headerObj;
    }, {});
}

/** Calls yargs.parse and passes any thrown errors to the callback.
 * Workaround for https://github.com/yargs/yargs/issues/755
 * @private
 */
function parseYargs(yargs, args, callback) {
  try {
    yargs.parse(args, callback);
  } catch (err) {
    // Since yargs doesn't nextTick its callback, don't here either
    callback(err);
  }
}

/** Gets validation messages from a validation response object.
 * @private
 */
function getMessages(result) {
  var messages = [];
  if (result.messages) {
    messages = messages.concat(result.messages);
  }
  if (result.schemaValidationMessages) {
    messages = messages.concat(result.schemaValidationMessages.map(function(m) {
      return m.level + ': ' + m.message;
    }));
  }
  return messages;
}

function validateAll(specPaths, options, callback) {
  var hadError = false;
  var hadInvalid = false;
  var numValidated = 0;
  specPaths.forEach(function(specPath) {
    function onResult(err, result) {
      if (err) {
        hadError = true;
        if (options.verbosity >= -1) {
          options.err.write(specPath + ': ' + err + '\n');
          if (options.verbosity >= 1) {
            options.err.write(err.stack);
          }
        }
      } else {
        var messages = getMessages(result);
        if (messages.length > 0) {
          hadInvalid = true;
          if (options.verbosity >= 0) {
            var messagesWithPath = messages.map(function(message) {
              return specPath + ': ' + message;
            });
            options.out.write(messagesWithPath.join('\n') + '\n');
          }
        }
      }

      numValidated += 1;
      if (numValidated === specPaths.length) {
        if (!hadError && !hadInvalid && options.verbosity >= 0) {
          options.err.write('All OpenAPI/Swagger specs are valid.\n');
        }

        callback(null, hadError ? 2 : hadInvalid ? 1 : 0);
      }
    }

    if (specPath === '-') {
      swaggerSpecValidator.validate(options.in, options, onResult);
    } else {
      swaggerSpecValidator.validateFile(specPath, options, onResult);
    }
  });
}

/** Options for command entry points.
 *
 * @typedef {{
 *   in: (stream.Readable|undefined),
 *   out: (stream.Writable|undefined),
 *   err: (stream.Writable|undefined)
 * }} CommandOptions
 * @property {stream.Readable=} in Stream from which input is read. (default:
 * process.stdin)
 * @property {stream.Writable=} out Stream to which output is written.
 * (default: process.stdout)
 * @property {stream.Writable=} err Stream to which errors (and non-output
 * status messages) are written. (default: process.stderr)
 */
// var CommandOptions;

/** Entry point for this command.
 *
 * @param {!Array<string>} args Command-line arguments.
 * @param {CommandOptions=} options Options.
 * @param {?function(Error, number=)=}
 * callback Callback for the exit code or an Error.
 * @return {Promise<number>|undefined} If callback is not given, a
 * Promise with the exit code or Error.
 * @exports swagger-spec-validator/bin/swagger-spec-validator
 */
function swaggerSpecValidatorCmd(args, options, callback) {
  if (!callback && typeof options === 'function') {
    callback = options;
    options = null;
  }

  if (!callback) {
    return new Promise(function(resolve, reject) {
      swaggerSpecValidatorCmd(args, options, function(err, result) {
        if (err) { reject(err); } else { resolve(result); }
      });
    });
  }

  if (typeof callback !== 'function') {
    throw new TypeError('callback must be a function');
  }

  try {
    if (args === undefined ||
        args === null ||
        (typeof args === 'object' && args.length === 0)) {
      args = [];
    } else if (typeof args !== 'object' ||
               Math.floor(args.length) !== args.length ||
               args.length < 2) {
      throw new TypeError('args must be Array-like with at least 2 elements');
    } else {
      args = Array.prototype.slice.call(args, 2).map(String);
    }

    if (options !== undefined && typeof options !== 'object') {
      throw new TypeError('options must be an object');
    }

    options = assign(
      {
        in: process.stdin,
        out: process.stdout,
        err: process.stderr
      },
      options
    );

    if (!options.in || typeof options.in.on !== 'function') {
      throw new TypeError('options.in must be a stream.Readable');
    }
    if (!options.out || typeof options.out.write !== 'function') {
      throw new TypeError('options.out must be a stream.Writable');
    }
    if (!options.err || typeof options.err.write !== 'function') {
      throw new TypeError('options.err must be a stream.Writable');
    }
  } catch (err) {
    process.nextTick(function() {
      callback(err);
    });
    return undefined;
  }

  var yargs = new Yargs()
    .usage('Usage: $0 [options] [swagger.yaml...]')
    .option('header', {
      alias: 'H',
      describe: 'Additional HTTP header to send',
      requiresArg: true,
      array: true,
      // Prevent array from eating non-option arguments
      nargs: 1,
      coerce: parseHeaders
    })
    .help()
    .alias('help', 'h')
    .alias('help', '?')
    .option('quiet', {
      alias: 'q',
      describe: 'Print less output',
      count: true
    })
    .option('url', {
      alias: 'u',
      describe: 'Validator URL',
      defaultDescription: swaggerSpecValidator.DEFAULT_URL
    })
    .option('verbose', {
      alias: 'v',
      describe: 'Print more output',
      count: true
    })
    .version(packageJson.name + ' ' + packageJson.version)
    .alias('version', 'V')
    .strict();
  parseYargs(yargs, args, function(err, argOpts, output) {
    if (err) {
      options.err.write(output ?
                          output + '\n' :
                          err.name + ': ' + err.message + '\n');
      callback(null, 3);
      return;
    }

    if (output) {
      options.out.write(output + '\n');
    }

    if (argOpts.help || argOpts.version) {
      callback(null, 0);
      return;
    }

    var verbosity = argOpts.verbose - argOpts.quiet;

    var specPaths = argOpts._;
    if (specPaths.length === 0) {
      // Default to validating stdin
      specPaths.push('-');
      if (verbosity > 1) {
        options.out.write('Reading spec from stdin...\n');
      }
    } else if (specPaths.length > 1) {
      specPaths = arrayUniq(specPaths);
    }

    var validateOpts = assign({}, options);
    validateOpts.request = argOpts.url ? url.parse(argOpts.url) : {};
    validateOpts.request.headers = argOpts.header;
    validateOpts.verbosity = verbosity;

    validateAll(specPaths, validateOpts, callback);
  });

  return undefined;
}

swaggerSpecValidatorCmd.default = swaggerSpecValidatorCmd;
module.exports = swaggerSpecValidatorCmd;

if (require.main === module) {
  // This file was invoked directly.
  /* eslint-disable no-process-exit */
  var mainOptions = {
    in: process.stdin,
    out: process.stdout,
    err: process.stderr
  };
  swaggerSpecValidatorCmd(process.argv, mainOptions, function(err, exitCode) {
    if (err) {
      if (err.stdout) { process.stdout.write(err.stdout); }
      if (err.stderr) { process.stderr.write(err.stderr); }
      process.stderr.write(err.name + ': ' + err.message + '\n');

      exitCode = typeof err.exitCode === 'number' ? err.exitCode : 1;
    }

    process.exit(exitCode);
  });
}
<|endoftext|>


<commit_before>
var editor;

Dependency.autorun(function() {
  editor = Dependency.get('editorService');
});

Dependency.add('browserService', (function browserService() {
  var s = {};

  var data = {
    path: new ReactiveVar([]),
    items: new ReactiveVar([])
  };

  /**
   * @summary Initialize browser service
   * @method init
   */
  s.init = function() {
    var path = data.path.get();
    if (!path.length || (path[0]._id !== editor.context.root()._id)) {
      data.path.set([]);
      s.forward(editor.context.root());
    }

    updateItems();
  };

  /**
   * @summary Set the next level of graph hierarchy
   * @method forward
   * @param {Object} [node] R or T node
   */
  s.forward = function(node) {
    if ((node.type === 'T') || node.type === 'R') {
      var path = data.path.get();
      path.push(node);
      data.path.set(path);
      editor.select(node);
    }
  };

  /**
   * @summary Go to the previous level of graph hierarchy
   * @method back
   * @param {Object} [root] new (browser context) root node
   */
  s.back = function(root) {
    var path = data.path.get();

    while (path[path.length-1]._id !== root._id) {
      path.pop();
    }

    data.path.set(path);
    editor.select(s.root());
  };

  /**
   * @summary Get root node of browser context
   * @method root
   * @return {Object}
   */
  s.root = function() {
    var path = data.path.get();
    return path[path.length-1];
  };

  /**
   * @summary Retrieve root node parent
   * @method parent
   * @return {Object}
   */
  s.parent = function() {
    var path = data.path.get();
    if (path.length > 1) {
      return path[path.length-2];
    }

    return null;
  };

  /**
   * @summary Get browser path
   * @method path
   * @return {Array}
   */
  s.path = function() {
    return data.path.get();
  };

  /**
   * @summary Get items on current path
   * @method items
   * @return {Array}
   */
  s.items = function() {
    return data.items.get();
  };

  /**
   * @summary Update browser items
   * @method updateItems
   */
  function updateItems() {
    var graph = editor.context.graph();
    var node = graph.$('#' + s.root()._id);
    var children = [];

    node.outgoers('[type = "T"], [type = "O"]').forEach(function(it) {
      children.push(it.id());
    });

    var items = Nodes.find({
      _id : {
        $in : children
      }
    }, { sort: { createdAt: 1 } }).fetch();

    data.items.set(items);
  }

  return s;
})());
<commit_msg>Browser service update<commit_after>
var editor;

Dependency.autorun(function() {
  editor = Dependency.get('editorService');
});

Dependency.add('browserService', (function browserService() {
  var s = {};

  var data = {
    path: new ReactiveVar([]),
    items: new ReactiveVar([])
  };

  /**
   * @summary Initialize browser service
   * @method init
   */
  s.init = function() {
    var path = data.path.get();
    if (!path.length || (path[0] !== editor.context.root()._id)) {
      data.path.set([]);
      s.forward(editor.context.root());
    }

    updateItems();
  };

  /**
   * @summary Set the next level of graph hierarchy
   * @method forward
   * @param {Object} [node] R or T node
   */
  s.forward = function(node) {
    if ((node.type === 'T') || node.type === 'R') {
      var path = data.path.get();
      path.push(node._id);
      data.path.set(path);
      editor.select(node);
    }
  };

  /**
   * @summary Go to the previous level of graph hierarchy
   * @method back
   * @param {Object} [root] new (browser context) root node
   */
  s.back = function(root) {
    var path = data.path.get();

    while (path[path.length-1] !== root._id) {
      path.pop();
    }

    data.path.set(path);
    editor.select(s.root());
  };

  /**
   * @summary Get root node of browser context
   * @method root
   * @return {Object}
   */
  s.root = function() {
    var path = data.path.get();
    return Nodes.findOne({ _id: path[path.length-1] });
  };

  /**
   * @summary Retrieve root node parent
   * @method parent
   * @return {Object}
   */
  s.parent = function() {
    var path = data.path.get();
    if (path.length > 1) {
      return Nodes.findOne({ _id: path[path.length-2] });
    }

    return null;
  };

  /**
   * @summary Get browser path
   * @method path
   * @return {Array}
   */
  s.path = function() {
    var path = data.path.get();

    var nodes = Nodes.find({ _id: { $in: path } }).fetch();
    nodes = Lazy(nodes).indexBy('_id').toObject();

    return Lazy(path).map(function(nodeId) { return nodes[nodeId]; }).toArray();
  };

  /**
   * @summary Get items on current path
   * @method items
   * @return {Array}
   */
  s.items = function() {
    return data.items.get();
  };

  /**
   * @summary Update browser items
   * @method updateItems
   */
  function updateItems() {
    var graph = editor.context.graph();
    var node = graph.$('#' + s.root()._id);
    var children = [];

    node.outgoers('[type = "T"], [type = "O"]').forEach(function(it) {
      children.push(it.id());
    });

    var items = Nodes.find({
      _id : {
        $in : children
      }
    }, { sort: { createdAt: 1 } }).fetch();

    data.items.set(items);
  }

  return s;
})());
<|endoftext|>


<commit_before>const randomizeCase = word => word.split('').map(c => Math.random() > 0.5 ? c.toUpperCase() : c.toLowerCase()).join('');

exports.run = (bot, msg, args) => {
    if (args.length < 1) {
        throw 'Please provide some text to clapify';
    }

    msg.edit(args.map(randomizeCase).join(':clap:'));
};

exports.info = {
    name: 'clap',
    usage: 'clap <text>',
    description: 'Calpifies your text'
};
<commit_msg>Fix typo in //clap description<commit_after>const randomizeCase = word => word.split('').map(c => Math.random() > 0.5 ? c.toUpperCase() : c.toLowerCase()).join('');

exports.run = (bot, msg, args) => {
    if (args.length < 1) {
        throw 'Please provide some text to clapify';
    }

    msg.edit(args.map(randomizeCase).join(':clap:'));
};

exports.info = {
    name: 'clap',
    usage: 'clap <text>',
    description: 'Clapifies your text'
};
<|endoftext|>