<commit_before>"use strict";var directiveModule=angular.module("angularjs-dropdown-multiselect",[]);directiveModule.directive("ngDropdownMultiselect",["$filter","$document","$compile","$parse",function($filter,$document){return{restrict:"AE",scope:{selectedModel:"=",options:"=",extraSettings:"=",events:"=",translationTexts:"=",groupBy:"@"},template:function(element,attrs){var checkboxes=attrs.checkboxes?!0:!1,groups=attrs.groupBy?!0:!1,template='
';template+='<button type="button" class="dropdown-toggle" ng-class="settings.buttonClasses" ng-click="toggleDropdown()">{{getButtonText()}} </button>',template+="
",template+='
 0">  {{texts.checkAll}}',template+='
   {{texts.uncheckAll}}
',template+='
 0) && !settings.showUncheckAll" class="divider">
',template+='

<input type="text" class="form-control" style="width: 100%;" ng-model="searchFilter" placeholder="{{texts.searchPlaceholder}}" />
',template+='

',groups?(template+='
{{ getGroupTitle(getPropertyForObject(option, settings.groupBy)) }}
',template+='
'):template+='
',template+='',template+=checkboxes?'
<input class="checkboxInput" type="checkbox" ng-click="checkboxClick($event, getPropertyForObject(option,settings.idProp))" ng-checked="isChecked(getPropertyForObject(option,settings.idProp))" /> {{getPropertyForObject(option, settings.displayProp)}}
':" {{getPropertyForObject(option, settings.displayProp)}}",template+="
",template+='
 1">
',template+='
 1">{{selectedModel.length}} {{texts.selectionOf}} {{settings.selectionLimit}} {{texts.selectionCount}}
',template+="
",template+="
",element.html(template)},link:function($scope,$element,$attrs){function getFindObj(id){var findObj={};return""===$scope.settings.externalIdProp?findObj[$scope.settings.idProp]=id:findObj[$scope.settings.externalIdProp]=id,findObj}function clearObject(object){for(var prop in object)delete object[prop]}$scope.toggleDropdown=function(){$scope.open=!$scope.open},$scope.checkboxClick=function($event,id){$scope.setSelectedItem(id),$event.stopImmediatePropagation()},$scope.searchFilter="",$scope.externalEvents={onItemSelect:angular.noop,onItemDeselect:angular.noop,onSelectAll:angular.noop,onDeselectAll:angular.noop,onInitDone:angular.noop,onMaxSelectionReached:angular.noop},$scope.settings={dynamicTitle:!0,scrollable:!1,scrollableHeight:"300px",closeOnBlur:!0,displayProp:"label",idProp:"id",externalIdProp:"id",enableSearch:!1,selectionLimit:0,showCheckAll:!0,showUncheckAll:!0,closeOnSelect:!1,buttonClasses:"btn btn-default",closeOnDeselect:!1,groupBy:$attrs.groupBy||void 0,groupByTextProvider:null,smartButtonMaxItems:0,smartButtonTextConverter:angular.noop},$scope.texts={checkAll:"Check All",uncheckAll:"Uncheck All",selectionCount:"checked",selectionOf:"/",searchPlaceholder:"Search...",buttonDefaultText:"Select",dynamicButtonTextSuffix:"checked"},angular.isDefined($scope.settings.groupBy)&&$scope.$watch("options",function(newValue){angular.isDefined(newValue)&&($scope.orderedItems=$filter("orderBy")(newValue,$scope.settings.groupBy))}),angular.extend($scope.settings,$scope.extraSettings||[]),angular.extend($scope.externalEvents,$scope.events||[]),angular.extend($scope.texts,$scope.translationTexts),$scope.singleSelection=1===$scope.settings.selectionLimit,$scope.singleSelection&&angular.isArray($scope.selectedModel)&&0===$scope.selectedModel.length&&clearObject($scope.selectedModel),$scope.settings.closeOnBlur&&$document.on("click",function(e){for(var target=e.target.parentElement,parentFound=!1;angular.isDefined(target)&&null!==target&&!parentFound;)_.contains(target.className.split(" "),"multiselect-parent")&&!parentFound&&(parentFound=!0),target=target.parentElement;parentFound||$scope.$apply(function(){$scope.open=!1})}),$scope.getGroupTitle=function(groupValue){return null!==$scope.settings.groupByTextProvider?$scope.settings.groupByTextProvider(groupValue):groupValue},$scope.getButtonText=function(){if($scope.settings.dynamicTitle&&($scope.selectedModel.length>0||angular.isObject($scope.selectedModel)&&_.keys($scope.selectedModel).length>0)){if($scope.settings.smartButtonMaxItems>0){var itemsText=[];return angular.forEach($scope.options,function(optionItem){if($scope.isChecked($scope.getPropertyForObject(optionItem,$scope.settings.idProp))){var displayText=$scope.getPropertyForObject(optionItem,$scope.settings.displayProp),converterResponse=$scope.settings.smartButtonTextConverter(displayText,optionItem);itemsText.push(converterResponse?converterResponse:displayText)}}),$scope.selectedModel.length>$scope.settings.smartButtonMaxItems&&(itemsText=itemsText.slice(0,$scope.settings.smartButtonMaxItems),itemsText.push("...")),itemsText.join(", ")}var totalSelected;return totalSelected=$scope.singleSelection?null!==$scope.selectedModel&&angular.isDefined($scope.selectedModel[$scope.settings.idProp])?1:0:angular.isDefined($scope.selectedModel)?$scope.selectedModel.length:0,0===totalSelected?$scope.texts.buttonDefaultText:totalSelected+" "+$scope.texts.dynamicButtonTextSuffix}return $scope.texts.buttonDefaultText},$scope.getPropertyForObject=function(object,property){return angular.isDefined(object)&&object.hasOwnProperty(property)?object[property]:""},$scope.selectAll=function(){$scope.deselectAll(!1),$scope.externalEvents.onSelectAll(),angular.forEach($scope.options,function(value){$scope.setSelectedItem(value[$scope.settings.idProp],!0)})},$scope.deselectAll=function(sendEvent){sendEvent=sendEvent||!0,sendEvent&&$scope.externalEvents.onDeselectAll(),$scope.singleSelection?clearObject($scope.selectedModel):$scope.selectedModel.splice(0,$scope.selectedModel.length)},$scope.setSelectedItem=function(id,dontRemove){var findObj=getFindObj(id),finalObj=null;if(finalObj=""===$scope.settings.externalIdProp?_.find($scope.options,findObj):findObj,$scope.singleSelection)return clearObject($scope.selectedModel),angular.extend($scope.selectedModel,finalObj),void $scope.externalEvents.onItemSelect(finalObj);dontRemove=dontRemove||!1;var exists=-1!==_.findIndex($scope.selectedModel,findObj);!dontRemove&&exists?($scope.selectedModel.splice(_.findIndex($scope.selectedModel,findObj),1),$scope.externalEvents.onItemDeselect(findObj)):!exists&&(0===$scope.settings.selectionLimit||$scope.selectedModel.length<$scope.settings.selectionLimit)&&($scope.selectedModel.push(finalObj),$scope.externalEvents.onItemSelect(finalObj))},$scope.isChecked=function(id){return $scope.singleSelection?null!==$scope.selectedModel&&angular.isDefined($scope.selectedModel[$scope.settings.idProp])&&$scope.selectedModel[$scope.settings.idProp]===getFindObj(id)[$scope.settings.idProp]:-1!==_.findIndex($scope.selectedModel,getFindObj(id))},$scope.externalEvents.onInitDone()}}}]);<commit_msg>updated minified<commit_after>"use strict";var directiveModule=angular.module("angularjs-dropdown-multiselect",[]);directiveModule.directive("ngDropdownMultiselect",["$filter","$document","$compile","$parse",function($filter,$document){return{restrict:"AE",scope:{selectedModel:"=",options:"=",extraSettings:"=",events:"=",translationTexts:"=",groupBy:"@"},template:function(element,attrs){var checkboxes=attrs.checkboxes?!0:!1,groups=attrs.groupBy?!0:!1,template='
';template+='<button type="button" class="dropdown-toggle" ng-class="settings.buttonClasses" ng-click="toggleDropdown()">{{getButtonText()}} </button>',template+="
",template+='
 0">  {{texts.checkAll}}',template+='
   {{texts.uncheckAll}}
',template+='
 0) && !settings.showUncheckAll" class="divider">
',template+='

<input type="text" class="form-control" style="width: 100%;" ng-model="searchFilter" placeholder="{{texts.searchPlaceholder}}" />
',template+='

',groups?(template+='
{{ getGroupTitle(getPropertyForObject(option, settings.groupBy)) }}
',template+='
'):template+='
',template+='',template+=checkboxes?'
<input class="checkboxInput" type="checkbox" ng-click="checkboxClick($event, getPropertyForObject(option,settings.idProp))" ng-checked="isChecked(getPropertyForObject(option,settings.idProp))" /> {{getPropertyForObject(option, settings.displayProp)}}
':" {{getPropertyForObject(option, settings.displayProp)}}",template+="
",template+='
 1">
',template+='
 1">{{selectedModel.length}} {{texts.selectionOf}} {{settings.selectionLimit}} {{texts.selectionCount}}
',template+="
",template+="
",element.html(template)},link:function($scope,$element,$attrs){function getFindObj(id){var findObj={};return""===$scope.settings.externalIdProp?findObj[$scope.settings.idProp]=id:findObj[$scope.settings.externalIdProp]=id,findObj}function clearObject(object){for(var prop in object)delete object[prop]}var $dropdownTrigger=$element.children()[0];$scope.toggleDropdown=function(){$scope.open=!$scope.open},$scope.checkboxClick=function($event,id){$scope.setSelectedItem(id),$event.stopImmediatePropagation()},$scope.searchFilter="",$scope.externalEvents={onItemSelect:angular.noop,onItemDeselect:angular.noop,onSelectAll:angular.noop,onDeselectAll:angular.noop,onInitDone:angular.noop,onMaxSelectionReached:angular.noop},$scope.settings={dynamicTitle:!0,scrollable:!1,scrollableHeight:"300px",closeOnBlur:!0,displayProp:"label",idProp:"id",externalIdProp:"id",enableSearch:!1,selectionLimit:0,showCheckAll:!0,showUncheckAll:!0,closeOnSelect:!1,buttonClasses:"btn btn-default",closeOnDeselect:!1,groupBy:$attrs.groupBy||void 0,groupByTextProvider:null,smartButtonMaxItems:0,smartButtonTextConverter:angular.noop},$scope.texts={checkAll:"Check All",uncheckAll:"Uncheck All",selectionCount:"checked",selectionOf:"/",searchPlaceholder:"Search...",buttonDefaultText:"Select",dynamicButtonTextSuffix:"checked"},angular.isDefined($scope.settings.groupBy)&&$scope.$watch("options",function(newValue){angular.isDefined(newValue)&&($scope.orderedItems=$filter("orderBy")(newValue,$scope.settings.groupBy))}),angular.extend($scope.settings,$scope.extraSettings||[]),angular.extend($scope.externalEvents,$scope.events||[]),angular.extend($scope.texts,$scope.translationTexts),$scope.singleSelection=1===$scope.settings.selectionLimit,$scope.singleSelection&&angular.isArray($scope.selectedModel)&&0===$scope.selectedModel.length&&clearObject($scope.selectedModel),$scope.settings.closeOnBlur&&$document.on("click",function(e){for(var target=e.target.parentElement,parentFound=!1;angular.isDefined(target)&&null!==target&&!parentFound;)_.contains(target.className.split(" "),"multiselect-parent")&&!parentFound&&target===$dropdownTrigger&&(parentFound=!0),target=target.parentElement;parentFound||$scope.$apply(function(){$scope.open=!1})}),$scope.getGroupTitle=function(groupValue){return null!==$scope.settings.groupByTextProvider?$scope.settings.groupByTextProvider(groupValue):groupValue},$scope.getButtonText=function(){if($scope.settings.dynamicTitle&&($scope.selectedModel.length>0||angular.isObject($scope.selectedModel)&&_.keys($scope.selectedModel).length>0)){if($scope.settings.smartButtonMaxItems>0){var itemsText=[];return angular.forEach($scope.options,function(optionItem){if($scope.isChecked($scope.getPropertyForObject(optionItem,$scope.settings.idProp))){var displayText=$scope.getPropertyForObject(optionItem,$scope.settings.displayProp),converterResponse=$scope.settings.smartButtonTextConverter(displayText,optionItem);itemsText.push(converterResponse?converterResponse:displayText)}}),$scope.selectedModel.length>$scope.settings.smartButtonMaxItems&&(itemsText=itemsText.slice(0,$scope.settings.smartButtonMaxItems),itemsText.push("...")),itemsText.join(", ")}var totalSelected;return totalSelected=$scope.singleSelection?null!==$scope.selectedModel&&angular.isDefined($scope.selectedModel[$scope.settings.idProp])?1:0:angular.isDefined($scope.selectedModel)?$scope.selectedModel.length:0,0===totalSelected?$scope.texts.buttonDefaultText:totalSelected+" "+$scope.texts.dynamicButtonTextSuffix}return $scope.texts.buttonDefaultText},$scope.getPropertyForObject=function(object,property){return angular.isDefined(object)&&object.hasOwnProperty(property)?object[property]:""},$scope.selectAll=function(){$scope.deselectAll(!1),$scope.externalEvents.onSelectAll(),angular.forEach($scope.options,function(value){$scope.setSelectedItem(value[$scope.settings.idProp],!0)})},$scope.deselectAll=function(sendEvent){sendEvent=sendEvent||!0,sendEvent&&$scope.externalEvents.onDeselectAll(),$scope.singleSelection?clearObject($scope.selectedModel):$scope.selectedModel.splice(0,$scope.selectedModel.length)},$scope.setSelectedItem=function(id,dontRemove){var findObj=getFindObj(id),finalObj=null;if(finalObj=""===$scope.settings.externalIdProp?_.find($scope.options,findObj):findObj,$scope.singleSelection)return clearObject($scope.selectedModel),angular.extend($scope.selectedModel,finalObj),void $scope.externalEvents.onItemSelect(finalObj);dontRemove=dontRemove||!1;var exists=-1!==_.findIndex($scope.selectedModel,findObj);!dontRemove&&exists?($scope.selectedModel.splice(_.findIndex($scope.selectedModel,findObj),1),$scope.externalEvents.onItemDeselect(findObj)):!exists&&(0===$scope.settings.selectionLimit||$scope.selectedModel.length<$scope.settings.selectionLimit)&&($scope.selectedModel.push(finalObj),$scope.externalEvents.onItemSelect(finalObj))},$scope.isChecked=function(id){return $scope.singleSelection?null!==$scope.selectedModel&&angular.isDefined($scope.selectedModel[$scope.settings.idProp])&&$scope.selectedModel[$scope.settings.idProp]===getFindObj(id)[$scope.settings.idProp]:-1!==_.findIndex($scope.selectedModel,getFindObj(id))},$scope.externalEvents.onInitDone()}}}]);
<|endoftext|>


<commit_before>/**
 * Author: Michał Gołębiowski <michal.golebiowski@laboratorium.ee>
 * Author: Brandon Aaron (http://brandonaaron.net)
 * Copyright (c) 2011 Brandon Aaron (http://brandonaaron.net)
 * Copyright (c) 2013 Laboratorium EE (http://laboratorium.ee)
 */

(function ($) {
    'use strict';

    // Modern browsers support 'wheel', others - 'mousewheel'.
    var nativeEvent = 'onwheel' in document.createElement('div') ? 'wheel' : 'mousewheel';

    // Normalizing event properties for the 'wheel' event (like event.which etc.).
    if (nativeEvent === 'wheel') {
        $.event.fixHooks.wheel = $.event.mouseHooks;
    } else {
        // We can't attach hooks to 'wheel' only since we need a type matching to originalEvent.type
        // and this field is non-mutable.
        $.event.fixHooks.mousewheel = $.event.mouseHooks;
    }

    function handler(orgEvent) {
        // Handler for the 'mousewheel' event (Chrome, Opera, Safari).
        /* jshint validthis: true */ // event handler

        var event = $.event.fix(orgEvent);

        if (nativeEvent === 'wheel') {
            event.deltaMode = orgEvent.deltaMode;
            event.deltaX = orgEvent.deltaX;
            event.deltaY = orgEvent.deltaY;
            event.deltaZ = orgEvent.deltaZ;
        } else {
            event.type = 'wheel';
            event.deltaMode = 0; // deltaMode === 0 => scrolling in pixels (in Chrome default wheelDeltaY is 120)
            event.deltaX = -1 * orgEvent.wheelDeltaX;
            event.deltaY = -1 * orgEvent.wheelDeltaY;
            event.deltaZ = 0; // not supported
        }

        // Exchange original event for the modified one in arguments list.
        var args = [].slice.call(arguments, 0);
        args[0] = event;

        return $.event.dispatch.apply(this, args);
    }

    // Implementing 'wheel' using non-standard 'mousewheel' event.
    $.event.special.wheel = {
        setup: function () {
            this.addEventListener(nativeEvent, handler, false);
        },

        teardown: function () {
            this.removeEventListener(nativeEvent, handler, false);
        }
    };

    // Implement `$object.wheel()` and `$object.wheel(handler)`.
    $.fn.wheel = function (data, fn) {
        return arguments.length > 0 ?
            this.on('wheel', null, data, fn) :
            this.trigger('wheel');
    };
})(jQuery);
<commit_msg>prevent polyfilling twice<commit_after>/**
 * Author: Michał Gołębiowski <michal.golebiowski@laboratorium.ee>
 * Author: Brandon Aaron (http://brandonaaron.net)
 * Copyright (c) 2011 Brandon Aaron (http://brandonaaron.net)
 * Copyright (c) 2013 Laboratorium EE (http://laboratorium.ee)
 */

(function ($) {
    'use strict';

    if ($.fn.wheel) { // already polyfilled
        return;
    }

    // Modern browsers support 'wheel', others - 'mousewheel'.
    var nativeEvent = 'onwheel' in document.createElement('div') ? 'wheel' : 'mousewheel';

    // Normalizing event properties for the 'wheel' event (like event.which etc.).
    if (nativeEvent === 'wheel') {
        $.event.fixHooks.wheel = $.event.mouseHooks;
    } else {
        // We can't attach hooks to 'wheel' only since we need a type matching to originalEvent.type
        // and this field is non-mutable.
        $.event.fixHooks.mousewheel = $.event.mouseHooks;
    }

    function handler(orgEvent) {
        // Handler for the 'mousewheel' event (Chrome, Opera, Safari).
        /* jshint validthis: true */ // event handler

        var event = $.event.fix(orgEvent);

        if (nativeEvent === 'wheel') {
            event.deltaMode = orgEvent.deltaMode;
            event.deltaX = orgEvent.deltaX;
            event.deltaY = orgEvent.deltaY;
            event.deltaZ = orgEvent.deltaZ;
        } else {
            event.type = 'wheel';
            event.deltaMode = 0; // deltaMode === 0 => scrolling in pixels (in Chrome default wheelDeltaY is 120)
            event.deltaX = -1 * orgEvent.wheelDeltaX;
            event.deltaY = -1 * orgEvent.wheelDeltaY;
            event.deltaZ = 0; // not supported
        }

        // Exchange original event for the modified one in arguments list.
        var args = [].slice.call(arguments, 0);
        args[0] = event;

        return $.event.dispatch.apply(this, args);
    }

    // Implementing 'wheel' using non-standard 'mousewheel' event.
    $.event.special.wheel = {
        setup: function () {
            this.addEventListener(nativeEvent, handler, false);
        },

        teardown: function () {
            this.removeEventListener(nativeEvent, handler, false);
        }
    };

    // Implement `$object.wheel()` and `$object.wheel(handler)`.
    $.fn.wheel = function (data, fn) {
        return arguments.length > 0 ?
            this.on('wheel', null, data, fn) :
            this.trigger('wheel');
    };
})(jQuery);
<|endoftext|>


<commit_before>// var firstComponent =
hello
;//this throws an error

var MyTitle = React.createClass({
    render: function(){
        return(
            React.DOM.div(null,
            React.DOM.h1(null, "check out second component"))
        )
    }
})

var firstComponent = React.createClass({
    render: function(){
        return (
            React.DOM.div(null,
            // React.DOM.h1(null, "this is react firstComponent"))
            React.createElement(MyTitle),
            React.createElement(MyTitle)
            )
        )
    }
})

ReactDOM.render(
    React.createElement(firstComponent),
    // firstComponent, this will not work, check console errors
    document.getElementById('app')
);<commit_msg>add props to component<commit_after>// var firstComponent =
hello
;//this throws an error

var MyTitle = React.createClass({
    render: function(){
        console.log(this.props)
        return(
            React.DOM.div(null,
            // React.DOM.h1(null, "this was second component")
            React.DOM.h1({style: {color: this.props.color} }, this.props.title)
            )
        )
    }
})

var MyTitleFactory = React.createFactory(MyTitle)

var firstComponent = React.createClass({
    render: function(){
        return (
            React.DOM.div(null,
            // React.DOM.h1(null, "this is react firstComponent"))
            // React.createElement(MyTitle),
            // React.createElement(MyTitle)
            MyTitleFactory({title: "this is being passed as props", color: "goldenrod"}),
            MyTitleFactory({title: "this as well, props", color: "aquamarine"})
            )
        )
    }
})

ReactDOM.render(
    React.createElement(firstComponent),
    // firstComponent, this will not work, check console errors
    document.getElementById('app')
);<|endoftext|>


<commit_before>'use strict';

const uuid = require('uuid');
const _ = require('lodash');
const url = require('url');
const qs = require('querystring');
const mime = require('mimelib');
const Odata = require('./odata');
const util = require('util');
const Expression = require('./expression');

var Batch = function(parent)
{
  this.parent = parent;
  this.boundary = `batch_${uuid.v4()}`;
  this.ops = [];
  this.reset();
  return this;
};

console.log(Odata);
util.inherits(Batch, Odata);

Batch.prototype.addPathComponent = function(component)
{
  this.url.addPathComponent(component);
};

Batch.prototype.addQueryParameter = function(name, value)
{
  this.url.addQueryParameter(name, value);
};

Batch.prototype.reset = function()
{
  if(this.parent._filter) {
    this._filter = new Expression(this.parent._filter);
  } else {
    delete this._filter;
  }
  if(this.parent._select) {
    this._select = _.slice(this.parent._select);
  } else {
    delete this._select;
  }
  this._count = this.parent._count;
  if(this.parent._order) {
    this._order = this.prent._order;
  } else {
    delete this._order;
  }
  if(this.parent._expand) {
    this._expand = this.parent._expand;
  } else {
    delete this._expand;
  }
  if(this.parent._search) {
    this._search = this.parent._search;
  } else {
    delete this._search;
  }
  this.config = this.parent.config;
  this.url = this.parent.url.clone();
};

var process = function(method, options, body)
{
  options = options || {};
  if(options.qs) {
    this.url.addQueryParameters(options.qs);
  }
  return {
    method: method,
    query: this.query(),
    headers: options.headers || {},
    body: body
  }
};

Batch.prototype.get = function(options)
{
  this.ops.push(process.call(this, 'GET', options));
  this.reset();
  return;
};

Batch.prototype.post = function(body, options)
{
  this.ops.push(process.call(this, 'POST', options, body));
  this.reset();
  return;
}

Batch.prototype.put = function(body, options)
{
  this.ops.push(process.call(this, 'PUT', options, body));
  this.reset();
  return;
}

Batch.prototype.patch = function(body, options)
{
  this.ops.push(process.call(this, 'PATCH', options, body));
  this.reset();
  return;
}

Batch.prototype.delete = function(options)
{
  this.ops.push(process.call(this, 'DELETE', options));
  this.reset();
  return;
};

Batch.prototype.body = function()
{
  var msg = '';
  for(let op of this.ops) {
    msg += `--${this.boundary}\r\n`;
    msg += 'Content-Type: application/http\r\n';
    msg += 'Content-Transfer-Encoding: binary\r\n\r\n';
    msg += `${op.method} ${op.query} HTTP/1.1\r\n`;
    _.forOwn(op.headers, function(v, k) {
      msg += mime.foldLine(`${k}: ${v}`, 76) + '\r\n';
    });
    let body = '';
    if(op.body) {
      let buf = '';
      if(op.headers['Content-Type'] === undefined || _.isPlainObject(op.body)) {
        msg += 'Content-Type: application/json\r\n';
        msg += 'Content-Transfer-Encoding: base64\r\n';
        buf = Buffer(JSON.stringify(op.body)).toString('base64');
      } else {
        msg += `Content-Type: ${op.headers['Content-Type']}\r\n`;
        msg += 'Content-Transfer-Encoding: base64\r\n';
        buf = Buffer(op.body.toString()).toString('base64');
      }

      body = `${mime.foldLine(buf, 76, true)}\r\n`;
    }
    msg += `Content-Length: ${body.length}\r\n\r\n${body}`;
  }
  if(this.ops.length > 0) {
    msg += `--${this.boundary}--`;
  }
  return msg;
};

module.exports = function(q)
{
  return new Batch(q);
};

<commit_msg>Add changesets to batches<commit_after>'use strict';

const uuid = require('uuid');
const _ = require('lodash');
const url = require('url');
const qs = require('querystring');
const mime = require('mimelib');
const Odata = require('./odata');
const util = require('util');
const Expression = require('./expression');

var Batch = function(parent)
{
  this.parent = parent;
  this.boundary = `batch_${uuid.v4()}`;
  this.ops = [];
  this.reset();
  return this;
};

console.log(Odata);
util.inherits(Batch, Odata);

Batch.prototype.addPathComponent = function(component)
{
  this.url.addPathComponent(component);
};

Batch.prototype.addQueryParameter = function(name, value)
{
  this.url.addQueryParameter(name, value);
};

Batch.prototype.reset = function()
{
  if(this.parent._filter) {
    this._filter = new Expression(this.parent._filter);
  } else {
    delete this._filter;
  }
  if(this.parent._select) {
    this._select = _.slice(this.parent._select);
  } else {
    delete this._select;
  }
  this._count = this.parent._count;
  if(this.parent._order) {
    this._order = this.prent._order;
  } else {
    delete this._order;
  }
  if(this.parent._expand) {
    this._expand = this.parent._expand;
  } else {
    delete this._expand;
  }
  if(this.parent._search) {
    this._search = this.parent._search;
  } else {
    delete this._search;
  }
  this.config = this.parent.config;
  this.url = this.parent.url.clone();
};

var process = function(method, options, body)
{
  options = options || {};
  if(method === 'GET') {
    delete this._changeset;
  } else {
    this._changeset = this._changeset || `changeset_${uuid.v4()}`;
  }
  if(options.qs) {
    this.url.addQueryParameters(options.qs);
  }
  return {
    method: method,
    query: this.query(),
    headers: options.headers || {},
    body: body,
    changeset: this._changeset
  }
};

Batch.prototype.get = function(options)
{
  this.ops.push(process.call(this, 'GET', options));
  this.reset();
  return;
};

Batch.prototype.post = function(body, options)
{
  this.ops.push(process.call(this, 'POST', options, body));
  this.reset();
  return;
}

Batch.prototype.put = function(body, options)
{
  this.ops.push(process.call(this, 'PUT', options, body));
  this.reset();
  return;
}

Batch.prototype.patch = function(body, options)
{
  this.ops.push(process.call(this, 'PATCH', options, body));
  this.reset();
  return;
}

Batch.prototype.delete = function(options)
{
  this.ops.push(process.call(this, 'DELETE', options));
  this.reset();
  return;
};

Batch.prototype.body = function()
{
  var msg = '';
  var last_changeset = '';
  for(let op of this.ops) {
    if(op.changeset) {
      if(op.changeset != last_changeset) {
        if(last_changeset) {
          msg += `--${last_changeset}--\r\n`;
        }
        msg += `Content-Type: multipart/mixed; boundary=${op.changeset}\r\n\r\n`;
        msg += `--${op.changeset}\r\n`;
      }
    } else {
      if(last_changeset) {
        msg += `--${last_changeset}--\r\n`;
      }
      msg += `--${this.boundary}\r\n`;
    }
    last_changeset = op.changeset;
    msg += 'Content-Type: application/http\r\n';
    msg += 'Content-Transfer-Encoding: binary\r\n\r\n';
    msg += `${op.method} ${op.query} HTTP/1.1\r\n`;
    _.forOwn(op.headers, function(v, k) {
      msg += mime.foldLine(`${k}: ${v}`, 76) + '\r\n';
    });
    let body = '';
    if(op.body) {
      let buf = '';
      if(op.headers['Content-Type'] === undefined || _.isPlainObject(op.body)) {
        msg += 'Content-Type: application/json\r\n';
        msg += 'Content-Transfer-Encoding: base64\r\n';
        buf = Buffer(JSON.stringify(op.body)).toString('base64');
      } else {
        msg += `Content-Type: ${op.headers['Content-Type']}\r\n`;
        msg += 'Content-Transfer-Encoding: base64\r\n';
        buf = Buffer(op.body.toString()).toString('base64');
      }

      body = `${mime.foldLine(buf, 76, true)}\r\n`;
    }
    msg += `Content-Length: ${body.length}\r\n\r\n${body}`;
  }
  if(this.ops.length > 0) {
    msg += `--${this.boundary}--`;
  }
  return msg;
};

module.exports = function(q)
{
  return new Batch(q);
};

<|endoftext|>


<commit_before>module.exports = {
    bemjson: {
        block: 'b1',
        count: 7
    },
    init: function() {
        console.log(this.bemjson);
    }
};
<commit_msg>тестовый блок с контейнером для песочницы<commit_after>module.exports = {
    bemjson: {
        block: 'b1',
        count: 7
    },
    init: function(container) {

        for (var i = 0; i < this.bemjson.count; i++) {
            container.innerHTML += '
hello!
';
        }
    }
};
<|endoftext|>


<commit_before>/* globals process */
import path from 'path'

import defaults from '../defaults'

/**
 * Check if type is either `number` or `string`.
 *
 * @param {*} value - Any value.
 *
 * @returns {boolean}
 */
function isNumberOrString(value) {
  const type = typeof value

  return type === 'string' || type === 'number'
}

/**
 * Validate primary options of stylelint plugin config.
 *
 * @param {string|string[]} actual - The actual config to validate.
 *
 * @returns {boolean}
 */
function validProperties(actual) {
  return isNumberOrString(actual)
    || (Array.isArray(actual) && actual.every(item => isNumberOrString(item)))
}

/**
 * Validate optional secondary options of stylelint plugin config.
 *
 * @param {Object} actual - The actual config to validate.
 * @param {boolean} [actual.ignoreVariables=true] - Whether or not to lint variables.
 * @param {boolean} [actual.ignoreFunctions=true] - Whether or not to lint functions.
 * @param {string} [actual.severity='error'] - What the severity level is for this rule.
 * @param {number|string|Array|Object} [actual.ignoreKeywords=null] - A keywords config.
 * @param {string} [actual.message=null] - A custom message to be delivered upon error interpolated with `${types}`, `${value}` and `${property}`.
 *
 * @returns {boolean}
 */
function validOptions(actual) {
  if (typeof actual !== 'object') return false

  const allowedKeys = Object.keys(defaults)
  if (!Object.keys(actual).every(key => allowedKeys.indexOf(key) > -1)) return false

  if ('ignoreVariables' in actual
    && typeof actual.ignoreVariables !== 'boolean'
    && actual.ignoreVariables !== null) return false

  if ('ignoreFunctions' in actual
    && typeof actual.ignoreFunctions !== 'boolean'
    && actual.ignoreFunctions !== null) return false

  if ('severity' in actual
    && typeof actual.severity !== 'string'
    && actual.severity !== null) return false

  if ('ignoreKeywords' in actual
    && !validProperties(actual.ignoreKeywords)
    && !validHash(actual.ignoreKeywords)) return false

  if ('message' in actual
    && typeof actual.message !== 'string'
    && actual.message !== null) return false

  if ('disableFix' in actual
    && typeof actual.disableFix !== 'boolean'
    && actual.disableFix !== null) return false

  if ('autoFixFunc' in actual
    && typeof actual.autoFixFunc !== 'function'
    && typeof actual.autoFixFunc !== 'string'
    && actual.autoFixFunc !== null) return false

  return true
}

/**
 * Validate optional hash keyword config.
 *
 * @param {Object} actual - A keyword config.
 *
 * @returns {boolean}
 */
function validHash(actual) {
  if (typeof actual !== 'object') return false

  return Object.keys(actual).every(key => validProperties(actual[key]))
}

/**
 * Build expected message for stylelint report.
 *
 * @param {Array} types - Either `variable`, `function` and/or `keyword`.
 * @param {string} value - The CSS declaration's value.
 * @param {string} property - The CSS declaration's property.
 * @param {string} [customMessage] - A custom message to be delivered upon error interpolated with `${types}`, `${value}` and `${property}`.
 * @returns {string}
 */
function expected(types, value, property, customMessage) {
  if (Array.isArray(types)) {
    const typesLast = types.pop()

    // eslint-disable-next-line no-param-reassign
    types = types.length ? `${types.join(', ')} or ${typesLast}` : typesLast
  }

  if (typeof customMessage === 'string' && customMessage.length) {
    /* eslint-disable no-template-curly-in-string */
    return customMessage.replace('${types}', types)
      .replace('${value}', value)
      .replace('${property}', property)
    /* eslint-enable no-template-curly-in-string */
  }

  return `Expected ${types} for "${value}" of "${property}"`
}

/**
 * Get configured types for stylelint report message.
 *
 * @param {Object} config - The secondary stylelint-plugin config.
 * @param {string} property - The specific CSS declaration's property of the current iteration.
 * @returns {Array}
 */
function getTypes(config, property) {
  const { ignoreVariables, ignoreFunctions, ignoreKeywords } = config
  const types = []

  if (ignoreVariables) {
    types.push('variable')
  }

  if (ignoreFunctions) {
    types.push('function')
  }

  if (ignoreKeywords && getIgnoredKeywords(ignoreKeywords, property)) {
    types.push('keyword')
  }

  return types
}

/**
 * Get the correct ignored keywords for an specific CSS declaration's property
 * out of a complex ignoreKeywords config hash or array.
 *
 * @param {Object|Array|string} ignoreKeywords - The keyword/-s to ignore.
 * @param {string} property - The specific CSS declaration's property of the current iteration.
 * @returns {Array}
 */
function getIgnoredKeywords(ignoreKeywords, property) {
  if (!ignoreKeywords) return null

  let keywords = ignoreKeywords

  if ({}.hasOwnProperty.call(keywords, property)) {
    keywords = keywords[property]
  } else if ({}.hasOwnProperty.call(keywords, '')) {
    keywords = keywords['']
  }

  return Array.isArray(keywords) ? keywords : [keywords]
}

/**
 *
 * @param autoFixFunc
 * @returns {*}
 */
function getAutoFixFunc(autoFixFunc) {
  const type = typeof autoFixFunc

  if (type === 'function') {
    return autoFixFunc
  }

  if (type === 'string') {
    let resolveAutoFixfunc

    try {
      resolveAutoFixfunc = require.resolve(autoFixFunc)
    } catch (error) {
      resolveAutoFixfunc = require.resolve(path.join(process.cwd(), autoFixFunc))
    }

    // eslint-disable-next-line import/no-dynamic-require, global-require
    return require(resolveAutoFixfunc)
  }

  return null
}

export {
  validProperties,
  validOptions,
  expected,
  getTypes,
  getIgnoredKeywords,
  getAutoFixFunc,
}
<commit_msg>completed doclet<commit_after>/* globals process */
import path from 'path'

import defaults from '../defaults'

/**
 * Check if type is either `number` or `string`.
 *
 * @param {*} value - Any value.
 *
 * @returns {boolean}
 */
function isNumberOrString(value) {
  const type = typeof value

  return type === 'string' || type === 'number'
}

/**
 * Validate primary options of stylelint plugin config.
 *
 * @param {string|string[]} actual - The actual config to validate.
 *
 * @returns {boolean}
 */
function validProperties(actual) {
  return isNumberOrString(actual)
    || (Array.isArray(actual) && actual.every(item => isNumberOrString(item)))
}

/**
 * Validate optional secondary options of stylelint plugin config.
 *
 * @param {Object} actual - The actual config to validate.
 * @param {boolean} [actual.ignoreVariables=true] - Whether or not to lint variables.
 * @param {boolean} [actual.ignoreFunctions=true] - Whether or not to lint functions.
 * @param {string} [actual.severity='error'] - What the severity level is for this rule.
 * @param {number|string|Array|Object} [actual.ignoreKeywords=null] - A keywords config.
 * @param {string} [actual.message=null] - A custom message to be delivered upon error interpolated with `${types}`, `${value}` and `${property}`.
 *
 * @returns {boolean}
 */
function validOptions(actual) {
  if (typeof actual !== 'object') return false

  const allowedKeys = Object.keys(defaults)
  if (!Object.keys(actual).every(key => allowedKeys.indexOf(key) > -1)) return false

  if ('ignoreVariables' in actual
    && typeof actual.ignoreVariables !== 'boolean'
    && actual.ignoreVariables !== null) return false

  if ('ignoreFunctions' in actual
    && typeof actual.ignoreFunctions !== 'boolean'
    && actual.ignoreFunctions !== null) return false

  if ('severity' in actual
    && typeof actual.severity !== 'string'
    && actual.severity !== null) return false

  if ('ignoreKeywords' in actual
    && !validProperties(actual.ignoreKeywords)
    && !validHash(actual.ignoreKeywords)) return false

  if ('message' in actual
    && typeof actual.message !== 'string'
    && actual.message !== null) return false

  if ('disableFix' in actual
    && typeof actual.disableFix !== 'boolean'
    && actual.disableFix !== null) return false

  if ('autoFixFunc' in actual
    && typeof actual.autoFixFunc !== 'function'
    && typeof actual.autoFixFunc !== 'string'
    && actual.autoFixFunc !== null) return false

  return true
}

/**
 * Validate optional hash keyword config.
 *
 * @param {Object} actual - A keyword config.
 *
 * @returns {boolean}
 */
function validHash(actual) {
  if (typeof actual !== 'object') return false

  return Object.keys(actual).every(key => validProperties(actual[key]))
}

/**
 * Build expected message for stylelint report.
 *
 * @param {Array} types - Either `variable`, `function` and/or `keyword`.
 * @param {string} value - The CSS declaration's value.
 * @param {string} property - The CSS declaration's property.
 * @param {string} [customMessage] - A custom message to be delivered upon error interpolated with `${types}`, `${value}` and `${property}`.
 * @returns {string}
 */
function expected(types, value, property, customMessage) {
  if (Array.isArray(types)) {
    const typesLast = types.pop()

    // eslint-disable-next-line no-param-reassign
    types = types.length ? `${types.join(', ')} or ${typesLast}` : typesLast
  }

  if (typeof customMessage === 'string' && customMessage.length) {
    /* eslint-disable no-template-curly-in-string */
    return customMessage.replace('${types}', types)
      .replace('${value}', value)
      .replace('${property}', property)
    /* eslint-enable no-template-curly-in-string */
  }

  return `Expected ${types} for "${value}" of "${property}"`
}

/**
 * Get configured types for stylelint report message.
 *
 * @param {Object} config - The secondary stylelint-plugin config.
 * @param {string} property - The specific CSS declaration's property of the current iteration.
 * @returns {Array}
 */
function getTypes(config, property) {
  const { ignoreVariables, ignoreFunctions, ignoreKeywords } = config
  const types = []

  if (ignoreVariables) {
    types.push('variable')
  }

  if (ignoreFunctions) {
    types.push('function')
  }

  if (ignoreKeywords && getIgnoredKeywords(ignoreKeywords, property)) {
    types.push('keyword')
  }

  return types
}

/**
 * Get the correct ignored keywords for an specific CSS declaration's property
 * out of a complex ignoreKeywords config hash or array.
 *
 * @param {Object|Array|string} ignoreKeywords - The keyword/-s to ignore.
 * @param {string} property - The specific CSS declaration's property of the current iteration.
 * @returns {Array}
 */
function getIgnoredKeywords(ignoreKeywords, property) {
  if (!ignoreKeywords) return null

  let keywords = ignoreKeywords

  if ({}.hasOwnProperty.call(keywords, property)) {
    keywords = keywords[property]
  } else if ({}.hasOwnProperty.call(keywords, '')) {
    keywords = keywords['']
  }

  return Array.isArray(keywords) ? keywords : [keywords]
}

/**
 * Get the auto-fix function either by a function directly or from source file.
 *
 * @param {Function|string} autoFixFunc
 * @returns {Function|null}
 */
function getAutoFixFunc(autoFixFunc) {
  const type = typeof autoFixFunc

  if (type === 'function') {
    return autoFixFunc
  }

  if (type === 'string') {
    let resolveAutoFixfunc

    try {
      resolveAutoFixfunc = require.resolve(autoFixFunc)
    } catch (error) {
      resolveAutoFixfunc = require.resolve(path.join(process.cwd(), autoFixFunc))
    }

    // eslint-disable-next-line import/no-dynamic-require, global-require
    return require(resolveAutoFixfunc)
  }

  return null
}

export {
  validProperties,
  validOptions,
  expected,
  getTypes,
  getIgnoredKeywords,
  getAutoFixFunc,
}
<|endoftext|>


<commit_before><commit_msg>Delete solve_tsp.js<commit_after><|endoftext|>


<commit_before>/**
 * Dimension Widget
 */
Humble( function () {

    var C_DIMENSION = 'humble-dvc-dimension',
        T_TITLE     = '

',
        T_TOTAL     = '

',
        T_TAXES     = '

';

    var Dimension = function (node, model) {

        this.node = node;
        this.model = model;

        this.render();
    }

    Dimension.prototype = {

        render : function () {

            this.titleNode = $(T_TITLE);
            this.totalNode = $(T_TOTAL);
            this.taxesNode = $(T_TAXES);

            this.node.append(this.titleNode);
            this.node.append(this.totalNode);
            this.node.append(this.taxesNode);

            this.node.hide();

            this.bind();
        },

        bind : function () {

            var that = this;

            Humble.Event.bind('humble:dvc:dimensionHover', function (e, key, hover) {
                if (hover) {
                    that.node.show();
                    that.doHover(key);
                } else {
                    that.node.hide();
                }
            });
        },

        doHover : function (key) {

            var model = this.model,
                total = model.get(key, 'amounti'),
                taxes = model.get(key, 'mycosti'),
                dimensions = Humble.Config.DVZ.budget.dimensions;

            this.titleNode.html(dimensions[key].name);
            this.totalNode.html(total);
            this.taxesNode.html(taxes);
        }

    }

    Humble.Dimension = Dimension;
});

<commit_msg>Initial keep shown on mouse over - race condition in event handlers.  Needs a timeout?<commit_after>/**
 * Dimension Widget
 */
Humble( function () {

    var C_DIMENSION = 'humble-dvc-dimension',
        T_TITLE     = '

',
        T_TOTAL     = '

',
        T_TAXES     = '

';

    var Dimension = function (node, model) {

        this.node = node;
        this.model = model;

        this.render();
    }

    Dimension.prototype = {

        render : function () {

            this.titleNode = $(T_TITLE);
            this.totalNode = $(T_TOTAL);
            this.taxesNode = $(T_TAXES);

            this.node.append(this.titleNode);
            this.node.append(this.totalNode);
            this.node.append(this.taxesNode);

            this.node.hide();

            this.bind();
        },

        bind : function () {

            var that = this;

            // TODO some timeout for hover outs would be cool?
            this.node.hover(function () {
                Humble.Event.trigger('humble:dvc:dimensionHover', [that.key, true]);
            }, function () {
                Humble.Event.trigger('humble:dvc:dimensionHover', [that.key, false]);
            });

            Humble.Event.bind('humble:dvc:dimensionHover', function (e, key, hover) {
                if (hover) {
                    that.node.show();
                    that.doHover(key);
                } else {
                    that.node.hide();
                    that.key = null;
                }
            });
        },

        doHover : function (key) {

            var model = this.model,
                total = model.get(key, 'amounti'),
                taxes = model.get(key, 'mycosti'),
                dimensions = Humble.Config.DVZ.budget.dimensions;

            this.titleNode.html(dimensions[key].name);
            this.totalNode.html(total);
            this.taxesNode.html(taxes);

            this.key = key;
        }

    }

    Humble.Dimension = Dimension;
});

<|endoftext|>


<commit_before>(function() {
  var globals = {
    //log: function() { console.log.apply(console, arguments) },
    after: '_.after',
    all: '_.all',
    any: '_.any',
    bindAll: '_.bindAll',
    bind: '_.bind',
    clone: '_.clone',
    Collection: 'Backbone.Collection',
    compact: '_.compact',
    compose: '_.compose',
    debounce: '_.debounce',
    defaults: '_.defaults',
    defer: '_.defer',
    delay: '_.delay',
    difference: '_.difference',
    each: '_.each',
    'escape': '_.escape',
    Events: 'Backbone.Events',
    extend: '_.extend',
    filter: '_.filter',
    find: '_.find',
    first: '_.first',
    flatten: '_.flatten',
    functions: '_.functions',
    groupBy: '_.groupBy',
    has: '_.has',
    identity: '_.identity',
    include: '_.include',
    indexOf: '_.indexOf',
    initial: '_.initial',
    intersection: '_.intersection',
    invoke: '_.invoke',
    isArguments: '_.isArguments',
    isArray: '_.isArray',
    isBoolean: '_.isBoolean',
    isDate: '_.isDate',
    isElement: '_.isElement',
    isEmpty: '_.isEmpty',
    isEqual: '_.isEqual',
    isFunction: '_.isFunction',
    isNaN: '_.isNaN',
    isNull: '_.isNull',
    isNumber: '_.isNumber',
    isRegExp: '_.isRegExp',
    isString: '_.isString',
    isUndefined: '_.isUndefined',
    json: '$.getJSON',
    keys: '_.keys',
    lastIndexOf: '_.lastIndexOf',
    last: '_.last',
    map: '_.map',
    max: '_.max',
    memoize: '_.memoize',
    min: '_.min',
    Model: 'Backbone.Model',
    once: '_.once',
    pluck: '_.pluck',
    range: '_.range',
    reduce: '_.reduce',
    reduceRight: '_.reduceRight',
    reject: '_.reject',
    rest: '_.rest',
    Router: 'Backbone.Router',
    shuffle: '_.shuffle',
    size: '_.size',
    sortBy: '_.sortBy',
    sortedIndex: '_.sortedIndex',
    tap: '_.tap',
    template: '_.template',
    throttle: '_.throttle',
    times: '_.times',
    toArray: '_.toArray',
    union: '_.union',
    uniq: '_.uniq',
    values: '_.values',
    View: 'Backbone.View',
    without: '_.without',
    wrap: '_.wrap',
    zip: '_.zip',
  };

  // forgive me
  _(globals).each(function(v,k) {
    var func = eval(v);
    window[k] = function() { return func.apply(this, arguments); };
    window[k].toString = function() { return v; } ;
  });

  // log
  window['log'] = function() { console.log.apply(console, arguments); };
  window['log'].toString = function() { return "console.log"; };

  var commands = new Commands();
  commands.fetch();
  var curr = commands.size();  // current command
  var error_state = false;

  var puts_node = document.getElementById('puts');

  window.editor = CodeMirror.fromTextArea(document.getElementById("input"), {
    mode: 'coffeescript',
    theme: 'idle',
    onChange: test_compile,
    extraKeys: {
      "Shift-Enter": CodeMirror.commands.newlineAndIndent,
      "Enter": go,
      "Up": up,
      "Down": down,
      "Tab": autocomplete,
      "Shift-Right": CodeMirror.commands.indentMore,
      "Shift-Left": CodeMirror.commands.indentLess
    }
  });

  editor.focus();

  // highlight examples
  $('.highlight').each(function() {
    var code = $(this).text();
    highlight_coffee(this, code);
  });

  function autocomplete(cm) {
    CodeMirror.simpleHint(cm, CodeMirror.coffeescriptHint);
  }

  function test_compile(cm) {
    try {
      error_state = false;
      CoffeeScript.compile(editor.getValue());
      $('#coffee-error').hide();
    } catch (err) {
      error_state = true;
      $('#coffee-error').removeClass('tried');
      $('#coffee-error #compile-error').text(err.message);
      $('#coffee-error').show();
    }
  }

  function up(cm) {
    if (curr > 0 && topline()) {
      curr -= 1;
      var command = commands.at(curr);
      editor.setValue(command.get('contents'));
    } else {
      CodeMirror.commands.goLineUp(cm);
    }
  };

  function down(cm) {
    if (curr < commands.size() && botline()) {
      curr += 1;
      if (curr != commands.size()) {
        var command = commands.at(curr);
        editor.setValue(command.get('contents'));
      } else {
        editor.setValue("");
      }
    } else {
      CodeMirror.commands.goLineDown(cm);
    }
  };

  function topline() {
    return coords().line == 0;
  };

  function botline() {
    var lines = editor.lineCount();
    return coords().line == lines - 1;
  };

  function coords() {
    var cursor = editor.cursorCoords();
    return editor.coordsChar(cursor);
  };

  function go() {
    if (error_state) {
      $('#coffee-error').addClass('tried');
      return;
    }

    var code = editor.getValue();
    editor.setValue("");

    var command = commands.create({
      contents: code
    });

    var command_view = new CommandView({
      model: command
    });

    command_view.render();

    jscode = command.compile();

    if (jscode.type == "success") {
      try {
        var result = eval.call(null, jscode.result);
        try {
          puts(result);
        } catch (error) {
          puts_error("Result: " + result);
          puts_error("Puts error: " + error.message);
        }
      } catch (error) {
        puts_error("Result: " + result);
        puts_error("Javascript error: " + error.message);
      }
    } else if (jscode.type == "error") {
      puts_error("CoffeeScript error: " + jscode.result.message);
    }

    curr = commands.size();
  };

  function puts_print(txt, className) {
    var txt_node = document.createElement('pre');
    txt_node.className = className;
    puts_node.appendChild(txt_node);

    if (className == 'input' || className == 'puts') {
      highlight_js(txt_node, txt);
    } else if (className == 'beans-puts-coffee') {
      highlight_coffee(txt_node, txt);
    } else {
      $(txt_node).text(txt);
    }

    toBottom();
  };

  function toBottom() {
    // scroll to bottom
    $('#puts').animate({scrollTop: $('#puts')[0].scrollHeight}, 0);
  };

  window.puts = function(result) {

    switch (type(result)) {
      case "array":
        try {
          result = JSON.stringify(result);
        } catch (error) {
          result = result.toString();
        }
        break;
      case "function":
        result = js2coffee(result);
        puts_print(result, "beans-puts-coffee");
        return;
      case "object":
        try {
          result = JSON.stringify(result);
        } catch (err) {
          puts_error("Print error: " + err.message);
          return;
        }
        break;
      case "number":
        result = result.toString();
        break;
      case "boolean":
        result = result.toString();
        break;
      case "string":
        result = result;
        break;
      case "undefined":
        result = "undefined";
        return;                  // do nothing
      case "null":
        result = "null";
        break;
      case "NaN":
        result = "NaN";
        break;
      case "date":
        result = result.toString();
        break;
      case "RegExp":
        result = result.toString();
        break;
      case "element":
        $(puts_node).append(result);
        setTimeout(function() { toBottom(); }, 40);
        return;
        break;
      default:
        result = result.toString();
    }

    //var coffee_result = Js2coffee.build(result + "");
    puts_print(result, "puts");
  };

  function puts_error(result) {
    puts_print(result, "error");
  };

  function highlight_coffee(node, code) {
    $(node).addClass('cm-s-idle');
    CodeMirror.runMode(code, "coffeescript", node);
  };

  function highlight_js(node, code) {
    $(node).addClass('cm-s-idle');
    CodeMirror.runMode(code, "javascript", node);
  };

})();

/* global functions */

function type(object) {
  if (_.isFunction(object)) return "function";
  if (_.isArray(object)) return "array";
  if (_.isElement(object)) return "element";
  if (_.isNull(object)) return "null";
  if (_.isNaN(object)) return "NaN";
  if (_.isDate(object)) return "date";
  if (_.isArguments(object)) return "arguments";
  if (_.isUndefined(object)) return "undefined";
  if (_.isRegExp(object)) {
    return "RegExp";
  } else {
    return typeof object;
  }
};

function html(str) {
  return $(str)[0];
};

function pretty(obj) {
  return JSON.stringify(obj, undefined, 2);
};

function repeat(func, interval) {
  func();
  setTimeout(function() {
    repeat(func, interval);
  }, interval);
};

function js2coffee(obj) {
  if ('function' == type(obj)) {
    var str = "var $_$_$ = " + obj.toString();
    var compiled = Js2coffee.build(str);
    return compiled.slice(8)
  }
};

function coffee2js(str) {
  return CoffeeScript.compile(str).slice(16,-17);
};
<commit_msg>moved globals into closure<commit_after>(function() {
  var commands = new Commands();
  commands.fetch();
  var curr = commands.size();  // current command
  var error_state = false;

  var puts_node = document.getElementById('puts');

  window.editor = CodeMirror.fromTextArea(document.getElementById("input"), {
    mode: 'coffeescript',
    theme: 'idle',
    onChange: test_compile,
    extraKeys: {
      "Shift-Enter": CodeMirror.commands.newlineAndIndent,
      "Enter": go,
      "Up": up,
      "Down": down,
      "Tab": autocomplete,
      "Shift-Right": CodeMirror.commands.indentMore,
      "Shift-Left": CodeMirror.commands.indentLess
    }
  });

  editor.focus();

  // highlight examples
  $('.highlight').each(function() {
    var code = $(this).text();
    highlight_coffee(this, code);
  });

  function autocomplete(cm) {
    CodeMirror.simpleHint(cm, CodeMirror.coffeescriptHint);
  }

  function test_compile(cm) {
    try {
      error_state = false;
      CoffeeScript.compile(editor.getValue());
      $('#coffee-error').hide();
    } catch (err) {
      error_state = true;
      $('#coffee-error').removeClass('tried');
      $('#coffee-error #compile-error').text(err.message);
      $('#coffee-error').show();
    }
  }

  function up(cm) {
    if (curr > 0 && topline()) {
      curr -= 1;
      var command = commands.at(curr);
      editor.setValue(command.get('contents'));
    } else {
      CodeMirror.commands.goLineUp(cm);
    }
  };

  function down(cm) {
    if (curr < commands.size() && botline()) {
      curr += 1;
      if (curr != commands.size()) {
        var command = commands.at(curr);
        editor.setValue(command.get('contents'));
      } else {
        editor.setValue("");
      }
    } else {
      CodeMirror.commands.goLineDown(cm);
    }
  };

  function topline() {
    return coords().line == 0;
  };

  function botline() {
    var lines = editor.lineCount();
    return coords().line == lines - 1;
  };

  function coords() {
    var cursor = editor.cursorCoords();
    return editor.coordsChar(cursor);
  };

  function go() {
    if (error_state) {
      $('#coffee-error').addClass('tried');
      return;
    }

    var code = editor.getValue();
    editor.setValue("");

    var command = commands.create({
      contents: code
    });

    var command_view = new CommandView({
      model: command
    });

    command_view.render();

    jscode = command.compile();

    if (jscode.type == "success") {
      try {
        var result = eval.call(null, jscode.result);
        try {
          puts(result);
        } catch (error) {
          puts_error("Result: " + result);
          puts_error("Puts error: " + error.message);
        }
      } catch (error) {
        puts_error("Result: " + result);
        puts_error("Javascript error: " + error.message);
      }
    } else if (jscode.type == "error") {
      puts_error("CoffeeScript error: " + jscode.result.message);
    }

    curr = commands.size();
  };

  function puts_print(txt, className) {
    var txt_node = document.createElement('pre');
    txt_node.className = className;
    puts_node.appendChild(txt_node);

    if (className == 'input' || className == 'puts') {
      highlight_js(txt_node, txt);
    } else if (className == 'beans-puts-coffee') {
      highlight_coffee(txt_node, txt);
    } else {
      $(txt_node).text(txt);
    }

    toBottom();
  };

  function toBottom() {
    // scroll to bottom
    $('#puts').animate({scrollTop: $('#puts')[0].scrollHeight}, 0);
  };

  window.puts = function(result) {

    switch (type(result)) {
      case "array":
        try {
          result = JSON.stringify(result);
        } catch (error) {
          result = result.toString();
        }
        break;
      case "function":
        result = js2coffee(result);
        puts_print(result, "beans-puts-coffee");
        return;
      case "object":
        try {
          result = JSON.stringify(result);
        } catch (err) {
          puts_error("Print error: " + err.message);
          return;
        }
        break;
      case "number":
        result = result.toString();
        break;
      case "boolean":
        result = result.toString();
        break;
      case "string":
        result = result;
        break;
      case "undefined":
        result = "undefined";
        return;                  // do nothing
      case "null":
        result = "null";
        break;
      case "NaN":
        result = "NaN";
        break;
      case "date":
        result = result.toString();
        break;
      case "RegExp":
        result = result.toString();
        break;
      case "element":
        $(puts_node).append(result);
        setTimeout(function() { toBottom(); }, 40);
        return;
        break;
      default:
        result = result.toString();
    }

    //var coffee_result = Js2coffee.build(result + "");
    puts_print(result, "puts");
  };

  function puts_error(result) {
    puts_print(result, "error");
  };

  function highlight_coffee(node, code) {
    $(node).addClass('cm-s-idle');
    CodeMirror.runMode(code, "coffeescript", node);
  };

  function highlight_js(node, code) {
    $(node).addClass('cm-s-idle');
    CodeMirror.runMode(code, "javascript", node);
  };

  var globals = {
    //log: function() { console.log.apply(console, arguments) },
    after: '_.after',
    all: '_.all',
    any: '_.any',
    bindAll: '_.bindAll',
    bind: '_.bind',
    clone: '_.clone',
    coffee2js: coffee2js,
    Collection: 'Backbone.Collection',
    compact: '_.compact',
    compose: '_.compose',
    debounce: '_.debounce',
    defaults: '_.defaults',
    defer: '_.defer',
    delay: '_.delay',
    difference: '_.difference',
    each: '_.each',
    'escape': '_.escape',
    Events: 'Backbone.Events',
    extend: '_.extend',
    filter: '_.filter',
    find: '_.find',
    first: '_.first',
    flatten: '_.flatten',
    functions: '_.functions',
    groupBy: '_.groupBy',
    has: '_.has',
    html: html,
    identity: '_.identity',
    include: '_.include',
    indexOf: '_.indexOf',
    initial: '_.initial',
    intersection: '_.intersection',
    invoke: '_.invoke',
    isArguments: '_.isArguments',
    isArray: '_.isArray',
    isBoolean: '_.isBoolean',
    isDate: '_.isDate',
    isElement: '_.isElement',
    isEmpty: '_.isEmpty',
    isEqual: '_.isEqual',
    isFunction: '_.isFunction',
    isNaN: '_.isNaN',
    isNull: '_.isNull',
    isNumber: '_.isNumber',
    isRegExp: '_.isRegExp',
    isString: '_.isString',
    isUndefined: '_.isUndefined',
    js2coffee: js2coffee,
    json: '$.getJSON',
    keys: '_.keys',
    lastIndexOf: '_.lastIndexOf',
    last: '_.last',
    map: '_.map',
    max: '_.max',
    memoize: '_.memoize',
    min: '_.min',
    Model: 'Backbone.Model',
    once: '_.once',
    pluck: '_.pluck',
    pretty: pretty,
    range: '_.range',
    reduce: '_.reduce',
    reduceRight: '_.reduceRight',
    reject: '_.reject',
    repeat: repeat,
    rest: '_.rest',
    Router: 'Backbone.Router',
    shuffle: '_.shuffle',
    size: '_.size',
    sortBy: '_.sortBy',
    sortedIndex: '_.sortedIndex',
    tap: '_.tap',
    template: '_.template',
    throttle: '_.throttle',
    times: '_.times',
    toArray: '_.toArray',
    type: type,
    union: '_.union',
    uniq: '_.uniq',
    values: '_.values',
    View: 'Backbone.View',
    without: '_.without',
    wrap: '_.wrap',
    zip: '_.zip'
  };

  /* global functions */

  function type(object) {
    if (_.isFunction(object)) return "function";
    if (_.isArray(object)) return "array";
    if (_.isElement(object)) return "element";
    if (_.isNull(object)) return "null";
    if (_.isNaN(object)) return "NaN";
    if (_.isDate(object)) return "date";
    if (_.isArguments(object)) return "arguments";
    if (_.isUndefined(object)) return "undefined";
    if (_.isRegExp(object)) {
      return "RegExp";
    } else {
      return typeof object;
    }
  };

  function html(str) {
    return $(str)[0];
  };

  function pretty(obj) {
    return JSON.stringify(obj, undefined, 2);
  };

  function repeat(func, interval) {
    func();
    setTimeout(function() {
      repeat(func, interval);
    }, interval);
  };

  function js2coffee(obj) {
    if ('function' == type(obj)) {
      var str = "var $_$_$ = " + obj.toString();
      var compiled = Js2coffee.build(str);
      return compiled.slice(8)
    }
  };

  function coffee2js(str) {
    return CoffeeScript.compile(str).slice(16,-17);
  };

  // forgive me
  _(globals).each(function(v,k) {
    if (_.isString(v)) {
      var func = eval(v);
      window[k] = function() { return func.apply(this, arguments); };
      window[k].toString = function() { return v; } ;
      return;
    }
    if (_.isFunction(v)) {
      window[k] = v;
    }
  });

  // log
  window['log'] = function() { console.log.apply(console, arguments); };
  window['log'].toString = function() { return "console.log"; };

})();

<|endoftext|>


<commit_before>/*!
 * FM4cast - FM4 chromecast receiver/sender
 * http://sehaas.github.io/fm4cast
 *
 * Copyright 2013,2014 Sebastian Haas (sehaas@deebas.com)
 * Released under the MIT license
 *
 */

;( function( $ ) {

	CastSource = function(opts) {
		var defaultOpt = {
			title:null,
			url:null,
			logo:null,
			parent:null,
			children:[],
			text:null,
			date:null,
		};
		$.extend(defaultOpt, opts);
		this.title = defaultOpt.title;
		this.url = defaultOpt.url;
		this.logo = defaultOpt.logo;
		this.parent = defaultOpt.parent;
		this.children = defaultOpt.children;
		this.text = defaultOpt.text;
		this.date = defaultOpt.date;
	},

	CastSource.prototype = {
		getLogo : function() {
			if (this.logo) {
				return this.logo;
			}
			if (this.parent) {
				return this.parent.getLogo();
			}
			return null;
		},

		getTitle : function() {
			if (this.title) {
				return this.title;
			}
			if (this.parent) {
				return this.parent.getTitle();
			}
			return null;
		},

		addChild : function(child) {
			if (!child) {
				return;
			}
			child.parent = this;
			this.children.push(child);
		}
	},

	$.FM4Sender = function() {
		this.content = new CastSource({
			title : "Radio FM4",
			logo : "http://fm4.orf.at/v2static/images/fm4_logo.jpg",
			text : "fm4.ORF.at: Berichte und Kommentare zu Musik, Popkultur, Film, Literatur, Games und Politik.",
			url : "http://mp3stream1.apasf.apa.at:8000/;",
		});
		this.podcast = null;
		this.ondemand = null;
	};

	$.FM4Sender.prototype = {

		getOnDemandShows : [
			'4HOPWed',
			'4ULMon',
			'4ULTue',
			'4ULWed',
			'4ULThu',
			'4ULFri',
			'4SSUSun',
			'4CHSat',
			'4ZSSun',
			'4JZFri',
			'4DDSat',
			'4ISSun',
			'4HEMon',
			'4HSTue',
			'4TVThe',
			'4SHFri',
			'4GLSun',
			'4PHTue',
			'4CZWed',
			'4BTThu',
			'4PXFri',
			'4LBFri',
			'4SSSat',
			'4LRMon',
			'4DKMSun',
			'4SOPMon',
			// '4UTAMon' ,
			// '4UTATue' ,
			// '4UTAWed' ,
			// '4UTAThu' ,
			// '4UTAFris' ,
			// '4DZWed' ,
		],

		getPodcasts : [
			"http://static.orf.at/podcast/fm4/fm4_interview_podcast.xml",
			"http://static.orf.at/podcast/fm4/FM4_Webtip.xml",
			"http://static.orf.at/podcast/fm4/fm4_reality_check_podcast.xml",
			"http://static.orf.at/podcast/fm4/fm4_musikerziehung.xml",
			"http://static.orf.at/podcast/fm4/fm4_ombudsmann.xml",
			"http://static.orf.at/podcast/fm4/fm4_science_busters.xml",
			"http://static.orf.at/podcast/fm4/FM4_Mit_Akzent.xml",
			"http://static.orf.at/podcast/fm4/FM4_Johanna_gefaellt_das_nicht.xml",
			"http://static.orf.at/podcast/fm4/fm4_projekt_x.xml",
			"http://static.orf.at/podcast/fm4/fm4_chez_hermes_extrawurscht.xml",
			//"http://static.orf.at/fm4/podcast/soundpark.xml",
			//"http://static.orf.at/fm4/podcast/fm4_comedy.xml",
		],

		getPodcastInfo : function(podcast, clear) {
			var that = this;
			if (this.podcast == null || clear) {
				this.podcast = new CastSource({
					title: "Podcasts"
				});
				this.content.addChild(this.podcast);
			}
			var pods = podcast;
			if (!(pods instanceof Array)) {
				pods = [pods];
			}
			this.pcToFetch = pods.length;
			$.each(pods, function(idx, val) {
				var url = "//ajax.googleapis.com/ajax/services/feed/load?v=1.0&output=xml&q=" + val;
				$.ajax({
					url : url,
					dataType : 'jsonp',
					cache : false,
					success : $.proxy(that._onPodcastInfo, that),
					error : function() { that.pcToFetch--; },
				});
			});
		},

		_onPodcastInfo : function(response) {
			var feed = $(response.responseData.xmlString);
			var pod = new CastSource({
				title : $("channel>title", feed).text(),
				text : $("channel>description", feed).text(),
			});
			$.each($("channel>item", feed), function(idx, val) {
				var itm = new CastSource({
					title : $("title", val).text(),
					url : $("enclosure", val).attr("url"),
					text :  $("description", val).text(),
					date : $("pubdate", val).text(),
				});
				pod.addChild(itm);
			});
			this.podcast.addChild(pod);
			this.pcToFetch--;
			if (this.pcToFetch <= 0) {
				$(this).trigger("sender-new-content", this.content);
			}
		},

		getOnDemandInfo : function( key, clear ) {
			var that = this;
			if (this.ondemand == null || clear) {
				this.ondemand = new CastSource({
					title: "On Demand",
				});
				this.content.addChild(this.ondemand);
			}
			var showurl = '//audioapi.orf.at/fm4/json/2.0/playlist/' + key;
			$.ajax({
				url : showurl,
				dataType : 'jsonp',
				cache : false,
				success : $.proxy(that._onDemandInfo, that)
			});
		},

		_onDemandInfo : function( response ) {
			var that = this;
			var url = "http://loopstream01.apa.at/?channel=fm4&ua=flash&id=";
			var data = response.data;
			if (!(data instanceof Array)) {
				data = [data];
			}
			$.each(data, function(idx, val) {
				// TODO: add more than stream0
				var description = "";
				if (val.subtitle) {
					description += val.subtitle + '\n';
				}

				if (val.description) {
					description += val.description;
				}
				var sendung = new CastSource({
					title : val.title,
					text : description,
					url : url + val.streams[0].loopStreamId,
					date : val.streams[0].startISO,
				});
				that.ondemand.addChild(sendung);
			});
			$(this).trigger("sender-new-content", this.content);
		},

	};

}(jQuery));

// helper function
if (!String.prototype.format) {
	String.prototype.format = String.prototype.f = function() {
		var s = this,
		i = arguments.length;

		while (i--) {
			s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i]);
		}
		return s;
	};
}<commit_msg>make the CastSource contructor less complex<commit_after>/*!
 * FM4cast - FM4 chromecast receiver/sender
 * http://sehaas.github.io/fm4cast
 *
 * Copyright 2013,2014 Sebastian Haas (sehaas@deebas.com)
 * Released under the MIT license
 *
 */

;( function( $ ) {

	CastSource = function(opts) {
		this.title = null;
		this.url = null;
		this.logo = null;
		this.parent = null;
		this.children = [];
		this.text = null;
		this.date = null;

		$.extend(this, opts);
	},

	CastSource.prototype = {
		getLogo : function() {
			if (this.logo) {
				return this.logo;
			}
			if (this.parent) {
				return this.parent.getLogo();
			}
			return null;
		},

		getTitle : function() {
			if (this.title) {
				return this.title;
			}
			if (this.parent) {
				return this.parent.getTitle();
			}
			return null;
		},

		addChild : function(child) {
			if (!child) {
				return;
			}
			child.parent = this;
			this.children.push(child);
		}
	},

	$.FM4Sender = function() {
		this.content = new CastSource({
			title : "Radio FM4",
			logo : "http://fm4.orf.at/v2static/images/fm4_logo.jpg",
			text : "fm4.ORF.at: Berichte und Kommentare zu Musik, Popkultur, Film, Literatur, Games und Politik.",
			url : "http://mp3stream1.apasf.apa.at:8000/;",
		});
		this.podcast = null;
		this.ondemand = null;
	};

	$.FM4Sender.prototype = {

		getOnDemandShows : [
			'4HOPWed',
			'4ULMon',
			'4ULTue',
			'4ULWed',
			'4ULThu',
			'4ULFri',
			'4SSUSun',
			'4CHSat',
			'4ZSSun',
			'4JZFri',
			'4DDSat',
			'4ISSun',
			'4HEMon',
			'4HSTue',
			'4TVThe',
			'4SHFri',
			'4GLSun',
			'4PHTue',
			'4CZWed',
			'4BTThu',
			'4PXFri',
			'4LBFri',
			'4SSSat',
			'4LRMon',
			'4DKMSun',
			'4SOPMon',
			// '4UTAMon' ,
			// '4UTATue' ,
			// '4UTAWed' ,
			// '4UTAThu' ,
			// '4UTAFris' ,
			// '4DZWed' ,
		],

		getPodcasts : [
			"http://static.orf.at/podcast/fm4/fm4_interview_podcast.xml",
			"http://static.orf.at/podcast/fm4/FM4_Webtip.xml",
			"http://static.orf.at/podcast/fm4/fm4_reality_check_podcast.xml",
			"http://static.orf.at/podcast/fm4/fm4_musikerziehung.xml",
			"http://static.orf.at/podcast/fm4/fm4_ombudsmann.xml",
			"http://static.orf.at/podcast/fm4/fm4_science_busters.xml",
			"http://static.orf.at/podcast/fm4/FM4_Mit_Akzent.xml",
			"http://static.orf.at/podcast/fm4/FM4_Johanna_gefaellt_das_nicht.xml",
			"http://static.orf.at/podcast/fm4/fm4_projekt_x.xml",
			"http://static.orf.at/podcast/fm4/fm4_chez_hermes_extrawurscht.xml",
			//"http://static.orf.at/fm4/podcast/soundpark.xml",
			//"http://static.orf.at/fm4/podcast/fm4_comedy.xml",
		],

		getPodcastInfo : function(podcast, clear) {
			var that = this;
			if (this.podcast == null || clear) {
				this.podcast = new CastSource({
					title: "Podcasts"
				});
				this.content.addChild(this.podcast);
			}
			var pods = podcast;
			if (!(pods instanceof Array)) {
				pods = [pods];
			}
			this.pcToFetch = pods.length;
			$.each(pods, function(idx, val) {
				var url = "//ajax.googleapis.com/ajax/services/feed/load?v=1.0&output=xml&q=" + val;
				$.ajax({
					url : url,
					dataType : 'jsonp',
					cache : false,
					success : $.proxy(that._onPodcastInfo, that),
					error : function() { that.pcToFetch--; },
				});
			});
		},

		_onPodcastInfo : function(response) {
			var feed = $(response.responseData.xmlString);
			var pod = new CastSource({
				title : $("channel>title", feed).text(),
				text : $("channel>description", feed).text(),
			});
			$.each($("channel>item", feed), function(idx, val) {
				var itm = new CastSource({
					title : $("title", val).text(),
					url : $("enclosure", val).attr("url"),
					text :  $("description", val).text(),
					date : $("pubdate", val).text(),
				});
				pod.addChild(itm);
			});
			this.podcast.addChild(pod);
			this.pcToFetch--;
			if (this.pcToFetch <= 0) {
				$(this).trigger("sender-new-content", this.content);
			}
		},

		getOnDemandInfo : function( key, clear ) {
			var that = this;
			if (this.ondemand == null || clear) {
				this.ondemand = new CastSource({
					title: "On Demand",
				});
				this.content.addChild(this.ondemand);
			}
			var showurl = '//audioapi.orf.at/fm4/json/2.0/playlist/' + key;
			$.ajax({
				url : showurl,
				dataType : 'jsonp',
				cache : false,
				success : $.proxy(that._onDemandInfo, that)
			});
		},

		_onDemandInfo : function( response ) {
			var that = this;
			var url = "http://loopstream01.apa.at/?channel=fm4&ua=flash&id=";
			var data = response.data;
			if (!(data instanceof Array)) {
				data = [data];
			}
			$.each(data, function(idx, val) {
				// TODO: add more than stream0
				var description = "";
				if (val.subtitle) {
					description += val.subtitle + '\n';
				}

				if (val.description) {
					description += val.description;
				}
				var sendung = new CastSource({
					title : val.title,
					text : description,
					url : url + val.streams[0].loopStreamId,
					date : val.streams[0].startISO,
				});
				that.ondemand.addChild(sendung);
			});
			$(this).trigger("sender-new-content", this.content);
		},

	};

}(jQuery));

// helper function
if (!String.prototype.format) {
	String.prototype.format = String.prototype.f = function() {
		var s = this,
		i = arguments.length;

		while (i--) {
			s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i]);
		}
		return s;
	};
}<|endoftext|>


