<commit_before>/*global setImmediate:true*/

if (typeof setImmediate === 'undefined') {
    setImmediate = process.nextTick;
}

var BufferedStream = require('bufferedstream'),
    URL = require('url'),
    http = require('http'),
    _ = require('underscore'),
    messy = require('messy'),
    metadataPropertyNames = ['strictAsync', 'errorPassedToNext', 'isDestroyed', 'nextCalled'];

module.exports = function (expect) {
    expect.installPlugin(require('unexpected-messy'));

    expect.addAssertion('to be middleware that processes', function (expect, subject, value, _done) {
        this.errorMode = 'nested';
        expect(_done, 'to be a function');

        var doneCalled = false;

        function done() {
            if (!doneCalled) {
                doneCalled = true;
                return _done.apply(this, arguments);
            }
        }

        var requestProperties = typeof value.request === 'string' ? {url: value.request} : _.extend({}, value.request),
            httpRequest = new messy.HttpRequest({
                method: requestProperties.method,
                url: requestProperties.url || '/',
                protocolName: 'HTTP',
                protocolVersion: requestProperties.httpVersion || '1.1',
                headers: requestProperties.headers,
                body: requestProperties.body
            });
        delete value.request;
        delete requestProperties.method;
        delete requestProperties.url;
        delete requestProperties.httpVersion;
        delete requestProperties.headers;
        delete requestProperties.body;
        if (typeof httpRequest.url === 'string') {
            var matchMethod = httpRequest.url.match(/^([A-Z]+) ([\s\S]*)$/);
            if (matchMethod) {
                httpRequest.method = httpRequest.method || matchMethod[1];
                httpRequest.url = matchMethod[2];
            }
        }
        httpRequest.method = httpRequest.method || 'GET';
        if (/^https?:\/\//.test(httpRequest.url)) {
            var urlObj = URL.parse(httpRequest.url);
            if (!httpRequest.headers.has('Host')) {
                httpRequest.headers.set('Host', urlObj.host);
            }
            if (urlObj.protocol === 'https:' && typeof requestProperties.https === 'undefined') {
                requestProperties.https = true;
            }
            httpRequest.url = urlObj.path;
        }

        var expectedResponseProperties;

        if (typeof value.response === 'number') {
            expectedResponseProperties = {statusCode: value.response};
        } else if (typeof value.response === 'string' || Buffer.isBuffer(value.response)) {
            expectedResponseProperties = {body: value.response};
        } else {
            expectedResponseProperties = _.extend({}, value.response);
        }
        delete value.response;

        // Avoid: "// should be 200 Bad Request" when no expected status message is provided
        if (typeof expectedResponseProperties.statusCode === 'number' && typeof expectedResponseProperties.statusMessage === 'undefined' && expectedResponseProperties.statusCode in http.STATUS_CODES) {
            expectedResponseProperties.statusMessage = http.STATUS_CODES[expectedResponseProperties.statusCode];
        }

        var responseProperties = {},
            requestStream,
            req;

        if (typeof httpRequest.body !== 'undefined') {
            if (httpRequest.body.pipe) {
                requestStream = httpRequest.body;
                if (requestStream.constructor && requestStream.constructor.name === 'FormData') {
                    if (!httpRequest.headers.has('Content-Type')) {
                        httpRequest.headers.set('Content-Type', 'multipart/form-data; boundary=' + requestStream.getBoundary());
                        // form-data pauses its streams by default for some reason:
                        setImmediate(function () {
                            requestStream.resume();
                        });
                    }
                }
                if (!httpRequest.headers.has('Transfer-Encoding')) {
                    httpRequest.headers.set('Transfer-Encoding', 'chunked');
                }
                var requestBodyChunks = [];
                requestStream.on('data', function (chunk) {
                    if (!Buffer.isBuffer(chunk)) {
                        chunk = new Buffer(chunk, 'utf-8');
                    }
                    requestBodyChunks.push(chunk);
                    req.emit('data', chunk);
                }).on('end', function () {
                    httpRequest.body = Buffer.concat(requestBodyChunks);
                    req.emit('end');
                }).on('error', function (err) {
                    req.emit('error', err);
                });
            } else {
                if (typeof httpRequest.body === 'object' && !Buffer.isBuffer(httpRequest.body)) {
                    if (!httpRequest.headers.has('Content-Type')) {
                        httpRequest.headers.set('Content-Type', 'application/json');
                    }
                    httpRequest.body = JSON.stringify(httpRequest.body);
                }

                if (!Buffer.isBuffer(httpRequest.body)) {
                    httpRequest.body = new Buffer(String(httpRequest.body), 'utf-8');
                }
                if (!httpRequest.headers.has('Content-Length') && !httpRequest.headers.has('Transfer-Encoding')) {
                    httpRequest.headers.set('Content-Length', String(httpRequest.body.length));
                }
                requestStream = new BufferedStream();
                setImmediate(function () {
                    req.emit('data', httpRequest.body);
                    req.emit('end');
                });
            }
        } else {
            requestStream = new BufferedStream();
            requestStream.destroy = function () {
                responseProperties.requestDestroyed = true;
            };
            setImmediate(function () {
                requestStream.emit('end');
                req.emit('end');
            });
        }

        req = new http.IncomingMessage(requestStream);
        req.httpVersion = httpRequest.protocolVersion;
        var matchProtocolVersion = String(httpRequest.protocolVersion).match(/^(\d+)(?:\.(\d+))$/);
        if (matchProtocolVersion) {
            req.httpVersionMajor = parseInt(matchProtocolVersion[1], 10);
            req.httpVersionMinor = matchProtocolVersion[2] ? parseInt(matchProtocolVersion[2], 10) : 0;
        }
        req.connection = req.connection || {};
        req.connection.encrypted = !!requestProperties.https;
        delete requestProperties.https;
        req.connection.remoteAddress = requestProperties.remoteAddress || requestProperties.ip || '127.0.0.1';
        delete requestProperties.ip;
        delete requestProperties.remoteAddress;
        req.headers = {};
        httpRequest.headers.getNames().forEach(function (headerName) {
            if (headerName === 'set-cookie') {
                req.headers[headerName] = [].concat(httpRequest.headers.valuesByName[headerName]);
            } else {
                req.headers[headerName] = httpRequest.headers.valuesByName[headerName].join(', ');
            }
        });
        req.method = httpRequest.method;
        req.url = httpRequest.url;
        _.extend(req, requestProperties);

        var res = new http.ServerResponse(req);
        _.extend(res, requestProperties.res); // Allows for specifying eg. res.locals
        res.connection = new BufferedStream();
        res.connection._httpMessage = res;

        var nextCallCount = 0,
            next = function (err, _req, _res, _next) {
                nextCallCount += 1;
                if (typeof err === 'number') {
                    var statusCode = err;
                    err = new Error('' + statusCode);
                    err.statusCode = statusCode;
                }
                res.statusCode = err && (err.statusCode || err.status) || 404;
                doTheAssertions(err);
            };

        var responseBodyChunks = [],
            isDestroyed = false,
            isAsync = false;

        setImmediate(function () {
            isAsync = true;
        });

        function doTheAssertions(errorPassedToNext) {
            var err = null,
                context = {
                    req: req,
                    res: res,
                    next: next,
                    httpRequest: httpRequest,
                    metadata: {
                        strictAsync: isAsync,
                        errorPassedToNext: false,
                        isDestroyed: isDestroyed,
                        nextCalled: nextCallCount > 0
                    }
                },
                expectedMetadata = _.extend(
                    {},
                    _.pick(expectedResponseProperties, metadataPropertyNames),
                    _.pick(value, metadataPropertyNames)
                );

            // Apparently setImmediate (or throwing an exception) is not an option here. If we don't call done, errors won't make it into mocha.
            try {
                if (errorPassedToNext) {
                    context.metadata.errorPassedToNext = errorPassedToNext;
                    if (typeof expectedMetadata.errorPassedToNext !== 'undefined') {
                        if (expectedMetadata.errorPassedToNext === true) {
                            context.metadata.errorPassedToNext = true;
                        } else if (typeof expectedMetadata.errorPassedToNext === 'string') {
                            context.metadata.errorPassedToNext = errorPassedToNext.message;
                        } else {
                            context.metadata.errorPassedToNext = errorPassedToNext;
                        }
                    } else {
                        return setImmediate(function () {
                            done(errorPassedToNext);
                        });
                    }
                }
                var httpResponse = context.httpResponse = new messy.HttpResponse(res._header || undefined); // Avoid a parse error if empty string
                httpResponse.statusCode = res.statusCode;
                httpResponse.body = Buffer.concat(responseBodyChunks.map(function (bufferOrString) {
                    if (!Buffer.isBuffer(bufferOrString)) {
                        return new Buffer(String(bufferOrString), 'utf-8');
                    } else {
                        return bufferOrString;
                    }
                }));

                expect(context.metadata, 'to satisfy', expectedMetadata);

                try {
                    expect(httpResponse, 'to satisfy', expectedResponseProperties);
                } catch (e) {
                    var expectedResponseHeaders = httpResponse.headers.clone();
                    _.extend(expectedResponseHeaders.valuesByName, new messy.Headers(expectedResponseProperties.headers).valuesByName);
                    if (expectedResponseProperties.headers) {
                        Object.keys(expectedResponseProperties.headers).forEach(function (headerName) {
                            if (typeof expectedResponseProperties.headers[headerName] === 'undefined') {
                                expectedResponseHeaders.remove(headerName);
                            }
                        });
                    }

                    var expectedHttpResponse = context.expectedHttpResponse = new messy.HttpResponse({
                        statusLine: _.defaults(_.pick(expectedResponseProperties, messy.StatusLine.propertyNames), httpResponse.statusLine),
                        headers: expectedResponseHeaders,
                        body: expectedResponseProperties.body
                    });
                    expect.fail(function (output) {
                        httpRequest.upgradeBody();
                        return output
                            .append(expect.inspect(httpRequest)).nl(2)
                            .append(expect.diff(httpResponse, expectedHttpResponse).diff);
                   });
                }
            } catch (assertionError) {
                err = assertionError;
            }
            setImmediate(function () {
                done(err, context);
            });
        }
        ['write', 'end', 'destroy'].forEach(function (methodName) {
            var orig = res[methodName];
            res[methodName] = function (chunk, encoding) {
                var returnValue = orig.apply(this, arguments);
                if (methodName !== 'destroy') {
                    if (encoding && !/^utf-?8$/i.test(encoding)) {
                        throw new Error('encoding parameter not supported except for "utf-8": ' + encoding);
                    }
                    if (chunk) {
                        responseBodyChunks.push(chunk);
                    }
                }
                if (methodName === 'end' || methodName === 'destroy') {
                    isDestroyed = methodName === 'destroy';
                    doTheAssertions();
                }
                return returnValue;
            };
        });
        subject(req, res, next);
    });
};
<commit_msg>Only define the assertion for functions<commit_after>/*global setImmediate:true*/

