<commit_before>/**
 * The search view for the map module.
 *
 * @class A Backbone view to handle the search popup.
 * @author Joakim Lundin
 * @type {Backbone.View}
 */
var SearchView = Backbone.View.extend(
    /** @lends SearchView */
    {

      /**
       * @constructs
       * @param options Options for this class. Expects campus name and a searchResult collection to add results to
       */
      initialize: function (options) {
        _.bindAll(this, "render", "populateFilter");
        this.inputField = $("#search-autocomplete").parent().find("form input");

        // This is done to show a search icon or text in the mobile keyboard
        this.inputField.get(0).type = "search";

        $("#search-autocomplete").listview("option", "filterCallback", this.filterSearch);

        this.setInputPlaceholderText();
        this.mapView = options.mapView;
      },

      /** Registers events */
      events: {
        'focus input': 'showFilteredList',
        'keyup input': 'inputKeyup',
        'click #cancelFilter': 'hideFilteredList',
        'click .autocomplete-link': 'showClickedLoction'
      },

      /**
       * Render the search view.
       */
      render: function (items) {
        this.items = items;
        this.populateFilter(this.items.toJSON());
        this.delegateEvents();
      },

      setInputPlaceholderText: function () {
        // get route from url, i.e auditorium from file:///devel/src/suApp/www/map/index.html#/auditoriums
        var route = window.location.hash.split("/").length > 1 ? window.location.hash.split("/")[1] : "n/a";
        var text = "Skriv in text för att söka";
        if (route == "auditoriums") {
          text = "Sök hör- & skrivsalar";
        }
        this.inputField.attr("placeholder", text);
      },

      inputKeyup: function (e) {
        if (e.which == 13) {
          $(e.target).trigger("blur");
        }
      },

      keyboardAway: function () {
        $("#search-box input").trigger("blur");
      },

      showFilteredList: function () {
        $("#search-box form").addClass("tight");
        $("#cancelFilter").show();

        //if input field not empty trigger new filtering with existing value, else show whole filter
        if ($('div#search-box input').val() !== "") {
          // jquerymobile remembers the old value in the input field.
          // in order to trigger a change event, we must set another value inbetween.
          var prevValue = this.inputField.val();
          this.inputField.val('').trigger('change');
          this.inputField.val(prevValue).trigger('change');
        } else {
          $("#search-autocomplete li").removeClass("ui-screen-hidden");
        }
      },

      /**
       * If evt is an object, i.e. a blur event, then delay the execussion
       * of hiding the list. This is done in order to capture the click event
       * (when clicking on elements in the list).
       */
      hideFilteredList: function (evt) {
        $("#search-box form").removeClass("tight");
        $("#cancelFilter").hide();
        $("#search-autocomplete li").addClass("ui-screen-hidden");
      },

      /**
       * getClickedLocation takes the clicked html snippet from the search-filter list,
       * i.e: E 421.
       * From this html snippet getClickedLocation extracts the element name, in this
       * case "E 421" and finds it in the this.items collection (containing) all items
       * for the given type (i.e. auditorium).
       *
       *  @returns A new Locations collection with just the inputed item.
       *           If for some reason the item is not found in this.items collection,
       *           an empty Locations collection is returned.
       */
      getClickedLocation: function (target) {
        var itemName = $(target).html();
        var item;
        $.each(this.items.toJSON(), function (i, v) {
          if (v.name == itemName) {
            item = v;
            return false;
          }
        });

        var location = new Locations([]);

        if (item) {
          location = new Locations([this.items.get(item)]);
        }

        return location;
      },

      showClickedLoction: function (event, ui) {
        this.hideFilteredList();
        var location = this.getClickedLocation(event.target);
        this.mapView.replacePoints(location);
      },

      populateFilter: function (list) {
        var html = "";

        $.each(list, function (i, val) {
          html += "
" + val.name + "
";
        });

        var $ul = $('#search-autocomplete');
        $ul.html(html);
        $ul.listview("refresh");
        $ul.trigger("updatelayout");

        // After populating the list, hide it (only show it when search-box has focus)
        // hide the list only if the input doesn't have focus.
        if (!this.inputField.is(":focus")) {
          this.hideFilteredList();
        }
      },

      filterSearch: function (text, searchValue) {
        //search value- what we are looking for, text- the filter item being evaluated
        var evalRet = true;

        var splitText = text.split(" "); //unstable? depends on data
        splitText.push(text);
        splitText.push(text.replace(" ", ""));

        $.each(splitText, function (i, val) {
          //===0, it occurs at the beginning of the string
          if (val.toLowerCase().indexOf(searchValue) === 0) {
            evalRet = false;
          }
        });

        return evalRet;
        //returns true of false, truth filters out said instance
      }
    }); //-- End of Search view
<commit_msg>MOB-128 removed unused code<commit_after>/**
 * The search view for the map module.
 *
 * @class A Backbone view to handle the search popup.
 * @author Joakim Lundin
 * @type {Backbone.View}
 */
var SearchView = Backbone.View.extend(
    /** @lends SearchView */
    {

      /**
       * @constructs
       * @param options Options for this class. Expects campus name and a searchResult collection to add results to
       */
      initialize: function (options) {
        _.bindAll(this, "render", "populateFilter");
        this.inputField = $("#search-autocomplete").parent().find("form input");

        // This is done to show a search icon or text in the mobile keyboard
        this.inputField.get(0).type = "search";

        $("#search-autocomplete").listview("option", "filterCallback", this.filterSearch);

        this.setInputPlaceholderText();
        this.mapView = options.mapView;
      },

      /** Registers events */
      events: {
        'focus input': 'showFilteredList',
        'keyup input': 'inputKeyup',
        'click #cancelFilter': 'hideFilteredList',
        'click .autocomplete-link': 'showClickedLoction'
      },

      /**
       * Render the search view.
       */
      render: function (items) {
        this.items = items;
        this.populateFilter(this.items.toJSON());
        this.delegateEvents();
      },

      setInputPlaceholderText: function () {
        // get route from url, i.e auditorium from file:///devel/src/suApp/www/map/index.html#/auditoriums
        var route = window.location.hash.split("/").length > 1 ? window.location.hash.split("/")[1] : "n/a";
        var text = "Skriv in text för att söka";
        if (route == "auditoriums") {
          text = "Sök hör- & skrivsalar";
        }
        this.inputField.attr("placeholder", text);
      },

      inputKeyup: function (e) {
        if (e.which == 13) {
          $(e.target).trigger("blur");
        }
      },

      showFilteredList: function () {
        $("#search-box form").addClass("tight");
        $("#cancelFilter").show();

        //if input field not empty trigger new filtering with existing value, else show whole filter
        if ($('div#search-box input').val() !== "") {
          // jquerymobile remembers the old value in the input field.
          // in order to trigger a change event, we must set another value inbetween.
          var prevValue = this.inputField.val();
          this.inputField.val('').trigger('change');
          this.inputField.val(prevValue).trigger('change');
        } else {
          $("#search-autocomplete li").removeClass("ui-screen-hidden");
        }
      },

      /**
       * If evt is an object, i.e. a blur event, then delay the execussion
       * of hiding the list. This is done in order to capture the click event
       * (when clicking on elements in the list).
       */
      hideFilteredList: function (evt) {
        $("#search-box form").removeClass("tight");
        $("#cancelFilter").hide();
        $("#search-autocomplete li").addClass("ui-screen-hidden");
      },

      /**
       * getClickedLocation takes the clicked html snippet from the search-filter list,
       * i.e: E 421.
       * From this html snippet getClickedLocation extracts the element name, in this
       * case "E 421" and finds it in the this.items collection (containing) all items
       * for the given type (i.e. auditorium).
       *
       *  @returns A new Locations collection with just the inputed item.
       *           If for some reason the item is not found in this.items collection,
       *           an empty Locations collection is returned.
       */
      getClickedLocation: function (target) {
        var itemName = $(target).html();
        var item;
        $.each(this.items.toJSON(), function (i, v) {
          if (v.name == itemName) {
            item = v;
            return false;
          }
        });

        var location = new Locations([]);

        if (item) {
          location = new Locations([this.items.get(item)]);
        }

        return location;
      },

      showClickedLoction: function (event, ui) {
        this.hideFilteredList();
        var location = this.getClickedLocation(event.target);
        this.mapView.replacePoints(location);
      },

      populateFilter: function (list) {
        var html = "";

        $.each(list, function (i, val) {
          html += "
" + val.name + "
";
        });

        var $ul = $('#search-autocomplete');
        $ul.html(html);
        $ul.listview("refresh");
        $ul.trigger("updatelayout");

        // After populating the list, hide it (only show it when search-box has focus)
        // hide the list only if the input doesn't have focus.
        if (!this.inputField.is(":focus")) {
          this.hideFilteredList();
        }
      },

      filterSearch: function (text, searchValue) {
        //search value- what we are looking for, text- the filter item being evaluated
        var evalRet = true;

        var splitText = text.split(" "); //unstable? depends on data
        splitText.push(text);
        splitText.push(text.replace(" ", ""));

        $.each(splitText, function (i, val) {
          //===0, it occurs at the beginning of the string
          if (val.toLowerCase().indexOf(searchValue) === 0) {
            evalRet = false;
          }
        });

        return evalRet;
        //returns true of false, truth filters out said instance
      }
    }); //-- End of Search view
<|endoftext|>


<commit_before>
//dog filter Logic

// quick search regex
var qsRegex;

// init Isotope
var $grid = $('#dog-list').isotope({
  itemSelector: '.dog-card',
  layoutMode: 'fitRows',
  filter: function() {
    return qsRegex ? $(this).text().match( qsRegex ) : true;
  }
});

// use value of search field to filter
var $quicksearch = $('#breed').keyup( debounce( function() {
  qsRegex = new RegExp( $quicksearch.val(), 'gi' );
  $grid.isotope();
}, 200 ) );

// debounce so filtering doesn't happen every millisecond
function debounce( fn, threshold ) {
  var timeout;
  return function debounced() {
    if ( timeout ) {
      clearTimeout( timeout );
    }
    function delayed() {
      fn();
      timeout = null;
    }
    timeout = setTimeout( delayed, threshold || 100 );
  }
}

// Dog Form Logic

$('#formCarousel').on('slid.bs.carousel', function (ev) {
  var id = ev.relatedTarget.id;
  switch (id) {
    case "1":
      $('#buttonLeft').hide();
      $("#buttonRight").show();
      $("#buttonSubmit").hide();
      $("#slide1").addClass("active");
      $("#slide2").removeClass("active");
      $("#slide3").removeClass("active");
      break;
    case "2":
      // do something the id is 2
      $('#buttonLeft').show();
      $('#buttonRight').show();
      $("#buttonSubmit").hide();
      $("#slide1").removeClass("active");
      $("#slide2").addClass("active");
      $("#slide3").removeClass("active");
      break;
    case "3":
      // do something the id is 3
      $("#buttonRight").hide();
      $("#buttonLeft").show();
      $("#buttonSubmit").show();
      $("#slide1").removeClass("active");
      $("#slide2").removeClass("active");
      $("#slide3").addClass("active");
      break;
    default:
      //the id is none of the above
  }
})