<commit_before>// Generated on <%= (new Date).toISOString().split('T')[0] %> using <%= pkg.name %> <%= pkg.version %>
'use strict';

var lrSnippet = require('grunt-contrib-livereload/lib/utils').livereloadSnippet;
var mountFolder = function (connect, dir) {
  return connect.static(require('path').resolve(dir));
};

// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// use this if you want to match all subfolders:
// 'test/spec/**/*.js'

module.exports = function (grunt) {
  // load all grunt tasks
  require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);

  // configurable paths
  var yeomanConfig = {
    app: 'app',
    dist: 'dist'
  };

  grunt.initConfig({
    yeoman: yeomanConfig,
    watch: {
      coffee: {
        files: ['<%%= yeoman.app %>/scripts/{,*/}*.coffee'],
        tasks: ['coffee']
      },
      recess: {
        files: ['<%%= yeoman.app %>/styles/{,*/}*.less'],
        tasks: ['recess']
      },
      livereload: {
        files: [
          '<%%= yeoman.app %>/*.html',
          '{.tmp,<%%= yeoman.app %>}/styles/{,*/}*.css',
          '{.tmp,<%%= yeoman.app %>}/scripts/{,*/}*.js',
          '<%%= yeoman.app %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'
        ],
        tasks: ['livereload']
      }
    },
    connect: {
      options: {
        port: 9000,
        // change this to '0.0.0.0' to access the server from outside
        hostname: 'localhost'
      },
      livereload: {
        options: {
          middleware: function (connect) {
            return [
              lrSnippet,
              mountFolder(connect, '.tmp'),
              mountFolder(connect, 'app')
            ];
          }
        }
      },
      test: {
        options: {
          middleware: function (connect) {
            return [
              mountFolder(connect, '.tmp'),
              mountFolder(connect, 'test')
            ];
          }
        }
      },
      dist: {
        options: {
          middleware: function (connect) {
            return [
              mountFolder(connect, 'dist')
            ];
          }
        }
      }
    },
    open: {
      server: {
        path: 'http://localhost:<%%= connect.options.port %>'
      }
    },
    clean: {
      dist: {
        files: [{
          dot: true,
          src: [
            '.tmp',
            '<%%= yeoman.dist %>/*',
            '!<%%= yeoman.dist %>/.git*'
          ]
        }]
      },
      server: '.tmp'
    },
    jshint: {
      options: {
        jshintrc: '.jshintrc'
      },
      all: [
        'Gruntfile.js',
        '<%%= yeoman.app %>/scripts/{,*/}*.js',
        '!<%%= yeoman.app %>/scripts/vendor/*',
        'test/spec/{,*/}*.js'
      ]
    },<% if (testFramework === 'mocha') { %>
    mocha: {
      all: {
        options: {
          run: true,
          urls: ['http://localhost:<%%= connect.options.port %>/index.html']
        }
      }
    },<% } else if (testFramework === 'jasmine') { %>
    jasmine: {
      all: {
        /*src: '',*/
        options: {
          specs: 'test/spec/{,*/}*.js'
        }
      }
    },<% } %>
    coffee: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%%= yeoman.app %>/scripts',
          src: '{,*/}*.coffee',
          dest: '<%%= yeoman.app %>/scripts',
          ext: '.js'
        }]
      }
    },
    recess: {
      dist: {
        options: {
          compile: true
        },
        files: {
          '<%%= yeoman.app %>/styles/main.css': ['<%%= yeoman.app %>/styles/main.less']
        }
      }
    },
    // not used since Uglify task does concat,
    // but still available if needed
    /*concat: {
      dist: {}
    },*/
    // not enabled since usemin task does concat and uglify
    // check index.html to edit your build targets
    // enable this task if you prefer defining your build targets here
    /*uglify: {
      dist: {}
    },*/
    rev: {
      dist: {
        files: {
          src: [
            '<%%= yeoman.dist %>/scripts/{,*/}*.js',
            '<%%= yeoman.dist %>/styles/{,*/}*.css',
            '<%%= yeoman.dist %>/images/{,*/}*.{png,jpg,jpeg,gif,webp}',
            '<%%= yeoman.dist %>/fonts/*'
          ]
        }
      }
    },
    useminPrepare: {
      html: '<%%= yeoman.app %>/index.html',
      options: {
        dest: '<%%= yeoman.dist %>'
      }
    },
    usemin: {
      html: ['<%%= yeoman.dist %>/{,*/}*.html'],
      css: ['<%%= yeoman.dist %>/styles/{,*/}*.css'],
      options: {
        dirs: ['<%%= yeoman.dist %>']
      }
    },
    imagemin: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%%= yeoman.app %>/images',
          src: '{,*/}*.{png,jpg,jpeg}',
          dest: '<%%= yeoman.dist %>/images'
        }]
      }
    },
    svgmin: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%%= yeoman.app %>/images',
          src: '{,*/}*.svg',
          dest: '<%%= yeoman.dist %>/images'
        }]
      }
    },
    cssmin: {
      dist: {
        files: {
          '<%%= yeoman.dist %>/styles/main.css': [
            '.tmp/styles/{,*/}*.css',
            '<%%= yeoman.app %>/styles/{,*/}*.css'
          ]
        }
      }
    },
    htmlmin: {
      dist: {
        options: {
          /*removeCommentsFromCDATA: true,
          // https://github.com/yeoman/grunt-usemin/issues/44
          //collapseWhitespace: true,
          collapseBooleanAttributes: true,
          removeAttributeQuotes: true,
          removeRedundantAttributes: true,
          useShortDoctype: true,
          removeEmptyAttributes: true,
          removeOptionalTags: true*/
        },
        files: [{
          expand: true,
          cwd: '<%%= yeoman.app %>',
          src: '*.html',
          dest: '<%%= yeoman.dist %>'
        }]
      }
    },
    copy: {
      dist: {
        files: [{
          expand: true,
          dot: true,
          cwd: '<%%= yeoman.app %>',
          dest: '<%%= yeoman.dist %>',
          src: [
            '*.{ico,txt}',<% if (fontawesome) { %>
            'fonts/*',<% } %>
            '.htaccess',
            'images/{,*/}*.{webp,gif}'
          ]
        }]
      },
      server: {
        files: [{
          expand: true,
          dot: true,<% if (fontawesome) { %>
          cwd: '<%%= yeoman.app %>/bower_components/font-awesome/font/',
          dest: '<%%= yeoman.app %>/fonts/',
          src: ['*']<% } else { %>
          cwd: '<%%= yeoman.app %>/bower_components/bootstrap/img/',
          dest: '<%%= yeoman.app %>/images/',
          src: ['*']<% } %>
        }]
      }
    },
    concurrent: {
      dist: [
        'coffee',
        'recess',
        'imagemin',
        'svgmin',
        'htmlmin'
      ]
    }
  });

  grunt.renameTask('regarde', 'watch');

  grunt.registerTask('server', function (target) {
    if (target === 'dist') {
      return grunt.task.run(['build', 'open', 'connect:dist:keepalive']);
    }

    grunt.task.run([
      'clean:server',
      'coffee',
      'recess',
      'copy:server',
      'livereload-start',
      'connect:livereload',
      'open',
      'watch'
    ]);
  });

  grunt.registerTask('test', [
    'clean:server',
    'coffee',
    'recess',
    'copy:server',
    'connect:test',<% if (testFramework === 'mocha') { %>
    'mocha'<% } else if (testFramework === 'jasmine') { %>
    'jasmine'<% } %>
  ]);

  grunt.registerTask('build', [
    'clean:dist',
    'copy:server',
    'useminPrepare',
    'concurrent',
    'cssmin',
    'concat',
    'uglify',
    'copy',
    'rev',
    'usemin'
  ]);

  grunt.registerTask('default', [
    'jshint',
    'test',
    'build'
  ]);
};
<commit_msg>Add touch icon pattern to copy:dist task<commit_after>// Generated on <%= (new Date).toISOString().split('T')[0] %> using <%= pkg.name %> <%= pkg.version %>
'use strict';