if (typeof setImmediate === 'undefined') {
    setImmediate = process.nextTick;
}

var BufferedStream = require('bufferedstream'),
    URL = require('url'),
    http = require('http'),
    _ = require('underscore'),
    messy = require('messy'),
    metadataPropertyNames = ['strictAsync', 'errorPassedToNext', 'isDestroyed', 'nextCalled'];

module.exports = function (expect) {
    expect.installPlugin(require('unexpected-messy'));

    expect.addAssertion('function', 'to be middleware that processes', function (expect, subject, value, _done) {
        this.errorMode = 'nested';
        expect(_done, 'to be a function');

        var doneCalled = false;

        function done() {
            if (!doneCalled) {
                doneCalled = true;
                return _done.apply(this, arguments);
            }
        }

        var requestProperties = typeof value.request === 'string' ? {url: value.request} : _.extend({}, value.request),
            httpRequest = new messy.HttpRequest({
                method: requestProperties.method,
                url: requestProperties.url || '/',
                protocolName: 'HTTP',
                protocolVersion: requestProperties.httpVersion || '1.1',
                headers: requestProperties.headers,
                body: requestProperties.body
            });
        delete value.request;
        delete requestProperties.method;
        delete requestProperties.url;
        delete requestProperties.httpVersion;
        delete requestProperties.headers;
        delete requestProperties.body;
        if (typeof httpRequest.url === 'string') {
            var matchMethod = httpRequest.url.match(/^([A-Z]+) ([\s\S]*)$/);
            if (matchMethod) {
                httpRequest.method = httpRequest.method || matchMethod[1];
                httpRequest.url = matchMethod[2];
            }
        }
        httpRequest.method = httpRequest.method || 'GET';
        if (/^https?:\/\//.test(httpRequest.url)) {
            var urlObj = URL.parse(httpRequest.url);
            if (!httpRequest.headers.has('Host')) {
                httpRequest.headers.set('Host', urlObj.host);
            }
            if (urlObj.protocol === 'https:' && typeof requestProperties.https === 'undefined') {
                requestProperties.https = true;
            }
            httpRequest.url = urlObj.path;
        }

        var expectedResponseProperties;

        if (typeof value.response === 'number') {
            expectedResponseProperties = {statusCode: value.response};
        } else if (typeof value.response === 'string' || Buffer.isBuffer(value.response)) {
            expectedResponseProperties = {body: value.response};
        } else {
            expectedResponseProperties = _.extend({}, value.response);
        }
        delete value.response;

        // Avoid: "// should be 200 Bad Request" when no expected status message is provided
        if (typeof expectedResponseProperties.statusCode === 'number' && typeof expectedResponseProperties.statusMessage === 'undefined' && expectedResponseProperties.statusCode in http.STATUS_CODES) {
            expectedResponseProperties.statusMessage = http.STATUS_CODES[expectedResponseProperties.statusCode];
        }

        var responseProperties = {},
            requestStream,
            req;

        if (typeof httpRequest.body !== 'undefined') {
            if (httpRequest.body.pipe) {
                requestStream = httpRequest.body;
                if (requestStream.constructor && requestStream.constructor.name === 'FormData') {
                    if (!httpRequest.headers.has('Content-Type')) {
                        httpRequest.headers.set('Content-Type', 'multipart/form-data; boundary=' + requestStream.getBoundary());
                        // form-data pauses its streams by default for some reason:
                        setImmediate(function () {
                            requestStream.resume();
                        });
                    }
                }
                if (!httpRequest.headers.has('Transfer-Encoding')) {
                    httpRequest.headers.set('Transfer-Encoding', 'chunked');
                }
                var requestBodyChunks = [];
                requestStream.on('data', function (chunk) {
                    if (!Buffer.isBuffer(chunk)) {
                        chunk = new Buffer(chunk, 'utf-8');
                    }
                    requestBodyChunks.push(chunk);
                    req.emit('data', chunk);
                }).on('end', function () {
                    httpRequest.body = Buffer.concat(requestBodyChunks);
                    req.emit('end');
                }).on('error', function (err) {
                    req.emit('error', err);
                });
            } else {
                if (typeof httpRequest.body === 'object' && !Buffer.isBuffer(httpRequest.body)) {
                    if (!httpRequest.headers.has('Content-Type')) {
                        httpRequest.headers.set('Content-Type', 'application/json');
                    }
                    httpRequest.body = JSON.stringify(httpRequest.body);
                }

                if (!Buffer.isBuffer(httpRequest.body)) {
                    httpRequest.body = new Buffer(String(httpRequest.body), 'utf-8');
                }
                if (!httpRequest.headers.has('Content-Length') && !httpRequest.headers.has('Transfer-Encoding')) {
                    httpRequest.headers.set('Content-Length', String(httpRequest.body.length));
                }
                requestStream = new BufferedStream();
                setImmediate(function () {
                    req.emit('data', httpRequest.body);
                    req.emit('end');
                });
            }
        } else {
            requestStream = new BufferedStream();
            requestStream.destroy = function () {
                responseProperties.requestDestroyed = true;
            };
            setImmediate(function () {
                requestStream.emit('end');
                req.emit('end');
            });
        }

        req = new http.IncomingMessage(requestStream);
        req.httpVersion = httpRequest.protocolVersion;
        var matchProtocolVersion = String(httpRequest.protocolVersion).match(/^(\d+)(?:\.(\d+))$/);
        if (matchProtocolVersion) {
            req.httpVersionMajor = parseInt(matchProtocolVersion[1], 10);
            req.httpVersionMinor = matchProtocolVersion[2] ? parseInt(matchProtocolVersion[2], 10) : 0;
        }
        req.connection = req.connection || {};
        req.connection.encrypted = !!requestProperties.https;
        delete requestProperties.https;
        req.connection.remoteAddress = requestProperties.remoteAddress || requestProperties.ip || '127.0.0.1';
        delete requestProperties.ip;
        delete requestProperties.remoteAddress;
        req.headers = {};
        httpRequest.headers.getNames().forEach(function (headerName) {
            if (headerName === 'set-cookie') {
                req.headers[headerName] = [].concat(httpRequest.headers.valuesByName[headerName]);
            } else {
                req.headers[headerName] = httpRequest.headers.valuesByName[headerName].join(', ');
            }
        });
        req.method = httpRequest.method;
        req.url = httpRequest.url;
        _.extend(req, requestProperties);

        var res = new http.ServerResponse(req);
        _.extend(res, requestProperties.res); // Allows for specifying eg. res.locals
        res.connection = new BufferedStream();
        res.connection._httpMessage = res;

        var nextCallCount = 0,
            next = function (err, _req, _res, _next) {
                nextCallCount += 1;
                if (typeof err === 'number') {
                    var statusCode = err;
                    err = new Error('' + statusCode);
                    err.statusCode = statusCode;
                }
                res.statusCode = err && (err.statusCode || err.status) || 404;
                doTheAssertions(err);
            };

        var responseBodyChunks = [],
            isDestroyed = false,
            isAsync = false;

        setImmediate(function () {
            isAsync = true;
        });

        function doTheAssertions(errorPassedToNext) {
            var err = null,
                context = {
                    req: req,
                    res: res,
                    next: next,
                    httpRequest: httpRequest,
                    metadata: {
                        strictAsync: isAsync,
                        errorPassedToNext: false,
                        isDestroyed: isDestroyed,
                        nextCalled: nextCallCount > 0
                    }
                },
                expectedMetadata = _.extend(
                    {},
                    _.pick(expectedResponseProperties, metadataPropertyNames),
                    _.pick(value, metadataPropertyNames)
                );

            // Apparently setImmediate (or throwing an exception) is not an option here. If we don't call done, errors won't make it into mocha.
            try {
                if (errorPassedToNext) {
                    context.metadata.errorPassedToNext = errorPassedToNext;
                    if (typeof expectedMetadata.errorPassedToNext !== 'undefined') {
                        if (expectedMetadata.errorPassedToNext === true) {
                            context.metadata.errorPassedToNext = true;
                        } else if (typeof expectedMetadata.errorPassedToNext === 'string') {
                            context.metadata.errorPassedToNext = errorPassedToNext.message;
                        } else {
                            context.metadata.errorPassedToNext = errorPassedToNext;
                        }
                    } else {
                        return setImmediate(function () {
                            done(errorPassedToNext);
                        });
                    }
                }
                var httpResponse = context.httpResponse = new messy.HttpResponse(res._header || undefined); // Avoid a parse error if empty string
                httpResponse.statusCode = res.statusCode;
                httpResponse.body = Buffer.concat(responseBodyChunks.map(function (bufferOrString) {
                    if (!Buffer.isBuffer(bufferOrString)) {
                        return new Buffer(String(bufferOrString), 'utf-8');
                    } else {
                        return bufferOrString;
                    }
                }));

                expect(context.metadata, 'to satisfy', expectedMetadata);

                try {
                    expect(httpResponse, 'to satisfy', expectedResponseProperties);
                } catch (e) {
                    var expectedResponseHeaders = httpResponse.headers.clone();
                    _.extend(expectedResponseHeaders.valuesByName, new messy.Headers(expectedResponseProperties.headers).valuesByName);
                    if (expectedResponseProperties.headers) {
                        Object.keys(expectedResponseProperties.headers).forEach(function (headerName) {
                            if (typeof expectedResponseProperties.headers[headerName] === 'undefined') {
                                expectedResponseHeaders.remove(headerName);
                            }
                        });
                    }

                    var expectedHttpResponse = context.expectedHttpResponse = new messy.HttpResponse({
                        statusLine: _.defaults(_.pick(expectedResponseProperties, messy.StatusLine.propertyNames), httpResponse.statusLine),
                        headers: expectedResponseHeaders,
                        body: expectedResponseProperties.body
                    });
                    expect.fail(function (output) {
                        httpRequest.upgradeBody();
                        return output
                            .append(expect.inspect(httpRequest)).nl(2)
                            .append(expect.diff(httpResponse, expectedHttpResponse).diff);
                   });
                }
            } catch (assertionError) {
                err = assertionError;
            }
            setImmediate(function () {
                done(err, context);
            });
        }
        ['write', 'end', 'destroy'].forEach(function (methodName) {
            var orig = res[methodName];
            res[methodName] = function (chunk, encoding) {
                var returnValue = orig.apply(this, arguments);
                if (methodName !== 'destroy') {
                    if (encoding && !/^utf-?8$/i.test(encoding)) {
                        throw new Error('encoding parameter not supported except for "utf-8": ' + encoding);
                    }
                    if (chunk) {
                        responseBodyChunks.push(chunk);
                    }
                }
                if (methodName === 'end' || methodName === 'destroy') {
                    isDestroyed = methodName === 'destroy';
                    doTheAssertions();
                }
                return returnValue;
            };
        });
        subject(req, res, next);
    });
};
<|endoftext|>