// Sticky Plugin

$(document).ready(function () {
  var top = $('.sticky-scroll-box').offset().top;
  $(window).scroll(function (event) {
    var y = $(this).scrollTop();
    if (y >= top)
      $('.sticky-scroll-box').addClass('fixed');
    else
      $('.sticky-scroll-box').removeClass('fixed');
    // $('.sticky-scroll-box').width($('.sticky-scroll-box').parent().width());
  });
});

$(document).ready(function () {
//Prefills the date
var d = new Date();
var n = d.toLocaleDateString();
var dateInput = document.getElementById('date_found');
dateInput.value = n;

//DOG-FORM Button trigger if COLLAR_YES
$('#collar_color').hide();
$('#collarYes').click(function(event){
  $('#collar_color').slideToggle();
})
$('#collarNo').click(function(event){
  $('#collar_color').hide();
})
});

var range = 100;

$(window).on('scroll', function () {
  var scrollTop = $(this).scrollTop(),
      height = $('#header').outerHeight(),
      offset = height/0.5,
      calc = 1 - (scrollTop - offset + range) / range;
  $('#header').css({ 'opacity': calc });
  if (calc > '1') {
    $('#header').css({ 'opacity': 1 });
  } else if ( calc < '0' ) {
    $('#header').css({ 'opacity': 0 });
  }
});

//////////////////////////
//END JULIE

//define what we have ws = connection form = the form we use messageInput = where we input data
//messagesList = where messages are stored message = the message we currently have entered
var ws;
var form = document.getElementById('form');
var messageInput = document.getElementById('message');
var messagesList = document.getElementById('messages');
var socketStatus = document.getElementById('status');
var closeBtn = document.getElementById('close');

window.onload = function() {
// hack for localhost versus production. will fix better later.
var url = document.URL;

ws = new WebSocket("ws://localhost:8080/websocket");

console.log("heloo there");

// Triggers when message is sent
ws.onmessage = function(event) {
  console.log("new message attempt");
  // defines message as the contents of the message
  var message = event.data;
  // overwrites messages with new message that is received
  messagesList.innerHTML += '
Received:	' + message + '
';
};
// Triggers on open websocket
ws.onopen = function(event) {
  console.log("new connection attempt");
  socketStatus.innerHTML = 'open';
  socketStatus.className = 'open';
};
//Triggers on close connection
ws.onclose = function(event) {
  console.log("new close attempt");
  socketStatus.innerHTML = 'closed';
  socketStatus.className = 'closed';
};
form.onsubmit = function(e) {

  // e.preventDefault();
  //define message field value
  var message = messageInput.value;
  // Send the message through the WebSocket.
  ws.send(message);
  // overwrites messages with new message that is sent
  messagesList.innerHTML += '
Sent:	' + message + '
';
  // Clear out the message field.
  messageInput.value = '';
  //terminate function
  window.location.reload()
  return false;
};
// Close the WebSocket connection when the close button is clicked.
closeBtn.onclick = function(e) {
  console.log("new close queue attempt");
  //prevents page refresh
  e.preventDefault();
  // Close the WebSocket.
  ws.close();
  //terminate function
  return false;
  };
}

var urlForm = document.getElementById("urlForm");
var urlInput = document.getElementById("urlInput");

urlForm.onsubmit = function(e) {

  // e.preventDefault();
  //define message field value
  var url = urlInput.value;
  // Send the message through the WebSocket.

  var redirect = "/py-scraper?url=" + url

  window.location.replace(redirect)
  return false;
};

module.exports = tornadoPy;
<commit_msg>fix isotope<commit_after>// Dog Form Logic

$('#formCarousel').on('slid.bs.carousel', function (ev) {
  var id = ev.relatedTarget.id;
  switch (id) {
    case "1":
      $('#buttonLeft').hide();
      $("#buttonRight").show();
      $("#buttonSubmit").hide();
      $("#slide1").addClass("active");
      $("#slide2").removeClass("active");
      $("#slide3").removeClass("active");
      break;
    case "2":
      // do something the id is 2
      $('#buttonLeft').show();
      $('#buttonRight').show();
      $("#buttonSubmit").hide();
      $("#slide1").removeClass("active");
      $("#slide2").addClass("active");
      $("#slide3").removeClass("active");
      break;
    case "3":
      // do something the id is 3
      $("#buttonRight").hide();
      $("#buttonLeft").show();
      $("#buttonSubmit").show();
      $("#slide1").removeClass("active");
      $("#slide2").removeClass("active");
      $("#slide3").addClass("active");
      break;
    default:
      //the id is none of the above
  }
})

// Sticky Plugin

$(document).ready(function () {
  var top = $('.sticky-scroll-box').offset().top;
  $(window).scroll(function (event) {
    var y = $(this).scrollTop();
    if (y >= top)
      $('.sticky-scroll-box').addClass('fixed');
    else
      $('.sticky-scroll-box').removeClass('fixed');
    // $('.sticky-scroll-box').width($('.sticky-scroll-box').parent().width());
  });
});

$(document).ready(function () {
//Prefills the date
var d = new Date();
var n = d.toLocaleDateString();
var dateInput = document.getElementById('date_found');
dateInput.value = n;

//DOG-FORM Button trigger if COLLAR_YES
$('#collar_color').hide();
$('#collarYes').click(function(event){
  $('#collar_color').slideToggle();
})
$('#collarNo').click(function(event){
  $('#collar_color').hide();
})
});

var range = 100;

$(window).on('scroll', function () {
  var scrollTop = $(this).scrollTop(),
      height = $('#header').outerHeight(),
      offset = height/0.5,
      calc = 1 - (scrollTop - offset + range) / range;
  $('#header').css({ 'opacity': calc });
  if (calc > '1') {
    $('#header').css({ 'opacity': 1 });
  } else if ( calc < '0' ) {
    $('#header').css({ 'opacity': 0 });
  }
});

//////////////////////////
//END JULIE

//define what we have ws = connection form = the form we use messageInput = where we input data
//messagesList = where messages are stored message = the message we currently have entered
var ws;
var form = document.getElementById('form');
var messageInput = document.getElementById('message');
var messagesList = document.getElementById('messages');
var socketStatus = document.getElementById('status');
var closeBtn = document.getElementById('close');

window.onload = function() {
// hack for localhost versus production. will fix better later.
var url = document.URL;

ws = new WebSocket("ws://localhost:8080/websocket");

console.log("heloo there");

// Triggers when message is sent
ws.onmessage = function(event) {
  console.log("new message attempt");
  // defines message as the contents of the message
  var message = event.data;
  // overwrites messages with new message that is received
  messagesList.innerHTML += '
Received:	' + message + '
';
};
// Triggers on open websocket
ws.onopen = function(event) {
  console.log("new connection attempt");
  socketStatus.innerHTML = 'open';
  socketStatus.className = 'open';
};
//Triggers on close connection
ws.onclose = function(event) {
  console.log("new close attempt");
  socketStatus.innerHTML = 'closed';
  socketStatus.className = 'closed';
};
form.onsubmit = function(e) {

  // e.preventDefault();
  //define message field value
  var message = messageInput.value;
  // Send the message through the WebSocket.
  ws.send(message);
  // overwrites messages with new message that is sent
  messagesList.innerHTML += '
Sent:	' + message + '
';
  // Clear out the message field.
  messageInput.value = '';
  //terminate function
  window.location.reload()
  return false;
};
// Close the WebSocket connection when the close button is clicked.
closeBtn.onclick = function(e) {
  console.log("new close queue attempt");
  //prevents page refresh
  e.preventDefault();
  // Close the WebSocket.
  ws.close();
  //terminate function
  return false;
  };
}

var urlForm = document.getElementById("urlForm");
var urlInput = document.getElementById("urlInput");

urlForm.onsubmit = function(e) {

  // e.preventDefault();
  //define message field value
  var url = urlInput.value;
  // Send the message through the WebSocket.

  var redirect = "/py-scraper?url=" + url

  window.location.replace(redirect)
  return false;
};

module.exports = tornadoPy;
<|endoftext|>


<commit_before>
function log(msg)
{
    console.LogInfo("[Tests::VercionCheck]: " + msg);
}

print("");

log("Application version: " + application.version);
log("  major       = " + application.majorVersion);
log("  minor       = " + application.minorVersion);
log("  major patch = " + application.majorPatchVersion);
log("  minor patch = " + application.minorPatchVersion);

print("");<commit_msg>VersionCheck.js typo fix.<commit_after>
function log(msg)
{
    console.LogInfo("[Tests::VersionCheck]: " + msg);
}

print("");

log("Application version: " + application.version);
log("  major       = " + application.majorVersion);
log("  minor       = " + application.minorVersion);
log("  major patch = " + application.majorPatchVersion);
log("  minor patch = " + application.minorPatchVersion);

print("");<|endoftext|>


<commit_before>/**
 * Prepros
 * (c) Subash Pathak
 * sbshpthk@gmail.com
 * License: MIT
 */

/*jshint browser: true, node: true*/
/*global prepros*/