var lrSnippet = require('grunt-contrib-livereload/lib/utils').livereloadSnippet;
var mountFolder = function (connect, dir) {
  return connect.static(require('path').resolve(dir));
};

// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// use this if you want to match all subfolders:
// 'test/spec/**/*.js'

module.exports = function (grunt) {
  // load all grunt tasks
  require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);

  // configurable paths
  var yeomanConfig = {
    app: 'app',
    dist: 'dist'
  };

  grunt.initConfig({
    yeoman: yeomanConfig,
    watch: {
      coffee: {
        files: ['<%%= yeoman.app %>/scripts/{,*/}*.coffee'],
        tasks: ['coffee']
      },
      recess: {
        files: ['<%%= yeoman.app %>/styles/{,*/}*.less'],
        tasks: ['recess']
      },
      livereload: {
        files: [
          '<%%= yeoman.app %>/*.html',
          '{.tmp,<%%= yeoman.app %>}/styles/{,*/}*.css',
          '{.tmp,<%%= yeoman.app %>}/scripts/{,*/}*.js',
          '<%%= yeoman.app %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'
        ],
        tasks: ['livereload']
      }
    },
    connect: {
      options: {
        port: 9000,
        // change this to '0.0.0.0' to access the server from outside
        hostname: 'localhost'
      },
      livereload: {
        options: {
          middleware: function (connect) {
            return [
              lrSnippet,
              mountFolder(connect, '.tmp'),
              mountFolder(connect, 'app')
            ];
          }
        }
      },
      test: {
        options: {
          middleware: function (connect) {
            return [
              mountFolder(connect, '.tmp'),
              mountFolder(connect, 'test')
            ];
          }
        }
      },
      dist: {
        options: {
          middleware: function (connect) {
            return [
              mountFolder(connect, 'dist')
            ];
          }
        }
      }
    },
    open: {
      server: {
        path: 'http://localhost:<%%= connect.options.port %>'
      }
    },
    clean: {
      dist: {
        files: [{
          dot: true,
          src: [
            '.tmp',
            '<%%= yeoman.dist %>/*',
            '!<%%= yeoman.dist %>/.git*'
          ]
        }]
      },
      server: '.tmp'
    },
    jshint: {
      options: {
        jshintrc: '.jshintrc'
      },
      all: [
        'Gruntfile.js',
        '<%%= yeoman.app %>/scripts/{,*/}*.js',
        '!<%%= yeoman.app %>/scripts/vendor/*',
        'test/spec/{,*/}*.js'
      ]
    },<% if (testFramework === 'mocha') { %>
    mocha: {
      all: {
        options: {
          run: true,
          urls: ['http://localhost:<%%= connect.options.port %>/index.html']
        }
      }
    },<% } else if (testFramework === 'jasmine') { %>
    jasmine: {
      all: {
        /*src: '',*/
        options: {
          specs: 'test/spec/{,*/}*.js'
        }
      }
    },<% } %>
    coffee: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%%= yeoman.app %>/scripts',
          src: '{,*/}*.coffee',
          dest: '<%%= yeoman.app %>/scripts',
          ext: '.js'
        }]
      }
    },
    recess: {
      dist: {
        options: {
          compile: true
        },
        files: {
          '<%%= yeoman.app %>/styles/main.css': ['<%%= yeoman.app %>/styles/main.less']
        }
      }
    },
    // not used since Uglify task does concat,
    // but still available if needed
    /*concat: {
      dist: {}
    },*/
    // not enabled since usemin task does concat and uglify
    // check index.html to edit your build targets
    // enable this task if you prefer defining your build targets here
    /*uglify: {
      dist: {}
    },*/
    rev: {
      dist: {
        files: {
          src: [
            '<%%= yeoman.dist %>/scripts/{,*/}*.js',
            '<%%= yeoman.dist %>/styles/{,*/}*.css',
            '<%%= yeoman.dist %>/images/{,*/}*.{png,jpg,jpeg,gif,webp}',
            '<%%= yeoman.dist %>/fonts/*'
          ]
        }
      }
    },
    useminPrepare: {
      html: '<%%= yeoman.app %>/index.html',
      options: {
        dest: '<%%= yeoman.dist %>'
      }
    },
    usemin: {
      html: ['<%%= yeoman.dist %>/{,*/}*.html'],
      css: ['<%%= yeoman.dist %>/styles/{,*/}*.css'],
      options: {
        dirs: ['<%%= yeoman.dist %>']
      }
    },
    imagemin: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%%= yeoman.app %>/images',
          src: '{,*/}*.{png,jpg,jpeg}',
          dest: '<%%= yeoman.dist %>/images'
        }]
      }
    },
    svgmin: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%%= yeoman.app %>/images',
          src: '{,*/}*.svg',
          dest: '<%%= yeoman.dist %>/images'
        }]
      }
    },
    cssmin: {
      dist: {
        files: {
          '<%%= yeoman.dist %>/styles/main.css': [
            '.tmp/styles/{,*/}*.css',
            '<%%= yeoman.app %>/styles/{,*/}*.css'
          ]
        }
      }
    },
    htmlmin: {
      dist: {
        options: {
          /*removeCommentsFromCDATA: true,
          // https://github.com/yeoman/grunt-usemin/issues/44
          //collapseWhitespace: true,
          collapseBooleanAttributes: true,
          removeAttributeQuotes: true,
          removeRedundantAttributes: true,
          useShortDoctype: true,
          removeEmptyAttributes: true,
          removeOptionalTags: true*/
        },
        files: [{
          expand: true,
          cwd: '<%%= yeoman.app %>',
          src: '*.html',
          dest: '<%%= yeoman.dist %>'
        }]
      }
    },
    copy: {
      dist: {
        files: [{
          expand: true,
          dot: true,
          cwd: '<%%= yeoman.app %>',
          dest: '<%%= yeoman.dist %>',
          src: [
            '*.{ico,png,txt}',<% if (fontawesome) { %>
            'fonts/*',<% } %>
            '.htaccess',
            'images/{,*/}*.{webp,gif}'
          ]
        }]
      },
      server: {
        files: [{
          expand: true,
          dot: true,<% if (fontawesome) { %>
          cwd: '<%%= yeoman.app %>/bower_components/font-awesome/font/',
          dest: '<%%= yeoman.app %>/fonts/',
          src: ['*']<% } else { %>
          cwd: '<%%= yeoman.app %>/bower_components/bootstrap/img/',
          dest: '<%%= yeoman.app %>/images/',
          src: ['*']<% } %>
        }]
      }
    },
    concurrent: {
      dist: [
        'coffee',
        'recess',
        'imagemin',
        'svgmin',
        'htmlmin'
      ]
    }
  });

  grunt.renameTask('regarde', 'watch');

  grunt.registerTask('server', function (target) {
    if (target === 'dist') {
      return grunt.task.run(['build', 'open', 'connect:dist:keepalive']);
    }

    grunt.task.run([
      'clean:server',
      'coffee',
      'recess',
      'copy:server',
      'livereload-start',
      'connect:livereload',
      'open',
      'watch'
    ]);
  });

  grunt.registerTask('test', [
    'clean:server',
    'coffee',
    'recess',
    'copy:server',
    'connect:test',<% if (testFramework === 'mocha') { %>
    'mocha'<% } else if (testFramework === 'jasmine') { %>
    'jasmine'<% } %>
  ]);

  grunt.registerTask('build', [
    'clean:dist',
    'copy:server',
    'useminPrepare',
    'concurrent',
    'cssmin',
    'concat',
    'uglify',
    'copy',
    'rev',
    'usemin'
  ]);

  grunt.registerTask('default', [
    'jshint',
    'test',
    'build'
  ]);
};
<|endoftext|>