<commit_before>
/**
 * Helper functions for parsing and testing node versions.
 * Just plain `parseFloat` doesn't work in case there's ever a "x.10" release,
 * which would be parsed as x.1 when represented as a Number.
 */

var regexp = /^(\d+)\.(\d+)/

/**
 * Accepts a String like "v0.10.4" and returns a String
 * containing the major and minor versions ("0.10").
 */

exports.parse = function parse (str) {
  str = String(str)
  if (str[0] === 'v') {
    str = str.substring(1)
  }
  var m = str.match(regexp)
  return m ? m[0] : null
}

/**
 * Accepts a major-minor version string (from `parseVersion`) and a major
 * and minor Number value to test that the given version is less that the
 * specified version. Returns true or false.
 */

exports.lessThan = function lessThan (ver, major, minor) {
  var exec = regexp.exec(ver)
    , inMaj = parseInt(exec[1])
    , inMin = parseInt(exec[2])
  if (inMaj > major) return false
  return inMin < minor
}
<commit_msg>node version regexp optimization.<commit_after>
/**
 * Helper functions for parsing and testing node versions.
 * Just plain `parseFloat` doesn't work in case there's ever a "x.10" release,
 * which would be parsed as x.1 when represented as a Number.
 */

var regexp = /(\d+)\.(\d+)/

/**
 * Accepts a String like "v0.10.4" and returns a String
 * containing the major and minor versions ("0.10").
 */

exports.parse = function parse (str) {
  var m = String(str).match(regexp)
  return m ? m[0] : null
}

/**
 * Accepts a major-minor version string (from `parseVersion`) and a major
 * and minor Number value to test that the given version is less that the
 * specified version. Returns true or false.
 */

exports.lessThan = function lessThan (ver, major, minor) {
  var exec = regexp.exec(ver)
    , inMaj = parseInt(exec[1])
    , inMin = parseInt(exec[2])
  if (inMaj > major) return false
  return inMin < minor
}
<|endoftext|>


<commit_before>//loader.includeJS("https://w.soundcloud.com/player/api.js");

window.$ = window.$ || function(){return window.$};
$.getScript = $.getScript || function(js,cb){loader.includeJS(js,cb);};

SoundCloudPlayer = (function() {
	var EVENT_MAP = {
			"onplay": "onPlaying",
			"onresume": "onPlaying",
			"onpause": "onPaused",
			"onstop": "onPaused",
			"onfinish": "onEnded"
		},
		ERROR_EVENTS = [
			"onerror",
			"ontimeout",
			"onfailure",
			"ondataerror"
		];

	function SoundCloudPlayer(eventHandlers, embedVars) {
		this.label = 'SoundCloud';
		this.eventHandlers = eventHandlers || {};
		this.embedVars = embedVars || {};
		this.element = null;
		this.widget = null;
		this.isReady = false;
		this.trackInfo = {};
		this.soundOptions = {autoPlay:true};

		var that = this;
		$.getScript("https://connect.soundcloud.com/sdk.js", function() {
			SC.initialize({client_id: SOUNDCLOUD_CLIENT_ID});
			for (var i in EVENT_MAP)
				(function(i) {
					that.soundOptions[i] = function() {
						console.log("SC event:", i /*, this*/);
						var handler = eventHandlers[EVENT_MAP[i]];
						handler && handler(that);
					}
				})(i);
			ERROR_EVENTS.map(function(evt){
				that.soundOptions[evt] = function(e) {
					console.log("SC error:", evt, e);
					that.eventHandlers.onError && that.eventHandlers.onError(that, {code:evt.substr(2), source:"SoundCloudPlayer"});
				};
			});
			that.isReady = true;
			that.callHandler("onApiLoaded", that); // eventHandlers.onApiLoaded && eventHandlers.onApiLoaded(that);
			soundManager.onready(function() {
				that.callHandler("onApiReady", that); // eventHandlers.onApiReady && eventHandlers.onApiReady(that);
			});
		});

		this.callHandler = function(name, params) {
			try {
				eventHandlers[name] && eventHandlers[name](params);//.apply(null, params);
			}
			catch (e) {
				console.log(e, e.stack);
			}
		}
	}

	SoundCloudPlayer.prototype.safeCall = function(fctName, param) {
		try {
			//console.log("SC safecall", fctName);
			if (this.widget && this.widget[fctName])
				this.widget[fctName](param);
		}
		catch(e) {
			console.log("SC safecall error", e, e.stack);
		}
	}

	SoundCloudPlayer.prototype.getEid = function(url, cb) {
		var matches = /(?:https?:)?\/\/(?:www\.)?soundcloud\.com\/([\w-_\/]+)/.exec(url);
		cb(matches ? url.substr(url.lastIndexOf("/")+1) : null, this);
	}

	SoundCloudPlayer.prototype.getTrackInfo = function(callback) {
		var that = this, i = setInterval(function() {
			//console.log("SC info", that.widget.duration)
			if (that.widget && that.widget.duration) {
				clearInterval(i);
				callback(that.widget);
			}
		}, 500);
	}

	SoundCloudPlayer.prototype.getTrackPosition = function(callback) {
		callback(this.trackInfo.position = this.widget.position / 1000);
		if (this.widget.durationEstimate)
			this.eventHandlers.onTrackInfo && this.eventHandlers.onTrackInfo({
				duration: this.widget.duration / 1000
			});
	};

	SoundCloudPlayer.prototype.setTrackPosition = function(pos) {
		this.safeCall("setPosition", pos * 1000);
	};

	SoundCloudPlayer.prototype.play = function(id) {
		this.trackInfo = {};
		this.embedVars.trackId = id;
		//console.log("soundcloud play", this.embedVars);
		var that = this;

		SC.stream("/tracks/"+id, this.soundOptions, function(sound){
			that.widget = sound;
			that.callHandler("onEmbedReady", that);
			//that.safeCall("play");
		});
	}

	SoundCloudPlayer.prototype.resume = function() {
		this.safeCall("play");
	}

	SoundCloudPlayer.prototype.pause = function() {
		this.safeCall("pause");
	}

	SoundCloudPlayer.prototype.stop = function() {
		this.safeCall("stop");
	}

	SoundCloudPlayer.prototype.setVolume = function(vol) {
		this.safeCall("setVolume", 100 * vol);
	}

	return SoundCloudPlayer;
})();
<commit_msg>removed unused getTrackInfo method<commit_after>//loader.includeJS("https://w.soundcloud.com/player/api.js");

window.$ = window.$ || function(){return window.$};
$.getScript = $.getScript || function(js,cb){loader.includeJS(js,cb);};