prepros.factory('sass', function (config, utils, notification) {

    'use strict';

    var fs = require('fs-extra'),
        path = require('path'),
        cp = require('child_process'),
        _id = utils.id;

    var format = function (filePath, projectPath) {

        //File name
        var name = path.basename(filePath);

        //Relative input path
        var shortInput = path.relative(projectPath, filePath).replace(/\\/g, '/');

        // Output path
        var output = filePath.replace(/\.sass|\.scss/gi, '.css');

        //Find output path; save to user defined css folder if file is in sass or scss folder
        if(filePath.match(/\\sass\\|\\scss\\|\/sass\/|\/scss\//gi)) {

            output = path.normalize(output.replace(/\\sass\\|\\scss\\|\/sass\/|\/scss\//gi, path.sep + '{{cssPath}}' + path.sep));

        }

        //Find short output path
        var shortOutput = output.replace(/\\/g, '/');

        //Show Relative path if output file is within project folder
        if (path.relative(projectPath, filePath).indexOf('.' + path.sep) === -1) {

            shortOutput = path.relative(projectPath, output).replace(/\\/g, '/');
        }

        var file = {
            id: _id(filePath),
            pid: _id(projectPath),
            name: name,
            input: filePath,
            shortInput: shortInput,
            output: output,
            shortOutput: shortOutput,
            config : config.getUserOptions().sass
        };

        var ext = path.extname(filePath);

        if (ext === '.scss') {

            file.type = 'Scss';

        } else if (ext === '.sass') {

            file.type = 'Sass';
        }

        return file;

    };

    //Compile

    var compile = function (file, callback) {

        var args =[];

        if(file.config.fullCompass && file.config.compass) {

            if(config.getUserOptions().useCustomSassCompass) {

                args = [config.getUserOptions().customCompassPath];

            } else {

                args = [config.ruby.gems.compass.path];
            }

            args.push('compile', path.relative(file.projectPath, file.input).replace(/\\/gi, '/'));

            args.push("--environment", 'development');

            //Output Style
            args.push('--output-style', file.config.outputStyle);

            //Line numbers
            if (!file.config.lineNumbers) {
                args.push('--no-line-comments');
            }

            //Debug info
            if(file.config.debug){

                args.push('--debug-info');
            }

            args.push('--force');

        } else {

            if(config.getUserOptions().useCustomSassCompass) {

                args = [config.getUserOptions().customSassPath];

            } else {

                args = [config.ruby.gems.sass.path];
            }

            //Force utf-8 encoding
            args.push('-E', 'utf-8');

            //Input and output
            args.push(file.input, file.output);

            //Load path for @imports
            args.push('--load-path', path.dirname(file.input));

            //Convert backslashes to double backslashes which weirdly escapes single quotes from sass cache path fix #52
            var cacheLocation = config.cachePath.replace(/\\\\/gi, '\\\\');

            //Cache location
            args.push('--cache-location', cacheLocation);

            //Output Style
            args.push('--style', file.config.outputStyle);

            //Debug info
            if(file.config.debug){

                args.push('--debug');
            }

            //Compass
            if (file.config.compass) {

                args.push('--compass');
            }

            //Sass bourbon
            args.push('--load-path', config.ruby.gems.bourbon.path);

            //Line numbers
            if (file.config.lineNumbers) {
                args.push('--line-numbers');
            }

            //Make output dir if it doesn't exist
            fs.mkdirsSync(path.dirname(file.output));

        }

        var rubyProcess;

        if(config.getUserOptions().useCustomSassCompass) {

            try {

                //Start a child process to compile the file; file.projectPath is provided by compiler.js file
                rubyProcess = cp.spawn(config.getUserOptions().customRubyPath, args, {cwd: file.projectPath});

            } catch(e) {

                notification.error('Invalid Custom Path', 'Prepros was unable to run custom executable.', e.message);
            }

        } else {

            //Start a child process to compile the file; file.projectPath is provided by compiler.js file
            rubyProcess = cp.spawn(config.ruby.path, args, {cwd: file.projectPath});

        }

        var compileErr = false;

        //If there is a compilation error
        rubyProcess.stderr.on('data', function (data) {

            compileErr = true;

            callback(true, data.toString());

        });

        //Success if there is no error
        rubyProcess.on('exit', function(){
            if(!compileErr){

                callback(false, file.input);

            }
        });

    };

    return {
        format: format,
        compile: compile
    };
});<commit_msg>Check if ruby path exists before executing<commit_after>/**
 * Prepros
 * (c) Subash Pathak
 * sbshpthk@gmail.com
 * License: MIT
 */

/*jshint browser: true, node: true*/
/*global prepros*/

prepros.factory('sass', function (config, utils, notification) {

    'use strict';

    var fs = require('fs-extra'),
        path = require('path'),
        cp = require('child_process'),
        _id = utils.id;

    var format = function (filePath, projectPath) {

        //File name
        var name = path.basename(filePath);

        //Relative input path
        var shortInput = path.relative(projectPath, filePath).replace(/\\/g, '/');

        // Output path
        var output = filePath.replace(/\.sass|\.scss/gi, '.css');

        //Find output path; save to user defined css folder if file is in sass or scss folder
        if(filePath.match(/\\sass\\|\\scss\\|\/sass\/|\/scss\//gi)) {

            output = path.normalize(output.replace(/\\sass\\|\\scss\\|\/sass\/|\/scss\//gi, path.sep + '{{cssPath}}' + path.sep));

        }

        //Find short output path
        var shortOutput = output.replace(/\\/g, '/');

        //Show Relative path if output file is within project folder
        if (path.relative(projectPath, filePath).indexOf('.' + path.sep) === -1) {

            shortOutput = path.relative(projectPath, output).replace(/\\/g, '/');
        }

        var file = {
            id: _id(filePath),
            pid: _id(projectPath),
            name: name,
            input: filePath,
            shortInput: shortInput,
            output: output,
            shortOutput: shortOutput,
            config : config.getUserOptions().sass
        };

        var ext = path.extname(filePath);

        if (ext === '.scss') {

            file.type = 'Scss';

        } else if (ext === '.sass') {

            file.type = 'Sass';
        }

        return file;

    };

    //Compile

    var compile = function (file, callback) {

        var args =[];

        if(file.config.fullCompass && file.config.compass) {

            if(config.getUserOptions().useCustomSassCompass) {

                args = [config.getUserOptions().customCompassPath];

            } else {

                args = [config.ruby.gems.compass.path];
            }

            args.push('compile', path.relative(file.projectPath, file.input).replace(/\\/gi, '/'));

            args.push("--environment", 'development');

            //Output Style
            args.push('--output-style', file.config.outputStyle);

            //Line numbers
            if (!file.config.lineNumbers) {
                args.push('--no-line-comments');
            }

            //Debug info
            if(file.config.debug){

                args.push('--debug-info');
            }

            args.push('--force');

        } else {

            if(config.getUserOptions().useCustomSassCompass) {

                args = [config.getUserOptions().customSassPath];

            } else {

                args = [config.ruby.gems.sass.path];
            }

            //Force utf-8 encoding
            args.push('-E', 'utf-8');

            //Input and output
            args.push(file.input, file.output);

            //Load path for @imports
            args.push('--load-path', path.dirname(file.input));

            //Convert backslashes to double backslashes which weirdly escapes single quotes from sass cache path fix #52
            var cacheLocation = config.cachePath.replace(/\\\\/gi, '\\\\');

            //Cache location
            args.push('--cache-location', cacheLocation);

            //Output Style
            args.push('--style', file.config.outputStyle);

            //Debug info
            if(file.config.debug){

                args.push('--debug');
            }

            //Compass
            if (file.config.compass) {

                args.push('--compass');
            }

            //Sass bourbon
            args.push('--load-path', config.ruby.gems.bourbon.path);

            //Line numbers
            if (file.config.lineNumbers) {
                args.push('--line-numbers');
            }

            //Make output dir if it doesn't exist
            fs.mkdirsSync(path.dirname(file.output));

        }

        var rubyProcess;

        if(config.getUserOptions().useCustomSassCompass) {

            try {

                if(fs.existsSync(config.getUserOptions().customRubyPath)) {

                    //Start a child process to compile the file; file.projectPath is provided by compiler.js file
                    rubyProcess = cp.spawn(config.getUserOptions().customRubyPath, args, {cwd: file.projectPath});

                } else {

                    notification.error('Invalid Ruby Path', 'Prepros was unable to run Ruby', config.getUserOptions().customRubyPath + ' not found');

                }

            } catch(e) {

                notification.error('Invalid Custom Path', 'Prepros was unable to run custom executable.', e.message);
            }

        } else {

            //Start a child process to compile the file; file.projectPath is provided by compiler.js file
            rubyProcess = cp.spawn(config.ruby.path, args, {cwd: file.projectPath});

        }

        var compileErr = false;

        //If there is a compilation error
        rubyProcess.stderr.on('data', function (data) {

            compileErr = true;

            callback(true, data.toString());

        });

        //Success if there is no error
        rubyProcess.on('exit', function(){
            if(!compileErr){

                callback(false, file.input);

            }
        });

    };

    return {
        format: format,
        compile: compile
    };
});<|endoftext|>


<commit_before>(function() {
    'use strict';

    ProfileService.$inject = ['api'];
    function ProfileService(api) {

        this.getUserActivity = function(user, maxResults, page) {
            var q = {
                where: {user: user._id},
                sort: '[(\'_created\',-1)]',
                embedded: {user: 1}
            };

            if (maxResults) {
                q.max_results = maxResults;
            }

            if (page > 1) {
                q.page = page;
            }

            return api.activity.query(q);
        };

        this.getUserActivityFiltered = function(maxResults, page) {
            var q = {
                sort: '[(\'_created\',-1)]',
                embedded: {user: 1}
            };

            if (maxResults) {
                q.max_results = maxResults;
            }

            if (page > 1) {
                q.page = page;
            }

            return api.activity.query(q);
        };
    }

    angular.module('superdesk.users.profile', ['superdesk.api', 'superdesk.users'])

        .service('profileService', ProfileService)

        .config(['apiProvider', function(apiProvider) {
            apiProvider.api('activity', {
                type: 'http',
                backend: {rel: 'activity'}
            });
        }])

        .config(['superdeskProvider', 'assetProvider', function(superdeskProvider, asset) {
            superdeskProvider.activity('/profile/', {
                label: gettext('My Profile'),
                controller: 'UserEditController',
                templateUrl: asset.templateUrl('superdesk-users/views/edit.html'),
                resolve: {
                    user: ['session', function(session) {
                        return session.getIdentity();
                    }]
                }
            });
        }])

        .directive('sdUserActivity', ['profileService', 'asset', function(profileService, asset) {
            return {
                restrict: 'A',
                replace: true,
                templateUrl: asset.templateUrl('superdesk-users/views/activity-feed.html'),
                scope: {
                    user: '='
                },
                link: function(scope, element, attrs) {
                    var page = 1;
                    var maxResults = 5;

                    scope.$watch('user', function() {
                        profileService.getUserActivity(scope.user, maxResults).then(function(list) {
                            scope.activityFeed = list;
                        });
                    });

                    scope.loadMore = function() {
                        page++;
                        profileService.getUserActivity(scope.user, maxResults, page).then(function(next) {
                            Array.prototype.push.apply(scope.activityFeed._items, next._items);
                            scope.activityFeed._links = next._links;
                        });
                    };
                }
            };
        }]);
})();
<commit_msg>fix(profile): get fresh copy of profile<commit_after>(function() {
    'use strict';

    ProfileService.$inject = ['api'];
    function ProfileService(api) {

        this.getUserActivity = function(user, maxResults, page) {
            var q = {
                where: {user: user._id},
                sort: '[(\'_created\',-1)]',
                embedded: {user: 1}
            };

            if (maxResults) {
                q.max_results = maxResults;
            }

            if (page > 1) {
                q.page = page;
            }

            return api.activity.query(q);
        };

        this.getUserActivityFiltered = function(maxResults, page) {
            var q = {
                sort: '[(\'_created\',-1)]',
                embedded: {user: 1}
            };

            if (maxResults) {
                q.max_results = maxResults;
            }

            if (page > 1) {
                q.page = page;
            }

            return api.activity.query(q);
        };
    }

    angular.module('superdesk.users.profile', ['superdesk.api', 'superdesk.users'])

        .service('profileService', ProfileService)

        .config(['apiProvider', function(apiProvider) {
            apiProvider.api('activity', {
                type: 'http',
                backend: {rel: 'activity'}
            });
        }])

        .config(['superdeskProvider', 'assetProvider', function(superdeskProvider, asset) {
            superdeskProvider.activity('/profile/', {
                label: gettext('My Profile'),
                controller: 'UserEditController',
                templateUrl: asset.templateUrl('superdesk-users/views/edit.html'),
                resolve: {
                    user: ['session', 'api', function(session, api) {
                        return session.getIdentity().then(function(identity) {
                            return api.get(identity._links.self.href);
                        });
                    }]
                }
            });
        }])

        .directive('sdUserActivity', ['profileService', 'asset', function(profileService, asset) {
            return {
                restrict: 'A',
                replace: true,
                templateUrl: asset.templateUrl('superdesk-users/views/activity-feed.html'),
                scope: {
                    user: '='
                },
                link: function(scope, element, attrs) {
                    var page = 1;
                    var maxResults = 5;

                    scope.$watch('user', function() {
                        profileService.getUserActivity(scope.user, maxResults).then(function(list) {
                            scope.activityFeed = list;
                        });
                    });

                    scope.loadMore = function() {
                        page++;
                        profileService.getUserActivity(scope.user, maxResults, page).then(function(next) {
                            Array.prototype.push.apply(scope.activityFeed._items, next._items);
                            scope.activityFeed._links = next._links;
                        });
                    };
                }
            };
        }]);
})();
<|endoftext|>


<commit_before>"use strict";

var Promise = require('bluebird')
  , async = require('async')
  , _ = require('underscore')
  , s = require("underscore.string")

exports.addSerializer = function() {
  var AbstractSerializer = function(object, strategy) {
    this.object   = object
    this.strategy = strategy
  }

  AbstractSerializer.prototype = {
    END_POINT: 1,
    NESTED_STRATEGY: 2,
    THROUGH_POINT: 3,

    getField: function(field, f) {
      if (!this.object) {
        f(null, null)
      } else if (!this.object[field]) {
        var name = "get" + s(field).capitalize().value()
        var method = this.object[name]

        if (method) {
          method.apply(this.object)
            .then(function(object) { f(null, object) })
            .catch(function(e) { f(e, null) })
        } else { f(null, null) }
      } else { f(null, this.object[field]) }
    },

    decideNode: function(field) {
      if (!this.strategy[field]) {
        return this.END_POINT
      } else {
        if (this.strategy[field].through) {
          return this.THROUGH_POINT
        } else {
          return this.NESTED_STRATEGY
        }
      }
    },

    prepareNestedField: function(name) {
      var nestedField = name

      if (name[name.length - 1] === 's') {
        nestedField = name.substr(0, name.length-1) + "Ids"
      } else {
        nestedField += "Id"
      }

      return nestedField
    },

    processMultiObjects: function(objects, strategy, serializer, root, level, f) {
      var result = []
      var jsonAdder = function(done) {
        return function(err, json) {
          result.push(json)
          done(err)
        }
      }

      async.forEach(objects, function(object, done) {
        if (serializer) {
          new serializer(object).toJSON(jsonAdder(done), root, level + 1)
        } else {
          new AbstractSerializer(object, strategy).toJSON(jsonAdder(done), root, level + 1)
        }
      }, function(err) {
        f(err, result)
      })
    },

    processMultiObjectsWithRoot: function(field, objects, strategy, serializer, root, level, f) {
      var result = []
      var jsonAdder = function(done) {
        return function(err, json) {
          result.push(json)
          done(err)
        }
      }

      async.forEach(objects, function(object, done) {
        if (serializer) {
          new serializer(object).toJSON(jsonAdder(done), root, level + 1)
        } else {
          new AbstractSerializer(object, strategy).toJSON(jsonAdder(done), root, level + 1)
        }
      }, function(err) {
        var node = serializer ? new serializer(objects[0]).name : field
        if (typeof root[node] === 'undefined') {
          root[node] = result
        } else {
          root[node] = root[node].concat(result)
        }

        f(err)
      })
    },

    getMaybeObjects: function(field, one, many) {
      this.getField(field, function(err, object) {
        Array.isArray(object) ? many(object) : one(object)
      })
    },

    processNestedStrategy: function(field, f, root, level) {
      var serializer = this

      serializer.getMaybeObjects(field, function(object) {
        new AbstractSerializer(object, serializer.strategy[field]).toJSON(f, root, level + 1)
      }, function(objects) {
        serializer.processMultiObjects(objects, serializer.strategy[field], null, root, level, f)
      })
    },

    processThroughPoint: function(field, f, root, level) {
      var serializer = this

      var processWithRoot = function(objects, one) {
        var objects = _.filter(objects, function(object) { return _.has(object, 'id') })
        var object_ids = objects.map(function(e) { return e.id })

        serializer.processMultiObjectsWithRoot(serializer.strategy[field].model || field,
                                               objects,
                                               serializer.strategy[field],
                                               serializer.strategy[field].through,
                                               root,
                                               level, function(err) {
          if (one)
            object_ids = object_ids[0]

          f(err, object_ids)
        })
      }

      serializer.getMaybeObjects(field, function(object) {
        if (serializer.strategy[field].embed) {
          if (object) {
            processWithRoot([object], true)
          } else {
            f(null, null)
          }
        } else {
          new serializer.strategy[field].through(object).toJSON(f)
        }
      }, function(objects) {
        if (serializer.strategy[field].embed) {
          processWithRoot(objects)
        } else {
          serializer.processMultiObjects(objects, null, serializer.strategy[field].through, root, level, f)
        }
      })
    },

    processNode: function(jsonAdder, root, level) {
      var serializer = this

      return function(field, done) {
        switch (serializer.decideNode(field)) {

        case serializer.END_POINT:
          serializer.getField(field, jsonAdder(field, done))
          break

        case serializer.NESTED_STRATEGY:
          serializer.processNestedStrategy(field, jsonAdder(field, done), root, level)
          break

        case serializer.THROUGH_POINT:
          var node = serializer.embed ? serializer.prepareNestedField(field) : field
          serializer.processThroughPoint(field, jsonAdder(node, done), root, level)
          break
        }
      }
    },

    toJSON: function(f, root, level) {
      var json = {}
      root = root || {}
      level = level || 0
      var jsonAdder = function(field, done) {
        return function(err, res) {
          json[field] = res
          done(err)
        }
      }

      var name = this.name
      async.forEach(this.strategy.select, this.processNode(jsonAdder, root, level + 1) , function(err) {
        if (level === 0) {
          var inner_json = json
          json = {}
          json[name] = inner_json

          json = _.extend(json, root)
        }

        f(err, json)
      })
    }
  }

  return AbstractSerializer
}
<commit_msg>Attempts to optimize serializer.<commit_after>"use strict";

var Promise = require('bluebird')
  , async = require('async')
  , _ = require('underscore')
  , s = require("underscore.string")

exports.addSerializer = function() {
  var AbstractSerializer = function(object, strategy) {
    this.object   = object
    this.strategy = strategy
  }

  AbstractSerializer.prototype = {
    END_POINT: 1,
    NESTED_STRATEGY: 2,
    THROUGH_POINT: 3,

    getField: function(field, f) {
      if (!this.object) {
        f(null, null)
      } else if (!this.object[field]) {
        var name = "get" + s(field).capitalize().value()
        var method = this.object[name]

        if (method) {
          method.apply(this.object)
            .then(function(object) { f(null, object) })
            .catch(function(e) { f(e, null) })
        } else { f(null, null) }
      } else { f(null, this.object[field]) }
    },

    decideNode: function(field) {
      if (!this.strategy[field]) {
        return this.END_POINT
      } else {
        if (this.strategy[field].through) {
          return this.THROUGH_POINT
        } else {
          return this.NESTED_STRATEGY
        }
      }
    },

    prepareNestedField: function(name) {
      var nestedField = name

      if (name[name.length - 1] === 's') {
        nestedField = name.substr(0, name.length-1) + "Ids"
      } else {
        nestedField += "Id"
      }

      return nestedField
    },

    processMultiObjects: function(objects, strategy, serializer, root, level, f) {
      var result = []
      var jsonAdder = function(done) {
        return function(err, json) {
          result.push(json)
          done(err)
        }
      }

      async.forEach(objects, function(object, done) {
        if (serializer) {
          new serializer(object).toJSON(jsonAdder(done), root, level + 1)
        } else {
          new AbstractSerializer(object, strategy).toJSON(jsonAdder(done), root, level + 1)
        }
      }, function(err) {
        f(err, result)
      })
    },

    processMultiObjectsWithRoot: function(field, objects, strategy, serializer, root, level, f) {
      var result = []
      var jsonAdder = function(done) {
        return function(err, json) {
          result.push(json)
          done(err)
        }
      }

      async.forEach(objects, function(object, done) {
        if (serializer) {
          new serializer(object).toJSON(jsonAdder(done), root, level + 1)
        } else {
          new AbstractSerializer(object, strategy).toJSON(jsonAdder(done), root, level + 1)
        }
      }, function(err) {
        var node = serializer ? new serializer(objects[0]).name : field
        if (typeof root[node] === 'undefined') {
          root[node] = result
        } else {
          root[node] = root[node].concat(result)
        }

        f(err)
      })
    },

    getMaybeObjects: function(field, one, many) {
      this.getField(field, function(err, object) {
        Array.isArray(object) ? many(object) : one(object)
      })
    },

    processNestedStrategy: function(field, f, root, level) {
      var serializer = this

      serializer.getMaybeObjects(field, function(object) {
        new AbstractSerializer(object, serializer.strategy[field]).toJSON(f, root, level + 1)
      }, function(objects) {
        serializer.processMultiObjects(objects, serializer.strategy[field], null, root, level, f)
      })
    },

    processThroughPoint: function(field, f, root, level) {
      var serializer = this

      var processWithRoot = function(objects, one) {
        var objects = _.filter(objects, function(object) { return _.has(object, 'id') })
        var objectIds = objects.map(function(e) { return e.id })

        var strategy = serializer.strategy[field]

        // Does not request objects that already has been serialized
        // and they are in root.
        // NOTE: this code is rather slow itself
        // var node = new strategy.through(objects[0]).name
        // var rootIds = _.map(root[node] || [], function(object) { return object.id })
        // objectIds = _.difference(objectIds, rootIds)
        // objects = _.filter(objects, function(object) {
        //   return _.contains(objectIds, object.id)
        // })

        serializer.processMultiObjectsWithRoot(strategy.model || field,
                                               objects,
                                               strategy,
                                               strategy.through,
                                               root,
                                               level, function(err) {
          if (one)
            objectIds = objectIds[0]

          f(err, objectIds)
        })
      }

      serializer.getMaybeObjects(field, function(object) {
        if (serializer.strategy[field].embed) {
          if (object) {
            processWithRoot([object], true)
          } else {
            f(null, null)
          }
        } else {
          new serializer.strategy[field].through(object).toJSON(f)
        }
      }, function(objects) {
        if (serializer.strategy[field].embed) {
          processWithRoot(objects)
        } else {
          serializer.processMultiObjects(objects, null, serializer.strategy[field].through, root, level, f)
        }
      })
    },

    processNode: function(jsonAdder, root, level) {
      var serializer = this

      return function(field, done) {
        switch (serializer.decideNode(field)) {

        case serializer.END_POINT:
          serializer.getField(field, jsonAdder(field, done))
          break

        case serializer.NESTED_STRATEGY:
          serializer.processNestedStrategy(field, jsonAdder(field, done), root, level)
          break

        case serializer.THROUGH_POINT:
          var node = serializer.embed ? serializer.prepareNestedField(field) : field
          serializer.processThroughPoint(field, jsonAdder(node, done), root, level)
          break
        }
      }
    },

    toJSON: function(f, root, level) {
      var json = {}
      root = root || {}
      level = level || 0
      var jsonAdder = function(field, done) {
        return function(err, res) {
          json[field] = res
          done(err)
        }
      }

      var name = this.name
      async.forEach(this.strategy.select, this.processNode(jsonAdder, root, level + 1) , function(err) {
        if (level === 0) {
          var inner_json = json
          json = {}
          json[name] = inner_json

          json = _.extend(json, root)
        }

        f(err, json)
      })
    }
  }

  return AbstractSerializer
}
<|endoftext|>


<commit_before>/* ==========================================================
 * issue-guidelines.js
 * http://twitter.github.com/bootstrap/javascript.html#alerts
 * ==========================================================
 * Copyright 2012 Twitter, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ========================================================== */

var assert = require('assert')

module.exports = {

    'pull-requests': {

        'should always be made against -wip branches': function (pull) {
            assert.ok(/\-wip$/.test(pull.base.label))
        },

        'should always be made from feature branches': function (pull) {
            assert.ok(pull.head.label != 'master')
        },

        'should always include a unit test if changing js files': function (pull) {
            var hasJS    = false
            var hasTests = false

            pull.files.forEach(function (file) {
                if (/^js\/[^./]+.js/.test(file.filename))            hasJS    = true
                if (/^js\/tests\/unit\/[^.]+.js/.test(file.filename)) hasTests = true
            })

            assert.ok(!hasJS || hasJS && hasTests)
        },

        'after': function (pull) {
            if (pull.reporter.stats.failures) {
                pull.reportFailures(pull.close.bind(pull))
            }
        }

    },

    'issues': {

        'before': function (issue) {
            var plus   = {}
            var labels = issue.labels.map(function (label) { return label.name });

            if (~labels.indexOf('popular')) return

            issue.comments.forEach(function (comment) {
                if (/\+1/.test(comment.body)) plus[comment.user.login] = true
            })

            if (Object.keys(plus).length > 5) {
                issue.tag('popular')
                issue.comment('Tagging this issue as popular, please stop commenting on this issue with +1. thanks!')
            }
        },

        'should include a jsfiddle/jsbin illustrating the problem if tagged with js but not a feature': function (issue) {
            var labels = issue.labels.map(function (label) { return label.name });
            if (~labels.indexOf('js') && !~labels.indexOf('feature')) assert.ok(/(jsfiddle|jsbin)/.test(issue.body))
        },

        'after': function (issue) {
            if (issue.reporter.stats.failures) {
                issue.reportFailures(issue.close.bind(issue))
            }
        }

    }

}<commit_msg>Use ref instead of label when checking branches in issue-guidelines<commit_after>/* ==========================================================
 * issue-guidelines.js
 * http://twitter.github.com/bootstrap/javascript.html#alerts
 * ==========================================================
 * Copyright 2012 Twitter, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ========================================================== */

var assert = require('assert')

module.exports = {

    'pull-requests': {

        'should always be made against -wip branches': function (pull) {
            assert.ok(/\-wip$/.test(pull.base.ref))
        },

        'should always be made from feature branches': function (pull) {
            assert.notEqual(pull.head.ref, 'master')
        },

        'should always include a unit test if changing js files': function (pull) {
            var hasJS    = false
            var hasTests = false

            pull.files.forEach(function (file) {
                if (/^js\/[^./]+.js/.test(file.filename))             hasJS    = true
                if (/^js\/tests\/unit\/[^.]+.js/.test(file.filename)) hasTests = true
            })

            assert.ok(!hasJS || hasJS && hasTests)
        },

        'after': function (pull) {
            if (pull.reporter.stats.failures) {
                pull.reportFailures(pull.close.bind(pull))
            }
        }

    },

    'issues': {

        'before': function (issue) {
            var plus   = {}
            var labels = issue.labels.map(function (label) { return label.name });

            if (~labels.indexOf('popular')) return

            issue.comments.forEach(function (comment) {
                if (/\+1/.test(comment.body)) plus[comment.user.login] = true
            })

            if (Object.keys(plus).length > 5) {
                issue.tag('popular')
                issue.comment('Tagging this issue as popular, please stop commenting on this issue with +1. thanks!')
            }
        },

        'should include a jsfiddle/jsbin illustrating the problem if tagged with js but not a feature': function (issue) {
            var labels = issue.labels.map(function (label) { return label.name });
            if (~labels.indexOf('js') && !~labels.indexOf('feature')) assert.ok(/(jsfiddle|jsbin)/.test(issue.body))
        },

        'after': function (issue) {
            if (issue.reporter.stats.failures) {
                issue.reportFailures(issue.close.bind(issue))
            }
        }

    }

}<|endoftext|>


<commit_before>#!/usr/bin/env node
/* eslint-disable no-process-exit */

import path from 'path'
import fs from 'fs-extra'
import tailwind from '..'
import postcss from 'postcss'
import process from 'process'
import program from 'commander'

function writeStrategy(options) {
  if (options.output === undefined) {
    return output => {
      process.stdout.write(output)
    }
  }
  return output => {
    fs.outputFileSync(options.output, output)
  }
}

function buildTailwind(inputFile, config, write) {
  console.log('Building Tailwind!')

  const input = fs.readFileSync(inputFile, 'utf8')

  return postcss([tailwind(config)])
    .process(input)
    .then(result => {
      write(result.css)
      console.log('Finished building Tailwind!')
    })
    .catch(error => console.log(error))
}

const packageJson = require(path.resolve(__dirname, '../package.json'))

program.version(packageJson.version).usage('<command> [<args>]')

program
  .command('init [filename]')
  .usage('[options] [filename]')
  .action((filename = 'tailwind.js') => {
    let destination = path.resolve(filename)

    if (!path.extname(filename).includes('.js')) {
      destination += '.js'
    }

    if (fs.existsSync(destination)) {
      console.log(`Destination ${destination} already exists, aborting.`)
      process.exit(1)
    }

    const output = fs.readFileSync(path.resolve(__dirname, '../defaultConfig.js'), 'utf8')
    fs.outputFileSync(destination, output.replace('// var defaultConfig', 'var defaultConfig'))
    process.exit()
  })

program
  .command('build')
  .usage('[options] <file ...>')
  .option('-c, --config [path]', 'Path to config file')
  .option('-o, --output [path]', 'Output file')
  .action((file, options) => {
    let inputFile = program.args[0]

    if (!inputFile) {
      console.error('No input file given!')
      process.exit(1)
    }

    buildTailwind(inputFile, options.config, writeStrategy(options)).then(() => {
      process.exit()
    })
  })

program
  .command('*', null, {
    noHelp: true,
  })
  .action(() => {
    program.help()
  })

program.parse(process.argv)

if (program.args.length === 0) {
  program.help()
  process.exit()
}
<commit_msg>Add success message after tailwind init command<commit_after>#!/usr/bin/env node
/* eslint-disable no-process-exit */

import path from 'path'
import fs from 'fs-extra'
import tailwind from '..'
import postcss from 'postcss'
import process from 'process'
import program from 'commander'

function writeStrategy(options) {
  if (options.output === undefined) {
    return output => {
      process.stdout.write(output)
    }
  }
  return output => {
    fs.outputFileSync(options.output, output)
  }
}

function buildTailwind(inputFile, config, write) {
  console.log('Building Tailwind!')

  const input = fs.readFileSync(inputFile, 'utf8')

  return postcss([tailwind(config)])
    .process(input)
    .then(result => {
      write(result.css)
      console.log('Finished building Tailwind!')
    })
    .catch(error => console.log(error))
}

const packageJson = require(path.resolve(__dirname, '../package.json'))

program.version(packageJson.version).usage('<command> [<args>]')

program
  .command('init [filename]')
  .usage('[options] [filename]')
  .action((filename = 'tailwind.js') => {
    let destination = path.resolve(filename)

    if (!path.extname(filename).includes('.js')) {
      destination += '.js'
    }

    if (fs.existsSync(destination)) {
      console.log(`Destination ${destination} already exists, aborting.`)
      process.exit(1)
    }

    const output = fs.readFileSync(path.resolve(__dirname, '../defaultConfig.js'), 'utf8')
    fs.outputFileSync(destination, output.replace('// var defaultConfig', 'var defaultConfig'))
    console.log(`Generated Tailwind config: ${destination}`)
    process.exit()
  })

program
  .command('build')
  .usage('[options] <file ...>')
  .option('-c, --config [path]', 'Path to config file')
  .option('-o, --output [path]', 'Output file')
  .action((file, options) => {
    let inputFile = program.args[0]

    if (!inputFile) {
      console.error('No input file given!')
      process.exit(1)
    }

    buildTailwind(inputFile, options.config, writeStrategy(options)).then(() => {
      process.exit()
    })
  })

program
  .command('*', null, {
    noHelp: true,
  })
  .action(() => {
    program.help()
  })

program.parse(process.argv)

if (program.args.length === 0) {
  program.help()
  process.exit()
}
<|endoftext|>


<commit_before>var program = require('commander');
var fs = require('fs');
var path = require('path');
var pjson = require('../package.json');
var colors = require('colors/safe');
var StorybookRunner = require('./index');
var handleError = function(err) {
  if (program && program.debug && err.stack) {
    console.error('DEBUG:', err.stack);
  } else {
    console.error(err.message || err.toString());
  }
  console.error('---');
  console.error('Exiting Screener Storybook');
  console.error('Need help? Contact: support@screener.io');
  process.exit(1);
};

program
  .version(pjson.version)
  .option('-c, --conf <config-file>', 'Path to Configuration File')
  .option('--build-cmd <build-cmd>', 'Set NPM Command for Building Storybook. Defaults to: build-storybook')
  .option('--static-server-only', 'Start Static Server only for testing purposes')
  .option('--debug', 'Enable debug mode')
  .parse(process.argv);

console.log(colors.bold('\nscreener-storybook v' + pjson.version + '\n'));

if (program.staticServerOnly) {
  StorybookRunner.staticStorybook(program.buildCmd)
    .then(function(result) {
      if (result && result.port) {
        console.log('Static Storybook server started on http://localhost:' + result.port);
      } else {
        throw new Error('Static Storybook server could not be started.');
      }
    })
    .catch(handleError);
} else {
  if (!program.conf) {
    console.error('--conf is a required argument. Type --help for more information.');
    process.exit(1);
  }

  var configPath = path.resolve(process.cwd(), program.conf);
  if (!fs.existsSync(configPath)) {
    console.error('Config file path "' + program.conf + '" cannot be found.');
    process.exit(1);
  }
  var config = require(configPath);

  // start local storybook server
  StorybookRunner.staticStorybook(program.buildCmd, config)
    .then(function(result) {
      if (result && result.port) {
        config.storybookPort = result.port;
        console.log('Static Storybook server started on http://localhost:' + result.port);
      }
      // get storybook object, and add to config
      var options = {
        staticPath: result && result.staticPath,
        debug: program.debug
      };
      return StorybookRunner.getStorybook(options);
    })
    .then(function(storybook) {
      config.storybook = storybook;
      if (program.debug) {
        console.log('DEBUG: config.storybook', JSON.stringify(config.storybook, null, 2));
      }
      process.exit();
      // run test against Screener
      return StorybookRunner.run(config, program);
    })
    .then(function(response) {
      console.log(response);
      process.exit();
    })
    .catch(handleError);
}
<commit_msg>remove exit<commit_after>var program = require('commander');
var fs = require('fs');
var path = require('path');
var pjson = require('../package.json');
var colors = require('colors/safe');
var StorybookRunner = require('./index');
var handleError = function(err) {
  if (program && program.debug && err.stack) {
    console.error('DEBUG:', err.stack);
  } else {
    console.error(err.message || err.toString());
  }
  console.error('---');
  console.error('Exiting Screener Storybook');
  console.error('Need help? Contact: support@screener.io');
  process.exit(1);
};

program
  .version(pjson.version)
  .option('-c, --conf <config-file>', 'Path to Configuration File')
  .option('--build-cmd <build-cmd>', 'Set NPM Command for Building Storybook. Defaults to: build-storybook')
  .option('--static-server-only', 'Start Static Server only for testing purposes')
  .option('--debug', 'Enable debug mode')
  .parse(process.argv);

console.log(colors.bold('\nscreener-storybook v' + pjson.version + '\n'));

if (program.staticServerOnly) {
  StorybookRunner.staticStorybook(program.buildCmd)
    .then(function(result) {
      if (result && result.port) {
        console.log('Static Storybook server started on http://localhost:' + result.port);
      } else {
        throw new Error('Static Storybook server could not be started.');
      }
    })
    .catch(handleError);
} else {
  if (!program.conf) {
    console.error('--conf is a required argument. Type --help for more information.');
    process.exit(1);
  }

  var configPath = path.resolve(process.cwd(), program.conf);
  if (!fs.existsSync(configPath)) {
    console.error('Config file path "' + program.conf + '" cannot be found.');
    process.exit(1);
  }
  var config = require(configPath);

  // start local storybook server
  StorybookRunner.staticStorybook(program.buildCmd, config)
    .then(function(result) {
      if (result && result.port) {
        config.storybookPort = result.port;
        console.log('Static Storybook server started on http://localhost:' + result.port);
      }
      // get storybook object, and add to config
      var options = {
        staticPath: result && result.staticPath,
        debug: program.debug
      };
      return StorybookRunner.getStorybook(options);
    })
    .then(function(storybook) {
      config.storybook = storybook;
      if (program.debug) {
        console.log('DEBUG: config.storybook', JSON.stringify(config.storybook, null, 2));
      }
      // run test against Screener
      return StorybookRunner.run(config, program);
    })
    .then(function(response) {
      console.log(response);
      process.exit();
    })
    .catch(handleError);
}
<|endoftext|>


<commit_before>import React from "react";
import { createGlobalStyle } from "styled-components";
import { configure, addDecorator } from "@storybook/react";
import { withInfo } from "@storybook/addon-info";

const req = require.context(
  "../",
  true,
  /^((?![\\/]node_modules).)*\.story\.js$/
);

function loadStories() {
  req.keys().forEach(filename => req(filename));
}

const GlobalStyle = createGlobalStyle`

@font-face {
  font-family: 'lato';
  src: url('./lato-regular-webfont.woff2') format('woff2'),
  url('./lato-regular-webfont.woff') format('woff');
  font-weight: 400;
  font-style: normal;
}

@font-face {
  font-family: 'lato';
  src: url('./lato-semibold-webfont.woff2') format('woff2'),
  url('./lato-semibold-webfont.woff') format('woff');
  font-weight: 600;
  font-style: normal;
}

@font-face {
  font-family: 'lato';
  src: url('./lato-light-webfont.woff2') format('woff2'),
  url('./lato-light-webfont.woff') format('woff');
  font-weight: 300;
  font-style: normal;
}

@font-face {
  font-family: 'whatsgood-fonticon';
  src: url('./whatsgood-iconfont.eot?vexkpz');
  src: url('./whatsgood-iconfont.eot?vexkpz#iefix') format('embedded-opentype'),
  url('./whatsgood-iconfont.ttf?vexkpz') format('truetype'),
  url('./whatsgood-iconfont.woff?vexkpz') format('woff'),
  url('./whatsgood-iconfont.svg?vexkpz#whatsgood-iconfont') format('svg');
  font-weight: normal;
  font-style: normal;
}
  .wg-order:before {
    content: "\\e906";
  }

  .wg-meat:before {
    content: "\\e933";
  }

  .wg-loading:before {
    content: "\\e90b";
  }

  .wg-edit:before {
    content: "\\e924";
  }

  .wg-close:before {
    content: "\\e965";
  }

  .wg-alert:before {
    content: "\\e92c";
  }

  .wg-small-arrow-right:before {
    content: "\\e944";
  }

  .wg-check:before {
    content: "\\e91b";
  }

  .wg-checker:before {
    content: "\\e949";
  }

  .wg-place:before {
    content: "\\e972";
  }

  .wg-external-link:before {
    content: "\\e973";
  }

  .wg-small-arrow-bottom:before {
    content: "\\e942";
  }

  .wg-small-arrow-top:before {
    content: "\\e945";
  }

  .wg-search:before {
    content: "\\e941";
  }

  .wg-close-int:before {
    content: "\\e91d";
  }

  .wg-purveyor:before {
    content: "\\e908";
  }

  .wg-question:before {
    content: "\\e93d";
  }

  .wg-add:before {
    content: "\\e90f";
  }

  .wg-minus:before {
    content: "\\e974";
  }

  .wg-location:before {
    content: "\\e931";
  }

  .wg-check-box:before {
    content: "\\e978";
  }

  .wg-order,
  .wg-meat,
  .wg-loading,
  .wg-close,
  .wg-alert,
  .wg-small-arrow-right,
  .wg-check,
  .wg-checker,
  .wg-edit,
  .wg-place,
  .wg-external-link,
  .wg-small-arrow-bottom,
  .wg-small-arrow-top,
  .wg-search,
  .wg-close-int,
  .wg-purveyor,
  .wg-question,
  .wg-minus,
  .wg-add,
  .wg-location,
  .wg-check-box {
    /* use !important to prevent issues with browser extensions that change fonts */
    font-family: 'whatsgood-fonticon' !important;
    speak: none;
    font-style: normal;
    font-weight: normal;
    font-variant: normal;
    text-transform: none;
    line-height: 1;

    /* Better Font Rendering =========== */
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
  }
`;

function withGlobalStyle(storyFn) {
  return (
    <React.Fragment>
      <GlobalStyle />
      {storyFn()}
    </React.Fragment>
  );
}

// avoid the withInfo decorator when generating snapshots/running tests
if (process.env.NODE_ENV !== "test") {
  addDecorator(withInfo);
}

addDecorator(withGlobalStyle);

configure(loadStories, module);
<commit_msg>feat(config): Add percy storybook config setup<commit_after>import React from "react";
import { createGlobalStyle } from "styled-components";
import {
  configure,
  addDecorator,
  getStorybook,
  setAddon,
} from "@storybook/react";
import createPercyAddon from "@percy-io/percy-storybook";

import { withInfo } from "@storybook/addon-info";

const { percyAddon, serializeStories } = createPercyAddon();
setAddon(percyAddon);

const req = require.context(
  "../",
  true,
  /^((?![\\/]node_modules).)*\.story\.js$/,
);

function loadStories() {
  req.keys().forEach(filename => req(filename));
}

const GlobalStyle = createGlobalStyle`

@font-face {
  font-family: 'lato';
  src: url('./lato-regular-webfont.woff2') format('woff2'),
  url('./lato-regular-webfont.woff') format('woff');
  font-weight: 400;
  font-style: normal;
}

@font-face {
  font-family: 'lato';
  src: url('./lato-semibold-webfont.woff2') format('woff2'),
  url('./lato-semibold-webfont.woff') format('woff');
  font-weight: 600;
  font-style: normal;
}

@font-face {
  font-family: 'lato';
  src: url('./lato-light-webfont.woff2') format('woff2'),
  url('./lato-light-webfont.woff') format('woff');
  font-weight: 300;
  font-style: normal;
}

@font-face {
  font-family: 'whatsgood-fonticon';
  src: url('./whatsgood-iconfont.eot?vexkpz');
  src: url('./whatsgood-iconfont.eot?vexkpz#iefix') format('embedded-opentype'),
  url('./whatsgood-iconfont.ttf?vexkpz') format('truetype'),
  url('./whatsgood-iconfont.woff?vexkpz') format('woff'),
  url('./whatsgood-iconfont.svg?vexkpz#whatsgood-iconfont') format('svg');
  font-weight: normal;
  font-style: normal;
}
  .wg-order:before {
    content: "\\e906";
  }

  .wg-meat:before {
    content: "\\e933";
  }

  .wg-loading:before {
    content: "\\e90b";
  }

  .wg-edit:before {
    content: "\\e924";
  }

  .wg-close:before {
    content: "\\e965";
  }

  .wg-alert:before {
    content: "\\e92c";
  }

  .wg-small-arrow-right:before {
    content: "\\e944";
  }

  .wg-check:before {
    content: "\\e91b";
  }

  .wg-checker:before {
    content: "\\e949";
  }

  .wg-place:before {
    content: "\\e972";
  }

  .wg-external-link:before {
    content: "\\e973";
  }

  .wg-small-arrow-bottom:before {
    content: "\\e942";
  }

  .wg-small-arrow-top:before {
    content: "\\e945";
  }

  .wg-search:before {
    content: "\\e941";
  }

  .wg-close-int:before {
    content: "\\e91d";
  }

  .wg-purveyor:before {
    content: "\\e908";
  }

  .wg-question:before {
    content: "\\e93d";
  }

  .wg-add:before {
    content: "\\e90f";
  }

  .wg-minus:before {
    content: "\\e974";
  }

  .wg-location:before {
    content: "\\e931";
  }

  .wg-check-box:before {
    content: "\\e978";
  }

  .wg-order,
  .wg-meat,
  .wg-loading,
  .wg-close,
  .wg-alert,
  .wg-small-arrow-right,
  .wg-check,
  .wg-checker,
  .wg-edit,
  .wg-place,
  .wg-external-link,
  .wg-small-arrow-bottom,
  .wg-small-arrow-top,
  .wg-search,
  .wg-close-int,
  .wg-purveyor,
  .wg-question,
  .wg-minus,
  .wg-add,
  .wg-location,
  .wg-check-box {
    /* use !important to prevent issues with browser extensions that change fonts */
    font-family: 'whatsgood-fonticon' !important;
    speak: none;
    font-style: normal;
    font-weight: normal;
    font-variant: normal;
    text-transform: none;
    line-height: 1;

    /* Better Font Rendering =========== */
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
  }
`;

function withGlobalStyle(storyFn) {
  return (
    <React.Fragment>
      <GlobalStyle />
      {storyFn()}
    </React.Fragment>
  );
}

// avoid the withInfo decorator when generating snapshots/running tests
if (process.env.NODE_ENV !== "test") {
  addDecorator(withInfo);
}

addDecorator(withGlobalStyle);

configure(loadStories, module);

serializeStories(getStorybook);
<|endoftext|>


<commit_before>import { configure, addDecorator } from '@storybook/react';
import { setDefaults } from '@storybook/addon-info';
import { setOptions } from '@storybook/addon-options';
import backgroundColor from 'react-storybook-decorator-background';
import { State } from '@sambego/storybook-state';

// addon-info
setDefaults({
  header: true,
  inline: true,
  source: true,
  propTablesExclude: [State],
  styles: stylesheet => {
    stylesheet.infoBody = {
      color: '#2a3b4d',
      fontFamily: 'Inter-UI-Regular',
      fontSize: '14px',
      margin: '48px 0',
      padding: '0',
    };

    stylesheet.header = {
      h1: {
        fontFamily: 'Inter-UI-Medium',
        fontSize: '24px',
        fontWeight: 500,
        lineHeight: '30px',
        margin: 0,
      },
      h2: {
        color: '#82828c',
        fontFamily: 'Inter-UI-Medium',
        fontSize: '18px',
        fontWeight: 500,
        lineHeight: '24px',
        margin: '24px 0 10px 0',
      },
      body: {
        borderBottom: '1px solid #c0c0c4',
        paddingTop: 10,
        marginBottom: 10,
      },
    };

    stylesheet.source = {
      h1: {
        borderBottom: '1px solid #c0c0c4',
        color: '#82828c',
        fontFamily: 'Inter-UI-Medium',
        margin: '24px 0 10px 0',
        fontWeight: 500,
        fontSize: '18px',
        lineHeight: '24px',
        padding: '12px 0',
      },
    };

    stylesheet.propTableHead = {
      color: '#344b63',
      fontFamily: 'Inter-UI-Medium',
      fontWeight: 500,
      fontSize: '16px',
      lineHeight: '21px',
      margin: '20px 0 0 0',
    };

    return stylesheet;
  }
});

setOptions({
  siteTitle: 'Teamleader',
  name: `Version ${process.env.__VERSION__}`,
  url: 'https://teamleader.design'
});

addDecorator(backgroundColor(['#ffffff', '#e6f2ff', '#ffeecc', '#d3f3f3', '#ffe3d9', '#e1edfa', '#f1f0ff', '#2a3b4d']));

const req = require.context('../stories', true, /\.js$/);

configure(() => {
  req.keys().forEach(filename => req(filename));
}, module);
<commit_msg>Generally set centerStyles as decorator which centers the story content<commit_after>import { centerStyles } from './styles';
import { configure, addDecorator } from '@storybook/react';
import { setDefaults } from '@storybook/addon-info';
import { setOptions } from '@storybook/addon-options';
import backgroundColor from 'react-storybook-decorator-background';
import styles from '@sambego/storybook-styles';
import { State } from '@sambego/storybook-state';

// addon-info
setDefaults({
  header: true,
  inline: true,
  source: true,
  propTablesExclude: [State],
  styles: stylesheet => {
    stylesheet.infoBody = {
      color: '#2a3b4d',
      fontFamily: 'Inter-UI-Regular',
      fontSize: '14px',
      margin: '48px 0',
      padding: '0',
    };

    stylesheet.header = {
      h1: {
        fontFamily: 'Inter-UI-Medium',
        fontSize: '24px',
        fontWeight: 500,
        lineHeight: '30px',
        margin: 0,
      },
      h2: {
        color: '#82828c',
        fontFamily: 'Inter-UI-Medium',
        fontSize: '18px',
        fontWeight: 500,
        lineHeight: '24px',
        margin: '24px 0 10px 0',
      },
      body: {
        borderBottom: '1px solid #c0c0c4',
        paddingTop: 10,
        marginBottom: 10,
      },
    };

    stylesheet.source = {
      h1: {
        borderBottom: '1px solid #c0c0c4',
        color: '#82828c',
        fontFamily: 'Inter-UI-Medium',
        margin: '24px 0 10px 0',
        fontWeight: 500,
        fontSize: '18px',
        lineHeight: '24px',
        padding: '12px 0',
      },
    };

    stylesheet.propTableHead = {
      color: '#344b63',
      fontFamily: 'Inter-UI-Medium',
      fontWeight: 500,
      fontSize: '16px',
      lineHeight: '21px',
      margin: '20px 0 0 0',
    };

    return stylesheet;
  }
});

setOptions({
  siteTitle: 'Teamleader',
  name: `Version ${process.env.__VERSION__}`,
  url: 'https://teamleader.design'
});

addDecorator(styles({ ...centerStyles }));
addDecorator(backgroundColor(['#ffffff', '#e6f2ff', '#ffeecc', '#d3f3f3', '#ffe3d9', '#e1edfa', '#f1f0ff', '#2a3b4d']));

const req = require.context('../stories', true, /\.js$/);

configure(() => {
  req.keys().forEach(filename => req(filename));
}, module);
<|endoftext|>


<commit_before>// ----------------------------------------------------------------------------
// capitilze provided string
// ----------------------------------------------------------------------------

export function capitalize(str) {
  return str.charAt(0).toUpperCase() + str.slice(1);
}

// ----------------------------------------------------------------------------
// Add isA function and register your class name
// ----------------------------------------------------------------------------

function isA(publicAPI, model = {}, name = null) {
  if (!model.isA) {
    model.isA = [];
  }

  if (name) {
    model.isA.push(name);
  }

  if (!publicAPI.isA) {
    publicAPI.isA = className => (model.isA.indexOf(className) !== -1);
  }
}

// ----------------------------------------------------------------------------
// Basic setter
// ----------------------------------------------------------------------------

function set(publicAPI, model = {}, names = []) {
  names.forEach(name => {
    publicAPI[`set${capitalize(name)}`] = value => {
      model[name] = value;
    };
  });
}

// ----------------------------------------------------------------------------
// Basic getter
// ----------------------------------------------------------------------------

function get(publicAPI, model = {}, names = []) {
  names.forEach(name => {
    publicAPI[`get${capitalize(name)}`] = () => model[name];
  });
}

// ----------------------------------------------------------------------------
// Add destroy function
// ----------------------------------------------------------------------------

function destroy(publicAPI, model = {}) {
  const previousDestroy = publicAPI.destroy;

  if (!model.subscriptions) {
    model.subscriptions = [];
  }

  publicAPI.destroy = () => {
    if (previousDestroy) {
      previousDestroy();
    }
    while (model.subscriptions.length) {
      model.subscriptions.pop().unsubscribe();
    }
    Object.keys(model).forEach(field => {
      delete model[field];
    });

    // Flag the instance beeing deleted
    model.deleted = true;
  };
}

// ----------------------------------------------------------------------------
// Event handling: onXXX(callback), fireXXX(args...)
// ----------------------------------------------------------------------------

function event(publicAPI, model, eventName, asynchrounous = true) {
  const callbacks = [];
  const previousDestroy = publicAPI.destroy;

  function off(index) {
    callbacks[index] = null;
  }

  function on(index) {
    function unsubscribe() {
      off(index);
    }
    return Object.freeze({ unsubscribe });
  }

  publicAPI[`fire${capitalize(eventName)}`] = (...args) => {
    if (model.deleted) {
      console.log('instance deleted - can not call any method');
      return;
    }

    function processCallbacks() {
      callbacks.forEach(callback => {
        if (callback) {
          try {
            callback.apply(publicAPI, args);
          } catch (errObj) {
            console.log('Error event:', eventName, errObj);
          }
        }
      });
    }

    if (asynchrounous) {
      setImmediate(processCallbacks);
    } else {
      processCallbacks();
    }
  };

  publicAPI[`on${capitalize(eventName)}`] = callback => {
    if (model.deleted) {
      console.log('instance deleted - can not call any method');
      return null;
    }

    const index = callbacks.length;
    callbacks.push(callback);
    return on(index);
  };

  publicAPI.destroy = () => {
    previousDestroy();
    callbacks.forEach((el, index) => off(index));
  };
}

// ----------------------------------------------------------------------------
// Fetch handling: setXXXFetchCallback / return { addRequest }
// ----------------------------------------------------------------------------
function fetch(publicAPI, model, name) {
  let fetchCallback = null;
  const requestQueue = [];

  publicAPI[`set${capitalize(name)}FetchCallback`] = fetchMethod => {
    if (requestQueue.length) {
      fetchMethod(requestQueue);
    }
    fetchCallback = fetchMethod;
  };

  return {
    addRequest(request) {
      requestQueue.push(request);
      if (fetchCallback) {
        fetchCallback(requestQueue);
      }
    },
    resetRequests(requestList) {
      while (requestQueue.length) {
        requestQueue.pop();
      }
      if (requestList) {
        // Rebuild request list
        requestList.forEach(req => {
          requestQueue.push(req);
        });
        // Also trigger a request
        if (fetchCallback) {
          fetchCallback(requestQueue);
        }
      }
    },
  };
}

// ----------------------------------------------------------------------------
// Chain function calls
// ----------------------------------------------------------------------------

function chain(...fn) {
  return (...args) => fn.filter(i => !!i).forEach(i => i(...args));
}

// ----------------------------------------------------------------------------
// newInstance
// ----------------------------------------------------------------------------

function newInstance(extend) {
  return (initialValues = {}) => {
    const model = {};
    const publicAPI = {};
    extend(publicAPI, model, initialValues);
    return Object.freeze(publicAPI);
  };
}

export default {
  chain,
  destroy,
  event,
  fetch,
  get,
  isA,
  newInstance,
  set,
};
<commit_msg>fix(CompositeClosureHelper): Fix destroy so it can be called several times<commit_after>// ----------------------------------------------------------------------------
// capitilze provided string
// ----------------------------------------------------------------------------

export function capitalize(str) {
  return str.charAt(0).toUpperCase() + str.slice(1);
}

// ----------------------------------------------------------------------------
// Add isA function and register your class name
// ----------------------------------------------------------------------------

function isA(publicAPI, model = {}, name = null) {
  if (!model.isA) {
    model.isA = [];
  }

  if (name) {
    model.isA.push(name);
  }

  if (!publicAPI.isA) {
    publicAPI.isA = className => (model.isA.indexOf(className) !== -1);
  }
}

// ----------------------------------------------------------------------------
// Basic setter
// ----------------------------------------------------------------------------

function set(publicAPI, model = {}, names = []) {
  names.forEach(name => {
    publicAPI[`set${capitalize(name)}`] = value => {
      model[name] = value;
    };
  });
}

// ----------------------------------------------------------------------------
// Basic getter
// ----------------------------------------------------------------------------

function get(publicAPI, model = {}, names = []) {
  names.forEach(name => {
    publicAPI[`get${capitalize(name)}`] = () => model[name];
  });
}

// ----------------------------------------------------------------------------
// Add destroy function
// ----------------------------------------------------------------------------

function destroy(publicAPI, model = {}) {
  const previousDestroy = publicAPI.destroy;

  if (!model.subscriptions) {
    model.subscriptions = [];
  }

  publicAPI.destroy = () => {
    if (previousDestroy) {
      previousDestroy();
    }
    while (model.subscriptions && model.subscriptions.length) {
      model.subscriptions.pop().unsubscribe();
    }
    Object.keys(model).forEach(field => {
      delete model[field];
    });

    // Flag the instance beeing deleted
    model.deleted = true;
  };
}

// ----------------------------------------------------------------------------
// Event handling: onXXX(callback), fireXXX(args...)
// ----------------------------------------------------------------------------

function event(publicAPI, model, eventName, asynchrounous = true) {
  const callbacks = [];
  const previousDestroy = publicAPI.destroy;

  function off(index) {
    callbacks[index] = null;
  }

  function on(index) {
    function unsubscribe() {
      off(index);
    }
    return Object.freeze({ unsubscribe });
  }

  publicAPI[`fire${capitalize(eventName)}`] = (...args) => {
    if (model.deleted) {
      console.log('instance deleted - can not call any method');
      return;
    }

    function processCallbacks() {
      callbacks.forEach(callback => {
        if (callback) {
          try {
            callback.apply(publicAPI, args);
          } catch (errObj) {
            console.log('Error event:', eventName, errObj);
          }
        }
      });
    }

    if (asynchrounous) {
      setImmediate(processCallbacks);
    } else {
      processCallbacks();
    }
  };

  publicAPI[`on${capitalize(eventName)}`] = callback => {
    if (model.deleted) {
      console.log('instance deleted - can not call any method');
      return null;
    }

    const index = callbacks.length;
    callbacks.push(callback);
    return on(index);
  };

  publicAPI.destroy = () => {
    previousDestroy();
    callbacks.forEach((el, index) => off(index));
  };
}

// ----------------------------------------------------------------------------
// Fetch handling: setXXXFetchCallback / return { addRequest }
// ----------------------------------------------------------------------------
function fetch(publicAPI, model, name) {
  let fetchCallback = null;
  const requestQueue = [];

  publicAPI[`set${capitalize(name)}FetchCallback`] = fetchMethod => {
    if (requestQueue.length) {
      fetchMethod(requestQueue);
    }
    fetchCallback = fetchMethod;
  };

  return {
    addRequest(request) {
      requestQueue.push(request);
      if (fetchCallback) {
        fetchCallback(requestQueue);
      }
    },
    resetRequests(requestList) {
      while (requestQueue.length) {
        requestQueue.pop();
      }
      if (requestList) {
        // Rebuild request list
        requestList.forEach(req => {
          requestQueue.push(req);
        });
        // Also trigger a request
        if (fetchCallback) {
          fetchCallback(requestQueue);
        }
      }
    },
  };
}

// ----------------------------------------------------------------------------
// Chain function calls
// ----------------------------------------------------------------------------

function chain(...fn) {
  return (...args) => fn.filter(i => !!i).forEach(i => i(...args));
}

// ----------------------------------------------------------------------------
// newInstance
// ----------------------------------------------------------------------------

function newInstance(extend) {
  return (initialValues = {}) => {
    const model = {};
    const publicAPI = {};
    extend(publicAPI, model, initialValues);
    return Object.freeze(publicAPI);
  };
}

export default {
  chain,
  destroy,
  event,
  fetch,
  get,
  isA,
  newInstance,
  set,
};
<|endoftext|>


<commit_before>// forEach starting from last element

'use strict';

var call           = Function.prototype.call
  , assertCallable = require('../../Object/assert-callable')
  , toObject       = require('../../to-object');

module.exports = function (cb, scope) {
	var i, self;

	self = toObject(this);
	assertCallable(cb);

	for (i = self.length; i >= 0; --i) {
		if (self.hasOwnProperty(i)) {
			call.call(cb, scope, self[i], i, self);
		}
	}
};
<commit_msg>Renamed argument to more descriptive name<commit_after>// forEach starting from last element

'use strict';

var call           = Function.prototype.call
  , assertCallable = require('../../Object/assert-callable')
  , toObject       = require('../../to-object');

module.exports = function (cb, thisArg) {
	var i, self;

	self = toObject(this);
	assertCallable(cb);

	for (i = self.length; i >= 0; --i) {
		if (self.hasOwnProperty(i)) {
			call.call(cb, thisArg, self[i], i, self);
		}
	}
};
<|endoftext|>


<commit_before>'use babel'

/* @flow */

import Path from 'path'
import FS from 'fs'
import isGlob from 'is-glob'
import {isMatch} from 'micromatch'

export const R_OK = 4
export const W_OK = 2
export const NormalizationRegExp = /\\/g
export const FindCache: Map<string, string> = new Map()

export function exists(path: string): Promise<boolean> {
  return new Promise(function(resolve) {
    FS.access(path, function(error) {
      resolve(error === null)
    })
  })
}

export async function find(rootDirectory: string, fileName: string): Promise<?string> {
  if (!await exists(rootDirectory)) {
    throw new Error(`Can not read directory ${rootDirectory}`)
  }

  const chunks = rootDirectory.split(Path.sep)
  while (chunks.length) {
    const filePath = Path.join(chunks.join(Path.sep), fileName)
    if (filePath === fileName) {
      break
    }
    if (await exists(filePath)) {
      return filePath
    }
    chunks.pop()
  }
  return null
}

export async function findCached(rootDirectory: string, fileName: string): Promise<?string> {
  const cacheKey = rootDirectory + ':' + fileName
  const cachedFilePath = FindCache.get(cacheKey)

  if (cachedFilePath) {
    if (await exists(cachedFilePath)) {
      return cachedFilePath
    }
    FindCache.delete(cacheKey)
  }
  const filePath = await find(rootDirectory, fileName)
  if (filePath) {
    FindCache.set(cacheKey, filePath)
  }
  return filePath
}

export function isIgnored(fileNames: Array<string> , ignored: Array<string>): boolean {
  return ignored.some(function(entry) {
    const entryIsGlob = isGlob(entry)
    for (const fileName of fileNames) {
      if (entryIsGlob ? isMatch(fileName, entry) : fileName === entry) {
        return true
      }
    }
    return false
  })
}

export function normalizePath(path: string): string {
  if (process.platform === 'win32') {
    return path.replace(NormalizationRegExp, '/')
  }
  return path
}
<commit_msg>:new: Add read and write helpers in common<commit_after>'use babel'

/* @flow */

import Path from 'path'
import FS from 'fs'
import isGlob from 'is-glob'
import {isMatch} from 'micromatch'

export const R_OK = 4
export const W_OK = 2
export const NormalizationRegExp = /\\/g
export const FindCache: Map<string, string> = new Map()

export function read(path: string): Promise<string> {
  return new Promise(function(resolve, reject) {
    FS.readFile(path, function(error, contents) {
      if (error) {
        reject(error)
      } else resolve(contents.toString())
    })
  })
}

export function write(path: string, contents: string): Promise {
  return new Promise(function(resolve, reject) {
    FS.writeFile(path, contents, function(error) {
      if (error) {
        reject(error)
      } else resolve()
    })
  })
}

export function exists(path: string): Promise<boolean> {
  return new Promise(function(resolve) {
    FS.access(path, function(error) {
      resolve(error === null)
    })
  })
}

export async function find(rootDirectory: string, fileName: string): Promise<?string> {
  if (!await exists(rootDirectory)) {
    throw new Error(`Can not read directory ${rootDirectory}`)
  }

  const chunks = rootDirectory.split(Path.sep)
  while (chunks.length) {
    const filePath = Path.join(chunks.join(Path.sep), fileName)
    if (filePath === fileName) {
      break
    }
    if (await exists(filePath)) {
      return filePath
    }
    chunks.pop()
  }
  return null
}

export async function findCached(rootDirectory: string, fileName: string): Promise<?string> {
  const cacheKey = rootDirectory + ':' + fileName
  const cachedFilePath = FindCache.get(cacheKey)

  if (cachedFilePath) {
    if (await exists(cachedFilePath)) {
      return cachedFilePath
    }
    FindCache.delete(cacheKey)
  }
  const filePath = await find(rootDirectory, fileName)
  if (filePath) {
    FindCache.set(cacheKey, filePath)
  }
  return filePath
}

export function isIgnored(fileNames: Array<string> , ignored: Array<string>): boolean {
  return ignored.some(function(entry) {
    const entryIsGlob = isGlob(entry)
    for (const fileName of fileNames) {
      if (entryIsGlob ? isMatch(fileName, entry) : fileName === entry) {
        return true
      }
    }
    return false
  })
}

export function normalizePath(path: string): string {
  if (process.platform === 'win32') {
    return path.replace(NormalizationRegExp, '/')
  }
  return path
}
<|endoftext|>


<commit_before>// Copyright © 2013-2014 Esko Luontola <www.orfjackal.net>
// This software is released under the Apache License 2.0.
// The license text is at http://www.apache.org/licenses/LICENSE-2.0

var config = {
    port: process.env.PA_MENTOR_PORT || 8080,
    dbUri: process.env.PA_MENTOR_DB_URI || 'mongodb://localhost:27017/paMentorTest',
    updateInterval: Math.max(1000, process.env.PA_MENTOR_UPDATE_INTERVAL || 60 * 60 * 1000)
};

module.exports = config;
<commit_msg>Sampling period parameter<commit_after>// Copyright © 2013-2014 Esko Luontola <www.orfjackal.net>
// This software is released under the Apache License 2.0.
// The license text is at http://www.apache.org/licenses/LICENSE-2.0

const SECOND = 1000;
const MINUTE = 60 * SECOND;
const HOUR = 60 * MINUTE;
const DAY = 24 * HOUR;

var config = {
    port: process.env.PA_MENTOR_PORT || 8080,
    dbUri: process.env.PA_MENTOR_DB_URI || 'mongodb://localhost:27017/paMentorTest',
    updateInterval: Math.max(SECOND, process.env.PA_MENTOR_UPDATE_INTERVAL || HOUR),
    samplingPeriod: Math.max(0, process.env.PA_MENTOR_SAMPLING_PERIOD || 30 * DAY)
};

module.exports = config;
<|endoftext|>