SoundCloudPlayer = (function() {
	var EVENT_MAP = {
			"onplay": "onPlaying",
			"onresume": "onPlaying",
			"onpause": "onPaused",
			"onstop": "onPaused",
			"onfinish": "onEnded"
		},
		ERROR_EVENTS = [
			"onerror",
			"ontimeout",
			"onfailure",
			"ondataerror"
		];

	function SoundCloudPlayer(eventHandlers, embedVars) {
		this.label = 'SoundCloud';
		this.eventHandlers = eventHandlers || {};
		this.embedVars = embedVars || {};
		this.element = null;
		this.widget = null;
		this.isReady = false;
		this.trackInfo = {};
		this.soundOptions = {autoPlay:true};

		var that = this;
		$.getScript("https://connect.soundcloud.com/sdk.js", function() {
			SC.initialize({client_id: SOUNDCLOUD_CLIENT_ID});
			for (var i in EVENT_MAP)
				(function(i) {
					that.soundOptions[i] = function() {
						console.log("SC event:", i /*, this*/);
						var handler = eventHandlers[EVENT_MAP[i]];
						handler && handler(that);
					}
				})(i);
			ERROR_EVENTS.map(function(evt){
				that.soundOptions[evt] = function(e) {
					console.log("SC error:", evt, e);
					that.eventHandlers.onError && that.eventHandlers.onError(that, {code:evt.substr(2), source:"SoundCloudPlayer"});
				};
			});
			that.isReady = true;
			that.callHandler("onApiLoaded", that); // eventHandlers.onApiLoaded && eventHandlers.onApiLoaded(that);
			soundManager.onready(function() {
				that.callHandler("onApiReady", that); // eventHandlers.onApiReady && eventHandlers.onApiReady(that);
			});
		});

		this.callHandler = function(name, params) {
			try {
				eventHandlers[name] && eventHandlers[name](params);//.apply(null, params);
			}
			catch (e) {
				console.log(e, e.stack);
			}
		}
	}

	SoundCloudPlayer.prototype.safeCall = function(fctName, param) {
		try {
			//console.log("SC safecall", fctName);
			if (this.widget && this.widget[fctName])
				this.widget[fctName](param);
		}
		catch(e) {
			console.log("SC safecall error", e, e.stack);
		}
	}

	SoundCloudPlayer.prototype.getEid = function(url, cb) {
		var matches = /(?:https?:)?\/\/(?:www\.)?soundcloud\.com\/([\w-_\/]+)/.exec(url);
		cb(matches ? url.substr(url.lastIndexOf("/")+1) : null, this);
	}

	SoundCloudPlayer.prototype.getTrackPosition = function(callback) {
		callback(this.trackInfo.position = this.widget.position / 1000);
		if (this.widget.durationEstimate)
			this.eventHandlers.onTrackInfo && this.eventHandlers.onTrackInfo({
				duration: this.widget.duration / 1000
			});
	};

	SoundCloudPlayer.prototype.setTrackPosition = function(pos) {
		this.safeCall("setPosition", pos * 1000);
	};

	SoundCloudPlayer.prototype.play = function(id) {
		this.trackInfo = {};
		this.embedVars.trackId = id;
		//console.log("soundcloud play", this.embedVars);
		var that = this;

		SC.stream("/tracks/"+id, this.soundOptions, function(sound){
			that.widget = sound;
			that.callHandler("onEmbedReady", that);
			//that.safeCall("play");
		});
	}

	SoundCloudPlayer.prototype.resume = function() {
		this.safeCall("play");
	}

	SoundCloudPlayer.prototype.pause = function() {
		this.safeCall("pause");
	}

	SoundCloudPlayer.prototype.stop = function() {
		this.safeCall("stop");
	}

	SoundCloudPlayer.prototype.setVolume = function(vol) {
		this.safeCall("setVolume", 100 * vol);
	}

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


<commit_before>import express from 'express';
import bodyparser from 'body-parser';
import protagonist from 'protagonist';
import dedent from 'dedent'
import mson_zoo from 'mson-zoo'
import async from 'async'

// Starts server
const app = express();

app.use(bodyparser.json());
app.use(express.static('dist'));
app.use('/', express.static(__dirname + '/views'));

app.post('/parse', (req, res) => {

  const attributes = parseMson(req.body.source, (err, attributes) => {
    if (err) {
      return res.status(400).json({error: err});
    } else {
      return res.json(attributes);
    }
  });
});

app.get('/fixtures', (req, res) => {
  async.map(mson_zoo.samples, (sample, callback) => {
    parseMson(sample.code, (err, result) => {
      if (err) {
        return callback(err);
      }

      return callback(null, {mson: sample.code, parsed: result, name: sample.name});
    });
  }, (err, result) => {
    if (err) {
      return res.status(400).json({error: err});
    } else {
      return res.json(result);
    }
  });
});

const server = app.listen(9090, 'localhost', () => {
  const host = server.address().address;
  const port = server.address().port;

  console.log(`Server is listening on ${host}:${port}`);
});

const parseMson = (mson, cb) => {
  const lines = mson.split('\n');
  let source = dedent`
    FORMAT: 1A
    # Attributes
    # Group Test
    ## Test [/test]
    + Attributes
    `;

  lines.forEach((item) => {
    source += `
    ${item}`;
  });

  source += dedent`
    ### Retrieve [GET]
  `;

  protagonist.parse(source.trim(), function(err, result) {
    if (err) {
      return cb(err);
    }

    let attributes = null;

    const categories = result.content[0];
    if (categories.content[0]) {
      const category = categories.content[0];
      if (category.content[0]) {
        const resource = category.content[0];
        if (resource.content[0]) {
          const dataStructure = resource.content[0];
          if (dataStructure.content[0]) {
            return cb(err, dataStructure.content[0]);
          }
        }
      }
    }

    return cb('No attribute parsed');

  });
};
<commit_msg>Fixed syntax errors and removed unused variable<commit_after>import express from 'express';
import bodyparser from 'body-parser';
import protagonist from 'protagonist';
import dedent from 'dedent';
import mson_zoo from 'mson-zoo';
import async from 'async';

// Starts server
const app = express();

app.use(bodyparser.json());
app.use(express.static('dist'));
app.use('/', express.static(__dirname + '/views'));

app.post('/parse', (req, res) => {

  const attributes = parseMson(req.body.source, (err, attributes) => {
    if (err) {
      return res.status(400).json({error: err});
    } else {
      return res.json(attributes);
    }
  });
});

app.get('/fixtures', (req, res) => {
  async.map(mson_zoo.samples, (sample, callback) => {
    parseMson(sample.code, (err, result) => {
      if (err) {
        return callback(err);
      }

      return callback(null, {mson: sample.code, parsed: result, name: sample.name});
    });
  }, (err, result) => {
    if (err) {
      return res.status(400).json({error: err});
    } else {
      return res.json(result);
    }
  });
});

const server = app.listen(9090, 'localhost', () => {
  const host = server.address().address;
  const port = server.address().port;

  console.log(`Server is listening on ${host}:${port}`);
});

const parseMson = (mson, cb) => {
  const lines = mson.split('\n');
  let source = dedent`
    FORMAT: 1A
    # Attributes
    # Group Test
    ## Test [/test]
    + Attributes
    `;

  lines.forEach((item) => {
    source += `
    ${item}`;
  });

  source += dedent`
    ### Retrieve [GET]
  `;

  protagonist.parse(source.trim(), function(err, result) {
    if (err) {
      return cb(err);
    }

    const categories = result.content[0];
    if (categories.content[0]) {
      const category = categories.content[0];
      if (category.content[0]) {
        const resource = category.content[0];
        if (resource.content[0]) {
          const dataStructure = resource.content[0];
          if (dataStructure.content[0]) {
            return cb(err, dataStructure.content[0]);
          }
        }
      }
    }

    return cb('No attribute parsed');
  });
};
<|endoftext|>


<commit_before>var request = require('request');
var languages = {
	'af': 'Afrikaans',
	'sq': 'Albanian',
	'ar': 'Arabic',
	'az': 'Azerbaijani',
	'eu': 'Basque',
	'bn': 'Bengali',
	'be': 'Belarusian',
	'bg': 'Bulgarian',
	'ca': 'Catalan',
	'zh-CN': 'Simplified-Chinese',
	'zh-TW': 'Traditional-Chinese',
	'hr': 'Croatian',
	'cs': 'Czech',
	'da': 'Danish',
	'nl': 'Dutch',
	'en': 'English',
	'eo': 'Esperanto',
	'et': 'Estonian',
	'tl': 'Filipino',
	'fi': 'Finnish',
	'fr': 'French',
	'gl': 'Galician',
	'ka': 'Georgian',
	'de': 'German',
	'el': 'Greek',
	'gu': 'Gujarati',
	'ht': 'Haitian Creole',
	'iw': 'Hebrew',
	'hi': 'Hindi',
	'hu': 'Hungarian',
	'is': 'Icelandic',
	'id': 'Indonesian',
	'ga': 'Irish',
	'it': 'Italian',
	'ja': 'Japanese',
	'kn': 'Kannada',
	'ko': 'Korean',
	'la': 'Latin',
	'lv': 'Latvian',
	'lt': 'Lithuanian',
	'mk': 'Macedonian',
	'ms': 'Malay',
	'mt': 'Maltese',
	'no': 'Norwegian',
	'fa': 'Persian',
	'pl': 'Polish',
	'pt': 'Portuguese',
	'ro': 'Romanian',
	'ru': 'Russian',
	'sr': 'Serbian',
	'sk': 'Slovak',
	'sl': 'Slovenian',
	'es': 'Spanish',
	'sw': 'Swahili',
	'sv': 'Swedish',
	'ta': 'Tamil',
	'te': 'Telugu',
	'th': 'Thai',
	'tr': 'Turkish',
	'uk': 'Ukranian',
	'ur': 'Urdu',
	'vi': 'Vietnamese',
	'cy': 'Welsh',
	'yi': 'Yiddish'
};
var getCode = function(language, languages){
	var code, lang;
	if(!language){
		return;
	}
	for(code in languages){
		lang = languages[code];
		if(lang.toLowerCase() === language.toLowerCase()){
			return code;
		}
	}
};
module.exports = function(bot){
	bot.addCommand('translate', 'Translate', '[<from>] [<to>]', USER_LEVEL_NORMAL, false, function(event){
		var keyword = event.params.slice(2).join('+'),
			to, from;
		if(event.params[0] !== ''){
			from = getCode(event.params[0], languages);
		}else{
			from = 'auto';
		}
		if(event.params[1]){
			to = getCode(event.params[1], languages);
		}else{
			to = 'en';
		}
		request('https://translate.google.com/translate_a/t?client=t&hl=en&multires=1&sc=1&sl=' + from + '&ssel=0&tl=' + to + '&tsel=0&uptl=en&text=' + keyword, function(error, response, body){
			if(body){
				try{
					var parsed = eval(body),
						language = languages[parsed[2]];
					parsed = parsed[0] && parsed[0][0] && parsed[0][0][0];
					if(parsed && languages[to]){
						bot.message(event.target, event.source.nick + ': The ' + language + ' ' + keyword.replace('+', '') + ' translates as ' + parsed + ' in ' + languages[to]);
					}else{
						bot.message(event.target, event.source.nick + ': Could not find translation.');
					}
				}catch(e){}
			}
		});
	});
}<commit_msg>more translate plugin fixes bro<commit_after>var request = require('request');
var languages = {
	'af': 'Afrikaans',
	'sq': 'Albanian',
	'ar': 'Arabic',
	'az': 'Azerbaijani',
	'eu': 'Basque',
	'bn': 'Bengali',
	'be': 'Belarusian',
	'bg': 'Bulgarian',
	'ca': 'Catalan',
	'zh-CN': 'Simplified-Chinese',
	'zh-TW': 'Traditional-Chinese',
	'hr': 'Croatian',
	'cs': 'Czech',
	'da': 'Danish',
	'nl': 'Dutch',
	'en': 'English',
	'eo': 'Esperanto',
	'et': 'Estonian',
	'tl': 'Filipino',
	'fi': 'Finnish',
	'fr': 'French',
	'gl': 'Galician',
	'ka': 'Georgian',
	'de': 'German',
	'el': 'Greek',
	'gu': 'Gujarati',
	'ht': 'Haitian Creole',
	'iw': 'Hebrew',
	'hi': 'Hindi',
	'hu': 'Hungarian',
	'is': 'Icelandic',
	'id': 'Indonesian',
	'ga': 'Irish',
	'it': 'Italian',
	'ja': 'Japanese',
	'kn': 'Kannada',
	'ko': 'Korean',
	'la': 'Latin',
	'lv': 'Latvian',
	'lt': 'Lithuanian',
	'mk': 'Macedonian',
	'ms': 'Malay',
	'mt': 'Maltese',
	'no': 'Norwegian',
	'fa': 'Persian',
	'pl': 'Polish',
	'pt': 'Portuguese',
	'ro': 'Romanian',
	'ru': 'Russian',
	'sr': 'Serbian',
	'sk': 'Slovak',
	'sl': 'Slovenian',
	'es': 'Spanish',
	'sw': 'Swahili',
	'sv': 'Swedish',
	'ta': 'Tamil',
	'te': 'Telugu',
	'th': 'Thai',
	'tr': 'Turkish',
	'uk': 'Ukranian',
	'ur': 'Urdu',
	'vi': 'Vietnamese',
	'cy': 'Welsh',
	'yi': 'Yiddish'
};
var getCode = function(language, languages){
	var code, lang;
	if(!language){
		return;
	}
	for(code in languages){
		lang = languages[code];
		if(lang.toLowerCase() === language.toLowerCase()){
			return code;
		}
	}
};
module.exports = function(bot){
	bot.addCommand('translate', 'Translate', '[<from>] [<to>]', USER_LEVEL_NORMAL, false, function(event){
		var keyword = event.params.slice(2).join('+'),
			to, from;
		if(event.params[0] !== ''){
			from = getCode(event.params[0], languages);
		}else{
			from = 'auto';
		}
		if(event.params[1]){
			to = getCode(event.params[1], languages);
		}else{
			to = 'en';
		}
		request('https://translate.google.com/translate_a/t?client=t&hl=en&multires=1&sc=1&sl=' + from + '&ssel=0&tl=' + to + '&tsel=0&uptl=en&text=' + keyword, function(error, response, body){
			if(body){
				try{
					var parsed = eval(body),
						language = languages[parsed[2]];
					parsed = parsed[0] && parsed[0][0] && parsed[0][0][0];
					if(parsed && languages[to]){
						bot.message(event.target, event.source.nick + ': ' + parsed);
					}else{
						bot.message(event.target, event.source.nick + ': Could not find translation.');
					}
				}catch(e){}
			}
		});
	});
}<|endoftext|>


<commit_before>const anymatch = require('anymatch')
const minimatch = require('minimatch')
const stylelint = require('stylelint')
const TapMap = require('tap-map')
const braces = require('braces')
const {splitTokens} = require('./lib/tokens')

const ruleName = 'primer/variables'
const IMPORTANT = '!important'

const DEFAULT_RULES = require('./lib/variable-rules')

module.exports = stylelint.createPlugin(ruleName, (enabled, options = {}, context = {}) => {
  if (enabled === false) {
    return noop
  }

  // The stylelint docs suggest respecting a "disableFix" rule option that
  // overrides the "global" context.fix (--fix) linting option.
  const fixEnabled = context.fix && !options.disableFix
  const {verbose = false} = options

  /* Rules are keyed on their name so that it's easy to override or disable
   * them while still "inheriting" the defaults:
   *
   * ```js
   * 'primer/variables': [true, {
   *   rules: {
   *     'background color': false,
   *     'text color': {
   *       props: ['fill', 'color'],
   *       values: ['$text-*', '$fill-*', 'transparent', 'currentColor']
   *     }
   *   }
   * }
   * ```
   */
  const rules = Object.assign({}, DEFAULT_RULES, options.rules)
  const cache = new TapMap()
  const tokenReplacementsByProperty = new Map()
  const entries = Object.entries(rules)
    .map(([name, rule]) => {
      if (!rule) {
        return false
      } else if (!rule.props && verbose) {
        // eslint-disable-next-line no-console
        console.warn(`[${ruleName}] rule "${name}" has no .props; the name will be used.`)
        rule.props = name
      }
      return Object.assign(
        {
          name,
          match: anymatch(rule.props),
          replacements: {}
        },
        rule,
        {
          testValue: getRuleValueTester(rule)
        }
      )
    })
    .filter(Boolean)

  for (const entry of entries) {
    const props = arrayify(entry.props).flatMap(braces.expand)
    for (const prop of props) {
      for (const [token, replacement] of Object.entries(entry.replacements)) {
        tokenReplacementsByProperty.set(`${prop}:${token}`, replacement)
        if (verbose) {
          // eslint-disable-next-line no-console
          console.warn(`replace: {${prop}: ${token}} -> "${replacement}"`)
        }
      }
    }
  }

  return (root, result) => {
    const messages = stylelint.utils.ruleMessages(ruleName, {
      rejected: message => message
    })

    root.walkDecls(decl => check(decl))

    function check(decl, prop = decl.prop, value = decl.value) {
      let replacementKey = `${prop}:${value}`
      let message
      if (prop === decl.prop && tokenReplacementsByProperty.has(replacementKey)) {
        const replacement = tokenReplacementsByProperty.get(replacementKey)
        if (fixEnabled) {
          decl.value = replacement
        } else {
          message = `Please use "${replacement}" instead of "${value}"`
        }
      }

      const rule = cache.tap(prop, () => entries.find(entry => entry.match(prop)))
      if (rule) {
        const {name} = rule
        const tokens = splitTokens(value)
        let fixed = false
        if (tokens.length > 1 && Array.isArray(rule.components)) {
          for (const [index, comp] of Object.entries(rule.components)) {
            const token = tokens[index]
            const fixedToken = check(decl, comp, token)
            if (fixEnabled && fixedToken) {
              tokens[index] = fixedToken
              fixed = true
            }
          }
        } else {
          for (const [index, token] of Object.entries(tokens)) {
            replacementKey = `${prop}:${token}`
            if (fixEnabled && rule.replacements.hasOwnProperty(token)) {
              tokens[index] = rule.replacements[token]
              fixed = true
            } else if (tokenReplacementsByProperty.has(replacementKey)) {
              const replacement = tokenReplacementsByProperty.get(replacementKey)
              if (verbose) {
                // eslint-disable-next-line no-console
                console.warn(`found exact replacement for {${prop}: ${token}}: "${replacement}"`)
              }
              if (fixEnabled) {
                tokens[index] = replacement
                fixed = true
              } else {
                message = `Please use "${replacement}" instead of "${token}"`
                break
              }
            } else if (!rule.testValue(token)) {
              message = `Please use a ${name} variable instead of "${value}"`
              break
            }
          }
        }

        if (fixed) {
          if (prop === decl.prop) {
            decl.value = tokens.join(' ')
          } else {
            return tokens.join(' ')
          }
        } else if (message) {
          stylelint.utils.report({
            message: messages.rejected(`${message}.`),
            node: decl,
            result,
            ruleName
          })
        }
      }
    }
  }
})

// export the default rules object so that it can be built on
Object.assign(module.exports, {DEFAULT_RULES})

function getRuleValueTester(rule) {
  const {values = []} = rule
  if (values && values.length) {
    const match = anymatch(values)
    return v => v === IMPORTANT || match(v)
  } else {
    return returnFalse
  }
}

function returnFalse() {
  return false
}

function noop() {}

function arrayify(value) {
  return Array.isArray(value) ? value : [value]
}
<commit_msg>remove some dead code<commit_after>const anymatch = require('anymatch')
const minimatch = require('minimatch')
const stylelint = require('stylelint')
const TapMap = require('tap-map')
const braces = require('braces')
const {splitTokens} = require('./lib/tokens')

const ruleName = 'primer/variables'
const IMPORTANT = '!important'

const DEFAULT_RULES = require('./lib/variable-rules')

module.exports = stylelint.createPlugin(ruleName, (enabled, options = {}, context = {}) => {
  if (enabled === false) {
    return noop
  }

  // The stylelint docs suggest respecting a "disableFix" rule option that
  // overrides the "global" context.fix (--fix) linting option.
  const fixEnabled = context.fix && !options.disableFix
  const {verbose = false} = options

  /* Rules are keyed on their name so that it's easy to override or disable
   * them while still "inheriting" the defaults:
   *
   * ```js
   * 'primer/variables': [true, {
   *   rules: {
   *     'background color': false,
   *     'text color': {
   *       props: ['fill', 'color'],
   *       values: ['$text-*', '$fill-*', 'transparent', 'currentColor']
   *     }
   *   }
   * }
   * ```
   */
  const rules = Object.assign({}, DEFAULT_RULES, options.rules)
  const cache = new TapMap()
  const tokenReplacementsByProperty = new Map()
  const entries = Object.entries(rules)
    .map(([name, rule]) => {
      if (!rule) {
        return false
      } else if (!rule.props && verbose) {
        // eslint-disable-next-line no-console
        console.warn(`[${ruleName}] rule "${name}" has no .props; the name will be used.`)
        rule.props = name
      }
      return Object.assign(
        {
          name,
          match: anymatch(rule.props),
          replacements: {}
        },
        rule,
        {
          testValue: getRuleValueTester(rule)
        }
      )
    })
    .filter(Boolean)

  for (const entry of entries) {
    const props = arrayify(entry.props).flatMap(braces.expand)
    for (const prop of props) {
      for (const [token, replacement] of Object.entries(entry.replacements)) {
        tokenReplacementsByProperty.set(`${prop}:${token}`, replacement)
        if (verbose) {
          // eslint-disable-next-line no-console
          console.warn(`replace: {${prop}: ${token}} -> "${replacement}"`)
        }
      }
    }
  }

  return (root, result) => {
    const messages = stylelint.utils.ruleMessages(ruleName, {
      rejected: message => message
    })

    root.walkDecls(decl => check(decl))

    function check(decl, prop = decl.prop, value = decl.value) {
      let replacementKey = `${prop}:${value}`
      let message
      if (prop === decl.prop && tokenReplacementsByProperty.has(replacementKey)) {
        const replacement = tokenReplacementsByProperty.get(replacementKey)
        if (fixEnabled) {
          decl.value = replacement
        } else {
          message = `Please use "${replacement}" instead of "${value}"`
        }
      }

      const rule = cache.tap(prop, () => entries.find(entry => entry.match(prop)))
      if (rule) {
        const {name} = rule
        const tokens = splitTokens(value)
        let fixed = false
        if (tokens.length > 1 && Array.isArray(rule.components)) {
          for (const [index, comp] of Object.entries(rule.components)) {
            const token = tokens[index]
            const fixedToken = check(decl, comp, token)
            if (fixEnabled && fixedToken) {
              tokens[index] = fixedToken
              fixed = true
            }
          }
        } else {
          for (const [index, token] of Object.entries(tokens)) {
            replacementKey = `${prop}:${token}`
            if (fixEnabled && rule.replacements.hasOwnProperty(token)) {
              tokens[index] = rule.replacements[token]
              fixed = true
            } else if (tokenReplacementsByProperty.has(replacementKey)) {
              const replacement = tokenReplacementsByProperty.get(replacementKey)
              if (verbose) {
                // eslint-disable-next-line no-console
                console.warn(`found exact replacement for {${prop}: ${token}}: "${replacement}"`)
              }
              if (fixEnabled) {
                tokens[index] = replacement
                fixed = true
              } else {
                message = `Please use "${replacement}" instead of "${token}"`
                break
              }
            } else if (!rule.testValue(token)) {
              message = `Please use a ${name} variable instead of "${value}"`
              break
            }
          }
        }

        if (fixed) {
          if (prop === decl.prop) {
            decl.value = tokens.join(' ')
          } else {
            return tokens.join(' ')
          }
        } else if (message) {
          stylelint.utils.report({
            message: messages.rejected(`${message}.`),
            node: decl,
            result,
            ruleName
          })
        }
      }
    }
  }
})

// export the default rules object so that it can be built on
Object.assign(module.exports, {DEFAULT_RULES})

function getRuleValueTester(rule) {
  const {values = []} = rule
  const match = anymatch(values)
  return v => v === IMPORTANT || match(v)
}

function noop() {}

function arrayify(value) {
  return Array.isArray(value) ? value : [value]
}
<|endoftext|>


<commit_before>import React from 'react';
import ReactDOM from 'react-dom';
import './bootstrap.css';
import './index.css';

import PropTypes from "prop-types";
import ReactAudioPlayer from 'react-audio-player';
import axios from "axios";

class AvailableDatalist extends React.Component {
  render() {
    console.log("props during render songs")
    console.log(this.props)
    var ret = []
    if(this.props.song_set[0] !== 0){
      ret = this.props.song_set.map(c =>

          {c.songName[0]}
          {c.album}
          {c.author}
          {c.date}

      )
    }else{
      ret[0] =
loading...

    }

    console.log("ret nach bearbeitung")
    console.log(ret)

    return(

            Songname
            Album
            Author
            Date

          {ret}

    )
  }
}

AvailableDatalist.propTypes = {
  song_set: PropTypes.array.isRequired
};

class SongBoard extends React.Component {
	state = {
	  song_set: [0:{name:"none", album:"none", author:"none"}]
	};

	renderAlbums(){
		console.log("button was clicked")
		console.log("current location")
		console.log(window.location.hostname)
		console.log("state befor render");
		console.log(this);
		axios
		.get("http://" + window.location.hostname + ":8000/album/")
		.then(response => {
			const song_set = response.data.map(c => {

				return{
					songName: c.song_set.map(d => {return(d.name)}),
					album: c.name,
					author: c.author,
					date: c.release_date
				};
			});

			const newState = Object.assign({}, this.state, {
						song_set: song_set
			});
			this.setState(newState);
			console.log("state after api request")
			console.log(this.state)

		})
		.catch(error => console.log(error));
	}

	renderSongs(){
		console.log("button was clicked")
		console.log("current location")
		console.log(window.location.hostname)
		console.log("state befor render");
		console.log(this.state);
	  axios
	  .get("http://" + window.location.hostname + ":8000/song/")
	  .then(response => {
	    const song_set2 = response.data.map(c => {
	      return{
					songName: c.name,
	        album: c.album,
	        author: "c.author",
	        date: "c.release_date"
	      };
	    });

	    const newState = Object.assign({}, this.state, {
	          song_set: song_set2[0]
	    });
	    this.setState(newState);
	    console.log("state after api request")
	    console.log(this.state)

	  })
	  .catch(error => console.log(error));
	}

	componentDidMount() {
		this.renderSongs();

	}

  render() {

    return(

							    <input type="radio" name="options" id="option1" autoComplete="off" defaultChecked={true} />
										Songs

							    <input type="radio" name="options" id="option2" autoComplete="off" />
										Album

	          <AvailableDatalist song_set={this.state.song_set}/> {/*songs={this.state.contacts}*/}

						playlist

    )
  }
}

class Player extends React.Component {
  render() {
    return(
      <ReactAudioPlayer
        src="my_audio_file.ogg"
        autoPlay
        controls
      />
    )
  }
}

class Site extends React.Component {
  render() {
    return (

          <Player />

          <SongBoard />

    )
  }
}

ReactDOM.render(
  <Site />,
  document.getElementById('root')
);
<commit_msg>songs<commit_after>import React from 'react';
import ReactDOM from 'react-dom';
import './bootstrap.css';
import './index.css';

import PropTypes from "prop-types";
import ReactAudioPlayer from 'react-audio-player';
import axios from "axios";

class AvailableDatalist extends React.Component {
  render() {
    console.log("props during render songs")
    console.log(this.props)
    var ret = []
    if(this.props.song_set[0] !== 0){
      ret = this.props.song_set.map(c =>

          {c.songName[0]}
          {c.album}
          {c.author}
          {c.date}

      )
    }else{
      ret[0] =
loading...

    }

    console.log("ret nach bearbeitung")
    console.log(ret)

    return(

            Songname
            Album
            Author
            Date

          {ret}

    )
  }
}

AvailableDatalist.propTypes = {
  song_set: PropTypes.array.isRequired
};

class SongBoard extends React.Component {
	state = {
	  song_set: [0:{name:"none", album:"none", author:"none"}]
	};

	renderAlbums(){
		console.log("button was clicked")
		console.log("current location")
		console.log(window.location.hostname)
		console.log("state befor render");
		console.log(this);
		axios
		.get("http://" + window.location.hostname + ":8000/album/")
		.then(response => {
			const song_set = response.data.map(c => {
				return{
					songName: c.song_set.map(d => {return(d.name)}),
					album: c.name,
					author: c.author,
					date: c.release_date
				};
			});

			const newState = Object.assign({}, this.state, {
						song_set: song_set
			});
			this.setState(newState);
			console.log("state after api request")
			console.log(this.state)

		})
		.catch(error => console.log(error));
	}

	renderSongs(){
		console.log("button was clicked")
		console.log("current location")
		console.log(window.location.hostname)
		console.log("state befor render");
		console.log(this.state);
	  axios
	  .get("http://" + window.location.hostname + ":8000/song/")
	  .then(response => {
	    const song_set2 = response.data.map(c => {
	      return{
					songName: c.name,
	        album: c.album,
	        author: "c.author",
	        date: "c.release_date"
	      };
	    });

	    const newState = Object.assign({}, this.state, {
	          song_set: song_set2
	    });
	    this.setState(newState);
	    console.log("state after api request")
	    console.log(this.state)

	  })
	  .catch(error => console.log(error));
	}

	componentDidMount() {
		this.renderSongs();

	}

  render() {

    return(

							    <input type="radio" name="options" id="option1" autoComplete="off" defaultChecked={true} />
										Songs

							    <input type="radio" name="options" id="option2" autoComplete="off" />
										Album

	          <AvailableDatalist song_set={this.state.song_set}/> {/*songs={this.state.contacts}*/}

						playlist

    )
  }
}

class Player extends React.Component {
  render() {
    return(
      <ReactAudioPlayer
        src="my_audio_file.ogg"
        autoPlay
        controls
      />
    )
  }
}

class Site extends React.Component {
  render() {
    return (

          <Player />

          <SongBoard />

    )
  }
}

ReactDOM.render(
  <Site />,
  document.getElementById('root')
);
<|endoftext|>


<commit_before>import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';

import PropTypes from "prop-types";
import ReactAudioPlayer from 'react-audio-player';
import axios from "axios";

class AvailableDatalist extends React.Component {

  render() {
    return(

{this.props.songs[0]['name']}

    )
  }

AvailableDatalist.propTypes = {
  songs: PropTypes.array.isRequired
};

class SongBoard extends React.Component {
state = {
  songs: [0:{name:"none", album:"none"}]
};

componentDidMount() {
  axios
  .get("http://192.168.1.107:8000/song/")
  .then(response => {
    const songs = response.data.map(c => {
      return{
        name: c.name,
        album: c.album
      };
    });

    const newState = Object.assign({}, this.state, {
          songs: songs
        });

    this.setState(newState);
    console.log(this.state.songs[0])

  })
  .catch(error => console.log(error));
}

  render() {

    return(

            <button className="song">
              Song
            </button>
            <button className="album">
              Album
            </button>

          <AvailableDatalist songs={this.state.songs}/> {/*songs={this.state.contacts}*/}

    )
  }
}

class Player extends React.Component {
  render() {
    return(
      <ReactAudioPlayer
        src="my_audio_file.ogg"
        autoPlay
        controls
      />
    )
  }
}

class Site extends React.Component {
  render() {
    return (

          <Player />

          <SongBoard />

    )
  }
}

ReactDOM.render(
  <Site />,
  document.getElementById('root')
);
<commit_msg>songs<commit_after>import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';

import PropTypes from "prop-types";
import ReactAudioPlayer from 'react-audio-player';
import axios from "axios";

class AvailableDatalist extends React.Component {

  render() {
    return(

{this.props.songs[0]['name']}

    )
  }
}

AvailableDatalist.propTypes = {
  songs: PropTypes.array.isRequired
};

class SongBoard extends React.Component {
state = {
  songs: [0:{name:"none", album:"none"}]
};

componentDidMount() {
  axios
  .get("http://192.168.1.107:8000/song/")
  .then(response => {
    const songs = response.data.map(c => {
      return{
        name: c.name,
        album: c.album
      };
    });

    const newState = Object.assign({}, this.state, {
          songs: songs
        });

    this.setState(newState);
    console.log(this.state.songs[0])

  })
  .catch(error => console.log(error));
}

  render() {

    return(

            <button className="song">
              Song
            </button>
            <button className="album">
              Album
            </button>

          <AvailableDatalist songs={this.state.songs}/> {/*songs={this.state.contacts}*/}

    )
  }
}

class Player extends React.Component {
  render() {
    return(
      <ReactAudioPlayer
        src="my_audio_file.ogg"
        autoPlay
        controls
      />
    )
  }
}

class Site extends React.Component {
  render() {
    return (

          <Player />

          <SongBoard />

    )
  }
}

ReactDOM.render(
  <Site />,
  document.getElementById('root')
);
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */
'use strict';

const mockColor = () => {
  return {
    bold: () => { return { }; },
  };
};

mockColor.bold = function() {
  return {};
};

module.exports = {
  dim: s =>  s,
  magenta: mockColor,
  white: mockColor,
  blue: mockColor,
  yellow: mockColor,
  green: mockColor,
  bold: mockColor,
  red: mockColor,
  cyan: mockColor,
  gray: mockColor,
  black: mockColor,
};
<commit_msg>Remove outdated file<commit_after><|endoftext|>


<commit_before>
if (!VieBundle) {
    var VieBundle = {};
}

VieBundle.Model = function(bundle, element) {

    this.bundle = bundle;
    this.element = element;
    this.vie = this.bundle.vie;

    // load entities with rdfa
    this.vie.load({element: element}).from('rdfa').execute();

    var subject = this.vie.service('rdfa').getElementSubject(element);
    this.entity = this.vie.entities.get(subject);

    // insert settings pane
    var id = subject.replace(/[^A-Za-z]/g, '-');
    this.element.prepend('

Article settings

<form>

Article tags
<input type="text" id="' + id + '-articleTags" class="tags" value="" />

Suggested tags
<input type="text" id="' + id + '-suggestedTags" class="tags" value="" />
</form>

');
    this.articleTags = this.element.find('.articleTags input');
    this.suggestedTags = this.element.find('.articleSuggestedTags input');

    // bind toggle events for settings pane
    this.element.find('.hiddenfieldsToggle').click(function(event) {
        var context = $(this).closest('.hiddenfieldsContainer');
        $('.hiddenfields', context).show();
        $('.hiddenfieldsToggle', context).hide();
        $('.hiddenfieldsCloseCorner', context).show();
        $('.hiddenfieldsCloseButton', context).show();
    });

    var that = this;
    this.element.find('.hiddenfieldsCloseCorner, .hiddenfieldsCloseButton').click(function(event) {
        that.closeTags();
    });

    $(document).click(function(e) {
        if ($(e.target).closest('.hiddenfieldsContainer').size() == 0 && $('.hiddenfieldsCloseCorner:visible').length > 0){
            that.closeTags();
        }
    });

    // init tags
    this.initTags();
    this.loadTags();

    // init editor
    this.initEditable();
};

VieBundle.Model.prototype.closeTags = function () {
    var context = $('.hiddenfieldsContainer');
    $('.hiddenfields', context).hide();
    $('.hiddenfieldsToggle', context).show();
    $('.hiddenfieldsCloseCorner', context).hide();
    $('.hiddenfieldsCloseButton', context).hide();

    // save on close
    this.save();
}

VieBundle.Model.prototype.tagLabel = function (value) {

    if (value.substring(0, 9) == '<urn:tag:') {
        value = value.substring(9, value.length - 1);
    }

    if (value.substring(0, 8) == '<http://') {
        value = value.substring(value.lastIndexOf('/') + 1, value.length - 1);
        value = value.replace(/_/g, ' ');
    }

    return value;
};

VieBundle.Model.prototype.initTags = function () {

    var that = this;

    this.articleTags.tagsInput({
        width:'auto',
        height: 'auto',
        onAddTag: function (tag) {

            var entity = that.entity;

            // convert to reference url
            if (!entity.isReference(tag)) {
                tag = 'urn:tag:' + tag;
            }

            // add tag to entity
            entity.attributes['<http://purl.org/dc/elements/1.1/subject>'].vie = that.vie;
            entity.attributes['<http://purl.org/dc/elements/1.1/subject>'].addOrUpdate({'@subject': tag});
        },
        onRemoveTag: function (tag) {

            // remove tag from entity
            that.entity.attributes['<http://purl.org/dc/elements/1.1/subject>'].remove(tag);
        },
        label: this.tagLabel
    });

    this.suggestedTags.tagsInput({
        width:'auto',
        height: 'auto',
        interactive: false,
        label: this.tagLabel,
        remove: false
    });

    // add suggested tag on click to tags
    this.element.find('.articleSuggestedTags .tag span').live('click', function(){

        var tag = $(this).text();
        that.articleTags.addTag($(this).data('value'));
        that.suggestedTags.removeTag($.trim(tag));

        return false;
    });
};

VieBundle.Model.prototype.loadTags = function () {

    var that = this;

    // load article tags
    var tags = this.entity.attributes['<http://purl.org/dc/elements/1.1/subject>'].models;
    jQuery(tags).each(function () {
        that.articleTags.addTag(this.id);
    });

    // load suggested tags
    var text = $(that.element).text();
    that.vie.analyze({element: $(that.element)}).using(['stanbol']).execute().success(function(enhancements) {
        return $(enhancements).each(function(i, e) {
            if (e.attributes['<rdfschema:label>']) {
                that.suggestedTags.addTag(e.id);
            }
        });
    }).fail(function(xhr) {
        console.log(xhr);
    });
};

VieBundle.Model.prototype.initEditable = function () {

    this.element.midgardEditable({
        vie: this.vie,
        model: this.entity,
        addButton: true,
        editorOptions: {
            'dcterms:title': {
                plugins: {
                    'hallooverlay': {},
                    'hallotoolbarlinebreak': {}
                }
            },
            'default': {
                plugins: {
                    'halloimage': { 'searchUrl': 'liip/vie/assets/search/', 'vie': this.vie },
                    'hallolink': { 'relatedUrl': vie_plugins_link_related_path },
                    'halloheadings': {},
                    'halloformat': {'formattings': {'strikeThrough': false, 'underline': false}},
                    'hallolists': {'lists': {'ordered': false}},
                    'hallojustify': {},
                    'halloreundo': {},
                    'hallotoolbarlinebreak': { 'breakAfter': ['hallolink'] },
                    'hallooverlay': {}
                },
                floating: false,
                showAlways: true
            }
        },
        deactivated: $.proxy(this.save, this)
    });
};

VieBundle.Model.prototype.save = function () {

    // move hover back behind
    //$('.liipVieBundleContentEditableHover').css('z-index', '0');

    // don't save if blocked by dragged images
    if (this.bundle.preventSave) {
        setTimeout(this.save, 5000);
        return;
    }

    // save the Backbone model
    this.entity.save(null, {
        success: function(model, response) {
            $(document).trigger("vieSaveSuccess");
            console.log(model.id + " was saved");
        },
        error: function(response) {
            console.log("Save failed");
            console.log(response);
        }
    });
};

VieBundle.Hallo = function () {

    this.preventSave = false;

    this.initVIE();

    var that = this;
    $('[typeof][about]').each(function() {

        var element = $(this);

        var model = new VieBundle.Model(that, element);
    });
};

VieBundle.Hallo.prototype.initVIE = function () {

    this.vie = new VIE();
    this.vie.EntityManager.entities.bind('add', function(model) {
        if (typeof model.id == 'string') {
            model.url = vie_phpcr_path + model.id.substring(1, model.id.length - 1);
            model.toJSON = model.toJSONLD;
        }
    });

    this.vie.use(new this.vie.RdfaService());

    this.vie.namespaces.add('sioc', 'http://rdfs.org/sioc/ns#');
    this.vie.namespaces.add('dc', 'http://purl.org/dc/elements/1.1/');

    this.vie.use(new this.vie.StanbolService({
        url: "http://cmf.lo/stanbol",
        proxyDisabled: true
    }));
};

VieBundle.Hallo.prototype.setPreventSave = function (value) {
    this.preventSave = value;
};

jQuery(document).ready(function ($) {

    var bundle = new VieBundle.Hallo();

    $(this).bind('startPreventSave', function() {
        bundle.setPreventSave(true);
    });

    $(this).bind('stopPreventSave', function() {
        bundle.setPreventSave(false);
    });

    $(window).resize(function() {
        if(!$('.inEditMode')[0] == undefined ){
            $('.halloToolbar').css('left', $('.inEditMode')[0].offsetLeft);
        }
    });

    // edit hover
    var hover = $('
');
    hover.hide();
    $('body').append(hover);

    // show edit button on hover
    $('[contenteditable]').not('.inEditMode').hover(function () {

        $(document).trigger('startPreventSave');

        var $this = $(this);

        if(!$this.hasClass('inEditMode')){
            var editButton = $('
edit
').addClass('editButton');
            $this.before(editButton);
        }

        var offset = $this.offset();
        hover.css({top: offset.top - 10, left: offset.left - 10});
        hover.width($this.width());
        hover.height($this.height());
        hover.show();

    }, function () {

        $(document).trigger('stopPreventSave');

        $('.editButton').remove();

        hover.hide();
    });
});
<commit_msg>trim whitespaces<commit_after>
if (!VieBundle) {
    var VieBundle = {};
}

VieBundle.Model = function(bundle, element) {

    this.bundle = bundle;
    this.element = element;
    this.vie = this.bundle.vie;

    // load entities with rdfa
    this.vie.load({element: element}).from('rdfa').execute();

    var subject = this.vie.service('rdfa').getElementSubject(element);
    this.entity = this.vie.entities.get(subject);

    // insert settings pane
    var id = subject.replace(/[^A-Za-z]/g, '-');
    this.element.prepend('

Article settings

<form>

Article tags
<input type="text" id="' + id + '-articleTags" class="tags" value="" />

Suggested tags
<input type="text" id="' + id + '-suggestedTags" class="tags" value="" />
</form>

');
    this.articleTags = this.element.find('.articleTags input');
    this.suggestedTags = this.element.find('.articleSuggestedTags input');

    // bind toggle events for settings pane
    this.element.find('.hiddenfieldsToggle').click(function(event) {
        var context = $(this).closest('.hiddenfieldsContainer');
        $('.hiddenfields', context).show();
        $('.hiddenfieldsToggle', context).hide();
        $('.hiddenfieldsCloseCorner', context).show();
        $('.hiddenfieldsCloseButton', context).show();
    });

    var that = this;
    this.element.find('.hiddenfieldsCloseCorner, .hiddenfieldsCloseButton').click(function(event) {
        that.closeTags();
    });

    $(document).click(function(e) {
        if ($(e.target).closest('.hiddenfieldsContainer').size() == 0 && $('.hiddenfieldsCloseCorner:visible').length > 0){
            that.closeTags();
        }
    });

    // init tags
    this.initTags();
    this.loadTags();

    // init editor
    this.initEditable();
};

VieBundle.Model.prototype.closeTags = function () {
    var context = $('.hiddenfieldsContainer');
    $('.hiddenfields', context).hide();
    $('.hiddenfieldsToggle', context).show();
    $('.hiddenfieldsCloseCorner', context).hide();
    $('.hiddenfieldsCloseButton', context).hide();

    // save on close
    this.save();
}

VieBundle.Model.prototype.tagLabel = function (value) {

    if (value.substring(0, 9) == '<urn:tag:') {
        value = value.substring(9, value.length - 1);
    }

    if (value.substring(0, 8) == '<http://') {
        value = value.substring(value.lastIndexOf('/') + 1, value.length - 1);
        value = value.replace(/_/g, ' ');
    }

    return value;
};

VieBundle.Model.prototype.initTags = function () {

    var that = this;

    this.articleTags.tagsInput({
        width:'auto',
        height: 'auto',
        onAddTag: function (tag) {

            var entity = that.entity;

            // convert to reference url
            if (!entity.isReference(tag)) {
                tag = 'urn:tag:' + tag;
            }

            // add tag to entity
            entity.attributes['<http://purl.org/dc/elements/1.1/subject>'].vie = that.vie;
            entity.attributes['<http://purl.org/dc/elements/1.1/subject>'].addOrUpdate({'@subject': tag});
        },
        onRemoveTag: function (tag) {

            // remove tag from entity
            that.entity.attributes['<http://purl.org/dc/elements/1.1/subject>'].remove(tag);
        },
        label: this.tagLabel
    });

    this.suggestedTags.tagsInput({
        width:'auto',
        height: 'auto',
        interactive: false,
        label: this.tagLabel,
        remove: false
    });

    // add suggested tag on click to tags
    this.element.find('.articleSuggestedTags .tag span').live('click', function(){

        var tag = $(this).text();
        that.articleTags.addTag($(this).data('value'));
        that.suggestedTags.removeTag($.trim(tag));

        return false;
    });
};

VieBundle.Model.prototype.loadTags = function () {

    var that = this;

    // load article tags
    var tags = this.entity.attributes['<http://purl.org/dc/elements/1.1/subject>'].models;
    jQuery(tags).each(function () {
        that.articleTags.addTag(this.id);
    });

    // load suggested tags
    var text = $(that.element).text();
    that.vie.analyze({element: $(that.element)}).using(['stanbol']).execute().success(function(enhancements) {
        return $(enhancements).each(function(i, e) {
            if (e.attributes['<rdfschema:label>']) {
                that.suggestedTags.addTag(e.id);
            }
        });
    }).fail(function(xhr) {
        console.log(xhr);
    });
};

VieBundle.Model.prototype.initEditable = function () {

    this.element.midgardEditable({
        vie: this.vie,
        model: this.entity,
        addButton: true,
        editorOptions: {
            'dcterms:title': {
                plugins: {
                    'hallooverlay': {},
                    'hallotoolbarlinebreak': {}
                }
            },
            'default': {
                plugins: {
                    'halloimage': { 'searchUrl': 'liip/vie/assets/search/', 'vie': this.vie },
                    'hallolink': { 'relatedUrl': vie_plugins_link_related_path },
                    'halloheadings': {},
                    'halloformat': {'formattings': {'strikeThrough': false, 'underline': false}},
                    'hallolists': {'lists': {'ordered': false}},
                    'hallojustify': {},
                    'halloreundo': {},
                    'hallotoolbarlinebreak': { 'breakAfter': ['hallolink'] },
                    'hallooverlay': {}
                },
                floating: false,
                showAlways: true
            }
        },
        deactivated: $.proxy(this.save, this)
    });
};

VieBundle.Model.prototype.save = function () {

    // move hover back behind
    //$('.liipVieBundleContentEditableHover').css('z-index', '0');

    // don't save if blocked by dragged images
    if (this.bundle.preventSave) {
        setTimeout(this.save, 5000);
        return;
    }

    // save the Backbone model
    this.entity.save(null, {
        success: function(model, response) {
            $(document).trigger("vieSaveSuccess");
            console.log(model.id + " was saved");
        },
        error: function(response) {
            console.log("Save failed");
            console.log(response);
        }
    });
};

VieBundle.Hallo = function () {

    this.preventSave = false;

    this.initVIE();

    var that = this;
    $('[typeof][about]').each(function() {

        var element = $(this);

        var model = new VieBundle.Model(that, element);
    });
};

VieBundle.Hallo.prototype.initVIE = function () {

    this.vie = new VIE();
    this.vie.EntityManager.entities.bind('add', function(model) {
        if (typeof model.id == 'string') {
            model.url = vie_phpcr_path + model.id.substring(1, model.id.length - 1);
            model.toJSON = model.toJSONLD;
        }
    });

    this.vie.use(new this.vie.RdfaService());

    this.vie.namespaces.add('sioc', 'http://rdfs.org/sioc/ns#');
    this.vie.namespaces.add('dc', 'http://purl.org/dc/elements/1.1/');

    this.vie.use(new this.vie.StanbolService({
        url: "http://cmf.lo/stanbol",
        proxyDisabled: true
    }));
};

VieBundle.Hallo.prototype.setPreventSave = function (value) {
    this.preventSave = value;
};

jQuery(document).ready(function ($) {

    var bundle = new VieBundle.Hallo();

    $(this).bind('startPreventSave', function() {
        bundle.setPreventSave(true);
    });

    $(this).bind('stopPreventSave', function() {
        bundle.setPreventSave(false);
    });

    $(window).resize(function() {
        if(!$('.inEditMode')[0] == undefined ){
            $('.halloToolbar').css('left', $('.inEditMode')[0].offsetLeft);
        }
    });

    // edit hover
    var hover = $('
');
    hover.hide();
    $('body').append(hover);

    // show edit button on hover
    $('[contenteditable]').not('.inEditMode').hover(function () {

        $(document).trigger('startPreventSave');

        var $this = $(this);

        if(!$this.hasClass('inEditMode')){
            var editButton = $('
edit
').addClass('editButton');
            $this.before(editButton);
        }

        var offset = $this.offset();
        hover.css({top: offset.top - 10, left: offset.left - 10});
        hover.width($this.width());
        hover.height($this.height());
        hover.show();

    }, function () {

        $(document).trigger('stopPreventSave');

        $('.editButton').remove();

        hover.hide();
    });
});
<|endoftext|>


<commit_before>/*
---
description: Creates instances of HtmlTable for any table with the css class .ccs-data_table with additional options for sortability and selectability.
provides: [Behavior.HtmlTable]
requires: [/Behavior, More/HtmlTable.Sort, More/HtmlTable.Zebra, More/HtmlTable.Select]
script: Behavior.HtmlTable.js
...
*/

Behavior.addGlobalFilters({

	HtmlTable: function(element, events){
		//make all data tables sortable
		var table = element;
		var selectable;
		var isSelectable = (table.hasClass('sortable') && !table.hasClass('noSelect')) || table.hasClass('selectable');
		var ht = new HtmlTable(table, {
			sortable: table.hasClass('sortable'),
			selectable: isSelectable,
			allowMultiSelect: table.hasClass('allowMultiSelect'),
			useKeyboard: false
		});
		if (isSelectable && !selectable) selectable = ht;
	}

});

<commit_msg>adding data-sort types to HtmlTable parsers<commit_after>/*
---
description: Creates instances of HtmlTable for any table with the css class .ccs-data_table with additional options for sortability and selectability.
provides: [Behavior.HtmlTable]
requires: [/Behavior, More/HtmlTable.Sort, More/HtmlTable.Zebra, More/HtmlTable.Select]
script: Behavior.HtmlTable.js
...
*/

Behavior.addGlobalFilters({

	HtmlTable: function(element, events){
		//make all data tables sortable
		var table = element;
		var selectable;
		var isSelectable = (table.hasClass('sortable') && !table.hasClass('noSelect')) || table.hasClass('selectable');
		var ht = new HtmlTable(table, {
			sortable: table.hasClass('sortable'),
			selectable: isSelectable,
			allowMultiSelect: table.hasClass('allowMultiSelect'),
			useKeyboard: false
		});
		if (isSelectable && !selectable) selectable = ht;
	}

});

HtmlTable.defineParsers({
	//A parser to allow numeric sorting by any value.
	dataSortNumeric: {
		match: /data-sort-numeric/,
		convert: function() {
			return this.get('data', 'sort-value');
		},
		number: true
	},
	//A parser to allow lexicographical sorting by any string.
	dataSortString: {
		match: /data-sort-string/,
		convert: function() {
			return this.get('data', 'sort-string');
		},
		number: false
	}
});<|endoftext|>